text
stringlengths
64
81.1k
meta
dict
Q: Weird behavior if() with false statement evaluates to true C# In few words: an if statement evaluating a statement as false is executing the code inside that if statement. I have proofs: Step 1 My code executes a constructor to create a new instance of irrelevant name class. The constructors receives an string with CSV format as parameter. Then the string is split by ',' and if the number of items in the resulting array is less than x an exception should be thrown Step 2: even when the statement is false the exception is thrown! Step 3 After crying and weeping for a while, I copy the exactly same amount of code a few lines below. Surprise! The code behaves as expected! The images are self explanatory. There is no trick. I am really astonished. I can work around this simply by having that code in the place where it behaves as expected. But in my opinion the output of a block of code must be independent of its position in a file! A: After all the answer was hidden in a comment by @Eric Lippert Are you compiling release or debug? The position of the current line when debugging the release build is sometimes wrong. Is the exception actually thrown? The exception was not thrown really. Although I was debugging the debug build the fact is that the current line entered the if even when the condition statement was false, although the line did not execute. When debugging I interpreted that that line was next to be executed. Curiously when removing the try catch block below then the debugging line step over. I am really embarrassed with you guys but the fact is that I was so used to be debugging and to consider the highlighted line to be the next to be executed that well... Nevertheless I would appreciate if someone could explain why this happens.
{ "pile_set_name": "StackExchange" }
Q: Do I need to wrap Trace.TraceError inside a try/catch? I am using System.Diagnostics.Trace#TraceError inside a try/catch to trace errors. By looking at the implementation of TraceError, it looks like errors from listeners are not really caught. Does it mean that I should write code like below to avoid errors from logging propagating to the caller: catch (Exception e) { try { Trace.TraceError(e); } catch { // Do nothing } } A: Trace.TraceError is not documented to throw exceptions, so no need to catch it. Even though if it is documented to throw exceptions you should never catch an exception and do nothing. Let the exception raise, only then you'll have a chance to find what's wrong. See Why is try {...} finally {...} good; try {...} catch{} bad?
{ "pile_set_name": "StackExchange" }
Q: How would I go about packaging an mp3 file into an mp4 container? So here's the issue that I'm currently having. I need an audio player for iOS that will play mp3. Now at first glance this may seem like a trivial issue, just create an audio tag and give it the URL to the mp3 file. While this technically works, it's basically unusable since iOS needs to download the entire file before starting to play it. This results in a really long wait time when trying to play large mp3 files (could get close to a minute). So the first thing I tried was to manually mimic the chunking that chrome does for playing mp3 files. I first sent a HEAD request to get the byte length of the audio file. Used that length / duration in seconds to get the average bytes per second and use that data to request chunks based on where the user seeks to. That didn't work since sometimes mp3 files contain metadata that throw off the calculation (like a cover image). Additionally, sometimes mp3 files use VBR (Variable Bit Rate) and then I'm well and truly screwed. So this lead me to thinking, Safari couldn't possibly require the end user to download an entire mp4 file before playing it. So I took an mp3 file, converted it to mp4 on an online converter and tested my theory out. Voila, it worked. Safari was streaming the mp4 file in chunks and the wait time went to close to 0. Alright, so now all I need to do is convert mp3 files to mp4 files. The problem now is, I have requirement not to use my server for converting these files. I want to offload this expensive operation to the client. After looking around for a bit I found a few wasm libraries to do this, great! Nope. These wasm libraries are huge (24 MB) and would add an unacceptable amount to my already large bundles files. So this brings me to my question. Is there any way to "trick" safari into thinking that my mp3 file is mp4. What I've tried already: On input change event -> get the file -> clone it into a new Blob with a mimeType of video/mp4 and then upload that file to the server. Chrome plays this file no problem (probably because it detects it's an mp3 file), on Safari however it's unable to play the file. So my question is, is there any way to package the mp3 file in an mp4 container (Client Side !important) to "force" Safari into chunking the file. A: Is there any way to "trick" safari into thinking that my mp3 file is mp4 mp4 files are not seekable because the client "thinks" they are mp4. They have an index in the file that is required for the seeking to work. That index does not magically exist because the mime type was changed. is there any way to package the mp3 file in an mp4 container (Client Side... Yes, totally. But you must write the code and it is very complicated. You can read ISO 14496-12 document to understand how mp4 files are structured. and ISO 11172-3 and ISO 13818-3 to parse the Mp3 into frames that can be written to the MP4
{ "pile_set_name": "StackExchange" }
Q: How to compile and run a JSP Beans project using Eclipse I am a noob trying to learn what I can about JSPs. I am using Eclipse as my ide and have run into a small problem that I hope someone can help me out with. I have a dynamic web project with the following files: index.html <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Get Name</title> </head> <body> <form action="saveName.jsp" method="post"> What is your name? <input type="text" name="username" size="20"> <br> What is your email address? <input type="text" name="email" size="20"> <br> What is your age? <input type="text" name="age" size="4"> <br> <input type="submit"> </form> </body> </html> nextPage.jsp <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <jsp:useBean id="user" class="user.UserData" scope="session"></jsp:useBean> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Next Page</title> </head> <body> You entered <br> Name: <%=user.getUserName()%> <br> Email: <%=user.getUserEmail()%> <br> Age: <%=user.getUserAge()%> </body> </html> saveName.jsp <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <jsp:useBean id="user" class="user.UserData" scope="session"></jsp:useBean> <jsp:setProperty property="*" name="user" /> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Save Name</title> </head> <body> <a href="nextPage.jsp">Continue</a> </body> </html> userData.java package user; public class UserData { String userName; String userEmail; String userAge; /** * @return the userName */ public String getUserName() { return userName; } /** * @param userName * the userName to set */ public void setUserName(String userName) { this.userName = userName; } /** * @return the userEmail */ public String getUserEmail() { return userEmail; } /** * @param userEmail * the userEmail to set */ public void setUserEmail(String userEmail) { this.userEmail = userEmail; } /** * @return the userAge */ public String getUserAge() { return userAge; } /** * @param userAge * the userAge to set */ public void setUserAge(String userAge) { this.userAge = userAge; } } This app runs just fine except that my nextPage.jsp has null for all of the values. I know this is is because the userData.java is not being called. Here is how the project is set up the html and jsp files are in the WebContent folder. userData.java is in the Java Resources folder under the user package. I am pretty sure the class for userData is supposed to be copied into the WEB-INF folder but it is not and even if I place it there myself the project still does not run right. Can someone show me how to set this up in Eclipse so that it will run correctly and I can experiment more with JSPs. A: The problem is the difference between you input name and the setter of UserData, please try to modify the index.html as: <form action="saveName.jsp" method="post"> What is your name? <input type="text" name="userName" size="20"> <br> What is your email address? <input type="text" name="userEmail" size="20"> <br> What is your age? <input type="text" name="userAge" size="4"> <br> <input type="submit"> </form> I have test it OK. Wish it helps.
{ "pile_set_name": "StackExchange" }
Q: Regex match of a string with numbers and uppercase letters failing I am trying to match lasko17A565 in the list below but the regex fails?specifically I am trying to look for the string present in variable train in the front followed by any combination of numbers and uppercase letters, can anyone provide guidance why it fails? import re xbsfindupdates_output_list = ['project-707.1.5 was found in the following updates of lasko:', '\tlasko17A565', '\tNewestlasko', '\tBuiltlasko'] train = 'lasko' found_new_SDK = False for SDK in xbsfindupdates_output_list: if re.match(r'%s[0-9A-Z]'%train,SDK): found_new_SDK = True print found_new_SDK CURRENT OUTPUT:- False EXPECTED OUTPUT:- True A: I suspect that the error is in how you are building the regex pattern to be used here. I suggest concatenating the input list together by space to form a single input string, and then using the following regex pattern with re.findall: \b(lasko[A-Z0-9]+)\b The word boundaries are appropriate here, because the train value should be bounded on the left by a tab, and on the right by a space. xbsfindupdates_output_list = ['project-707.1.5 was found in the following updates of lasko:', '\tlasko17A565', '\tNewestlasko', '\tBuiltlasko'] train = 'lasko' inp = ' '.join(xbsfindupdates_output_list) pattern = r'\b(' + train + r'[A-Z0-9]+)\b' matches = re.findall(pattern, inp) print(matches) This prints: ['lasko17A565'] Edit: If you just want to find out if there is a match, then try: xbsfindupdates_output_list = ['project-707.1.5 was found in the following updates of lasko:', '\tlasko17A565', '\tNewestlasko', '\tBuiltlasko'] train = 'lasko' inp = ' '.join(xbsfindupdates_output_list) pattern = r'\b' + train + r'[A-Z0-9]+\b' if re.search(pattern, inp): print("MATCH") else: print("NO MATCH")
{ "pile_set_name": "StackExchange" }
Q: Spring HTML URL View Not Found I have a simple question. In a Spring Boot Application I have a controller that works fine: @GetMapping("/mycats") public String getCats(){ return "cats.html"; } cats.html is a html file in resources/static/ When I change the action URL like this @GetMapping("/mycats/my") public String getCats(){ return "cats.html"; } Spring cannot find the html file anymore. I have tried many directory combinations and still no success. I don't use thymeleaf/jsp. Why is that happening? A: This is due to the context. When you use "mycats" it will look for the page in static directory. but when you use "mycats/my" it will look for the page in the static/my directory. This directory does not exists, so you get a 404 error. You can make a little change to you controller. You can command it that look for in the previos directory with "../", but you always have to be only on directory deep. @GetMapping("/mycats/my") public String getCats(){ return "../cats.html"; } Or from any directory, you can tell spring that looks at root directory with "/" @GetMapping("/mycats/my") public String getCats(){ return "/cats.html"; }
{ "pile_set_name": "StackExchange" }
Q: jquery count the elements by class and set the another class a certain element in the list How with jQuery/Javascript count the elements by class and set another class a certain element in the list. It is possible? An example, i have four elements with the class "qa" and change or add class "qa2" second element in list. A: Using jquery var el = $('.cls'); alert(el.length); // Will alert length To add a class to the 2nd element $(el[1]).addClass('classOne'); // first item is 0 and second item is 1 and so on Inside a loop to add class to 2nd element using condition. el.each(function(i){ if(i==1) // If 2nd item then add the class $(el[i]).addClass('newClass'); });​ Or this will add 'newClass' class to all elements that has class 'cls' $('.cls').addClass('newClass')​; OR this will add different classes to odd and even items in the list/matched items ​$('.cls').each(function(i){ if(!(i%2)) $(this).addClass('odd'); else $(this).addClass('even'); });​
{ "pile_set_name": "StackExchange" }
Q: Consecutively copy two lines and skip the third using awk With fairly simply awk: awk '(NR%3)' awk.write for this file: this line 1 no un1x this lines 22 0 butbutbut this 33 22 has unix but not 1 THIS is not butbutbut ffff second line I have output as: this line 1 no un1x this lines 22 0 but not 1 THIS is not second line But the last line is not wanted since it doesn't qualify the definition of consecutive. How can I the get the first two of every three consecutive lines? A: You can use a variable to track if the previous line is present or not: $ awk ' FNR % 3 == 1 {f = $0; next} # The first line keep in f, skip to next line FNR % 3 && f {print f;print} # Previous line present, print it and current line ' <file this line 1 no un1x this lines 22 0 but not 1 THIS is not Or with sed: sed -ne 'N;/\n/p;N;d' <file
{ "pile_set_name": "StackExchange" }
Q: Weird Gap Between Views in React Native I am new to react naive and am trying to place two views one under the other but when I try doing this there is a big gap between the views as shown below. This anyway to be able to fix this or do I need to use flatlist? Here is my code. render() { return ( <> <View style={{ flex: 1, flexDirection: "row", height: 130 }}> <View style={styles.IconImage}> <TouchableOpacity onPress={() => Linking.openURL("http://facebook.com/") } > <FontAwesome name="location-arrow" size={40} color={"#E8AA65"} /> </TouchableOpacity> </View> <View style={{ paddingTop: 50, paddingLeft: 40 }}> <Text style={{ fontSize: 20 }}>Find Us</Text> </View> </View> <View style={{ flexDirection: "row", height: 130 }}> <View style={styles.IconImage}> <TouchableOpacity onPress={() => Linking.openURL("http://facebook.com/") } > <Icon name={Platform.OS === "ios" ? "ios-settings" : "md-settings"} size={40} color={"#E8AA65"} /> </TouchableOpacity> </View> <View style={{ paddingTop: 50, paddingLeft: 40 }}> <Text style={{ fontSize: 20 }}>Settings</Text> </View> </View> </> ); } const styles = StyleSheet.create({ IconImage: { paddingTop: 40, paddingLeft: 40, }, }); A: The issue is caused by providing flex:1 in your main view. Output without flex:1: The remaining offset is caused by your height together with your padding values. Demo: I've created a snack where you can play around with it: https://snack.expo.io/rkUKpLUUU
{ "pile_set_name": "StackExchange" }
Q: Combinatorics. Please explain me how to do it. In how many different ways three persons A, B, C having 6, 7 and 8 one rupee coins respectively can donate Rs.10 collectively? This isn't a homework question. Please explain me the steps. Thank you! A: Let $a,b,c$ be the amounts that $A,B$ and $C$ give resp. Then we want to count the number of distinct solutions to $a + b + c = 10$ under the condition that $a,b,c$ are positive integers and $a \le 6, b \le 7, c \le 8$. One way to compute this is to compute the coefficient of $x^{10}$ in the expression $(1+x+\ldots +x^6)(1+x+\ldots +x^7)(1+x+\ldots +x^8)$ ($a$ is the exponent we choose in the first term, $b$ in the second etc., so the fact that we go up to $x^6$ in the first term expresses the $a \le 6$ and so on.) We can write these terms as $\frac{1-x^7}{1-x}$, $\frac{1-x^8}{1-x}$ and $\frac{1-x^9}{1-x}$, respectively, so this product equals $$(1-x^7)(1-x^8)(1-x^9)(1-x)^{-3}$$ and then we can use the general Newton formula to compute the coefficient of $x^{10}$ (we expand $(1-x)^{-3}$ using that, and then count the (not too many) ways the first terms give rise to a power of $x$ that is $\le 10$). Expanded: the general binomial implies $$(1-x)^{-3} = \sum_{n=0}^{\infty} \binom{k+2}{2} x^k$$ e.g. see here, and now note that we can form $x^{10}$ by picking 1's in the first 3 terms and the coefficient of $x^{10}$ in this expansion, so $\binom{12}{2}$, and also by picking $-x^7$,1,1 and $\binom{5}{3}$ (term for $x^3$), $1,-x^8,1$ and the $x^2$ term and finally $1,1,-x^9$ and the term for $x^1$ in the infinite expansion. So we get $$\binom{12}{2} - \binom{5}{3} - \binom{4}{2} - \binom{3}{1} = 47$$
{ "pile_set_name": "StackExchange" }
Q: PHP Form index undefined and variable undefined been doing a simple search, but I have come in to a problem. I get an error of index undefined and variable undefined on my _POST request! I can't really find the mistake, could anyone help me? The project is done on 3 different files by the way. HTML: <form action="ajax/queries.php" method="POST" class="searchbox sbx-google"> <div role="search" class="sbx-google__wrapper"> <input type="text" name="search" placeholder="Įveskite paieškos terminus" autocomplete="off" required="required" class="sbx-google__input"> <button type="submit" title="Submit your search query." class="sbx-google__submit"> <svg role="img" aria-label="Search"> <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#sbx-icon-search-13"></use> </svg> </button> <button type="reset" title="Clear the search query." class="sbx-google__reset"> <svg role="img" aria-label="Reset"> <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#sbx-icon-clear-3"></use> </svg> </button> </div> </form> <script type="text/javascript"> document.querySelector('.searchbox [type="reset"]').addEventListener('click', function() { this.parentNode.querySelector('input').focus();}); </script> PHP before editing, I get index undefined error, though on queries.php page, I can see the contents of search, though it still shows off as an error and doens't supply it to the processing script: global $query; // $query = htmlspecialchars($_POST['search']); PHP after editing, I get variable undefined error: //Query if (!isset($_POST)) { if (!isset($_POST["search"])){ $query = htmlspecialchars($_POST['search']); } } EDIT: adding some more code: https://pastebin.com/XcKPvWvb queries.php https://pastebin.com/v7cL6Jw5 paieska.php (query doesn't get supplied to it) pastebin dot com slash jh5wLPLR index.php (html) A: On your form, you gave the name="search" for the form, input field, and also for the button which made an confusion Updated Html I changed method from GET to POST, also changed the name of form,and the search button <form action="ajax/queries.php" method="POST" name="search_form" class="searchbox sbx-google"> <div role="search" class="sbx-google__wrapper"> <input type="text" name="search" placeholder="Įveskite paieškos terminus" autocomplete="off" required="required" class="sbx-google__input"> <button type="submit" title="Submit your search query." name="search_button" class="sbx-google__submit"> <svg role="img" aria-label="Search"> <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#sbx-icon-search-13"></use> </svg> </button> Just a small mistake.. on each if(isset.. conditions you had used ! (not) Operator Updated PHP code if (isset($_POST['search_button'])) { if (isset($_POST["search"])){ $query = htmlspecialchars($_POST['search']); } }
{ "pile_set_name": "StackExchange" }
Q: preventing anyone from accessing back server pages I searched for the answer for my question but I couldn't find exactly what I wanted. If you find a duplicate of this please send me it! I have a couple of files in my website that are used to do background functions that I don't want anyone to access them- not even the admin. for example files like PHPMailer.php, login-inc.php logout-inc.php and more. I need a way to prevent anyone from accessing those pages and not prevent them from working when triggered by buttons/forms. I'm aware that using a session can redirect not logged users, although, here, I need to prevent everyone from accessing the pages by redirecting them or sending them to a 404 page. what do I need to use to do that? thanks! Update: I'm very new to web coding so sorry for the confusing question, I wanted to block users from entering some pages by entering their location with a link for example I don't want users to be able to access tokens/passwords... Using .htaccess solves my problem. thank you. A: One way to protect your files to be called by web server is to move them out of site webroot directory. That way there is no way that someone access the with web browser and you still can include them. It's common solution. Other way is to intercept web server requests and i.e. forbid some of them, redirect some others and so on. I.e for Apache web server you can do that inside .htaccess file. You have to allow that in website settings. For your specific case, with those buttons: You'll have to use .htaccess (or equivalent) to intercept all requests to those files. Then redirect those request to some php script, with also saving passed parameters. Then your PHP script should decide what to do with that request...reject it (redirect to 404 page) or allow access. For that your buttons, should pass some kind of pass code. So your PHP script can check, when it's called if valid pass code is provided (allow access) or not (redirect to 404). Now making that pass code that can't be manipulated could be tricky, but generally you must invent some formula to generate them (based i.e. on current time) so PHP script could you the same formula to check it's validity. Other way is to i.e. to do some JS action when button is pressed (i..e write some cookie) and PHP script will check for that JS action result (cookie exists or not).
{ "pile_set_name": "StackExchange" }
Q: Battery backup for small IoT devices? I'm making a number of small devices such as temperature sensors, RF433 transmitter and receiver (for controlling and receiving devices => MQTT) mostly using EPS8266. They work fine, and are USB powered because it's simple and works. They probably all use too much power to run off batteries but it would be nice if I could incorporate perhaps a small rechargable battery so that my temperature sensor for example could continue to work for a day or two if unplugged. I could make something, but does anyone know of anything very cheap that is a plug in solution for this kind of thing. Small and cheap are essential. A: You can hook up a USB battery pack to both the Pi and the charger (as long as it is designed to charge while being used) and if the power goes out the USB battery pack will take over powering the Pi directly. Search for "USB UPS" and you will find tons of info on individual setups. A: If possible choose a device that has a built in battery. A few such examples that use the common 2-pin JST connector. The first two are based off of the esp8266 WioLink WioNode C.H.I.P ($9 computer) Raspberry Pi Zero + battery module A: You can switch over from main power to battery backup using a couple of diodes, for example like this. I did something similar with a 15 V transformer and a 12 V car battery: as long as the mains power is on, the diode to the battery is reverse-biased, and no current flows from the battery into the circuit. When the main power fails, the cut-over to the battery is automatic.
{ "pile_set_name": "StackExchange" }
Q: Error in Reading CSV Files The Download Method will read the CSV-File, which is in the lnkReportFile.NavigateUrl Element, and bring a "Save" Window to choose the directory. The problem is it reads all the data till the end. But then it additionally reads the current ASPX page as well. So when I save the .CSV File and open it, i can see the html at the end of the file. Could anyone please help solving this problem? Private Sub btnCreateReport(....) Handles .. Try 'Logic comes here..' 'At the end ' Link setzen und anzeigen lnkReportFile.NavigateUrl = strPathToNavigate lnkReportFile.Visible = True Catch ex As Exception Finally ' Datei schliessen über den StreamWriter If Not writer Is Nothing Then ' es kann sein, das der StreamWriter nicht initialisiert wurde writer.Close() downloadReport() End If End Try End Sub Private Sub downloadReport() Dim fileName As String = System.IO.Path.GetFileName(lnkReportFile.NavigateUrl) Dim fileToDownload As String = Server.MapPath("~\" & Constants.Reports.strReportPath & "\" & fileName) Response.ContentType = "application/octet-stream" Dim cd As ContentDisposition = New ContentDisposition() cd.Inline = False cd.FileName = System.IO.Path.GetFileName(fileName) Response.AddHeader("Content-Disposition", cd.ToString()) Dim fileData As Byte() = System.IO.File.ReadAllBytes(fileToDownload) Response.OutputStream.Write(fileData, 0, fileData.Length) End Sub A: Try something the above : Response.Flush(); Response.End(); I hope that helps. This is "stolen" from here . It worked fine with ajax and asp.net an also with mvc.
{ "pile_set_name": "StackExchange" }
Q: How to remove comma in the input text form using JS before it will be submitted to the server? I have a form that when submitted to the server will contain commas in the query string values, for example: test.com/?manufacturer=0&body-style=0&min-price=270%2C000&max-price=780%2C000 Is there a way to remove this comma using JS just after the user clicks the form but before it will be submitted to the server? I have this approach here: How replace query string values using jQuery? But that will only change the text to integer but in the URL itself. I also tried using input number attribute in HTML 5 but I cannot figure out how to use a comma by default to show it on the form: How to force to display a number with a comma with input type number? I would appreciate any tips. Thanks. UPDATE Final working solution: $('.my_form').submit(function() { var x=$('#input_text_field_one').val(); x=x.replace(/,/g,''); x=parseInt(x,10); $('#input_text_field_one').val(x); return true; }); input_text_field_one is the input text form containing a number with commas. .my_form is the class name for the form. After form submit the above code replace the numbers with commas to without commas. So finally, the numbers are submitted as number. :) A: I think you want something like this:- form.onSubmit = function(){ form.action = form.action.replace(",", ""); return true; }
{ "pile_set_name": "StackExchange" }
Q: Get nth cdr of a list without using nthcdr I'm a Common Lisp beginner struggling with one of my assignment... One of my CS assignment is to create a function which basically works as the built-in nthcdr function of clisp. We will call it ncdr: (ncdr n L) => n being the cdr we want to output, L the list Examples: (ncdr 2 '(a b c)) => (c) (ncdr 0 '(a b c)) => (a b c) (ncdr -1 '(a b c)) => nil (ncdr 5 '(a b c)) => nil So my approach was to set a counter and compare it to n Here are the conditions I thought of: if n < 0 -> nil if counter < n -> + 1 counter and (ncdr (cdr list) if counter = n -> output list if counter > n -> nil And here is what I came up with... I don't think it's the most effective way though and, for now, well it doesn't work. (defun ncdr (n L &aux counter) (setq counter 0) (cond ((atom L) nil) ((< n 0) nil) ((< counter n) (+ 1 counter (ncdr n (cdr L)))) ((eq counter n) L) ((> counter n) nil) )) From the hours I spent experimenting with each cond line of my function I know this line doesn't work as intended ((< counter n) (+ 1 counter (ncdr n (cdr L)))) I get an error: nil is not an number I feel like I'm missing something critical to solve this. A: First, the error. In: (+ 1 counter (ncdr n (cdr L)))) you are actually summing three values: 1, the value of the variable counter, and the result of the function ncdr applied to two parameters, which, when nil, produces the error (you are summing, for instance, (+ 1 0 nil) and nil is not a number). Then, let’s go to the logic of your program. Your conditions are basically correct, although they led to a program that could be improved, as we will see later. But, you made a logical error in their implementation: counter should change at each recursive call of the function, increasing by 1, while for each call, you reset it to zero at the beginning of the execution of the body of the function. This is because the increment, even if done correctly, is canceled by the assignment (setq counter 0). How can we increment such a variable correctly? By adding a new parameter counter to function, and avoiding to reset it to zero each time, but only assigning it to zero at the beginning, in the initial call. How could this be done in Common Lisp? Using an optional parameter, not a auxiliary variable, in this way: (defun ncdr (n L &optional (counter 0)) (cond ((atom L) nil) ((< n 0) nil) ((< counter n) (+ 1 counter (ncdr n (cdr L)))) ; <- Wrong!!! To be corrected ((eq counter n) L) ((> counter n) nil))) So, let’s revise the recursive branch of the conditional, to correctly pass the new value in the recursive call (and perform some minor adjustment): (defun ncdr (n L &optional (counter 0)) (cond ((atom L) nil) ((< n 0) nil) ((< counter n) (ncdr n (cdr L) (+ 1 counter))) ; or (1+ counter) ((= counter n) L) ; use = for numbers ((> counter n) nil))) The &optional keyword in the lambda list has the effect that initially you call (ncdr 2 '(a b c)) so counter is assigned to 0, while in the remaining calls the current value is passed along, incremented by 1, so that at the end of recursion it will be equal to n. Efficiency There is no need to use another variable, counter, since you already have a variable suitable for the recursion: n. In fact, you could reformulate your conditions in this way: if the list is empty, return nil if n is less then 0, return nil if n is 0, return the list if n is greater than 0, recur on n-1 and on the cdr of the list that bring to a program with the following structure: (defun ncdr (n L) (cond ((null L) nil) ((< n 0) nil) ((= n 0) L) (t (ncdr ...)) ; <- recursive call - to be completed as exercise!
{ "pile_set_name": "StackExchange" }
Q: Passing and overwriting parameters to Verilog modules I'm studying the way of passing parameters from one module to another and I have one question. I have this instance in the top level module. parameter a= 100; parameter b = 200 ; test#(b/(a*2)) test( .clk(clk), .reset(reset), .out(out) ); In test module, I have this header: module test#(parameter max = 33 )( input clk, input reset, output out ); So, my question is: Which value will the module take as input parameter? 33 or 1 ? I mean, Is max=33 overwritten by the one I'm passing from the top level module? A: Yes, the value will be overwritten by the one passed from the top module. The value 33 will only be used when there is nothing passed. You can think of it as a default value.
{ "pile_set_name": "StackExchange" }
Q: Law of Iterated Logarithm for Fractional Brownian Motion (Cross-posted to https://mathoverflow.net/questions/281342/reference-for-lil-for-fractional-brownian-motion.) Let $(\Omega,\mathcal F,\Bbb P)$ be a complete probability space. If $B=(B_t)_{t\ge0}$ is a standard real valued Brownian Motion on this space, then the following things are well known: The trajectories of $B$ are a.s. $\alpha$-Holder continuous for all $0<\alpha<1/2$. $B\notin\operatorname{BV}[0,T]$ but a.s. $B$ has finite quadratic variation, and if I remember well this is the best possible, in sense that a.s. $\|B\|_p=+\infty$ for every $p<2$ (here $\|\cdot\|_p$ is the $p$-variation norm on the fixed interval $[0,T]$). A.s. the law of iterated logarithm says that $$ \limsup_{t\to0^+}\frac{B_t}{\sqrt{2t\log\log(1/t)}}=1$$ $$ \liminf_{t\to0^+}\frac{B_t}{\sqrt{2t\log\log(1/t)}}=-1$$ 4.Set $S_t:=\sup_{0\le s\le t}B_s$ and fixed $a>0$, then reflection principle ensures that $$ \Bbb P(S_t\ge a)=\Bbb P(|B_t|\ge a) $$ from which we get the distribution of $S$. My questions are: what can we say about the Fractional Brownian Motion $B^H$ of Hurst parameter $0<H<1$ (I'm particularly interested in the case of $1/2<H<1$)? And what about $|B^H|$? It is well known that a.s. $B^H$ has trajectories which are $\alpha$-Holder continuous for all $0<\alpha<H$; the same holds for $|B^H|$ since the composition of an $\alpha$-Holder and a $\beta$-Holder function is $\alpha\beta$-Holder continous. I'm not sure, but it seems reasonable that $\|B^H\|_{1/H}<+\infty$ and $\|B^H\|_p=+\infty$ for every $p<1/H$. What about $|B^H|$? For the third property, I don't know neither how to conjecture an analogous claim. Is it true that, putting $S_t^H:=\sup_{0\le s\le t}B_t^H$ $$ \Bbb P(S_t^H\ge a)=\Bbb P(|B_t^H|\ge a)\;? $$ What about $|S_t^H|:=\sup_{0\le s\le t}|B_t^H|$. I bet all these properties are collected somewhere, in some lecture note, so any appropriate reference can be a perfect answer! A: The exact modulus of continuity for fBm is $\delta^{H} |\log \delta|^{1/2}$, see e.g. Lifshitz Gaussian Random Functions, p. 220. In particular, it is $\alpha$-Hölder for any $\alpha\in (0,H)$. This is very well known and is written in many introductory texts about fBm, see e.g. Nourdin Selected Aspects of Fractional Brownian Motion, Corollary 2.1. Yes, there is a law of iterated logarithm $$ \limsup_{t\to 0+} \frac{B_t^H}{t^H|2\log\log t|^{1/2}} = 1 $$ almost surely, see here, p. 36. No, neither of this is true. The distribution of maximum of fBm (or its absolute value) is quite involved.
{ "pile_set_name": "StackExchange" }
Q: Call an activity and remove calling activity from stack? I have an Activity which is NOT the main Activity of my application, but which is launchable via a shortcut. When launched directly from the shortcut it accepts some user input then launches the MainActivity using the code below: Intent myIntent = new Intent( QuickTimerActivity.this.getBaseContext(), MainActivity.class); myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); QuickTimerActivity.this.startActivity(myIntent); After calling the MainActivity I want the calling activity to disappear from the stack - i.e. when the user presses the back button on the MainActivity I want them to exit the app. I've looked through other posts and tried adding various flags to my intent (including FLAG_ACTIVITY_CLEAR_TOP as shown above), but none of them have the desired effect. How can I remove the calling Activity from the stack, or alternatively have the user exit the application if the user presses the back button and the activity was called from the code above? A: Call finish(); after sending the intent.
{ "pile_set_name": "StackExchange" }
Q: What's your take on the death of InfoPath? Microsoft recently announced that they will be "retiring" InfoPath: In an effort to streamline our investments and deliver a more integrated Office forms user experience, we’re retiring InfoPath and investing in new forms technology across SharePoint, Access, and Word. This means that InfoPath 2013 is the last release of the desktop client, and InfoPath Forms Services in SharePoint Server 2013 is the last release of InfoPath Forms Services. The InfoPath Forms Services technology within Office 365 will be maintained and it will function until further notice. Update on InfoPath and SharePoint Forms However, some of the additional guidance given in the article seems contradictory to a total break from the product line: What should I use to build and complete forms? You should continue to use InfoPath technology. Will there be a migration tool or process for the next generation of forms technology? We’ll provide more details on migration scenarios and guidance in Q4 of CY 2014. So what does everyone think about this? And how should this affect our guidance of clients on this matter? A: I'm a little miffed and I seem to be the minority. It does things like repeating sections very well and stores it all as XML. You can then do so many things with that XML. I love having Nintex available to run xslt againt it and generate awesome looking email notifications. It also handles rules and show/hihding content well. It takes less time to create forms than to create it all in html/spd/vs and then wire up all the javascript to handle showing and hiding content as well as all the validation too. A: Since MS has said that they will support InfoPath for 10(!) more years there is no need for extreme action as of now. Probably the support will be discontinued with the next on premise release, and hopefully by then MS has presented the new alternative to InfoPath (in my dreams, and probably only there, with great migration paths). My guess is that we will see more of a web forms approach (like MVC) with a huge part of the logic and rendering done client side (JavaScript). TL DR: For now, I see no reason to not carry on with business as usual. Microsoft says to take no actions, and they have yet to present their alternative :) A: I've had the extreme pleasure of working with InfoPath and administrative forms. You know what I say? Good Riddance. I'll give you a couple reasons why: Code-behind administrative forms are very tricky to migrate. Usually there are misreferences, and they need to be republished manually. Think about it, there can be a better forms integration technology that uses code behind, and since the CSOM is becoming the new standard, XPath and administrative forms doesn't make sense anymore. Using XPath is fun if you know what you are doing, but it's not realistic. Very steep learning curve. XML is getting trumped by JSON, I think they know that.
{ "pile_set_name": "StackExchange" }
Q: Reading data using Anahkiasen/Polyglot returns error trying to get property of non-object After adding the Anahkiasen/Polyglot package to my Laravel 4.2 project I tried to get this to work. I set up everything the way I think it's supposed to be (the documentation is kinda bad). Saving to the database doesn't seem to be a problem but when I want to read I get the following error: Trying to get property of non-object (View: /Applications/MAMP/htdocs/*my view*.blade.php) Models: use Polyglot\Polyglot; class Page extends Polyglot { use SoftDeletingTrait; protected $fillable = [ 'lang', 'meta_title', 'meta_description', 'title', 'page_title', 'page_content', ]; protected $polyglot = [ 'meta_title', 'meta_description', 'title', 'page_title', 'page_content', ]; // ... } class PageLang extends Eloquent { public $timestamps = false; protected $fillable = [ 'page_id', 'lang', 'meta_title', 'meta_description', 'title', 'page_title', 'page_content', ]; } My blade template: $page->nl->title /* This is what's causing the error $page->title doesn't produce errors but is, of course, empty */ Been stuck on this for a while now. Any help is greatly appreciated :-) A: I'm not familiar with the library, but looking at the base Polyglot class, it looks like this abstraction works by using PHP's magic __get variable to inject n localization object when you access something like $page->nl Looking at __get, public function __get($key) { // If the relation has been loaded already, return it if (array_key_exists($key, $this->relations)) { return $this->relations[$key]; } // If the model supports the locale, load and return it if (in_array($key, $this->getAvailable())) { $relation = $this->hasOne($this->getLangClass())->whereLang($key); if ($relation->getResults() === null) { $relation = $this->hasOne($this->getLangClass())->whereLang(Config::get('polyglot::fallback')); } return $this->relations[$key] = $relation->getResults(); } // If the attribute is set to be automatically localized if ($this->polyglot) { if (in_array($key, $this->polyglot)) { /** * If query executed with join and a property is already there */ if (isset($this->attributes[$key])) { return $this->attributes[$key]; } $lang = Lang::getLocale(); return $this->$lang ? $this->$lang->$key : null; } } return parent::__get($key); } there's a number of conditionals that, if failed, result in the parent's __get being called return parent::__get($key); In other words, the normal model behavior. That's probably what's happening above -- and since nl isn't a set object PHP complains when you try to call a method on it. Of the three conditionals in __get, this seems like the most likely candidate for failure if (in_array($key, $this->getAvailable())) { $relation = $this->hasOne($this->getLangClass())->whereLang($key); if ($relation->getResults() === null) { $relation = $this->hasOne($this->getLangClass())->whereLang(Config::get('polyglot::fallback')); } return $this->relations[$key] = $relation->getResults(); } If your specific case, it's going to look like if (in_array('nl', $this->getAvailable())) { //... } Looking at getAvailable() protected function getAvailable() { return Config::get('polyglot::locales'); } it looks for a configuration field named Config::get('polyglot::locales');. I'd check if calling that configuration field returns nl as a configured locale var_dump(Config::get('polyglot::locales')); My guess would be it doesn't, possibly because you didn't run the artisan command to publish the configuration for the package php artisan config:publish anahkiasen/polyglot
{ "pile_set_name": "StackExchange" }
Q: How to update data in a database Consider the following code in a datamapper, to save data into a database: /** * Save data into the database * @param Site_Model_User $model * @throws InvalidArgumentException */ public function save($model) { if (!$model instanceof Model_User) { throw new InvalidArgumentException('Model is not of correct type'); } $data = array(); $data['username'] = $model->getUserName(); $data['firstname'] = $model->getFirstName(); $data['lastname'] = $model->getLastName(); $data['email'] = $model->getEmail(); $data['password'] = $model->getPassword(); $data['role'] = $model->getRole(); $data['pic'] = $model->getImage(); if ($model->getId() < 0) { // nieuw object, doe insert $id = $this->getDao()->insert($data); $model->setId($id); } else { // bestaand object, doe update $where = $this->getDao()->getAdapter()->quoteInto('id = ?', $model->getId()); $this->getDao()->update($data, $where); } } What i do is that i save my object everytime. When doing an insert this is no problem. Because I send a complete filled update. But lets say I want to update my password. And i do a update. It doesn't let me do the update because it says that certain values can not be 0. For example: Mysqli statement execute error : Column 'username' cannot be null" What is the best soultion for this? Should I first load the whole object again from the database, then change the fields and then do the update? Or are ther other better, more common solutions? Thanks A: yes, you have to load all the fields from the database and fill up all the required form fields except password fields and then change your password and submit the form. this will help you for validate required field not NULL and go further. Thanks.
{ "pile_set_name": "StackExchange" }
Q: Context menu only showing for a few TableView rows javafx fxml I have a TableView, in which i need each row to have a context menu. In this context menu there should be an Edit option and a Remove option. I wrote this class: public class ContextMenuRowFactory<T> implements Callback<TableView<T>, TableRow<T>> { private List<MenuItem> menuItems; public List<MenuItem> getMenuItems() { return menuItems; } public void setMenuItems(List<MenuItem> menuItems) { this.menuItems = menuItems; } @Override public TableRow<T> call(TableView<T> view) { final TableRow<T> row = new TableRow<>(); final ContextMenu menu = new ContextMenu(); menu.getItems().addAll(menuItems); row.setContextMenu(menu); row.contextMenuProperty().bind( Bindings.when(Bindings.isNotNull(row.itemProperty())).then(menu).otherwise((ContextMenu) null)); return row; } } And I use it like this, in fxml: <TableView fx:id="table" layoutX="14.0" layoutY="35.0" prefHeight="660.0" prefWidth="514.0" editable="true"> <columnResizePolicy> <TableView fx:constant="CONSTRAINED_RESIZE_POLICY" /> </columnResizePolicy> <items> <FXCollections fx:id="tableData" fx:factory="observableArrayList" /> </items> <columns> <TableColumn prefWidth="50" text="Column 1" /> <TableColumn prefWidth="50" text="Column 2" /> </columns> <rowFactory> <ContextMenuRowFactory> <menuItems> <FXCollections fx:factory="observableArrayList" > <MenuItem text="Edit" /> <MenuItem text="Remove" /> </FXCollections> </menuItems> </ContextMenuRowFactory> </rowFactory> </TableView> However, it only seems to be working for a small number of the rows. In the table i have 1000 entries and i could find 6/1000 where a context menu would show. A: A MenuItem may only belong to one menu; you are trying to use the same MenuItem instances in all the ContextMenus you create. The simplest fix is just to create a single ContextMenu: import java.util.List; import javafx.beans.binding.Bindings; import javafx.scene.control.ContextMenu; import javafx.scene.control.MenuItem; import javafx.scene.control.TableRow; import javafx.scene.control.TableView; import javafx.util.Callback; public class ContextMenuRowFactory<T> implements Callback<TableView<T>, TableRow<T>> { private final ContextMenu menu = new ContextMenu(); public List<MenuItem> getMenuItems() { return menu.getItems(); } public void setMenuItems(List<MenuItem> menuItems) { menu.getItems().setAll(menuItems); } @Override public TableRow<T> call(TableView<T> view) { final TableRow<T> row = new TableRow<>(); row.contextMenuProperty().bind( Bindings.when(Bindings.isNotNull(row.itemProperty())).then(menu).otherwise((ContextMenu) null) ); return row; } }
{ "pile_set_name": "StackExchange" }
Q: Difference between the terms 'famous' & 'infamous'; 'valuable' & 'invaluable' Question in Short: Why is it that the terms valuable and invaluable mean almost the same thing while the terms famous and infamous are almost semantically opposite in meaning? That is, one is used to describe something/someone well known for their good qualities, while the other is used to describe something/someone well known for their bad qualities? Question in Detail: One of the answers to the question titled Difference between “valuable” and “invaluable” [closed] suggest that the term valuable is almost synonymous with invaluable, although the preferred answer points out their subtle differences as being costly and priceless, respectively. That is, something that can be bought or sold (valuable), as opposed to something that cannot be bought or sold (invaluable), yet is treasured. Why is it that the terms famous and infamous are not semantically synonymous according to these online references? A: The prefix does its job faithfully regardless of the ultimate result of connotation or implication. Some explanation may be in order. in-: prefix denoting 'not'. ∴ in + famous → not famous & in + valuable → not valuable (Patience!) fame: good reputation; famous: widely known for something good; infamy bad reputation; infamous: widely known for something bad. – Naturally? value (n): worth; (to) value (v): to estimate the worth of; valuable: that whose worth can be estimated; invaluable: that whose worth can not be estimated; too valuable. It all adds up nicely. The prefix modifies in a mechanical way here, while the meaning on the other hand, depends on the nature of the word, its original implication, even its etymology and usage. Even not valuable can be understood in the right context to mean something that cannot be valued (not value+able).
{ "pile_set_name": "StackExchange" }
Q: Scipy: difference between optimize.fmin and optimize.leastsq What's the difference between scipy's optimize.fmin and optimize.leastsq? They seem to be used in pretty much the same way in this example page. The only difference I can see is that leastsq actually calculates the sum of squares on its own (as its name would suggest) while when using fmin one has to do this manually. Other than that, are the two functions equivalent? A: Different algorithms underneath. fmin is using the simplex method; leastsq is using least squares fitting.
{ "pile_set_name": "StackExchange" }
Q: Use of run-time polymorphism I am novice in programming, I want to ask that what is the ultimate use of run-time polymorphism? Example: class Parent { //do something } class Child : Parent { //do something } main() { Parent p = new Child (); // run-time polymorphism Child q = new Child(); // no polymorphism } My question is that, we use first line (Parent p = new Child();) to achieve runtime polymorphism, but we can use second line (Child q = new Child();) in lieu of first one.... So what is the difference between both of them? Why do we use run-time polymorphism? A: While your example shows why that is a poor example, picture something like this: main() { Parent p = Factory("SomeCondition"); ///run-time polymorphism } Parent Factory(string condition) { if (condition == "SomeCondition") { return new Child(); } else { return new Parent(); } } When the factory is called, we don't know what the return type will actually be, it could be a child, it could be a parent. A: There's no actual use for the code snippet you've provided. But think about this method: public void DoSomething( Parent parent ){ ... } You can do this: Child child = new Child(); DoSomething( child ); In this case, for DoSomething it will be just a Parent. It doesn't care if it is a subclass or not. Hope it helps.
{ "pile_set_name": "StackExchange" }
Q: I have a textarea parent component I want to change the height of textarea in my child component by using @input How to change the size of textarea component when accessed in child component? textarea.html <textarea style = "height"=150px></textarea> // height is set globally here xyz.html <app-textarea></app-textarea> // want to change the height of text area in this component value set globally cant be change A: In the textarea component define an input property, which will contain the height of the textarea: @Input() textareaHeight: string; And in the textarea.html do: <textarea [ngStyle]="{'height': textareaHeight}"></textarea>. More about ngStyle: ngStyle In the xyz.html: <app-textarea height="150px"></app-textarea>
{ "pile_set_name": "StackExchange" }
Q: Change color of bar plots I have a plot: p <- plot_ly( x = c(data$sum), y = c(data$candidate), name = "Trump v Clinton", type = "bar" ) Candidate is realDonaldTrump and HilaryClinton while sum is 10000 and 5000. Is it possible to set the colour for the bar of each candidate? I.e. Trump be red and Hilary blue. A: Looking for something like this?: library(plotly) data<-data.frame(sum=c(10000, 5000), candidate=c("DonaldTrump", "HilaryClinton")) data$color<-c("red", "blue") p <- plot_ly( y = data$sum, x = data$candidate, color = I(data$color), type = "bar" ) p<-layout(p, title = "Trump vs Clinton") print(p) It plot as a vertical barplot, I needed to swap the values for the x and y axis.
{ "pile_set_name": "StackExchange" }
Q: Java CSS spriting library I'm looking for a pure Java CSS spriting library that I can integrate into my Maven build, so that spriting would be done automatically for every new build. (I'm currently using http://code.google.com/p/wro4j/ for JavaScript and CSS minimizing) I was looking into http://csssprites.org/ first but the CSS annotation effort required somewhat put me off. Is there any other library out there I should be looking at? A: Although not 100% ideal, I went for SmartSprites in the end. There's a nice Jangaroo Maven Plugin, meaning you can integrate the Sprite generation into your Maven build process easily. Downside of this solution is, that you have to add quite a bit of extra hints into your CSS files, so SmartSprites can do its spriting. Would have been nice, if SmartSprites would (semantically) parse the CSS files and do the spriting automatically.
{ "pile_set_name": "StackExchange" }
Q: Как выровнять высоту 3 блоков по родительскому контейнеру? Вот конкретный раздел сайта над которым я работаю: Вот сайт У меня есть 3 блока с услугами. В данный момент все они имеют высоту в зависимости от контента. Мне необходимо выровнять их высоту по самому большому из этих блоков, а также разместить кнопку "Узнать прайс" внизу блока с отступом в 20 пикселей от нижней части. Помогите пожалуйста это сделать. Уже пол дня играюсь с position:relative, absolute для родителей и child блоков и никак не могу получить нужный результат. A: Как вариант, использовать flexbox для раздела и position:absolute - для кнопки: .row { display: flex; justify-content: space-between; } .block { width: calc((100% - 126px) / 3); border: #ccc solid 1px; padding-bottom: 50px; position: relative; } .btn { position: absolute; width: 50px; bottom: 10px; left: 50%; margin-left: -25px; border: #ccc solid 1px; text-align: center; } <div class="row"> <div class="block"> <br /><br /><br /><br /><br /><br /><br /><br /><br /><br /> <div class="btn">Кнопка</div> </div> <div class="block"> <br /><br /><br /><br /><br /><br /> <div class="btn">Кнопка</div> </div> <div class="block"> <br /><br /><br /><br /><br /><br /><br /><br /> <div class="btn">Кнопка</div> </div> </div>
{ "pile_set_name": "StackExchange" }
Q: How to calculate $ \lim\limits_{n\to\infty} e^n\left( 1-\frac{1}{\sqrt n} \right)^n $? $$ \lim_{n\to\infty} e^{\sqrt n} \left( 1-\frac{1}{\sqrt n} \right)^n $$ How is this limit? And how does it work? A: The logarithm of the expression is $$n+n\ln\left(1-\frac1{\sqrt n}\right).$$ Recall that $$\ln(1-x)=-x+O(x^2)$$ for $x\to0$ etc. A: Note that $1-1/\sqrt n > 1/2$ for $n>4.$ For such $n$ the expression is at least $e^n\cdot (1/2)^n = (e/2)^n \to \infty.$
{ "pile_set_name": "StackExchange" }
Q: Trying to understand UIAnimation paths I am trying to get my animation move in more than one generated path. I got my codes down but I still don't get what is wrong with it. Here is where I place my image in the view UIImageView *faceAni = [[UIImageView alloc] initWithFrame:CGRectMake(200, 100, 50.0, 50.0)]; faceAni.animationImages = faces; faceAni.animationDuration = 10; faceAni.animationRepeatCount = 0; [faceAni startAnimating]; [self addSubview:faceAni]; And here is where I try to get the animation to move in a triangular path coordinates. [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDuration:1]; [UIView animateWithDuration:4 delay:0 options:UIViewAnimationOptionRepeat|UIViewAnimationOptionAutoreverse animations:^{faceAni.transform = CGAffineTransformMakeTranslation(0, 200);} completion:^(BOOL finished) { [UIView animateWithDuration:4 delay:0 options:UIViewAnimationOptionRepeat|UIViewAnimationOptionAutoreverse animations:^{faceAni.transform = CGAffineTransformTranslate(faceAni.transform, -100, 0);} completion:^(BOOL finished) { [UIView animateWithDuration:4 delay:0 options:UIViewAnimationOptionRepeat|UIViewAnimationOptionAutoreverse animations:^{faceAni.transform = CGAffineTransformTranslate(faceAni.transform, 300, 0);} completion:NULL]; }]; }]; I still don't get what is wrong with my codes. Thanks in advance! A: It might help if you describe the behaviour that you're seeing. As a guess, though, you probably don't want the UIViewAnimationOptionRepeat|UIViewAnimationOptionAutoreverse flags you're passing to each animation.
{ "pile_set_name": "StackExchange" }
Q: Identity theft? I recently checked my credit report through 3 different sites and everything seemed OK. But recently I applied to finance a car and had to confirm 6-8 years of previous addresses. Two unknown addresses were listed in my home town that I have never lived at. With the credit reports/scores showing no signs of fraud activity would I be right in thinking someone has applied for a loan under my identity or something along those lines? If so how can this be? A: Assuming you live in the US, it is quite normal when you are applying for a loan that the application will ask you to confirm your identity. One of these methods is to ask you which of the following addresses you have lived at, with some of them being very similar (i.e. same city, or maybe even the same street). Sometimes they will ask questions and your answer would be "None of the above." This is done to prevent fraudsters from applying for a loan under your identity. If you see no signs of unauthorized accounts or activities on your credit reports, and you initiated the car loan application, then you should be fine.
{ "pile_set_name": "StackExchange" }
Q: What is the TypeScript return type of a React stateless component? What would the return type be here? const Foo : () => // ??? = () => ( <div> Foobar </div> ) A: StatelessComponent type mentioned in this answer has been deprecated because after introducing the Hooks API they are not always stateless. A function component is of type React.FunctionComponent and it has an alias React.FC to keep things nice and short. It has one required property, a function, which will return a ReactElement or null. It has a few optional properties, such as propTypes, contextTypes, defaultProps and displayName. Here's an example: const MyFunctionComponent: React.FC = (): ReactElement => { return <div>Hello, I am a function component</div> } And here are the types from @types/react 16.8.24: type FC<P = {}> = FunctionComponent<P>; interface FunctionComponent<P = {}> { (props: PropsWithChildren<P>, context?: any): ReactElement | null; propTypes?: WeakValidationMap<P>; contextTypes?: ValidationMap<any>; defaultProps?: Partial<P>; displayName?: string; } A: The correct return type here is ReactElement<P>, but a better option would be to use React.StatelessComponent<P> like this const Foo : React.StatelessComponent<{}> = () => ( <div> Foobar </div> )
{ "pile_set_name": "StackExchange" }
Q: What does buying a wish in Sega's Aladdin do? In Sega Genesis's version of Disney's Aladdin, the player on multiple occasions encounters a merchant who will offer either an extra life for every five rubies Aladdin collects, or a scroll labeled wish for every ten rubies- what benefit does the scroll labeled wish offer? A: From this guide - "A wish gives Aladdin one continue. That means when he loses his last life, he can continue the game from the level he is at instead of having to start over. Every time you continue a game, you get the same number of lives as when you first started the game. A wish could be worth up to 6 extra lives." So since a continue is worth so much more, it makes sense to save up for them instead of just regular extra lives, if you can.
{ "pile_set_name": "StackExchange" }
Q: Necesito ayuda para guardar imágenes en base de datos con java Ayer tenía mi código en perfecto funcionamiento. Pero hoy que intenté retomarlo y guardar más registros no funciona. De hecho, no cambié nada en el código. Probé incluso con versiones anteriores del proyecto pero tampoco funcionan. El error es: GRIZZLY0155: Invalid chunk starting at byte [6] and ending at byte [6] with a value of [null] ignored Analizando un poco el código, creo que el error está en que no lee correctamente la imágen, porque al comprobar si le llegan los parámetros, da error desde ahí. Mi formulario: <form action="SaveProduct" method="POST" enctype="multipart/form-data"> <input type="text" name="name"> <input type="text" name="price"> <select name="category"> <option>Categoría</option> <% java.sql.Connection con1 = Connection.getConnection(); java.sql.Statement set1 = con1.createStatement(); java.sql.ResultSet rs1 = set1.executeQuery("select * from producto"); while(rs1.next()){ %> <option> <%= rs1.getString("cla_pro") %> </option> <% } con1.close(); %> </select> <input type="file" name="photop"> <input type="submit" value="Guardar"> </form> Lo de java: String name = request.getParameter("name"); float price = Float.parseFloat(request.getParameter("price")); String category = request.getParameter("category"); int id_pro = 0; Part filepart = request.getPart("photop"); InputStream is = filepart.getInputStream(); Antes de la clase tengo esto: @MultipartConfig public class SaveProduct extends HttpServlet { Ayuda por favor, estoy muy desesperado :c A: aveces es problema de netbeans al compilar me ha ocurrido que me lanza errores y el codigo esta bien, es aislado el caso pero ocurre, prueba cerrando el proyecto y cerrando el IDE vuelve a abrir tanto el IDE como el proyecto.
{ "pile_set_name": "StackExchange" }
Q: Action on submit I have beginner question about submit behavior. Every time I press submit my loginModal keep coming back up, is this expected behavior? Its like the ready() function is fired again. I would like my initiate App() function to be executed after submit Here is bits of my code: //Show loginModal on page ready $(document).ready(function(){ $('#loginModal').modal('show'); }); //loginModal submit <div class="modal-footer"> <button type="submit" class="btn btn-danger btn-default pull-left" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Cancel</button>`enter code here` </div> //When submit button is clicked $('#loginModal').submit(function() {} initiateApp() }); A: You need to prevent the default behviour of the submit button i.e. to refresh the page. Use event.preventDefault() $('#loginModal').submit(function(event) { event.preventDefault(); initiateApp() } );
{ "pile_set_name": "StackExchange" }
Q: Laravel Service Provider bypassed I have the following Class: <?php namespace App\CustomClasses; class Disqus { protected $secretKey; protected $publicKey; public function __construct() { $this->secretKey = 'abc'; $this->publicKey = '123'; } public function payload() { ... } } I have also created a Service Provider (simplified bellow), to bind this class to the IOC container: <?php namespace App\Providers; use Illuminate\Support\ServiceProvider; use App\CustomClasses\Disqus; class DisqusServiceProvider extends ServiceProvider { public function register() { $this->app->singleton('Disqus', function() { return new Disqus(); }); } public function boot() { // } } And in my controller: <?php use App\CustomClasses\Disqus; class ArticlesController extends Controller { public function view(Disqus $disqus) { ... //$disqus = App::make('Disqus'); return View::make('articles.view', compact(array('disqus'))); } } The problem is that whenever I use the $disqus variable, it is not 'generated' from the Service Provider, but the Disqus class itself. However, when I have $disqus = App::make('Disqus');, the variable goes through the service provider. So my question is, since the binding exists in the Service Provider, shouldn't the $disqus variable come from the DisqusServiceProvider rather than the Disqus class directly when I use it in my controller? Am I missing something? Thanks in advance for any help. A: When the controller's action requires an object of class App\CustomClasses\Disqus to be passed, the service container searches its mappings for the class name of the dependency to see if it has the corresponding service. However, it uses the fully qualified class name and this is the reason it doesn't work correctly in your case. In your service provider you have bound the service to Disqus, while the fully qualified class name is App\CustomClasses\Disqus. Use the fully qualified class name in the provider and it should work.
{ "pile_set_name": "StackExchange" }
Q: Determining character frequency in a string (Javascript) I'm working on a solution for determining character frequency in a string. The characters are being added to my object properly but all counts end up as NaN. (I think I'm taking a less efficient approach by splitting the string into an array of characters, but I'd like to solve this approach nonetheless.) var charFreq = function (frequencyString) { var stringArray = frequencyString.split(""); var frequencies = {}; for (var k in stringArray) { var nowLetter = stringArray[k]; if (stringArray.hasOwnProperty(k)) { frequencies[nowLetter] += 1; } } return frequencies; } charFreq("what is the reason for this"); A: Your frequencies is an object and when you access frequencies[nowLetter] += 1; you are accessing a previously unavailable property like frequencies.a which will be undefined. Hence you are getting NaN. See http://jsfiddle.net/xbUtR/ for the fix. if(frequencies[nowLetter] === undefined) frequencies[nowLetter] = 0; frequencies[nowLetter] += 1; A: frequencies[nowLetter] is undefined in your code. A better approach: function charFreq(txt){ var obj = {}; for(var i = 0; i < txt.length; i++){ obj[txt[i]] = ++obj[txt[i]]||1; } return obj; } A: Because the property values in frequencies have an initial value of undefined and undefined + 1 == NaN Try code like this: var charFreq = function (frequencyString) { var stringArray = frequencyString.split(""); var frequencies = {}; for (var k in stringArray) { var nowLetter = stringArray[k]; if (stringArray.hasOwnProperty(k)) { // One way to initialize the value -- not the only way. if (!frequencies[nowLetter]) { frequencies[nowLetter] = 0; } frequencies[nowLetter] += 1; } } return frequencies; }
{ "pile_set_name": "StackExchange" }
Q: Is there a client+server-side MVC JS framework I've been working with Node+Express for a while now, and I'd like to start looking for a strong structure for building average to huge web apps, but which could also be used (and not be too much overkill) for simple websites. I've been taking interest for backbone, but I'm looking for something much more "complete" already. I Know backbone can do everything with the right plugins and by respecting the best practices, but what I'm looking for is something more "strong" as is and from the start, like AngularJS, CanJS or Ember (maybe CanJS is the best compromise between flexibility and conventions althought all of this can be mostly subjective). Just to be sure to keep into the best practices, even if I must stick to an opinionated FW. Now, before choosing anything, and because I'll be using Node in the backend, so full JS, I'd like to know if there is a framework which would deliver client+server MVC capabilities, or if I must use Node/Express in the back and something else for the front. Other info that may be useful, I'd like to code in CoffeeScript/LESS, and keep HTML as is (so no Jade-like stuff). If I'm not asking too much, I'd like to use this technology for all of my projects, which will be targeting also mobile phones, as websites (for sure), and sometimes even as Phonegap-based apps. Maybe this becomes hard (Meteor doesn't support Phonegap for it's client-side part for what I've read, maybe Derby ?). Also, I must point out that I'm not asking anything subjective like "what is the best between ..." but simply if full client+server MVC JS framework exists, and if yes, which ones meets those needs. A: rendr (backbone with server-side support) meteor (very real-time oriented)
{ "pile_set_name": "StackExchange" }
Q: Should I redo this pruning cut? It looks to me that this pruning cut left too much of the branch that was cut: Should I cut again closer to the trunk? Should I perhaps fill the hole in the center with something? Is there a sign of any serious illness? UPDATE: New photos: A: The cut is fine but the tree has or will have issues. You can see that there is already interior decay in the heartwood of the tree. As stormy indicates water will enter the wound and decay will continue. Do not put tar on the wound or do anything else. Research has shown further action with sealants is harmful to the tree as this answer indicates. On the plus side you have created a new home for wildlife.
{ "pile_set_name": "StackExchange" }
Q: Replacing Classes in the System Namespace I'm currently working to hack my .NET operating system into running on top of MS.NET/Mono (previously it ran bare-metal only), and I've hit a small snag. I need to implement my own System.Console that talks to my service infrastructure, and I can't find a good way to replace it without either 1) not linking against mscorlib (would be hellacious to do), or 2) Using a NotQuiteSystem namespace for my replacements, which would break compatibility. Is there a mechanism by which I can cleanly replace System classes without doing one of those things? Edit: One thought is to use Mono.Cecil to rewrite references to System.Console to Renraku.System.Console or somesuch, but I'd prefer to work within the framework if possible. A: You should look into the free tool PostSharp. It allows you to change existing .Net assemblies at design time by automating the modification of the MSIL. See this page for more information on compile-time weaving in PostSharp. and this page for information on load-time weaving (occurs at runtime just before the assembly is loaded in memory). For Runtime weaving (modifying existing methods at runtime), look at LinFu. [Except from page] ... you can use LinFu.AOP to dynamically intercept any method on any type, regardless of whether or not the method is declared virtual or non-virtual. You’ll also be able to dynamically intercept (and even replace) methods declared on sealed types, in addition to any static methods that are declared on that type. [/Except from page]
{ "pile_set_name": "StackExchange" }
Q: Please put your answers in the answers section, even if they're short It's sometimes tempting to put short answers into the comments section of a question, rather than putting them as answers. Stack Exchange site guidance discourages this. Instead, please post answers in the answer section, where you can later edit typos, make improvements, and get upvotes. Using the comments defeats the functioning of the Stack Exchange engine. And since comments on the question go above real answers, it's a way to get in a first word, which is unfair to the real answers — even if you didn't mean it that way. Comment-answers also push down comments which might be used to get clarification and improve the question itself — which is the intended purpose of comments to questions. (See again the guidance linked above.) If you have a good, succinct answer, please put it in the answer section. If you know that your comment is an incomplete answer, it's probably best to think about how to round it out. Or maybe just let someone else answer. (Or, if you really can't resist, think about coming back later after someone else answers and deleting your comment so it doesn't distract. Maybe it could even fit as an edit to another answer, or a comment to an answer, which is less harmful since at least the answer comes first.) I have mixed thoughts on comments like "Here's a youtube video on this subject", or "Google for foo and you'll see..." That's often pragmatically helpful, which is good, but... We're pretty strict about not allowing these as answers, but having those same things as comments doesn't solve the problems noted above. (Why does this get page-position priority over full answers? What if the video is pulled or moved and no one bit a mod can edit to fix?) I think it's really better to take the time to provide at least a brief real answer along with the link. The main exception is when the question is clearly going to be closed (and as something other than a duplicate). In that case, comments can help the user and are really better than full answers (because answer on off-topic questions encourage more of the same). Should we encourge / allow comments with helpful advice to questions we know will be closed? On several other SE sites where I participate, comments are regularly deleted by the mods en masse even if they're helpful. I like that we don't tend to do that here, but it does mean we should be more careful of starting messiness. I know I'm guilty of all of this myself sometimes so I'm not on a high horse or anything. It's something we can all do to improve the quality of our Q&A archive. A: I have to admit that I have occasionally abused comments (can't really remember which SE sites) for one of these reasons: I'm too lazy to write a comprehensive answer, or don't have much time at the moment. It would take more research or other real work (as apposed to just putting in words something already in my brain) than I feel like bothering with, and I know that the level I do want to answer at would make a crappy answer that may get downvoted. I have a link-only answer and don't feel like elaborating, probably because I think it's a dumb question and the OP should have been able to find the linked reference easily himself. The OP is being a moron, and deserves to be publicly embarassed for asking such a stupid question. However, I know that a answer like that would get downvoted. So, a comment for something a comment isn't really meant for is just a sneaky way of using the mechanics of the system to get away with something it doesn't really want you doing. So how does this answer the question? On one hand, this argues for comments should be aggressively policed. On the other hand, I won't be able to get away with some things anymore. However, since it would prevent everyone else from utilizing the same abuses I do (it's OK for me to do it, but I really don't want everyone else doing it), this answser is in support of being more strict with comments. Go ahead and delete them when they aren't for the intended purpose. A: When someone insists on continually answering question after question in the comments to the question it comes across to me this way: I'm too important to be expected to submit an answer and have the community decide where in the pecking order of multiple answers it should fall. My answers should always be at the top of the page, regardless of how the other users in the community view said answers, and should be sheltered from review and correction by the rest of the community. Such an attitude goes against the fundamental spirit of the stack exchange network in which community opinion is one of the most important mechanisms used for separating the figurative "wheat" from the "chaff". Early on during my membership here I admit I was guilty at times of answering questions with short comments. I have since made a conscious effort to resist the urge. On occasion, when coming across a question to which I made such a comment in the past, I have even rewritten the comment as an answer and then deleted the comment. There are times when it is difficult to ask a question for clarification from the OP without essentially answering the question. The OP may ask something vague such as, "Why did my picture turn out totally black?" Without any additional information it would be impossible to answer the question with a single succinct answer as there are many possible causes. One might make a comment that asks the OP, "Did you remember to remove the lens cap?" The OP might respond, "Oh! Silly me! That was it." In such a case the comment requesting a clarification from the OP has answered the question. But there are many cases beyond such a request for clarification that are obvious attempts to answer the question in the comment section so that it can't be ranked, downvoted, or edited by the community at large. Often these "comments" are so long as to require bridging them over multiple comments at or close to the maximum allowable length! A: In a number of SE forums I'm increasingly likely to comment than to answer. The alternative may be to not answer at all. If moderators in a given forum (as noted by others) make a policy of destroying value by deleting useful comments, that's a problem that the site's owners need to address if they care about it. Answers that seek to be useful rather than pretty are too often treated badly by the community and/or moderators. People who say things like "I'll upvote this answer if you reformat it entirely / phrase it in ways which suit me / change the paragraph or list structure / .... " seem to feel they are offering an inducement. They're not. The main value I see in 'rep'is that it gives people some indication that one's answers may be valid and or useful if there is some doubt - ie "authority fallacy" fodder :-). Effort spent prettying to keep the nay-sayers at bay can be better spent providing useful input where it seems apposite to add it.
{ "pile_set_name": "StackExchange" }
Q: Menu contextual I'm trying to make a context menu to edit and delete items from a list. As follows. HTML <div class="row"> <div id="capa1" class="col-md-4 col-md-offset-4"> <p> Div 1</p> </div> </div> <div class="row"> <div id="capa2" class="col-md-4 col-md-offset-4"> <p> Div 2</p> </div> </div> <div class="row"> <div id="capa3" class="col-md-4 col-md-offset-4"> <p> Div 3</p> </div> </div> This is the contextual menu <ul id="menuCapa" class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1"> <li role="presentation"> <a role="menuitem" tabindex="-1" href="#" onClick="restauraCapa();">Restaurar</a> </li> <li role="presentation" class="divider"></li> <li role="presentation"> <a role="menuitem" tabindex="-1" href="#" onClick="eliminaCapa();">Eliminar</a> </li> </ul> And the script <script> //cierra cuando abandona el elemento $(document).mouseleave(function(){ $("#menuCapa").hide('fast'); }); //cierra cuando se presiona esc $(document).keydown(function(){ $("#menuCapa").hide('fast'); }); //muestra el menu $("#capa1").mousedown(function(e) { if (e.button == 2){ $("#menuCapa").css("top", e.pageY - 20); $("#menuCapa").css("left", e.pageX - 20); $("#menuCapa").show('fast'); } }); //cierra el menu por defecto $(document).bind("contextmenu", function(e){ return false; }); </script> The menu works but for a single id, since the div I generate them through a foreach cycle with php that is to say they are dynamic I need to know which was the id to which was given a click to be able to pass it to the function, I hope that I have explained well and beforehand thank you. A: Give them each the same class Then $(".capa_class").mousedown(function(e) { if (e.button == 2){ $(this).css("top", e.pageY - 20); $(this).css("left", e.pageX - 20); $(this).show('fast'); } }); So the trick is to use a class, not an id, and use $(this) to do whatever you want with the clicked/mouseleave/keydown element.
{ "pile_set_name": "StackExchange" }
Q: Android: use developer.android.com offline? I live in Iran and Google blocks Iranian internet users to access some of its utilities like Android Developers website. Each time I'm going to use this website I have to set proxies that take the speed of my internet connection and make a lot of interrupts in it. Is there any possible ways to download Android Developers website in order to use it offline? Any tips or tricks will be appreciated. A: When you download the Android SDK, you can include the documents, which have most of the information from developers.android.com. In addition, you might consider getting a copy of the offline Google kit, available from this link.
{ "pile_set_name": "StackExchange" }
Q: Product rule for partial derivatives I am going through the solution for a problem (1.7 from Goldstein's Classical Mechanics) where it says: I don't understand why the right-hand side of the second line only contains 4 terms when there should be 5. The very last term on line 1 has been expanded into 1 term on line 2 using the product rule, but according to the product rule there should be 2 terms. A: $q$, $\dot{q}$ and $\ddot{q}$ are being treated here as separate variables, so $\dfrac{\partial \ddot{q}}{\partial \dot{q}} = 0$.
{ "pile_set_name": "StackExchange" }
Q: EJB3 / JPA @Transactional Is there an EJB or JPA annotiation that is equivalent to Spring's @Transactional ? A: The equivalent EJB3 attribute is javax.ejb.TransactionAttribute. Just like Spring's @Transactional annotation, you can control the transaction 'propagation' by passing a TransactionAttributeType to the TransactionAttribute annotation, like: @TransactionAttribute(NOT_SUPPORTED) @Stateful public class TransactionBean implements Transaction { ... @TransactionAttribute(REQUIRES_NEW) public void firstMethod() {...} @TransactionAttribute(REQUIRED) public void secondMethod() {...} public void thirdMethod() {...} public void fourthMethod() {...} } Container managed transactions are described in Part IV of the Java EE 5 Tutorial. A: See javadoc on. http://docs.oracle.com/javaee/7/api/javax/transaction/Transactional.html Namely the paragraph: See the EJB specification for restrictions on the use of @Transactional with EJBs. I did not find in EJB 3.2 any reference to the conditioning on this support. http://www.oracle.com/technetwork/java/javaee/tech/index-jsp-142185.html However, I in weblogic 12.1.2 EJB 3.1 - the @Transactional attribute works on @Stateless @Local ejbs that you inject into a base class using the CDI @Inject annotation. In any case, I would not use the @Transactional annotation for EJBs, even if all your EJBs are local and you inject them all with @Inject instead of @EJB. I would continue to use the @TransactionAttribute with EJBs.
{ "pile_set_name": "StackExchange" }
Q: Subgradient of argmax and chain rule Let $\mathcal{X} \subset \mathbb{R}^n$ and $c \in \mathbb{R}^n$. Moreover, define $$ f(c) := \max_{x\in\mathcal{X}} \ x^\top c \quad \text{and} \quad \bar{x}_c := \text{arg}\max_{x\in\mathcal{X}} \ x^\top c. $$ In this paper, Proposition 3.1, it is argued that $\bar{x}_\hat{c}$ is a subgradient of $f$ at $\hat{c}$. They prove it using the following argument: For any $c \in \mathbb{R}^n$, $$ f(c) - f(\hat{c}) = \max_{x\in\mathcal{X}} \ x^\top c - \max_{x\in\mathcal{X}} \ x^\top \hat{c} = \max_{x\in\mathcal{X}} \ x^\top c - \bar{x}_\hat{c}^\top \hat{c} \geq \bar{x}_\hat{c}^\top (c - \hat{c}). $$ My question is twofold: In order to show that $\bar{x}_\hat{c}$ is a subgradient of $f$ at $\hat{c}$, is it enough to show that $f(\hat{c}) + \bar{x}_\hat{c}^\top (c - \hat{c})$ lower bounds $f(c)$ for any $c$, as was done in the paper? By definition, $f(c) = \bar{x}_c^\top c$. Since $\bar{x}_c$ is a function of $c$, can we derive a (sub)gradient of $f$ w.r.t. $c$ using some kind of chain rule? Moreover, does it yield the same result as shown in the paper? A: Yes, that's the definition of the subgradient, $\partial f(x_0) = \{g : f(x) - f(x_0) \ge g' (x-x_0), \quad \forall x \in X\}$. That's called the envelope theorem. $\nabla f(c) = \bar{x}_c$ means that the solution correspondence is a supporting hyperplane to the choice set, $X$.
{ "pile_set_name": "StackExchange" }
Q: How to convert string representation of an ASCII value to character I have a String containing ASCII representation of a character i.e. String test = "0x07"; Is there a way I can somehow parse it to its character value. I want something like char c = 0x07; But what the character exactly is, will be known only by reading the value in the string. A: You have to add one step: String test = "0x07"; int decimal = Integer.decode(test); char c = (char) decimal;
{ "pile_set_name": "StackExchange" }
Q: Asp.net core separation of concern using service layer I'm having a problem on what is the best approach to design my service layer and use them in my controller. Here is my concern. Currently I'm using this to delete categories [HttpPost] [ValidateAntiForgeryToken] public IActionResult Delete(List<Guid> ids) { if(ids == null || ids.Count == 0) return RedirectToAction("List"); _categoryService.DeleteCategories(_categoryService.GetCategoryByIds(ids)); _categoryService.SaveChanges(); return RedirectToAction("List"); } my concern is should I just pass ids to DeleteCategories then call the GetCategoryByIds inside the DeleteCategories. And If I'm only going to delete 1 Category, is it better to add another method like DeleteCategory then in the controller check the length of the ids and if it is only 1, use DeleteCategory instead, A: my concern is should I just pass ids to DeleteCategories then call the GetCategoryByIds inside the DeleteCategories. Just pass the ID's to the DeleteCategories method. I wouldn't even bother calling GetCategoryByIds inside of it. There's no need to query the database for all the rest of the category information if you're just planning on deleting it. And If I'm only going to delete 1 Category, is it better to add another method like DeleteCategory then in the controller check the length of the ids and if it is only 1, use DeleteCategory instead I wouldn't bother with creating another method. You could just pass a list with one value in it. There's nothing a DeleteCategory method could do that you can't already do with DeleteCategories.
{ "pile_set_name": "StackExchange" }
Q: Exposing service WSDL in WSO2 API Manager Based on WSO2 Architecture blog posts http://wso2.com/blogs/architecture/2013/05/a-pragmatic-approach-to-the-api-faade-pattern/ http://wso2.com/blogs/architecture/2013/05/implementing-an-api-faade-with-the-wso2-api-management-platform/ I tried to publish API, but exposed WSDL is direct link to back-end ESB. I planned to expose to outer Internet just API Manager so all calls will be proxied through it. Access to ESB should be limited to internal services and not to public. Did I something wrong in configuration or API Manager doesn't support this function? I use WSO2 API Manager 1.4.0 and WSO2 ESB 4.7.0. A: DO NOT expose the WSDL of ESB proxy service. The use case for exposing wsdl to allow users to get to know the service contract. You can host the wsdl in a separate location and provide that in the APIManager. But i think, when we host a WSDL from APIManager, it's port bindings need to be changed according to the gateway node.SO,the requests will be routed via gateway..But that feature is not available in the released versions..We will consider that in the future release.
{ "pile_set_name": "StackExchange" }
Q: R: Find unique vectors in list of vectors I have a list of vectors list_of_vectors <- list(c("a", "b", "c"), c("a", "c", "b"), c("b", "c", "a"), c("b", "b", "c"), c("c", "c", "b"), c("b", "c", "b"), c("b", "b", "c", "d"), NULL) For this list I would like to know which vectors are unique in terms of their elements. That is, I would like the following output [[1]] [1] "a" "b" "c" [[2]] [1] "b" "b" "c" [[3]] [1] "c" "c" "b" [[4]] [1] "b" "b" "c" "d" [[5]] [1] NULL Is there a function in R for performing this check? Or do I need do a lot of workarounds by writing functions? My current not so elegant solution: # Function for turning vectors into strings ordered by alphabet stringer <- function(vector) { if(is.null(vector)) { return(NULL) } else { vector_ordered <- vector[order(vector)] vector_string <- paste(vector_ordered, collapse = "") return(vector_string) } } # Identifying unique strings vector_strings_unique <- unique(lapply(list_of_vectors, function(vector) stringer(vector))) vector_strings_unique [[1]] [1] "abc" [[2]] [1] "bbc" [[3]] [1] "bcc" [[4]] [1] "bbcd" [[5]] NULL # Function for splitting the strings back into vectors splitter <- function(string) { if(is.null(string)) { return(NULL) } else { vector <- unlist(strsplit(string, split = "")) return(vector) } } # Applying function lapply(vector_strings_unique, function(string) splitter(string)) [[1]] [1] "a" "b" "c" [[2]] [1] "b" "b" "c" [[3]] [1] "c" "c" "b" [[4]] [1] "b" "b" "c" "d" [[5]] [1] NULL It does the trick and could be rewritten as a single function, but there must be a more elegant solution. A: We can sort the list elements, apply duplicated to get a logical index of unique elements and subset the list based on that list_of_vectors[!duplicated(lapply(list_of_vectors, sort))] #[[1]] #[1] "a" "b" "c" #[[2]] #[1] "b" "b" "c" #[[3]] #[1] "c" "c" "b" #[[4]] #[1] "b" "b" "c" "d" #[[5]] #NULL
{ "pile_set_name": "StackExchange" }
Q: Should I do a direct upgrade from 16.04 to 19.04? I have a laptop running 16.04 and plan to upgrade to 19.04 in a few weeks and I was wondering if it matters if I directly upgrade to it, if I should first upgrade to 18.04 in preparation, or just do a complete clean install. Yes, I know a complete clean install is often recommended, but it is necessary because of the 3 year jump? Options: Directly to 19.04 18.04, then upgrade to 19.04 Clean Install A: There is no way to upgrade directly from 16.04 to 19.04 Ubuntu only allows upgrade to the immediately next version with one exception. The exception is for Long Term Support (LTS) versions. You can upgrade one LTS version to the immediate next LTS version as well. Ubuntu 16.04 is LTS When Ubuntu 16.10 came out in October of 2016, you could upgrade Ubuntu 16.04 LTS to 16.10 (non-LTS). However, the non-LTS versions are supported only for 9 months. That is, in July of 2017 Ubuntu 16.10 reached the end of its life. From that point onward you couldn't upgrade Ubuntu 16.04 LTS to any non-LTS versions. If you upgrade from 16.04 LTS to 18.04 LTS, there is still no direct way to get to 19.04. The only non-LTS upgrade from 18.04 LTS was to 18.10. So you will have to get to 19.04 in three steps: 16.04 LTS > 18.04 LTS > 18.10 non-LTS > 19.04 non-LTS. One option is to upgrade to 18.04 LTS. I recommend this, as non-LTS versions reach the end of life in a short nine months. After the end of life, Ubuntu 19.04 will not get any security (or other) updates. If you don't upgrade Ubuntu 19.04 to 19.10 within the first three months after 19.10 comes out in October of 2019, then you will be left with an obsolete version of Ubuntu and no path to upgrade it any further (other than a clean install). LTS get released every two years. Once you are in Ubuntu 18.04 LTS, you will able to upgrade to 20.04 LTS in next April. Other option is to clean Install Ubuntu 19.04 You can backup your data and install Ubuntu 19.04 when the final version is released later this month. Hope this helps
{ "pile_set_name": "StackExchange" }
Q: Re-populating a JList on an ActionListener event Depending on what they choose in the JComboBox I want the JList to show different strings, not sure how to repopulate a JList though. When searching through the API, still found nothing. Any idea on how you might code this? Im using NetBeans by the way for reference. A: not sure how to repopulate a JList though DefaultListModel model = new DefaultListModel(...); // add items to the model list.setModel( model ); Or you could use the DefaultComboBoxModel which would allow you to create with model with a Vector or Array.
{ "pile_set_name": "StackExchange" }
Q: Elementos em uma nova linha quando atingir uma determinada quantidade Eu tenho um código no qual tem o objetivo de gerar alguns elementos <td> (células) na tabela e se a linha onde se encontra os elementos <td> atingir uma determinada quantidade de elementos <td> (no qual é 10) é criado uma nova linha com o elemento tr e insere o restante dos elementos <td> nessa nova linha, caso atigir novamente 10 elementos <td> é repetido novamente tudo de novo: let table = document.querySelector('table'); // Criar inicialmente o elemento tr. let tr = document.createElement('tr'); table.appendChild(tr); // Gerar 20 elementos td para extrapolar a quantidade máxima. for (let t = 1; t <= 20; t ++) { let td = document.createElement('td'); // Inserir o conteúdo do incremento no td. td.innerHTML = t; let trChild = document.querySelector('tr'); // Verificar se o número de filhos é maior do que 10. // Se sim criar um novo elemento tr e inserir os td. if (trChild.childElementCount > 10) { tr = document.createElement('tr'); tr.appendChild(td); } else { // Se não continuar no tr atual. tr.appendChild(td); } } table, td { border: 1px solid #505050; border-collapse: collapse; padding: 10px; font-family: sans-serif; font-size: 1.1em; } <table> </table> Mas vejo que a minha lógica está meio que errada, onde eu estou errando e o que eu posso fazer para corrigir? A: Você esquece de aninha-lo na table quando é criada, e a contagem também dá errada por conta do operador > que só retorna true quando já há mais 1, então correto é < 11 ou == 10. let table = document.querySelector('table'); // Criar inicialmente o elemento tr. let tr = document.createElement('tr'); table.appendChild(tr); // Gerar 20 elementos td para extrapolar a quantidade máxima. for (let t = 1; t <= 20; t ++) { let td = document.createElement('td'); // Inserir o conteúdo do incremento no td. td.innerHTML = t; // Verificar se o número de filhos é maior do que 10. // Se sim criar um novo elemento tr e inserir os td. if (tr.childElementCount == 10) { tr = document.createElement('tr'); table.appendChild(tr); } // adiciona na nova referencia do tr tr.appendChild(td); } table, td { border: 1px solid #505050; border-collapse: collapse; padding: 10px; font-family: sans-serif; font-size: 1.1em; } <table> </table> Espero ter ajudado :)
{ "pile_set_name": "StackExchange" }
Q: How do you find the nth node in a binary tree? I want to find the nth node/element in a binary tree. Not the nth largest/smallest, just the nth in inorder order for example. How would this be done? Is it possible to keep it to one function? Many functions employ an external variable to keep track of the iterations outside of the recursion, but that seems... lazy, for lack of a better term. A: You can augment the binary search tree into an order statistic tree, which supports a "return the nth element" operation Edit: If you just want the ith element of an inorder traversal (instead of the ith smallest element) and don't want to use external variables then you can do something like the following: class Node { Node left Node right int data } class IterationData { int returnVal int iterationCount } IterationData findNth(Node node, IterationData data, int n) { if(node.left != null) { data = findNth(node.left, data, n) } if(data.iterationCount < n) { data.iterationCount++ if(data.iterationCount == n) { data.returnVal = node.data return data } else if(node.right != null) { return findNth(node.right, data, n) } else { return data } } } You'll need some way to return two values, one for the iteration count and one for the return value once the nth node is found; I've used a class, but if your tree contains integers then you could use an integer array with two elements instead.
{ "pile_set_name": "StackExchange" }
Q: Prevent keyboard input but allow automatic scanner input on textbox Hello everyone I'm using a RFID scanner that puts the scanned code in whatever text field available at scanning time. For instance, it could put the text inside a cell in Excel or in the address bar of a web browser. I made an application with a textbox that receives the input sent by the scanner, but I want to disable user-input (keyboard). I tried setting the textbox property "read only" to true, but then the text is not displayed in the textbox. How can I do that? Thanks in advance :) A: Most barcode scanners are just keyboard input. This would could be done via intercepting HID calls or intercepting key press events in the input box. I wouldn't expect that to work well, but good luck.
{ "pile_set_name": "StackExchange" }
Q: Sorting CSV in Python I assumed sorting a CSV file on multiple text/numeric fields using Python would be a problem that was already solved. But I can't find any example code anywhere, except for specific code focusing on sorting date fields. How would one go about sorting a relatively large CSV file (tens of thousand lines) on multiple fields, in order? Python code samples would be appreciated. A: Python's sort works in-memory only; however, tens of thousands of lines should fit in memory easily on a modern machine. So: import csv def sortcsvbymanyfields(csvfilename, themanyfieldscolumnnumbers): with open(csvfilename, 'rb') as f: readit = csv.reader(f) thedata = list(readit) thedata.sort(key=operator.itemgetter(*themanyfieldscolumnnumbers)) with open(csvfilename, 'wb') as f: writeit = csv.writer(f) writeit.writerows(thedata) A: Here's Alex's answer, reworked to support column data types: import csv import operator def sort_csv(csv_filename, types, sort_key_columns): """sort (and rewrite) a csv file. types: data types (conversion functions) for each column in the file sort_key_columns: column numbers of columns to sort by""" data = [] with open(csv_filename, 'rb') as f: for row in csv.reader(f): data.append(convert(types, row)) data.sort(key=operator.itemgetter(*sort_key_columns)) with open(csv_filename, 'wb') as f: csv.writer(f).writerows(data) Edit: I did a stupid. I was playing with various things in IDLE and wrote a convert function a couple of days ago. I forgot I'd written it, and I haven't closed IDLE in a good long while - so when I wrote the above, I thought convert was a built-in function. Sadly no. Here's my implementation, though John Machin's is nicer: def convert(types, values): return [t(v) for t, v in zip(types, values)] Usage: import datetime def date(s): return datetime.strptime(s, '%m/%d/%y') >>> convert((int, date, str), ('1', '2/15/09', 'z')) [1, datetime.datetime(2009, 2, 15, 0, 0), 'z']
{ "pile_set_name": "StackExchange" }
Q: Jmeter : using While Controller for failed request retries, ThreadGroup loop count not working I added a While Controller and try to send this request multiple times in case if it doesn't work the first time or simply just trying to implement retry logic. Thread Group configurations are : Threads (Users) - 1 Loop - 10 Issue: As per thread group config, it should run ( while controller * 10 ) but it only runs 1 time. In my Bean PostProcessor : vars.remove("response_code"); vars.put("response_code",prev.getResponseCode()); In WhileController : ${__jexl3(${response_code} != 200 && ${retries} < 3,)} Any help would be appreciated! A: On 2nd iteration of your Thread Group your ${response_code} variable becomes 200 therefore it will not enter the While Loop. The solution is to reset both ${response_code} and ${retries} variables to 0 Add JSR223 Sampler to be the first Sampler in your Thread Group Put the following code into "Script" area: SampleResult.setIgnore() vars.put('response_code', '0') vars.put('retries', '0') Also be aware that starting from JMeter 3.1 you shouldn't be using Beanshell so consider migrating from the Beanshell PostProcessor to the JSR223 PostProcessor. More information: Apache Groovy - Why and How You Should Use It
{ "pile_set_name": "StackExchange" }
Q: async_read doesn't read data sent from telnet This is my current code for the server. I connect to the server using telnet. #include <cstdlib> #include <iostream> #include <boost/bind.hpp> #include <boost/asio.hpp> using boost::asio::ip::tcp; class Connection { public: Connection(boost::asio::io_service& io_service) : socket_(io_service) { } void start() { AsyncRead(); } tcp::socket& socket() { return socket_; } private: void AsyncRead() { boost::asio::async_read(socket_, boost::asio::buffer(data_, max_length), [this](boost::system::error_code ec, std::size_t length) { if (!ec) { std::cout << data_ << std::endl; } }); } tcp::socket socket_; enum { max_length = 1024 }; char data_[max_length]; }; class server { public: server(boost::asio::io_service& io_service, short port) : io_service_(io_service), acceptor_(io_service, tcp::endpoint(tcp::v4(), port)) { start_accept(); } private: void start_accept() { Connection* connection = new Connection(io_service_); acceptor_.async_accept(connection->socket(), [this, connection](boost::system::error_code ec) { //std::cout << ec.message() << std::endl; if(!ec) { std::cout << "Connected." << std::endl; connection->start(); } else { delete connection; } start_accept(); }); } boost::asio::io_service& io_service_; tcp::acceptor acceptor_; }; int main(int argc, char* argv[]) { try { boost::asio::io_service io_service; server s(io_service, 7899); io_service.run(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; } Instead of async_read I use async_read_some I can get the first message sent from telnet and thats it. Any suggestions on what I am doing wrong ? Thanks. A: async_read will read the number of bytes specified in the length parameter. You aren't seeing the first message because async_read is still waiting to read max_length bytes. This question discusses similar behaviour
{ "pile_set_name": "StackExchange" }
Q: Visual Studio 2012 Professional - unit tests not working After building my application I get in the test output: ------ Discover test started ------ Exception has been thrown by the target of an invocation. ========== Discover test finished: 1 found (0:00:01,457) ========== I'm using Visual Studio 2012 Professional on win7 32bit. Tried: repairing vs2012 reinstalling vs2012 changing configurations changing path to Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll Nothing worked... Any ideas? Previously I worked with Visual Studio 2010 Express edition. Application is correct - I made just simple class library and test project just to be sure it works. And it doesn't. The same project works with my student premium version. A: Ok I looked again in http://connect.microsoft.com/visualstudio and tried also: moving project files to another location than default changing security rights in files and folders properties run vs as administrator Nothing really worked until i found by chance vs2012 update 1 (under the "Additional Software" category) After download and installation everything works fine.
{ "pile_set_name": "StackExchange" }
Q: What are the differences between a OpenGL shader code written in a .cg file and another in a vsh/fsh file? I'm a OpenGL ES 2.0 beginner and I don't understand why are different types of code for shaders. In particular, the differences between .cg and .vsh / .fsh. A: Cg is a shading language owned and operated by NVIDIA. GLSL is the shading language for OpenGL. Cg works by being compiled into some form of GLSL, based on a "profile" that represents the GLSL version and shader stage type. If you're using OpenGL ES, you should be ignoring Cg. You can't use Cg in OpenGL ES, because ES's version of GLSL has requirements that Cg can't fulfill. So if you're seeing some tutorial using Cg, ignore it. The extension names are entirely irrelevant. Use whatever extension is clearest to you; OpenGL doesn't read files, so it's up to you to feed shader strings to glView.
{ "pile_set_name": "StackExchange" }
Q: Time complexity of algorithm with random component (Gillespie Algorithm) I'm trying to find the time complexity of the Gillespie Algorithm. General algorithm can be found: Here More extended version: Here The assumption is that the number of reactions and the number of proteins is constant. This might allow me to calculate the time complexity by the time variable alone. But I get stuck since the time increase each iteration is based on a random value. Let me elaborate (removed non relevant code): So this is the general loop, each iteration the reactions are updated, then the currentTime is updated. currentTime = 0.0; while(currentTime < timeEnd) { reactions->calcHazard(); currentTime += this->getNextTime(); } The function getNextTime calculates a new time. double Gillespie::getNextTime() { double randVal; randVal = ((double) rand() / (double)(RAND_MAX)); while ( randVal == 0) { randVal = ((double) rand() / (double)(RAND_MAX)); } return ((1.0/reactions->getSum())*(log(1.0/randVal))); } The calculation of a the new time size is based on a random value R. The other variable component here is the result of reactions->getsum. The return value of this function is sum(k*A(t)) Where k and A(t) are both vectors, k is the probability for each reaction and A(t) is the number of proteins at time t. Better explanation about the time increase might be provided by page 7 of previous link. Is it possible to say anything about the time complexity of this (iteration from tStart -> tEnd)? Or is this impossible without also including information about about #proteins and #reactions? A: It's O(n). You don't really need to calculate the expected return value of getNextTime(). It's enough to know that its return doesn't change in response to the simulation running. Let's assume your code iterates that loop N times for a 1 hour simulation. It's pretty obvious that these are equivalent... timeEnd = currentTime + 2hours; while (currentTime < timeEnd) { ... } // ??? iterations is equivalent to timeMid = currentTime + 1hour; timeEnd = currentTime + 1hour; while (currentTime < timeMid) { ... } // N iterations while (currentTime < timeEnd) { ... } // <=N iterations So, it iterates the loop approx 2N times for a 2 hour simulation. The assumption is that the number of reactions and the number of proteins is constant That is useful assumption. Basically, that means that getNextTime() will not systematically increase or decrease as the simulation runs. If the return value of getNextTime() decreased over the course of the simulation (meaning A(t) was increasing over the course of the simulation), then the second loop would take more iterations than the first one. You can probably make that assumption anyways if the system hits equilibrium at some point (that's inevitable right? I'm not a chemist). Because then A(t) is constant, since that's... what equilibrium is.
{ "pile_set_name": "StackExchange" }
Q: Ignoring a certain file type in a .net "filter" I made a program which uses a filesystemwatcher component, but it seems to record absolutely EVERY change made, and I want to set it to ignore some file types. How can I set the filter to ignore certain types? For example, .LOG files. I don't want it telling me that that file updates, cause it does it every second practically. Even better, is there any way to make it ignore some folders? Thanks for the help! A: I don't think you can exclude certain file types using only a Filter. I would suggest that you add a test at the start of each of your handlers to skip any processing of files which you don't want to process. The FileSystemWatcher watches for changes to all files and folders within a folder, including files and folders within sub-directories. If you want to ignore changes to your log files, for example, it might be a better option to move the log directory to a folder which is not within the path that you are watching.
{ "pile_set_name": "StackExchange" }
Q: QGIS feature form : Force attribute to save as uppercase For example I have feature form with colum name NAME (with names of contries). I want that all counties names are in capital letters. As users enter the names in lowercase, uppercase, mixed ... I am setting all nemes to uppercase on this way: attributre table -> Field calculator -> Expression -> upper("NAME") and this is working fine, but the idea is that I don't have to repeat it every time, is there any way to save ('field properties') in the project so that no matter what the user enters, it will be capitalized and saved into table. A: The easiest way is to set up two NAME field (NAME_1 and NAME_2 for exemple). The first being directly fill by the user, the second set as "hidden" in the feature form and with a default value set to upper("NAME_1"), don't forget to check the "Apply default value on update" box. This will give you a field with the country name in uppercase but you will also have an useless second field with the country name in mixed case... A: You could use python to check each time the attribute value is changed or added and convert it to uppercase if necessary. According to the PyQGIS API docs the attributeValueChanged signal is emitted whenever an attribute value change is done in the edit buffer. And the featureAdded signal is emitted when a new feature has been added to the layer. You can use the Project Macros to connect a functions to the attributeValueChanged and featureAdded events each time the project is loaded. Here's some quick code I used to test that it works: from qgis.core import QgsProject lyrName = "test" fldNum=5 def openProject(): lyr=QgsProject.instance().mapLayersByName(lyrName)[0] lyr.attributeValueChanged.connect(ChkName) lyr.featureAdded.connect(ChkNew) pass def saveProject(): pass def closeProject(): pass def ChkName(fid,idx,v): if (idx==fldNum): if(not v.isupper()): layers=QgsProject.instance().mapLayersByName(lyrName) layer = layers[0] layer.changeAttributeValue(fid, fldNum, v.upper()) layer.updateFeature(layer.getFeature(fid)) def ChkNew(fid): layers=QgsProject.instance().mapLayersByName(lyrName) layer = layers[0] f = layer.getFeature(fid) v = f.attribute(fldNum) if(not v.isupper()): layer.changeAttributeValue(fid, fldNum, v.upper()) layer.updateFeature(layer.getFeature(fid)) Replace the text in the Project Macros with the code above and change the value of lyrName to the name of your layer, and change the fldNum to the column number (starting from zero) of the "NAME" column. I swear initially I saw the value changing to uppercase as soon as I tabbed out of the field, but now I don't see the changes until I close and reopen the feature form/attribute table. A: In the end I found a simple solution. if someone is going to have the same problems, here is the solution: QGis 3.X Layer properties -> select the attribute (that you want to capitalize,or whatever) -> Defaults -> set default value to upper( "NAME") , check Apply default value on update -> apply
{ "pile_set_name": "StackExchange" }
Q: How to check if Javascript is activated from Firefox extension? I haven't found any info on that. I basically need to know from a Firefox extension if the browser has javascript enabled. Is that possible? I am totally new to programming FF extensions -- actually this is my first one and among the requirements is this one I haven't been able to figure out. A: Via @ChristianSonne: You could try require("preferences-service").get("javascript.enabled") in Jetpack-style addons.
{ "pile_set_name": "StackExchange" }
Q: Best practice for selecting month/year I have a form where users can choose a month and year to display a series of reports. (there is no need to choose the day - all the reports for that month will be displayed) What is the best practice for this? I can think of 3 options: Two drop downs (one for the month, one for the year) and a "GO" button. Pro: Makes it easier to change the year only ("let's see what was going on in the same month last year") Con: Requires another click on "GO" to refresh the page One drop down only, where months are listed as "JAN 2012", "FEB 2012" etc. Pro: Can trigger an automated page refresh when the date is changed Con: It is potentially difficult to scroll down or up many months Date picker with just month/year Pro: Very intuitive Con: Requires JavaScript enabled What do you think? A: I think is important to point out that HTML 5 has a new input type=month which seems to be exactly what you want. And altought most browsers doesn't support it yet that doesn't mean we should overlook that. Because they'll probably implement that in the near future, and then most users will be presented with their most familiar and fast UI for each device (think of smartphones presenting its number keyboard on the year textbox for instance). So I would use a polyfill to workaround non-supporting browsers. The best I could find was Webshims lib: http://afarkas.github.io/webshim/demos/#Forms-forms-ext On most browser you will see this polyfill in action: On Google Chrome (for instance) you will see this: At first glance you can think they could look better, but if you try them out you'll see that both are way better than most solutions out there. With excellent support for keyboard and mouse, no dropdown for years (a spinner is usually better unless you have very few years to choose from), and lots of functionality to make your pick easier. And what about customization? Or keeping the same look and feel on every browser (and maybe not on mobile browsers)? Webshims can handle that too: https://stackoverflow.com/questions/9067536/html5-forms-with-polyfills-is-it-worth-it A: Dropdowns and textfields are always faster, assuming that the user can type somewhat quickly and can Tab through the form, and especially if s/he will be fetching multiple reports. A date picker is intuitive and fail-safe, but the clicks add up if you're thinking of a standard picker; the ones that I've used only let me scroll through months and years. For example, if the current month and year are selected by default and I want the report from August 2010, I'd have to click three times to reach August (from November) and then click three more times to reach 2010 (from 2013). The click-count will really add up if for some reason I need all the monthly reports for 2010 and I have to start from November 2013 each time. Because I type over 70 wpm, my preference is actually a dropdown for the months (preferably with the months listed as numbers) and either a dropdown or textfield for the year. In case any of you don't know, you can select an item from a dropdown menu without clicking it by Tabbing to said menu and then typing the option that you want. The user needs to be somewhat quick in typing "11" to avoid selecting "1" or typing "Jul" to select July instead of June. Numbers are easier to type quickly, obviously. I've used some forms that don't allow me to quick-type for dropdown menus; in most cases its custom dropdown styling that's the cause. One site doesn't even let me press Enter to submit its form. Don't disable either function.
{ "pile_set_name": "StackExchange" }
Q: Building an Excel API I tried unzipping the .xlsx file and could find some files in it. But I am not sure as to what these files contain and how they are related. Where can I find the DOCS for creating spreadsheetML? A: You can find the full specification of the Open XML file formats here. The specification contains a description of the files that are contained in an Open XML file package (such as an XLSX file), their contents and relationships. There are also a lot of great articles and tutorials about Office Open XML formats at the OpenXML Developer Blog and Eric White's Blog. For learning Office Open XML, I would recommend starting with this series of articles and this to learn how SpreadsheetML (the XLSX file format) works.
{ "pile_set_name": "StackExchange" }
Q: How to Reel parts from Cut-Tape? How does Digi-Key make Digi-Reels (or Mouser make Mouser-Reels, or whatever)? That is to say, given parts in Cut-Tape form, what tools and additional materials are needed to add a leader to support spooling onto a tape feeder? The picture below shows some kind of foil that bonds the leader to the cut tape in such a way as to keep the pitch consistent through the join. Is it plausible / cost-effective to do this on my own instead of paying a reeling fee to distributors? A: If the junction is not clean, the edge will jam the feeder. Also, the brass will often stick on the sprocket. It does work occasionally but you can also be in for some fun clearing the feeder. Hopefully it isn't on customer tour day because it isn't pretty. A: They use a cut tape splicer - this company seems to sell a few, along with the necessary supplies: http://www.tapesplice.com
{ "pile_set_name": "StackExchange" }
Q: Detecting Firefox Australis from CSS or JavaScript Since Firefox Australis is now on Nightly channel, I want to make my addon compatible with this new UI. I was wondering how I can detect if user is on Firefox Australis from both CSS and JavaScript. For CSS part I am interested to optimize my toolbar icon such that it is compatible with older versions of Firefox as well. A: From (privileged) JavaScript if("gCustomizeMode" in window){ //Australis code }
{ "pile_set_name": "StackExchange" }
Q: From Perl to Java I am trying to solve some online puzzle finding the largest prime factor of a very large number (7393913335919140050521110339491123405991919445111971 to be exact). In my search for a solution I stumbled upon this Perl code (from here): use strict; use warnings; my $magic = <number>; sub largestprimef($); sub max($$); print largestprimef($magic); sub largestprimef($) { my $n = shift; my $i; return largestprimef(max(2, $n/2)) if($n % 2 == 0); my $sn = int( sqrt($n) ); for ( $i = 3 ; $i <= $sn ; $i += 2 ) { if ( $n % $i == 0 ) { last; } } if ( $i > $sn ) #loop ran over, means the number is prime { return $n; } else { return max( $i, largestprimef( $n / $i ) ); } } sub max($$) { return ( sort { $a <=> $b } (@_) )[1]; } Now that algorithm seemed to work! Small problem with Perl is that it doesn't accept really big numbers. So I rewrote my $magic = <number>; to my $magic = Math::BigInt->new(' <number> '); but that just runs for ages and ages. So I rewrote it to Java (in which I'm a bit more familiar) which resulted in this: static final BigInteger two = new BigInteger( "2" ); public static void main( String[] args ) { BigInteger number = new BigInteger( "<number>" ); System.out.println( goAtIt( number ) ); } static BigInteger goAtIt( BigInteger prime ) { if ( isEven( prime ) ) return goAtIt( prime.divide( two ).max( two ) ); BigInteger sqrt = sqrt( prime ); BigInteger comp = new BigInteger( "3" ); while (sqrt.compareTo( comp ) > 0) { if ( prime.remainder( comp ).equals( BigInteger.ZERO ) ) break; comp = comp.add( two ); } if ( comp.compareTo( sqrt ) > 0 ) return prime; return comp.max( goAtIt( prime.divide( comp ) ) ); } With as auxiliaries (which seem to be fine): static boolean isEven( BigInteger number ) { return number.getLowestSetBit() != 0; } static BigInteger sqrt( BigInteger n ) { BigInteger a = BigInteger.ONE; BigInteger b = new BigInteger( n.shiftRight( 5 ).add( new BigInteger( "8" ) ).toString() ); while (b.compareTo( a ) >= 0) { BigInteger mid = new BigInteger( a.add( b ).shiftRight( 1 ).toString() ); if ( mid.multiply( mid ).compareTo( n ) > 0 ) b = mid.subtract( BigInteger.ONE ); else a = mid.add( BigInteger.ONE ); } return a.subtract( BigInteger.ONE ); } But my results are always off... and my Perl is not really that good to reverse-engineer the original code. Does anyone have a clue on what I'm missing? ==UPDATE: problem is (somewhat) solved by workaround A: To answer the translation question... Your Java translation is very close. It only has one problem - your while loop condition should be >= 0, rather than >0. With that amendment, it will work. As it is - it will output the second largest prime factor in a some cases. To show this - try it on 1148487369611039 - which has prime factors 104717, 104723 & 104729. Without the correction - it outputs 104723, with the correction, you get the right answer: 104729 Comment on algorithm As others have noted in comments - this isn't a particularly fast way to do what you want. In fact that's an understatement - it's very slow. On my box it took over 3 minutes to find the correct answer (459905301806642105202622615174502491)1, but it would take a very long time (maybe 500 years, or that kind of order), to prove that number was prime by simply trial dividing every odd number up to its square root (which is what the algorithm does). You could use all kinds of tricks to get faster, depending how certain you want to be of getting the answer. One would be to pre-test any candidates for primality - e.g. inserting a test using BigInteger.isProbablePrime() with high certainty as a test in goAtIt() and returning early if you get a very big prime early in the process. If you don't like the probabilistic element of that, you could roll your own Miller-Rabin primality deterministic test. You could also build tables of primes and only ever use those in any trial divisions and / or lookups. You might also consider the Pollard-Strassen algorithm 1(I put an output just after the while loop in goAtIt() to check when it actually found the solution) Note on Perl big numbers Small problem with Perl is that it doesn't accept really big numbers I think its worse than that because Perl will implicitly turn the large integer into a double precision floating point if you simply replace my $magic = <number>; with my $magic = 7393913335919140050521110339491123405991919445111971; So - it would give the wrong answer rather than throwing an error as demonstrated on ideone here. Rather nasty, as the algorithm works fine for small numbers and could lull unwary users into a false sense of security if used with larger inputs...
{ "pile_set_name": "StackExchange" }
Q: Bool issue - changing value Morning all. I have the following method that I use to to try and bring back a bool: public static bool GetShowCatSubProdStatus(string memberid, string username) { MyEnts showcatsubprodstatus = new MyEnts.PDC_VDSOREntities35(); var r = from p in showcatsubprodstatus.tblKeyAccountInfoes where p.MemberID == memberid && p.UserName == username select p.ShowCatSubProd; return r.Any(); } When I call this method and debug it, the result is correct. However, when I run this method in a page load, although the method result returns the correct result, when I step through, the boolean value changes! bool showcatsubprodstatus = MyEnts.GetShowCatSubProdStatus(_memberid, _username); if (showcatsubprodstatus != true) { panCatSubProd.Visible = false; } Can someone explain what is going on here and how I can solve this puzzler?! PS: Apologies for being thick. EDIT - Right, narrowed it down to the variable. It is always return 'true' regardless of the method result?!?! A: This piece of code returns an IEnumerable<bool> : var r = from p in showcatsubprodstatus.tblKeyAccountInfoes where p.MemberID == memberid && p.UserName == username select p.ShowCatSubProd; By calling the .Any() you are asking it if there are any items in the IEnumerable. If there are you return true; That is why you always get true back, because it always finds something. The solution Either you go for calling .SingleOrDefault() which returns the only element there is (if there is one) or returns the default value of that type. var r = from p in showcatsubprodstatus.tblKeyAccountInfoes where p.MemberID == memberid && p.UserName == username select p.ShowCatSubProd; return r.SingleOrDefault(); //assuming p.ShowCatSubProd is a bool and not a Nullable<bool> else you need to adjust your return type or cast it to a boolean using .GetValueOrDefault().
{ "pile_set_name": "StackExchange" }
Q: How do I add a specific tableview cell into a tableview? I have looked through stackoverflow and there are some questions that seem to brush the sides of this but none that actually answer it. The closest I have found is this question here but this isn't what I am after. I have a tableview which is filled with tableview cells (lets call them A cells). When I click one of these cells I want to insert another custom tableview cell below it (B cells). The other answers I have had always involved hiding and revealing cells but I want to be able to click multiple times to keep adding more of these custom cells. This is what I am currently working with: -(id) initWithGuestNumber: (NSInteger *) numberOfPeople { self = [super initWithNibName:Nil bundle:Nil]; if (self) { numberOfGuests = * numberOfPeople; guestArray = [NSMutableArray new]; for (NSInteger i = 1; i <= numberOfGuests; i++) { BGuest * guest = [BGuest alloc]; NSMutableArray * array = [NSMutableArray new]; // Set up guest object guest.name = [NSString stringWithFormat:@"Person %li", (long)i]; guest.mealArray = array; guest.priceArray = array; guest.cost = 0; [guestArray addObject:guest]; } } return self; } - (void)viewDidLoad { [super viewDidLoad]; // Set up custom tableview cells [self.tableView registerNib:[UINib nibWithNibName:@"BHeaderCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"HeaderCell"]; [self.tableView registerNib:[UINib nibWithNibName:@"BContentCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"ContentCell"]; } - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView_ { // Want a section for each guest return guestArray.count; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { BGuest * guest = guestArray[section]; // Want a row in the section for each meal added to each guest - by clicking the row return guest.mealArray.count + 1; } -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { BHeaderCell * headerCell = [tableView dequeueReusableCellWithIdentifier:@"HeaderCell"]; BContentCell * contentCell = [tableView dequeueReusableCellWithIdentifier:@"ContentCell"]; // Setting the delegate programatically to set the textfield BGuest * guest = guestArray[indexPath.section]; if (indexPath.row == 0) { headerCell.guestNameTextField.delegate = headerCell; headerCell.guestNameTextField.placeholder = guest.name; headerCell.guestMealPriceLabel.text = [NSString stringWithFormat:@"£%.2f", guest.cost]; } else { contentCell.mealNameTextField.delegate = contentCell; contentCell.mealCostTextField.delegate = contentCell; contentCell.mealNameTextField.text = @"Meal Name"; contentCell.mealCostTextField.text = @"Meal Cost"; } return headerCell; } -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { BGuest * guest = guestArray[indexPath.section]; NSString * first = @"first"; [guest.mealArray addObject:first]; [self.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:indexPath.row + 1 inSection:indexPath.section]] withRowAnimation:UITableViewRowAnimationFade]; [tableView deselectRowAtIndexPath:indexPath animated:YES]; } So currently when I click a row a new row is added below but it is the same custom cell as the row clicked (clicking an A cell adds another A cell underneath). What I want is to insert a new custom cell underneath when the row is clicked (click an A cell and a B cell is inserted underneath). Is there any way to do this using insertrowatindexpath or is there a better/different way? Thanks for and help you guys/girls can give A: As soon as I clicked post question it suddenly popped out in front of me. Currently in my code I was always returning the headerCell (A cell) I switched round the code slightly in the cellForRowAtIndex and it started working: -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { // Setting the delegate programatically to set the textfield BGuest * guest = guestArray[indexPath.section]; if (indexPath.row == 0) { BHeaderCell * headerCell = [tableView dequeueReusableCellWithIdentifier:@"HeaderCell"]; headerCell.guestNameTextField.delegate = headerCell; headerCell.guestNameTextField.placeholder = guest.name; headerCell.guestMealPriceLabel.text = [NSString stringWithFormat:@"£%.2f", guest.cost]; return headerCell; } else { BContentCell * contentCell = [tableView dequeueReusableCellWithIdentifier:@"ContentCell"]; //contentCell.mealNameTextField.delegate = contentCell; //contentCell.mealCostTextField.delegate = contentCell; contentCell.mealNameTextField.text = @"Yeah"; contentCell.mealCostTextField.text = @"£1.50"; return contentCell; } } Hopefully this will save people the time it took me to spot in the future
{ "pile_set_name": "StackExchange" }
Q: Flexbox on IOS scrolls differently I noticed the scrolling functionality is different when using a flexbox based layout vs a position: fixed footer. The fixed footer is much smoother and shows a scrollbar. Flexbox isn't smooth at all, and does not show the scrollbar. I'd much prefer to use flexbox for my layout, but want the nicer scroll. Is there any way to achieve it with flexbox? I'm testing on IOS 10 Iphone 7. Happens on both chrome and safari Flexbox example Fixed footer example HTML: <html> <head> <meta name=viewport content="width=device-width,initial-scale=1"> </head> <body> <div id='main'> ...lots of content so it would scroll </div> <nav class="footer">footer</nav> </body> </html> Flexbox method: html, body { height: 100%; margin: 0; padding: 0; } body { -webkit-flex-direction: column; flex-direction: column; display: flex; } #main { -webkit-flex: 1 1 auto; overflow-y: auto; min-height: 0px; } .footer { height: 72px; min-height: 72px; background-color: blue; } Fixed footer method: html, body { height: 100%; margin: 0; padding: 0; } #main { padding-bottom: 72px; } .footer { position: fixed; bottom: 0; height: 72px; min-height: 72px; width: 100%; background-color: blue; } A: there's nothing to do with Flexbox.it's only the problem about overflow.so add this : -webkit-overflow-scrolling: touch; will work.
{ "pile_set_name": "StackExchange" }
Q: Is carbonated water unhealthy? I have a coworker who says that drinking soda leads to kidney problems. I did some Googling and while I found a lot of blogs and message board posts saying such, the only credible link I found was this paper, Carbonated beverages and chronic kidney disease, whose abstract reads: Drinking 2 or more colas per day was associated with increased risk of chronic kidney disease. Results were the same for regular colas and artificially sweetened colas. Noncola carbonated beverages were not associated with chronic kidney disease. These preliminary results suggest that cola consumption may increase the risk of chronic kidney disease. I can't read the entire paper, but the abstract makes it sound as if the risk lies more in cola consumption than carbonated water consumption. Is there a scientific consensus on the risks posed by consumption of carbonated water? A: First, regarding general health effects of carbonation, in their 1992 paper Lambert et al compare re-hydration after exercise for carbonated and non carbonated beverages. The paper measures blood plasma levels prior to dehydration and after the administration of test solutions concluding; A major finding of this investigation was that fluid replacement was similar in the carbonated and non-carbonated treatments. ... the similar plasma volume and total plasma protein values at all time points suggest that beverage carbonation did not measurably alter the availability of ingested fluid. Also, Cuomo et al investigate the effects of carbonation on digestion, concluding In patients complaining of functional dyspepsia and constipation, carbonated water increases satiety and improves dyspepsia, constipation and gallbladder emptying. Which may explain why many people use sugarless carbonated beverages (such as sprite) to calm upset stomachs. Also, a particularly interesting paper by Simons et al investigates the oral sensation associated with carbonated beverages, arguing carbonated water excites lingual nociceptors via a carbonic anhydrase-dependent process, in turn exciting neurons in Vc that are presumably involved in signaling oral irritant sensations. Regarding kidney function, beverages with high fructose content may pose a risk whether carbonated or not. Studying rats, Gersch et al find an association between fructose and kidney problems. Next, El-Badrawy et al touch on a distinction between 'cola' and 'un-cola' beverages, finding histopathological effects (I needed a quick wikipedia to understand this refers broadly to tissue damage) from colored soft drinks only. The kidney of rats consuming dark color soft drink showed congestion of interlobular homogenous proteinaceaus casts in some renal tubules (Pict.7). While the kidney of rats consuming orange color showed the previous changes with congestion of the glomerular tufts (Pict. 8). Kidney of rats consuming colorless soft drink revealed no histopathological changes (Pict. 9), meanwhile, kidney of rats consuming mixed soft drink showed vacuolation of endothelial lining the glomerular tuft together with necrobiotic changes of epithelial lining of some renal tubules (Pict .10). Like the original poster, I had trouble finding a credible source clearly attributing health impacts to one or more ingredients in soda individually. Many papers unequivocally argue soft drinks are harmful to health generally, but parsing out the effect of carbonation seems more difficult. Even in a randomized setting, isolating the effect of one substance consumed in tandem with many others poses a challenge. Also, though similar in many ways, humans and rats differ. With these caveats in mind, the research outlined above seems to suggest the primary health risk associated with cola may be attributed to sugar content. That said, none of the literature I reviewed affirmed the negative, i.e. ``carbonated water does not impair kidney function''.
{ "pile_set_name": "StackExchange" }
Q: Google Core IoT Device Offline Event or Connection Status Does anybody know of an easy way to trigger an event when a device on Google Core IoT goes offline? Before I switched to Google's IoT implementation, this was very easily handled by triggering an event when MQTT disconnects, but it seems Google has no easy way of doing this. Does anybody know if there is something planned for this? Who's back do I need to scratch to get them to see that something like this is a basic requirement for IoT device management! Other platforms like AWS and Microsoft already have this implemented (or some way to handle it easily): https://docs.aws.amazon.com/iot/latest/developerguide/life-cycle-events.html Device connectivity(online/offline)status with the Auzure iot hub I wish I had known this before writing all my code and implementing my setup using Google's IoT platform, I guess that's my fault for assuming something so simple and that should be standard for IoT devices would be available. How are you going to compete with other IoT providers if you can't even provide basic offline/online events?! My reply in this SO question shows how I had to write 100+ lines of code just to create a firebase function to check if a device is online (but that still doesn't handle offline events, and is just a hack for something that should be native to ANY IoT service provider!): https://stackoverflow.com/a/54609628/378506 I'm hoping someone else has figured out a way to do this, as i've spent numerous days searching SO, Google, Google Core IoT Documentation, and still have not found anything. Even if MQTT Last Will was supported we could make that work, but even that IS NOT SUPPORTED by Google (https://cloud.google.com/iot/docs/requirements) ... come on guys! A: Your cloud project does have access to the individual MQTT connect/disconnect events, but currently they only show up in the Stackdriver logs. Within the cloud console, you can create an exporter that will publish these events to a Pub/Sub topic: Visit the Stackdriver Logs in the Cloud Console. Enter the following advanced filter: resource.type="cloudiot_device" jsonPayload.eventType="DISCONNECT" OR "CONNECT" Click CREATE EXPORT Enter a value for Sink Name Select Cloud Pub/Sub for Sink Service Create a new Cloud Pub/Sub topic as the Sink Destination The exporter publishes the full LogEntry, which you can then consume from a cloud function subscribed to the same Pub/Sub topic: export const checkDeviceOnline = functions.pubsub.topic('online-state').onPublish(async (message) => { const logEntry = JSON.parse(Buffer.from(message.data, 'base64').toString()); const deviceId = logEntry.labels.device_id; let online; switch (logEntry.jsonPayload.eventType) { case 'CONNECT': online = true; break; case 'DISCONNECT': online = false; break; default: throw new Error('Invalid message type'); } // ...write updated state to Firebase... }); Note that in cases of connectivity loss, the time lag between the device being unreachable and an actual DISCONNECT event could be as long the MQTT keep-alive interval. If you need an immediate check on whether a device is reachable, you can send a command to that device.
{ "pile_set_name": "StackExchange" }
Q: Refactoring Similar Code Across Data Types I am working in Java, inserting data from HashMaps of certain types into a SQL database. It has produced some code like this: for ( String key : strings.keySet() ) { result_set.updateString(key, strings.get(key)); } for ( String key : booleans.keySet() ) { result_set.updateBoolean(key, booleans.get(key)); } for ( String key : dates.keySet() ) { result_set.updateDate(key, dates.get(key)); } I am used to Ruby, where code like this would take up one line and I can't believe I have to do it like this in Java. I must be wrong. Is there a better way? I assume using Generics? I tried using result_set.updateObject(key, object) but it gave me "SQLException: Unable to convert between java.util.Date and VARCHAR." A: Take a look at MyBatis, an SQL Mapper that handles the mapping between POJOs (including Maps and Lists) and SQL. It's saved us a ton of work relative to what it would take to do everything ourselves in raw JDBC.
{ "pile_set_name": "StackExchange" }
Q: Does the JVM / x86 guarantee non-volatile propagation of values across cores? Assuming the following code: class X { private int v = 1; public void set(int v) { this.v = v; } public int get() { return v; } } is there any possibility that by not having marked v as volatile, when calling set(123) its value will not propagate to other cores (that is, their caches and / or main-memory), or is it just a matter of time until that happens? By asking around, the general idea seems to be that sooner or later the value "will get there", so as long as we don't care too much time-preciseness, it's OK to leave the value non-volatile, but I wanted to be formally sure. My understanding is that as there's no acquire / release semantics, the JMM doesn't guarantee this to work, but on the other hand, my (limited) understanding of cache coherence / consistency models (namely, TSO-x86) is that it will necessarily eventually propagate (marking it as volatile would simply put a fence to disallow reorderings in the CPU's store-buffer but other than that it will eventually be propagated to other caches). Regarding this, there's only one point that makes me wonder -- what happens if another core writes something to another variable in the same cache line? Can it in any case overwrite v? Can anyone knowledgeable on the matters give me a more concrete answer? Thanks! A: According the memory model of the JVM there is no happens-before relation in your example. Thus formally there is no gurantee that another thread will see updates to a shared variables ever. Relying on implementation details of a particular JVM and processor architecture does not seem like a good idea to me. What works today in the lab might fail in the field tomorrow. Also note, that eventually might be a very long time as there is no upper bound to it. In fact I've experienced cases where my programme seemingly blocked due to missing volatile annotations and had to be restarted.
{ "pile_set_name": "StackExchange" }
Q: Grails flash message w/ gritter Normally the message appears by using <g:if test='${flash.message}'> <div>${flash.message}</div> </g:if> whenever an action is triggered. How do you set it to appear like a gritter notification? So that say i click a submit button <button class="btn btn-primary" data-dismiss="modal" type="submit">Log me in</button> A pop-up on the upper right will appear. Here's the gritter snippet. I find it hard since im new to javascript $('#flash-message').click(function(){ $.gritter.add({ title: 'Notice', text: '${flash.message}', image: '', sticky: false, time: '' }); return false; }); A: Just wrap the g:if around the JavaScript block, so it won't be generated if there's no message. PS: you will probably need to rewrite the content of your gritter text attribute, I'm not sure it's going to work like that.
{ "pile_set_name": "StackExchange" }
Q: Disabling HTML PDF Viewer Object I have embedded a PDF viwer in my page and would like to disable the object in such a way that it's not possible to interact with it (no scrolling, no zoom in/out). My html object looks like this: <div id="pdf"> <object width="650" height="500" type="application/pdf" data="./forms/my.pdf?#zoom=45&scrollbar=0&toolbar=0&navpanes=0" id="pdf_content"> <p>PDF could not be loaded.</p> </object> </div> Is it even possible to disable the object? A: If your PDF is rendering as intended on page load and you simply want to prevent mouse interaction, you can cover it up with an invisible element like so with CSS: #pdf { position: relative; } #pdf::before { content: ''; position: absolute; top: 0; right: 0; left: 0; bottom: 0; z-index: 1; background: rgba(0, 0, 0, .3); } And per your request, a way to toggle this on/off (using jQuery): $('#toggle').on('click', function() { if ($('#pdf').hasClass('enable')) { $('#pdf').removeClass('enable').on('mousedown scroll', function() { return false; }); $(this).text('Enable PDF Interaction'); } else { $('#pdf').addClass('enable').off(); $(this).text('Disable PDF Interaction'); } }); #pdf { position: relative; /* sizes for example since PDF won't load: */ width: 650px; height: 500px; } #pdf::before { content: ''; position: absolute; top: 0; right: 0; left: 0; bottom: 0; z-index: 1; background: rgba(0, 0, 0, .3); } #pdf.enable::before { content: none; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="toggle">Disable PDF Interaction</button> <div id="pdf" class="enable"> <object width="650" height="500" type="application/pdf" data="https://upload.wikimedia.org/wikipedia/en/d/dc/Convergent_Synthesis_Example.pdf" id="pdf_content"> <p>PDF could not be loaded.</p> </object> </div>
{ "pile_set_name": "StackExchange" }
Q: SQL Server get data types for each column in a select statement I have a proc that uses a temp table and then at the end inserts into that from a select statement. I'm getting the following error: Arithmetic overflow error converting numeric to data type numeric Is there a way that I can find out what data type the select statement is using for the columns so I can compare that to the temp table definition so I can see what column(s) may be having the issue? I guess another way to put it, how can I tell which records are causing this problem? I figured if I could get the data type in each column in the select statement and compare to the temp table then it would help lead me to finding the issue. A: below query will give the results SELECT c.name 'Column Name', t.Name 'Data type', c.max_length 'Max Length', c.precision , c.scale , c.is_nullable, ISNULL(i.is_primary_key, 0) 'Primary Key' FROM sys.columns c INNER JOIN sys.types t ON c.user_type_id = t.user_type_id LEFT OUTER JOIN sys.index_columns ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id LEFT OUTER JOIN sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id WHERE c.object_id = OBJECT_ID('TableName')
{ "pile_set_name": "StackExchange" }
Q: Probabilistic Robotics Would questions on probabilistic robotics be appropriate here or better suited for a different StackExchange site like Mathematics.SE? I have some questions on the theories but also on setting up the sensors and range finders. A: If a question is essentially a robotics question then it is welcome here, even if it is also on topic for aother site. You are correct though that some types of questions might be better placed on other sites. Having said that, we do already have a variety of questions with the tags kalman-filter, slam and particle-filter, so there are already experts here who are interested in the kinds of topics that the book Probabilistic Robotics covers.
{ "pile_set_name": "StackExchange" }
Q: Need help for resolving merge conflicts I am learning git. I have a file called README which contains a,b,c,d. I created four branches out of master. User on branch 1 changes a to p, user on branch 2 changes b to q, user on branch 3 changes c to r and user on branch 4 changes d to s. Now when I try to merge all branches to master I get merge conflict. How do I merge all branches to master without conflict? A: Look in the conflicted files and decide which parts of the code between the <<<<<< ==== >>>>>> symbols you want to keep. Don't forget to delete them afterwards! Then do git commit -a.
{ "pile_set_name": "StackExchange" }
Q: Designing database for storing food recipes I want to create an app for searching food recipes and intend to create 3 tables below: Recipes(recipeID, recipeName). Ingredients(ingredientsID, ingredientsName). Recipe_ingredients(recipeID,ingredientsID, amount) <= this one is to map two tables above using foreign key. My question is in this case, if I have 100 recipes, so I need to create 100 recipe_ingredients table, right? on the other hand, in total, I would have to create one recipes table, 1 ingredients table and 100 recipe_ingredients tables, right? or I only need to make a very long recipe_ingredients including all 100 recipes? I know this question might sound silly, but I'm so new to database world. Any help? A: You would need 3 tables total: Recipes Ingredients Recipe_Ingredients. In your current design, you'd simply add data to your database; 100 tables would not be required. I think there may be a misunderstanding of the word table. A table in where you store the data. So in recipes you'd store a RecipeID and its corresponding recipeName. For the recipe_ingredients, you'd simply connect the recipe and an ingredient of your choice. There is no need to create 100 tables for that. Just add the data in your single table. Example: say you have one recipe that takes 5 ingredients: RecipeID = 1; IngredientID = 1 to 5. You will have to add each of these ingredients with a connection to the recipeID in the recipe_ingredientstable. The following entries would be in this table: PrimaryKey --- RecipeID --- IngredientID 1 --- 1 --- 1 2 --- 1 --- 2 3 --- 1 --- 3 4 --- 1 --- 4 5 --- 1 --- 5 Note that the PrimaryKey is used to distinguish each entry in this table. If you'd want all ingredients for the recipe with ID 1; you can query this by selecting all IngredientIDs' for RecipeID 1 and then join the ingredientName from your ingredientstable. On another note, you may want to reconsider your names too. Take a look here: Table Naming Dilemma: Singular vs. Plural Names
{ "pile_set_name": "StackExchange" }
Q: https://api.instagram.com/oauth/authorize api login error Instagram login API is in use. After approving the app, the following error occurs. The user denied your request. It worked well until yesterday. What's the problem? A: The value of the authorization buttons is different in other languages which probably causes the issue, I guess an issue on Instagram itself. After doing some research I found out you can change the language of the authorization screen using the following parameter: &hl=en Did some test with my apps and it's solving the issue. Note: The language parameter is not in the official documentation, so in theory they could change it, but for now it is fixing the issue. A: Workaround I can confirm that there is a problem in other languages except English. I had the same problem. If you set the web main language to English, you will be logged in. A: I have same error, but &hl=en helps me. Facebook and instagram support completely not competent, there are huge problems and no way to inform support about them.
{ "pile_set_name": "StackExchange" }
Q: Cocos2d low image quality I am now developing a game for iOS .I create a sprite sheet with Texturepacker which produces 2 file .plist and .png file . When I use these files in my code I found that the images of the all sprites have low quality and the color are pale very pale and I think this is because texturepacker program . Please I want your advise what shall I do to overcome this problem . A: I guess u didn't change back buffer pixel formate. U can try this. Used pixel formate kEAGLColorFormatRGBA8 instead of kEAGLColorFormatRGB565. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Create the main window window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // Create an CCGLView with a RGB565 color buffer, and a depth buffer of 0-bits CCGLView *glView = [CCGLView viewWithFrame:[window_ bounds] pixelFormat:kEAGLColorFormatRGBA8 //Guru - replaced kEAGLColorFormatRGBA8 / kEAGLColorFormatRGB565 depthFormat:0 //GL_DEPTH_COMPONENT24_OES preserveBackbuffer:NO sharegroup:nil multiSampling:NO numberOfSamples:0];
{ "pile_set_name": "StackExchange" }
Q: I have 5 choices in a test. I have a csv database. When I press on one of the buttons, I want the Text on the button to change to the next header I have 5 choices in a test. I have a csv database which I read the headers and answers from. When I press on one of the buttons, I want the Text on the button to change to the next header. I want to use a "for" loop for that. How will I keep the same layout, but change the text on the buttons in this for loop? public class MainActivity extends AppCompatActivity { int say,may=0; Button a,b,c,d,e; private List<WeatherSample> weatherSamples=new ArrayList<>(); String[][] deneme=new String[20][7]; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final Button asikki = (Button) findViewById(R.id.asikki); final Button bsikki = (Button) findViewById(R.id.bsikki); final Button csikki = (Button) findViewById(R.id.csikki); final Button dsikki = (Button) findViewById(R.id.dsikki); final Button esikki = (Button) findViewById(R.id.esikki); String line = ""; a = (Button) findViewById(R.id.asikki); b = (Button) findViewById(R.id.bsikki); c = (Button) findViewById(R.id.csikki); d = (Button) findViewById(R.id.dsikki); e = (Button) findViewById(R.id.esikki); InputStream is = getResources().openRawResource(R.raw.data); BufferedReader reader = new BufferedReader( new InputStreamReader(is, Charset.forName("UTF-8")) ); try { // step over header line reader.readLine(); while ((line = reader.readLine()) != null) { may++; String sira = Integer.toString(may); String[] tokens = line.split(","); WeatherSample sample = new WeatherSample(); deneme[may][0] = tokens[0]; deneme[may][1] = tokens[1]; deneme[may][2] = tokens[2]; deneme[may][3] = tokens[3]; deneme[may][4] = tokens[4]; deneme[may][5] = tokens[5]; deneme[may][6] = tokens[6]; } } catch (IOException e) { e.printStackTrace(); } for (int say=0;say<10;say++){ a.setText("A) " + deneme[1][0]); b.setText("B) " + deneme[1][1]); c.setText("C) " + deneme[1][2]); d.setText("D) " + deneme[1][3]); e.setText("E) " + deneme[1][4]); asikki.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { asikki.setText("bilgin"); asikki.setBackgroundColor(Color.BLACK); asikki.setTextColor(Color.WHITE); } }); bsikki.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { bsikki.setText("bilgin"); bsikki.setBackgroundColor(Color.BLACK); bsikki.setTextColor(Color.WHITE); } }); csikki.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { csikki.setText("bilgin"); csikki.setBackgroundColor(Color.BLACK); csikki.setTextColor(Color.WHITE); } }); dsikki.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { dsikki.setText("bilgin"); dsikki.setBackgroundColor(Color.BLACK); dsikki.setTextColor(Color.WHITE); } }); esikki.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { esikki.setText("bilgin"); esikki.setBackgroundColor(Color.BLACK); esikki.setTextColor(Color.WHITE); } }); } } A: for loop is something to be executed immediately, it doesn't wait, you only need the listener asikki.setText(deneme[0][0]); asikki.setBackgroundColor(Color.BLACK); asikki.setTextColor(Color.WHITE); asikki.setOnClickListener(new View.OnClickListener() { int say = 1; public void onClick(View v) { // TODO check say isn't out of bound asikki.setText("A) " +deneme[say++][0]); } });
{ "pile_set_name": "StackExchange" }
Q: Using Stored Procedure with Entity Framework where SP Parameters don't match entity I have stored procedures that take a user's username (to log who makes changes to the database) in addition to other information (like name, ID, email, etc.). Within the stored procedure I look up the user's ID and store that in the table. The issue I am experiencing is that the Entity Table does not match the input of the stored procedure, therefore there is no way to map (or include) the user's username. Is there a standard way to include non-entity properties in a stored procedure mapping? A: If I get your question correctly (not entirely sure I do), then: If you aren't already using your own DataContext derived class, do so. Add a method that calls ExecuteMethodCall in that class (it's protected, so you can only call it from a derived type, passing in "raw" types (the relevant strings, ints, datetimes, etc. rather than instances of entity classes). Add a method (presumably to your entity class, though it could live elsewhere) that does the necessary work for obtaining the username (whether it's a member of your class or input from elsewhere etc. isn't clear in your question) and calls the method on your DataContext-derived class. Hope that's useful, and I'm not mis-reading.
{ "pile_set_name": "StackExchange" }
Q: I cant align two input next to each other in Chrome, not in the same line <div id="row2"> <input type="text"> <input type="text"> </div> input { float: left; -moz-border-bottom-colors: none; -moz-border-left-colors: none; -moz-border-right-colors: none; -moz-border-top-colors: none; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; background-color: #E4E2D6; border-collapse: collapse; border-color: #DDDBCF #EAE9E0 #E2E0D4 #DDDBCF; border-image: none; border-radius: 4px; border-style: solid; border-width: 2px; color: #959494; font-family: georgia; font-size: 1.6em; height: 40px; margin: 1%; padding-left: 10px; width: 48%; } Updated the same in fiddle this works well with firefox... but with chrome, it goes to new line. A: Add this -webkit-box-sizing: border-box
{ "pile_set_name": "StackExchange" }
Q: Reference request: learn measure theory for PDEs I am requesting some references to learn appropriate measure theory for PDEs. Specifically, I would like to learn all the measure theory necessary to understand well-posedness of PDEs with measure valued data and things like that (I prefer weak/Sobolev spaces). I really would like something succinct without too much extra detail, so a book called "Measure Theory" would probably be a bad suggestion. Maybe a set of lecture notes designed for PDE people would be good? I would like to avoid all the minute details and lemmas that I will never remember if possible. Thanks. A: This supposed to be a comment but I can't comment yet. Evans also has a book "measure theory and fine properties of functions" coauthored with Gariepy if I'm not mistaken. It is more about geometric measure theory, but has a lot of interesting stuff about Sobolev spaces among other things. A: Since your question is formulated somewhat provocatively, let me answer in a similar spirit: The only measure theory you need to know is that the space of Radon measures is the topological dual of the space of continuous functions. And since you're not interested in details and lemmas, you're already done. Put less facetiously, what you need from measure theory is mainly the Riesz representation theorem in sufficiently general form. This is already treated in textbooks on abstract analysis (as part of integration theory), and you can avoid books on (modern) abstract measure theory (which evolved, in part, as a foundation for probability theory). A list of suitable texts can be found in Measure theory treatment geared toward the Riesz representation theorem, to which I would add Conway's recent Course in Abstract Analysis, AMS 2012. (If you're interested in even "cooler" right-hand sides, you really need to make your question more specific.)
{ "pile_set_name": "StackExchange" }
Q: SQL insert for multi select list I have implemented bootstrap multi select list in Laravel and I have a query to insert selected items into database but my query inserts only item which has lowest id number. So if I select employees with id numbers 2 3 4, id 2 will always be inserted and the rest is ignored. Just to imagine what my web app is going to do: I have a car repair and every repair has its own id. When creating new repair, I create repair instance first, then I get it's id and I insert it into table repair_employees with columns like this: "worker_id" "repair_id". So let's say I have new repair with id = 87. I select workers from the multi selection list with id: 2, 3, 4. So with proper sql insertion, table would look like this: "repair_id" , "worker_id" "87" , "2" "87" , "3" "87" , "4" Here is my code for insertion: public function addRepairWorker(Request $request , Vehicle $vehicle, $idcko){ $workers_needed = null; DB::transaction(function () use ($request, $vehicle, $idcko) { Log::info('Creating new repair worker instance.'); $workers_needed = new Repair_worker(); $workers_needed->repair_id = $idcko; $workers_needed->worker_id = $request->worker_id; DB::insert('insert into repair_worker (repair_id, worker_id) values (?, ?)', [$workers_needed->repair_id, $workers_needed->worker_id]); Log::info('Repair created.'); flash('Repair successfully added.', 'success'); }); } And here (if needed) is my view (form.blade.php) for the multi selection list: <select multiple class="form-control" name="worker_id"> @foreach($workers as $worker) <option value="{{ $worker->id }}" @if(isset($repair_worker) && ($worker->id == $worker_id)) selected @endif)> {{ $worker->name }} {{$worker->surname}} </option> @endforeach </select> What do I need to change to insert all "workers" ? EDIT: Here is function in my controller, where do I have to have a loop to get all array values? It's a bit confusing which part should loop to get it done. public function addRepair(Request $request, Customer $customer, Vehicle $vehicle) { $workers = DB::select(DB::raw('select workers.id as id, workers.name as name, workers.surname as surname from workers order by name')); if ($request->isMethod('post')) { $this->validate($request, [ 'worker_id' => 'required' //'part_id' => 'required' ]); $this->repairsService->createRepair($request, $vehicle); foreach ($workers_id as $id){ $this->repairsService->addRepairWorker($request, $vehicle); //this function does the insert into database } return redirect()->route('Customers:detailVehicle', ['customer' => $customer, 'vehicle' => $vehicle]); } return view('repairs.form', ['repair' => null, 'workers' => $workers]); } A: Firstly, with your select in your HTML, you need to adjust the name (note the square brackets). This will create an input value on your request as an array. If you do not do this, you will only have a single value, as it will overwrite all the previous values. <select multiple class="form-control" name="worker_id[]"> In your controller, you will need to loop through $worker_id array and do the insert for each value. Also, just do: $workers_needed->save(); instead of your insert statement, as you are defeating the purpose of having the models in the first place.
{ "pile_set_name": "StackExchange" }
Q: How to append a vue props data to base path for an image source I've been working with Vue js and Laravel recently and I'm trying to get an image from a source, the image source contains a base path and a vue prop data. But the problem is it returns an error stating that vue can not evaluate the expression. Any help will appreciated thanks <a class="thumbLink"><img data-large="url('uploads/products/285x380/@{{ itemDetails.product_image}}')" alt="img" class="img-responsive" src="uploads/products/285x380/@{{ itemDetails.product_image) }}"> </a> Error message [Vue warn]: Invalid expression. Generated function body: "uploads/products/285x380/"+(scope.itemDetails.product_image)) [Vue warn]: Error when evaluating expression ""uploads/products/285x380/"+(itemDetails.product_image))". Turn on debug mode to see stack trace. [Vue warn]: src="uploads/products/285x380/{{ itemDetails.product_image) }}": interpolation in "src" attribute will cause a 404 request. Use v-bind:src instead. [Vue warn]: Error when evaluating expression ""uploads/products/285x380/"+(itemDetails.product_image))". Turn on debug mode to see stack trace. [Vue warn]: src="{{ itemDetails.product_image_lg }}": interpolation in "src" attribute will cause a 404 request. Use v-bind:src instead. A: Vue cannot evaluate the expression because there's a syntax error. There's an unnecessary right bracket ) in @{{ itemDetails.product_image) }}. Also, there's a warning suggesting to use v-bind:src rather than interpolation. Here's the code with both changes applied: <a class="thumbLink"> <img data-large="url('uploads/products/285x380/@{{ itemDetails.product_image}}')" alt="img" class="img-responsive" :src="'uploads/products/285x380/' + itemDetails.product_image" > </a> Note that :src is shorthand for v-bind:src. Using v-bind causes the entire attribute to be evaluated as an expression.
{ "pile_set_name": "StackExchange" }
Q: bounding the number of zeros for a multivariate polynomial Let $f \in \mathbb{F}[x_1,\ldots,x_n]$ be a nonzero polynomial such that the maximum exponent of each variable is $d.$ I would like to show that for any $S \subseteq \mathbb{F}$ of size $|S| \geq d$ there are at least $(|S|-d)^n$ points in $S^n$ for which $f$ is not zero. I would like to prove the above claim by induction on $n.$ For the inductive step I am suggested to fix a $(a_1,\ldots,a_n) \in \mathbb{F}^n$ and consider the multinomials $$g(x_1,\ldots,x_{n-1}) = f(x_1,\ldots,x_{n-1},a_n) \quad \mbox{and} \quad h(x_n) = f(a_1, \ldots,a_{n-1},x_n).$$ By the induction hypothesis we would then have at least $(S-d)^{n-1}$ points that are not a zero for $g$ and $S-d$ points that are not zero for $h.$ But I do not see how to proceed from here? Can someone suggest a proof of this fact? A: For simpler notation, let $k=|S|-d, N=\{(\alpha_1,...,\alpha_n)\in S^n: f(\alpha_1,...\alpha_n)\neq 0\}.$ The induction base is the well known fact that a polynomial $f\in K[x]$ has at most $\text{deg}f$ roots in $K$. Let $\Bbb E=\Bbb F(x_1,x_2,...,x_{n-1}).$ We view $f$ as a polynomial in one variable with coefficients in $\Bbb E,$ i.e. let $h(x_n)=f(x_1,...,x_n)\in \Bbb E[x_n].$ By the induction base there are at least $k$ elements $a_1, a_2,...,a_k$ in $S$ such that $h(a_i)\neq 0$. For $1\le i\le k$ define $g_i(x_1,...,x_{n-1})=f(x_1,...,x_{n-1},a_i)\in \Bbb F[x_1,...,x_n]$ and $S_i=\{(b_1,...,b_{n-1})\in S^{n-1}:g(b_1,...,b_{n-1})\neq 0\}.$ By the induction hypothesis $|S_i|\ge k^{n-1}$ for each $i$, hence $|N|\ge k\cdot k^{n-1}=k^n$.
{ "pile_set_name": "StackExchange" }
Q: Stuck in iOS AutoLayout Mire I have a UIScrollView... inside of that UIScrollView is a UIView (Content Container)... inside that Content Container are 3 Views... A Label Another UIView (A) Another UIView (B) ALL THREE CREATED PROGRAMATICALLY 2 and 3 are both loaded from separate ReST calls... so while the view is loading they are both 30pt tall with a spinner. After one or both of the of the calls returns I want to size them correctly (the top will get an image that is 320x320) and the bottom will get a table (size is not determined right now)... I am trying to achieve this spacing Top of Container - 20pt - Label - 20pt - Content A - 20pt - Content B - Bottom of Container I am using the following inside -(void) updateViewConstraints [_containerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-20-[{label}]-20-[{content A}]-20-[{content B}]" options:0 metrics:nil views:viewsDictionary]]; Here is what it looks like after the call to get the content for A is returned: I am literally ready to stab my eyes out... I have no idea why this is so difficult. The frame for Content B looks like this: Other Frame: {{0, 150}, {320, 30}}, Bounds: {{0, 0}, {320, 30}} What I'm ultimately trying to do is create a UIScrollView that will allow me to scroll the view to see both the image and the table that will be displayed at the bottom... I have the UIScrollView and the Container View (_containerView = UIView) as IBOutlets in the IB. A: You haven't said anything about the appearance of your table view. If the table view has only one section, the easiest solution might be to instead give it three sections. Put one cell in the first section, containing the label. Put one cell in the second section, containing either the spinner or the image view for the “A” content. Put the “B” content in the third section. If you can't do that, here's another approach. Set up the “static” members of the view hierarchy like this: scrollView - UIScrollView scrollContentView - UIView label - UILabel aContainer - UIView bContainer - UIView Set up vertical constraints like this: V:|-[scrollContentView]-| V:|-[label]-[aContainer]-[bContainer]-| Insert the A spinner as a subview of aContainer, and set up its constraints like this: V:|[aSpinner]| Insert the B spinner as a subview of bContainer, and set up its constraints the same way: V:|[bSpinner]| When the image for area A arrives, remove aSpinner from its superview. This will remove the constraints between aSpinner and aContainer. Add the aImageView as a subview of aContainer and set up constraints for it: V:|[aImageView]| When the table data for area B arrives, remove bSpinner from its superview. Add the bTableView as a subview of bContainer and set up constraints for it: V:|[bTableView]| You need to figure out how tall to make the table view, and set up a constraint for it. You might find this answer useful.
{ "pile_set_name": "StackExchange" }
Q: Files built with Delphi 2010 report virus/trojan I tried to email a DLL-file built with Delphi but received an rejection email reporting: "Your email was rejected because it contains the Trojan.Delf-9364" So I uploaded the file to http://scanner.novirusthanks.org and sure enough it reports a positive in one of the virus scanners: "F-PROT6 20100630 4.5.1.85 W32/Swizzor-based.2!Maximus" I then built a empty exe-file (File - New - VCL Forms Application) and uploaded again, this time I get another positive: "VBA32 01/07/2010 3.12.12.2 Trojan.Win32.Swisyn.acyl" More details here: http://scanner.novirusthanks.org/analysis/e59033c40f1a6e37c210cb1c4f40f059/UHJvamVjdDEuZXhl/ So I'm not sure how to interpret these results. Are all the above false positives, are my computer infected with a virus that infects all binaries, or is my copy of Delphi infected with a Delphi-specific virus? I use AVG antivirus and it reports no problems on my computer. Perhaps someone else with Delphi 2010 can try uploading a project1.exe and see if they receive different results? A: I think it is a false positive. There have been more questions here about Delphi applications detected as virus, but those were all false positives. Report this as a false positive. There is a virus that infects your Delphi installation (4,5,6,7) by modifying SysConst.pas and compiling it, leaving a SysConst.bak in your lib directory. You can check for this. Follow this link for more information: http://www.securelist.com/en/weblog?weblogid=208187826 But you are on Delphi 2010, so you are not affected by that virus. A: Yeah, I just uploaded a blank project from D2010 and got "VBA32 01/07/2010 3.12.12.2 Trojan.Win32.Swisyn.acyl" too. Looks like a false positive to me. This has happened a few times in the past. Delphi's very good at creating software that works well very quickly. But unfortunately, that holds true even when the "software" in question is evil. It's been so widely used for nefarious purposes that there have been a few incidents of antivirus makers inserting a "virus signature" in their definitions that was actually part of the VCL or RTL. Looks like something similar's happened again. You ought to report this as a false positive.
{ "pile_set_name": "StackExchange" }
Q: Why can I use an Observable without subscribe? My problem is this example https://github.com/AngularFirebase/144-firestore-group-chat from Jeff Delaney. I'm trying to understand why it is possible to use an observable without subscribe(). For example the auth.service.ts from the Github repo: import { Injectable } from '@angular/core'; import { Router } from '@angular/router'; import { auth } from 'firebase/app'; import { AngularFireAuth } from '@angular/fire/auth'; import { AngularFirestore, AngularFirestoreDocument } from '@angular/fire/firestore'; import { Observable, of } from 'rxjs'; import { switchMap, first, map } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class AuthService { user$: Observable<any>; constructor( private afAuth: AngularFireAuth, private afs: AngularFirestore, private router: Router ) { this.user$ = this.afAuth.authState.pipe( switchMap(user => { if (user) { return this.afs.doc<any>(`users/${user.uid}`).valueChanges(); } else { return of(null); } }) ); } There is no subscribe() in the constructor nor in the rest of the project, but the example works fine. Another example is in chat.service.ts this function: getUserChats() { return this.auth.user$.pipe( switchMap(user => { return this.afs .collection('chats', ref => ref.where('uid', '==', user.uid)) .snapshotChanges() .pipe( map(actions => { return actions.map(a => { const data: Object = a.payload.doc.data(); const id = a.payload.doc.id; return { id, ...data }; }); }) ); }) ); } Why is it possible to use an Observable without subscribe()? A: There's async in this guard file, that allows the app to work properly. Since the guard is asking getUser() method from the AuthService which has a .toPromise() at the return: getUser() { return this.user$.pipe(first()).toPromise(); }
{ "pile_set_name": "StackExchange" }
Q: How to access data passed to the jade during compilation? Here is the code I've written in Gruntfile.js where I pass JSON file to Jade. compile: { files: { // some files }, options: { pretty: true, // Passing .Json file as data to jade data: grunt.file.readJSON("./src/jade/config.json") } How do I get access to data in .jade files? I've looked around but couldn't found a solution. A: The data you pass is a map of key-value pairs. You can then use a Jade syntax to use those values by the associated key names. For instance, if data would be: { "key1": "value1", "key2": "value2" } Then the following template: div= key1 div Some text #{key2} Would render: <div>value1</div> <div>Some text value2</div> The reference for this is in the Jade documentation, specifically in the string interpolation chapter.
{ "pile_set_name": "StackExchange" }
Q: Why are ssh keys not present in the folder? I have experimented with creating a SSH key as follows: But as I look in the directory using PowerShell, I cannot find any files. Am I missing something or doing something wrong? Note: I have censored my username. A: The file should be in the C:\Users\your-username folder. After you execute ssh-keygen, it asked you where you wanted to save your key, and it told you that the default location would be C:\Users\your-username/.ssh/id_ed25519, but you specified afdsaf instead without giving absolute path. So the resulting key would be C:\Users\your-username\afdsaf.
{ "pile_set_name": "StackExchange" }
Q: How to use nhibernate with ASP.NET 3.5 (not MVC) What is the best way to interop with NHibernate 2.0 and ASP.NET 3.5? How can I easily develop a CRUD application? Is the ObjectDataSource the way to go? Thank you. A: you can watch screencasts at http://www.summerofnhibernate.com/ that will explain how to set up CRUD, and will shed some light on more advanced topics A: You might find Rhino Commons a good option. It offers Repository<T> and UnitOfWorkApplication. Together these provide data gateway and session management in the context of a web application. Use with Castle.Service.Transaction to handle transactions transparently.
{ "pile_set_name": "StackExchange" }
Q: Proof that 2 and 3 are the only siamese twins that exist! Let us say that two prime number p and q are siamese twins if |p-q|=1. List all the siamese twins that exist, and prove your list is complete. Proof: 2 and 3 are prime numbers and 3-2=1. Therefore 2 and 3 are siamese twins. Lets assume that there exists another even prime number k and k $\neq$ 2. Since k is even we say that k = 2t for some integer t. Thus k is divisble by 2, by itself, and the number 1. This is a contradiction, therefore k cannot be a prime number. Thus 2 is the only even prime number which means every other prime number is odd. The shortest distance between any two odd numbers is 2. Therefore 2 and 3 are the only existing siamese twins. "Should I also prove that the shortest distance between any two odd numbers is 2? or should i just mention it?" "Is my proof good enough?" Any feedback would be greatly appreciated. Thanks. A: I would say that the proof is OK, but can be improved. It is not hard to prove that the distance between two odd numbers is always $2$ or more, but still, another sentence about it would not hurt, would it?
{ "pile_set_name": "StackExchange" }