text
stringlengths
64
81.1k
meta
dict
Q: How to attach a file to send a mail using php I have been struggling to get a mail with attachment using php . The below is my application form.php <form name="frm" action="ThankYou.php" method="post" style="padding-top:10px;"> <table style="text-align: left; width: 100%; color: rgb(255, 0, 0); font-family: Arial; font-size: 11px; font-weight: bold;" rules="all" border="0" cellpadding="0" cellspacing="0"> <tbody> <tr> <td>*mandatory fields</td> </tr> <tr> <td align="left" valign="top"><p><table id="Table2" cellSpacing="0" cellPadding="3" width="100%" align="center" border="0"> <tr> <td style="WIDTH: 152px; HEIGHT: 31px" vAlign="top" align="left"><span id="Label1" class="text" class="text" style="background-color:Transparent;"><span style="font-size:13px; font-family:Arial; font-weight: normal; color:#000000"><span id="Label15" class="asterix" style="color:Red;"></span>Form of address</span></span></td> <td style="HEIGHT: 31px"><select name="DDtitle" id="DDtitle" class="formtext"> <option value=" ">Select</option> <option value="Mr.">Mr.</option> <option value="Ms.">Ms.</option> <option value="Ms.">Mrs.</option> </select></td> </tr><br> <tr> <td height="35" valign="top"><span style="font-size:13px; font-family:Arial; font-weight: normal; color:#000000"><font color="#FF0000"><sup>*</sup></font>First Name:<font color="#FF0000"></font></span></td> <td valign="top"><input type="text" size="35" name="name" id="name" value=""></td></tr> <tr> <td height="35" valign="top"><span style="font-size:13px; font-family:Arial; font-weight: normal; color:#000000"><font color="#FF0000"><sup>*</sup></font>Last Name:<font color="#FF0000"></font></span></td> <td valign="top"><input type="text" size="35" name="lname" id="lname" value=""></td></tr> <tr> <td height="35" valign="top"><span style="font-size:13px; font-family:Arial; font-weight: normal; color:#000000">Address: <font color="#FF0000"></font></span></td> <td valign="top"><textarea cols="28" rows="2" name="address" id="address"></textarea><br><br> <span id="txt_mobile" style="font-size:11px;"></span></td> </tr> <tr> <td height="35" valign="top"><span style="font-size:13px; font-family:Arial; font-weight: normal; color:#000000"><font color="#FF0000"><sup>*</sup></font>City:<font color="#FF0000"></font></span></td> <td valign="top"><input type="text" size="35" name="city" id="city" value=""></td></tr> <tr> <td height="35" valign="top"><span style="font-size:13px; font-family:Arial; font-weight: normal; color:#000000"><font color="#FF0000"><sup>*</sup></font>Contact No:<font color="#FF0000"></font></span></td> <td valign="top"><input type="text" size="35" name="number" id="number" value=""></td></tr> <tr> <td height="35" valign="top"><span style="font-size:13px; font-family:Arial; font-weight: normal; color:#000000"><font color="#FF0000"><sup>*</sup></font>Email Id:<font color="#FF0000"></font></span></td> <td valign="top"><input type="text" size="35" name="email" id="email" value=""></td></tr> <tr> <td height="35" valign="top"><span style="font-size:13px; font-family:Arial; font-weight: normal; color:#000000"><font color="#FF0000"><sup>*</sup></font>Position Applied for:<font color="#FF0000"></font></span></td> <td style="HEIGHT: 21px"><select name="position" id="position" class="formtext"> <option value="">Select</option> <option value="Trainee Business Development Executive">Trainee Business Development Executive</option> <option value="Business Development Executive">Business Development Executive</option> </select> </td></tr> <tr> <td style="WIDTH: 152px" vAlign="top"><span id="Label4" class="text" class="text"> <span style="font-size:13px; font-family:Arial; font-weight: normal; color:#000000">Current organisation</span></span></td> <td><input type="text" size="35" name="organization" id="organization" value=""></td> </tr> <tr> <td style="WIDTH: 152px; HEIGHT: 43px" vAlign="top"><span id="Label5" class="text" class="text"> <span style="font-size:13px; font-family:Arial; font-weight: normal; color:#000000">Designation</span></span></td> <td style="HEIGHT: 43px"><input type="text" size="35" name="designation" id="designation" value=""></td> </tr> <tr> <td style="WIDTH: 152px; HEIGHT: 23px" vAlign="top"><span lang="EN-GB" style="FONT-FAMILY: 'Times New Roman'; FONT-SIZE: 11pt; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-GB; mso-fareast-language: EN-US; mso-bidi-language: AR-SA"><span id="Label32" class="text" class="text"><span style="font-size:13px; font-family:Arial; font-weight: normal; color:#000000">Total work experience </span></span></span></td> <td><select name="ExperienceYears" id="ExperienceYears" class="formtext"> <option value=" ">Years</option> <option value="0">0</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13">13</option> <option value="14">14</option> <option value="15">15</option> <option value="16">16</option> <option value="17">17</option> <option value="18">18</option> <option value="19">19</option> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> <option value="23">23</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> <option value="29">29</option> <option value="30">30</option> <option value="31">31</option> <option value="32">32</option> <option value="33">33</option> <option value="34">34</option> <option value="35">35</option> <option value="36">36</option> <option value="37">37</option> <option value="38">38</option> <option value="39">39</option> <option value="40">40</option> </select><select name="ExperienceYears" id="ExperienceMonths" class="formtext"> <option value=" ">Months</option> <option value="0">0</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> </select></td> </tr> <tr> <td vAlign="top" width="100%" colSpan="2"> <table id="Table11" cellSpacing="0" cellPadding="1" width="100%" border="0"> <tr> <td class="text" style="HEIGHT: 15px" vAlign="top"><span style="font-size:13px; font-family:Arial; font-weight: normal; color:#000000">Resume</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </td> <td vAlign="top"><input name="file" type="file" id="file" class="FormText" /> </td> </tr> </table> </td> </tr> <!--<tr> <td colSpan="2"><span id="Label13" class="text">Enter the text as it is shown in the box below</span></td> </tr> <tr> <td colSpan="2"><img id="Image1" src="../CreateCaptcha.aspx" style="border-width:0px;" /><input name="strCAPTCHA" type="text" maxlength="6" id="strCAPTCHA" class="formtext" style="width:112px;" /></td> </tr>!--> <tr> <td align="center" colSpan="2"><input style="margin-left:50px;" type="submit" value="Submit" class="submit" onclick="return reguser_validation(frm);"/></td> </tr> <!-- InstanceEndEditable --> </table> </TR> </TABLE> </td> </tr> <tbody> </table> </td> </tr></td></tr></table> </td> </tr> </table> </td> </tr> </table> </td> </tr> </table> </td> </tr> </table> </td> </tr> /*Validations*/ <script type="text/javascript" src="email_validate.js"></script> <script type="text/javascript" src="signup.js"></script> <script language="javascript"> function reguser_validation(field) { var name = document.frm.name; var lname = document.frm.lname; var city = document.frm.city; var number = document.frm.number; var email = document.frm.email; var position = document.frm.position; if ((name.value == null) || (name.value == '')) { alert("Please enter your First name"); name.focus(); return false; } /*if(name='!alphabetics') { alert("Please enter Alphabets in your First name"); return false; }*/ if ((lname.value == null) || (lname.value == '')) { alert("Please enter your Last name"); lname.focus(); return false; } /*if(lname='!alphabetics') { alert("Please enter Alphabets in your Last name"); return false; }*/ if ((city.value == null) || (city.value == '')) { alert("Please enter your City name"); city.focus(); return false; } /* if(city='!alphabetics') { alert("Please enter Alphabets in your city name"); return false; }*/ if ((number.value == null) || (number.value == '')) { alert("Please enter your Contact Number"); number.focus(); return false; } if(Mobile_Validate(number) == false) { return false; } if ((email.value == null) || (email.value == '')){ alert("Please enter your Email ID."); email.focus(); return false; } if (emailcheck(email.value) == false){ alert("Please Enter Valid Email ID."); email.focus(); return false; } if (position.value == '') { alert('Please Enter the position that your applying for'); position.focus(); return false; } return true; } </script> The below is my ThankYou.php <?php $to = "[email protected]"; $subject = "Uploaded file"; $fileatt = $_FILES['file']['tmp_name']; $fileatt_type = $_FILES['file']['type']; $fileatt_name = $_FILES['file']['name']; $headers = "From: $from"; if (is_uploaded_file($fileatt)) { // Read the file to be attached ('rb' = read binary) $file = fopen($fileatt, 'rb'); $data = fread($file, filesize($fileatt)); $semi_rand = md5(time()); $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; $headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\""; $mail_body = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $mail_body . "\n\n"; $data = chunk_split( base64_encode($data)); $mail_body .= "--{$mime_boundary}\n" . "Content-Type: {$fileatt_type};\n" . " name=\"{$fileatt_name}\"\n" . "Content-Disposition: attachment;\n" . " filename=\"{$fileatt_name}\"\n" . "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n" . "--{$mime_boundary}--\n"; if ($_SERVER['REQUEST_METHOD'] == "POST") { foreach ($_POST as $key => $value) { $msg .= ucfirst ($key) ." : ". $value . "\n"; } } else { foreach ($_GET as $key => $value) { $msg .= ucfirst ($key) ." : ". $value . "\n"; } } $ok = @mail($to, $subject, $msg, $mail_body, $headers); if($ok) echo "<b>Thank you for submitting Your Resume.<br> We will get back to you as soon as possible.</b>"; else echo "Server Busy please try after few minutes"; fclose($file); } ?> and i also need to know how to add virus checker for the attachment to avoid any virus Any help would be appreciable..waiting for expertise reply.... A: $file1=$_FILES['filenm']['name']; $to = "[email protected]"; $subject = "your subject"; $base = basename($file1); $file = fopen('your folder name/'.$file1,'rb'); $size = filesize('your folder name/'.$file1); $data = fread($file,$size); fclose($file); $data = chunk_split(base64_encode($data)); $message="<html><body>"; $message="<table border='1'>"; $message.="<tr><td colspan='3' align='center' style='color:#FFFFFF;font-size:large; background:#000000'>Information</td></tr>"; $message.="</table>"; $message.="</body></html>"; //boundary $div = "==Multipart_Boundary_x".md5(time())."x"; //headers $head = "From: $email\n". "MIME-Version: 1.0\n". "Content-Type: multipart/mixed;\n". " boundary=\"$div\""; //message $mess = "--$div\n". "Content-Type: text/html; charset=\"iso-8859-1\"\n". "Content-Transfer-Encoding: 7bit\n\n". "$message\n\n". "--$div\n". "Content-Type: application/octet-stream; name=\"$base\"\n". "Content-Description: $base\n". "Content-Disposition: attachment;\n". " filename=\"$base\"; size=$size;\n". "Content-Transfer-Encoding: base64\n\n". "$data\n\n". "--$div\n"; $return = "-f$email"; mail($to,$subject,$mess,$head,$return); try it code with change your email, your subject, your message, and your folder name
{ "pile_set_name": "StackExchange" }
Q: Why script is not working in Centos 6.3 minimal trying with script automaticly create directions and permissions for users . at first I am adding users # adduser mysite.com # adduser mysite1.com # adduser mysite2.com # adduser mysite3.com after that, to not create direction manualy, I write the following script cd /home for dir in `ls -1 `; do mkdir /home/$dir/log mkdir /home/$dir/html chown -R $dir:apache $dir chmod ug+rX $dir done; but get the following error "mkdir: cannot create directory `/home/\033[0m\033[01;34mlog\033[0m/log': No such file or directory..." and etc what do I do wrong ? In old VPS all were ok, but in new VPS I got that error A: If you have to use ls there, change it to this: for dir in `ls --color=never -1 `; do Using * would simplify this: for dir in *; do
{ "pile_set_name": "StackExchange" }
Q: Define type for object parameter that can have different structure I have a function that takes an object as its argument, but the objects passed can have different structures. How can I define a type/types for the argument, without having to set any of the object properties as optional (since this does the whole typing thing a lot less useful)? What I would like to do, but apparently doesn't work, is something like this: type One = { a: string b: string } type Two = { c: string d: string } type Three = { e: string } type OneOfTheseTypes = One | Two | Three const myGenericFunction = (obj: OneOfTheseTypes) => {...} P.S. I'm just starting to take my first baby steps with TypeScript so please forgive me if I'm thinking about this all wrong! EDIT: So the function returns an object of the same type as the argument, and when I use the returned object (like returnedObj.a) I get errors saying "Property 'a' does not exist on type 'OneOfTheseTypes'." and "Property 'a' does not exist on type 'Two'." I'm using TypeScript with React, I don't know if that has anything to do with it. A: TypeScript has correct error message that 'a' property does not exist on OneOfTheseTypes. But you can type cast your result to a narrow type with as operator if you sure about this. Be careful though: you'll have a runtime error if your result will have type Two or Three. let one: One = { a: 'hi', b: 'bye' } let res = myGenericFunction(one); (res as One).a; // OK
{ "pile_set_name": "StackExchange" }
Q: In Excel 2010, how can I convert cells containing "1 day", "2 days" etc to just "1", "2" etc In order to treat them as numbers? I copied the column from another program which has a list of durations. Unfortunately Excel will not treat these cells as numbers at all so I can't use them in formulas. I've tried using the Format Cells tool and selecting "Number", but this does not change the cell at all - it still displays "1 day" and formulas referencing it still do not work. Is there a simple way where a cell value starts with a number and is appended by a string to just get the number value? A: Select the column that contains the data. Press CTRL+H to load the find and replace dialogue. For Find, enter day (note the space before the word day) For Replace, leave empty. Click on the Replace All button. This will remove all occurrences of the word ' day' leaving you with your number. A: Try this formula: =IFERROR(VALUE(LEFT(A1,SEARCH(" ",A1)-1)),A1) This will try the get the number before any space and convert it into a number.
{ "pile_set_name": "StackExchange" }
Q: Find the volume of the solid rotating about $x=2$ $y=x^3, y=0, x=1$ rotated about $x=2$ Plugging in $x=1$ into $y=x^3$ we get 1 so our bounds are $[0,1]$ In order to account for rotating about the line $x=2$ subtract 2 from the function $$\int_0^1 \pi [y^{\frac{1}{3}}-2]^2 dy$$ $$\pi \int_0^1 y^{\frac{2}{3}}-4y^{\frac{1}{3}}+4$$ $$\frac{3}{5}y^{\frac{5}{3}}-3y^{\frac{4}{3}}+4y \Big\vert_0^1$$ pluggin all of this in I get: $\frac{3}{5}+1=\frac{8}{5} \pi$ The answer is supposed to be $\frac{3\pi}{5}$ A: For any given $y$-value, what is the area of the corresponding annulus ("washer") cross section of our solid of rotation? The outer radius is $2 - y^{1/3}$, while the inner radius is $1$. So the area becomes $$ \pi(2-y^{1/3})^2 - \pi\cdot 1^2 = \pi\left[(2-y^{1/3})^2 - 1\right] $$ This is what you should integrate. All in all, it's not difficult to see that the additional $-1$ decreases your answer by $\pi$, which means we get the result we should. Your calculation didn't take this inner radius into account, and thus calculated the volume of the region between $y= x^3$, $y = 0$, $y = 1$ and $x = 2$, rotated about $x = 2$. This has the extra square bounded by $y = 0, y = 1, x = 1, x = 2$ that shouldn't have been included. Note that the solid of rotation of this region is a cylinder with volume $\pi$.
{ "pile_set_name": "StackExchange" }
Q: Comparison of Different Types of Nonlinear Regression Models Thank you for seeing this post. Various regression models are being applied to the curve estimating (actual measured ventilation rate). Comparison was made using the GLM and GAM models including polynomial regression. I use R. Are there any other types of regression models that can simulate that curve well? like...bayesian? (In fact, I didn't even understand if it could be applied here) Sincerely. A: loads of non linear methods exist, and many would give similar results, but this is a statistics question. it would fit better on cross validated. also, you have to tell: do you want to do interpolation, even extrapolation? what is your analysis for? bayesian methods are used when you have knowledge of the phenomenon prior to data, or in some cases when you want to apply regularization or graphical models to data generation processes, I think you should better leave out bayesian statistics here. edit: to be short: if you want to obtain a readable formulation of the curve, and you don't have any specific mathematical model in mind, go for a polynomial fit. Other popular choices, which are better for only plotting the curve, instead of reporting it in a mathematical expression, are smoothing splines and LOESS. for further details, maybe ask a new question on stats.stackexchange.com, after studing better the alternatives.
{ "pile_set_name": "StackExchange" }
Q: Бесконечная карусель блоков У меня есть 4 блока: <div class="row"> <div class="col-md-3"> <div class="card"> <div class="card-body"> This is some text within a card body. </div> </div> </div> <div class="col-md-3" > <div class="card"> <div class="card-body"> This is some text within a card body. </div> </div> </div> <div class="col-md-3"> <div class="card"> <div class="card-body"> This is some text within a card body. </div> </div> </div> <div class="col-md-3"> <div class="card"> <div class="card-body"> This is some text within a card body. </div> </div> </div> </div> Как средствами JS или CSS сделать так, что бы эти 4 блока прокручивались горизонтально автоматически после загрузки страницы в бесконечном цикле? Например как здесь Тинькофф A: Используй Slick.js, там всё просто Оффициальный сайт, Документация Можно настроить слайдер для этого. Включить autoplay и поставить autoplaySpeed на 0. А чтобы оно не останавливалось убедится что easing cssEase стоят на linear $('.autoplay').slick({ slidesToShow: 2, slidesToScroll: 1, autoplay: true, autoplaySpeed: 0, speed: 2000 easing: 'linear', cssEase: 'linear', //Убрать возможность ручного скролла arrows: false, swipe: false, draggable: false }); Как то так Тоже самое в CodePen
{ "pile_set_name": "StackExchange" }
Q: php preg_match_all not specific number I want to exclude a specific number like 4800 from a string of numbers like 569048004801. I'm using php for this and the method preg_match_all some pattern's examples I have tried : /([^4])([^8])([^0])([^0])/i /([^4800])/i A: If you just want to see if a string contain 4800, you don't need regular expressions : <?php $string = '569048004801'; if(strpos($string,'4800') === false){ echo '4800 was not found in the string'; } else{ echo '4800 was found in the string'; } More information about strpos in the documentation here A: /([^4])([^8])([^0])([^0])/i This actually says, a sequence of four characters that is not "4800". Close. /([^4800])/i This actually says, a single character that is not '4', '8', or '0'. Assuming you mean to capture a number that doesn't contain "4800" in it, I think you might want /(?!\d*4800)\d+/i This says, check first that we're not looking at a string of numbers with "4800" somewhere, and provided this is the case, capture the string of numbers. It's called a "negative lookahead assertion".
{ "pile_set_name": "StackExchange" }
Q: How to use if statement in SQL I have a scheduling database in Microsoft Access. I have a table that has my orders in it and am using two different queries with if statements to calculate the estimated shipping date, i have 30 columns and between the two queries i am using ,IIf([engraving]>0,Date()+18,IIf([plating]>0,Date()+17, and so on..... I am wondering if there is an easier way to do this in SQL because i have to union two different queries and i am getting duplicates even if i am not using union all. Added more as requested: SELECT IIf([BLAST]>0,Date()+18,IIf([Strip Cu-Ni]>0,Date()+18,IIf([Strip Hard Face]>0,Date()+17,IIf([Repair Determination]>0,Date()+16,IIf([Machine For Patch]>0,Date()+16,IIf([Fit Up]>0,Date()+15,IIf([EB Weld]>0,Date()+15,IIf([Bader]>0,Date()+14,IIf([Local Straightening]>0,Date()+13,IIf([Hot Die]>0,Date()+12,IIf([Vapor Hone]>0,Date()+11))))))))))) AS [Estimated Ship Date], [Front End Classic].[CUSTOMER NAME], [Front End Classic].Priority, [Front End Classic].FAMILY, [Front End Classic].[PO#], [Front End Classic].[DATE RECEIVED], [Front End Classic].Priority, [Front End Classic].qty, [Front End Classic].Blast, [Front End Classic].[Strip Cu-Ni], [Front End Classic].[Strip Hard Face], [Front End Classic].CMM, [Front End Classic].[Repair Determination], [Front End Classic].UT, [Front End Classic].[Machine For Patch], [Front End Classic].[Fit Up], [Front End Classic].[EB Weld], [Front End Classic].Bader, [Front End Classic].[Local Straightening], [Front End Classic].[Hot Die], [Front End Classic].[Vapor Hone], [Front End Classic].[Prep Shroud], [Front End Classic].[Weld Shroud], [Front End Classic].[Prep Tip], [Front End Classic].[Weld Tip], [Front End Classic].[Mill Tip], [Front End Classic].[Mill Shroud], [Front End Classic].Blend, [Front End Classic].[Stress Relief], [Front End Classic].FPI, [Front End Classic].[X-Ray], [Front End Classic].PEEN, [Front End Classic].ECI, [Front End Classic].HVOF, [Front End Classic].Vibro, [Front End Classic].[CU-NI], [Front End Classic].Seals, [Front End Classic].[Moly Dag] FROM [Front End Classic] WHERE (((IIf([BLAST]>0,Date()+18,IIf([Strip Cu-Ni]>0,Date()+18,IIf([Strip Hard Face]>0,Date()+17,IIf([Repair Determination]>0,Date()+16,IIf([Machine For Patch]>0,Date()+16,IIf([Fit Up]>0,Date()+15,IIf([EB Weld]>0,Date()+15,IIf([Bader]>0,Date()+14,IIf([Local Straightening]>0,Date()+13,IIf([Hot Die]>0,Date()+12,IIf([Vapor Hone]>0,Date()+11)))))))))))) Is Not Null)); A: I would explore using the Switch function, which would be a lot cleaner. I.e. Date() + SWITCH([Strip Cu-Ni]>0, 18, [Strip Hard Face]>0, 17, etc) As [EstimatedShipDate] Note that the first condition that evaluates to true, reading left to right, will resolve the switch and it will exit. In all honesty, it looks like your data model is not designed well to give you what you need, but you may not have the luxury of changing that. :-) Hope it helps...
{ "pile_set_name": "StackExchange" }
Q: What is the difference between 'keys.each' and 'each_key'? When iterating through a hash like below: hash.keys.each do |key| process_key(key) end Rubocop proclaims I should use: each_key instead of: keys.each What is the "key" difference between keys.each and each_key? A: Rubocop wants you to follow this based on your evaluated code due to performance. Using large sets of data is where this becomes noticeable. Here's the doc on it: https://github.com/bbatsov/rubocop/blob/master/manual/cops_performance.md#performancehasheachmethods I also found a benchmark someone wrote up to test this: https://gist.github.com/jodosha/8ca2bee6137be94e9dcb I modified it a bit and ran it on on of my systems: Warming up -------------------------------------- string each 128.742k i/100ms string keys 114.523k i/100ms string each_key 134.279k i/100ms symbol each 128.838k i/100ms symbol keys 109.398k i/100ms symbol each_key 132.021k i/100ms Calculating ------------------------------------- string each 2.053M (± 4.0%) i/s - 10.299M in 5.026890s string keys 1.864M (± 1.4%) i/s - 9.391M in 5.039759s string each_key 2.224M (± 5.5%) i/s - 11.145M in 5.032201s symbol each 2.082M (± 1.0%) i/s - 10.436M in 5.013145s symbol keys 1.815M (± 2.1%) i/s - 9.080M in 5.004690s symbol each_key 2.240M (± 1.9%) i/s - 11.222M in 5.012184s Comparison: symbol each_key: 2239720.0 i/s string each_key: 2224205.1 i/s - same-ish: difference falls within error symbol each: 2081895.2 i/s - 1.08x slower string each: 2052884.9 i/s - 1.09x slower string keys: 1863740.5 i/s - 1.20x slower symbol keys: 1815131.1 i/s - 1.23x slower Chaining methods is going to be slower than using the built-in method (in this case) which accomplishes the task with a single special enumerator. The language creators put it there for a reason, also its idiomatic. A: Rubocop is wrong. Which one you should use depends on what you want as the return value. If you want an array of the keys back, then you should use keys.each. key creates a new array of keys, and each returns that array of keys after performing the block on each key. If you do not need to have an array of keys (and want the original hash back), then you should use each_key since that does not create an array that would not be used, and would be more efficient.
{ "pile_set_name": "StackExchange" }
Q: SQL JOIN two tables to access all of the data I am needing to connect two tables by id then access any of the data from either of them inside a foreach loop. I've never done any LEFT JOINS or anything so I'm not sure how to start. The first table named "sys_acl_levels_members" looks like this: IDMember IDLevel DateStarts DateExpires TransactionID The other table "Profiles" has many more colums but here are the first few: ID NickName Email I need help with writing an SQL to gather all this information, then some ways to access it inside of a foreach loop. For example if I wanted to get "DateStarts"," DateExpires" From "sys_acl_levels_members" and "NickName" FROM "Profiles" WHERE IDLevel = ID. A: SELECT acl.DateStarts, acl.DateExpires FROM sys_acl_levels_members acl LEFT JOIN Profiles p ON p.ID = acl.IDLevel
{ "pile_set_name": "StackExchange" }
Q: Prove that series of orthogonal set of orthogonal projections converges Let $H$ be a Hilbert space, $(P_n)$ be sequence of orthogonal projections such that $P_mP_n=0$ for $n\neq m$. Prove that $\forall x\in H$, $\sum_n P_n(x)$ convergent. I tried to prove it is a Cauchy sequence but it seems not work. Could you please give me some hints? A: Any finite sum of the mutually orthogonal projections $P_m$ is an orthogonal projection, which gives $$ \|P_1x +P_2x + \cdots + P_mx \|^2 \le \|x\|^2 \\ \|P_1x\|^2+\|P_2x\|^2+\cdots+\|P_mx\|^2 \le \|x\|^2. $$ This forces $\sum_{n=1}^{\infty}\|P_nx\|^2 < \infty$. And $y_m=\sum_{n=1}^{m}P_nx$ is a Cauchy sequence because \begin{align} \| y_{m+k}-y_{m} \|^2 & = \| \sum_{n=m+1}^{m+k}P_nx \|^2 \\ & = \sum_{n=m+1}^{m+k}\|P_nx\|^2 \rightarrow0 \mbox{ as } m\rightarrow\infty. \end{align} This gives meaning to the unordered sum $y=\sum_n P_n x$ as a limit.
{ "pile_set_name": "StackExchange" }
Q: Regexp: back-reference an optional grouping I'm using regular expressions, with this code: Regexp.new("^(?<ast>\\\*\\\*)?(?<key>#{@meta_types.join("|")}):(?<value>.*)\\k<ast>?$", Regexp::MULTILINE) What I'm going for is parsing basic metadata like so: Title: Some title of a book or something Except, some of the lines have ** around them, and others don't. The problem is that some of the items under <value> span multiple lines, so I can't do ?<value>.*?. Essentially, I need to require the second <ast> grouping if and only if there is a first <ast> grouping present. Is there a way to do this, or does someone have a better solution? *(It's a Word-to-Markdown conversion, and some of the lines were bolded.) Edit: the solution r = Regexp.new("(?<ast>(?:\\\*\\\*)?)(?<key>Title):(?<value>[^\*]*)\k<ast>", Regexp::MULTILINE) s = "**Title: Some pieces of text with a random\nnewline thrown in for good measure**\n" r.match s A: Replace: (?<ast>\\\*\\\*)? With: (?<ast>(?:\\\*\\\*)?) And remove the final "?" at the end. This will force the first capture group to exist, even if it matches nothing.
{ "pile_set_name": "StackExchange" }
Q: Firebase google SignIn result is always false? I'm trying to register my app using Firebase google Sign In methods. The googleSignInResult.isSuccess() returns always false. I tried googling all possible sites. But couldn't find whats wrong with my code. googleSignInButton = (Button)findViewById(R.id.googleSignInButton); googleSignInButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent googleSignInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); startActivityForResult(googleSignInIntent, RC_SIGN_IN); } }); Code for Handling the result @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(requestCode == RC_SIGN_IN){ mAuth = FirebaseAuth.getInstance(); GoogleSignInResult googleSignInResult = Auth.GoogleSignInApi.getSignInResultFromIntent(data); Log.d(TAG , "Google signIn" + googleSignInResult.isSuccess() ); if(googleSignInResult.isSuccess()) { GoogleSignInAccount googleSignInAccount = googleSignInResult.getSignInAccount(); AuthCredential accountAuthCredential = GoogleAuthProvider .getCredential(googleSignInAccount.getIdToken(),null); mAuth.signInWithCredential(accountAuthCredential).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if(task.isSuccessful()){ Intent i = new Intent(getApplicationContext(), MainActivity.class); startActivity(i); }else{ } } }); }else { } } } A: I had similar issue. The following solved it: Ensure SHA1 configured in Firebase project settings In build.gradle (App) set: apply plugin: 'com.android.application' in the beginning of the file and apply plugin: 'com.google.gms.google-services' at the end after dependencies {....} Hope this helps
{ "pile_set_name": "StackExchange" }
Q: how to get array data from XML loop foreach I have sparql output in XML like this : ` <sparql xmlns="http://www.w3.org/2005/sparql-results#"> <head> <variable name="Keyword2"/> </head> <results ordered="false" distinct="false"> <result> <binding name="Keyword2"> <uri>http://www.semanticweb.org/g/ontologies/2010/0/OntologiBatikTanty#Soga_Jawa</uri> </binding> </result> <result> <binding name="Keyword2"> <uri>http://www.semanticweb.org/g/ontologies/2010/0/OntologiBatikTanty#Warna_Alami</uri> </binding> </result> </results> </sparql> ` I make foreach looping in php like this: ` $xml = simplexml_load_string($hasil) or die ("error cannot create object"); $results = $xml->results->result; $jumlah=count($results); echo "Total hasil pencarian : $jumlah <br><br>"; //$keyword2=array(); $output=array(); foreach($xml->results->result as $nodes){ $jumlah=count($nodes); foreach ($nodes->binding as $key =>$node) { $output=$node->uri; echo $output; echo "<br><br>"; echo $keyword=substr($output,66); echo "<br><br>"; } } echo"<hr>"; echo $keyword[0]; ` My question is how to acces the data array from outside looping. for example i want to acces index[0]. but the output only "W" it should be "Soga_Jawa" A: solved your issue please check this code $xml = simplexml_load_string($hasil) or die ("error cannot create object"); $results = $xml->results->result; $jumlah=count($results); echo "Total hasil pencarian : $jumlah <br><br>"; //$keyword2=array(); $output=array(); $keyword = array(); foreach($xml->results->result as $nodes){ $jumlah=count($nodes); foreach ($nodes->binding as $key =>$node) { $output=$node->uri; echo $output; echo "<br><br>"; echo $keyword[]=substr($output,66); echo "<br><br>"; } } echo"<hr>"; echo $keyword[0]; use keyword as array type and get it to out of loop
{ "pile_set_name": "StackExchange" }
Q: Update the values of a list with their absolute values Newbie to scala. I am trying to make this code to work for a few hours now . It is intended to update the List[Int](list of integers) with absolute values of the integers. Took a long time to figure out that List is immutable, so found that ListBuffer can be the saviour, but eventually in returning it back into the List form is seeing some issue i guess. def f (arr:List[Int]) : List[Int] = { val list = new scala.collection.mutable.ListBuffer[Int](); val len = arr.length; for ( i <- 0 to len) { if(arr(i) < 0) { list.append((-1)*arr(i)) ; } else { list.append(arr(i)); } } return list.toList; } which is giving this error: java.lang.IndexOutOfBoundsException: 12 at scala.collection.LinearSeqOptimized$class.apply(LinearSeqOptimized.scala:52) at scala.collection.immutable.List.apply(List.scala:84) at Solution$.f(Solution.scala:7) at Solution$delayedInit$body.apply(Solution.scala:23) at scala.Function0$class.apply$mcV$sp(Function0.scala:40) at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:12) at scala.App$$anonfun$main$1.apply(App.scala:71) at scala.App$$anonfun$main$1.apply(App.scala:7... Not getting what's wrong here. A: The best way is to use Scala functions like @senia suggested in comments. For example: val res = list map math.abs But if you want to fix your code just replace to with until. You are getting off by one error: def f (arr:List[Int]) : List[Int] = { val list = new scala.collection.mutable.ListBuffer[Int](); val len = arr.length; for ( i <- 0 until len) { if(arr(i) < 0) { list.append((-1)*arr(i)) ; } else { list.append(arr(i)); } } return list.toList; } Here is the difference between until and to: 1 to 3 // Range(1, 2, 3) 1 until 3 // Range(1, 2) You can also remove return, ; and even braces { used with if/else.
{ "pile_set_name": "StackExchange" }
Q: Class implementing ServletContainerInitializer in web.xml Can you point to a class implementing the ServletContainerInitializer interface in the web.xml file or do you have to add a file under the META-INF/services/javax.servlet.ServletContainerInitializer to have a J2EE server pick it up? If it's possible via the web.xml file, please explain how. A: I've checked the Java Servlet Specification 3.0 and I've not found any clue that it could be configured via web.xml. I think the only way is the META-INF/services/javax.servlet.ServletContainerInitializer file. Please note that the META-INF/services/javax.servlet.ServletContainerInitializer is a file (not a directory) which has to contain the fully qualified name of the initalizer, like: com.example.MyServletContainerInitializer It could be inside the war too (tested with Tomcat 7.0.21). Here is a complete example: http://nullhaus.com/2011/03/using-servlets-3-0-servletcontainerinitializer/
{ "pile_set_name": "StackExchange" }
Q: How to approach for this webservice request? Currently I'm displaying orders and related objects in a visualforce page. The new requirement is: For every order a hyperlink/button will be added. On clicking that button, a related document from SAP server will be downloaded using a unique number (order id). For example: (http: www.somelink.com/id=12345) How would I need to start this? I know how to expose a webservice from apex. I'm pretty excited because this is a great opportunity for me to learn webservices in salesforce. Suggestions and references would be appreciated. Thanks. A: On the object -"order" where you can see the record values for an order, create a formula(text) field And try something like this:: HYPERLINK('https://somelink.com/'& File_Name__c , 'https://somelink.com/'& File_Name__c ) where file_name__c is the file on that particular server/endpoint. Note - file_name__c should be a value in records.
{ "pile_set_name": "StackExchange" }
Q: Load an image "on the fly" in RAM, without using the hard disk It is possible to get a text from the internet (or even decoding a string) and represent it in a JLabel, without touching the hard disk. So, I was wondering if it was possible to do the same with an image. Let me explain myself: I want to represent an image with its hexadecimal representation in a JLabel "on the fly", I mean, in RAM, without even touching the hard disk. I don't mean loding it from the internet, I mean something like reading a file which has the hexadecimal code of an image, converting it to ASCII and programmatically insert it into a JLabel, like if it were a file. Is this even possible? I think I am not being very clear, but I hope you understand what I am trying to say. A: Yes you can. If you are loading the image from internet, javax.swing.ImageIcon constructor accepts URL as parameter which then you give the ImageIcon to JLabel. In response to your clarification, yes you can still do that. There are a few options, here are a couple: You can still the same method above and use "file://your/image/file" as the URL to ImageIcon. ImageIcon also accepts byte[] of image data. So you can do your regular file reading into ByteArrayInputStream and get byte[] out of that.
{ "pile_set_name": "StackExchange" }
Q: Why is my code only printing the first element in the array in Xcode? The resulting code only prints out the first element of the array in my Xcode, even though I pass it three words. Any reason why? char str[100] = {0}; NSLog(@"Please enter three words: "); scanf("%s", str); NSString *words = [NSString stringWithUTF8String: str]; NSMutableArray *mutableWords = [[words componentsSeparatedByString: @" "] mutableCopy]; NSLog(@"%@", mutableWords); A: fgets(str, sizeof(str), stdin); This will read the entire line into str. The easiest way to get rid of the '\n' character left as the last index of your array is to simple change how you're splitting your array: NSMutableArray *mutableWords = [[words componentsSeparatedByCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]] mutableCopy];
{ "pile_set_name": "StackExchange" }
Q: Implementing dark theme windows in Mac app How can I customize my mac app's windows to a 'dark theme' as seen in Facetime? I'm wondering if this is a setting in Interface Builder, or if I will have to use a custom gradient. A: You'll need to do it yourself, including the controls. You might use the transparent controls here: http://brandonwalkin.com/bwtoolkit/
{ "pile_set_name": "StackExchange" }
Q: What is the SO user deletion rate? Browsing some of the older SO questions I am noticing quite a few where the original owner of the answer or question is no longer on the site, i.e. have had their accounts deleted. Since deleting an account requires the team to intervene and process the deletion, I am interested in the following: How many deletions have there been since launch? How many requests are there in a day/week? What are the major reasons for these deletions? How can this be prevented? I don't expect exact numbers, just an indication would be sufficient, the last 2 questions are more valuable to me. A: I can't say what the deletion rate is, but there is an automated process that deletes old, inactive users: We delete cookie-based unregistered accounts when the user has not visited Stack Overflow in four months AND the user has less than 100 reputation We delete OpenID registered accounts when the user has not visited Stack Overflow in four months AND the user has only 1 reputation
{ "pile_set_name": "StackExchange" }
Q: R seriation -> In max(criterion) : no non-missing arguments to max; returning -Inf I have following dataset: 0101110 1010000 1010011 0101010 1000101 and want to seriate it. When I read it a call seriate function, like this: matr <- read.table(...) ser <- seriate(as.matrix(matr)) And I get an error: Error in seriate.default(max(criterion) - criterion, method = "TSP", control = control) : seriate not implemented for class 'numeric'. In addition: Warning message: In max(criterion) : no non-missing arguments to max; returning -Inf What is the problem? I do not understand. I also read documentation and found nothing A: It seems that you have a problem in the way you read the data. The following works fine: > library(seriation) > m <- matrix(c(0,1,0,1,1,1,0, + 1,0,1,0,0,0,0, + 1,0,1,0,0,1,1, + 0,1,0,1,0,1,0, + 1,0,0,0,1,0,1), nrow=5, byrow=T ) > m [,1] [,2] [,3] [,4] [,5] [,6] [,7] [1,] 0 1 0 1 1 1 0 [2,] 1 0 1 0 0 0 0 [3,] 1 0 1 0 0 1 1 [4,] 0 1 0 1 0 1 0 [5,] 1 0 0 0 1 0 1 > > seriate(m) object of class ‘ser_permutation’, ‘list’ contains permutation vectors for 2-mode data vector length seriation method 1 5 BEA_TSP 2 7 BEA_TSP However, if I cast the matrix as numeric, I get the same error that you got, which seems to indicate that you matrix is a numeric and that seriate reacts to a direct cast to matrix. With other words, ensure that your input is correct. > m <- as.numeric(m) > seriate(as.matrix(m)) Error in seriate.default(max(criterion) - criterion, method = "TSP", control = control) : seriate not implemented for class 'numeric'. In addition: Warning message: In max(criterion) : no non-missing arguments to max; returning -Inf
{ "pile_set_name": "StackExchange" }
Q: Such a crappy riddle I'm on patrol I'm on a roll! I want to clean Could you please lean? What could I be? Your answer should be one or two words, depending on how you spell this well-used phrase. Make sure you provide an explanation. Bonus Question (And a hint): How many should you take? (Answer is in the riddle as well) A: My suggestion (somewhat too straightforward) bathroom tissue (or toilet paper, etc.) Because It's usually on a roll and used for cleaning. Also, the title hints :)
{ "pile_set_name": "StackExchange" }
Q: Directory.Exists sensible to time? I have the following piece of code in my application: if (!Directory.Exists(myPath)) Directory.CreateDirectory(myPath); If I run it in a regular unit test sometimes it passes, sometimes not. The directory is always there (I made sure of it, so technically it will never be "created" by code). But every once in a while Directory.Exists(myPath) returned false, which makes the code try to create the folder and then I get an UnauthorizedAccessException! The funny thing here is if I put a breakpoint on the CreateDirectory, and then move the yellow arrow up back to test, the test returns true! What's going on? myPath is \\nameOfLocalMachine\sharedFolder. The share is reliable and constantly used... .NET 4.0 I just made a fiddler simulate 3000 sequentials requests. 175 failed... All with the same message: Access to the path '\nameOfLocalMachine\sharedFolder\randomFileName.json' is denied A: This mishap is pretty normal on Windows. Programs open a handle on a directory like this and specify delete sharing. Which permits anybody to delete the directory, even though the program is using it. The directory won't actually disappear from the file system until that handle is closed. What follows is that trying to recreate that directory cannot work, it still exists. Windows generates an "access denied" error, reported in your C# program with the UnauthorizedAccessException. While that sounds like an obscure feature, every program in Windows does this. Every process has a default working directory, the value of Environment.CurrentDirectory. Creating a handle on such a directory ensures that it cannot disappear while the program is using it. There are other cases, FileSystemWatcher would be another example. Or a program busy iterating the directory. Anti-malware and search indexers are notorious for hard to diagnose sources of such errors. Otherwise a standard hazard of a multi-tasking operating system. You are not the only one using the file system. Not repeatedly deleting and creating the same directory ought to be very high on your list. If this is absolutely necessary then rename the directory first before you delete it. You'd still fail to delete the renamed directory but you won't fail recreating it. You can delete it later, next time you need to do this. Much lower odds for trouble then. Because more time passed.
{ "pile_set_name": "StackExchange" }
Q: how to merge two order by statements in sql I have the following relational schema create table employeeb37( employee_id int primary key, last_name varchar(255), first_name varchar(255), middle_name varchar(255), job_id references jobb37(job_id), manager_id varchar(255), hiredate date, salary int, comm int, department_id int ) I want to query the database by employee details according to their job_id in ascending order and salaries in descending order but i am not getting proper result for select * from employeeb37 order by job_id asc and salary desc I want to know if there is any other possible solution for my problem A: How about : select * from employeeb37 order by job_id asc, salary desc A: Use comma (,) instead of AND in your ORDER BY clause: SELECT * FROM employeeb37 ORDER BY job_id ASC, salary DESC Have a look at ORDER BY clause
{ "pile_set_name": "StackExchange" }
Q: Add X hours to a date & time I am currently fetching the time and date trough: DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); Date date = new Date(); System.out.println(dateFormat.format(date)); This returns the example '05/14/2014 01:10:00' Now I am trying to make it so I can add a hour to this time without having to worry about a new day or month etc. How would I go on getting '05/14/2014 01:10:00' but then for 10 hours later in the same format? Thanks in advance. A: Look at the Calendar object: Calendar Calendar cal = Calendar.getInstance(); cal.add(Calendar.HOUR_OF_DAY, 10); DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); System.out.println(dateFormat.format(cal.getTime()));
{ "pile_set_name": "StackExchange" }
Q: SQL Server WITH XMLNAMESPACES dynamic declaration I have the following query: ;WITH XMLNAMESPACES ( 'Bob' AS b ) SELECT 'Test' AS [@b:Test] FOR XML PATH('root') However I'd like the name space definition to be dynamically picked up at runtime from a configuration table. I've tried the following but they don't appear to be valid SQL: -- use a sub query ;WITH XMLNAMESPACES ( (SELECT 'Fred') AS b ) SELECT 'Test' AS [@b:Test] FOR XML PATH('root') -- declare a variable DECLARE @ns VARCHAR(10) = 'Fred' ;WITH XMLNAMESPACES ( @ns AS b ) SELECT 'Test' AS [@b:Test] FOR XML PATH('root') Is there any way to have the name space definition dynamic? Thanks, Tom A: You should use dynamic SQL: DECLARE @d NVARCHAR(30)='Fred' ;WITH XMLNAMESPACES ( 'UniqueValue' AS b ) SELECT @ns=( SELECT 'Test' AS [@b:Test] FOR XML PATH('root')) SELECT CAST(REPLACE(@ns, 'UniqueValue',@D) AS XML)
{ "pile_set_name": "StackExchange" }
Q: App is crashing after load images i'm working on a project with a lot of images but after i load the images (60/70 images) with .xml (thumbnail) the app is crashing. When i only load 30 images the app is working normally. Does anyone now how i can delay the load of the images? example; first load 10 images and after 5 seconds 10 more? The .xml is very simply; <images> imagename.png, imagename.png </images> More than 30 images = App crash, less = app working. Loading the images [DolphiniMages initBook:@"images.xml" curOrientation:curInterfaceOrientation]; A: Implement this method in your app delegate: - (void)applicationDidReceiveMemoryWarning:(UIApplication *)application Chances are you're getting a memory warning and ignoring it, so you're being booted by the OS.
{ "pile_set_name": "StackExchange" }
Q: reloadData is not calling cellForRowAtIndexPath I know this topic has been raised quite a few times but I can't seem to get through. This is a simple UITableViewController who's cells are either normal UITableViewCells or custom ones. This allow users to input text in a textField in a cell and add it directly to the tableView. When the user is done entering his text he hits return and the new entry gets added to listOfItems. At this point I want my tableView to reload its data to show the last item added. Doesn't seem to work. class CreateListTableViewController: UITableViewController { // MARK: - Model var listOfItems = [String]() { didSet { tableView.reloadData() println(listOfItems) } } // MARK: - View LifeCycle override func viewDidLoad() { super.viewDidLoad() navigationController?.navigationBarHidden = false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return listOfItems.count + 1 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.row + 1 == listOfItems.count{ let cell = tableView.dequeueReusableCellWithIdentifier("tableCellSearch", forIndexPath: indexPath) as! ListItemTableViewCell cell.configure(text: "", placeholder: "Enter an item") return cell } else { let cell = tableView.dequeueReusableCellWithIdentifier("tableCell", forIndexPath: indexPath) as! UITableViewCell println(indexPath.row) cell.textLabel?.text = listOfItems[indexPath.row] return cell } } } Here's the code for the custom UITableViewCell: class ListItemTableViewCell: UITableViewCell, UITextFieldDelegate { @IBOutlet weak var cellTextField: UITextField! var controllerArray = CreateListTableViewController() func configure(#text: String?, placeholder: String){ cellTextField.text = text cellTextField.placeholder = placeholder cellTextField.accessibilityValue = text cellTextField.accessibilityLabel = placeholder } func textFieldShouldBeginEditing(textField: UITextField) -> Bool { textField.text = "" return true } override func awakeFromNib() { super.awakeFromNib() cellTextField.delegate = self } func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() controllerArray.listOfItems += [textField.text] textField.text = "" return true } func textFieldShouldEndEditing(textField: UITextField) -> Bool { return true } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } Interestingly reloadData calls 'numberOfRows' but not 'cellForRow'. A: Your indexes/sizes are off such that your code only works when listOfItems' size is 0. Try this: override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return listOfItems.count + 1 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.row == listOfItems.count { let cell = tableView.dequeueReusableCellWithIdentifier("tableCellSearch", forIndexPath: indexPath) as! ListItemTableViewCell cell.configure(text: "", placeholder: "Enter an item") return cell } else { let cell = tableView.dequeueReusableCellWithIdentifier("tableCell", forIndexPath: indexPath) as! UITableViewCell println(indexPath.row) cell.textLabel?.text = listOfItems[indexPath.row] return cell } } Update: OK, the problem is that in ListItemTableViewCell you are creating a new instance of CreateListTableViewController and assigning it to controllerArray. This means that when you call controllerArray.listOfItems += [textField.text], you are calling it on a separate, second instance of CreateListTableViewController that is not on the screen. Instead, you should leave controllerArray uninitialized in ListItemTableViewCell and then set it from cellForRowAtIndexPath like this: override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.row + 1 == listOfItems.count{ let cell = tableView.dequeueReusableCellWithIdentifier("tableCellSearch", forIndexPath: indexPath) as! ListItemTableViewCell cell.configure(text: "", placeholder: "Enter an item") cell.controllerArray = self return cell } else { let cell = tableView.dequeueReusableCellWithIdentifier("tableCell", forIndexPath: indexPath) as! UITableViewCell println(indexPath.row) cell.textLabel?.text = listOfItems[indexPath.row] return cell } }
{ "pile_set_name": "StackExchange" }
Q: What happens when 0 is subtracted For input 1234 the output is 134.What is happening here?When i print a[1] in this case it prints nothing. #include <iostream> using namespace std; int main() { char a[100]; cin >> a; a[1] = a[1] - '0'; cout << a; return 0; } A: '0' refers to the printable character 0, which in ASCII translates to the value of 48. '2' has a value of 50, so subtracting 50 from 48 yields 2, which is Start of Text character. This character doesn't translate into a printable character, so cout doesn't print it.
{ "pile_set_name": "StackExchange" }
Q: How to manage huge sized classes and refactoring in unit testing (junit) In our project which has huge sized classes and sub relations we have been developing for months. Also, we have been developing junit test cases. Automatic unit tests are good in general, but in real life it is not easy as we think. Managing the unit test architecture is easier than creating mock objects and stubs etc. Also, we are testing the dao and service layers. The problem is that our classes have so many attributes. (I know it's not a good object oriendted design but it's legacy architecture.) For example; customer class has 58 attributes and it's related to address, marsaccounts and etc. Totally if you want to test this class you have to create inputs, inputs with 90 or more attributes. Our architecture has many business rule on Customer, so that we have to create more than 50 customer inputs to test every rule, method or flow. In short, you have to create 4500 (90 x 50) attributes for all, but less for a reliable test (only necessary attributes). Preparing the test inputs are painful and annoying. Imagine, 2 columns added to Customer object and they store critical values. it seems easy, but refactoring the test inputs are soul-destroying. How can I manage the test stub and How can I overcome the huge input set ? Regards. A: it looks like you have only two options: make less attributes relevant or learn to easily set-up tests with large number of attributes. less attributes: refactor. and no one will give you much more detailed help because we don't know your business. try to find smaller groups of attributes that control some logic and test that logic using only those attributes. easy test set-up: you can use customer builders. by default they create customer with some standard/most common settings and you tune the result however you want like customer = makeCustomer().withActiveStatus(false).withDebit(3000).build() Then, when new attribute appears you just have to change makeCustomer() in one place. you can also use parameterized tests to define a test case as a one liner or load data from spreadsheet which may be easier to maintain. Often when new attribute appears it's not that it changes everything completely. usually it just adds new behaviour in one spot when that attribute is non-standard. therefore usually it's just adding the default attribute to the builder and a few tests that override that attribute another way to make tests easy is to do property testing (QuickCheck family) although not always it's easy to use it in business logic
{ "pile_set_name": "StackExchange" }
Q: Birthday problem vs having N known non-duplicates and choosing one more I understand the birthday problem from a basic level, but I'm curious how checking for a pair after every choice of N alters the probabilities. For example, assuming you want to choose N random numbers between 1 and 100,000,000. If N = 12,000, the probability of there being two duplicate numbers in the group is about 50%. However, if you had 12,000 unduplicated numbers, and you wanted to choose the 12,001st number, is the probability of getting a match = 12,000/100,000,000 or 0.012%? A: Yes, that is correct. The "birthday paradox" is created because with $n$ birthdays you have ${n \choose 2}=\frac 12n(n-1)$ pairs of birthdays, any one of which can match. When you rule out matches in the first batch of birthdays you only get as many chances to match as you already have birthdays and the "paradox" disappears.
{ "pile_set_name": "StackExchange" }
Q: Выполнение скрипта ajax Есть скрипт, нужно при его выполнении выводилось сообщение "Заявка отправлена"и модальное окно закрывалось.Скрипт работает а вот сообщение не выводится. Почему то у меня не все работает верно, подправьте код пожалуйста. <script> $(function(){ 'use strict'; $('#form').on('submit', function(e){ e.preventDefault(); var fd = new FormData( this ); $.ajax({ url: 'send.php', type: 'POST', contentType: false, processData: false, data: fd, success: function(msg){ if(msg == 'ok') { $(".button").val("Отправлено"); } else { $(".button").val("Ошибка"); setTimeout(function() {$(".button").val("Отправить");}, 3000); } } }); }); }); </script> Модальное окно <div id="openModal" class="modalDialog"> <div> <a href="#close" title="Закрыть" class="close">x</a> <h2>Заявка онлайн</h2> <form enctype="multipart/form-data" method="post" id="form"> <p>Имя</p> <input placeholder="Владимир Владимирович" name="name" type="text" > <p>Телефон</p> <input placeholder="+7 777 77 77 777" name="number" type="text" > <p>Email</p> <input placeholder="[email protected]" name="email" type="text" > <p><input value="Отправить" type="submit"></p> </form> </div> </div> A: success: function(msg){ alert("SUCCESS! Look in browser console."); console.log("SUCCESS: ", msg); if (msg == 'ok') { $("#form input[type='submit']").val("Отправлено"); } else { $("#form input[type='submit']").val("Ошибка"); setTimeout(function() { $("#form input[type='submit']").val("Отправить"); }, 3000); } }, error: function (rqst) { alert("ERROR! Look in browser console."); console.log("ERROR: ", rqst); }
{ "pile_set_name": "StackExchange" }
Q: How to check if a list contains duplicate items? I want to validate a list to make sure that there are no duplicate items. My problem is that I don't know how to do this in the if statement. Is there a method or something in python that will return False if there are duplicates in the list? Here is what I had in mind: lst = ["1","2","3","3","4"] if #lst contains no duplicates : print("success") else: print("duplicate found") Thanks in advance. A: As said by Jkdc, convert it to a set and compare the length lst = ["1","2","3","3","4"] if len(set(lst)) == len(lst): print("success") else: print("duplicate found")
{ "pile_set_name": "StackExchange" }
Q: Numeric solve transcendental equation in python or Matlab I have a Euler-Bernoulli equation I'm trying to solve where: q(x) = a*x + b + w(x) Euler-Bernoulli equation: E * I * diff(w(x), x, x, x, x) = q(x) I don't really know if this is Transcendental, but I have E, I, a, b and know my integration limits too (0 to H). I have numbers for E, I, a, b and H. How can I obtain points of w(x),x varying x from 0 to H? A: If you wanted to solve it symbolically, you could, with e.g. sympy: from __future__ import division from sympy import * x = symbols('x') w = symbols('w', cls=Function) a,b,E,J = symbols('a b E J') equ = E*J*diff(w(x),x,4) - a*x -b - w(x) dsolve(equ, w(x)) # This generates a function that is too generic and too big to copy-paste # Let's make some assumptions J = Symbol('J', real=True, positive=True) E = Symbol('E', real=True, positive=True) equ = E*J*diff(w(x),x,4) - a*x -b - w(x) dsolve(equ, w(x)) which results in: -x x ─────────── ─────────── 4 ___ 4 ___ 4 ___ 4 ___ ╲╱ E ⋅╲╱ J ╲╱ E ⋅╲╱ J ⎛ x ⎞ ⎛ x ⎞ w(x) = C₁⋅ℯ + C₂⋅ℯ + C₃⋅sin⎜───────────⎟ + C₄⋅cos⎜───────────⎟ - a⋅x - b ⎜4 ___ 4 ___⎟ ⎜4 ___ 4 ___⎟ ⎝╲╱ E ⋅╲╱ J ⎠ ⎝╲╱ E ⋅╲╱ J ⎠ Which you could probably even simplify further, given extra information about your boundary conditions. You'll need them in any case, because you still have 4 unknown coefficients.
{ "pile_set_name": "StackExchange" }
Q: PHP If statement in html form I have the following form but would like to add a condition so that only managers can see 'clear' option. <form action="vision_ref.php" method="post"> With selected: <select name='multi'> <option value='now'>Set next action time to now</option> <option value='clear'>Remove the ticket</option> <option value='unassign'>Unassign Specialist</option> <option value='priority'>Toggle Priority</option> </select> <input type="submit" value="Go!"> </form> Something like: if(havePriv('grp_mgr')) A: <?php if(havePriv('grp_mgr')) : ?> <option value='clear'>Remove the ticket</option> <?php endif; ?> Does the trick
{ "pile_set_name": "StackExchange" }
Q: Twitter Bootstrap 2.0.1 Togglable tabs don't execute properly I'm having an issue right now when trying to use the Twitter Bootstrap Togglable tabs and having it display different div nodes. Everything lays out properly (so I know CSS is hooked up right) and I have the JavaScript referenced and made sure that the functions I need are there, but for some reason when I click the tabs it doesn't display the other div's (based on the link clicked in the navigation field). Here's the markup I'm trying to use <script> $(function () { $('.tabs a:last').tab('show') }) </script> <ul class="nav nav-tabs"> <li class="active"><a href="#home" data-toggle="tab">home</a></li> <li><a href="#about" data-toggle="tab">about tom</a></li> <li><a href="#services" data-toggle="tab">services</a></li> <li><a href="#new_patient" data-toggle="tab">new patients</a></li> </ul> <div class="tab-content" id="tab-content"> <div class="tab-pane fade in active" id="home"> <div class="container"> <div class="slider-wrapper theme-default"> <div id="slider" class="nivoSlider"> <img src="i/6.jpg" alt="" /> <img src="i/1.jpg" alt="" /> <img src="i/2.jpg" alt="" /> <img src="i/3.jpg" alt="" /> <img src="i/4.jpg" alt="" /> <img src="i/5.jpg" alt="" /> </div> </div> <div class="row"> <div class="span4"> <h2>Heading</h2> <p>Etiam porta sem malesuada magna mollis euismod. Integer posuere erat a ante venenatis dapibus posuere velit aliquet. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum. Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit.</p> <p><a class="btn" href="#">View details &raquo;</a></p> </div> <div class="span4"> <h2>Heading</h2> <p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risks. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p> <p><a class="btn" href="#">View details &raquo;</a></p> </div> <div class="span4"> <h2>Heading</h2> <p>Donec sed odio dui. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Vestibulum id ligula porta felis euismod semper. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus.</p> <p><a class="btn" href="#">View details &raquo;</a></p> </div> </div> </div> </div> <div class="tab-pane fade" id="about"> about </div> <div class="tab-pane fade" id="services"> services </div> <div class="tab-pane fade" id="contact"> contact </div> <div class="tab-pane fade" id="new_patient"> new patient form </div> </div> A: I had to add the transition script file and include "fade in" classes to make it work. See the fiddle here: http://jsfiddle.net/johnpapa/qSqpD/
{ "pile_set_name": "StackExchange" }
Q: When to use columns and when a separate table? - Database Design Most people don't recommend EAV and I know some of the reasons. However what is the difference between an EAV-approach and such an approach? Table computer: id, price, description Table connections: id, name (possible values: LAN, USB, HDMI, ..., all all about 10) Table connections_computer comp_id, conn_id Or is that EAV, too? If yes, what would be a normalized alternative? Consider, that I want to do searches like that: All computers, that have BOTH a LAN and a HDMI connection. In this case I would need 1 join / filter attribute, when having it as 1 column / attribute, searching would be easy, but I would have many NULL values. Any recommendation how to do? A: Your example is a plain many-to-many. In the EAV an attribute name is a value of a column, instead of being a name of the column. For example, computer: {computer_id, attr_name, attr_value} insert into computer (computer_id, attr_name, attr_value) values (1, 'connection', 'HDMI') , (1, 'connection', 'USB') , (1, 'memory', '2 GB') ; would be an EAV approach. Here is an example of the price you pay for the EAV approach (flexibility) in a RDBMS.
{ "pile_set_name": "StackExchange" }
Q: How do I convert a string of numbers with commas in it to an integer and add them? I have an object called bondFilms with the following properties, for example "title", "year", and "gross": "272,828,282". I want to loop through each item and add the gross values to get the total gross amount. const bondFilms = [ { "title" : "Skyfall", "year" : 2012, "actor" : "Daniel Craig", "gross" : "$1,108,561,008" }, { "title" : "Thunderball", "year" : 1965, "actor" : "Sean Connery", "gross" : "$1,014,941,117" }, { "title" : "Goldfinger", "year" : 1964, "actor" : "Sean Connery", "gross" : "$912,257,512" }, { "title" : "Live and Let Die", "year" : 1973, "actor" : "Roger Moore", "gross" : "$825,110,761" }, { "title" : "You Only Live Twice", "year" : 1967, "actor" : "Sean Connery", "gross" : "$756,544,419" }, { "title" : "The Spy Who Loved Me", "year" : 1977, "actor" : "Roger Moore", "gross" : "$692,713,752" }, { "title" : "Casino Royale", "year" : 2006, "actor" : "Daniel Craig", "gross" : "$669,789,482" }, { "title" : "Moonraker", "year" : 1979, "actor" : "Roger Moore", "gross" : "$655,872,400" }, { "title" : "Diamonds Are Forever", "year" : 1971, "actor" : "Sean Connery", "gross" : "$648,514,469" }, { "title" : "Quantum of Solace", "year" : 2008, "actor" : "Daniel Craig", "gross" : "$622,246,378" }, { "title" : "From Russia with Love", "year" : 1963, "actor" : "Sean Connery", "gross" : "$576,277,964" }, { "title" : "Die Another Day", "year" : 2002, "actor" : "Pierce Brosnan", "gross" : "$543,639,638" }, { "title" : "Goldeneye", "year" : 1995, "actor" : "Pierce Brosnan", "gross" : "$529,548,711" }, { "title" : "On Her Majesty's Secret Service", "year" : 1969, "actor" : "George Lazenby", "gross" : "$505,899,782" }, { "title" : "The World is Not Enough", "year" : 1999, "actor" : "Pierce Brosnan", "gross" : "$491,617,153" }, { "title" : "For Your Eyes Only", "year" : 1981, "actor" : "Roger Moore", "gross" : "$486,468,881" }, { "title" : "Tomorrow Never Dies", "year" : 1997, "actor" : "Pierce Brosnan", "gross" : "$478,946,402" }, { "title" : "The Man with the Golden Gun", "year" : 1974, "actor" : "Roger Moore", "gross" : "$448,249,281" }, { "title" : "Dr. No", "year" : 1962, "actor" : "Sean Connery", "gross" : "$440,759,072" }, { "title" : "Octopussy", "year" : 1983, "actor" : "Roger Moore", "gross" : "$426,244,352" }, { "title" : "The Living Daylights", "year" : 1987, "actor" : "Timothy Dalton", "gross" : "$381,088,866" }, { "title" : "A View to a Kill", "year" : 1985, "actor" : "Roger Moore", "gross" : "$321,172,633" }, { "title" : "License to Kill", "year" : 1989, "actor" : "Timothy Dalton", "gross" : "$285,157,191" } ]; let result = 0; bondFilms.forEach((film)=>{ result = result + parseInt(film.gross.replace(",", ""))}; console.log(result); However, for some reason I keep on getting NaN. Where did I go wrong? A: A reproduction of the problem is: console.log(parseInt("$42")); That is, we need to account for the "$", because parseInt can't. We can do this by passing a regex to String#replace: /[$,]/g, which matches any literal "$" or "," character (we could also use something like /\D/g, being wary that we might accidentally chop leading negative signs). Note the g global flag. Also, note that you're missing a closing ) on your filter function. const bondFilms = [{ "title" : "Skyfall", "year" : 2012, "actor" : "Daniel Craig", "gross" : "$1,108,561,008" },{ "title" : "Thunderball", "year" : 1965, "actor" : "Sean Connery", "gross" : "$1,014,941,117" },{ "title" : "Goldfinger", "year" : 1964, "actor" : "Sean Connery", "gross" : "$912,257,512" },{ "title" : "Live and Let Die", "year" : 1973, "actor" : "Roger Moore", "gross" : "$825,110,761" },{ "title" : "You Only Live Twice", "year" : 1967, "actor" : "Sean Connery", "gross" : "$756,544,419" },{ "title" : "The Spy Who Loved Me", "year" : 1977, "actor" : "Roger Moore", "gross" : "$692,713,752" },{ "title" : "Casino Royale", "year" : 2006, "actor" : "Daniel Craig", "gross" : "$669,789,482" },{ "title" : "Moonraker", "year" : 1979, "actor" : "Roger Moore", "gross" : "$655,872,400" },{ "title" : "Diamonds Are Forever", "year" : 1971, "actor" : "Sean Connery", "gross" : "$648,514,469" },{ "title" : "Quantum of Solace", "year" : 2008, "actor" : "Daniel Craig", "gross" : "$622,246,378" },{ "title" : "From Russia with Love", "year" : 1963, "actor" : "Sean Connery", "gross" : "$576,277,964" },{ "title" : "Die Another Day", "year" : 2002, "actor" : "Pierce Brosnan", "gross" : "$543,639,638" },{ "title" : "Goldeneye", "year" : 1995, "actor" : "Pierce Brosnan", "gross" : "$529,548,711" },{ "title" : "On Her Majesty's Secret Service", "year" : 1969, "actor" : "George Lazenby", "gross" : "$505,899,782" },{ "title" : "The World is Not Enough", "year" : 1999, "actor" : "Pierce Brosnan", "gross" : "$491,617,153" },{ "title" : "For Your Eyes Only", "year" : 1981, "actor" : "Roger Moore", "gross" : "$486,468,881" },{ "title" : "Tomorrow Never Dies", "year" : 1997, "actor" : "Pierce Brosnan", "gross" : "$478,946,402" },{ "title" : "The Man with the Golden Gun", "year" : 1974, "actor" : "Roger Moore", "gross" : "$448,249,281" },{ "title" : "Dr. No", "year" : 1962, "actor" : "Sean Connery", "gross" : "$440,759,072" },{ "title" : "Octopussy", "year" : 1983, "actor" : "Roger Moore", "gross" : "$426,244,352" },{ "title" : "The Living Daylights", "year" : 1987, "actor" : "Timothy Dalton", "gross" : "$381,088,866" },{ "title" : "A View to a Kill", "year" : 1985, "actor" : "Roger Moore", "gross" : "$321,172,633" },{ "title" : "License to Kill", "year" : 1989, "actor" : "Timothy Dalton", "gross" : "$285,157,191" }]; let result = 0; bondFilms.forEach((film) => { result = result + parseInt(film.gross.replace(/[$,]/g, "")) }); console.log(result); There are more succinct ways of achieving a reduction (transforming an array to a single value), for example Array#reduce, which accumulates a total using a callback function for each element in the array and an initial value for the accumulator. The unary + operator gives the same results as Number, performing a conversion without parseInt (results can be different, but edge cases are unlikely here). const bondFilms = [{ "title" : "Skyfall", "year" : 2012, "actor" : "Daniel Craig", "gross" : "$1,108,561,008" },{ "title" : "Thunderball", "year" : 1965, "actor" : "Sean Connery", "gross" : "$1,014,941,117" },{ "title" : "Goldfinger", "year" : 1964, "actor" : "Sean Connery", "gross" : "$912,257,512" },{ "title" : "Live and Let Die", "year" : 1973, "actor" : "Roger Moore", "gross" : "$825,110,761" },{ "title" : "You Only Live Twice", "year" : 1967, "actor" : "Sean Connery", "gross" : "$756,544,419" },{ "title" : "The Spy Who Loved Me", "year" : 1977, "actor" : "Roger Moore", "gross" : "$692,713,752" },{ "title" : "Casino Royale", "year" : 2006, "actor" : "Daniel Craig", "gross" : "$669,789,482" },{ "title" : "Moonraker", "year" : 1979, "actor" : "Roger Moore", "gross" : "$655,872,400" },{ "title" : "Diamonds Are Forever", "year" : 1971, "actor" : "Sean Connery", "gross" : "$648,514,469" },{ "title" : "Quantum of Solace", "year" : 2008, "actor" : "Daniel Craig", "gross" : "$622,246,378" },{ "title" : "From Russia with Love", "year" : 1963, "actor" : "Sean Connery", "gross" : "$576,277,964" },{ "title" : "Die Another Day", "year" : 2002, "actor" : "Pierce Brosnan", "gross" : "$543,639,638" },{ "title" : "Goldeneye", "year" : 1995, "actor" : "Pierce Brosnan", "gross" : "$529,548,711" },{ "title" : "On Her Majesty's Secret Service", "year" : 1969, "actor" : "George Lazenby", "gross" : "$505,899,782" },{ "title" : "The World is Not Enough", "year" : 1999, "actor" : "Pierce Brosnan", "gross" : "$491,617,153" },{ "title" : "For Your Eyes Only", "year" : 1981, "actor" : "Roger Moore", "gross" : "$486,468,881" },{ "title" : "Tomorrow Never Dies", "year" : 1997, "actor" : "Pierce Brosnan", "gross" : "$478,946,402" },{ "title" : "The Man with the Golden Gun", "year" : 1974, "actor" : "Roger Moore", "gross" : "$448,249,281" },{ "title" : "Dr. No", "year" : 1962, "actor" : "Sean Connery", "gross" : "$440,759,072" },{ "title" : "Octopussy", "year" : 1983, "actor" : "Roger Moore", "gross" : "$426,244,352" },{ "title" : "The Living Daylights", "year" : 1987, "actor" : "Timothy Dalton", "gross" : "$381,088,866" },{ "title" : "A View to a Kill", "year" : 1985, "actor" : "Roger Moore", "gross" : "$321,172,633" },{ "title" : "License to Kill", "year" : 1989, "actor" : "Timothy Dalton", "gross" : "$285,157,191" }]; const result = bondFilms.reduce((a, e) => a + +e.gross.replace(/[$,]/g, ""), 0) ; console.log(result);
{ "pile_set_name": "StackExchange" }
Q: How to bind one texblock value to other textblock one way and get value in MVVM Let me explain my question by an Image I have MVVM structure in My project. I have two textblocks, Textblock 1 and textblock 2. Now I want textblock2's Text same as Textblock1's Text, whenever Textblock1's Text changed. but I should be able to set Textblock2's Text different from Textblock1's. So I am setting Oneway binding of Textblock1's Text Property. How Can I get the Text property of Textblock2's In MVVM. If I create a property for Textblock2's Text property, I wont be able to bind Textblock1's text to textblock2. Let me know if I want to clear my question further. Thanks in anticipation. A: Use two properties in VM, and implement the equal/override logic there. That's exactly the kind of stuff VMs are good in. VM Prop1 <-- Binding- TextBlock1 Prop2 <-- Binding- TextBlock2 The Prop1 setter is implemented such that it also updates Prop2 (don't forget INotifyPropertyChanged), if you set Prop2 make it to switch to and keep the different value.
{ "pile_set_name": "StackExchange" }
Q: Java - private static vs. public static A wrapper class for storing primitive parameters which are initialized with values. Is it better to use public static or private static with bunch of getters and setters, for these constants? public class Wrapper { // This private static int PARAMETER = 100; /** * EDIT: * public int getParameter(); * public void setParameter(int n); * Pointed out by @JimmyJames that I forgot the static accessor. */ public static int getParameter(); public static void setParameter(); // Or this? public static int ANOTHER_PARAMETER = 200; } My observations: 1. These parameter are rarely changed. 2. I feel like it reduces readability when there are a lot of these parameters, if using private static with lots of getters and setters. Any thoughts on which one is better? Maybe depending on different scenarios? Thanks. EDIT Pointed out by @JimmyJames that I missed the static accessor on the methods. I do not think this is related to my question. I should probably phrase my question better, these PARAMETER are more likeCONSTANTS, making them static or even final makes things easier to access directly like doOperation(Wrapper.ANOTHER_PARAMETER) or doOperation(Wrapper.getParameter()). After reading comments and answer of @Robert Harvey and @JimmyJames, and other readings, I think essentially this is a bad practice that should be avoided (using class to hold constants). Where do you keep Constants used throughout your application? MORE QUESTION What if there are moderate amounts of PARAMETERS/CONSTANTS that are used across a module and they cannot be pinpointed to specific classes, at this time should we consider grouping all these together in a class, and access them through the methods mentioned above(as they will be available when class is loaded)? A: There's a major problem with the first approach you are showing here. You have static variables but your methods are not static. This is very abnormal in Java and will create a lot of confusion if you are working on a team. It also has some really negative implications if you ever need to multi-thread. Even in a single-threaded app, you could see instabilities if you are not extremely careful. You should some spend time up-front creating robust classes so that you don't incur the cost of having to be careful with how you use them later. The problem here is that this class needs to be instantiated in order for you to set the class-level variables variables. But there's nothing here preventing more than one instantiation of this class. You could have any number of these objects around and calling a set method will change the value returned by get for all the other instances. This is not typically expected. When you create a object and modify a property, the normal pattern is for it to only change that object. To resolve this, you could make the getter and setter static. This will make it work in a more expected manner. But as Robert Harvey noted in his comment, using static in this way is widely discouraged. Effectively, you will have created global variables (with some minor caveats.) I'm not going to explain why globals are problematic here as there are many articles and answers about that topic already. The more popular option here is to (again as mentioned by Robert Harvey) create a normal Java object that you then pass to things that need these parameters. This can be done in code or using various injection frameworks.
{ "pile_set_name": "StackExchange" }
Q: I can't get correct emaid, phone number for a name {"name":["bineesh","Administrator","binu","binu","bijith","prem","rahul"],"email":["[email protected]","[email protected]","[email protected]","[email protected]","[email protected]","[email protected]","[email protected]"],"phone":["345366","12345","0","0","0","979797","7655775"]} JSON parsing using to I retrieve all the name value. I showed that name in a list view but when I click first name I can't get correct email, and phone number for name Please help. JSONObject myJson = new JSONObject(result); JSONArray ja = myJson.getJSONArray("name"); JSONArray je = myJson.getJSONArray("email"); JSONArray jp = myJson.getJSONArray("phone"); int length=ja.length(); List<String> listContents = new ArrayList<String>(length); for (int i = 0; i < length; i++) { // employeeText.setText(ja.getString(i)); System.out.println(ja.getString(i)); listContents.add(ja.getString(i)); } ArrayAdapter<String> a=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,listContents); setListAdapter(a); } catch(JSONException e1){ Toast.makeText(getBaseContext(), "No name found" ,Toast.LENGTH_LONG).show(); } catch (ParseException e1) { e1.printStackTrace(); } } @Override protected void onListItemClick(ListView l, View v, int position, long id) { // TODO Auto-generated method stub super.onListItemClick(l, v, position, id); if(id==0) { for (int i = 0; i < je.length(); i++) { // employeeText.setText(ja.getString(i)); try { System.out.println(je.getString(0)); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } Intent i=new Intent(Employeedetail.this,details.class); startActivity(i); A: Instead i would suggest you create a JSON Array with object. One Object is having name, email and phone values. Because you just have to get an object from particular position only. It would also decrease load of this comparison.
{ "pile_set_name": "StackExchange" }
Q: How do you make images load lazily only when they are in the viewport? I am seeing a lot of sites these days, mainly tutorial sites that have a lot of images and they only load images further down the page once they come into the view port? How would I go about doing this? As you scroll down the page the images who were below the viewport fade in A: Simple solution that does not depend on JQuery: <script type="text/javascript"> refresh_handler = function(e) { var elements = document.querySelectorAll("*[realsrc]"); for (var i = 0; i < elements.length; i++) { var boundingClientRect = elements[i].getBoundingClientRect(); if (elements[i].hasAttribute("realsrc") && boundingClientRect.top < window.innerHeight) { elements[i].setAttribute("src", elements[i].getAttribute("realsrc")); elements[i].removeAttribute("realsrc"); } } }; window.addEventListener('scroll', refresh_handler); window.addEventListener('load', refresh_handler); window.addEventListener('resize', refresh_handler); </script> A: http://www.appelsiini.net/projects/lazyload https://github.com/tuupola/jquery_lazyload Demo: http://www.appelsiini.net/projects/lazyload/enabled.html A: Replace your images with placeholders (e.g. just change the "src" attribute to something else so the image won't load, but the url will still be accessible), and then bind the window scroll event to a function which will find all images at the current scroll position, and swap the image src into a real img tag. Here's the code. It's untested, but this should be the basic idea: <img src="" realsrc="/myimage.png" /> $(document).ready(function(){ $(window).scroll(function(){ $('img[realsrc]').each(function(i){ var t = $(this); if(t.position().top > ($(window).scrollTop()+$(window).height()){ t.attr('src', t.attr('realsrc')); // trigger the image load t.removeAttr('realsrc'); // so we only process this image once } }); }) });
{ "pile_set_name": "StackExchange" }
Q: AppDomain.CurrentDomain.GetAssemblies() throws System.Reflection.ReflectionTypeLoadException when using Sybase I think i have used a quite common pattern: var result = from a in AppDomain.CurrentDomain.GetAssemblies() from t in a.GetTypes() where t.IsDefined(typeof(TAttribute), inherit) select t; If i call the code from Program.cs it works. Also if i call it from a form it works - sometimes, depending on the form. Sometimes it is only throwing an error: Mindestens ein Typ in der Assembly kann nicht geladen werden. Rufen Sie die LoaderExceptions-Eigenschaft ab, wenn Sie weitere Informationen benötigen. In the details there is the information: {"Die Datei oder Assembly \"EntityFramework, Version=4.2.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" oder eine Abhängigkeit davon wurde nicht gefunden. Das System kann die angegebene Datei nicht finden.":"EntityFramework, Version=4.2.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"} This is somehow a bit amazing for me. As far as I know we don't use EntityFramework anywhere, only Telerik as ER. I have done a "findstr /s /i /m entityframework ." in the projekt directories. Funilly, it has found it in a Sybase dll "SQL Anywhere 12\iAnywhere.Data.SQLAnywhere.v4.0.dll". okay - that seems a bit like a sybase sql data provider. But so far as I can see we do not need EntityFramework, and the project also works as anticipated. How can i resolve this issue? Like saying: I want to parse Appdomain, but not some third party dlls. Or is there any way to ignor the error? A: Parsing whole appdomain in such matter will scan all dlls that are loaded and all types form all of them will be loaded event if they are not used in your application. I'm not fluent in German but I assume that the error means that EF dll was not found. It is required to load some class that is not used by your code and is declared in some dll that is loaded in appdomain and it requires EF. You say you use Telerik, maybe it has some controls that utilize EF directly? The simple solution if you want to scan only your dlls would be to introduce convention for assembly names. Say all your dlls will be named OfflerCompany.ProjectName.Something and scan dll name for OfflerCompany. Also note that dlls are lazy loaded to appdomain so if you expect all of your dlls to be present you might be disappointed (there might be there already if all where used directly or not at least once). You might want to consider crrating configuration file that contains names of all dlls that need to be scanned. This is the cleanest and most transparent solution that I prefer.
{ "pile_set_name": "StackExchange" }
Q: Extracting data from .txt files and writing to Excel - follow-up After I got this answer, I edited my code after that answer, but the code still seems kind of slow. Can I make any other improvements? And why does the code seem to get slower with every minute? It seems to start great and continue slow. Am I missing something here? using System; using System.Windows.Forms; using Microsoft.Office.Interop.Excel; using System.IO; using System.Linq; using System.Diagnostics; namespace Report { public partial class Form1 : Form { public Form1() { InitializeComponent(); } string GetLine(string fileName, int line) { using (var sr = new StreamReader(fileName)) { for (int i = 1; i < line; i++) sr.ReadLine(); return sr.ReadLine(); } } private void button1_Click(object sender, EventArgs e) { Stopwatch timer = new Stopwatch(); timer.Start(); Microsoft.Office.Interop.Excel.Application excelapp = new Microsoft.Office.Interop.Excel.Application(); excelapp.Visible = true; _Workbook workbook = (_Workbook)(excelapp.Workbooks.Open(textBox2.Text)); _Worksheet worksheet = (_Worksheet)workbook.ActiveSheet; DateTime dt = DateTime.Now; foreach (string fileName in Directory.GetFiles(textBox1.Text, "*.txt")) { int row = 1, EmptyRow = 0; while (Convert.ToString(worksheet.Range["A" + row].Value) != null) { row++; EmptyRow = row; } var line2s = File.ReadLines(fileName).Skip(9).Take(1).ToArray(); string comp = line2s[0]; string compare = comp.Substring(30, comp.Length - 30); if (compare != "Failed") { continue; } else { string[] lines = File.ReadAllLines(fileName); string serial = lines[3]; string data = lines[4]; string time = lines[5]; string operat = lines[6]; string result = lines[9]; (worksheet.Cells[EmptyRow, 1] as Microsoft.Office.Interop.Excel.Range).Value2 = serial.Substring(30, serial.Length - 30); (worksheet.Cells[EmptyRow, 2] as Microsoft.Office.Interop.Excel.Range).Value2 = data.Substring(30, data.Length - 30); (worksheet.Cells[EmptyRow, 3] as Microsoft.Office.Interop.Excel.Range).Value2 = time.Substring(30, time.Length - 30); (worksheet.Cells[EmptyRow, 4] as Microsoft.Office.Interop.Excel.Range).Value2 = operat.Substring(30, operat.Length - 30); (worksheet.Cells[EmptyRow, 5] as Microsoft.Office.Interop.Excel.Range).Value2 = result.Substring(30, result.Length - 30); foreach (string line in lines) { if (line.Contains("FixtureCoverResistance:")) { (worksheet.Cells[EmptyRow, 6] as Microsoft.Office.Interop.Excel.Range).Value2 = line.Substring(31, line.Length - 31); } else if (line.Contains("FwProgrammingCheck:")) { (worksheet.Cells[EmptyRow, 7] as Microsoft.Office.Interop.Excel.Range).Value2 = line.Substring(31, line.Length - 31); } else if (line.Contains("Checksum =")) { (worksheet.Cells[EmptyRow, 8] as Microsoft.Office.Interop.Excel.Range).Value2 = line.Substring(11, line.Length - 11); } else if (line.Contains("FwEepromCheck:")) { (worksheet.Cells[EmptyRow, 9] as Microsoft.Office.Interop.Excel.Range).Value2 = line.Substring(31, line.Length - 31); } else if (line.Contains("FixtureCoverResistanceAfterProg:")) { (worksheet.Cells[EmptyRow, 11] as Microsoft.Office.Interop.Excel.Range).Value2 = line.Substring(33, line.Length - 33); } } } } TimeSpan ts = timer.Elapsed; label2.Text = ts.ToString("mm\\:ss\\.ff"); timer.Stop(); } private void button2_Click(object sender, EventArgs e) { if (folderBrowserDialog1.ShowDialog() == DialogResult.OK) { textBox1.Text = folderBrowserDialog1.SelectedPath; } } private void button3_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == DialogResult.OK) { textBox2.Text = openFileDialog1.FileName.ToString(); } } } } A: I am not providing review from programming good practice or architecture perspective. I just want to provide you some recommendations to improve performance of your code you have asked. 1) Find first empty cell on worksheet Your while loop way to find first empty row is inefficient. Getting value from cell via Interop is slow. Instead of this block: while (Convert.ToString(worksheet.Range["A" + row].Value) != null) { row++; EmptyRow = row; } Use single line built in Excel function: int emptyRow = worksheet.Cells[worksheet.Cells.Rows.Count, "A"].End[-4162].Row + 1; Constant -4162 is xlUp constant and you can find it in Excel documentation or in object browser in VBE. 2) Use temporary string[] array Writing to worksheet cells one by one is inefficient. Work with string array and fill final array at once into worksheet. You can initialize array: string[,] rangeArray = new string[1, 11]; Then instead of writing values to cells: (worksheet.Cells[EmptyRow, 1] as Range).Value2 = serial.Substring(30, serial.Length - 30); (worksheet.Cells[EmptyRow, 2] as Range).Value2 = data.Substring(30, data.Length - 30); store them in array, which is very fast operation: rangeArray[0,0] = serial.Substring(30, serial.Length - 30); rangeArray[0,1] = data.Substring(30, data.Length - 30); Finally fill array in worksheet: Range c1 = (Range)worksheet.Cells[emptyRow, 1]; Range c2 = (Range)worksheet.Cells[emptyRow, 11]; Range range = worksheet.Range[c1, c2]; range.Value = rangeArray; 3) Still not satisfied with performance? If you are still not satisfied with performance, avoid of using Office.Interop. You can parse your text files in C# and store the output in CSV file. The final CSV file you can easily open in Excel. There are also alternatives like ExcelLibrary. This should be also faster than Interop.
{ "pile_set_name": "StackExchange" }
Q: Is it possible to get number of downloads of an application from Google Play? I am trying to get the number of downloads of an application that I have uploaded to Google Play. I am searching for an API (or something similar) that retrieves to me the number of downloads with the authentification of the user. I do not want third party applications (like AppAnnie). It would be great if it could be on PHP and I found that there is a library which I think it is the most closest API I could find to get data from Google applications. Google APIs Client Library for PHP but I cannot find any mention to Google Play applications. Is there some way to get the downloads of an specific application having the authentification keys? Thanks in advance! A: This is about meta data api. You can look at below. https://developers.google.com/android-publisher/api-ref/reviews A: Use the google-play-scraper library to get an app information as below: Example: $app = $scraper->getApp('com.mojang.minecraftpe'); Result: array ( 'id' => 'com.mojang.minecraftpe', 'url' => 'https://play.google.com/store/apps/details?id=com.mojang.minecraftpe', 'image' => 'https://lh3.googleusercontent.com/30koN0eGl-LHqvUZrCj9HT4qVPQdvN508p2wuhaWUnqKeCp6nrs9QW8v6IVGvGNauA=w300', 'title' => 'Minecraft: Pocket Edition', 'author' => 'Mojang', 'author_link' => 'https://play.google.com/store/apps/developer?id=Mojang', 'categories' => array ( 'Arcade', 'Creativity', ), 'price' => '$6.99', 'screenshots' => array ( 'https://lh3.googleusercontent.com/VkLE0e0EDuRID6jdTE97cC8BomcDReJtZOem9Jlb14jw9O7ytAGvE-2pLqvoSJ7w3IdK=h310', 'https://lh3.googleusercontent.com/28b1vxJQe916wOaSVB4CmcnDujk8M2SNaCwqtQ4cUS0wYKYn9kCYeqxX0uyI2X-nQv0=h310', // [...] ), 'description' => 'Our latest free update includes the Nether and all its inhabitants[...]', 'description_html' => 'Our latest free update includes the Nether and all its inhabitants[...]', 'rating' => 4.4726405143737793, 'votes' => 1136962, 'last_updated' => 'October 22, 2015', 'size' => 'Varies with device', 'downloads' => '10,000,000 - 50,000,000', 'version' => 'Varies with device', 'supported_os' => 'Varies with device', 'content_rating' => 'Everyone 10+', 'whatsnew' => 'Build, explore and survive on the go with Minecraft: Pocket Edition[...]', 'video_link' => 'https://www.youtube.com/embed/D2Z9oKTzzrM?ps=play&vq=large&rel=0&autohide=1&showinfo=0&autoplay=1', 'video_image' => 'https://i.ytimg.com/vi/D2Z9oKTzzrM/hqdefault.jpg', ) EDIT: Easily get downloads count as below: echo $app['downloads']; // Outputs: '10,000,000 - 50,000,000' Or if you want the left value: $matches = null; $returnValue = preg_match('/.*(?= -)/', '10,000,000 - 50,000,000', $matches); echo $matches[0]; // Outputs: '10,000,000' Or if you want the right value: $matches = null; $returnValue = preg_match('/(?<=- ).*/', '10,000,000 - 50,000,000', $matches); echo $matches[0]; // Outputs: '50,000,000' Then easily convert it to integer using: $count = null; $returnValue = (int)preg_replace('/,/', '', $matches[0], -1, $count); echo $returnValue; // Outputs: 10000000 or 50000000 A: You need to Scrape it. Generally speaking, & of course in this particular case, when the website(here: Google Play) does not provide an API to make your(client's) desired data accessible to him, Web scraping is one of the best methods to gather your required information. Nearly every piece of information that you can see on a web page, can be scraped. Nowadays with great improvements of web scrapers, not only you are able to grab data from a target website, but also "crawling it like a user", "posting information to website via forms", "logging in as a user" & etc. has become a routine for any web scraper. There are very strong scrapers out there, like Scrapy(likely the most reputed one, written in Python) almost for every language. AFAIK the best web scraper in PHP, is Goutte written by legendary @fabpot from FriendsOfPHP. From the Data-Extraction POV, Goutte supports both "CSS Selectors" & XPath (Because it uses Symfony's DOM Crawler as Crawling engine). So you can crawl the document the way you want to extract every piece of information in any hidden corner of a web page! You can go faraway in scraping with Goutte, But just as a tiny example for grabbing "number of installs" from an ordinary App page in a blink of an eye: use Goutte\Client; $Client = new Client(); /** * @var \Symfony\Component\DomCrawler\Crawler */ $Crawler = $Client->request('GET', "https://play.google.com/store/apps/details?id=com.somago.brainoperator&hl=en"); $numberOfInstalls = $Crawler->filter('div.details-section-contents div.meta-info')->eq(1)->filter('div.content')->eq(0)->text(); echo $numberOfInstalls; It will simply print Brain Operator game's "number of downloads".
{ "pile_set_name": "StackExchange" }
Q: Виртуальный манипулятор (джойстик) на JS Для проекта требуется создать эмулятор джойстика, чтобы при определенном положении манипулятора серверу отсылалась определенная команда, исходя из X и Y координат. Серый квадрат в левом верхнем углу и есть сам манипулятор. Он должен находится в центре темно-серой области с начальными значениями X:0 Y:0 Передвижение осуществляется мышкой (навести -> нажать -> перетащить в любую точку области) Подскажите, пожалуйста, с чего начать? Так как в JS новичок, опыта совсем нет, погуглив понял, что используют фреймворк jQuery, но какие именно методы брать из него - не совсем понятно. html: <!DOCTYPE html> <html lang="ru"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Joystick</title> <script src="joy.js"></script> <script src="jquery/jquery-1.9.1.js"></script> <script src="jquery/jquery-ui.js"></script> <link rel="stylesheet" href="style.css"> </head> <body> <div id="joyStick" class="joyStick"> <div class="joyManipulator"></div> </div> <div id = "panel"> <center> <p> <input type="text" value="0" id="ox" /><br /> <input type="text" value="0" id="oy" /><br /></p> <button id = "reset">reset</button><p> </center> </div> </body> </html> css: html, body { height: 100%; margin: 0; padding: 0; overflow-x:hidden; } body{ background-color: #2e2e2e; } .joyStick { margin: 500px auto; margin-bottom: 20px; width:200px; height:200px; background:#222121; border:1px solid black; border-radius: 10px; border-width: 1px; position:relative; } .joyManipulator { width:40px; height:40px; position:absolute; border-radius:10px; background:rgb(206, 206, 206); cursor:pointer; } #panel { margin: 0 auto; width: 200px; background-color: #222121; border:1px solid black; border-radius: 10px; border-width: 1px; } #reset { padding: 10px; color: rgb(255, 255, 255); font-family: Arial; border:1px solid rgb(255, 255, 255); border-width: 1px; background-color: rgb(47, 47, 47); cursor: pointer; } #ox, #oy { margin: 0 auto; padding: 5px; } A: Так как в JS новичок, опыта совсем нет Необходимо изучить основы JS. Сделать такое можно при помощи getBoundingClientRect() https://learn.javascript.ru/coordinates#koordinaty-otnositelno-okna-getboundingclientrect https://developer.mozilla.org/ru/docs/Web/API/Element/getBoundingClientRect Примеры реализаций: codepen.io/nathantaylor/pen/QdpOyB codepen.io/dev357/pen/ldaKx
{ "pile_set_name": "StackExchange" }
Q: How to convert Month in character to number, for example, September to 9 I am working with a df, one column is factor, value from January to December, I want to convert them into numbers, such as January ——> 1 A: x <- c("September", "December", "January") match(x, month.name) [1] 9 12 1
{ "pile_set_name": "StackExchange" }
Q: how to check an instance variable I am new to rails and am stuck: I have a model for Articles, Topics and Links. On the page, where the whole article is displayed, I show in div-boxes all @topics and all @links, which are connected to this article (@topics.each ...). Sometimes there is/are no topic/topics or link/links connected to this one article and I don't want to show the div-box. How do I test if the instance variable @topics is empty and therefore must not be displayed? Do I check this in the view or do I check it in the controller? Since I have no real clue I don't know where to start looking for. A: The usual pattern is this: if (@topics.present?) @topics.each do |topic| # ... Show each row end else # .. Show a "no entires" row. end
{ "pile_set_name": "StackExchange" }
Q: definition of caffe.Layer class When defining a python layer in Caffe like this, there are fields like voc_dir, split,random, etc, some of them are said to inherit from caffe.Layer class. However where can I find the definition of caffe.Layer class? Searched through Caffe's documentation but they provide very little explanation, and didn't find it after looking in several directories in their code base. A: The Layer class is implemented in the (core) C++ code of caffe. (link) The Boost Python wrapper defines the interface as follows, in python/_caffe.cpp (which is compiled to python/caffe/_caffe.so): bp::class_<Layer<Dtype>, shared_ptr<PythonLayer<Dtype> >, boost::noncopyable>("Layer", bp::init<const LayerParameter&>()) This interface is then imported by the caffe module init: from ._caffe import init_log, log, set_mode_cpu, set_mode_gpu, set_device, **Layer**
{ "pile_set_name": "StackExchange" }
Q: Book on market microstructure Can I get some recommendations for a book on market microstructure? I'm not looking for some author's questionable methods for trading, I'm just looking for a book that provides me with facts about how order books, closing auctions, order execution, etc. really works. I'm also NOT looking for the type of depth that a HFT would be interested in. I know that whole books can be written about the various plumbing of a particular exchange. I'm simply looking for a general overview of how exchanges work. A: My two favorites books on microstructure are: Barry Johnson's Algorithmic Trading and DMA - very good on technological aspects and for an overview of needed implementations; L and Laruelle's Market Microstructure in Practice - for common knowledge and understanding of market microstructure and its mechanisms. Recently, three new books have been published: The Financial Mathematics of Market Liquidity: From Optimal Execution to Market Making, by Olivier Guéant - useful for optimal trading in practice, to be read by quants. Algorithmic and High-Frequency Trading, by A. Cartea, S. Jaimungal, and J Penalva - useful for a stochastic-control oriented on different optimal trading frameworks, to be read be researchers starting in the domain. Quantitative Trading: Algorithms, Analytics, Data, Models, Optimization, by Xin Guo, Tze Leung Lai, Howard Shek, Samuel Po-Shing Wong - for a generic overview (including software programming) of automated trading. On the theoretical (economical) aspect, you have two good books: Vives' Information and Learning in Markets - The Impact of Market Microstructure - for a theoretical overview; Foucault et al.'s Market Liquidity: Theory, Evidence, and Policy - more focussed on recent evolutions. In terms of skills, you need to be able to learn statistics, (stochastic) control and optimization. That for I would consider to read: Meucci's Risk and Asset Allocation - of course it is not written explicitly for microstructure, but if I had to learn from scratch multivariate statistics for financial markets, I will definitely use this one. you should take a book on stochastic control, take the one you want, but frankly my favorite is Soner's Controlled Markov Processes and Viscosity Solutions. It may be too theoretical for what you need to control a trading algorithm, but it may be the occasion to read a good book on control. A: I've not yet read it, but Lehalle's recent book is bound to be a goldmine of good micro-structure bits and pieces. Market Microstructure in Practice EDIT: I'm reading the book now, so far it's quite good. A: Classical book on market microstructure is: Trading and Exchanges: Market Microstructure for Practitioners by Larry Harris. It's a bit outdated (2002) and missing few recent market developments like dark pools etc. but the way it currently is it's already highly recommended reading. Personally I'm waiting for the next edition of the same book, and surely many others waiting as well (though not sure it will ever be published, even so Larry Harris is still actively engaged in the industry and academy). The current market microstructure - probably the best source would be academic papers, I'm not aware of recent good books on this topic.
{ "pile_set_name": "StackExchange" }
Q: How to find this $\iint_{D}f(x)\,dxdy$ Let $x\in \left[0,\dfrac{\pi}{2}\right]$ and $$f(x)=\int_{0}^{\cos^2{x}}\arccos{\sqrt{t}}\,dt-\int_{0}^{\sin^2{x}}\arcsin{\sqrt{t}}\,dt.$$ Find the value $$\iint_{D}f(x)\, dxdy,\quad\text{where } D=\{(x,y)\mid x^2+y^2\le 1\}.$$ My idea: $$f'(x)=-2\cos{x}\sin{x}\cdot x-2\sin{x}\cos{x}\cdot x=-2x\sin{2x}$$ so $$f(x)=\int_{0}^{x}f(t)\,dt+f(0)=\cdots=\int_{0}^{1}\arccos{\sqrt{t}}\,dt+x\cos{2x}-\dfrac{1}{2}\sin{(2x)}$$ so $$\iint_{D}f(x)\,dxdy=\cdots=\dfrac{\pi}{2}\int_{0}^{1}\arccos{\sqrt{t}}\,dt+2+\iint_{D}x\cos{(2x)}\,dxdy-1/2\iint_{D}\sin{2x}\,dxdy$$ But $$\iint_{D}x\cos{(2x)}\,dxdy$$ is very ugly, so my idea is not good? Thank you everyone have nice methods? Thank you A: You are off on the right foot; I agree that $f'(x)=-2 x \sin{2 x}$, and therefore $f(x) = x^2 \cos{2 x} - (x/2) \sin{2 x} + C$, where $$\begin{align}C = f(0) &= \int_0^1 dt \, \arccos{\sqrt{t}}\\ &= 2 \int_0^1 du \, u \, \arccos{u}\\ &= [u^2 \arccos{u}]_0^1 + \int_0^1 du \frac{u^2}{\sqrt{1-u^2}} \\ &= 0 + \int_0^{\pi/2} d\theta \, \sin^2{\theta} \\ &= \frac{\pi}{4}\end{align}$$ The double integral may be simply expressed in Cartesians: $$\begin{align}\iint_D dx dy \,f(x) &= \int_{-1}^1 dx \, \left (x^2 \cos{2 x} - \frac{x}{2} \sin{2 x} + \frac{\pi}{4} \right ) \int_{-\sqrt{1-x^2}}^{\sqrt{1-x^2}} dy \\ &= 2 \int_{-1}^1 dx \, \left (x^2 \cos{2 x} - \frac{x}{2} \sin{2 x} + \frac{\pi}{4} \right ) \sqrt{1-x^2}\end{align}$$ Now, $$\frac{\pi}{2} \int_{-1}^1 dx \, \sqrt{1-x^2} = \frac{\pi^2}{4}$$ For the other integrals, consider the following integral: $$J(a) = \int_{-1}^1 dx \, \sqrt{1-x^2} \, e^{i a x} = \frac{\pi}{a} J_1(a)$$ where $J_1$ is the Bessel function of the first kind of order $1$. Now, $$J'(a) = i \int_{-1}^1 dx \, x \, \sqrt{1-x^2} \, e^{i a x} =\pi \frac{d}{da} \frac{J_1(a)}{a}$$ so that $$\int_{-1}^1 dx \, x \, \sqrt{1-x^2} \, \sin{a x} = -\pi \left (\frac{J_1'(a)}{a} - \frac{J_1(a)}{a^2} \right ) = \frac{\pi}{2 a} \left [\frac{2 J_1(a)}{a} + J_2(a)-J_0(a) \right ] \\ =\frac{\pi}{a} J_2(a) $$ Evaluating $J''(a)$ in a similar fashion, we find that $$\int_{-1}^1 dx \, x^2 \sqrt{1-x^2} \cos{a x} = \frac{\pi}{a} \left [J_1(a) - \frac{3 J_2(a)}{a} \right ]$$ Putting this all together, plugging in $a=2$, I get $$\iint_D dx dy \,f(x) = \pi [ J_1(2)- 2 J_2(2)]+\frac{\pi^2}{4}$$
{ "pile_set_name": "StackExchange" }
Q: Strip spaces when inserting a record into Rails I have a table in Rails with just one column called :name. When inserting a record into this table, I would like to strip all the spaces from the text and change it to upper case. Where would i write this method — in the Model file? What method would I have to override? When inserting data into this Model, I'm using a method called find_or_create_by_name. A: Use an ActiveRecord callback. It might look like this: class MyModel < ActiveRecord::Base before_save :strip_and_upcase_name def strip_and_upcase_name self.name.strip! self.name.upcase! end end
{ "pile_set_name": "StackExchange" }
Q: iOS: Getting real-time (ish) video data I'm trying to write an program that, as part of its functionality, continuously captures video and calculates the average luminance of the video data of the given frame in real-time, or as close to real-time as possible. This is my first foray into any video stuff/iOS camera things at all, so I've kind of just schlepped a lot of things I've researched on the internet together in addition to my own stuff. Right now this code in my ViewController.m file will compile and run on my device, but it doesn't appear to be doing anything: - (void)viewDidLoad{ [super viewDidLoad]; _val = 0; //Set up the video capture session. NSLog(@"Setting up the capture session...\n"); captureSession = [[AVCaptureSession alloc] init]; //Add input. NSLog(@"Adding video input...\n"); AVCaptureDevice *captureDevice = [self frontFacingCameraIfAvailable]; if(captureDevice){ NSError *error; videoInputDevice = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error]; if(!error){ if([captureSession canAddInput:videoInputDevice]) [captureSession addInput:videoInputDevice]; else NSLog(@"Couldn't add video input.\n"); }else{ NSLog(@"Couldn't create video input.\n"); } }else{ NSLog(@"Couldn't create capture device.\n"); } //Add output. NSLog(@"Adding video data output...\n"); vidOutput = [[AVCaptureVideoDataOutput alloc] init]; vidOutput.alwaysDiscardsLateVideoFrames = YES; if([captureSession canAddOutput:vidOutput]) [captureSession addOutput:vidOutput]; else NSLog(@"Couldn't add video output.\n"); NSString* key = (NSString*)kCVPixelBufferPixelFormatTypeKey; NSNumber* value = [NSNumber numberWithUnsignedInt:kCVPixelFormatType_420YpCbCr8BiPlanarFullRange]; NSDictionary* videoSettings = [NSDictionary dictionaryWithObject:value forKey:key]; [vidOutput setVideoSettings:videoSettings]; dispatch_queue_t queue = dispatch_queue_create("MyQueue", NULL); [vidOutput setSampleBufferDelegate:self queue:queue]; } - (void)viewDidUnload{ [super viewDidUnload]; // Release any retained subviews of the main view. } -(AVCaptureDevice *)frontFacingCameraIfAvailable{ NSArray *videoDevices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]; AVCaptureDevice *captureDevice = nil; for (AVCaptureDevice *device in videoDevices){ if (device.position == AVCaptureDevicePositionFront){ captureDevice = device; break; } } //couldn't find one on the front, so just get the default video device. if (!captureDevice){ captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; } return captureDevice; } - (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection: (AVCaptureConnection *)connection{ // Create autorelease pool because we are not in the main_queue @autoreleasepool { CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer); // Lock the imagebuffer CVPixelBufferLockBaseAddress(imageBuffer,0); // Get information about the image uint8_t *baseAddress = (uint8_t *)CVPixelBufferGetBaseAddress(imageBuffer); // size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer); size_t width = CVPixelBufferGetWidth(imageBuffer); size_t height = CVPixelBufferGetHeight(imageBuffer); size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer); CVPlanarPixelBufferInfo_YCbCrBiPlanar *bufferInfo = (CVPlanarPixelBufferInfo_YCbCrBiPlanar *)baseAddress; // This just moved the pointer past the offset baseAddress = (uint8_t *)CVPixelBufferGetBaseAddressOfPlane(imageBuffer, 0); // convert the image UIImage *image = [self makeImage:baseAddress bufferInfo:bufferInfo width:width height:height bytesPerRow:bytesPerRow]; // Update the display with the captured image for DEBUG purposes //dispatch_async(dispatch_get_main_queue(), ^{ //[self.vImage setImage:image]; //}); CGImageRef cgImage = [image CGImage]; CGDataProviderRef provider = CGImageGetDataProvider(cgImage); CFDataRef bitmapData = CGDataProviderCopyData(provider); const UInt8* data = CFDataGetBytePtr(bitmapData); int cols = width - 1; int rows = height - 1; float avgLuminance = 0.0; for(int i = 0; i < cols; i++){ for(int j = 0; j < rows; j++){ const UInt8* pixel = data + j*bytesPerRow + i*4; avgLuminance += pixel[0]*0.299 + pixel[1]*0.587 + pixel[2]*0.114; } } avgLuminance /= (cols*rows); NSLog(@"Average Luminance: %f\n", avgLuminance); } } -(UIImage *)makeImage:(uint8_t *)inBaseAddress bufferInfo:(CVPlanarPixelBufferInfo_YCbCrBiPlanar *)inBufferInfo width: (size_t)Width height:(size_t)Height bytesPerRow:(size_t)BytesPerRow{ NSUInteger yPitch = EndianU32_BtoN(inBufferInfo->componentInfoY.rowBytes); uint8_t *rgbBuffer = (uint8_t *)malloc(Width * Height * 4); uint8_t *yBuffer = (uint8_t *)inBaseAddress; uint8_t val; int bytesPerPixel = 4; // for each byte in the input buffer, fill in the output buffer with four bytes // the first byte is the Alpha channel, then the next three contain the same // value of the input buffer for(int y = 0; y < Height*Width; y++){ val = yBuffer[y]; // Alpha channel rgbBuffer[(y*bytesPerPixel)] = 0xff; // next three bytes same as input rgbBuffer[(y*bytesPerPixel)+1] = rgbBuffer[(y*bytesPerPixel)+2] = rgbBuffer[y*bytesPerPixel+3] = val; } // Create a device-dependent RGB color space CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(rgbBuffer, yPitch, Height, 8,yPitch*bytesPerPixel, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedLast); CGImageRef quartzImage = CGBitmapContextCreateImage(context); CGContextRelease(context); //UIImage *image = [[UIImage alloc] initWithCGImage:quartzImage scale:(CGFloat)0.5 orientation:UIImageOrientationRight]; UIImage *image = [UIImage imageWithCGImage:quartzImage]; CGImageRelease(quartzImage); free(rgbBuffer); return image; } I set my .h file as an AVCaptureVideoDataOutputSampleBufferDelegate but I get the feeling that I'm not quite understanding what I need to do in my code to be constantly getting data from the camera, as the CaptureOutput method never gets called anywhere. How/where should I be calling it in order to get a constant stream of data? A: I'm an idiot. All I needed was this: [captureSession startRunning]; Imagine that. Heh.
{ "pile_set_name": "StackExchange" }
Q: javascript executed php mail script not sending email My Website uses the following javascript to check the entered values and the execute the php script: $(function() { $("#contactForm input,#contactForm textarea").jqBootstrapValidation({ preventSubmit: true, submitError: function($form, event, errors) { // additional error messages or events }, submitSuccess: function($form, event) { event.preventDefault(); // prevent default submit behaviour // get values from FORM var name = $("input#name").val(); var email = $("input#email").val(); var phone = $("input#phone").val(); var message = $("textarea#message").val(); var firstName = name; // For Success/Failure Message // Check for white space in name for Success/Fail message if (firstName.indexOf(' ') >= 0) { firstName = name.split(' ').slice(0, -1).join(' '); } console.log("name: " + name + ", email: " + email + ", phone: " + phone + ", message: " + message); $.ajax({ url: "././mail/contact_me.php", type: "POST", data: { name: name, phone: phone, email: email, message: message }, cache: false, success: function() { // Success message $('#success').html("<div class='alert alert-success'>"); $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;") .append("</button>"); $('#success > .alert-success') .append("<strong>Your message has been sent. </strong>"); $('#success > .alert-success') .append('</div>'); //clear all fields $('#contactForm').trigger("reset"); }, error: function() { // Fail message $('#success').html("<div class='alert alert-danger'>"); $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;") .append("</button>"); $('#success > .alert-danger').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!"); $('#success > .alert-danger').append('</div>'); //clear all fields $('#contactForm').trigger("reset"); }, }) }, filter: function() { return $(this).is(":visible"); }, }); $("a[data-toggle=\"tab\"]").click(function(e) { e.preventDefault(); $(this).tab("show"); }); }); /*When clicking on Full hide fail/success boxes */ $('#name').focus(function() { $('#success').html(''); }); The php script is as follows: <?php // Check for empty fields if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['phone']) || empty($_POST['message']) || !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)) { echo "No arguments Provided!"; return false; } $name = $_POST['name']; $email_address = $_POST['email']; $phone = $_POST['phone']; $message = $_POST['message']; // Create the email and send the message $to = '[email protected]'; $email_subject = "Fixed IT Contact Form: $name"; $email_body = "Volgend bericht werd verstuurd via fixedit.eu:\n\nNaam: $name\n\nEmail: $email_address\n\nTelefoon: $phone\n\nBericht:\n$message"; $headers = "From: [email protected]\n"; $headers .= "Reply-To: $email_address"; mail($to,$email_subject,$email_body,$headers); return true; ?> However, the javascript code is executed with succes but the mail never comes in the mailbox for [email protected]. Does anyone have an idea why this is not working? Kind regards, Ronald Kamp Fixed IT A: Try send without headers if it works you have problem with headers. Use \r\n instead \n.
{ "pile_set_name": "StackExchange" }
Q: Which of the following data duplication options across shards is recommended? High performance mysql book suggests that for sharding a blog application, one may want to put comments data across 2 shards: first, on the shard of a person posting comment, and on the shard where the post is stored. So this raises the question how to reliably duplicate this data. Which of the following data duplication options across shards is recommended? Option 1: Make 2 separate inserts from the PHP script. Pros: a) Logic is in application layer. Cons: a) User is held for 2 inserts. b) This logic will need to be duplicated in every client trying to insert similar data. Conclusion: Seems reasonable. Option 2: Form federated tables and use some trigger to handle the insert of duplicate. Pros: a) App layer doesn't need to worry about multiple inserts Cons: a) Every shard need to have federated connection to every other shard; b) Federation will work on machines in LAN, but what about at 2 different sites. c) what if connection to federated server fails. Conclusion: Doesn't seem like a sound idea. Option 3: Messaging such as RabbitMQ Pros: a) Different clients can insert data at one place, and all subscribers can consume the insert. Cons: a) Complex; b) may impose overhead in order to host messaging server, and clients; c) not sure how will it work with a look-up service to locate appropriate shards Conclusion: Not sure Option 4: your suggestion? I will greatly appreciate your help. A: As you point out, having triggers between the various shards is silly; the whole reason for sharding is independent database operations. So you can throw it out right away. Updating both tables at the same time is the approach with the fewest moving parts. Over the long term, it will be the most maintainable. And it will be the easiest to debug if something goes wrong. But if response time is important, then you might think of some sort of messaging approach: update the comments-by-entry table, and queue a message to update the comments-by-user table. If it takes an hour for that message to be processed -- or if it gets lost in a system crash -- no big deal, you can always recover. By no means should you use a messaging approach to update both tables. Answer by: @kdgregory Link: https://softwareengineering.stackexchange.com/a/134607/41398
{ "pile_set_name": "StackExchange" }
Q: Expand RAID array I'm pretty new to RAID, so please forgive my silly question. I have an Ubuntu Server 12.04 x64 installed on a pc having 4 hdds. During RAID setup I selected RAID10 and (my ignorance) choose 2 active hdds and 2 spare hdds. I'm pretty sure it's not the optimal configuration and probably I should have selected 4 active hdds. Running cat /proc/mdstat I get md1 : active raid10 sdb2[1] sdd2[3](S) sdc2[2](S) sda2[0] 948736 blocks super 1.2 2 near-copies [2/2] [UU] md0 : active raid10 sdb1[1] sdd1[3](S) sdc1[2](S) sda1[0] 311619072 blocks super 1.2 2 near-copies [2/2] [UU] unused devices: <none> Is there a way I can convert spare disks to active disks? I tried using mdadm --grow /dev/md1 --raid-devices=4, but got this answer mdadm: RAID10 can only be changed to RAID0 A: You cannot grow a RAID1+0 (it's not supported by mdadm). From mdadm manpage: Grow (or shrink) an array, or otherwise reshape it in some way. Currently supported growth options including changing the active size of component devices and changing the number of active devices in Linear and RAID levels 0/1/4/5/6, changing the RAID level between 0, 1, 5, and 6, and between 0 and 10, changing the chunk size and layout for RAID 0,4,5,6, as well as adding or removing a write-intent bitmap.
{ "pile_set_name": "StackExchange" }
Q: Using R to plot daily messages per user, given data frame listing all messages Given a data frame representing messages like this: df <- structure(list(message.id = c(123L, 456L), user.id = c(999L, 888L), message.date = structure(c(1310950467, 1311119810), class = c("POSIXct", "POSIXt"), tzone = "")), .Names = c("messageid", "user.id", "message.date"), row.names = c(NA, -2L), class = "data.frame") head(df) message.id user.id message.date 123 999 2011-07-17 17:54:27 456 888 2011-07-19 16:56:50 How would you plot the daily average number of messages per user assuming that some users would have a lot of messages and others very few (e.g. pareto distribution). Thanks. A: Your example is quite small to really work with, so I simulated a larger data frame that should be the same: set.seed(1) start <- strptime("2012-01-01 00:00:00",format="%Y-%m-%d %H:%M:%S") end <- strptime("2012-03-01 00:00:00",format="%Y-%m-%d %H:%M:%S") df <- data.frame( message.id = 1:1000, user.id = sample(1:10,1000,TRUE,prob=1:10), message.date = seq(start,end,length=1000)) Then first we need to extract the dates as dates (instead of POSIXt): df$date <- as.Date(df$message.date) Then I think we can use plyr to compute the average number of messages per user per day as followed: library("plyr") df2 <- ddply(df,.(user.id),summarize,AvPerDay = mean(sapply(seq(min(df$date),max(df$date),by="day"),function(x)sum(date==x)))) The new data frame df2 gives me: user.id AvPerDay 1 1 0.3278689 2 2 0.6229508 3 3 0.9836066 4 4 1.1311475 5 5 1.3442623 6 6 1.8524590 7 7 1.8032787 8 8 2.8032787 9 9 2.5081967 10 10 3.0163934 To plot it you could just make a barplot: barplot(df2$user.id,df2$AvPerDay)
{ "pile_set_name": "StackExchange" }
Q: How to ask a good regex question? What are the qualities of a good, answerable question that involves regular expressions? What information does an asker need to include to be able to receive good answers to regex questions? I often see regex questions where users, who are new to regular expressions and often new to StackOverflow as well, don't provide enough information to properly answer the question. Oftentimes they don't include the language that the regex is to be used in, or there aren't enough examples to properly construct any pattern. I find myself regurgitating the same basic comments on these sorts of questions, which could be perfectly reasonable if the asker would just put a little more effort into crafting them. I'd like to be able to point users to a vetted faq page that cover what information must be provided in the question to receive a good answer, and why the information is necessary. Ideally it would also include simple examples demonstrating why the extra effort makes a difference. A: I believe that a question should state: the language the purpose of the regex (this should help verify the need for regex and whether a different approach may be more suitable) examples of both matching and not maching inputs any code where the regex is to be used (that also helps to verify what's the real requirement and whether regex is the best solution) (if available) any attempts at creating a regex It may be a good idea to create a page with "how to ask" information. One place to create it is the wiki page if the regex tag. Update: I should have checked before answering: the regex tag page already contains a section on asking regex questions. Most of what I mentioned above is already included.
{ "pile_set_name": "StackExchange" }
Q: Relationship Between Hessian and Gradient for Inequality about Convex Functions "Let $f:\mathcal{O} \subset \mathbb{R}^n \to \mathbb{R}$, $f \in C^2(\mathcal{O})$, $\mathcal{O}$ an open convex set. Assume that $D^2f(x)$ is positive semi-definite $\forall x \in \mathcal{O}$. Prove that $f(x) \geq f(a) + \nabla f(a) \cdot (x-a)$, $\forall x \in \mathcal{O}$." I feel like I could probably answer this question if I knew the relationship between $D^2f(a)$, the hessian matrix, and $\nabla f(a)$, the gradient. In other words, I feel like I should apply the positive semi-definiteness of $D^2f(a)$ somehow, but I don't know how to. Any hints? A: Since nobody seemed to care I had to figure it out myself. Here's the answer for anyone who might care in the future. Consider the first degree Taylor approximation of $f$, $P_{1, a}(x) = f(a) + \nabla f(a)(x-a)$. The remainder, $R_{1, a, \theta}$ (for some $\theta \in [0, 1]$), is going to be positive or zero since $D^2f(x)$ is positive semi-definite. Thus we see that, since $f(x) = P_{1, a}(x) + R_{1, a, \theta}(x)$, we do have $f(x) \geq P_{1, a}(a) = f(a) + \nabla f(a)(x-a)$.
{ "pile_set_name": "StackExchange" }
Q: Odd behavior with mongodb find In my DB when I execute db.markers.find() I have this result: { "_id" : ObjectId("518134733198c6952f000000"), "location" : { "type" : "Point", "coordinates" : [ -48.8397216796875, -19.68656825792867 ] }, "m_info" : { "category" : "14", "sub_category" : "156", "description" : "Teste" }, "user_info" : { "email" : "[email protected]", "name" : "John Doe" } } { "_id" : ObjectId("518192d13198c69e3c000000"), "location" : { "type" : "Point", "coordinates" : [ -44.52420382953613, -17.586578222234177 ] }, "marker_info" : { "category" : "9", "sub_category" : "118", "description" : "I'm working with TI." }, "user_info" : { "email" : "[email protected]", "name" : "John Doe2" } } but when I try something like db.markers.find({ user_info : { email : '[email protected]' }}) it returns no results Why is this not working? Thanks, A: This is because you are looking for all documents where user_info object is exactly { email : '[email protected]' } If you want to match a document which happens to have email as '[email protected]" inside of user_info regardless of the rest of the subdocument use the dot notation: db.markers.find({ "user_info.email" : "[email protected] })
{ "pile_set_name": "StackExchange" }
Q: How do I 'get' Lisp? I've read The Nature of Lisp. The only thing I really got out of that was "code is data." But without defining what these terms mean and why they are usually thought to be separate, I gain no insight. My initial reaction to "code is data" is, so what? A: The old fashioned view: 'it' is interactive computation with symbolic expressions. Lisp enables easy representation of all kinds of expressions: english sentence (the man saw the moon) math (2 * x ** 3 + 4 * x ** 2 - 3 * x + 3) rules (<- (likes Kim ?x) (likes ?x Lee) (likes ?x Kim)) and also Lisp itself (mapcar (function sqr) (quote (1 2 3 4 5))) and many many many more. Lisp now allows to write programs that compute with such expressions: (translate (quote (the man saw the moon)) (quote german)) (solve (quote (2 * x ** 3 + 4 * x ** 2 - 3 * x + 3)) (quote (x . 3))) (show-all (quote (<- (likes Kim ?x) (likes ?x Lee) (likes ?x Kim)))) (eval (quote (mapcar (function sqr) (quote (1 2 3 4 5))))) Interactive means that programming is a dialog with Lisp. You enter an expression and Lisp computes the side effects (for example output) and the value. So your programming session is like 'talking' with the Lisp system. You work with it until you get the right answers. What are these expressions? They are sentences in some language. They are part descriptions of turbines. They are theorems describing a floating point engine of an AMD processor. They are computer algebra expressions in physics. They are descriptions of circuits. They are rules in a game. They are descriptions of behavior of actors in games. They are rules in a medical diagnosis system. Lisp allows you to write down facts, rules, formulas as symbolic expressions. It allows you to write programs that work with these expressions. You can compute the value of a formula. But you can equally easy write programs that compute new formulas from formulas (symbolic math: integrate, derive, ...). That was Lisp designed for. As a side effect Lisp programs are represented as such expressions too. Then there is also a Lisp program that evaluates or compiles other Lisp programs. So the very idea of Lisp, the computation with symbolic expressions, has been applied to Lisp itself. Lisp programs are symbolic expressions and the computation is a Lisp expression. Alan Kay (of Smalltalk fame) calls the original definition of Lisp evaluation in Lisp the Maxwell's equations of programming. A: Write Lisp code. The only way to really 'get' Lisp (or any language, for that matter) is to roll up your sleeves and implement some things in it. Like anything else, you can read all you want, but if you want to really get a firm grasp on what's going on, you've got to step outside the theoretical and start working with the practical. A: The way you "get" any language is by trying to write some code in it. About the "data is code" thing, in most languages there is a clear separation between the code that gets executed, and the data that is processed. For example, the following simple C-like function: void foo(int i){ int j; if (i % 42 == 0){ bar(i-2); } for (j = 0; j < i; ++j){ baz(); } } the actual control flow is determined once, statically, while writing the code. The function bar isn't going to change, and the if statement at the beginning of the function isn't going to disappear. This code is not data, it can not be manipulated by the program. All that can be manipulated is the initial value of i. And on the other hand, that value can not be executed the way code can. You can call the function foo, but you can't call the variable i. So i is data, but it is not code. Lisp does not have this distinction. The program code is data that can be manipulated too. Your code can, at runtime, take the function foo, and perhaps add another if statement, perhaps change the condition in the for-loop, perhaps replace the call to baz with another function call. All your code is data that can be inspected and manipulated as simply as the above function can inspect and manipulate the integer i.
{ "pile_set_name": "StackExchange" }
Q: How to disable button with jquery? I've tried everything! $('#m-button').button('disabled') $('#m-button').attr('disabled', 'disabled') $('#m-button').prop('disabled', 'disabled') $('#m-button').attr('disabled', 'true') $('#m-button').prop('disabled', 'true') $('#m-button').attr('enabled', 'false') <button id="m-button" class="btn" type="button" >Add Note</button> It stays enabled though. What's the proper way to disable a <button>? A: $('#m-button').prop('disabled', true) without quotes around true. jsFiddle example Per the jQuery docs on .prop(): Properties generally affect the dynamic state of a DOM element without changing the serialized HTML attribute. Examples include the value property of input elements, the disabled property of inputs and buttons, or the checked property of a checkbox. The .prop() method should be used to set disabled and checked instead of the .attr() method.
{ "pile_set_name": "StackExchange" }
Q: Boost 1.41 LNK1104 error I have been using Boost 1.36 for a while without any problems. Had to upgrade to 1.41 to get PropertyTree. Boost appears to build properly but when i try and compile the project that was using boost 1.36 I get this error. 1>LINK : fatal error LNK1104: cannot open file 'C:\dev\3rdparty\boost-build_1_41_0\boost\bin.v2\libs\filesystem\build\msvc-9.0\debug\link-static\threading-multi.obj' The object file name seems invalid. threading-multi is a directory. I built boost using bootstrap .\bjam and also tried bjam --build-dir=c:\dev\3rdparty\boost-build_1_41_0 --toolset=msvc --threading=multi --without-python --runtime-link=static --buildtype=complete stage both at the Vs2008 command prompt. I have updated references to the correct boost directories in the project. Thanks A: I am relatively sure that this is not a problem with Boost itself. If it were a problem with autolink, you will not see that long path in the linker error message. Can you create a brand new project and see if the problem reproduces? If no, check your project to see if you refer to "bin.v2" anywhere. Remove such references. You should only add the 'stage/lib' directory to additional library paths.
{ "pile_set_name": "StackExchange" }
Q: Mocha test cases throwing Error: expected 200 "OK", got 403 "Forbidden" I am using mochajs for my mean applications server side test cases.The test cases are showing an error, Error: expected 200 "OK", got 403 "Forbidden". I tried using console logs inside the functions that I am trying to test, but they never get executed. I am unable to find out the issue. Can someone help me with this. My controller exports.signin = function(req, res) { req.body.username = new Buffer(req.body.username, base64').toString('ascii'); User.findOne({ username: req.body.username.toLowerCase() }, function(err, user) { if (err) { //do something } else if (!user) { //do something } else { //do something } }); }; My test case it('should be able to signin if the credentials are valid', function(done) { var obj = { username: new Buffer('demo').toString('base64'), password: new Buffer('demouser').toString('base64') }; agent.post('/auth/signin') .send(obj) .expect(200) .end(function(signinErr, res) { if (signinErr){ console.log(signinErr); done(signinErr); } else{ var temp = res.body; console.log(temp); done(); } }); }); And my route app.route('/auth/signin').post(users.signin); A: I was facing the same issue. I found out that we were forcing SSL in our application using the middleware express-force-ssl by app.use(force-ssl). We used a flag to control this behavior. When I made that false, the test cases ran fine. So if you are not controlling it with the flag. Try removing that module and running your test cases.
{ "pile_set_name": "StackExchange" }
Q: javascript to reverse order of values How can I reverse the order of Duck, Donald with Javascript? I am currently retrieving Duck, Donald from a query string and I would like to be able to display it on the page, receiving it as Dondald Duck. I am using document.write("Name: " + Request.QueryString("name")); to write Duck, Donald to the page and I would also like to be able to change 'Mouse', 'Mickey G' to just 'Mickey Mouse'. A: var name = Request.QueryString("name").Item(1).split(",").reverse().join(" ").trim(); if(name.split(" ").length > 2) { name = name.split(" "); name.splice(1, 1); name = name.join(" "); } document.write(name); Example at http://jsfiddle.net/6AdGs/
{ "pile_set_name": "StackExchange" }
Q: When double-clicking on a word, highlight every occurrence of this word in the Aptana 3 text editor Good morning. With Aptana 2, a very useful function was the automatic hightlighting of the selected word : when double-clicking on a variable name, function name, ... (on a word), Aptana 2 automatically highlight this word in the document. Why it was really useful : in the description of a function, when clicking on a variable declaration, if the variable is used, I can immediately see where. With Aptana 3, I've lost this function. No doubt that I can configure the editor but I can't find where. A: It might be a bit late, but I missed that too and I just found out how to activate it: http://www.screencast.com/t/CjZOtMgwe Just needed to click on the highlight (Mark Occurrences) icon on top of the editor.
{ "pile_set_name": "StackExchange" }
Q: Constrained Homogeneous LS Minimization over Time I am new to this forum and would like to ask a question. Let us assume I have a set of matrices $U_{(t)}$ over $t = 1 ... T$ time steps. For each time step I want to find a vector $p_{(t)}$ which satisfies the equation $U_{(t)}p_{(t)}=0$. The solution can easily be found by computing the eigenvector with the smallest eigenvalue. However, I want the adjacent $p_{(t)}$ and $p_{(t-1)}$ to be close to each other for $t>1$, because I know $U_{(t)}$ is subject to little changes over time, $U_{(t)}=U_{(t-1)} + \epsilon$. This amounts to solving $$argmin_{p_{(t)}} ||U_{(t)}p_{(t)}||^2$$ subject to $$||p_{(t)}||^2=1$$ $$||p_{(t-1)}-p_{(t)}||^2=0$$ Reformulating this in Lagrangian form is thus: $$p_{(t)}U_{(t)}^TU_{(t)}p_{(t)} + \lambda(1-p_{(t)}^Tp_{(t)}) + \gamma\bigl((p_{(t-1)}-p_{(t)})^T(p_{(t-1)}-p_{(t)})\bigr)$$ Taking the derivative of the equation $\frac{\partial}{\partial p_{(t)}}$ setting it to zero leads me to: $$2U_{(t)}^TU_{(t)}p_{(t)} - 2\lambda p_{(t)}-2\gamma p_{(t-1)}+2\gamma p_{(t)}$$ Dropping the constants $$U_{(t)}^TU_{(t)}p_{(t)} - \lambda p_{(t)}+\gamma(p_{(t)} - p_{(t-1)}) = 0$$ I've made a slight mistake in the original derivation. However, I'm struggling a bit to solve the problem analytically. Thank you in advance. A: Ok, so I've figured out the question. I am sharing the it with you. My current second side condition is simply $p^T_{(t−1)}p_{(t)}>=0$, which is equivalent to the cosine-similarity equation, as $p$ is unit-length anyways. The solution can then easily be obtained by scipy.optimize.minimize, which can handle inequalities and equalities: https://www.youtube.com/watch?time_continue=490&v=cXHvC_FGx24
{ "pile_set_name": "StackExchange" }
Q: 64-BIT mode do not support PUSH and POP instructions NASM returns an error like: "instruction not supported in 64-bit mode" and I couldn't figure out what to do. The subject instruction is pop ecx and push ecx instructions. What can I use instead of them or is there an other way to fix this issue? A: The general idea is that you normally push and pop full registers, i.e. 64-bit registers in 64-bit mode. push's default operand-size is 64-bit, and 32-bit operand-size is not available. Does each PUSH instruction push a multiple of 8 bytes on x64? (yes, unless you specifically use a 16-bit push, but 32-bit isn't available). You cannot push a 32 bit register in 64 bit mode; instead, you can push and pop the whole 64 bit register that contains a 32-bit value you want, so that's push rax instead of push eax. The same holds for memory references - you can push qword ptr[rax], but not push dword ptr[rax]. But: even in 64 bit mode you can still push: 8 or 32 bit immediates sign extended to 64; this is generally handled automatically by your assembler as an optimization (if you do push 1 it will encode it with the most compact encoding, which will be 6A01, i.e. with an imm8 operand). It's always a 64-bit push unless you explicitly specify push word 1, regardless of what width of immediate the assembler picks. the fs and gs segment registers but not the cs, ds, es, ss registers (which aren't important in 64-bit mode, and can only be read with mov, not push, freeing up those push/pop opcode for potential future use). As an exception, segment registers are either zero-extended or pushed on the stack with a 16-bit move (i.e. the other 48 bit on the stack are left unmodified); this isn't really much of a problem, since pop fs and pop gs just discard these extra bits. You can emulate a push imm64 with push low32 / mov dword [rsp+4], high32. Or with mov r64, imm64 / push r64; mov to register (not memory) is the only x86-64 instruction that can take a 64-bit immediate. With 16-bit operand-size (a 66h prefix), you can do a 16-bit push which adjusts RSP by 2 instead of 8. But normally don't do this because it will misalign the stack until you do a 16-bit pop or otherwise correct it. 16 bit registers (push ax) and memory references (push word ptr[rax]); 8-bit sign-extended or 16 bit immediates. 8-bit registers can't be pushed in any mode (except as part of a wider register), and 32-bit isn't available in 64-bit mode, even with a REX.W=0 prefix.
{ "pile_set_name": "StackExchange" }
Q: Using Fubini's Theorem to find an infinite sum. I need to find the sum $$f\left(x\right)=\sum_{n=0}^\infty \left(\frac{n+1}{2^{n+1}}\right)x^n$$ using Fubini's Theorem. Essentially, I need to figure out how to write my original summation as a double sum instead. I know how to use Fubini's once I have the double sum, but my problem is I do not know what sum to use. I assume I need to rewrite all or part of $\frac{n+1}{2^{n+1}}$ as a sum. Any suggestions? A: Note that \begin{align*} \sum_{n=0}^\infty \left(\frac{n+1}{2^{n+1}}\right)x^n &=\sum_{n=0}^\infty\left(\sum_{i=0}^n \right)\frac{1}{2^{n+1}}x^n\\\tag{1} &=\sum_{i=0}^\infty\frac{1}{2}\sum_{n=i}^\infty\left(\frac{x}{2}\right)^n\\ &=\frac{1}{2-x}\sum_{i=0}^\infty\frac{x^i}{2^i}\\ &=\frac{2}{(2-x)^2} \end{align*} where the interchanging of summation in (1) is justified by noting that the series converges absolutely for $|x|<2$ by using the root test for example.
{ "pile_set_name": "StackExchange" }
Q: Replace multiple try catches with a single global try catch block I am trying to aim for a global try catch exception handler as I have several child class methods that have try catches inside them. So basically I want the parent class method to catch all those exceptions and log it. One of the common ones are SQL exceptions. What is the best approach here to create a common handler which will catch the errors? Here is an example of what is going on in my application public class Parent { public void ParentMethod() { try { var childClass = new Child(); var process = childClass.Process(); if (process) { // Do this } else { // raise new Exception } } catch(Exception ex){ WriteToErrorLogger.Error(ex) } } } public class Child { public bool Process() { try{ // Do something and save to Database } catch (SqlException sqlEx) { // log exception return false; } catch (Exception ex) { // log exception return false; } } } A: What do you mean? What would make sense would be to do the exact opposite public class Parent { public void ParentMethod() { try { var childClass = new Child(); var process = childClass.Process(); if (process) { // Do this } else { // raise new Exception } } catch (SqlException sqlEx) { WriteToErrorLogger.Error(ex); } catch(Exception ex){ WriteToErrorLogger.Error(ex); } } } Child public class Child { public bool Process() { // Do something and save to Database } } If you want to conditionally do it, you could change the child like this public class Child { public bool Process(bool rethrow = false) { try{ // Do something and save to Database } catch (SqlException sqlEx) { if(rethrow) throw; // log exception return false; } catch (Exception ex) { if(rethrow) throw // log exception return false; } } }
{ "pile_set_name": "StackExchange" }
Q: cannot check/uncheck checkbox in javascript/jquery I have a checkbox which will toggle some other check boxes on a html form: <input type="checkbox" name="selector" onclick="toggle_all(this);"/> <script language="javascript"> function toggle_all(source) { var checkboxes = $(":input[name^='form[r']"); if($(source).is(':checked')) { checkboxes.attr('checked', 'checked'); } else { checkboxes.removeAttr('checked'); } alert('done'); } </script> First time I click the "selector" check box, all check boxes with names starting "form[r" will be checked. Then when "selector" check box is unchecked, all others are unchecked as well. Since then checking/unchecking "selector" checkbox doesn't affect other checkboxes. The code is running because alert('done') shows up. What's wrong here? A: I would suggest an improvement. Change HTML, add some class to all your checkboxes: <input class="check" type="checkbox" name="form[r]"> And JS: function toggle_all(source) { $(".check").prop('checked', source.checked); } http://jsfiddle.net/tFv3G/ And the reason why is that searching elements by its attributes much slower than by class name. And less readable as well.
{ "pile_set_name": "StackExchange" }
Q: Same asked a different way this time the StringConverter is acting up Books.java `final class Books extends Group { private TableView table = new TableView(); private ObservableList<Book> data; //private ObservableList<Person> plist; final HBox hb = new HBox(); final TextField Title = new TextField(); final TextField Author = new TextField(); final TextField Publisher = new TextField(); final TextField Copywrite = new TextField(); final TextField ISBN = new TextField(); final Boolean CheckedOut = false; final Label Whom; final Button addButton = new Button("Add"); Boolean FirstRead = true; //StringConverter<Person> converter; public final class Book { private final SimpleStringProperty title; private final SimpleStringProperty author; private final SimpleStringProperty publisher; private final SimpleStringProperty copywrite; private final SimpleStringProperty isbn; private final BooleanProperty checkedout; private final SimpleStringProperty who; Book(String Titl, String Auth, String Publ, String Cpywrit, String IsBn, Boolean ChkdOut, String WHO) { this.title = new SimpleStringProperty(Titl); this.author = new SimpleStringProperty(Auth); this.publisher = new SimpleStringProperty(Publ); this.copywrite = new SimpleStringProperty(Cpywrit); this.isbn = new SimpleStringProperty(IsBn); this.checkedout = new SimpleBooleanProperty(ChkdOut); this.who = new SimpleStringProperty(WHO); } public boolean isCheckedOut() { return checkedout.get(); } public void setCheckedOut(boolean international) { this.checkedout.set(international); } public BooleanProperty isCheckedOutProperty() { return checkedout; } public String getTitle() { return title.get(); } public void setTitle(String Title) { title.set(Title); } public String getAuthor() { return author.get(); } public void setAutor(String Author) { author.set(Author); } public String getPublisher() { return publisher.get(); } public void setPublisher(String Publisher) { publisher.set(Publisher); } public String getCopywrite() { return copywrite.get(); } public void setCopywrite(String Copywrite) { copywrite.set(Copywrite); } public String getIsbn() { return isbn.get(); } public void setIsbn(String ISBN) { isbn.set(ISBN); } public Boolean getIo() { return checkedout.get(); } public void setIo(Boolean CheckedOut) { checkedout.set(CheckedOut); } public String getWho() { return who.get(); } public void setWho(String Who) { who.set(Who); } public String isWhoProperty() { return getWho(); } } public Books(final File User) throws IOException { this.Whom = new Label("inLibrary"); this.data = FXCollections.<Book>observableArrayList( (Book bk) -> new Observable[]{bk.isCheckedOutProperty() }); PhoneList list = new PhoneList(User); final Label label = new Label("Book List"); label.setFont(new Font("Arial", 20)); table.setPrefSize(600, 400); table.setEditable(true); TableColumn nameCol = bookName(); TableColumn authorCol = bookAuthor(); TableColumn publisherCol = bookPublisher(); TableColumn copywriteCol = bookCopywrite(); TableColumn isbnCol = bookISBN(); TableColumn<Book, Boolean> ioCol = ioCol(); ///// START work area final TableColumn whoCol; whoCol = new TableColumn<>("Who to"); whoCol.setMinWidth(100); whoCol.setEditable(true); whoCol.setCellValueFactory( new PropertyValueFactory<Person, String>("who")); whoCol.setCellFactory(ComboBoxTableCell.forTableColumn(list.phonelist)); //////////////////////////////////////////////////////////////////////////////// //whoCol.setCellValueFactory(new PropertyValueFactory<>("who")); //whoCol.setCellFactory(ComboBoxTableCell.<String, Person>forTableColumn(converter, plist)); //whoCol.setCellFactory(ComboBoxTableCell.forTableColumn(list.phonelist)); /* whoCol.setOnEditCommit((TableColumn.CellEditEvent<Book, String> t) -> { ((Book) t.getTableView().getItems().get( t.getTablePosition().getRow())) .setWho(t.getNewValue()); try { writeFile(User); } catch (IOException ex) { Logger.getLogger(Books.class.getName()).log(Level.SEVERE, null, ex); } }); */ //// END work area AddBook(nameCol, authorCol, publisherCol, copywriteCol, isbnCol, ioCol, whoCol, User); data.addListener((javafx.collections.ListChangeListener.Change<? extends Book> change) -> { while (change.next()) { if (change.wasUpdated() && FirstRead != true) { try { System.out.println("List changed"); writeFile(User); } catch (IOException ex) { Logger.getLogger(Books.class.getName()).log(Level.SEVERE, null, ex); } } } }); final VBox vbox = new VBox(); vbox.setSpacing(5); vbox.setPadding(new Insets(10, 0, 0, 10)); vbox.getChildren().addAll(label, table, hb); getChildren().addAll(vbox); try { readFile(User); } catch (Exception ex) { Logger.getLogger(Books.class.getName()).log(Level.SEVERE, null, ex); } } private TableColumn<Book, Boolean> ioCol() { final TableColumn<Book, Boolean> ioCol = new TableColumn<>("In/Out"); ioCol.setMinWidth(50); ioCol.setEditable(true); ioCol.setCellValueFactory(new PropertyValueFactory<>("isCheckedOut")); final Callback<TableColumn<Book, Boolean>, TableCell<Book, Boolean>> iocellFactory = CheckBoxTableCell.forTableColumn(ioCol); ioCol.setCellFactory((TableColumn<Book, Boolean> column) -> { TableCell<Book, Boolean> iocell = iocellFactory.call(column); iocell.setAlignment(Pos.CENTER); return iocell; }); ioCol.setCellFactory(iocellFactory); return ioCol; } private TableColumn bookISBN() { //Column ISBN Number TableColumn isbnCol = new TableColumn("ISBN #"); isbnCol.setMinWidth(100); isbnCol.setCellValueFactory( new PropertyValueFactory<>("isbn")); isbnCol.setCellFactory(TextFieldTableCell.forTableColumn()); return isbnCol; } private TableColumn bookCopywrite() { //Column Copywrite TableColumn copywriteCol = new TableColumn("Copywrite"); copywriteCol.setMinWidth(100); copywriteCol.setCellValueFactory( new PropertyValueFactory<>("copywrite")); copywriteCol.setCellFactory(TextFieldTableCell.forTableColumn()); return copywriteCol; } private TableColumn bookPublisher() { //Column Publisher TableColumn publisherCol = new TableColumn("Publisher"); publisherCol.setMinWidth(100); publisherCol.setCellValueFactory( new PropertyValueFactory<>("publisher")); publisherCol.setCellFactory(TextFieldTableCell.forTableColumn()); return publisherCol; } private TableColumn bookAuthor() { //Column Author TableColumn authorCol = new TableColumn("Author"); authorCol.setMinWidth(100); authorCol.setCellValueFactory( new PropertyValueFactory<>("author")); authorCol.setCellFactory(TextFieldTableCell.forTableColumn()); return authorCol; } private TableColumn bookName() { // Column Name TableColumn nameCol = new TableColumn("Title"); nameCol.setMaxWidth(100); nameCol.setCellValueFactory( new PropertyValueFactory<>("title")); nameCol.setCellFactory(TextFieldTableCell.forTableColumn()); return nameCol; } private void AddBook(TableColumn nameCol, TableColumn authorCol, TableColumn publisherCol, TableColumn copywriteCol, TableColumn isbnCol, TableColumn ioCol, TableColumn whoCol, final File User) { table.setItems(data); table.getColumns().addAll(nameCol, authorCol, publisherCol, copywriteCol, isbnCol, ioCol, whoCol); addButton.setOnAction( new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { addBook(); try { writeFile(User); } catch (IOException ex) { Logger.getLogger(Books.class.getName()).log(Level.SEVERE, null, ex); } } private void addBook() { data.add(new Book( Title.getText(), Author.getText(), Publisher.getText(), Copywrite.getText(), ISBN.getText(), CheckedOut, Whom.getText() )); Title.clear(); Author.clear(); Publisher.clear(); Copywrite.clear(); ISBN.clear(); } }); hb.getChildren().addAll(Title, Author, Publisher, Copywrite, ISBN, addButton); hb.setSpacing(10); Title.setPromptText("Tile of Book"); Title.setMaxWidth(nameCol.getPrefWidth()); Author.setMaxWidth(authorCol.getPrefWidth()); Author.setPromptText("Author"); Publisher.setMaxWidth(publisherCol.getPrefWidth()); Publisher.setPromptText("Publisher"); Copywrite.setMaxWidth(copywriteCol.getPrefWidth()); Copywrite.setPromptText("Year Copywrite"); ISBN.setMaxWidth(isbnCol.getPrefWidth()); ISBN.setPromptText("ISBN #"); } private void writeFile(File User) throws IOException { File file = new File(User + "/Books.txt"); FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); PrintWriter outFile = new PrintWriter(bw); if (table.getItems() != null) { data.stream().map((data1) -> { if (data1.getTitle().equals("")) { data1.setTitle("No_Title"); } return data1; }).map((data1) -> { if (data1.getAuthor().equals("")) { data1.setAutor("No_Author"); } return data1; }).map((data1) -> { if (data1.getPublisher().equals("")) { data1.setPublisher("No_Publisher"); } return data1; }).map((data1) -> { if (data1.getCopywrite().equals("")) { data1.setCopywrite("No_Copywrite"); } return data1; }).map((data1) -> { if (data1.getIsbn().equals("")) { data1.setIsbn("No_ISBN"); } return data1; }).map((data1) -> { if (data1.getWho().equals("")) { data1.setWho("InLibrary"); } return data1; }).map((data1) -> { outFile.println(data1.getTitle()); return data1; }).map((data1) -> { outFile.println(data1.getAuthor()); return data1; }).map((data1) -> { outFile.println(data1.getPublisher()); return data1; }).map((data1) -> { outFile.println(data1.getCopywrite()); return data1; }).map((data1) -> { outFile.println(data1.getIsbn()); return data1; }).map((data1) -> { outFile.println(data1.getIo()); return data1; }).forEach((data1) -> { outFile.println(data1.getWho()); }); outFile.close(); } } private void readFile(File User) throws Exception { try { String name, author, publisher, copywrite, isbn, whom; Boolean InOut; try (Scanner inFile = new Scanner(new File(User + "/Books.txt"))) { while (inFile.hasNextLine()) { name = inFile.next(); author = inFile.next(); publisher = inFile.next(); copywrite = inFile.next(); isbn = inFile.next(); InOut = inFile.nextBoolean(); whom = inFile.next(); data.add(new Book(name, author, publisher, copywrite, isbn, InOut, whom)); } } table.setItems(data); } //insert catch statements catch (FileNotFoundException exception) { System.out.println("File not found"); } catch (ArrayIndexOutOfBoundsException AIOOBexception) { System.out.println("Array Index is out of bounds"); } catch (IllegalArgumentException IAexception) { System.out.println("Divide by zero error"); } catch (NoSuchElementException NAexception) { } FirstRead = false; } }` PhoneList.java `final class PhoneList extends Group { private TableView table = new TableView(); final ObservableList<Person> phonelist = FXCollections.observableArrayList(); final HBox hb = new HBox(); public PhoneList(final File User) { final Label label = new Label("Phone List"); label.setFont(new Font("Arial", 20)); table.setEditable(true); TableColumn firstNameCol = new TableColumn("First Name"); firstNameCol.setMaxWidth(100); firstNameCol.setCellValueFactory( new PropertyValueFactory<>("firstName")); firstNameCol.setCellFactory(TextFieldTableCell.forTableColumn()); firstNameCol.setOnEditCommit( new EventHandler<CellEditEvent<Person, String>>() { @Override public void handle(CellEditEvent<Person, String> t) { try { ((Person) t.getTableView().getItems().get( t.getTablePosition().getRow())).setFirstName(t.getNewValue()); writeFile(User); } catch (IOException ex) { Logger.getLogger(PhoneList.class.getName()).log(Level.SEVERE, null, ex); } } }); TableColumn lastNameCol = new TableColumn("Last Name"); lastNameCol.setMinWidth(100); lastNameCol.setCellValueFactory( new PropertyValueFactory<>("lastName")); lastNameCol.setCellFactory(TextFieldTableCell.forTableColumn()); lastNameCol.setOnEditCommit( new EventHandler<CellEditEvent<Person, String>>() { @Override public void handle(CellEditEvent<Person, String> t) { try { ((Person) t.getTableView().getItems().get( t.getTablePosition().getRow())).setLastName(t.getNewValue()); writeFile(User); } catch (IOException ex) { Logger.getLogger(PhoneList.class.getName()).log(Level.SEVERE, null, ex); } } }); TableColumn phoneNumCol = new TableColumn("Phone Number"); phoneNumCol.setMinWidth(100); phoneNumCol.setCellValueFactory( new PropertyValueFactory<>("phoneNum")); phoneNumCol.setCellFactory(TextFieldTableCell.forTableColumn()); phoneNumCol.setOnEditCommit( new EventHandler<CellEditEvent<Person, String>>() { @Override public void handle(CellEditEvent<Person, String> t) { try { ((Person) t.getTableView().getItems().get( t.getTablePosition().getRow())).setPhoneNum(t.getNewValue()); writeFile(User); } catch (IOException ex) { Logger.getLogger(PhoneList.class.getName()).log(Level.SEVERE, null, ex); } } }); TableColumn emailCol = new TableColumn("Email"); emailCol.setMinWidth(120); emailCol.setCellValueFactory( new PropertyValueFactory<>("email")); emailCol.setCellFactory(TextFieldTableCell.forTableColumn()); emailCol.setOnEditCommit( new EventHandler<CellEditEvent<Person, String>>() { @Override public void handle(CellEditEvent<Person, String> t) { try { ((Person) t.getTableView().getItems().get( t.getTablePosition().getRow())).setEmail(t.getNewValue()); writeFile(User); } catch (IOException ex) { Logger.getLogger(PhoneList.class.getName()).log(Level.SEVERE, null, ex); } } }); table.setItems(phonelist); table.getColumns().addAll(firstNameCol, lastNameCol, phoneNumCol, emailCol); final TextField addFirstName = new TextField(); addFirstName.setPromptText("First Name"); addFirstName.setMaxWidth(firstNameCol.getPrefWidth()); final TextField addLastName = new TextField(); addLastName.setMaxWidth(lastNameCol.getPrefWidth()); addLastName.setPromptText("Last Name"); final TextField addPhoneNum = new TextField(); addPhoneNum.setMaxWidth(lastNameCol.getPrefWidth()); addPhoneNum.setPromptText("Phone Number"); final TextField addEmail = new TextField(); //addEmail.setMaxWidth(emailCol.getPrefWidth()); addEmail.setPrefWidth(175); addEmail.setPromptText("Email"); final Button addButton = new Button("Add"); addButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { try { phonelist.add(new Person( addFirstName.getText(), addLastName.getText(), addPhoneNum.getText(), addEmail.getText())); addFirstName.clear(); addLastName.clear(); addPhoneNum.clear(); addEmail.clear(); writeFile(User); } catch (IOException ex) { Logger.getLogger(PhoneList.class.getName()).log(Level.SEVERE, null, ex); } } }); hb.getChildren().addAll(addFirstName, addLastName, addPhoneNum, addEmail, addButton); hb.setSpacing(3); final VBox vbox = new VBox(); vbox.setSpacing(5); vbox.setPadding(new Insets(10, 0, 0, 10)); vbox.getChildren().addAll(label, table, hb); getChildren().addAll(vbox); try { readFile(User); } catch (Exception ex) { Logger.getLogger(PhoneList.class.getName()).log(Level.SEVERE, null, ex); } } private void readFile(File User) throws Exception { try { String fN, lN, pNum, eMail; try (Scanner inFile = new Scanner(new File(User + "/PhoneList.txt"))) { while (inFile.hasNextLine()) { fN = inFile.next(); lN = inFile.next(); pNum = inFile.next(); eMail = inFile.next(); phonelist.add(new Person(fN, lN, pNum, eMail)); } } table.setItems(phonelist); } //insert catch statements catch (FileNotFoundException exception) { System.out.println("File not found"); } catch (ArrayIndexOutOfBoundsException AIOOBexception) { System.out.println("Array Index is out of bounds"); } catch (IllegalArgumentException IAexception) { System.out.println("Divide by zero error"); } catch (NoSuchElementException NAexception) { } } public void writeFile(File User) throws IOException { File file = new File(User + "/PhoneList.txt"); FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); PrintWriter outFile = new PrintWriter(bw); if (table.getItems() != null) { for (int i = 0; i < phonelist.size(); i++) { outFile.println(phonelist.get(i).getFirstName()); outFile.println(phonelist.get(i).getLastName()); if (phonelist.get(i).getPhoneNum().equals("")) { phonelist.get(i).setPhoneNum("No_Phone"); } if (phonelist.get(i).getEmail().equals("")) { phonelist.get(i).setEmail("No_Email"); } outFile.println(phonelist.get(i).getPhoneNum()); outFile.println(phonelist.get(i).getEmail()); } outFile.close(); } } public static class Person { private final SimpleStringProperty firstName; private final SimpleStringProperty lastName; private final SimpleStringProperty phoneNum; private final SimpleStringProperty eMail; Person(String fName, String lName, String pNum, String email) { this.firstName = new SimpleStringProperty(fName); this.lastName = new SimpleStringProperty(lName); this.phoneNum = new SimpleStringProperty(pNum); this.eMail = new SimpleStringProperty(email); } public String getFirstName() { return firstName.get(); } public void setFirstName(String fName) { firstName.set(fName); } public String getLastName() { return lastName.get(); } public void setLastName(String lName) { lastName.set(lName); } public String getPhoneNum() { return phoneNum.get(); } public void setPhoneNum(String pNum) { phoneNum.set(pNum); } public String getEmail() { return eMail.get(); } public void setEmail(String email) { eMail.set(email); } public String getName() { String Name = getFirstName() + "_" + getLastName(); return Name; } public Observable isWhoProperty() { return firstName; } @Override public String toString() { String Name = getFirstName() + "_" + getLastName(); return Name; } } class EditingCell extends TableCell<Person, String> { private TextField textField; public EditingCell() { } @Override public void startEdit() { if (!isEmpty()) { super.startEdit(); createTextField(); setText(null); setGraphic(textField); textField.selectAll(); } } @Override public void cancelEdit() { super.cancelEdit(); setText((String) getItem()); setGraphic(null); } @Override public void updateItem(String item, boolean empty) { super.updateItem(item, empty); if (empty) { setText(null); setGraphic(null); } else { if (isEditing()) { if (textField != null) { textField.setText(getString()); } setText(null); setGraphic(textField); } else { setText(getString()); setGraphic(null); } } } private void createTextField() { textField = new TextField(getString()); textField.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2); textField.focusedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> arg0, Boolean arg1, Boolean arg2) { if (!arg2) { commitEdit(textField.getText()); } } }); } private String getString() { return getItem() == null ? "" : getItem(); } } }` With these two I do have the ComboBoxTableCell working properly... Thank you very much. Now its time to figure out how to save it to the .txt file. Hmm can't think of anything more to say - make sure that you also get MykeZ folder and its contents. but this version has all it needs to work so you can add new data if necessary. `final TableColumn<Book, Person> whoCol; whoCol = new TableColumn<>("Who to"); whoCol.setMinWidth(100); whoCol.setEditable(true); whoCol.setCellValueFactory(new PropertyValueFactory("who")); whoCol.setCellFactory(ComboBoxTableCell.forTableColumn(list.phonelist)); whoCol.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<Book, Person>>() { public void handle(TableColumn.CellEditEvent<Book, Person> evt) { try { evt.getRowValue().setWho(evt.getNewValue().getName()); writeFile(User); } catch (IOException ex) { Logger.getLogger(Books.class.getName()).log(Level.SEVERE, null, ex); } } });` And were finished Please give your self credit in this postings for the answer, am very happy thank you your the best A: I don't really understand the question, but you should be doing something like this. edit: from looking briefly at your code you might be trying to do something like this; import javafx.application.Application; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.SimpleStringProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.scene.Scene; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.cell.ComboBoxTableCell; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.layout.StackPane; import javafx.stage.Stage; import javafx.util.StringConverter; public class ComboBoxTable extends Application { @Override public void start(Stage stage) { ObservableList<Person> persons = FXCollections.observableArrayList(); persons.addAll(new Person("Jack"),new Person("Jill"),new Person("John")); ObservableList<Book> books = FXCollections.observableArrayList(); for (int i=1;i<5;i++)books.add(new Book(i*100,new Person("wrong guy"))); StringConverter<Person> cvrt = new StringConverter<Person>(){ @Override public String toString(Person person) { return person.getName(); } @Override public Person fromString(String string) { return null; } }; TableView<Book> tv = new TableView(books); tv.setEditable(true); tv.getSelectionModel().setCellSelectionEnabled(true); TableColumn<Book, Integer> numCol = new TableColumn("Book Num"); numCol.setCellValueFactory(new PropertyValueFactory("num")); TableColumn<Book, Person> nameCol = new TableColumn("Name"); nameCol.setCellValueFactory(new PropertyValueFactory("person")); nameCol.setCellFactory(ComboBoxTableCell.<Book, Person>forTableColumn(cvrt,persons)); tv.getColumns().addAll(numCol, nameCol); StackPane root = new StackPane(tv); Scene scene = new Scene(root, 300, 250); stage.setScene(scene); stage.show(); } public class Person{ SimpleStringProperty name; public Person(String name) { this.name = new SimpleStringProperty(name); } public SimpleStringProperty nameProperty() { return name; } public String getName() { return name.get(); } //in simple cases you can just do this and not use a string converter @Override public String toString(){ return name.get(); } } public class Book{ SimpleIntegerProperty num; SimpleObjectProperty<Person> person; public Book(int num, Person person) { this.num = new SimpleIntegerProperty(num); this.person = new SimpleObjectProperty<>(person); } public SimpleIntegerProperty numProperty() { return num; } public SimpleObjectProperty<Person> personProperty() { return person; } } } Look at the TableView, TableColumn, and ComboBoxTableCell documentation and pay attention to the <S,T> The reason you're getting a reference to Person is because the ComboBox doesn't know how to convert it to a string. I put a simple bit of code to override the toString() method for the Person class. If you don't specify a StringConverter it won't know how to convert and just uses toString() for objects. Edit again: Look at your Book class, you have StringProperty who and you're trying to store a person in that field. Look at my code and I use an ObjectProperty<Person>. You can do it your way but override the toString() in the Person class like in my example and don't use a StringConverter. @Override public String toString(){ return name.get(); } Then make your TableColumn like this and use the type <Book, Person> TableColumn<Book, Person> whoCol = new TableColumn<>("Who to"); whoCol.setMinWidth(100); //editable is true for columns by default. whoCol.setCellValueFactory(new PropertyValueFactory("who")); whoCol.setCellFactory(ComboBoxTableCell.forTableColumn(p.phonelist)); whoCol.setOnEditCommit((evt) -> { evt.getRowValue().setWho(evt.getNewValue().getName()); }); I made an onEditCommit so the Book class will know how to store the Person info.
{ "pile_set_name": "StackExchange" }
Q: Multiple IF statement; Months I know this might be a really stupid question and I know I should import a class for this, but I would really like to know what is the mistake in the following code. I am taking Java class and I would really like to get some help. int m = 1; String month; if(int m = 1){ month = "January"; }else if(int m = 2){ month = "February"; }else if(int m = 3){ month = "March"; }else if(int m = 4){ month = "April"; }else if(int m = 5){ month = "May"; }else if(int m = 6){ month = "June"; }else if(int m = 7){ month = "July"; }else if(int m = 8){ month = "August"; }else if(int m = 9){ month = "September"; }else if(int m = 10){ month = "October"; }else if(int m = 11){ month = "November"; }else if(int m = 12){ month = "December"; } I keep getting *./Root/Main.java:16: error: '.class' expected if(int m = 1){ ^* Is the problem with the string name? A: Your if statement is re-defining the variable m. The comparison should read as follows: if (m == 1). The corrected code would be: int m = 1; String month; if(m == 1){ month = "January"; }else if(m == 2){ month = "February"; }else if(m == 3){ month = "March"; }else if(m == 4){ month = "April"; }else if(m == 5){ month = "May"; }else if(m == 6){ month = "June"; }else if(m == 7){ month = "July"; }else if(m == 8){ month = "August"; }else if(m == 9){ month = "September"; }else if(m == 10){ month = "October"; }else if(m == 11){ month = "November"; }else if(m == 12){ month = "December"; }
{ "pile_set_name": "StackExchange" }
Q: Is there a way to check if Ektron is loading a page in Edit mode in my codebehind? (C#) I have a page that prompts the user for a password in order to display the content. However, when Ektron users are editing the page content, I want it to just show the content without asking for the password. The password functionality is all set in the codebehind; the password in the metadata for the page tells the code to hide the usercontrols that show the content (ux.Visible = false) and display the usercontrol that asks for a password. What I'd like to do is check at this point to see whether Ektron is currently in Edit mode, and if so, set ux.Visible = true. Is there a way to check for this? A: I found this on the Ektron developer center. [Works with 8.7] if (_host != null) // make sure widget is being used inside a PageBuilder page { var p = this.Page as PageBuilder; // get PageBuilder object if (p.Status == Mode.Editing) // check for Editing mode { ux.Visible = true //Display UX } }
{ "pile_set_name": "StackExchange" }
Q: Google Maps via Link with Region I'm currently working on a site that I want to link "Get Directions" button to Google Maps (without using the JS API). It is very important that the Sea of Japan is labeled as East Sea. This is achievable in the Google Maps JS API by setting "?region=KO" when fetching the API JS Script. Using the example link below, is their a query string I can append to set the region as Korea. Otherwise is there another method I can use to set the region to Korea but keep the language in English. Example of link: https://maps.google.com/?saddr=Current+Location&daddr=Brisbane+Australia&zoom=14&directionsmode=driving Sea Of Japan Naming Issues: http://en.wikipedia.org/wiki/Sea_of_Japan_naming_dispute Thanks, Zac A: Using the Korean domain google.co.kr to set the region then setting the language ?hl=en appears to give you the "East Sea" yet retain English street terminology. East Sea https://www.google.co.kr/maps/@39.6573449,135.6637105,7z?hl=en Sea of Japan https://www.google.com/maps/@39.6573449,135.6637105,7z Korean Labels https://www.google.co.kr/maps/@-27.4789154,153.0226005,14z English Labels https://www.google.co.kr/maps/@-27.4789154,153.0226005,14z?hl=en
{ "pile_set_name": "StackExchange" }
Q: Draw poly line on the road in mkmap view - iphone i am making an navigation based application. In this application i am drawing a route from points selected by the user. for Calculating the route i have used Google direction API. and for drawing the route i have used this code - (void) drawRoute:(NSArray *) path { NSInteger numberOfSteps = path.count; [self.objMapView removeOverlays: self.objMapView.overlays]; CLLocationCoordinate2D coordinates[numberOfSteps]; for (NSInteger index = 0; index < numberOfSteps; index++) { CLLocation *location = [path objectAtIndex:index]; CLLocationCoordinate2D coordinate = location.coordinate; coordinates[index] = coordinate; } for( id <MKOverlay> ovr in [self.objMapView overlays]) { MKPolylineView *polylineView = [[MKPolylineView alloc] initWithPolyline:ovr]; if (polylineView.tag == 22) { [self.objMapView removeOverlay:ovr]; } [polylineView release]; } MKPolyline *polyLine = [MKPolyline polylineWithCoordinates:coordinates count:numberOfSteps]; [self.objMapView addOverlay:polyLine]; } PROBLEM :~ When i am drawing a route i encountered a problem that it is not drawing polyline on the road. To explain this i have attached an image as shown in the picture polyline is not on the road. I have used UICGDirections but it is not working properly some times. Please help me i am new to mapview. Thanks in advance A: Below is a sample IPhone application demonstrates drawing routes on MKMapView using http://maps.google.com/maps?output=dragdir&saddr=%@&daddr=%@ as URL MapWithRoutes You can take this as a reference as it has implemented the same thing what you are trying to achieve.
{ "pile_set_name": "StackExchange" }
Q: Web page aligning badly on Internet Explore i have an app that will only be viewed on internet explorer,the page contents are positioned well in other browser on the center but in IE everything aligns to the left.I kindly need help here is my css <head> <meta charset="UTF-8"> <title>SCOPE ACADEMY | HOME</title> <link rel="stylesheet" type="text/css" href="css/style.css" /> <style> /* NOTE: The styles were added inline because Prefixfree needs access to styles and they must be inlined if they are on local disk! */ @import url("http://fonts.googleapis.com/css?family=Open+Sans:400,600,700"); @import url("http://netdna.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.css"); *, *:before, *:after { margin: 0; padding: 0; box-sizing: border-box; } html, body { height: 100%; } body { font: 14px/1 'Open Sans', sans-serif; color: #555; background: #fff; } h1 { padding: 50px 0; font-weight: 400; text-align: center; } p { margin: 0 0 20px; line-height: 1.5; } main { min-width: 320px; max-width: 800px; padding: 50px; margin: 0 auto; background: #fff; } section { display: none; padding: 20px 0 0; border-top: 1px solid #ddd; } input { display: none; } label { display: inline-block; margin: 0 0 -1px; padding: 15px 25px; font-weight: 600; text-align: center; color: #bbb; border: 1px solid transparent; } label:before { font-family: fontawesome; font-weight: normal; margin-right: 10px; } label[for*='1']:before { content: '\f015'; } label[for*='2']:before { content: '\f07c'; } label[for*='3']:before { content: '\f0d6'; } label[for*='4']:before { content: '\f085'; } label[for*='5']:before { content: '\f109'; } label:hover { color: #0066cc; cursor: pointer; } input:checked + label { color: #0066cc; border: 1px solid #ddd; border-top: 2px solid orange; border-bottom: 1px solid #fff; } #tab1:checked ~ #content1, #tab2:checked ~ #content2, #tab3:checked ~ #content3, #tab4:checked ~ #content4, #tab5:checked ~ #content5 { display: block; } @media screen and (max-width: 650px) { label { font-size: 0; } label:before { margin: 0; font-size: 18px; } } @media screen and (max-width: 400px) { label { padding: 15px; } } /*img { position: absolute; top: 0; bottom:1200; left: 0; right:0; margin: auto; }*/ span.centerImage { text-align: center; } /*.footer { position: absolute; right: 0; bottom: 0; left: 0; padding: 1rem; background-color: #efefef; text-align: center; } */ /* IE 6 */ * html .footer { position:absolute; top:expression((0-(footer.offsetHeight)+(document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight)+(ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop))+'px'); } /*inline accordion css styles*/ </style> <script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script> </head> Thanks in advance A: Just add display:block property for main tag main { min-width: 320px; max-width: 800px; padding: 50px; margin: 0 auto; background: #fff; display:block; }
{ "pile_set_name": "StackExchange" }
Q: R language: Unexpected behaviour with function arguments in lapply I am attempting to create a list of matrices containing iid Normal numbers. For the sake of a simple example, let the matrices be 4 by 2 and consider a list of length 3. The following code seemed like it should work (to me): MyMatrix <- lapply(1:3, function() {matrix(rnorm(8), 4, 2)}) But it failed, with the following error: Error in FUN(1:3[[1L]], ...) : unused argument (1:3[[1]]) On a whim, I tried: MyMatrix <- lapply(1:3, function(x) {matrix(rnorm(8), 4, 2)}) And it worked! But why? x is not used anywhere in the function, and on experimentation, the behaviour of the expression is not affected by whether x already exists in the workspace or not. It appears to be entirely superfluous. I am new to R, so I would be very grateful if an experienced user could explain what is going on here and why my first line fails. A: You can't have a function that doesn't take arguments and then pass it arguments. Which is exactly what you are doing when you run lapply, as each value is passed in turn as the first argument to the function. E.g. out <- lapply(1:3, function(x) x) str(out) #List of 3 # $ : int 1 # $ : int 2 # $ : int 3 Simple example throwing an error: test <- function() {"woot"} test() #[1] "woot" test(1) #Error in test(1) : unused argument (1) lapply(1:3, test) #Error in FUN(1:3[[1L]], ...) : unused argument (1:3[[1]]) It's good form for R to error out, as it likely means you're expecting the function's returned result to change based on the arguments passed to the function. And it wouldn't. There are functions like this included in base R, like Sys.time(), which will fail if you try to pass it superfluous arguments which might otherwise make sense: Sys.time() #[1] "2014-07-07 13:22:11 EST" Sys.time(tz="UTC") #Error in Sys.time(tz = "UTC") : unused argument (tz = "UTC")
{ "pile_set_name": "StackExchange" }
Q: During the iOS review process, does Apple use production or development APS notification certificates for testing? I'm using a third party service and I need to know which p12 file to upload to their servers -- development or distribution? My app relies heavily on push notifications. A: When you upload your application for submission to the app store, it should be a production-ready version. Thus it should include your production push certificates.
{ "pile_set_name": "StackExchange" }
Q: Multiple coding keys for a single data in Codable The API I am using supports multi-language. For instance: // For Japanese { "earthquake_detail": { "advisory_title_ja": "津波注意報", "depth_title_ja": "震源深さ", "depth_value_ja": "30km", } } // For English { "earthquake_detail": { "advisory_title_en": "Tsunami Advisory", "depth_title_en": "Depth", "depth_value_en": "30km", } } I am using swift codable to map them to a struct. Is there a way that I can map multiple coding keys to a single variable? Here is my swift struct. struct EarthquakeDetail: Codable { var advisoryTitle, depthTitle, depthValue: String? enum CodingKeys: String, CodingKey { case advisoryTitle = "advisory_title_ja" case depthTitle = "depth_title_ja" case depthValue = "depth_value_ja" } } What I want to obtain is for Japanese this will be the coding keys: enum CodingKeys: String, CodingKey { case advisoryTitle = "advisory_title_ja" case depthTitle = "depth_title_ja" case depthValue = "depth_value_ja" } and for English: enum CodingKeys: String, CodingKey { case advisoryTitle = "advisory_title_en" case depthTitle = "depth_title_en" case depthValue = "depth_value_en" } A: If you are not going to use the convertFromSnakeCase strategy add a custom key decoding strategy which drops the _xx from the three coding keys. let decoder = JSONDecoder() decoder.keyDecodingStrategy = .custom { codingKeys in let lastKey = codingKeys.last! if lastKey.intValue != nil || codingKeys.count != 2 { return lastKey } if codingKeys.dropLast().last!.stringValue != "earthquake_detail" { return lastKey } return AnyCodingKey(stringValue: String(lastKey.stringValue.dropLast(3)))! } If the earthquake_detail key is deeper than on level 2 change != 2 accordingly To be able to create custom coding keys you need struct AnyCodingKey: CodingKey { var stringValue: String var intValue: Int? init?(stringValue: String) { self.stringValue = stringValue } init?(intValue: Int) { self.stringValue = String(intValue) self.intValue = intValue } } Now declare EarthquakeDetail as follows struct EarthquakeDetail: Codable { var advisoryTitle, depthTitle, depthValue: String enum CodingKeys: String, CodingKey { case advisoryTitle = "advisory_title" case depthTitle = "depth_title" case depthValue = "depth_value" } }
{ "pile_set_name": "StackExchange" }
Q: Windows workflow 4.5 - Send notifications at regular intervals I am having an approval workflow. The client is asp.net mvc 4 and the client calls out to a WEB API. This WEB API in turn hosts the WF using WorkflowAplication class. The scenario here is, if a request is not approved for a certain time, i need the persisted workflow to load send an email and persist again. Is this scenario possible somehow using WF 4.5 A: Make a timer object outside of the workflows but trigger it from within the workflow (Pass it into the workflow as an Argument). Then when the timer fires you can use the event to restart the workflow from a persist point, send the e-mail and then persist again.
{ "pile_set_name": "StackExchange" }
Q: New line printing I am trying to print my answer on two lines. I tried with \n , but It was not working and I could not find exact match of my case so that I can see how exactly it has to be done. Here is my code that should be printed. I used two print functions: print ("X1 = " + "%.2f"%x1) print ("X2 = " + "%.2f"%x2) However, I would like to do it only with one print function and \n? I tried so far with the following format of \n function: print 'First line \n Second line' However, as I supposed, this is not working. I am Python beginner and I know how to get to the final outcome, but I want to learn some new things and not just use the print function couple of times. Thanks in advance! A: print ("X1 = " + "%.2f"%x1 + "\n" + "X2 = " + "%.2f"%x2) Just concat the two string you want to print with a \n <- new line EDIT: 1. more efficient way to do the same thing: print("X1 = %.2f\nX2 = %.2f"%(x1,x2)) Using format(): print("X1 = {0:.2f}\nX2 = {1:.2f}f".format(x1,x2)) Using format strings: print(f"X1 = {x1:.2f}\nX2 = {x2:.2f}")
{ "pile_set_name": "StackExchange" }
Q: Grunt task: Dynamic source folders & dynamic ouput folders dependant on source location My project has "Scripts" folder which has a lot of sub-folder full of javascript files. At the moment I am integrating babel as a grunt task. All files which needs to be transpiled has names "*.babel.js", so in my watch object I have such task: babel: { files: 'Content/styles/**/*.babel.js', tasks: [ 'babel' ] }, My babel task options object is: "babel": { options: { sourceMap: true }, dist: { files: { "dist/app.js": "src/app.js" } } } Please pay attention to bold part. Is it possible to select all files with name "*.babel.js" and put the compiled files with the same folder as source ones? What I'm trying to do here is avoiding to define each of the *.babel.js to the config object as there are plenty of files and there will be plenty more... + all my files are in different levels of the Scripts sub folders. Is this possible? A: Solved it, babel object: { options: { sourceMap: true }, dist: { files: [ { "expand": true, "cwd": "Scripts/", "src": ["**/*.babel.js"], "dest": "Scripts/", "ext": ".js" } ] } } This compiles script file to the same folder where source file exists.
{ "pile_set_name": "StackExchange" }
Q: Create a binary wall Given an array of positive integers in base 10, where n > 0, output their representation of a binary wall. How does this work? Convert each number to it's binary representation. Pad the representation with leading zeroes to the length of the longest one i.e. 1, 2 -> 1, 10 -> 01, 10. Create a wall where the 1s are bricks and 0s are missing bricks. A wall is a block of characters where any printable character represents a brick and a space (32) represents a missing brick. You may choose any character for the brick, it need not be distinct across the wall as long as it isn't a white space character. The missing brick character must be a space. For the example below I have used * for the bricks. Example Input: [ 15, 7, 13, 11 ] [ 1111, 111, 1101, 1011 ] [ 1111, 0111, 1101, 1011 ] Output: **** *** ** * * ** Rules Input must be taken in base 10, if your language accepts other bases you may not use them. Leading and trailing new lines are allowed. Input may be taken as a list of integers, separate arguments or any reasonable format. Output may be in any reasonable format: new line separated string, array of lines, 2d array etc. Standard loopholes are disallowed. Test Cases Note that in the first test case all of layers have an empty brick at the end. [ 14, 4, 6, 2 ] *** * ** * [ 1, 2, 4, 8, 16 ] * * * * * [ 15, 11, 15, 15 ] **** * ** **** **** [ 11, 10, 9, 8 ] * ** * * * * * This is code golf so shortest code wins! A: MATL, 5 bytes B42*c Try it online! Explanation B % Implicitly input an array of numbers. Convert to binary. % Gives a matrix with each row corresponding to a number 42 % Push 42 (ASCII code of '*') * % Multiply c % Convert to char. Char 0 is displayed as space. Implicitly display A: J, 8 bytes ' *'{~#: Try it online! Explanation ' *'{~#: Input: array of integers #: Convert each to binary with left-padding ' *'{~ Use the digits to index into the string ' *' A: Jelly, 9 bytes Bo⁶Uz⁶ZUY Try it online! EDIT: HOW J BEAT JELLY DAT IMPOSSIBLE >_<
{ "pile_set_name": "StackExchange" }
Q: JQuery UI onSelect Not Firing I have been racking my brain trying to figure this one out. I have looked all over stackOverflow and Google, and nothing seems to be working for me. I have an inline JQuery UI datepicker and want an alert box to pop up when the user selects a date. My code is: HMTL: <div id="datePicker1"></div> JavaScript: <script type="text/javascript"> $("#datePicker1").datepicker(); $("#datePicker1").datepicker({ onSelect: function(dateText, inst){ alert('hi'); } }); </script> The calendar shows up, but when I select any date, nothing happens. I would love to know why. Any help is appreciated. Thanks. A: Options are initialized the first time you call datePicker() on an element. If you want to change the options later, you have to use the option method: $(function() { $("#datePicker1").datepicker(); $("#datePicker1").datepicker("option", { onSelect: function(dateText, inst) { alert('hi'); } }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script> <input id="datePicker1">
{ "pile_set_name": "StackExchange" }
Q: In R, how to parse specific frame within a webpage? Greetings all, Is there a way to only read the HTML code from a specific frame within a webpage? For example, if I submit a url to google translate, is there a way to parse only the translated page frame? Whenever I try, I can only access the top frame on the page but not the translated frame. Here is my self-contained sample code: library(XML) url <- "http://www.baidu.com/s?wd=r+project" url.google.translate <- URLencode(paste("http://translate.google.com/translate?js=y&prev=_t&hl=en&ie=UTF-8&layout=1&eotf=1&sl=zh-CN&tl=en&u=", url, sep="")) htmlTreeParse(url.google.translate, useInternalNodes = FALSE) The above code refers to this url: $file [1] "http://translate.google.com/translate?js=y&prev=_t&hl=en&ie=UTF-8&layout=1&eotf=1&sl=zh-CN&tl=en&u=http://www.baidu.com/s?wd=r+project" The output however only access the top frame of the page and not the main frame, which is what I am interested in. Hope that made sense and thanks in advance for any help. Tony UPDATE - Thanks to the answer from @kwantam below (accepted), I was able to use it to get my solution as follows (self-contained): > # Load R packages > library(RCurl) > library(XML) > > # STAGE 1 - find forward url in relevent frame > ( url <- "http://www.baidu.com/s?wd=r+project" ) [1] "http://www.baidu.com/s?wd=r+project" > gt.url <- URLencode(paste("http://translate.google.com/translate?js=y&prev=_t&hl=en&ie=UTF-8&layout=1&eotf=1&sl=zh-CN&tl=en&u=", url, sep="")) > gt.doc <- getURL(gt.url) > gt.html <- htmlTreeParse(gt.doc, useInternalNodes = TRUE, error=function(...){}) > nodes <- getNodeSet(gt.html, '//frameset//frame[@name="c"]') > gt.parameters <- sapply(nodes, function(x) x <- xmlAttrs(x)[[1]]) > gt.url <- paste("http://translate.google.com", gt.parameters, sep = "") > > # STAGE 2 - find forward url to translated page > doc <- getURL(gt.url, followlocation = TRUE) > html <- htmlTreeParse(doc, useInternalNodes = TRUE, error=function(...){}) > url.trans <- capture.output(getNodeSet(html, '//meta[@http-equiv="refresh"]')[[1]]) > url.trans <- strsplit(url.trans, "URL=", fixed = TRUE)[[1]][2] > url.trans <- gsub("\"/>", "", url.trans, fixed = TRUE) > url.trans <- xmlValue(getNodeSet(htmlParse(url.trans, asText = TRUE), "//p")[[1]]) > > # STAGE 3 - load translated page > url.trans [1] "http://translate.googleusercontent.com/translate_c?hl=en&ie=UTF-8&sl=zh-CN&tl=en&u=http://www.baidu.com/s%3Fwd%3Dr%2520project&prev=_t&rurl=translate.google.com&usg=ALkJrhiCMu1mKv-czCmEaB7PO925TJCa-A " > #getURL(url.trans) If anyone knows of a simpler solution to what I've given above then please feel free to let me know! :) A: Most of the following answer is for the particular case of google translate. In most cases, you'll just need to parse the <frameset> and pull out whichever frame you're looking for, though it might not be immediately obvious which is the main one from the HTML (perhaps look at the relative sizing of the frames). It looks like you're going to have to follow a few refreshes to get the actual content. In particular, when you grab the URL you just mentioned, you'll see something like *snip* <noframes> <script> <!--document.location="/translate_p?hl=en&amp;ie=UTF-8&amp;sl=zh-CN&amp;tl=en&amp;u=http://www.baidu.com/s%3Fwd%3Dr%2520project&amp;prev=_t&amp;usg=asdf";--> </script> <a href="/translate_p?hl=en&amp;ie=UTF-8&amp;sl=zh-CN&amp;tl=en&amp;u=http://www.baidu.com/s%3Fwd%3Dr%2520project&amp;prev=_t&amp;usg=asdf">Translate </a> </noframes> *snip* If you follow the link here (remember to unescape '&' first), it'll give you another small HTML fragment which includes <meta http-equiv="refresh" content="0;URL=http://translate.googleusercontent.com/translate_c?hl=en&amp;ie=UTF-8&amp;sl=zh-CN&amp;tl=en&amp;u=http://www.baidu.com/s%3Fwd%3Dr%2520project&amp;prev=_t&amp;rurl=translate.google.com&amp;usg=asdf"> Again, unescaping the '&' and then following the refresh, you'll have the translated page that you're looking for. Play with this in wget or curl and it should become more clear what you're going to need to do.
{ "pile_set_name": "StackExchange" }
Q: How do I make a MySQL infinite array table? I am using this code to create an infinite table for my mysql queries: <table cellspacing='0'> <!-- cellspacing='0' is important, must stay --> <!-- Table Header --> <thead> <tr> <th>User</th> <th>SteamID</th> <th>Banned by</th> <th>Admin SteamID</th> <th>Time Banned (min)</th> <th>Reason</th> </tr> </thead> <!-- Table Header --> <!-- Table Body --> <tbody> <?php echo '<tr>'; for($i = 0; $bans = mysqli_fetch_array($query2); $i = ($i+1)%3){ echo '<td>'.$bans['name'].'</td>'; echo '<td>'.$bans['steamid'].'</td>'; echo '<td>'.$bans['nameAdmin'].'</td>'; echo '<td>'.$bans['steamidAdmin'].'</td>'; echo '<td>'.$bans['time'].'</td>'; echo '<td>'.$bans['reason'].'</td>'; if($i == 2) echo '</tr><tr>'; } echo '</tr>'; ?> </tbody> I got that code from Mysql fetch array, table results It works fine, except it doesn't CORRECTLY go further down than 6 rows. The other rows for whatever reason are placed to the right of my last column as shown in this screenshot: http://puu.sh/h0qZF/a12de1dd87.png How can I fix this? Is there something wrong with my code? Why is it happening? A: Well, your looping makes no sense. Using $i to inject new rows, like is done here, is not necessary; you can just loop over each row and then output it as a row: <table> <!-- <thead>...</thead> --> <tbody> <?php while ($bans = mysqli_fetch_array($query2)): ?> <tr> <td><?php echo $bans['name'] ?></td> <td><?php echo $bans['steamid'] ?></td> <td><?php echo $bans['nameAdmin'] ?></td> <td><?php echo $bans['steamidAdmin'] ?></td> <td><?php echo $bans['time'] ?></td> <td><?php echo $bans['reason'] ?></td> </tr> <?php endwhile ?> </tbody> </table>
{ "pile_set_name": "StackExchange" }
Q: HTML5 input type range show range value I am making a website where I want to use range slider(I know it only supports webkit browsers). I have integrated it fully and works fine. But I would like to use a textbox to show the current slide value. I mean if initially the slider is at value 5, so in text box it should show as 5, when I slide the value in text box should change. Can I do this using only CSS or html. I want to avoid JQuery. Is it possible? A: For those who are still searching for a solution without a separate javascript code. There is little easy solution without writing a javascript or jquery function: <form name="registrationForm"> <input type="range" name="ageInputName" id="ageInputId" value="24" min="1" max="100" oninput="ageOutputId.value = ageInputId.value"> <output name="ageOutputName" id="ageOutputId">24</output> </form> JsFiddle Demo If you want to show the value in text box, simply change output to input. Update: It is still Javascript written within your html, you can replace the bindings with below JS code: document.registrationForm.ageInputId.oninput = function(){ document.registrationForm.ageOutputId.value = document.registrationForm.ageInputId.value; } Either use element's Id or name, both are supported in morden browsers. A: This uses javascript, not jquery directly. It might help get you started. function updateTextInput(val) { document.getElementById('textInput').value=val; } <input type="range" name="rangeInput" min="0" max="100" onchange="updateTextInput(this.value);"> <input type="text" id="textInput" value=""> A: version with editable input: <form> <input type="range" name="amountRange" min="0" max="20" value="0" oninput="this.form.amountInput.value=this.value" /> <input type="number" name="amountInput" min="0" max="20" value="0" oninput="this.form.amountRange.value=this.value" /> </form> http://jsfiddle.net/Xjxe6/
{ "pile_set_name": "StackExchange" }
Q: requery db & rxjava observableResult calls subsequent function multiple times On android I am using requery db and trying to upload my DB changes to server. To achieve the same, I am running the following logic Scheduler sub2 = Schedulers.newThread(); Scheduler ob2 = Schedulers.newThread(); data.select(Broadcaster.class) .where(Broadcaster.IS_DIRTY.eq(true)) .get() .observableResult() .subscribeOn(sub2) .observeOn(ob2) .flatMap(broadcasters->broadcasters.observable()) .flatMap(broadcasters->Backend.getInstance() .uploadBroadcaster(broadcasters) .onExceptionResumeNext(Observable.empty())) .flatMapSingle(broadcaster -> markUploaded(broadcaster)) .doOnError(t->Log.e(TAG,"Error uploading ",t)) .subscribe(); But for every change the uploadBroadcaster is called multiple times (4-10 times) with the same data. What am I doing wrong here. A: Mistake was mine. This block of code was called multiple times. so the subscription happened multiple times.
{ "pile_set_name": "StackExchange" }
Q: Radiation by a transparent body We know that the rate of radiation is proportional to the surface area offthe emitting body. However, this is true for an opaque body. When considering a transparent body, will the radiation still be proportional to the surface area? Or, will it be proportional to the volume of the body which seems more likely to me? (I am assuming that the material is ideally transparent to all wavelengths) Also, taking it a bit further say if a (transparent) sphere having sphereicaly symmetric temperature distribution maintained constantly by some hypothetical arrangement how should the amount of radiation emitted be calculated? A: A perfectly transparent sphere will not emit any electromagnetic radiation (this could happen if we consider a blob of cold dark matter, for example). However, there are cases like optically thin plasmas where radiation is released and each photon unlikely to be captured by another particle before it escapes. In particular, there is thermal Bremsstrahlung where free electrons and ions in a plasma will radiate energy like $P_{br} \propto n_e n_i \sqrt{T}$ where $n_e,n_i$ is the number density of electrons and ions. The total emissions will be proportional to the volume rather than the surface area as long as the density is low enough that there is not too much self-absorption; as density increases the spectrum becomes more blackbody-like. If the sphere is maintained at constant temperature the best way of estimating the radiation is to measure how much energy is being put into the sphere per unit of time to maintain the disequilibrium. In more realistic cases like astrophysicists looking at intergalactic plasmas they use the shape of the spectrum to estimate parameters like temperature and density and then estimate the total power from that.
{ "pile_set_name": "StackExchange" }
Q: LTRIM function in C I am trying to write a left trim function in C. Could someone please find out what is the mistake I am doing int main() { char string2[]=" wind"; ltrim(string2); int new_len2=strlen(string2); printf("After trim String2 is <%s>\nLength is %d\n",string2,new_len2); return 0; } void ltrim(char *string) { int i=0; while(string[i]==' ') { i++; string=string+i; } printf("inside function string is <%s>---length is %d\n",string,strlen(string)); } output: inside function string is <wind>---length is 4 After trim String2 is < wind> Length is 7 Why the string is not changing in the main function after trimming. A: Minimalistic solution without using <string.h> void ltrim(char *src) { char *dst; /* find position of first non-space character */ for (dst=src; *src == ' '; src++) {;} /* nothing to do */ if (dst==src) return; /* K&R style strcpy() */ while ((*dst++ = *src++)) {;} return; }
{ "pile_set_name": "StackExchange" }
Q: neighborlist.getCid() returns -1 as value always I have used the following code, TelephonyManager telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE); List<NeighboringCellInfo> neighboringCellInfoList = telephonyManager.getNeighboringCellInfo(); if (neighboringCellInfoList == null || neighboringCellInfoList.size() == 0) { /*Toast.makeText(this, "List Empty", Toast.LENGTH_SHORT).show();*/ Log.e(TAG, "List Empty"); } else { TowerAdapter towerAdapter = new TowerAdapter(MainActivity.this, neighboringCellInfoList); recyclerView.setAdapter(towerAdapter); } } And my bind view holder in adapter is @Override public void onBindViewHolder(@NonNull TowerViewHolder towerViewHolder, int i) { String cid = String.valueOf(cellInfoList.get(i).getCid()); String signal = String.valueOf(cellInfoList.get(i).getRssi()); towerViewHolder.cid.setText(cid); towerViewHolder.signal.setText(signal); } But always I am getting '-1' as CID value. what might me the problem? output screenshot here A: Might just be the correct result instead of a problem. For NeighboringCellInfo the method getCid() returns the value of UNKNOWN_CID if the network type is UMTS, CDMA, or Unknown. The value of UNKNOWN_CID is -1.
{ "pile_set_name": "StackExchange" }
Q: Use Salesforce Sites page in an iFrame on external site I have a requirement to allow web-to-case form to upload attachments. Now, as per the docs there are two possible ways to do so: Implement Visualforce pages in Force.com Sites. Using Force.com web services API implementation. I opted for the former solution, i.e. VF page in Force.com Sites. All is working fine, but I have to use that page in 5 different client sites. So, I proposed, to use the VF page inside an iFrame, so the branding of the site would override the VF page with the header and footer, etc. I tried that myself first on Blogger to see if the idea works as I hoped it would! (see below) Workarounds available at my disposal: Create 5 different VF pages with specific styling related to each site brand and then share each VF page with specific team. Problem: any change in requirements or fields would need to me change every VF page. Question Is there a way to display my Force.com Site VF page on external site with their branding? A: I was able to display my site's page on external in an iFrame by following method goto Site settings from setup set the "Clickjack Protection Level" to "Allow framing by any page (no protection)" press "Save" Review "Load denied by X-Frame-Options: URL does not permit framing.' error message" for more details.
{ "pile_set_name": "StackExchange" }
Q: Disable href and execute function I have this code: <a href="link.cshtml"> <div>...</div> <div class="function">...</div> <div>....</div> </a> I would like disable href on div with class function and call a function when I click on this div. I have tried with onclick="return false; testFunction();" but obviously it doesn't work. Can someone help me? Thanks in advance A: You should use the preventDefault to make sure the browser will not run the default href. If you return - nothing will run after that... function testFunction() { alert('hi'); } document.querySelector('.function').addEventListener('click', function() { event.preventDefault(); testFunction(); }); <a href="https://www.yahoo.com"> <div>...</div> <div class="function">Click here will not change page</div> <div>....</div> </a>
{ "pile_set_name": "StackExchange" }
Q: Browse files inside a Hyper-V snapshot If it possible to browse the inside of a snapshot file for a specific file? It is not possible for us to merge this particular snapshot file so we are looking for an alternative to recover a specific file inside it. How can one open a snapshot file and navigate inside it? A: Is the snapshot corrupt? If not, why not just take a snapshot of your current environment, and apply the one you want to look at, then re-apply your current one? A: Make copies of all the .AVHD and .VHD files associated with your VM in some other location. Then use Disk Manager to mount the (copy of the) .AVHD file associated with your snapshot. This requires Server 2008 R2. The .AVHD files won't show up by default in the user interface, but it can still mount them. Then browse the file system looking for whatever you like. Don't try to mount them without copying them, though, or you'll (at best) corrupt your snapshot chain. Even mounting an NTFS volume changes it.
{ "pile_set_name": "StackExchange" }
Q: how to enable TLS and https requests for a website using node.js and express.js? I'm doing one of my first projects of web programming using node.js (using express.js) as back and react as front. Some requests to my node server need to be secure like post requests for sending login and register data. what should i do? is there any library for node or react to help me? and which parts of my project should i change? A: I see two ways: Enable https at node express level. Use some tutorial like this https://medium.com/@nileshsingh/everything-about-creating-an-https-server-using-node-js-2fc5c48a8d4e Or put node server behind nginx reverse proxy. This way actually is easier for beginner. Simple nginx configuration + certbot and it is done. Certbot is a tool that will provide you free certificates and integrate them into your nginx configuration - https://certbot.eff.org/
{ "pile_set_name": "StackExchange" }
Q: Should I use Singleton registrations in Simple Injector? In my registry, I'm registering a lot of things as Singleton. I'm doing this because they're all thread safe and have no state. Therefore, one instance in memory is fine. I'm also using AsyncScoped lifestyles for types that need context/state, but they are few and far-between compared to the amount of singleton registrations that I have. Is there anything wrong with registering thread safe, stateless types as singleton? A: This is actually a hard question to answer. There are two general DI Composition Models you can apply to construct dependency graphs: Closure Composition Model Ambient Composition Model Both models have their pros and cons, but it is only when you apply the Ambient Composition Model holistically that you're able to register your components as Singleton. I started blogging about these two models here.
{ "pile_set_name": "StackExchange" }
Q: laravel api package does not recognize my previous routes i have a project that already has some api working and now i wanna use dingo on it to version my apis now i just did all the documentation said and yet i get this error in below : { message: "The version given was unknown or has no registered routes.", status_code: 400, here is a part of my api.php route $api->version('v1', function (Router $api) { $api->group(['prefix' => 'v1'], function(Router $api) { $api->group(['middleware' => 'bindings'], function(Router $api) { /************************************************* * * Accommodation Api Crud * **************************************************/ $api->get('accommodationbooking', 'App\\Api\\V1\\Controllers\\AccommodationBookingController@index'); Any one With similar problem ??? A: when you make new routes for you app you have to cache them again the problem was i didnt know that caching routes and api routes are different so i ran : php artisan api:cache because it clears cache first and cache again after that it will recognize your routes
{ "pile_set_name": "StackExchange" }