source
stringclasses 1
value | task_type
stringclasses 1
value | in_source_id
stringlengths 1
8
| prompt
stringlengths 209
40.4k
| gold_standard_solution
stringlengths 0
56.7k
| verification_info
stringclasses 1
value | metadata
stringlengths 138
225
| problem_id
stringlengths 9
10
|
---|---|---|---|---|---|---|---|
stackexchange | llm_judgeable_groundtruth_similarity | 19584908 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm writing an app for iOS 7 only and I'm trying to get decent formatting on bullet points in a non-editable UITextView. It's easy enough to just insert a bullet point character, but of course the left indentation won't follow. What's the easiest way on iOS 7 to set a left indent after a bullet point? Thanks in advance, Frank
Now provide the response and nothing else.
| So I've looked around, and here is the extracted minimal code from Duncan's answer to make it work: NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:yourLabel.text];NSMutableParagraphStyle *paragrahStyle = [[NSMutableParagraphStyle alloc] init];[paragrahStyle setParagraphSpacing:4];[paragrahStyle setParagraphSpacingBefore:3];[paragrahStyle setFirstLineHeadIndent:0.0f]; // First line is the one with bullet point[paragrahStyle setHeadIndent:10.5f]; // Set the indent for given bullet character and size font[attributedString addAttribute:NSParagraphStyleAttributeName value:paragrahStyle range:NSMakeRange(0, [self.descriptionLabel.text length])];yourLabel.attributedText = attributedString; And here is the result of that in my app: | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19584908', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/224690/']} | jdg_86141 |
stackexchange | llm_judgeable_groundtruth_similarity | 13463103 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In the documentation, R suggests that raw data files (not Rdata nor Rda) should be placed in inst/extdata/ From the first paragraph in: http://cran.r-project.org/doc/manuals/R-exts.html#Data-in-packages The data subdirectory is for data files, either to be made available via lazy-loading or for loading using data(). (The choice is made by the ‘LazyData’ field in the DESCRIPTION file: the default is not to do so.) It should not be used for other data files needed by the package, and the convention has grown up to use directory inst/extdata for such files. So, I have moved all of my raw data into this folder, but when I build and reload the package and then try to access the data in a function with (for example): read.csv(file=paste(path.package("my_package"),"/inst/extdata/my_raw_data.csv",sep="")) # .path.package is now path.package in R 3.0+ I get the "cannot open file" error. However, it does look like there is a folder called /extdata in the package directory with the files in it (post-build and install). What's happening to the /inst folder? Does everything in the /inst folder get pushed into the / of the package?
Now provide the response and nothing else.
| You were both very close and essentially had this. A formal reference from 'Writing R Extensions' is: 1.1.3 Package subdirectories [...] The contents of the inst subdirectory will be copied recursively to the installation directory. Subdirectories of inst should not interfere with those used by R (currently, R , data , demo , exec , libs , man , help , html and Meta , and earlier versions used latex , R-ex ). The copying of the inst happens after src is built so its Makefile can create files to be installed. Prior to R 2.12.2, the files were installed on POSIX platforms with the permissions in the package sources, so care should be taken to ensure these are not too restrictive: R CMD build will make suitable adjustments. To exclude files from being installed, one can specify a list of exclude patterns in file .Rinstignore in the top-level source directory. These patterns should be Perl-like regular expressions (see the help for regexp in R for the precise details), one per line, to be matched(10) against the file and directory paths, e.g. doc/.*[.]png$ will exclude all PNG files in inst/doc based on the (lower-case) extension. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13463103', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/170352/']} | jdg_86142 |
stackexchange | llm_judgeable_groundtruth_similarity | 23567067 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Consider: protected string Active_Frozen(string text, string color){ connection(); string query = "SELECT CustomerInfo FROM ActiveSubscription WHERE UserName=@UserName"; SqlCommand cmd = new SqlCommand(query, conn); if(query=="true") { text = "Active"; color = "Green"; } else { text = "Frozen"; color= "Red"; } return (text, color);} I want to return both strings: text and color, but I am not sure what the problem is. Error @ return statement: (parameter) ? text/color Cannot convert lambda expression to type 'string' because it is not a delegate type
Now provide the response and nothing else.
| When you are returning two things, you need to declare your function as returning two things. However, your function is declared as returning one string. One way to fix it is using Tuple<T1,T2> : Tuple<string,string> Active_Frozen(string text, string color) { ... return Tuple.Create(text, color);} Note that returning the name of the color, rather than a color object itself, may not be ideal, depending on the use of the returned values in your design. If you wish to return an object representation of the color instead of a string, change the second type argument of the Tuple , or create your own class that represents the text and its color. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23567067', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3611542/']} | jdg_86143 |
stackexchange | llm_judgeable_groundtruth_similarity | 6081 |
Below is a question asked on the forum dsp.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
According to Wikipedia human whistling is a pure sine wave. If that is true and if a human is whistling and produces a rhythm like any song, is he still producing a pure sine wave? For example, if I am producing a tone of any music through my whistle would it still be a pure single harmonic sinusoidal wave?
Now provide the response and nothing else.
| This is only an approximation! While the sound of whistling has a very prominent first harmonic, the other harmonics are still present too; there's a non-harmonic noise component; and the first harmonic is more a narrow bump than a sharp line. A better description of the sound of whistling would be white noise filtered through a band-pass filter with a very high Q, and sent through a slight waveshaper adding harmonics. With a slight modulation of amplitude and filter frequency. A pure sine wave is a stationary signal, it has constant frequency and constant amplitude. If you observe a whistling sound on a window larger than a few tenths of seconds, you will observe modulations in frequency (because of the melody and articulations between notes), and modulations in amplitude (as you breath and start/end notes). | {} | {'log_upvote_score': 5, 'links': ['https://dsp.stackexchange.com/questions/6081', 'https://dsp.stackexchange.com', 'https://dsp.stackexchange.com/users/1324/']} | jdg_86144 |
stackexchange | llm_judgeable_groundtruth_similarity | 60157 |
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I know the maths behind, I know if I do the algebra I can get the result of the 3 cases. I also have an intuition of the 3 cases: Quora However, I just cannot memorize this "simple" 3 cases whenever I need to apply them in real life problems. I don't know if it is a shame that a CS graduate has to Google this theorem, which I learnt at the first year in University, just because I cannot memorize it. (Or is it actually no need to memorize it, please tell me, I will close the question at once) So assuming this basic theorem is important and I have to memorize it just like how we memorize F = ma in physics field, is there any way to aid memorizing these 3 cases in long term speaking? A way may means visualization, better intuition with clear reasoning behind, or even just die hard memorizing it, I just want to know how other CS people memorize this theorem.
Now provide the response and nothing else.
| I have a confession for you. I often can't remember the Master theorem, either. Don't worry about it. It's not a big deal. Here's how I deal with it. In many situations, you can look it up each time you need it; and if so, no big deal. Occasionally, you might not be able to look it up. So, I taught myself how to derive the Master theorem. That might sound intimidating, but it's not as hard as it sounds. Personally, I find memorization hard, but if I can figure out how to re-derive the formula myself whenever I need it, I know I'm in good shape. So, my advice to you is: learn how to re-derive the Master theorem on your own, whenever you need it. Here's one way you could do that: First, learn the recursion tree method. Learn how to build the tree, how to count the number of leaves, and how to count the amount of "extra work" at each level, and how to sum them (by summing a series, e.g., a geometric series). Next, open up a textbook read a standard proof of the Master theorem. Work through each step and check that you understand what's happening. Now, close your textbook and put away all your resources. Put a blank piece of paper in front of you... and derive the Master theorem yourself. How do you do that? Well, you use the recursion tree method. Try working through it by yourself and try to solve the recurrence entirely on your own. If you get stuck, as a last resort you can open the textbook back up and see how to proceed from there... but then the next day, you should try this exercise again. If you understand the recursion tree method well, you should be able to get to the point where you can derive the Master theorem yourself, from scratch, using just a blank piece of paper and nothing more. | {} | {'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/60157', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/46483/']} | jdg_86145 |
stackexchange | llm_judgeable_groundtruth_similarity | 60575 |
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm new to Wolfram Mathematica so the the question may seem quite simple. I define the following function: d[i_, j_] := Sum[α^(i + j - 2 k) (-1)^(-k) Sqrt[i!] Sqrt[j!]/((i - k)! (j - k)! k!), {k, 0, Min[i, j]}] Then, when I set α = 0 and try to evaluate d[0, 0] I get the following warning: Power::indet: Indeterminate expression 0^0 encountered. How can I input the condition Power[0,0]=1 in my function ? Please help!
Now provide the response and nothing else.
| Although it is best to avoid this when possible, using the undocumented function Internal`InheritedBlock you can temporarily add a rule to Power : α = 0;d[i_, j_] := Internal`InheritedBlock[{Power}, Unprotect[Power]; Power[0, 0] = 1; Sum[α^(i + j - 2 k) (-1)^(-k) Sqrt[i!] Sqrt[j!]/((i - k)! (j - k)! k!), {k, 0, Min[i, j]}] ]d[0, 0] 1 Be aware that user rules for System functions may be ignored when working with packed arrays. See: Block attributes of Equal Generally better is to use a proxy replacement for Power with your own behavior: Attributes[myPower] = {Listable};myPower[0, 0] = 1;myPower[x_, y_] := x^y;d[i_, j_] := Sum[myPower[α, (i + j - 2 k)] (-1)^(-k) Sqrt[ i!] Sqrt[j!]/((i - k)! (j - k)! k!), {k, 0, Min[i, j]}] The Listable attribute makes sure that zeroes in vectors and matrices are also handled in the way we defined: In[2]:= myPower[0, {{1, 1}, {1, 0}}]Out[2]= {{0, 0}, {0, 1}} | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/60575', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/20003/']} | jdg_86146 |
stackexchange | llm_judgeable_groundtruth_similarity | 30787391 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a large CSV file, which is a log of caller data. A short snippet of my file: CompanyName High Priority QualityIssueCustomer1 Yes UserCustomer1 Yes UserCustomer2 No UserCustomer3 No EquipmentCustomer1 No NeitherCustomer3 No UserCustomer3 Yes UserCustomer3 Yes EquipmentCustomer4 No User I want to sort the entire list by the frequency of occurrence of customers so it will be like: CompanyName High Priority QualityIssueCustomer3 No EquipmentCustomer3 No UserCustomer3 Yes UserCustomer3 Yes EquipmentCustomer1 Yes UserCustomer1 Yes UserCustomer1 No NeitherCustomer2 No UserCustomer4 No User I've tried groupby , but that only prints out the Company Name and the frequency but not the other columns, I also tried df['Totals']= [sum(df['CompanyName'] == df['CompanyName'][i]) for i in xrange(len(df))] and df = [sum(df['CompanyName'] == df['CompanyName'][i]) for i in xrange(len(df))] But these give me errors: ValueError: The wrong number of items passed 1, indices imply 24 I've looked at something like this: for key, value in sorted(mydict.iteritems(), key=lambda (k,v): (v,k)): print "%s: %s" % (key, value) but this only prints out two columns, and I want to sort my entire CSV. My output should be my entire CSV sorted by the first column. Thanks for the help in advance!
Now provide the response and nothing else.
| This seems to do what you want, basically add a count column by performing a groupby and transform with value_counts and then you can sort on that column: df['count'] = df.groupby('CompanyName')['CompanyName'].transform(pd.Series.value_counts)df.sort_values('count', ascending=False) Output: CompanyName HighPriority QualityIssue count5 Customer3 No User 43 Customer3 No Equipment 47 Customer3 Yes Equipment 46 Customer3 Yes User 40 Customer1 Yes User 34 Customer1 No Neither 31 Customer1 Yes User 38 Customer4 No User 12 Customer2 No User 1 You can drop the extraneous column using df.drop : df.drop('count', axis=1) Output: CompanyName HighPriority QualityIssue5 Customer3 No User3 Customer3 No Equipment7 Customer3 Yes Equipment6 Customer3 Yes User0 Customer1 Yes User4 Customer1 No Neither1 Customer1 Yes User8 Customer4 No User2 Customer2 No User | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30787391', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4945793/']} | jdg_86147 |
stackexchange | llm_judgeable_groundtruth_similarity | 14149269 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have three projects in my eclipse workspace: EventKitchenCoreEventKitchenDesktopEventKitchenAndroid EventKitchenCore contains all the core functionality, and EventKitchenDesktop and EventKitchenAndroid are essentially just different user interfaces. I have EventKitchenCore added and working as a library in EventKitchenDesktop , however I am unable to figure out how to add it as a library to EventKitchenAndroid . How do I do this? It would be a pain in the tush to have to export as a jar in the lib directory every time I make a change... I tried adding the Core project in Properties > Java Build Path > Libraries and Properties > Android > Library , but no luck :\ Update - for now, I got it working by exporting the core project as a jar in the libs folder. However I make frequent changes, and like I said, it's a pain in the tush.
Now provide the response and nothing else.
| Eclipse has builtin Ant support. You can make use of it to automatically create a JAR of the current project and put it in a folder of another project. Provided that EventKitchenAndroid and EventKitchenCore projects are both in the same workspace, create a build.xml file in EventKitchenCore project which contains just this: <?xml version="1.0" encoding="UTF-8"?><project name="EventKitchenCore" default="createjar"> <target name="createjar"> <jar destfile="../EventKitchenAndroid/libs/EventKitchenCore.jar" basedir="bin" /> </target></project> To test it, select the file in Eclipse and press Ctrl + F11 to run it as Ant build file. If it works the way you want, then you can tell Eclipse to automatically execute this build file everytime the project is built. Go to the project properties of EventKitchenCore and in the Builders property, click Import... and select the build.xml file you just created. Now, it will be executed everytime the project is built. You can manually force the build of a project by pressing Ctrl + B . See also the video demo I just created. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14149269', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/481702/']} | jdg_86148 |
stackexchange | llm_judgeable_groundtruth_similarity | 3780478 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
(I hope that this question is acceptable and within the rules of math.stackexchange. If not, mods should edit at will and let me know if this question must be broken into several different questions. I ask these all together at once because they seem crucially tied together insofar as answers would correct my misunderstandings.) I am currently studying Galois Theory, but I am unable to get a handle on the subject. My intuition leads to me conclusions which are obviously incorrect, so I will ask a brief series of questions which I think will help me correct my course. Let $Q$ be the rationals. Let $f$ be an irreducible polynomial (hence separable) over $Q$ with degree $n$ . Let $F$ be the splitting field of $f$ . So $F/Q$ is Galois. Let $G$ be the Galois group of $F/Q$ . Let $a_1,\dots ,a_n$ be the distinct roots of $f$ . My understanding is that $F=Q(a_1,\dots ,a_n)$ . Question 1: Since every automorphism of $F/Q$ permutes $a_1,\dots ,a_n$ , it is clear that $G$ can be embedded into $S_n$ as a subgroup. Why is it not the case that $G$ is automatically all of $S_n$ ? Surely any permutation of the roots gives an automorphism of $F$ preserving $Q$ ? If not, what might be an instructive minimal example? Question 2: Conceptually speaking, what exactly prevents certain permutations from being acceptable automorphisms of $F/Q$ ? Question 3: Alternatively, if $f$ is not irreducible, then $F$ is the splitting field of some polynomial which is not irreducible. In this case, I believe that roots from different irreducible components cannot jump to roots of other irreducible components. Why is this the case? Question 4: Again we assume that $f$ is irreducible. What must be unique about the situation in order for $G$ to really be all of $S_n$ ? Question 5: Now set $n=4$ . I know that $A_{4}$ is the only subgroup of $S_4$ with order $12$ . Suppose that $G=S_4$ . Suppose $K=Q(a_1)$ . Why is it not the case that $F/K$ has order $12$ and hence has Galois group $A_4$ ? It seems that the Galois group of $F/K$ could include all permutations of $a_1,\dots ,a_4$ that map $a_1$ to itself. Question 6: Suppose we are in the case of Question 5. Why is it the case that the Galois group of $F/K$ has a transposition?
Now provide the response and nothing else.
| Question 1: Consider $f(x) = x^4 + 1$ , which is irreducible over $\mathbb{Q}$ . Then we may write all the roots of $f(x)$ as $\zeta_8^i$ where $i = 1, 3, 5, 7$ . In particular $[F : \mathbb{Q}] = [\mathbb{Q}(\zeta_8) : \mathbb{Q}] = 4$ . Thus the galois group cannot be all of $S_4$ - if you write out the automorphisms you will see that saying where $\zeta_8$ goes is the same as saying where all the $\zeta_8^i$ go. Question 2: This was answered above, sometimes there is dependencies between the roots, so because each element of the galois group is a field automorphism, some will be disallowed. Question 3: If $F$ is the splitting field of $f(x)$ and $f(x) = g(x)h(x)$ then if $\sigma \in Gal(F / \mathbb{Q})$ we have $\sigma(g(x)) = g(\sigma(x))$ . In particular if $\alpha$ is a root of $g(x)$ then so is $\sigma(\alpha)$ . Question 4: This is a somewhat difficult question to answer. There are many criteria for when a subgroup of $S_n$ might be the symmetric group (e.g., if it is a transitive subgroup containing an $(n-1)$ -cycle and a transposition). In general if I were trying to answer this in some situation I would do some algebraic number theory and look mod $p$ . Question 5: The degree $[\mathbb{Q}(a_i): \mathbb{Q}] = 4$ ( $a_i$ a root of an irreducible polynomial of degree $4$ , in particular $[F : \mathbb{Q}(a_i)] = 24/4 = 6$ by the tower law. You are correct, the elements are the permutations that fix $a_i$ , but that is just $S_3$ !. Question 6: The element fixing $a_1$ and $a_2$ but permuting $a_3$ and $a_4$ is in $Gal( F / \mathbb{Q}(a_1))$ and is clearly a transposition. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3780478', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/796019/']} | jdg_86149 |
stackexchange | llm_judgeable_groundtruth_similarity | 987672 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to format (bold or italics) only a portion of a textbox or Formula object (IFieldObject) in Crystal Reports for Visual Studio 2008. I know how to make the entire field bold, but I want only a portion. For example: ...blah blah blah May 12, 2009 blah blah blah... Is this possible? I'm thinking there must be some sort of markup, but can't find any reference to it.
Now provide the response and nothing else.
| You can do this by inserting HTML markup in the field (using a formula) and then displaying the new formula as a HTML field. e.g. Here's a basic Syntax formula that takes a field and adds the bold tag around the text before the colon. dim sTmp as string dim sLeft as string dim sRight as string dim sAll as string sTmp = {yourtable.yourfield}sLeft = (split(sTmp,":"))(1)sRight = (split(sTmp,":"))(2)sAll = "<b>"+sLeft+":</b>"+sRightformula = sAll If you place this new formula into the report and then ... Right Click the field and choose "Format Field" Change Text Interpretation to HTML Text Click 'OK' There are Gotchas here. The original text is not HTML encoded, and I'm sure my example code does a simple one-line thing in about ten lines. Also, if your field has no colons in it, you'll force an error. However, it should give you the right idea. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/987672', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/18821/']} | jdg_86150 |
stackexchange | llm_judgeable_groundtruth_similarity | 27607144 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have two tables: Request: RequestID | Msg---------------- 5 | abc 6 | def 7 | ghi 8 | jkl RequestStatus: RequestStatusID | RequestID |StatusID------------------------------------- 1 5 1 2 8 2 Not every request has a record in RequestStatus I need all the records from table Request except when StatusID = 2 . ( requestID=8 should be filter-out) I am using LEFT OUTER JOIN to recieve the records from table Request but when I am adding Where clause (Where StatusID = 1) of course it does not work.
Now provide the response and nothing else.
| Move the constraint to your on clause. select *from request rleft join requestStatus rson r.requestID = rs.requestID--and status_id = 1and status_id <> 2 What's happening to you is that the outer join is performed first. Any rows coming from the outer join that don't have matches will have nulls in all the columns. Then your where clause is applied, but since 1 <> null, it's not going to work like you want it to. EDIT: Changed on clause based on Piyush's comment. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27607144', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1073658/']} | jdg_86151 |
stackexchange | llm_judgeable_groundtruth_similarity | 5186973 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it possible with .NET standard JavascriptSerializer/JsonDataContractSerializer or external parsers, to serialize objects array using a wrapper approach including the object type? For example, to generate this JSON from a List: [{ 'dog': { ...dog properties... } }, { 'cat': { ...cat properties... } }] instead of typical: [{ ...dog properties... }, { ...cat properties... }] This is doable in Java with Jackson using JsonTypeInfo.As.WRAPPER_OBJECT attribute.
Now provide the response and nothing else.
| Json.NET has a neat solution for this. There is a setting that intelligently adds type information - declare it like this: new JsonSerializer { TypeNameHandling = TypeNameHandling.Auto }; This will determine whether type embedding is required and add it where necessary. Lets say I had the following classes: public class Message{ public object Body { get; set; }}public class Person{ public string Name { get; set; }}public class Manager : Person{}public class Department{ private List<Person> _employees = new List<Person>(); public List<Person> Employees { get { return _employees; } }} Notice the Message Body is of type object, and that Manager subclasses Person. If I serialize a Message with a Department Body that has a single Manager I get this: { "Body": { "$type":"Department, MyAssembly", "Employees":[ { "$type":"Manager, MyAssembly", "Name":"Tim" }] }} Notice how it's added the $type property to describe the Department and Manager types. If I now add a Person to the Employees list and change the Message Body to be of type Department like this: public class Message{ public Department Body { get; set; }} then the Body type annotation is no longer needed and the new Person is not annotated - absence of annotation assumes the element instance is of the declared array type. The serialized format becomes: { "Body": { "Employees":[ { "$type":"Manager, MyAssembly", "Name":"Tim" }, { "Name":"James" }] }} This is an efficient approach - type annotation is only added where required. While this is .NET specific, the approach is simple enough to handle that deserializers/message types on other platforms should be fairly easily extended to handle this. I'd be reticent about using this in a public API though, as it is non-standard. In that case you'd want to avoid polymorphism, and make versioning and type information very explicit properties in the message. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5186973', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1330118/']} | jdg_86152 |
stackexchange | llm_judgeable_groundtruth_similarity | 4529819 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a problem to find common elements in two arrays and that's of different size. Take , Array A1 of size n and Array A2 of size m , and m != n So far, I've tried to iterate lists one by one and copy elements to another list. If the element already contains mark it, but I know it's not a good solution.
Now provide the response and nothing else.
| Sort the arrays. Then iterate through them with two pointers, always advancing the one pointing to the smaller value. When they point to equal values, you have a common value. This will be O(n log n+m log m) where n and m are the sizes of the two lists. It's just like a merge in merge sort , but where you only produce output when the values being pointed to are equal. def common_elements(a, b): a.sort() b.sort() i, j = 0, 0 common = [] while i < len(a) and j < len(b): if a[i] == b[j]: common.append(a[i]) i += 1 j += 1 elif a[i] < b[j]: i += 1 else: j += 1 return commonprint 'Common values:', ', '.join(map(str, common_elements([1, 2, 4, 8], [1, 4, 9]))) outputs Common values: 1, 4 If the elements aren't comparable, throw the elements from one list into a hashmap and check the elements in the second list against the hashmap. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4529819', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/83501/']} | jdg_86153 |
stackexchange | llm_judgeable_groundtruth_similarity | 45275 |
Below is a question asked on the forum dsp.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
My try: First of all I tried observing the symmetry but I did'nt find any.So I tried to calculate the fourier series coefficient of the signal like this First I differentiated the signal $x(t)$ so that $y(t)=\frac{dx(t)}{dt}$ Now suppose $d_k$ is the Fourier series coefficient of the differentiated signal and $a_k$ is the fourier series coefficient of Orignal signal $x(t)$Now $d_k=(jk \omega_0 )c_k$ so $c_k=\frac{d_k}{jk \omega_0}$.Now calculating $d_k$ That is \begin{align}d_k &=\frac{1}{3} \int_{-1}^2 \big(\delta(t+1)+\delta(t)-2\delta(t-1)\big) e^{\frac{-jk2\pi t}{T}}dt\\&=\frac{1}{3}\big(1+e^{\frac{jk2\pi}{3}}-2e^{\frac{-jk2\pi}{3}}\big)\end{align} Now $$a_k=\frac{\frac{1}{3}\big(1+e^{\frac{jk2\pi}{3}}-2e^{\frac{-jk2\pi}{3}}\big)}{jk \omega_0}$$$$a_k=\frac{\big(1+e^{\frac{jk2\pi}{3}}-2e^{\frac{-jk2\pi}{3}} \big)}{j2\pi k}$$ Now checking at $k=1,a_k\ne 0$and at $k=2,a_k\ne 0$ so for one odd and one even value of n its not zero so no options matching.What is the mistake? EDIT: As stated by @Matt L in the commment to check for period T=6 also, so I did like this I differentiated the signal from -3 to +3 so the fourier series coefficient I got like this \begin{align}d_k &=\frac{1}{6} \int_{-3}^3 \big(\delta(t+3)-2\delta(t+2)+\delta(t+1)+\delta(t)-2\delta(t-1)+\delta(t-2)\big)e^{\frac{-jk2\pi t}{6}}dt\\&=\frac{1}{6}\big(1+e^{jn\pi}-2e^{\frac{jk2\pi}{3}}+e^{\frac{jn\pi}{3}}-2e^{\frac{-jk\pi}{3}}+e^{\frac{jk2\pi}{3}}\big)\end{align} Now at $k=1,d_k=0$ at $k=2,d_k\ne 0$,at $k=3,d_k=0$ but at $k=6$ also $d_k=0$ Now whats the mistake???
Now provide the response and nothing else.
| You can see this by using integration by parts : $$\begin{align}\int_{-\infty}^{\infty}x(t)\delta'(t-T)dt&=x(t)\delta(t-T){\Big|}_{-\infty}^{\infty}-\int_{-\infty}^{\infty}x'(t)\delta(t-T)dt\\&=x(T)\delta(t-T){\Big|}_{-\infty}^{\infty}-x'(T)\\&=-x'(T)\end{align}$$ where it is assumed that $x(t)$ and $x'(t)$ are continuous at $t=T$. | {} | {'log_upvote_score': 4, 'links': ['https://dsp.stackexchange.com/questions/45275', 'https://dsp.stackexchange.com', 'https://dsp.stackexchange.com/users/29743/']} | jdg_86154 |
stackexchange | llm_judgeable_groundtruth_similarity | 323101 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I got this question in a practice book. A,B,C and D are $n\times n$ matrices with non-zero determinant. $ABCD = I$ , then $B^{-1}$ = ? The answer to this was $B^{-1}= CDA$. How was that answer arrived at ?
Now provide the response and nothing else.
| $ABCD=I$, $BCD=A^{-1}$, $CD=B^{-1}A^{-1}$, $CDA=B^{-1}$. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/323101', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/15861/']} | jdg_86155 |
stackexchange | llm_judgeable_groundtruth_similarity | 10732297 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to parse a String in "dd-MM-yy" format to a Date object. The problem is that it tries to guess the century for the date. When specified from 01 to 31, year is interpreted as 2000s (21st Century) and 32 t0 99 is considered 1900s (20th Century). SimpleDateFormat fm =new SimpleDateFormat("dd-MM-yy");String datestr="21-11-31";try { Date date= fm.parse(datestr); System.out.println(date);} catch (ParseException e) {} Can anyone help me? How can I specify that I am only working in the 21st Century neatly. I am not exactly trying to look for tricks like manipulating the string or shifting the date based on the condition.
Now provide the response and nothing else.
| You can change the century it uses to interpret 2 digit data entry with the set2DigitYearStart() method. SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yy");String aDate = "03/17/40";Calendar cal = Calendar.getInstance();cal.clear();cal.set(Calendar.YEAR, 2000);dateFormat.set2DigitYearStart(cal.getTime());System.out.println(dateFormat.get2DigitYearStart());System.out.println(dateFormat.parse(aDate)); Will print March 17, 2040. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10732297', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1117127/']} | jdg_86156 |
stackexchange | llm_judgeable_groundtruth_similarity | 49288415 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to make axios working with a request interceptor. Howeverbefore a request is made the interceptor is not triggered. What could be going wrong here? I've red already a lot about this problem but notfound a solution so far. Could use some help here! This is my code: import VueRouter from 'vue-router'; import Login from './components/Login.vue' import Home from './components/Home.vue' import axios from 'axios'; window.Vue = require('vue'); window.axios = axios.create({ baseURL: 'http://localhost:8080', timeout: 10000, params: {} // do not remove this, its added to add params later in the config }); Vue.use(VueRouter); // Check the user's auth status when the app starts // auth.checkAuth() const routes = [ { path: '/', component: Login, name: 'login' }, { path: '/home', component: Home, name: 'home', beforeEnter: requireAuth }, ]; const router = new VueRouter({ routes // short for `routes: routes` }); const app = new Vue({ router }).$mount('#app'); function requireAuth (to, from, next) { if (!loggedIn()) { router.push('/'); } else { next() } } function loggedIn() { return localStorage.token !== undefined; } axios.interceptors.request.use(function (config) { alert('test'); return config; }, function (error) { // Do something with request error return Promise.reject(error) }) When I use axios within another vue file: axios.get('users').then((data) => { console.log(data); }); The interceptor is not triggered!
Now provide the response and nothing else.
| You're calling the interceptor on the axios instance you imported, but it needs to be on the instances you created. Calling window.axios = axios.create() is really bad style anyway and you should avoid it at all costs. If you want it to be globally available you should bind it to the Vue Prototype. Even better would be to move it out in another module: const instance = axios.create({ baseURL: 'http://localhost:8080', timeout: 10000, params: {} // do not remove this, its added to add params later in the config});instance.interceptors.request.use(function (config) { alert('test'); return config;}, function (error) { // Do something with request error return Promise.reject(error)})export default instance If you really want it to be available everywhere without having to import it, consider wrapping my code from above inside a Vue plugin and let your Vue instance use it, as shown here in the 4. comment . | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/49288415', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4779178/']} | jdg_86157 |
stackexchange | llm_judgeable_groundtruth_similarity | 2449505 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Another Riemann sum I'm struggling to convert to a definite integral... $\lim_{n\to \infty}$ $\sum_{i=1}^n$ $\frac{6n}{9n^2+4i^2}$. Any ideas as to what my $x_i$ should be in this case?
Now provide the response and nothing else.
| Let $x_i=\dfrac{i}{n}$ then $x_1=\dfrac{1}{n}\to0$, $x_n=\dfrac{n}{n}\to1$and $\Delta x=\dfrac1n$ so$$\lim_{n\to\infty}\sum_{i=1}^n\dfrac{6}{9+4(\dfrac{i}{n})^2}\frac1n=\int_0^1\dfrac{6}{9+4x^2}dx$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2449505', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/477187/']} | jdg_86158 |
stackexchange | llm_judgeable_groundtruth_similarity | 98345 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Despite the fact that $\forall n, n^3 + 2n \equiv 0 \pmod 3$, I understand that $n^3 + 2n$ (considered as a polynomial with coefficients in $\mathbb Z/3\mathbb Z$) is not equal to the zero polynomial. What is the value of defining polynomials in this (strange) way? What situations does it make things simpler? I ask this because it seemed natural to me to define polynomials as a subset of functions, so I was surprised by this.
Now provide the response and nothing else.
| $p(x) = x^3 + 2x$ may give the zero function on the finite field $\mathbb{F}_3$, but it does not give the zero function on its field extensions , such as $\mathbb{F}_9$. A polynomial with coefficients in a field $F$ actually gives a well-defined function over any extension of $F$, and in this generality it's true that distinct polynomials give distinct functions. This isn't really the reason, though. To my mind, the main reason is that polynomials satisfy a universal property : for a commutative ring $R$, the ring $R[x_1, ... x_n]$ is the free $R$-algebra on $n$ generators. In other words, if $S$ is any other $R$-algebra, then there is a natural bijection between the set$$\text{Hom}_R(R[x_1, ... x_n], S)$$ of $R$-algebra homomorphisms $R[x_1, ... x_n] \to S$ and the set$$S^n$$of $n$-tuples of elements of $S$. This universal property fails if the polynomial ring is replaced by any quotient of it, since the values of $x_1, ... x_n$ will be constrained by any additional relations. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/98345', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']} | jdg_86159 |
stackexchange | llm_judgeable_groundtruth_similarity | 22683 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The most basic example of a topologically non-trivial real line bundle is the well-known Möbius strip . Everyone who learns about vector bundles will be confronted by it, if only because it has the distinguished advantage that we can draw a picture of it. I would like to draw pictures of other line bundles, too. In particular, I have a complex line bundle which I would like to visualize somehow. How do I do that? To be more specific: The base manifold is the torus $M = S^1\times S^1$. It should be fine to visualize it as a rectangle, though. The complex line bundle has structure group $U(1)$. It is given as a direct summand of the trivial bundle $M \times L^2(\mathbb R^3)$. In other words, it is embedded in an infinite dimensional Hilbert space bundle. In particular, there is an induced connection coming from the hermitian form (scalar product). (The bundle arises from an analysis of the Quantum Hall Effect.) My questions: 1) Are there any example drawings of complex line bundles? I imagine that one attaches a plane to every point of the base manifold, but it is not clear how to me how to arrange them such that one obtains a qualitative picture of the fact that they represent complex numbers. 2) Is there a minimal dimension $N$ such that every complex line bundle can be embedded into $\mathbb R^N$ in a suitable fashion? It is probably the case that $N \geq 4$, so this won't be of much use, but it might still shed some insight on the problem, in particular because we are also given a connection. 3a) Any ideas of how one might go about drawing a complex line bundle? 3b) Any ideas on how to best visualize the connection coming from a hermitian form?
Now provide the response and nothing else.
| Apparently, Mario Serna has produced pictures of $U(1)$-bundles on his webpage and in his paper "Riemannian Gauge Theory and Charge Quantization" . Here an example The image represents a trivial $\mathbb R^3$ over some rectangular base manifold. The $U(1)$ bundle which we want to visualize is shown as an $\mathbb R^2$-sub-bundle: the disks indicate the 2-dimensional fibers at each point, to be understood as subspaces of small 3-dimensional boxes at each point (not shown). It seems that the disks are also meant to give an impression of the connection, but I don't fully understand how parallel transport is supposed to work here. He cites a result by Narasimhan and Ramanan which says that every $U(1)$ bundle can be embedded into a trivial $(2d+1)$-dimensional complex vector bundle where $d = \text{dim} M$ is the dimension of the base manifold. Fortunately, the dimension is lower in the cases drawn. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/22683', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/434/']} | jdg_86160 |
stackexchange | llm_judgeable_groundtruth_similarity | 944678 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Background I have created ASMX web services in the past and have been able to access the service from the web browser and Ajax GET requests using the address convention: MyService.asmx/MyMethod?Param=xxx I just got started using WCF and created a new web service in my ASP.NET project. It creates a file with the .svc extension such as MyService.svc. Current Situation I am able to consume the service using the WcfTestClient that comes with VS2008. I am also able to create my own WCF Client by either adding a service reference in another project or using the svcutil.exe commandline to generate the proxy and config file. The Problem When I try to use the service from a browser using MyService.svc/MyMethod?MyParam=xxx , I get a blank page without any errors. What I have tried I have already added a basicHttpBinding to the web.config and made it HttpGetEnabled in the behavior configuration. I also added the [WebGet(UriTemplate = "MyMethod?MyParam={MyParam}")] attribute to my operation contract. I have already followed the information in this other stack overflow question: REST / SOAP EndPoints for a WCF Service However, I either get a blank page or an HTTP 404 Error after following those steps. There's nothing special about the code. I am just taking in a string as a parameter and returning "Hello xxx". This is a basic "Hello WCF World" proof-of-concept type thing. UPDATE - Here's the relevant code [ServiceContract]public interface IMyService{ [WebGet(UriTemplate = "MyMethod/MyParam={MyParam}")] [OperationContract] string MyMethod(string MyParam);} Web.Config - system.serviceModel Section <system.serviceModel> <behaviors> <serviceBehaviors> <behavior name="MyServiceBehavior"> <serviceMetadata httpGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="true"/> </behavior> </serviceBehaviors> </behaviors> <services> <service behaviorConfiguration="MyServiceBehavior" name="MyService"> <endpoint address="" binding="wsHttpBinding" contract="IMyService" /> <endpoint address="MyService.svc" binding="basicHttpBinding" contract="IMyService" /> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> </service> </services> </system.serviceModel>
Now provide the response and nothing else.
| Looking at your web.config serviceModel section, I can see that you need to add a webHttpBinding and associate an endPointBehavior that includes webHttpGet . Your operation contract is correct. Here's how your system.serviceModel config section should look in order for you to be able to consume the service from a GET HTTP request. <system.serviceModel> <behaviors> <serviceBehaviors> <behavior name="MyServiceBehavior"> <serviceMetadata httpGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="true"/> </behavior> </serviceBehaviors> <endpointBehaviors> <behavior name="WebBehavior"> <webHttp /> </behavior> </endpointBehaviors> </behaviors> <services> <service behaviorConfiguration="MyServiceBehavior" name="MyService"> <endpoint address="ws" binding="wsHttpBinding" contract="IMyService"/> <endpoint address="" behaviorConfiguration="WebBehavior" binding="webHttpBinding" contract="IMyService"> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> </service> </services> </system.serviceModel> Be sure to assign a different address to your wsHttpBinding endpoint, otherwise you will get an error saying that you have two endpoints listening on the same URI. Another option is to leave the address blank in the wsHttpBinding, but assign a different address to the webHttpBinding service. However, that will change your GET address as well. For example, if you assign the address as "asmx", you would call your service with the address " MyService.svc/asmx/MyMethod?MyParam=xxxx ". | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/944678', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/37081/']} | jdg_86161 |
stackexchange | llm_judgeable_groundtruth_similarity | 607051 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a set of ages, $\mathbb{T}=\{30, 33, 39, 40, 41\}$. I'd like to refer to the last $X$ of these ages by $\mathbb{T}^{(X)}$. So, $\mathbb{T}^{(2)} = \{ 40, 41 \}$. But how can I define this $\mathbb{T}^{(X)}$? Somehow I need to communicate, formally, that $\mathbb{T}^{(X)}$ is the subset of $\mathbb{T}$ containing the last $X$ elements of $\mathbb{T}$ when sorted. FYI: I'm open to using something other than a superscripted parenthetical numeral if there's something more standard.
Now provide the response and nothing else.
| Why not define the $\newcommand{\T}{\mathbb T}X$ last number $\T_{(-X)}$ like this$$\T_{(-X)}=\max\left(t\mbox{ such that }\#\{s\in\T\ |\ s\geq t\}=X\right)$$and then$$\T^{(X)}=\{t\in\T\ |\ t\geq\T_{(-X)}\}$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/607051', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/73479/']} | jdg_86162 |
stackexchange | llm_judgeable_groundtruth_similarity | 7606597 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have next arrays NAMES1: array[0..1] of string = ('NO1','NAME1');NAMES2: array[0..1] of string = ('NO2','NAME2'); and a record structure TMyRec = record( Name: ????;); As result I need to declare a constant array of records like following const StringArraysList: array[0..1] of TMyRec = ( (Name: NAMES1), (Name: NAMES2) ); The question is what type should I select for Name in TMyRec?
Now provide the response and nothing else.
| You need to do it like this: type TTwoNames = array[0..1] of string; TMyRec = record Names: TTwoNames; end;const StringArraysList: array[0..1] of TMyRec = ( (Names: ('NO1','NAME1')), (Names: ('NO2','NAME2')) ); You would prefer to write the final declaration as const NAMES1: TTwoNames = ('NO1','NAME1'); NAMES2: TTwoNames = ('NO2','NAME2'); StringArraysList: array[0..1] of TMyRec = ( (Names: NAMES1), (Names: NAMES2) ); But that results in [DCC Error] Unit1.pas(38): E2026 Constant expression expected Some Delphi constants are not as constant as you would like them to be! The documentation for record constants states that The values must be represented by constant expressions. The documentation for typed constants states that Typed constants cannot occur in constant expressions. Put these two rules together and we have E2026 . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7606597', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/960513/']} | jdg_86163 |
stackexchange | llm_judgeable_groundtruth_similarity | 140176 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to build kernel 3.13.9, fetched using apt-get source , and built in a clean debootstrap chroot (both host and chroot being installations of Ubuntu Trusty). My goal is to boot a diskless machine to a console over NFS. I ran make menuconfig and enabled 64-bit kernel, disabled debugging, and made sure I was doing a 64-bit build. In addition, I went to file systems->network file systems, and enabled the following: Network File Systems NFS Client Support The host has nfs-kernel-server installed, and an export set up for the directory that I would like to use as the root of the network-booted system. PXE boot happens OK, kernel and initrd are loaded, but after a long pause, I'm dumped to a busybox prompt, due to a root filesystem being missing. What could be the cause? (or, is more info needed?) Edit: I'm already passing nfsroot : LABEL linuxKERNEL vmlinuz-3.13.9APPEND root=/dev/nfs initrd=initrd.img-3.13.9 nfsroot=192.168.1.39:/nfsroot,rw ip=dhcp rw
Now provide the response and nothing else.
| As the kernel documentation states, /dev/nfs is not a real device but only a hint to the kernel to use NFS as rootfs . You'll also have to tell the kernel where to find this root through the nfsroot parameter or a properly set up DHCP daemon. For the latter one to work you'll also have to either configure your kernel to auto-configure its network interfaces or have an initramfs which takes care of this. Also, make sure to have NFS support built into your kernel binary and not as a module (or have an initramfs , which takes care of this). Same goes for network drivers: you'll most probably want to have the driver for you ethernet NIC built into your kernel image, otherwise you'll have to load it from an initramfs . In short, there are several possibilities: Do as above link tells you: have root=/dev/nfs set, give the correct nfsroot parameter and tell your kernel your network configuration via the ip parameter (this would be the best way to make sure it's working at all, i.e. to rule out a misconfigured DHCP server). Have CONFIG_IP_PNP and CONFIG_IP_PNP_DHCP enabled and set up a DHCP daemon to tell your client which IP address to use and where to find its NFS-root. Build an initramfs which does the correct configuration and NFS-mounting. Edit: I think if you're using an initrd / initramfs as your edit suggests, you'll have to do the NFS-mount in the initrd (resp. your initrd has to be aware of the fact that it has to do so). Automounting through the kernel (as IP autoconfiguration, IIRC) only works if there's no initrd . | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/140176', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/20352/']} | jdg_86164 |
stackexchange | llm_judgeable_groundtruth_similarity | 39228648 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to deploy a flask app on GAE. All dependencies like Flask, jinja2 etc are in the same directory When GAE launcher deploys the app locally, it gets deployed but nothing gets displayed on the home url once the local server is up and running even though the main.py returns some text for the home url Following are my files: app.yaml application: texsummversion: 1runtime: python27api_version: 1threadsafe: truehandlers:- url: .* script: main.app main.py from flask import Flask, render_template, requestapp = Flask(__name__)@app.route("/")def template_test(): return "Hello"if __name__ == "__main__": app.run() What can be the issue ?
Now provide the response and nothing else.
| Ok, the following worked for me: Add a ref to the native component in the render method of the JavaScript class. Use findNodeHandle method from react-native package, passing the obtained ref as an argument. The findNodeHandle method returns a react ID, save it. Use UIManager.dispatchViewManagerCommand method from react-native , passing the react ID as the first argument. Second argument is a command id. Third argument are additional arguments (can be null ). Override receiveCommand method in your ViewManager native class, which exposes the component. In this method, handle the command. Example JS: componentDidMount() { this.mapViewHandle = findNodeHandle(this.mapViewRef);}center() { UIManager.dispatchViewManagerCommand(this.mapViewHandle, 0, null);}render() { return ( <MapView ref={(mv) => this.mapViewRef = mv} /> );} Example Java: @Overridepublic void receiveCommand(MapView view, int commandId, @Nullable ReadableArray args) { super.receiveCommand(view, commandId, args); if (commandId == 0) { if (mMyLocation != null) { view.getController().setCenter(mMyLocation); } }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39228648', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4770722/']} | jdg_86165 |
stackexchange | llm_judgeable_groundtruth_similarity | 114 |
Below is a question asked on the forum scicomp.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In my numerical analysis courses, I learned to analyze the efficiency of algorithms by counting the number of floating-point operations (flops) they require, relative to the size of the problem. For instance, in Trefethen & Bau's text on Numerical Linear Algebra, there are even 3D-looking pictures of the flop counts. Now it's fashionable to say that "flops are free" because the memory latency to fetch anything not in cache is so much greater than the cost of a flop. But we're still teaching students to count flops, at least in numerical analysis courses. Should we be teaching them to count memory accesses instead? Do we need to write new textbooks? Or is memory access too machine-specific to spend time on? What is the long-term trend going to be in terms of whether flops or memory access is the bottleneck? Note: some of the answers below seem to be answering a different question like "Should I obsessively rewrite my implementation to save a few flops or improve cache performance?" But what I'm asking is more along the lines of " Is it more useful to estimate algorithmic complexity in terms of arithmetic operations or memory accesses ?"
Now provide the response and nothing else.
| I think the (first order) right thing to do is look at the ratio of flops to bytes needed in the algorithm, which I call $\beta$. Let $F_{\mathrm{max}}$ be the maximum flop rate of the processor, and $B_{\mathrm{max}}$ the maximum bandwidth. If $\frac{F_{\mathrm{max}}}{\beta} > B_{\mathrm{max}}$, then the algorithm will be bandwidth limited. If $B_{\mathrm{max}}\beta > F_{\mathrm{max}}$, the algorithm is flop limited. I think counting memory accesses is mandatory, but we should also be thinking about: How much local memory is required How much possible concurrency we have Then you can start to analyze algorithms for modern hardware. | {} | {'log_upvote_score': 6, 'links': ['https://scicomp.stackexchange.com/questions/114', 'https://scicomp.stackexchange.com', 'https://scicomp.stackexchange.com/users/123/']} | jdg_86166 |
stackexchange | llm_judgeable_groundtruth_similarity | 37052 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have the following files in a directory: -rw-r--r-- 1 smsc sys 46 Apr 22 12:09 bills.50.1.3G.MO.X.20120422120453.Z-rw-r--r-- 1 smsc sys 28 Apr 22 12:15 bills.50.1.3G.MO.X.20120422120953.Z-rw-r--r-- 1 smsc sys 46 Apr 22 12:20 bills.50.1.3G.MO.X.20120422121453.Z-rw-r--r-- 1 smsc sys 46 Apr 22 12:25 bills.50.1.3G.MO.X.20120422121953.Z Where the fifth column is the file's size. I wish to delete all files which size is 46. In order to filter out these files I used the following command: ls -ltr | awk '$5 ~ /46/ {print $0}' Which works fine. But now I want to delete all files which were filtered out, so I add the following to the above command: ls -ltr | awk '$5 ~ /46/ {print $0}' | xargs rm However it gives me the following error: rm: invalid option -- w It seems that I have to use find over ls so I will get the output in the below format: ./bills.50.1.3G.MO.X.20120421050453.Z./bills.50.1.3G.MO.X.20120421154953.Z./bills.50.1.3G.MO.X.20120419133452.Z But then I have no way to filter the files by its parameters.How this task could be done?
Now provide the response and nothing else.
| You have two bugs: You are comparing for a size that contains 46 ; you want it to be equal to 46. You are printing the entire line, when you want only the filename. And an additional issue: what is the point of -ltr to sort the ls output when you aren't using the sort order? You want to do something like ls -l | awk '$5 == "46" {print $9}' | xargs rm Except you don't want to do that, because while it might be safe at the moment, parsing ls output is unreliable. Use an appropriate tool such as find . -maxdepth 1 -size 46c -delete # requires GNU find (Doing this portably is more annoying, since POSIX find doesn't have -maxdepth or -size that operates in units other than blocks. Better to write a script in a Perl/Python/Ruby/etc. that can use a proper directory scan that won't get in trouble with special characters in filenames.) | {} | {'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/37052', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/15142/']} | jdg_86167 |
stackexchange | llm_judgeable_groundtruth_similarity | 5241147 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What is a function literal in Scala and when should I use them?
Now provide the response and nothing else.
| A function literal is an alternate syntax for defining a function. It's useful for when you want to pass a function as an argument to a method (especially a higher-order one like a fold or a filter operation) but you don't want to define a separate function. Function literals are anonymous -- they don't have a name by default, but you can give them a name by binding them to a variable. A function literal is defined like so: (a:Int, b:Int) => a + b You can bind them to variables: val add = (a:Int, b:Int) => a + badd(1, 2) // Result is 3 Like I said before, function literals are useful for passing as arguments to higher-order functions. They're also useful for defining one-liners or helper functions nested within other functions. A Tour of Scala gives a pretty good reference for function literals (they call them anonymous functions). | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5241147', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/516982/']} | jdg_86168 |
stackexchange | llm_judgeable_groundtruth_similarity | 44815580 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am using Firebase Auth signInWithPopup() which is absolutely great. Butwhen initially configured, the popup reads: Choose an account to continue to myApp-123.firebaseapp.com I would really like it to read: Choose an account to continue to myApp.com How can I make the popup show my own domain?
Now provide the response and nothing else.
| In my solution that follows I should say that the steps I followed worked. It is possible that I did something that it not absolutely required, but to my knowledge and at this time, I have not broken anything. This workflow (and the documentation) is a bit broken up because you must adjust both your Google Cloud Platform (GCP) credentials and the Firebase authentication. Documentation was provided by each side of this workflow but I was not able to find a document that covered the entire workflow to make this substitution. GCP Console Setup I first adjusted my GCP credentials for the OAuth Client: Go to the GCP console > APIs & Services > Credentials page ( https://console.cloud.google.com/apis/credentials?project= _ and select your project) At the bottom of the page, find "OAuth 2.0 client IDs". There should be an entry titled "Web client (auto created by Google Service)" To the right side of page click on the edit icon (pen), which opens the configuration page. Under "Authorized JavaScript origins", you should see your yourFirebaseApp.firebaseapp.com domain. Click "+ Add URI" and add your custom URI. This should be an "https" domain, so use https://myApp.com Under "Authorized redirect URIs", you should see https://yourFirebaseApp.firebaseapp.com/__/auth/handler . (The __/auth/handler bit on the tail is the auth callback that Firebase provides). Click "+ Add URI" and add your domain, with __/auth/handler at the end. (For example: https://myApp.com/__/auth/handler ) Click Save Go to the OAuth Consent Screen ( https://console.cloud.google.com/apis/credentials/consent/edit?project=_ ). Add your custom domain to "Application Homepage link", and fill in the "Application Name" and "Logo", and "Application Privacy Policy link" with custom values for your app. Firebase Console Setup Then, you'll need to add your custom domain to the Firebase auth authorized domain list: Go to the Firebase Console > Authentication > Sign-in Methods page ( https://console.firebase.google.com/project/_/authentication/providers and select your project) Under "Authorized Domains" you should see localhost and the default yourFirebaseApp.firebaseapp.com domain. Click the "Add Domain" and enter your custom domain name, then click add. Web App Setup You will likely remember the block of code that you copied from your firebase project and pasted into the code from which you compile and deploy your Web App. (Some people use the hosting default init.js script - if you do, go back and setup your app using the config snippet instead) Find the "authDomain" field in the code snippet, and change it to your custom domain, then re-deploy. This procedure worked for me and my project, I have posted this in the hopes that these instructions may be refined via feedback from others performing this or similar operations. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44815580', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_86169 |
stackexchange | llm_judgeable_groundtruth_similarity | 12438224 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How can I set the window size programmatically? I have a window in IB and I want to set the size of it in my code to make it larger.
Now provide the response and nothing else.
| Use -setFrame:display:animate: for maximum control: NSRect frame = [window frame];frame.size = theSizeYouWant;[window setFrame: frame display: YES animate: whetherYouWantAnimation]; Note that window coordinates are flipped from what you might be used to. The origin point of a rectangle is at its bottom left in Quartz/Cocoa on OS X. To ensure the origin point remains the same: NSRect frame = [window frame];frame.origin.y -= frame.size.height; // remove the old heightframe.origin.y += theSizeYouWant.height; // add the new heightframe.size = theSizeYouWant;// continue as before | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12438224', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1508048/']} | jdg_86170 |
stackexchange | llm_judgeable_groundtruth_similarity | 39587 |
Below is a question asked on the forum mechanics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I was draining the fluid out of the automatic transmission of a '94 Sentra with a RL4F03A tranmission. While I was removing the magnets, one of them was holding onto a 10 mm hex nut. It was clean, not mangled, not stripped. After getting back under the car to remove the transmission filter (it's bolted on), I looked all over the inside of the exposed part of the transmission (without taking anything else apart) and couldn't find any bolt that is missing a nut. In fact, I could not find any exposed nuts. What did my mystery 10 mm hex nut fall off of?
Now provide the response and nothing else.
| Okay. Lot's of research, long story, found the answer, don't like it. Overall design of the Nissan B13: one of the things that always impressed me about this vehicle is that it seems to have been designed with the DIY home mechanic in mind. Components are accessible and tasks can typically be accomplished using only 2 different wrench sizes, and maybe a screwdriver and pliers. When I got under there to flush the tranny, I found a drain plug for the tranny. Tranny filter vs tranny screen: What? Yes. Some trannies have a filter that you replace when you change the fluid, other trannies have a screen (metal mesh) that you clean when you change the fluid. Filters are usually clipped on, screens are usually bolted on. This RL04F03A tranny has a screen. Other people found nuts in their tranny pan: this post from a Miata forum talks about their tranny having a few bolts holding the screen onto the valve body via some threaded holes, but there's this 1 bolt that goes through the valve body and can only be tightened by a nut on the upper side of the valve body. It's just not feasible to get a finger in there to get the bolt started into the nut, you need to remove the valve body. But that's a Miata! This is a Nissan! Well, I was a bit surprised to find so many dadgum bolts holding a flimsy little filter-looking thing that turned out to be a screen. I went at it and removed the bolts, and, half way around, started noticing the bolts weren't all the same. Great. Just GREAT. There were 8 long ones, 2 short ones and 2 medium ones. The 2 medium ones flanked one of the short ones and the other short one is on the opposite side, I figured I could remember all that. Besides, it was too late to do the cardboard thing as most of the bolts were out. When it was time to reassemble, it turned out there were 2 kinds of long ones, 7 with threads all the way up, and 1 with threads near the end only. Aw crap. That's the one that needs the nut. Really? You need to remove the valve body? Well, if you want to take the screen off and put it back on, yes you should remove the valve body. Because of the risk of introducing dust, dirt and other particulates into the transmission by removing the valve body, many sources recommend leaving the screen in place and just changing the fluid. That's why there's a drain plug. Great. So how did the nut come lose and what do you do about it? Well, if you don't know there's a nut up there, you won't go looking for it. That last bolt, the one that needs the nut, won't thread tight, but you may not notice, since it goes through so much metal before getting to the other side and there's still plenty of tranny fluid dripping down the hole to make a "fluid lock" and make the bolt seem a bit tight. Fire up the car and the fluid will swish (that's a technical term) that nut around until the magnets grab it. That's what magnets are in the tranny pan for (metal shavings and things that come loose). That nut has been in there since the very first time the car was started up after the last tranny service. The tranny's been performing fine, it didn't miss that nut or it's associated bolt not being threaded in tight, it won't miss it going forward. Long story short. On this tranny, don't even bother taking the pan off. Drain the fluid using the drain plug, then refill. I always wondered why my fancier other vehicles don't have a tranny drain plug. It's because they have filters, they WANT you to take the pan off so you may as well change the filter because it's just there. I don't want to generalize, but I would expect vehicles with a screen (not a filter) would have a tranny drain plug to discourage you from getting your dirty little fingers in there when you don't really need to. And just for posterity, I'll link to 2 YouTube videos I've found about people tearing down this specific tranny. Not a single nut to be found, and the screen was installed off camera while the valve body was out of sight. Don't you just love it when you find a video with a long enough runtime to make you think it's complete, detailed and exhaustive only to find it skips right over the part you really need? 1997 Nissan Primeria SR20DE with RL04F03A 1997 Nissan Sentra GA16DE with RL04F03A | {} | {'log_upvote_score': 5, 'links': ['https://mechanics.stackexchange.com/questions/39587', 'https://mechanics.stackexchange.com', 'https://mechanics.stackexchange.com/users/18919/']} | jdg_86171 |
stackexchange | llm_judgeable_groundtruth_similarity | 8105847 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am helping someone with C++ input even though I don't know C++ myself. Here's a short example: #include <iostream>#include <string>using namespace std;int main() { int i; string s; cout << "enter i:\n"; cin >> i; cout << "enter s:\n"; getline(cin, s); //cin.ignore(100, '\n'); cout << "i: " << i << ", s: " << s << "\n";} As expected, the getline() call will not prompt the user for input because it will simply swallow the trailing \n after the cin >> i call and return immediately. What I find odd is that if you uncomment the cin.ignore() call, the getline() call will prompt the user for input (even though nothing will be saved into s ). Could someone explain why? In my view, the line in question should not change the behaviour at all.
Now provide the response and nothing else.
| The first suggested creating an IBPlugin, which would then mean my bindings would be available in the Bindings Inspector. I could then bind the view to the controller using IB. Apparently IBPlugins aren't supported in Xcode 4, so that one's out the window. Correct. Interface Builder is dead; long live the Xcode nib editor (which they still call Interface Builder sometimes). With IB gone, so are IBPlugins. I'm also assuming (maybe wrongly) that IBPlugins are no longer supported because there's a better way of doing such things these days? Nope. The second option was to bind the controller to the view programmatically. I'm a bit confused as to exactly how I would achieve this. Send the view a bind:toObject:withKeyPath:options: message . Would it require subclassing NSObjectController so I can add the calls to bind to the view? Not NSObjectController, but something that either owns the nib (such as a window controller or view controller) or is a top-level object inside it (such as the application's delegate in the MainMenu nib). Would I need to add anything to the view to support this? See below. Some examples I've seen say you'd need to override the bind method, and others say you don't. You used to, for non-views (views always worked without overriding it), but not anymore. You no longer need to override the bind:::: method. I don't know when this changed, but I wrote a test app to confirm the current behavior (as of Snow Leopard and Lion). Also, I've noticed that some example custom views call [self exposeBinding:@"bindingName"] in the initializer. From what I gather from various sources, this is something that's related to IBPlugins and isn't something I need to do if I'm not using them. Is that correct? Nope. You don't need to override bind:::: to bind to any KVC-/KVO-compliant property, and you don't need to send exposeBinding: . Confusingly, the documentation says otherwise : that you must override bind:::: and unbind: , even in views, and that exposeBinding: is useful for anything. All you have to do to create an available binding is implement a KVC-/KVO-compliant property. If it's a synthesized @property , this is done. Otherwise, see here . Then, send the view/object a bind:::: message to actually bind it, since there's no way to expose the binding in the nib editor. TL;DR: Just implement a regular property, and you'll be able to bind it with a bind:toObject:withKeyPath:options: message (at least in Snow Leopard and Lion). You don't need to send exposeBinding: from anywhere anymore. You can't make custom bindings show up in the nib editor in Xcode 4. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8105847', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/56463/']} | jdg_86172 |
stackexchange | llm_judgeable_groundtruth_similarity | 11222121 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
We were having this discussion wiht my colleagues about Inner assignments such as: return result = myObject.doSomething(); or if ( null == (point = field.getPoint()) ) Are these acceptable or should they be replaced by the following and why? int result = myObject.doSomething();return result; or Point point = field.getPoint();if ( null == point)
Now provide the response and nothing else.
| The inner assignment is harder to read and easier to miss. In a complex condition it can even be missed, and can cause error. Eg. this will be a hard to find error, if the condition evaluation prevent to assign a value to the variable: if (i == 2 && null == (point = field.getPoint())) ... If i == 2 is false, the point variable will not have value later on. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11222121', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1058319/']} | jdg_86173 |
stackexchange | llm_judgeable_groundtruth_similarity | 547512 |
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I believe I have a misunderstanding of some principles, but I have not, even through quite a bit of research, been able to understand this problem. My current understanding of transmission, reflection and absorption is as follows: transmission occurs when the energy of an incident photon does not correspond to any electron's energy transition within the material. Therefore, the photon does not interact with the atoms / electrons and is transmitted through. Absorption occurs when the incident photon's energy exactly equals that of an electron's energy transition. The photon is absorbed and excites an electron to a higher state. Reflection I feel like my understanding is flawed, since I have read multiple different views. I believe that a photon is absorbed by an atom, exciting an electron. The electron, however, almost immediately transitions back into a lower energy level, emitting a photon of identical wavelength. My question concerning reflection is: Why are some wavelengths absorbed and immediately re-emitted? I presume that it is because the electron is in a type of unstable state and therefore drops back to its previous energy level? Given a solid object that appears red to us (therefore reflects wavelengths somewhere between 625 and 740nm), how can it be possible that all other incident wavelengths are absorbed? They must be absorbed, since the only wavelength being reflected is in the "red" range, and I can clearly see there's no visible light being transmitted through the object. However, in my knowledge, the wavelengths can only be absorbed if they correspond to the energy transition of an electron, which is not the case for every wavelength in the visible spectrum. How is it then possible that they are absorbed?Additionally, if the electron is excited to a higher level, does it just store the energy? Does it take thermal form?? I assume that perhaps I cannot simply apply these principles of absorption, that I was taught only in relation to a single atom, to a complex body consisting of billions of atoms. Could someone elaborate on this and explain my questions about absorption and reflection? Thanks very much!
Now provide the response and nothing else.
| Your misunderstanding is very common and quite easy to make. Basically, what students are usually introduced to first is the thermodynamics of ideal monoatomic gasses. This is good because it is simple and easy to understand, but can be problematic because features specific to the simple substance can be misunderstood as general features of all substances. In an ideal monoatomic gas light can interact either by scattering or by absorbing an amount of energy corresponding to an atomic transition*. Note, in the latter case the photon is not absorbed by the electron but by the atom as a whole because the atom has different internal states corresponding to the absorbed energy. As a result ideal monoatomic gasses tend to be transparent except at a few narrow** frequencies. Now, consider a molecular gas. Just like an atom has internal states that an electron does not, similarly a molecule has internal states that an atom does not. Some states correspond to electron transitions in the molecule, but others correspond to rotational or vibrational modes. The molecular electronic transitions combined with the molecular vibrational and rotational transitions gives rise to a multitude of absorption lines, often forming continuous absorption bands, so many times these are visibly not transparent. Now, consider a solid. Just like a molecule has states that an atom does not, similarly a solid has states that a molecule does not. The rotational and vibrational modes gain additional degrees of freedom and can act over fairly large groups of molecules (e.g. phonons). These states can have energy levels that are so closely spaced they form continuous bands, and are called energy bands. Any energy in the band will be easily absorbed. This makes most solids opaque as they absorb broad bands of radiation. Finally, when a photon is absorbed it may be re-emitted at the same wavelength to fall back to the original energy state. However, if there are other energy states available then the energy can be emitted and retained at different energy levels. For example, a UV photon could be absorbed and a visible photon could be emitted along with an increase in a rotational degree of freedom. *Even for an ideal monoatomic gas there are other less common mechanisms like ionization and deep inelastic scattering, but for clarity these are neglected here. **Note that even for an ideal monoatomic gas the frequency bands are not infinitely narrow but have some breadth. This is caused by two factors. First, the width of the peaks is fundamentally limited by the time-energy uncertainty relation which says that $2 \Delta T \ \Delta E \ge \hbar$ where $\Delta E$ is the width of the energy band and $\Delta T$ is the lifetime of the transition. Second, random thermal movement of the gas will cause Doppler and pressure broadening of the frequency band. | {} | {'log_upvote_score': 7, 'links': ['https://physics.stackexchange.com/questions/547512', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/262447/']} | jdg_86174 |
stackexchange | llm_judgeable_groundtruth_similarity | 106102 |
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The Lie algebra of $ \mathfrak{so(3)} $ and $ \mathfrak{su(2)} $ are respectively $$ [L_i,L_j] = i\epsilon_{ij}^{\;\;k}L_k $$ $$ [\frac{\sigma_i}{2},\frac{\sigma_j}{2}] = i\epsilon_{ij}^{\;\;k}\frac{\sigma_k}{2} $$ And of course, there is an isomorphism between these two algebras, $$ \Lambda : \mathfrak{su(2)} \rightarrow \mathfrak{so(3)} $$ such that $ \Lambda(\sigma_i/2) =L_i $ Now is it possible, using $\Lambda$ , to construct a group homomorphism between $SU(2)$ and $SO(3)$ ? I was checking up on Lie group homomorphism , and in Wikipedia, there is a beautiful image In this image's language, how are $\phi$ and $\phi_*$ related to each other (just like the algebra and group elements are). Note : I know there is a one-to-two homomorphism between these two groups which can be directly found using the group elements. I am not looking for this. EDIT 1 : In $ SL(2,\mathbb{R}) $ the generators, say $X_1,X_2,X_3$ , they obey the following commutation rules : $$ [X_1,X_2] = 2X_2 $$ $$ [X_1,X_3] = -2X_3 $$ $$ [X_2,X_3] = X_1 $$ And in the case of $ SO(3) $ with a different basis, $ L_{\pm} = L_1 \pm i L_2 $ and $ L_z = L_3 $ with the commutators being, $$ [L_z,L_{\pm}]= \pm L_{\pm} $$ $$ [L_+,L_-]= 2 L_z $$ This algebra is very similar to the algebra of the previous one, so why is that we can't define a map ? EDIT 2 : Can the group homomorphism between these two groups be written like this (Something like what I expected) : $$ R = \exp(\sum_k i t_k L_k) = \exp\left(\sum_k i t_k \frac{\sigma_k}{2}\right) = \exp\left(\sum_k i t_k \frac{1}{2}ln(U_k)\right) $$ Now this seems like the map $\phi$ , $$ R = \phi(U) = \exp\bigg(\sum_k i t_k \frac{1}{2}ln(U_k)\bigg) $$
Now provide the response and nothing else.
| First notice that the generators are $-i\sigma_k/2$ and $-iL_k$, since the groups are real Lie groups and thus the structure tensor must be real . The answer to your question is positive. In principle it is enough to take the exponential of the Lie algebra isomorphism and a surjective Lie group homomorphism arises this way $\phi : SU(2)\to SO(3)$: $$\phi\left(\exp\left\{-\sum_k t^k i\sigma_k/2\right\}\right) =\exp\left\{-\sum_k t^k iL_k\right\}\:.$$The point is that one should be sure that the argument in the left-hand side covers the whole group. For the considered case, this is true because $SU(2)$ is compact. If you instead consider no compact Lie groups, like $SL(2,\mathbb C)$, the exponential does not cover the group. However it is possible to prove that products of exponential do. In that case a product of two exponentials is sufficient, in practice decomposing an element of $SL(2,\mathbb C)$ by means of the polar decomposition, mathematically speaking, or as a (unique) product of a rotation and a boost physically speaking. | {} | {'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/106102', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/35952/']} | jdg_86175 |
stackexchange | llm_judgeable_groundtruth_similarity | 3799053 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I would like to know how to check if I have write permissions to a folder. I'm writing a C++ project and I should print some data to a result.txt file, but I need to know if I have permissions or not. Is the check different between Linux and Windows? Because my project should run on Linux and currently I'm working in Visual Studio.
Now provide the response and nothing else.
| The portable way to check permissions is to try to open the file and check if that succeeded. If not, and errno (from the header <cerrno> is set to the value EACCES [yes, with one S], then you did not have sufficient permissions. This should work on both Unix/Linux and Windows . Example for stdio: FILE *fp = fopen("results.txt", "w");if (fp == NULL) { if (errno == EACCES) cerr << "Permission denied" << endl; else cerr << "Something went wrong: " << strerror(errno) << endl;} Iostreams will work a bit differently. AFAIK, they do not guarantee to set errno on both platforms, or report more specific errors than just "failure". As Jerry Coffin wrote, don't rely on separate access test functions since your program will be prone to race conditions and security holes. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3799053', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/454558/']} | jdg_86176 |
stackexchange | llm_judgeable_groundtruth_similarity | 1561716 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have spent the last couple weeks in my Fourier Analysis course to solve PDEs with the method of separations of variables. However, I have come up with something that annoys me and I can't really explain it. Let me show an example. I have this problem here $$u_{xx}+u_{yy}=0 \\u(0,y) = u(1,y) = 0 \\u(x,0) = u(x,1) = \frac{x^3-x}{6}$$ So I separate the variables and get these ODEs $$X''(x)+ \lambda^2 X(x) = 0 \\Y''(y)- \lambda^2 Y(y) = 0$$ and these are simple to solve. The first one is just $X(x)= A\cos(\lambda x)+B \sin(\lambda x)$ and now is the confusing part. For me the solution to the second equation have always been $Y(y)=Ce^{- \lambda y}+ De^{ \lambda y}$ but the book have suddenly started to use the hyperbolic equations $\cosh$ and $\sinh$ , why is that? Is it something I am missing?
Now provide the response and nothing else.
| The awesome thing about hyberbolic (trig) functions is how they can be represented as sums of exponentials (and vice versa). Recall that $\cosh(u) = \dfrac{e^u + e^{-u}}{2}$ and $\sinh(u) = \dfrac{e^u - e^{-u}}{2}$ . It's just a matter of how you want to indicate the constants that come about from your initial conditions. For example, since you're used to the solution $Y(y) = Ce^{\lambda y} + De^{-\lambda y}$ . Here's how you could express the same solution with hyperbolic trig functions (namely $\cosh$ and $\sinh$ ). Let $C = \frac{A+B}{2}$ and $D=\frac{A-B}{2}$ . Then $$ Ce^{\lambda y} + De^{-\lambda y} \\ = \frac{A+B}{2}e^{\lambda y} + \frac{A-B}{2}e^{-\lambda y} \\ = \frac{A}{2}e^{\lambda y} + \frac{B}{2}e^{\lambda y} + \frac{A}{2}e^{-\lambda y} - \frac{B}{2}e^{-\lambda y} \\ = \frac{A}{2}(e^{\lambda y} + e^{-\lambda y}) + \frac{B}{2}(e^{\lambda y} - e^{-\lambda y}) \\ = A \frac{e^{\lambda y} + e^{-\lambda y}}{2} + B \frac{e^{\lambda y} - e^{-\lambda y}}{2} \\ = A\cosh(\lambda y) + B \sinh(\lambda y).$$ Again, notice that the only thing that changed was really how you defined the constants with a relation from $C,D$ to $A,B$ . I stress that these are direct results from your initial (or given) conditions. As far as your question from the comments, "Why write it in that way instead of just the exponentials?", it is really a matter of conveniently denoting the properties of a solution. In an analogous fashion, even your familiar sines and cosines are merely just one way of expressing solutions to almost identical differential equations. Since $\cos(u) = \dfrac{e^{iu}+e^{-iu}}{2}$ and $\sin(u) = \dfrac{e^{iu}+-e^{-iu}}{2i}$ (where $i^2 = -1$ ), it depends on the context of your problem or possibly just your preference of where to write a solution as $P\cos(x)+Q\sin(x)$ or in the form $Ue^{ix}+Ve^{-ix}$ . It is straightforward to relate the constants $P,Q$ to $U,V$ in the same way that $A,B$ and $C,D$ were related for the hyperbolic trig case. There are several examples that I'd love to present to show why expressing your solutions as a sum of hyperbolic trig functions. There are properties of hyperbolic trig functions that are so closely related to the familiar circular trig functions that manipulating them can be very natural (as opposed to working with a sum of 2 exponentials). For example, let's say your solution was expressed as $y(x) = C\cosh(mx)+D\sinh(mx)$ . How would you find the $n$ -th derivative of $y(x)$ ? Since $\frac{d}{dx}[\cosh{mx}] = m\sinh(mx)$ and $\frac{d}{dx}[\sinh{mx}] = m\cosh(mx)$ , it's very easy to express the derivatives of $y(x)$ : $$ y(x) = y^{(0)}(x) = C\cosh(mx)+D\sinh(mx) \\y'(x) = y^{(1)}(x) = Cm\sinh(mx) + Dm\cosh(mx) \\y''(x) = y^{(2)}(x) = Cm^2\cosh(mx)+Dm^2\sinh(mx) \\y'''(x) = y^{(3)}(x) = Cm^3\sinh(mx) + Dm^3\cosh(mx) \\\vdots$$ | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1561716', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']} | jdg_86177 |
stackexchange | llm_judgeable_groundtruth_similarity | 4568464 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In SQL Server stored procedures when to use temporary tables and when to use cursors. which is the best option performance wise?
Now provide the response and nothing else.
| If ever possible avoid cursors like the plague. SQL Server is set-based - anything you need to do in an RBAR (row-by-agonizing-row) fashion will be slow, sluggish and goes against the basic principles of how SQL works. Your question is very vague - based on that information, we cannot really tell what you're trying to do. But the main recommendation remains: whenever possible (and it's possible in the vast majority of cases), use set-based operations - SELECT, UPDATE, INSERT and joins - don't force your procedural thinking onto SQL Server - that's not the best way to go. So if you can use set-based operations to fill and use your temporary tables, I would prefer that method over cursors every time. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4568464', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/238306/']} | jdg_86178 |
stackexchange | llm_judgeable_groundtruth_similarity | 168177 |
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
So, my aim is to produce a user interface with checkboxes not only returning True / False , but also the order in which they were selected. The final goal is an intuitive or comprehensive user interface (.cdf compatible) in which several parameters could be added/removed. The expected behaviour is a ranked list of controls. If one unmarks control b, (which was initially at rank 2) then control c (previously rank 3) has to be set to rank 2. And a renewed selection of b, would set it at rank 3. That's the principle. I actually managed to produce the desired result... but through an INSANELY COMPLICATED and LONG code!!! Please help me to get that in a few lines! :) DynamicModule[{a, b, c, a1, b1, c1}, Panel@Row[{Legended[ Panel@Column@{Dynamic@ Button[Control[{{a, True, "a"}, {True, False}}], { a = If[a, False, True], If[Not@a, {If[b1 == 3, b1 = 2, If[And[b1 == 2, c1 =!= 1], b1 = 1]], If[c1 == 3, c1 = 2, If[And[c1 == 2, b1 =!= 1], c1 = 1]]}], a1 = If[Not@a, 0, If[And[b, c], 3, If[Nor[b, c], 1, 2]]] }, Appearance -> "Frameless"], Dynamic@Button[Control[{{b, True, "b"}, {True, False}}], { b = If[b, False, True], If[Not@b, {If[a1 == 3, a1 = 2, If[And[a1 == 2, c1 =!= 1], a1 = 1]], If[c1 == 3, c1 = 2, If[And[c1 == 2, a1 =!= 1], c1 = 1]]}], b1 = If[Not@b, 0, If[And[a, c], 3, If[Nor[a, c], 1, 2]]] }, Appearance -> "Frameless"], Dynamic@Button[Control[{{c, True, "c"}, {True, False}}], { c = If[c, False, True], If[Not@c, {If[a1 == 3, a1 = 2, If[And[a1 == 2, b1 =!= 1], a1 = 1]], If[b1 == 3, b1 = 2, If[And[b1 == 2, a1 =!= 1], b1 = 1]]}], c1 = If[Not@c, 0, If[And[b, a], 3, If[Nor[b, a], 1, 2]]] }, Appearance -> "Frameless"]}, Placed["Controls", Above]], Spacer[25], Legended[Panel[Dynamic /@ {a1, b1, c1}], Placed["Ranks", Above]]}], Initialization :> {{a1, b1, c1} = {1, 2, 3}}] For sure, Slot or SlotSequence has to be integrated, but I failed in it. Yes, I guess that wrapping a checkbox in a button isn't that clean... I do not need more that 3 parameters, but why not find a generalised solution for more? :-D Thank you!!!
Now provide the response and nothing else.
| Try this: DynamicModule[{pos = Range[3]}, Panel[Row[{Column[{"Controls", CheckboxBar[Dynamic[pos], {1 -> "a", 2 -> "b", 3 -> "c"}, Appearance -> "Vertical"]}], Column[{"Ranks", Dynamic[Pane[ReplacePart[{0, 0, 0}, Thread[pos -> Range[Length[pos]]]]]]}]}]]] | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/168177', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/47532/']} | jdg_86179 |
stackexchange | llm_judgeable_groundtruth_similarity | 159763 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
The Goedel incompleteness theorems can be considered meta-mathematical theorems, as they are "written" in a meta-theory and "talk" about properties of a class of formal theories. The following may be a naive question, but... Are there any "interesting" results at the next level, i.e. so to speak, that take place in a meta-meta-theory and talk about meta-theories and properties thereof and the theories they describe/codify?
Now provide the response and nothing else.
| In Reverse Mathematics, we can study what happens if we use weak systems of second-arithmetic as metatheories. For example, we can study the strength of the completeness theorem and prove results such as "Gödel’s completeness theorem is equivalent to $\mathsf{WKL}_0$ over $\mathsf{RCA}_0$." That can be seen as a meta-meta-theorem: we are investigating which axioms are required in the metatheory for the completeness theorem to hold. This is not as trivial as it may sound; some results are genuinely unexpected. For example, one interesting fact is that every countable $\omega$-model $M$ of $\mathsf{WKL}_0$ contains a real $C$ that codes a countable $\omega$-model of $\mathsf{WKL}_0$. Due to other weaknesses of $\mathsf{WKL}_0$, this does not cause $\mathsf{WKL}_0$ to be inconsistent! We identify the coded $\omega$-model $C$ not within $M$, but at a level one step above $M$; the model $M$ will not, in general, recognize that $C$ satisfies $\mathsf{WKL}_0$. So we are viewing $\mathsf{WKL}_0$ as our metatheory and our object theory, but not as our meta-meta-theory - we cannot prove the desired result in $\mathsf{WKL}_0$ because of incompleteness phenomena. | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/159763', 'https://mathoverflow.net', 'https://mathoverflow.net/users/4721/']} | jdg_86180 |
stackexchange | llm_judgeable_groundtruth_similarity | 54635382 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have nodejs app that needs a few infinite loops which call async functions. I was considering implementing the following: async function execute1() { ...do some async work...}async function execute2() { ...do some async work...}setInterval(execute1, 500)setInterval(execute2, 500) My concern is that if the async functions will take a long time to complete, the open references will pile up and this can result in a memory crash down the line. is setInterval the right tool for this job? is there a more suitable tool? What is the most elegant method to make sure the execute() function will not start if the previous run hasn't return?
Now provide the response and nothing else.
| setInterval isn't the right tool because it's unaware of promises and can't maintain correct control flow. It can be async function with infinite loop: async function execute1() { while (true) { await new Promise(resolve => setTimeout(resolve, 500)); // ...do some async work... }}execute1(); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/54635382', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/218677/']} | jdg_86181 |
stackexchange | llm_judgeable_groundtruth_similarity | 28344126 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How to make one item in a combobox unselectable because I need to separate items in a combobox with a sub-topic . And is it possible to modify the font of that particular item individually? jComboBox_btech_course.setFont(new java.awt.Font("Tahoma", 0, 14)); jComboBox_btech_course.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Select Course" })); jComboBox_btech_course.setName("");private class theHandler implements ActionListener{ public void actionPerformed(ActionEvent evt) { //BTech courses if(jComboBox_mtech_dept.getSelectedItem().equals("Civil Engineering")) { jComboBox_btech_course.removeAllItems(); jComboBox_btech_course.addItem("Building Construction"); jComboBox_btech_course.addItem("Principle And Practice"); jComboBox_btech_course.addItem("Surveying"); jComboBox_btech_course.addItem("Engineering Geology"); jComboBox_btech_course.addItem("Structural Analysis"); jComboBox_btech_course.addItem("Hydraulic Engineering"); jComboBox_btech_course.addItem("Environmental Engineering"); jComboBox_btech_course.addItem("Structural Design"); jComboBox_btech_course.addItem("Geotechnical Engineering"); /*This item has to be unselectable*/ jComboBox_btech_course.addItem("***Sub-topic***"); jComboBox_btech_course.addItem("Transportation Engineering"); jComboBox_btech_course.addItem("Foundation Engineering"); jComboBox_btech_course.addItem("Estimation & Valuation"); jComboBox_btech_course.addItem("Hydrology & Flood Control"); jComboBox_btech_course.addItem("System Analysis, Project Planning And Construction Management"); jComboBox_btech_course.addItem("Irrigation Engineering"); jComboBox_btech_course.addItem("Computer Application in Civil Engineering"); jComboBox_btech_course.addItem("Planning, Design & Detailing"); } }}
Now provide the response and nothing else.
| Foreword: In the proposed solution I assume that you want to disable items that start with "**" . You can change this logic to whatever you want to. In an improved version the MyComboModel class (see below) may even store which items are disabled allowing arbitrary items to be marked disabled. Solution to your question involves 2 things: 1. Disallow selecting items which you want to be disabled For this you can use a custom ComboBoxModel , and override its setSelectedItem() method to do nothing if the item to be selected is a disabled one: class MyComboModel extends DefaultComboBoxModel<String> { public MyComboModel() {} public MyComboModel(Vector<String> items) { super(items); } @Override public void setSelectedItem(Object item) { if (item.toString().startsWith("**")) return; super.setSelectedItem(item); };} And you can set this new model by passing an instance of it to the JComboBox constructor: JComboBox<String> cb = new JComboBox<>(new MyComboModel()); 2. Display disabled items with different font For this you have to use a custom ListCellRenderer and in getListCellRendererComponent() method you can configure different visual appearance for disabled and enabled items: Font f1 = cb.getFont();Font f2 = new Font("Tahoma", 0, 14);cb.setRenderer(new DefaultListCellRenderer() { @Override public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) { if (value instanceof JComponent) return (JComponent) value; boolean itemEnabled = !value.toString().startsWith("**"); super.getListCellRendererComponent(list, value, index, isSelected && itemEnabled, cellHasFocus); // Render item as disabled and with different font: setEnabled(itemEnabled); setFont(itemEnabled ? f1 : f2); return this; }}); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28344126', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4441536/']} | jdg_86182 |
stackexchange | llm_judgeable_groundtruth_similarity | 3786941 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How does the || works in Perl? I want to achieve c style || operation. @ARRAY=qw(one two THREE four);$i=0;if(($ARRAY[2] ne "three")||($ARRAY[2] ne "THREE")) #What's the problem with this{ print ":::::$ARRAY[2]::::::\n";}while(($ARRAY[$i] ne "three")||($ARRAY[$i] ne "THREE")) #This goes to infinite loop{ print "->$ARRAY[$i]\n"; $i=$i+1;}
Now provide the response and nothing else.
| It works exactly the way you thought it would. However, you have a thinko in your condition. Every value is either not one value or not another value. I believe you might have wanted if ($ARRAY[2] ne 'three' && $ARRAY[2] ne 'THREE') { ... or if ($ARRAY[2] eq 'three' || $ARRAY[2] eq 'THREE') { ... You might also want some case-insensitive way of comparing, like if (lc $ARRAY[2] ne 'three') { ... or possibly a case-insensitive regexp match. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3786941', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/430294/']} | jdg_86183 |
stackexchange | llm_judgeable_groundtruth_similarity | 27329137 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to use new Android Toolbar pattern instead of ActionBar.I add a Toolbar as SupportActionBar from appCompat v21 and now, I want to hide/show it with animation while scrolling listView items.before, I use methods: actionBar.show() and actionBar.hide() and it animate automatically. but now, in Toolbar it hide and show without any animation.What should I do??? Activity Layout: <include layout="@layout/toolbar_actionbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="@dimen/actionbar_margin" /> Toolbar Layout: <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"android:id="@+id/toolbarActionbar_T_actionToolbar"android:layout_width="match_parent"android:layout_height="wrap_content"android:minHeight="?attr/actionBarSize"android:background="?attr/colorPrimary"app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" /> Activity Java: actionToolbar = (Toolbar) findViewById(R.id.toolbarActionbar_T_actionToolbar);setSupportActionBar(actionToolbar); ScreenShot:
Now provide the response and nothing else.
| What you need is a scroll listener. It detects whether you scroll up or down and hides or shows the Toolbar accordingly. Also known as the ' Quick Return ' pattern. Apart from just using the hide() and show() methods, for the animation, you must do it like this: For hiding: toolbarContainer.animate().translationY(-toolbarHeight).setInterpolator(new AccelerateInterpolator(2)).start(); For showing the Toolbar: toolbarContainer.animate().translationY(0).setInterpolator(new DecelerateInterpolator(2)).start(); For further reading, you can refer this tutorial .It talks about a Floating Action Button, but its the same animation for a Toolbar. Or find its code at GitHub . You can do this quite simply without any external library. :-) UPDATE You no longer need to manually maintain any listener. The Design Support library by Android enables you to do this with pure XML. Here's the XML Snippet to enable a Quick Return: <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"android:layout_width="match_parent"android:layout_height="match_parent"><android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <android.support.v7.widget.Toolbar android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" app:layout_scrollFlags="scroll|enterAlways" /></android.support.design.widget.AppBarLayout><android.support.v7.widget.RecyclerView android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" /> The key lies in this line: app:layout_scrollFlags="scroll|enterAlways" You can read more about implementing Quick Return with the Design Support library, here . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27329137', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3266253/']} | jdg_86184 |
stackexchange | llm_judgeable_groundtruth_similarity | 39193419 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a docker container which does alot of read/write to disk. I would like to test out what happens when my entire docker filesystem is in memory. I have seen some answers here that say it will not be a real performance improvement, but this is for testing. The ideal solution I would like to test is sharing the common parts of each image and copy to your memory space when needed. Each container files which are created during runtime should be in memory as well and separated. it shouldn't be more than 5GB fs in idle time and up to 7GB in processing time. Simple solutions would duplicate all shared files (even those part of the OS you never use) for each container.
Now provide the response and nothing else.
| There's no difference between the storage of the image and the base filesystem of the container, the layered FS accesses the images layers directly as a RO layer, with the container using a RW layer above to catch any changes. Therefore your goal of having the container running in memory while the Docker installation remains on disk doesn't have an easy implementation. If you know where your RW activity is occurring (it's fairly easy to check the docker diff of a running container), the best option to me would be a tmpfs mounted at that location in your container, which is natively supported by docker (from the docker run reference ): $ docker run -d --tmpfs /run:rw,noexec,nosuid,size=65536k my_image | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/39193419', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/780027/']} | jdg_86185 |
stackexchange | llm_judgeable_groundtruth_similarity | 53868070 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a text which was earlier wrapped in an H1 tag. I need to focus on that text once my page is loaded. I wrapped it in a div for my convenience. render() { const { translate, billing: { primaryContactSelection = true } } = this.props; return ( <div {...resolve(BillingStyles, 'billingContainer')}> <div id="mainHeader"><h1 {...resolve(BillingStyles, 'mainHeader')}> {translate('PanelBillingHeadingText')} </h1> </div> <div {...resolve(BillingStyles, 'billingInfoContainer')}> ...... ...... </div> </div> ); }} I have tried the below code: componentDidMount() { console.log('Component Did Mount .............'); document.getElementById('#mainHeader').focus(); } But it is not focusing on the div.
Now provide the response and nothing else.
| First div elements are not focusable by default so you need to give it a tabIndex : render() { const { translate, billing: { primaryContactSelection = true } } = this.props; return ( <div {...resolve(BillingStyles, 'billingContainer')}> <div tabIndex="0" id="mainHeader"><h1 {...resolve(BillingStyles, 'mainHeader')}> {translate('PanelBillingHeadingText')} </h1> </div> <div {...resolve(BillingStyles, 'billingInfoContainer')}> ...... ...... </div> </div> ); }} Next make sure you don't include the hashtag when calling getElementById, so it should be : componentDidMount() { console.log('Component Did Mount .............'); document.getElementById('mainHeader').focus(); } And that should work from there. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/53868070', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2323150/']} | jdg_86186 |
stackexchange | llm_judgeable_groundtruth_similarity | 31088974 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to know that how can we use sort or sorted function for multidimensional array in Swift? For example theirs an array: [ [5, "test888"], [3, "test663"], [2, "test443"], [1, "test123"]] And I want to sort it via the first ID's low to high: [ [1, "test123"], [2, "test443"], [3, "test663"], [5, "test888"]] So how can we do this? Thanks!
Now provide the response and nothing else.
| You can use sort : let sortedArray = arr.sort { ($0[0] as? Int) < ($1[0] as? Int) } Result: [[1, test123], [2, test443], [3, test663], [5, test123]] We optionally cast the parameter as an Int since the content of your arrays are AnyObject. Note: sort was previously named sorted in Swift 1. No problem if you declare the internal arrays as AnyObject, an empty one won't be inferred as an NSArray: var arr = [[AnyObject]]()let sortedArray1 = arr.sort { ($0[0] as? Int) < ($1[0] as? Int) }print(sortedArray1) // []arr = [[5, "test123"], [2, "test443"], [3, "test663"], [1, "test123"]]let sortedArray2 = arr.sort { ($0[0] as? Int) < ($1[0] as? Int) }print(sortedArray2) // [[1, test123], [2, test443], [3, test663], [5, test123]] | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31088974', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2603230/']} | jdg_86187 |
stackexchange | llm_judgeable_groundtruth_similarity | 27045899 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
We have two tables Spot and Spot_Log with the following data: Spot: ESN | Department | VehicleModel | AssignedToName--------------------------------------------------------0-2506698 | 23 | 2014 Equinox | Ron0-2507419 | 32 | 2015 Sierra | Chuck0-2506208 | 32 | 2015 Sierra | Don0-2506629 | 32 | 2014 Silverado | Jonathan Spot_Log: ESN_ID | est_dt | latitude | longitude -----------------------------------------------------0-2506698 | 20/11/2014 11:08 | 43.712910 | -79.3677980-2506698 | 20/11/2014 10:43 | 43.713322 | -79.3597410-2506698 | 20/11/2014 10:39 | 43.713341 | -79.3597410-2506629 | 20/11/2014 10:07 | 48.412701 | -89.2480470-2506629 | 20/11/2014 10:02 | 48.412720 | -89.2480470-2506629 | 20/11/2014 10:01 | 48.412788 | -89.2481080-2506698 | 20/11/2014 09:26 | 43.714870 | -79.3577580-2506698 | 20/11/2014 09:21 | 43.714729 | -79.3578190-2506698 | 20/11/2014 07:15 | 43.993961 | -79.2294010-2506698 | 20/11/2014 07:11 | 44.018250 | -79.2305910-2506629 | 19/11/2014 19:01 | 48.412682 | -89.2478870-2506629 | 19/11/2014 16:53 | 48.412670 | -89.2479930-2506629 | 19/11/2014 16:48 | 48.412670 | -89.2479630-2506208 | 19/11/2014 16:43 | 48.399891 | -89.2575990-2506629 | 19/11/2014 16:39 | 48.404961 | -89.2528080-2506208 | 19/11/2014 16:38 | 48.399940 | -89.2577210-2506698 | 19/11/2014 16:37 | 44.096931 | -79.1290280-2506208 | 19/11/2014 16:33 | 48.399872 | -89.257690-2506698 | 19/11/2014 16:32 | 44.096951 | -79.1290590-2506208 | 19/11/2014 16:31 | 48.402531 | -89.2540890-2506698 | 19/11/2014 16:27 | 44.080601 | -79.159790-2506698 | 19/11/2014 15:07 | 43.765202 | -79.3768010-2506698 | 19/11/2014 14:59 | 43.732059 | -79.4403380-2507419 | 19/11/2014 14:49 | 48.399891 | -89.257660-2507419 | 19/11/2014 14:43 | 48.399879 | -89.257660-2507419 | 19/11/2014 14:38 | 48.399830 | -89.2577210-2507419 | 19/11/2014 14:34 | 48.399899 | -89.257690-2507419 | 19/11/2014 14:00 | 48.399872 | -89.25766 All we have to do is pick the LATEST data based on the column Spot_Log.est_dt for each vehicle listed in the Spot table as follows: ESN | Department | VehicleModel | AssignedToName | est_dt | latitude | longitude ----------------------------------------------------------------------------------------------------0-2506698 | 23 | 2014 Equinox | Ron | 20/11/2014 11:08 | 43.712910 | -79.3677980-2507419 | 32 | 2015 Sierra | Chuck | 19/11/2014 14:49 | 48.399891 | -89.257660-2506208 | 32 | 2015 Sierra | Don | 19/11/2014 16:43 | 48.399891 | -89.2575990-2506629 | 32 | 2014 Silverado | Jonathan | 20/11/2014 10:07 | 48.412701 | -89.248047 Since right now there are 4 records in the Spot table it should return 4 latest records. I have tried the following queries which shows all the rows despite DISTINCT and the join condition is mentioned SELECT s.ESN, s.AssignedToName, s.Department, sl.est_dt, sl.latitude, sl.longitudeFROM SpotTrace s, SpotTrace_Log slWHERE s.ESN = sl.ESN_ID ORDER BY s.ESN, sl.est_dt DESC;SELECT DISTINCT s.ESN, s.AssignedToName, s.Department, sl.est_dt, sl.latitude, sl.longitudeFROM SpotTrace s, SpotTrace_Log slWHERE s.ESN = sl.ESN_ID ORDER BY s.ESN, sl.est_dt DESC I have also tried Limit 4 but it only shows the first 4 of all the rows as shown above. SELECT DISTINCT s.ESN, s.AssignedToName, s.Department, sl.est_dt, sl.latitude, sl.longitudeFROM SpotTrace s, SpotTrace_Log slWHERE s.ESN = sl.ESN_ID ORDER BY s.ESN, sl.est_dt DESCLIMIT 4; Thanks for your kind help.
Now provide the response and nothing else.
| You can definitely make a dictionary of dictionaries. However, you need a different syntax for that: var myDictOfDict:NSDictionary = [ "a" : ["fname": "abc", "lname": "def"], "b" : ["fname": "ghi", "lname": "jkl"], ... : ...] What you have looks like an array of dictionaries, though: var myArrayOfDict: NSArray = [ ["fname": "abc", "lname": "def"], ["fname": "ghi", "lname": "jkl"], ...] To get JSON that looks like this {"Data": [{"User": myDict1}, {"User": myDict1},...]} you need to add the above array to a dictionary, like this: var myDict:NSDictionary = ["Data" : myArrayOfDict] | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/27045899', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/886110/']} | jdg_86188 |
stackexchange | llm_judgeable_groundtruth_similarity | 23630668 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have an array that looks like this static String[][][] School= new String[1000][20][5]; In the first bracket I save the class name In the second I save an ID of a student In the third I save information about the student (his name, family name etc). First I assign all the class names, after that I assign to every class its student ID and then I can fill in their information. How can I do it? I tried it with for example School[i] = "A1"; but it's not working. EDIT: Or is there an other way to save this all 3 things? (class name, its students and its iformation)
Now provide the response and nothing else.
| static String[][][] School= new String[1000][20][5]; Consider figure which has 3 Dimension. So when you insert School[0][0][0]="A1" it means you have entered element at 0,0,0 position. From 0,0,0 this will move upto the position 1000,20,5. You can insert like this But you have so many elements. School[0][0][0]="A1"School[0][0][1]="A2"School[0][0][2]="A3".....School[0][1][0]="B1"School[0][1][1]="B2"School[0][1][2]="B3"...... In 3D array elements look like int[3][4][2] array3D// means Three (4x2) 2 Dimensional Arrays int[4][2] //means Four 1 dimensional arrays. Now how to add elements in 3D array? At Start you can directly use int[][][] threeDArray = { { {1, 2, 3}, { 4, 5, 6}, { 7, 8, 9} }, { {10, 11, 12}, {13, 14, 15}, {16, 17, 18} }, { {19, 20, 21}, {22, 23, 24}, {25, 26, 27} } }; This is very tedious task in your case as you want to insert details at every position.As you have 1000 records. Your array will have elements like this NOTE : It's not recommended to use 3D array for this purpose. Suggestion : Declare a class with three Strings create constructor with this three parameters and put getter and setters to get and set values via Objects | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23630668', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3549340/']} | jdg_86189 |
stackexchange | llm_judgeable_groundtruth_similarity | 868682 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
If $f:[a,b]\to\mathbb{R}$ is a continuous function and $f(x)\in\mathbb{Q}$ for all $x\in[a,b]$ then what can say about $f$? My try: I think f should be constant, if it is not constant then it contradicts the continuity. Can anyone prove that f is constant?
Now provide the response and nothing else.
| We proceed by contradiction: Assume that $$\begin{cases}a\le x,y\le b \\f(x)\ne f(y)\end{cases}$$ WLOG assume $f(x)<f(y)$ (if not: switch their labels). Then by the intermediate value theorem, $f$ takes all values in the interval $[f(x),f(y)]$. Since there are infinitely many irrationals between any two real numbers, $f$ takes on an irrational value: a contradiction. So $f$ is constant. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/868682', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/163998/']} | jdg_86190 |
stackexchange | llm_judgeable_groundtruth_similarity | 10769162 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
We are considering node.js as a web platform. But I have one crucial question, because I think I don't get the architecture of node.js : It looks like that by default you're forced to use their custom HTTP server, no WSGI or anything?! It looks like that when doing some "real computation" in a response (not only some I/O), all the infrastructure is messed up and ab -n ... -c ... returns enormous times per request compared with e.g. Python -- Pyramid/Flask or whatever?! So, authors of node.js assume that we're doing only I/O or I've missed something very basic?
Now provide the response and nothing else.
| You contradict yourself: "by default" and "forced" are not compatible. You can use whatever HTTP library you want. The core http module may be thought of as a "default," but nothing stops you from using another. JavaScript is a single-threaded language, and Node.js is a JavaScript runtime, not a web server that spawns a thread-per-response like many others. You can still do a thread per response if you want, and there are projects built on top of Node that do this, but you lose most of the benefits of Node. If you are doing computation-heavy stuff in response to a web request (and you have clients who are willing to wait for you to do it), you should spin off a separate thread via one of the many available solutions (web workers, threads-a-go-go, child_process, etc.). The authors of Node.js assume you are writing a web server. Most of the things you do in a web server are, essentially, IO, whether that IO involves a filesystem, a database, or even a message bus used for queuing computationally-intensive tasks on other workhouse processes. Looking over your question, you seem to have a basic misunderstanding of what Node.js is, if you're trying to integrate it with Python and WSGI. Node.js is for writing web servers, so trying to use it... alongside Python? inside Python? (I'm really not sure what you're trying to accomplish) makes little sense. If your tasks are not only I/O bound, you should probably not be hosting those tasks on the same box as your web server. Thus, the message bus approach mentioned briefly in 3. But if you are determined to do so, and are sure that those tasks won't hog all the CPU, you should determine how often such tasks are prevalent. If they are on every web request, you should not use Node.js; you are giving up its most basic advantages, leaving only minor ones (like the ecosystem that's grown up around it). If they are rare, then you should spin them off in separate threads via the many methods available in 2. Relevant: https://gist.github.com/2794861 | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10769162', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/684534/']} | jdg_86191 |
stackexchange | llm_judgeable_groundtruth_similarity | 19350260 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
The smallest number of internal nodes in a red-black tree with black height of k is 2 k -1 which is one in the following image: The largest number of internal nodes with black height of k is 2 2k -1 which, if the black height is 2, should be 2 4 - 1 = 15. However, consider this image: The number of internal nodes is 7. What am I doing wrong?
Now provide the response and nothing else.
| (I've completely rewritten this answer because, as the commenters noted, it was initially incorrect.) I think it might help to think about this problem by using the isometry between red-black trees and 2-3-4 trees . Specifically, a red-black tree with black height h corresponds to a 2-3-4 tree with height h, where each red node corresponds to a key in a multi-key node. This connection makes it easier for us to make a few neat observations. First, any 2-3-4 tree node in the bottom layer corresponds to a black node with either no red children, one red child, or two red children. These are the only nodes that can be leaf nodes in the red-black tree. If we wanted to maximize the number of total nodes in the tree, we'd want to make the 2-3-4 tree have nothing but 4-nodes, which (under the isometry) maps to a red/black tree where every black node has two red children. An interesting effect of this is that it makes the tree layer colors alternate between black and red, with the top layer (containing the root) being black. Essentially, this boils down to counting the number of internal nodes in a complete binary tree of height 2h - 1 (2h layers alternating between black and red). This is equal to the number of nodes in a complete binary tree of height 2h - 2 (since if you pull off all the leaves, you're left with a complete tree of height one less than what you started with). This works out to 2 2h - 1 - 1, which differs from the number that you were given (which I'm now convinced is incorrect) but matches the number that you're getting. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19350260', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2808178/']} | jdg_86192 |
stackexchange | llm_judgeable_groundtruth_similarity | 63534 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I found in an article "Imperfect Bose Gas with Hard-Sphere Interaction" , Phys. Rev. 105, 776–784 (1957) the following integral, but I don't know how to solve it. Any hints? $$\int_0^\infty {\int_0^\infty {\mathrm dp\mathrm dq\frac{\sinh(upq)}{q^2 - p^2}pq} } e^{-vq^2 - wp^2} = \frac{\pi}{4}\frac{u(w - v)}{\left[(w + v)^2-u^2 \right]\left(4wv-u^2\right)^{1/2}}$$ for $u,v,w > 0$.
Now provide the response and nothing else.
| First of all one can note that the integral converges and is a differentiable function of parameters for $4vw>u^2$. With the change of variables $p\to p' u^{1/2}$, $q\to q' u^{1/2}$ the general case be reduced to $u=1$. Now denoting the lhs$$f(v,w)=\int_0^\infty {\int_0^\infty {\mathrm dp\mathrm dq\frac{\sinh(pq)}{q^2 - p^2}pq} } e^{-vq^2 - wp^2}$$we have $$\frac{\partial}{\partial v}f(v,w)-\frac{\partial}{\partial w}f(v,w)=\int_0^\infty {\int_0^\infty {\mathrm dp\mathrm dq\sinh(pq)pq}} e^{-vq^2 - wp^2}=\frac{\pi }{2 (4 v w-1)^{3/2}},$$the integral converging for $vw>1/4$. Since $f(w,v)=-f(v,w)$ we have $f(v,v)=0\;$. The solution of this Cauchy problem can be obtained in the standard way (rotating the coordinate system on $\pi/4$ etc.): $$f(v,w)=\frac{\pi (w-v)}{4 \left((v+w)^2-1\right)\sqrt{4 v w-1} }\;.$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/63534', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/15860/']} | jdg_86193 |
stackexchange | llm_judgeable_groundtruth_similarity | 449914 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Function of shown circuit is biasing of output power stage complementary audio amplifier. P1 allows precise adjustment of \$ V_{CE} \$ of VBE multiplier and \$C_B\$ improves its rail rejection. \$ r_e' \$ negates unwanted effects of \$ r_e \$ , also known as current-dependent emitter resistance. simulate this circuit – Schematic created using CircuitLab In book about construction of audio amplifiers, writer G. Randy Slone wrote next about this circuit and \$ r_e \$ effect cancellation: "Re prime (that is \$ r_e \$ ) manifests itself as small Vbias changes brought on by power supply rail variations and small current variations through Qbias relevant to temperature. To negate the effects of re prime, a resistor can be placed in the collector circuit of Qbias to provide slight modification of the voltage drop across P1." I don't get it why has \$ r_e \$ any influence on \$ V_{CE} \$ of VBE multiplier regarding rail variation and current variation of Qbias due to temperature variations. Or does it represents and error regarding resistive voltage divider with potentiometer connected to base of Qbias? As far as I know, it is just a series resistance with emitter that changes with quiescent current of Qbias. Why would \$ r_e \$ cause any error in setting of bias voltage for the following output stage anyway? Also, in what manner \$ r_e' \$ opposes/ negates effects of \$ r_e \$ ?
Now provide the response and nothing else.
| I'd like to somewhat simplify the schematic you've got, so that we can temporarily avoid having to continually discuss the potentiometer when the real purpose is supposed to be trying to understand the circuit: simulate this circuit – Schematic created using CircuitLab In the above, I've provided a behavioral model on the left side. It's followed up on the 1st order BJT \$V_\text{BE}\$ multiplier topology without compensation for varying currents through the multiplier block in the middle example. On the right, is a 2nd order BJT \$V_\text{BE}\$ multiplier topology that includes compensation for varying currents through the block. Everything starts by analyzing the middle schematic. How you analyze it depends upon the tools you have available for analysis. One could use the linearized small-signal hyprid- \$\pi\$ model. But that assumes you fully understand and accept it. So, instead, let's take this from a more prosaic understanding of the BJT model that neglects any AC analysis. Instead, let's take it entirely from large signal DC models and just compare "nearby" DC results to see what happens. Let's assume that we are using a constant current source which can vary its current slightly, around some assumed average value of \$I_\text{src}=4\:\text{mA}\$ . For simplicity's sake, let's also assume that the value of the base-emitter junction, when \$I_\text{C}=4\:\text{mA}\$ exactly, is exactly \$V_\text{BE}\left(I_\text{C}=4\:\text{mA}\right)=700\:\text{mV}\$ . Assume the operating temperature is such that \$V_T=26\:\text{mV}\$ and that the operating temperature doesn't change regardless of variations in \$I_\text{src}\$ under consideration. Finally, we'll assume that variations in \$V_\text{BE}\$ follow the general rule developed from the following approximation: $$\begin{align*}\text{Assuming,}\\\\V_{BE}{\left(I_\text{C}\right)}&= V^{I_\text{C}=4\:\text{mA}}_\text{BE}+V_T\cdot\operatorname{ln}\left(\frac{I_\text{C}}{I_\text{C}=4\:\text{mA}}\right)\\\\&\therefore\\\\\text{The change in }&V_\text{BE}\text{ for a change in }I_\text{C}\text{ near }I_\text{C}=4\:\text{mA}\text{ is,}\\\\\Delta\, V_{BE}{\left(I_\text{C}\right)}&=V_{BE}{\left(I_\text{C}\right)}-V_{BE}{\left(I_\text{C}=4\:\text{mA}\right)}\\\\&=V_{BE}{\left(I_\text{C}\right)}-V^{I_\text{C}=4\:\text{mA}}_\text{BE}\\\\\text{Or, more simply,}\\\\\Delta\, V_{BE}{\left(I_\text{C}\right)}&=V_T\cdot\operatorname{ln}\left(\frac{I_\text{C}}{I_\text{C}=4\:\text{mA}}\right)\end{align*}$$ Is this enough to get you started? Remember, when the \$V_\text{BE}\$ multiplier is used as part of the class-AB amplifier's output stage, the current source itself varies somewhat with respect to power supply rail variations and also variations in the base drive for the output stage's upper and lower quadrants. (The upper quadrant, when it needs base drive current, will be siphoning off current away from the high-side source and therefore this will cause the current through the \$V_\text{BE}\$ multiplier to vary -- sometimes, depending on design values, varying a lot.) Can you work through some of the math involved here? Or do you need more help? (I just noted where that capacitor is sitting in your diagram. I think it should be between the collector and emitter. But who knows? Maybe I'm wrong about that. So let's leave that for a different question.) Usual \$V_\text{BE}\$ Multiplier Equation This will be a very simplified approach, for now. (The model here will need adjustments, later.) We'll assume that the bottom node ( \$V_-\$ ) will be grounded, for reference purposes. It doesn't matter if this node is attached to the collector of a VAS and the actual voltage moves up and down in a real amplifier stage. The purpose here is to figure out the \$V_\text{BE}\$ multiplier voltage at \$V_+\$ with respect to \$V_-\$ . Note that the base voltage of the BJT, \$V_\text{B}\$ , is also exactly the same as \$V_\text{BE}\$ . So \$V_\text{BE}=V_\text{B}\$ . I can use either one of these for the purposes of nodal analysis. I choose to use \$V_\text{BE}\$ as the name of the node at the BJT base. The simplified equation is: $$\frac{V_\text{BE}}{R_1}+\frac{V_\text{BE}}{R_2}+I_\text{B}=\frac{V_+}{R_1}$$ (The outgoing currents are on the left and the incoming currents are on the right. They must be equal.) We also have a current source. I'll call it \$I_\text{src}\$ . For the middle circuit above, part of that current passes through \$R_1\$ and the rest of it passes through the collector of \$Q_1\$ . The base current is the collector current ( \$I_\text{C}=I_\text{src}-\frac{V_+-V_\text{BE}}{R_1}\$ ) divided by \$\beta\$ . Given \$I_\text{B}=\frac{I_\text{C}}{\beta}\$ , we can rewrite the above equation: $$\frac{V_\text{BE}}{R_1}+\frac{V_\text{BE}}{R_2}+\frac{I_\text{src}-\frac{V_+-V_\text{BE}}{R_1}}{\beta}=\frac{V_+}{R_1}$$ Solving for \$V_+\$ , we find: $$V_+=V_\text{BE}\left(1+\frac{R_1}{R_2}\frac{\beta}{\beta+1}\right)+I_\text{src}\frac{R_1}{\beta}$$ When the second term is small (or neglected), then the first term can be simplified by assuming \$\beta\$ is large and the whole equation becomes: $$V_+=V_\text{BE}\left(1+\frac{R_1}{R_2}\right)$$ Which is the usual equation used to estimate the voltage of a \$V_\text{BE}\$ multiplier. Just keep in mind that this is highly simplified. In fact, too much so. The value of \$V_\text{BE}\$ is considered a constant and, in fact, it's not at all a constant. Instead, it is a function of the collector current. (Also, we neglected the second term. That term may matter enough to worry over, depending on the design.) Since the \$V_\text{BE}\$ multiplier actually multiplies \$V_\text{BE}\$ by some value greater than 1, any erroneous estimations about \$V_\text{BE}\$ will be multiplied. And since the current source used in a practical circuit is also providing the upper quadrant with base drive current for half of each output cycle before it reaches the \$V_\text{BE}\$ multiplier, the value of \$V_\text{BE}\$ will be varying for that half-cycle because its collector current will be also varying. Anything useful that can be done (cheaply) to improve how it varies in those circumstances should probably be done. One technique is to just slap a capacitor across the middle \$V_\text{BE}\$ multiplier circuit. But another technique is to use a collector resistor, \$R_\text{comp}\$ in the above right side schematic. Analyzing the Middle Schematic for Collector Current Variations None of the above equation development is all that useful for working out the effect of varying values for \$I_\text{src}\$ . There are a number of ways to work it out. One useful simplification is to imagine that there is a tiny resistor sitting inside of the BJT and located just prior to its emitter terminal: (Both of the above images were borrowed from page 193 of "Learning the Art of Electronics: A Hands-On Lab Course" by Thomas C. Hayes, with assistance from Paul Horowitz.) The above concept represents the dynamic resistance , which is just the local slope along a non-linear curve. This resistor is called \$r_e\$ and its value depends upon the emitter/collector current magnitude. You will see it as either \$r_e=\frac{V_T}{\overline{I_\text{C}}}\$ or as \$r_e=\frac{V_T}{\overline{I_\text{E}}}\$ , where \$\overline{I_\text{C}}\$ and \$\overline{I_\text{E}}\$ are some assumed mid-point on the curve around which those currents vary. It doesn't really matter which you use, because modern BJTs have rather high values for \$\beta\$ . So let's not fret over minutia and instead just assume \$r_e\$ is a function of the collector current. Note: In the following, I will continue to follow above book's approach in calling this \$r_e\$ , despite it being based upon thecollector current. In various literature, it may be denoted as \$r_e^{\,'}\$ and it may be based upon the emitter current, instead,as well. But for these purposes here, I intend to remain consistentwith the above book's approach. If we accept this simplification for now, then we can consider that there is an internal \$V^{'}_\text{BE}\$ with a fixed value that sits between the base terminal and the internal side of \$r_e\$ and we lump all of the variations in our observed external measurement of \$V_\text{BE}\$ as being due to the collector current passing through \$r_e\$ . This works okay as an approximate, improved model, so long as you don't deviate far from some assumed average collector current used to compute \$r_e\$ . (Small-signal assumption.) [If it really does vary a lot (for example, say, the collector current varies from \$10\:\mu\text{A}\$ to \$10\:\text{mA}\$ ), then the \$r_e\$ model ceases to be nearly so useful.] But let's say you design your current source so that \$I_\text{src}=4\:\text{mA}\$ and you don't expect the upper quadrant to require more than \$1\:\text{mA}\$ for its base drive. This means that your \$V_\text{BE}\$ multiplier will experience currents through it from \$3\:\text{mA}\$ to \$4\:\text{mA}\$ during operation. How much would you expect the \$V_\text{BE}\$ multiplier to vary its voltage under these varying circumstances? Well, that's actually pretty easy. We've now lumped all of the variation in \$V_\text{BE}\$ as a result of our model's \$r_e\$ , computed at some chosen mid-point collector current value. Since the multiplier multiplies the external, observable \$V_\text{BE}\$ and since that includes the effect of collector current upon \$r_e\$ we then can expect (using the highly simplified estimate developed earlier): $$V_+=\left(V^{'}_\text{BE}+I_\text{C}\cdot r_e\right)\left(1+\frac{R_1}{R_2}\right)$$ So the variation in \$V_+\$ is due to the second term in the first factor, or \$I_\text{C}\cdot r_e\cdot \left(1+\frac{R_1}{R_2}\right)\$ . (Note that \$I_\text{C}\$ in this factor is not the same as \$\overline{I_\text{C}}\$ used to compute \$r_e\$ so you cannot simplify the product of \$I_\text{C}\$ and \$r_e\$ here. In fact, the whole point in creating \$r_e\$ is that you can't make that cancellation.) If you lump the last two factors there into an effective "resistance" value that the collector current must go through, then that resistance would be \$r_e\cdot \left(1+\frac{R_1}{R_2}\right)\$ . Which is just what G36 mentioned as the effective resistance for the middle schematic. Adding a Collector Resistor to the \$V_\text{BE}\$ Multiplier Now, keep in mind that the collector current does in fact vary, in operation. Perhaps like I mentioned above. Perhaps more. Perhaps less. But it does vary. How important that is will depend on your schematic and your design choices. But let's assume it is important enough that you are willing to consider adding a cheap resistor to the collector leg as shown in the schematic on the right, above. (You've been told that this is a "good idea.") Why is this a good idea? Well, at first blush it should be easy to see that if the collector current in the middle circuit increases then the \$V_+\$ increases by some small amount. But what if we added a collector resistor? Wouldn't that mean that if the collector current increased, that the collector voltage itself would drop because of the change in the voltage drop through the collector resistor? Does this suggest to you that if you could pick the right value for this collector resistor, then you might be able to design it just right so that the increased drop across it just matched what would otherwise have been an increase in \$V_+\$ in the middle circuit? If you agree with that logic, can you also now work out how to compute a value for \$R_\text{comp}\$ that would be "just right" and then compute the new effective resistance of the new circuit? Just think about this for a moment. You have a \$V_\text{BE}\$ multiplier here and you know the approximate equation used to compute its voltage. But this equation doesn't take into account the fact that \$V_\text{BE}\$ changes when the collector current changes. The value of \$r_e\$ (at some design value for the collector current) is the tool that helps you quantify the change in \$V_\text{BE}\$ for changes in the collector current. And you know that the \$V_\text{BE}\$ multiplier will multiply that change, too. So if the collector current increases (because the upper quadrant stops requiring base drive current, leaving all of the current source's current to flow through the multiplier), then the multiplier's voltage will increase by the multiplied change in drop across \$r_e\$ . To counter this effect, you want the collector resistor's voltage drop to likewise increase by just that same amount. So, does that help you think about how to compute the collector resistor value? As a first approximation, wouldn't you want the value to be about \$R_\text{comp}\approx r_e\left(1+\frac{R_1}{R_2}\right)\$ so that when the change in collector current creates a multiplied change in \$V_\text{BE}\$ that the drop in this newly added collector resistor will just match up with it? More Detailed Analysis Related to Selecting \$R_\text{comp}\$ The actual multiplier voltage will be better approximated with the more complex version I developed from nodal analysis: $$V_+=V_\text{BE}\left(1+\frac{R_1}{R_2}\frac{\beta}{\beta+1}\right)+I_\text{src}\frac{R_1}{\beta}$$ For example, assume \$I_\text{src}=4\:\text{mA}\$ and an operating temperature that sets \$V_T=26\:\text{mV}\$ . Also, let's assume we use \$R_1=R_2=4.7\:\text{k}\Omega\$ . And let's assume \$\beta=200\$ for the BJT we have in hand, right now. Let's also assume that the base-emitter voltage is taken as \$V_\text{BE}=690\:\text{mV}\$ (I'm picking an odd value on purpose.) Then the first term's value is \$\approx 1.38\:\text{V}\$ . But the second term's value is \$\approx 100\:\text{mV}\$ . So we'd really be expecting perhaps \$\approx 1.48\:\text{V}\$ for the multiplier voltage. Now let's take the above equation and work through the details of what happens when the current passing through the \$V_\text{BE}\$ multiplier changes (which it will do because of the upper quadrant base drive variations, in operation): $$\newcommand{\dd}[1]{\text{d}\left(#1\right)}\newcommand{\d}[1]{\text{d}\,#1}\begin{align*}V_+&=V_\text{BE}\left(1+\frac{R_1}{R_2}\frac{\beta}{\beta+1}\right)+R_1\,\frac{I_\text{src}}{\beta}\\\\\dd{V_+}&=\dd{V_\text{BE}\left(1+\frac{R_1}{R_2}\frac{\beta}{\beta+1}\right)+R_1\,\frac{I_\text{src}}{\beta}}\\\\&=\dd{V_\text{BE}}\left(1+\frac{R_1}{R_2}\frac{\beta}{\beta+1}\right)+\dd{R_1\,\frac{I_\text{src}}{\beta}}\\\\&=\dd{I_\text{src}}\,r_e\,\left(1+\frac{R_1}{R_2}\frac{\beta}{\beta+1}\right)+\dd{I_\text{src}}\,\frac{R_1}{\beta}\\\\&=\dd{I_\text{src}}\,\left[r_e\,\left(1+\frac{R_1}{R_2}\frac{\beta}{\beta+1}\right)+\frac{R_1}{\beta}\right]\\\\&\therefore\\\\\frac{\d{V_+}}{\d{I_\text{src}}}&=r_e\,\left(1+\frac{R_1}{R_2}\frac{\beta}{\beta+1}\right)+\frac{R_1}{\beta}\end{align*}$$ The first term is about what I wrote earlier about the estimated impedance of the multiplier. But now we have a second term. Let's check out the relative values (given the above assumptions about specific circuit elements and assumptions.) Here, after accounting for the base resistor divider pair's current and the required base current, the first term is \$\approx 14\:\Omega\$ . The second term is \$\approx 24\:\Omega\$ . So the total impedance is \$\approx 38\:\Omega\$ . Please take close note that this is actually a fair bit larger than we'd have expected from the earlier simplified estimate! So the \$V_\text{BE}\$ multiplier is worse than hoped. Current changes will have a larger than otherwise expected change. This is something worth fixing with a collector resistor. Suppose we make the collector resistor exactly equal to this above-computed total resistance. Namely, \$R_\text{comp}=38\:\Omega\$ . The reason is that we expect that the change in voltage drop across \$R_\text{comp}\$ will just match the increase/decrease in the \$V_\text{BE}\$ multiplier as both are then equally affected by changes in the collector current due to changes in \$I_\text{src}\$ . (We have so far avoided directly performing a full analysis on the right-side schematic and we are instead just making hand-waving estimates about what to expect.) Given the prior estimated impedance and this circuit adjustment used to compensate it, we should expect to see almost no change in the voltage output if we used the right-side schematic. Here is the LTspice's schematic I used to represent the right-side, compensated schematic: And here is LTspice's plotted analysis of the \$V_+\$ output using a DC sweep: Note how well the output is compensated! Note the peak is located almost exactly where our nominal value for \$I_\text{src}\$ is located, too? The idea works! Both in terms of being compensated exactly where we want that compensation as well as in providing pretty good behavior nearby. Not bad!!! Appendix: Derivation of \$r_e\$ I'm sure you remember the equation I'll start with. Just follow the logic below: $$\newcommand{\dd}[1]{\text{d}\left(#1\right)}\newcommand{\d}[1]{\text{d}\,#1}\begin{align*}I_\text{C}&=I_\text{sat}\left[e^{^\frac{V_\text{BE}}{\eta\,V_T}}-1\right]\\\\\dd{I_\text{C}}&=\dd{I_\text{sat}\left[e^{^\frac{V_\text{BE}}{\eta\,V_T}}-1\right]}=I_\text{sat}\cdot\dd{e^{^\frac{V_\text{BE}}{\eta\,V_T}}-1}=I_\text{sat}\cdot\dd{e^{^\frac{V_\text{BE}}{\eta\,V_T}}}\\\\&=I_\text{sat}\cdot e^{^\frac{V_\text{BE}}{\eta\,V_T}}\cdot\frac{\dd{V_\text{BE}}}{\eta\,V_T}\end{align*}$$ Since \$I_\text{sat}\left[e^{^\frac{V_\text{BE}}{\eta\,V_T}}-1\right]\approx I_\text{sat}\cdot e^{^\frac{V_\text{BE}}{\eta\,V_T}}\$ (the -1 term makes no practical difference), we can conclude: $$\begin{align*}\dd{I_\text{C}}&=I_\text{C}\cdot\frac{\dd{V_\text{BE}}}{\eta\,V_T}\end{align*}$$ From which very simple algebraic manipulation produces: $$\newcommand{\dd}[1]{\text{d}\left(#1\right)}\newcommand{\d}[1]{\text{d}\,#1}\begin{align*}\frac{\dd{V_\text{BE}}}{\dd{I_\text{C}}}&=\frac{\d{V_\text{BE}}}{\d{I_\text{C}}}=\frac{\eta\,V_T}{I_\text{C}}=r_e\end{align*}$$ The idea here is that the active-mode BJT Shockley equation, relating the base-emitter voltage to the collector current, is an exponential curve (absent the -1 term, anyway) and the value of \$r_e\$ is a way of representing the local slope (tangent) of that curve. So long as the deviation of the collector current away from where this dynamic resistor value was computed is small, the value of \$r_e\$ doesn't change much and you then easily estimate the small change in \$V_\text{BE}\$ as being caused by the small change in collector current through this dynamic resistor. Since the collector current must be summed into the emitter current, \$r_e\$ is best "visualized" as "being right at the very tip of the emitter." This is so that changes in the collector current cause a change in the base-emitter voltage. (If you'd instead imagined \$r_e\$ as being at the collector tip, it would not affect the base-emitter voltage and so would be useless for the intended purpose.) | {} | {'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/449914', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/133145/']} | jdg_86194 |
stackexchange | llm_judgeable_groundtruth_similarity | 48661907 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to create a list containing indices that would be used to get elements from another list. A simple case: A = [5,6,7,8,9,10] b = 2:4 I want to then do something like C = A[b] Which would be like saying C = A[2:4] I want to later extend this to multidimensional arrays, where e.g b = [2:4, 5:6] and I can simply call A[b] to extract a multidimensional array out of A.
Now provide the response and nothing else.
| You can define b as a slice object to achieve this: In[9]:A = [5,6,7,8,9,10] b = slice(2,4)A[b]Out[9]: [7, 8] Regarding your other requirement I think if you create a list object containing 2 slice objects then it should achieve what you want: In[18]:import numpy as npa = np.arange(100).reshape(10,10)b = [slice(1,3), slice(3,4)]a[b]Out[18]: array([[13], [23]]) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48661907', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9327000/']} | jdg_86195 |
stackexchange | llm_judgeable_groundtruth_similarity | 4541582 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there anything wrong with this proof of the Chain Rule? $$\begin{align}(f(g(x)))'&=\lim_{h\to 0} \frac{f(g(x+h))-f(g(x))}{h}\tag{eq 1}\\g'(x) &= \lim _{h\to 0} \frac{g(x+h))-g(x)}{h}\\g'(x)\cdot\lim_{h\to 0} h &= \lim _{h\to 0}\,(g(x+h)-g(x))\\g'(x)\cdot\lim _{h\to 0} h + \lim _{h\to 0} g(x) &= \lim _{h\to 0} g(x+h)\\\lim _{h\to 0} g(x+h)) &= g'(x)\cdot \lim _{h\to 0} h + \lim _{h\to 0} g(x)\tag{eq 2}\end{align}$$ Substitute Equation 2 into Equation 1: $$\begin{align}(f(g(x)))'&=\lim _{h\to 0}\frac{f(g(x+h))-f(g(x))}{h}\\&=\lim _{h\to 0} \frac{f(g'(x)\cdot h + g(x))-f(g(x))}{h}\end{align}$$ Let $g'(x)\cdot h = h'$ . $$\begin{align}\lim _{h'\to 0}\frac{f(g'(x)\cdot h+ g(x))-f(g(x)))}{h}&=\lim _{h'\to 0} \frac{f(h' + g(x))-f(g(x))}{h}\\&=g'(x)\cdot\lim _{h'\to 0}\frac{f(h'+g(x))-f(g(x))}{g'(x)h}\\&= g'(x)\cdot\lim_{h'\to 0}\frac{f(h'+g(x))-f(g(x))}{h'}\\&= g'(x) f'(g(x))\end{align}$$ Hence $\;(f(g(x)))' = g'(x) f'(g(x))$
Now provide the response and nothing else.
| There are a number of problems in what you write. There isn't a single problem, there are multiple problems. Here's three of them. Your step from Line 2 to Line 3 is incorrect. You got from $$g'(x) = \lim_{h\to 0}\frac{g(x+h)-g(x)}{h}$$ to $$g'(x)\lim_{h\to 0} h = \lim_{h\to 0}(g(x+h)-g(x)).$$ This step is not reversible. You seem to be using that the limit of a quotient is the quotient of the limits... but that is only valid of the limit of the denominator is not zero... which is not the case here. The second equality holds, but is not reversible (you can't go from Line 3 to Line 2). Line 3 is really trivial when you look at it closely: it just says that $0=0$ . Replace $g'(x)$ with $17$ , and it still holds. Replace $g'(x)$ with $2g'(x)$ and it still holds... and the substitution you would try later (which is invalid anyway, see below) would give you an extra factor of $2$ that would mess up your calculations... You are trying to substitute Equation 2 into Equation 1. But Equation 2 is $$\lim_{h\to 0}g(x+h) =g'(x)\lim_{h\to 0}h + g(x). \tag{Eq 2}$$ You are instead substituting $g'(x)\lim_{h\to 0}h + g(x)$ for $g(x+h)$ . But that is not valid; you can't just ignore the $\lim_{h\to 0}$ on the left hand side of Eq 2, because in general it is not true that $g(x+h) = g'(x)\lim_{h\to 0}h + g(x)$ . The left hand side depends on both $x$ and $h$ , while the right hand side is just $g(x)$ . So you are not even in a position to make that substitution. The reason you can't do the substitution is also the reason why your manipulation after the substitution is invalid. You have a limit, and are trying to "add" a limit inside the limit to justify the substitution. And later, you have a limit inside a limit and you are converting that into a single limit. Neither is in general true. You need to keep the limit variables separate. If you were actually able to do your substitution, it should really look like $$\begin{align}(f(g(x)))'&=\lim _{h\to 0}\frac{f(g(x+h))-f(g(x))}{h}\\&=\lim _{h\to 0} \frac{f(g'(x)\cdot\left(\lim_{k\to 0}k\right) + g(x))-f(g(x))}{h}\end{align}$$ and this is not the same thing as $$\lim_{h\to 0}\frac{f(g'(x)\cdot h + g(x))-f(g(x))}{h}$$ which is what you claimed.For instance, suppose you have $$\lim_{x\to 0}\frac{x}{x+x}.$$ You are saying that I could consider this as $$\lim_{x\to 0}\frac{x}{x+\lim_{x\to 0}x}$$ to make the first substitution, and something similar in the other direction to convert it back to a single limit. But replace the limit-inside-the-limit with $\lim_{y\to 0}y$ to see what this does not work: compare $$\lim_{x\to 0}\frac{x}{x+\lim_{y\to 0}y} = \lim_{x\to 0}\frac{x}{x+0} = \lim_{x\to 0}\frac{x}{x} = 1$$ with $$\lim_{x\to 0}\frac{x}{x+x} = \lim_{x\to 0}\frac{x}{2x} = \frac{1}{2}.$$ So you can't just convert what you actually have to what you claim you get. That step is invalid both coming and going. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4541582', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/675638/']} | jdg_86196 |
stackexchange | llm_judgeable_groundtruth_similarity | 55690 |
Below is a question asked on the forum quant.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to calibrate a one-factor mean-reverting process in python 3. The process is defined as: \begin{equation}dX = k(\alpha - X)dt + \sigma dW,\end{equation} where $\alpha = \mu - \frac{\sigma^2}{2k}$ is the long-run mean log price and $k$ is the speed of adjustment. Under the risk neutral probability $Q$ we write the previous equation as \begin{equation}dX = k(\alpha^* - X)dt + \sigma dW^*.\end{equation} Here $\alpha^*= \alpha - \lambda$ , where $\lambda$ is the market price of risk. Based on Girsanov's Theorem $dW^*$ is a Brownian Motion under the martingale measure $Q$ . My measurement and transition equations are: The measurement equation relates the time series of observable variables, in my case futures prices for different maturities, to the unobservable state variable, the spot price: \begin{equation}y_{t} = Z_{t}X_{t} + d_{t} + \epsilon_{t}, \qquad t = 1, ..., NT\end{equation} where $y_{t}=\left[\ln F\left(T_{i}\right)\right]$ , $i=1,...,N$ , $N\times 1$ vector of observables, $d_{t}=\left[\left(1-e^{-\kappa T_{1}}\right) \alpha^{*}+\frac{\sigma^{2}}{4 \kappa}\left(1-e^{-2 k T_{1}}\right)\right], \quad i=1, \ldots, N, \quad N \times 1$ vector, $Z_{t}=\left[e^{-\kappa T_{i}}\right], \quad i=1, \ldots, N, \quad N \times 1$ vector, $\epsilon_{t}, \quad N\times 1$ vector of serially uncorrelated disturbances with $\mathbb{E}(\epsilon_{t}) = 0$ and $Var(\epsilon_{t}) = H$ . The transition equation is a discrete-time version of the O-U oil price stochastic process: \begin{equation}X_{t}=c_{t}+Q_{t} X_{t-1}+\eta_{t}, \quad t=1, \ldots, N T\label{eq:38},\end{equation} where $c_{t}=\kappa \alpha \Delta t$ $Q_{t}=1-\kappa \Delta t$ $\eta_{t}$ , serially uncorrelated disturbances with $\mathbb{E}(\eta_{t}) = 0$ and $Var(\eta_{t}) = \sigma^2 \Delta t$ . The aim is to calibrate the model parameters using the time series of different maturities Futures prices via MLE. Any help with the coding part (in python 3) would be much appreciated!
Now provide the response and nothing else.
| Expanding on the answer by @ir7, here is some pykalman code/psuedocode to help get you started. This can be adjusted in many ways but I have left in some parameters to give you an idea. I left a documentation link at the bottom as well. The functions will setup Kalman Filters that are applied to your data and subsequently that data is fed to a regression that is subsequently called in a backtest function: import pandas as pdimport numpy as npfrom pykalman import KalmanFilterdef your_function_name(x): your_filter_name = KalmanFilter(transition_matrices = [1], observation_matrices = [1], observation_covariance=1, transition_covariance=.01, initial_state_mean = 0, initial_state_covariance = 1) state_means, _ = kf.filter(x.values) state_means = pd.Series(state_means.flatten(), index=x.index) return state_meansdef your_regression_filter(x, y): delta = 1e-3 trans_cov = delta / (1 - delta) * np.eye(2) #random walk wiggle obs_mat = np.expand_dims(np.vstack([[x], [np.ones(len(x))]]).T, axis=1) kf = KalmanFilter(n_dim_obs=1, n_dim_state=2, initial_state_mean=[0,0], initial_state_covariance=np.ones((2, 2)), transition_matrices=np.eye(2), observation_matrices=obs_mat, observation_covariance=2, transition_covariance=trans_cov) # Use the observations y to get running estimates and errors for the state parameters state_means, state_covs = kf.filter(y.values) return state_means With these 2 functions your would define a backtest function in which you would pull state_means by calling: state_means = your_regression_filter(your_function_name(x), your_function_name(y)) How you use state_means from here depends on you. For more info: pykalman documentation | {} | {'log_upvote_score': 4, 'links': ['https://quant.stackexchange.com/questions/55690', 'https://quant.stackexchange.com', 'https://quant.stackexchange.com/users/48126/']} | jdg_86197 |
stackexchange | llm_judgeable_groundtruth_similarity | 26783219 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm deeply puzzled by the way grep seems to parse a regex: $ echo "@NS500287" | grep '^@NS500[0-9]{3}'#nothing$ echo "@NS500287" | grep '^@NS500[0-9]\{3\}'@NS500287 That can't be right. Why am I escaping curly brackets that are part of a "match the previous, N times" component (and not, say, the square brackets as well)? Shouldn't escaping be necessary only when I'm writing a regex that actually matches { and } as literal characters in the query string? More of a cri de coeur than anything else, but I'm curious about the answer.
Now provide the response and nothing else.
| This is because {} are special characters and they need to handled differently to have this special behaviour. Otherwise, they will be treated as literal { and } . You can either escape like you did: $ echo "@NS500287" | grep '^@NS500[0-9]\{3\}'@NS500287 or use grep -E : $ echo "@NS500287" | grep -E '^@NS500[0-9]{3}'@NS500287 Without any processing: $ echo "he{llo" | grep "{"he{llo From man grep : -E , --extended-regexp Interpret PATTERN as an extended regular expression (ERE, see below). (-E is specified by POSIX.) ... REGULAR EXPRESSIONS A regular expression is a pattern that describes a set of strings. Regular expressions are constructed analogously to arithmetic expressions, by using various operators to combine smaller expressions. grep understands three different versions of regular expression syntax: “basic,” “extended” and “perl.” In GNU grep, there is no difference in available functionality between basic and extended syntaxes. In other implementations, basic regular expressions are less powerful. The following description applies to extended regular expressions; differences for basic regular expressions are summarized afterwards. Perl regular expressions give additional functionality, and are documented in pcresyntax(3) and pcrepattern(3), but may not be available on every system. ... Basic vs Extended Regular Expressions In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \? , \+ , \{ , \| , \( , and \) . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26783219', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1714523/']} | jdg_86198 |
stackexchange | llm_judgeable_groundtruth_similarity | 20465070 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to plot vertical bar plots over a map. I went through examples online but somehow not being able to. My data is currently in this format: University| Count | Category | lat | long Here is the code that I am trying execute: library(ggplot2)library(ggmap)library(ggsubplot)df1 <- data.frame( University = c(rep("University1", 4), rep("University2", 4), rep("University3", 4), rep("University4", 4)), Count = sample(1:10, 16, replace = T), Category = rep(c("A", "B", "C", "D")), lat = c(rep(10.902469, 4), rep(17.921959, 4), rep(18.606910, 4), rep(13.202366, 4)), long = c(rep(76.90020, 4), rep(83.42510, 4), rep(73.87501, 4), rep(77.62340, 4)))india <- get_map("India", zoom = 5)p <- ggmap(india)p + geom_subplot(data = df1, mapping=aes(x = long, y = lat, group = University,subplot= geom_bar(aes(x = Category, y = Count, color = Category, stat = "identity")))) When I run the above code, I get the following error: Error in get(x, envir = this, inherits = inh)(this, ...) : could not find function "%:::%"
Now provide the response and nothing else.
| You should also use the mapproj package. With the following code: ggmap(india) + geom_subplot(data = df1, aes(x = long, y = lat, group = University, subplot = geom_bar(aes(x = Category, y = Count, fill = Category, stat = "identity")))) I got the following result: As noted in the comments of the question: this solution works in R 2.15.3 but for some reason not in R 3.0.2 UPDATE 16 januari 2014: when you update the ggsubplot package to the latest version, this solution now also works in R 3.0.2 UPDATE 2 oktober 2014: Below the answer of the package author (Garret Grolemund) about the issue mentioned by @jazzuro (text formatting mine): Unfortunately, ggsubplot is not very stable. ggplot2 was not designed to be extensible or recursive, so the api between ggsubplot and ggplot2 is very jury rigged. I think entropy will assert itself as R continues to update. The future plan for development is to implement ggsubplot as a built in part of Hadley's new package ggvis . This will be much more maintainable than the ggsubplot + ggplot2 pairing. I won't be available to debug ggsubplot for several months, but I would be happy to accept pull requests on github. UPDATE 23 december 2016: The ggsubplot -package is no longer actively maintained and is archived on CRAN : Package ‘ggsubplot’ was removed from the CRAN repository. Formerly available versions can be obtained from the archive. Archived on 2016-01-11 as requested by the maintainer . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20465070', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1372269/']} | jdg_86199 |
stackexchange | llm_judgeable_groundtruth_similarity | 61210 |
Below is a question asked on the forum arduino.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a .h library file in which I want to declare a global variable that can be read in the program loop and in the library's .cpp file. The question is, is it possible to declare a variable in the .h file and make it global?
Now provide the response and nothing else.
| .h file is included by the compilation preprocessor as text into the .c or .cpp file. It is included as if you would replace the #include preprocessor instruction with the content of the .h file. (The Arduino .ino file is converted to cpp file before preprocessing .) After the inclusion the cpp file is compiled to 'object' (.o file). If the cpp file contains a variable definition the variable is defined in this object file. If your .h file contained a variable definition , the it is also in this object file. If two cpp files included the .h file with the definition of the variable, then the variable will be in two object files and the linker will exit with an error, because of two variables with the same name.If only one cpp/ino files includes the variable definition , then it is OK. It is not a good practice, but sometimes a necessary compromise. ( example of it ) To have one global variable made accessible by a .h file, the variable should be only declared in the .h file and be defined in one cpp file. Usually it is a pair of .h and .cpp file with same name. An example of global variable is Serial . It is a global object of type HardwareSerial declared in HardwareSerial.h as extern HardwareSerial Serial; and defined in HardwareSerial0.cpp as HardwareSerial Serial(&UBRR0H, &UBRR0L, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0); Do you see the difference? The declaration has the keyword extern and the definition has in this case parameters for the constructor of the object. The declaration with extern keyword makes object Serial visible in all cpp files which include HardwareSerial.h (or an include file which includes HardwareSerial.h like Arduino.h included by ino to cpp conversion). | {} | {'log_upvote_score': 5, 'links': ['https://arduino.stackexchange.com/questions/61210', 'https://arduino.stackexchange.com', 'https://arduino.stackexchange.com/users/53592/']} | jdg_86200 |
stackexchange | llm_judgeable_groundtruth_similarity | 21132 |
Below is a question asked on the forum mechanics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I see hundreds of exhaust scrapes on speed humps and things, or general gashes in the direction in which cars travel over them. Does hitting the exhaust on bumps damage the car? It's probably blindingly obvious, but how does it happen? I mean in my 2003 Opel Agila I've never hit the exhaust, and gone over humps at about 30mph (~50kph), and haven't bottomed out...
Now provide the response and nothing else.
| The bottom line is yes, if you drag your exhaust over the speed bumps, it will cause damage to your car. It will be mainly localized to the exhaust on the vehicle. Besides flattening out the exhaust pipes, you also put stress on the joints and the hangers for the different mounting points. If you hit the exhaust hard enough, you can cause further damage to the under side where the exhaust may be pushed up into other parts. If hit hard enough, it can also force damage up into the exhaust manifolds on the engine. The damage to the speed bump could be caused from any of several reasons. It happens when the lowest part of the car is not high enough to go over the speed bump. It might be the exhaust which hits (most likely part on modified cars). It could also be other parts. For instance, I had an aftermarket torque arm on my 94 Camaro Z28. The mount for it hung low due to it's design which allowed the single exhaust pipe to go through without touching it. It was in the center of the vehicle. Since it hung low, then add in 1.5" worth of drop from lowering springs, this made it really tough to go over speed bumps without hitting anything. | {} | {'log_upvote_score': 4, 'links': ['https://mechanics.stackexchange.com/questions/21132', 'https://mechanics.stackexchange.com', 'https://mechanics.stackexchange.com/users/4906/']} | jdg_86201 |
stackexchange | llm_judgeable_groundtruth_similarity | 53066396 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to write a VBA script that goes through a column of cells and one, underlines text between html <u></u> tags and two, removes those tags from the text afterwards. Cells may have multiple tags inside of them, other text next two them, or no tags at all. So far I've been able to get the script to underline between tags but when I try to remove them nothing really works (sometimes nothing is changed, sometimes the tag is underlined, etc.). I'm omitting input/output examples for brevity and in the hopes that there are glaringly obvious issues with my code but they are available on request. Trying to solve this problem using VBA initially stems from an inability for me to do this in Python since the object model only goes as low as cells, not the content of the cell. Any solutions using Python to do this would also be appreciated! Thank you so much for the help! Let me know if there's anything else I can do to help you all! Sub PleaseUnderline()'Holds the content between the tagsDim s As String'Holds the row number of the active cellDim a As Integer'Holds the location of the beginning of the open tagDim b As Integer'Holds the location of the beginning of the close tagDim e As IntegerDim holder As String 'Select the last cell in column A and make it the active cell Range("A" & ActiveCell.SpecialCells(xlLastCell).Row).Select For a = ActiveCell.Row To 1 Step -1 Range("A" & a).Select holder = Range("A" & a).Value s = "" b = 1 e = 1 Do b = InStr(b, ActiveCell, "<u>") If b = 0 Then Exit Do e = b + 1 e = InStr(e, ActiveCell, "</u>") If e = 0 Then Exit Do Else s = Mid(ActiveCell, b + 3, e - b - 3) End If holder = Replace(holder, "<u>", "", 1, 1) holder = Replace(holder, "</u>", "", 1, 1) Worksheets("Sheet").Range("A" & a).Value = holder ActiveCell.Characters(b, Len(s)).Font.Underline = True b = e + 1 Loop Next aEnd Sub
Now provide the response and nothing else.
| Starting on your newBranch: git checkout master to get back on the master branch git pull origin master to get the most up-to-date version of the master branch git checkout newBranch to get back on your newBranch git rebase origin/master -i to perform an interactive rebase. The command will take you through and let you pick commits, rename them, squash them, etc. Assuming you will want to keep them all, it will pause when there are merge conflicts and then you'll have to resolve them in your text editor, it will tell you where (in your text editor) that the conflicts occur. You will have to add those files after fixing them then do git rebase --continue to proceed with the rebase. When you're done with the rebase your newBranch will be synced up with master and have any commits in master that weren't there when you started your work, and all merge conflicts will be resolved so that you can easily merge your newBranch. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/53066396', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5597844/']} | jdg_86202 |
stackexchange | llm_judgeable_groundtruth_similarity | 8342 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Suppose I have export MY_VAR=0 in ~/.bashrc . I have an opened gnome terminal, and in this terminal, I change $MY_VAR value to 200 . So, if I do echo $MY_VAR in this terminal, 200 is shown. Now, I opened another tab in my gnome terminal, and do echo $MY_VAR ...and instead of 200 , I have 0 . What should I do to persist the 200 value when a terminal modifies an environment variable, making this modification (setting to 200) available to all subsequent sub shells and such? Is this possible?
Now provide the response and nothing else.
| A copy of the environment propagates to sub-shells, so this works: $ export MY_VAR=200$ bash$ echo $MY_VAR200 but since it's a copy, you can't get that value up to the parent shell — not by changing the environment, at least. It sounds like you actually want to go a step further, which is to make something which acts like a global variable, shared by "sibling" shells initiated separately from the parent — like your new tab in Gnome Terminal. Mostly, the answer is "you can't, because environment variables don't work that way". However, there's another answer, which is, well, you can always hack something up. One approach would be to write the value of the variable to a file, like ~/.myvar , and then include that in ~/.bashrc . Then, each new shell will start with the value read from that file. You could go a step further — make ~/.myvar be in the format MYVAR=200 , and then set PROMPT_COMMAND=source ~/.myvar , which would cause the value to be re-read every time you get a new prompt. It's still not quite a shared global variable, but it's starting to act like it. It won't activate until a prompt comes back, though, which depending on what you're trying to do could be a serious limitation. And then, of course, the next thing is to automatically write changes to ~/.myvar . That gets a little more complicated, and I'm going to stop at this point, because really, environment variables were not meant to be an inter-shell communication mechanism, and it's better to just find another way to do it. | {} | {'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/8342', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/2689/']} | jdg_86203 |
stackexchange | llm_judgeable_groundtruth_similarity | 43912124 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to write a unit test for a function that will interact with the filesystem and I'd like to be able to mock the filesystem during testing. The code below was given as the answer to this question, where you would create a filesystem interface to use during testing, but I'm new to Go and am struggling to figure out how to use it. Would someone be able to provide an example of how this interface would be used in a test please? var fs fileSystem = osFS{}type fileSystem interface { Open(name string) (file, error) Stat(name string) (os.FileInfo, error)}type file interface { io.Closer io.Reader io.ReaderAt io.Seeker Stat() (os.FileInfo, error)}// osFS implements fileSystem using the local disk.type osFS struct{}func (osFS) Open(name string) (file, error) { return os.Open(name) }func (osFS) Stat(name string) (os.FileInfo, error) { return os.Stat(name) }
Now provide the response and nothing else.
| One important thing you must not forget: you can only mock the file system if the code that interacts with the file system does so via the above presented file system interface ( filesystem ), using the fs global variable (or some other filesystem value that the test code can change, e.g. a passed fs parameter). Let's see such an example function: func getSize(name string) (int64, error) { stat, err := fs.Stat(name) if err != nil { return 0, err } return stat.Size(), nil} This simple getSize() function returns the size of a file specified by its name, returning the error if filesystem.Stat() fails (returns an error). And now let's write some unit tests that fully cover this getSize() function. What we will need We need a mocked version of filesystem , mocked so that it does not actually interact with the filesystem, but returns sensible data when methods of filesystem are called ( filesystem.Stat() in our case). To easiest mock filesystem (or any interface), we will embed filesystem in our mockedFS , so we "inherit" all its methods, and we will only need to mock what is actually used by the testable code. Note that calling other methods would result in runtime panic, as we won't really give a sensible, non- nil value to this embedded filesystem , but for the sake of tests it is not needed. Since filesystem returns a value of os.FileInfo (besides an error), which is an interface (and its implementation is not exported from the os package), we will also need to mock os.FileInfo . This will be mockedFileInfo , and we will do it very similarly to mocking filesystem : we'll embed the interface type os.FileInfo , so actually we'll only need to implement FileInfo.Size() , because that is the only method called by the testable getSize() function. Preparing / Setting up the mocked filesystem Once we have the mocked types, we have to set them up. Since getSize() uses the global fs variable to interact with the filesystem, we need to assign a value of our mockedFS to this global fs variable. Before doing so it's recommended to save its old value, and properly restore the old value once we're done with the test: "cleanup". Since we fully want to test getSize() (including the error case), we armour our mockedFS with the ability to control whether it should return an error, and also the ability to tell it what to return in case we don't want any errors. When doing the tests, we can manipulate the "state" of the mockedFS to bend its behavior to our needs. And the test(ing) code Without further ado, the full testing code: type mockedFS struct { // Embed so we only need to "override" what is used by testable functions osFS reportErr bool // Tells if this mocked FS should return error in our tests reportSize int64 // Tells what size should Stat() report in our test}type mockedFileInfo struct { // Embed this so we only need to add methods used by testable functions os.FileInfo size int64}func (m mockedFileInfo) Size() int64 { return m.size }func (m mockedFS) Stat(name string) (os.FileInfo, error) { if m.reportErr { return nil, os.ErrNotExist } return mockedFileInfo{size: m.reportSize}, nil}func TestGetSize(t *testing.T) { oldFs := fs // Create and "install" mocked fs: mfs := &mockedFS{} fs = mfs // Make sure fs is restored after this test: defer func() { fs = oldFs }() // Test when filesystem.Stat() reports error: mfs.reportErr = true if _, err := getSize("hello.go"); err == nil { t.Error("Expected error, but err is nil!") } // Test when no error and size is returned: mfs.reportErr = false mfs.reportSize = 123 if size, err := getSize("hello.go"); err != nil { t.Errorf("Expected no error, got: %v", err) } else if size != 123 { t.Errorf("Expected size %d, got: %d", 123, size) }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43912124', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_86204 |
stackexchange | llm_judgeable_groundtruth_similarity | 4771 |
Below is a question asked on the forum economics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I come from a strong quantitative background and am going to law school in the fall. I'm interested in financial product regulation and competition law. I have taken an introductory course in economics, but my exposure to economics stopped there. I was wondering if you had reading suggestions in micro, macro, and financial markets . Although I don't have an issue with calculus, lin alg, or probability, I tend to prefer learning by the use of examples, e.g. "too many chefs in the kitchen" to explain diminishing returns. I really don't like jargon and so far I seem to come across a lot of online resources (especially regarding financial products) that seem to use a lot of jargon with little reference to basic concrete examples. I tend to be very detailed oriented, so I prefer texts that lay out their variables and constants clearly. Something lighter and shorter tailored for independent study would be best.
Now provide the response and nothing else.
| Explosiveness The paper contains an error, which causes the explosive dynamics in your simulation (although presumably the underlying computations in the paper were correct). The equilibrium condition derived from eigenvalue decomposition is contained in the third row of matrix $Q^{-1}$ on page 12 of the paper, with variables ordered as $(c,k,h,z)$ (I'll drop tildas, so all lowercase variables are to be understood as log-deviations). Comparing with eqn. (16) on p. 13, we see that coefficients for $k$ and $h$ are switched, and so the correct condition is $$c_t = 0.54 k_t + 0.02 h_t + 0.44 z_t$$ Simulation First, we can express consumption and labor as linear function of state variables (no need to solve the system at each step of the simulation). The intertemporal and intratemporal equilibrium conditions can be written as $$\begin{bmatrix}1 & -0.02 \\ 2.78 & 1 \end{bmatrix} \begin{bmatrix} c_t \\ h_t\end{bmatrix} = \begin{bmatrix} 0.54 & 0.44 \\ 1 & 2.78 \end{bmatrix} \begin{bmatrix} k_t \\ z_t\end{bmatrix}$$ so after multiplying by an inverse we get $$\begin{bmatrix} c_t \\ h_t\end{bmatrix} = \begin{bmatrix} 0.53 & 0.47 \\-0.47 & 1.47 \end{bmatrix} \begin{bmatrix} k_t \\ z_t\end{bmatrix}$$ Next, transition for states can be written as $$\begin{bmatrix} k_{t+1} \\ z_{t+1} \end{bmatrix} = \begin{bmatrix} -0.07 & 0.06 \\ 0 & 0 \end{bmatrix} \begin{bmatrix} c_t \\ h_t\end{bmatrix} + \begin{bmatrix} 1.01 & 0.1 \\ 0 & 0.95 \end{bmatrix} \begin{bmatrix} k_t \\ z_t\end{bmatrix} + \begin{bmatrix} 0 \\ \epsilon_{t+1}\end{bmatrix}$$ which can be reduced by substuting for control variables to $$\begin{bmatrix} k_{t+1} \\ z_{t+1} \end{bmatrix} = \begin{bmatrix} 0.94 & 0.16 \\ 0 & 0.95 \end{bmatrix} \begin{bmatrix} k_t \\ z_t\end{bmatrix} + \begin{bmatrix} 0 \\ \epsilon_{t+1}\end{bmatrix}$$ Now the simulation should be trivial, here's a Matlab/Octave example: T = 200;X = zeros(2,T);for i=2:T X(:,i) = [0.94 0.16; 0 0.95] * X(:,i-1) + [0; 0.007*randn()];endY = [0.53 0.47; -0.47 1.47] * X;figureplot(1:T, [X; Y])legend('k','z','c','h') Of course in practice, you should probably recompute the whole solution, including the eigenvalue decomposition, so that you would be able to change parameters, etc. | {} | {'log_upvote_score': 4, 'links': ['https://economics.stackexchange.com/questions/4771', 'https://economics.stackexchange.com', 'https://economics.stackexchange.com/users/4209/']} | jdg_86205 |
stackexchange | llm_judgeable_groundtruth_similarity | 13488697 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
When designing resource hierarchies, when should one use sub-resources? I used to believe that when a resource could not exist without another, it should be represented as its sub-resource. I recently ran across this counter-example: An employee is uniquely identifiable across all companies. An employee's access control and life-cycle depend on the company. I modeled this as: /companies/{companyName}/employee/{employeeId} Notice, I don't need to look up the company in order to locate the employee, so should I? If I do, I'm paying a price to look up information I don't need. If I don't, this URL mistakenly returns HTTP 200: /companies/{nonExistingName}/employee/{existingId} How should I represent the fact that a resource to belongs to another? How should I represent the fact that a resource cannot be identified without another? What relationships are sub-resources meant and not meant to model?
Now provide the response and nothing else.
| A year later, I ended with the following compromise (for database rows that contain a unique identifier): Assign all resources a canonical URI at the root (e.g. /companies/{id} and /employees/{id} ). If a resource cannot exist without another, it should be represented as its sub-resource; however, treat the operation as a search engine query. Meaning, instead of carrying out the operation immediately, simply return HTTP 307 ("Temporary redirect") pointing at the canonical URI. This will cause clients to repeat the operation against the canonical URI. Your specification document should only expose root resources that match your conceptual model (not dependent on implementation details). Implementation details might change (your rows might no longer be unique identifiable) but your conceptual model will remain intact. In the above example, you'd tell clients about /companies but not /employees . This approach has the following benefits: It eliminates the need to do unnecessary database look-ups. It reduces the number of sanity-checks to one per request. At most, I have to check whether an employee belongs to a company, but I no longer have to do two validation checks for /companies/{companyId}/employees/{employeeId}/computers/{computerId} . It has a mixed impact on database scalability. On the one hand you are reducing lock contention by locking less tables, for a shorter period of time. But on the other hand, you are increasing the possibility of deadlocks because each root resource must use a different locking order. I have no idea whether this is a net gain or loss but I take comfort in the fact that database deadlocks cannot be prevented anyway and the resulting locking rules are simpler to understand and implement. When in doubt, opt for simplicity. Our conceptual model remains intact. By ensuring that the specification document only exposes our conceptual model, we are free to drop URIs containing implementation details in the future without breaking existing clients. Remember, nothing prevents you from exposing implementation details in intermediate URIs so long as your specification declares their structure as undefined. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13488697', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14731/']} | jdg_86206 |
stackexchange | llm_judgeable_groundtruth_similarity | 1842089 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The question arise in connection with this problem Prove that $$\lim_{n\rightarrow \infty}\sqrt{\frac{1}n}-\sqrt{\frac{2}n}+\sqrt{\frac{3}n}-\cdots+\sqrt{\frac{4n-3}n}-\sqrt{\frac{4n-2}n}+\sqrt{\frac{4n-1}n}=1$$ Thanks to answer @Vincenzo Oliva. I forgot the Stolz-Cesàro theorem
Now provide the response and nothing else.
| Note that the sequence you're interested in can be written as $a_n=\dfrac1{\sqrt{n}}\left(\sqrt{4n-1}+\sum\limits_{k=1}^{2n-1}\sqrt{2k-1}-\sqrt{2k}\right).$ Applying the Stolz-Cesàro theorem, we have \begin{align}\lim_{n\to\infty} a_n&=\lim_{n\to\infty}\frac{\sqrt{4n+3}-\sqrt{4n-1}+\sqrt{4n-1}-\sqrt{4n}+\sqrt{4n+1}-\sqrt{4n+2}}{\sqrt{n+1}-\sqrt{n}} \\ &= \lim_{n\to\infty} 2\frac{\sqrt{1+3/(4n)}-1+\sqrt{1+1/(4n)}-\sqrt{1+1/(2n)}}{\sqrt{1+1/n}-1} \\ &=\lim_{n\to\infty} \frac2n\frac{3/8+1/8-1/4}{1/(2n)}=1.\end{align} | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1842089', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/309360/']} | jdg_86207 |
stackexchange | llm_judgeable_groundtruth_similarity | 20279127 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a 2d list like this: 1 2 3 4 5 6 and I want to make this: 1 4 2 5 3 6 I've tried to do a for loop and switch each value but I keep getting an index out of bound error. Here's what I have: for i in results: for j in range(numCenturies): rotated[i][j] = results [j][i]
Now provide the response and nothing else.
| From python documentation on zip function: This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The returned list is truncated in length to the length of the shortest argument sequence. When there are multiple arguments which are all of the same length, zip() is similar to map() with an initial argument of None. With a single sequence argument, it returns a list of 1-tuples. With no arguments, it returns an empty list. Example: zip([1, 2, 3], [4, 5, 6]) # returns [(1, 4), (2, 5), (3, 6)] If you need the result to be the list of lists, not the list of tuples, you can use list comprehension: [list(x) for x in zip([1, 2, 3], [4, 5, 6], [7, 8, 9])] # returns [[1, 4, 7], [2, 5, 8], [3, 6, 9]] If all your variables are stored in one 2d list, and you want it pass it into zip function, you can use the following (I'll call it the star notation , because I can't remember the proper English term for it): results = [[1, 2, 3], [4, 5, 6]]zip(*results) # returns [(1, 4), (2, 5), (3, 6)] | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20279127', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1110590/']} | jdg_86208 |
stackexchange | llm_judgeable_groundtruth_similarity | 1539329 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there a way to sort a JTable programmatically? I have my JTable's sort working (with setRowSorter) so that when the user presses any of the columns, the table gets sorted. I know, SWingX JXTable would probably work, but I'd rather not go through the hassle because everything else is pretty much working now and I don't know how well NetBeans' visual editor handles JXTable etc. EDIT: The selected answer is referring to my (now removed) statement that the answer from Sun's pages didn't work for me. That was just an environment issue caused by my ignorance.
Now provide the response and nothing else.
| Works fine for me: import java.awt.*;import java.awt.event.*;import java.util.*;import javax.swing.*;import javax.swing.table.*;public class TableBasic extends JPanel{ public TableBasic() { String[] columnNames = {"Date", "String", "Integer", "Boolean"}; Object[][] data = { {new Date(), "A", Integer.valueOf(1), Boolean.TRUE }, {new Date(), "B", Integer.valueOf(2), Boolean.FALSE}, {new Date(), "C", Integer.valueOf(19), Boolean.TRUE }, {new Date(), "D", Integer.valueOf(4), Boolean.FALSE} }; DefaultTableModel model = new DefaultTableModel(data, columnNames) { // Returning the Class of each column will allow different // renderers and editors to be used based on Class public Class getColumnClass(int column) { switch (column) { case 0: return Date.class; case 2: return Integer.class; case 3: return Boolean.class; } return super.getColumnClass(column); } }; JTable table = new JTable(model); table.setPreferredScrollableViewportSize(table.getPreferredSize()); table.setAutoCreateRowSorter(true); // DefaultRowSorter has the sort() method ArrayList<RowSorter.SortKey> list = new ArrayList<>(); DefaultRowSorter sorter = ((DefaultRowSorter)table.getRowSorter()); sorter.setSortsOnUpdates(true); list.add( new RowSorter.SortKey(2, SortOrder.ASCENDING) ); sorter.setSortKeys(list); sorter.sort(); JScrollPane scrollPane = new JScrollPane( table ); add( scrollPane ); } private static void createAndShowGUI() { JFrame frame = new JFrame("Table Basic"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(new TableBasic()); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.pack(); frame.setLocationByPlatform( true ); frame.setVisible( true ); } public static void main(String[] args) throws Exception { SwingUtilities.invokeLater( () -> createAndShowGUI() ); }} Next time post your minimal, reproducible example when something doesn't work. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1539329', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4110/']} | jdg_86209 |
stackexchange | llm_judgeable_groundtruth_similarity | 11382189 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
You have an N x N chessboard and you wish to place N kings on it. Each row and column should contain exactly one king, and no two kings should attack each other (two kings attack each other if they are present in squares which share a corner). The kings in the first K rows of the board have already been placed. You are given the positions of these kings as an array pos[ ]. pos[i] is the column in which the king in the ith row has already been placed. All indices are 0-indexed. In how many ways can the remaining kings be placed? Input:The first line contains the number of test cases T. T test cases follow. Each test case contains N and K on the first line, followed by a line having K integers, denoting the array pos[ ] as described above.Output:Output the number of ways to place kings in the remaining rows satisfying the above conditions. Output all numbers modulo 1000000007.Constraints:1 <= T <= 201 <= N <= 160 <= K <= N0 <= pos_i < NThe kings specified in the input will be in different columns and not attack each other.Sample Input:54 123 05 21 34 41 3 0 26 12Sample Output:102118 Explanation:For the first example, there is a king already placed at row 0 and column 2. The king in the second row must belong to column 0. The king in the third row must belong to column 3, and the last king must beong to column 1. Thus there is only 1 valid placement. For the second example, there is no valid placement. How should i approach this problem
Now provide the response and nothing else.
| The question is essentially asking us to count permutations of 1 2 ... N such that i and i+1 are not adjacent for 1 <= i <= N-1 . Additionally, we have a prefix constraint. We should count only those permutations which start with pos_1 pos_2 ... pos_k . If it were not for the prefix constraint, you can find the answer in O(N) time using the formula from OEIS . That is if N is not too large. The number of digits in the answer grows as Θ(N log N), so multiplication and addition would incur additional overhead. Or you could compute the answer modulo some number. This question was asked in the Egyptian Olympiad in Informatics (2009) . With the prefix constraint, I have an O(N 2 ) dynamic programming solution. However, since N is as small as 16, using a polynomial time algorithm is overkill. There exists an easier dynamic programming solution running in time O(2 N N 2 ). Although this algorithm would probably take longer to code than the previous solution, its much faster to think of. The backtracking solution would, however, take somewhere between 20 to 100 hours (on an ordinary desktop/laptop) to run in the worst case. There are 2806878055610 solutions alone to visit for N = 16 . In addition to that, there would probably be a heavy cost of visiting non-solution dead-ends. O(2 N N 2 ) Solution This solution can be generalized to finding the number of Hamiltonian paths in a graph. Our state would be a pair (S, i) ; where S is a subset of {1,2...N} and i is an element of S . Let the cardinality of S be M . Define F(S,i) to be the number of ways to place the the elements 1, 2, ..., M in the positions specified in S ; respecting the constraint that k and k+1 never appear together; and the element M being placed in position i . The base case is F(P,pos_k) = 1 where P = {pos_1, pos_2 ... pos_k}. It is straightforward to compute F(S,i) for all S and i in time O(2 N N 2 ). The final answer is F([N],1) + F([N],2) + ... + F([N],N) where [N] = {1,2...N} . C++ code follows. Bitmasks were used to represent subsets of {1,2...N} . const int MAXN = 18;long long DP[1 << MAXN][MAXN];void solve() { int n, k; cin >> n >> k; int pmask = 0, p; for(int i = 0; i < k; i++){ cin >> p; pmask |= (1<<p); } // base cases if(k > 0) { DP[pmask][p] = 1; } else { for(int i = 0; i < n; i++) DP[1<<i][i] = 1; } long long ans = 0; for(int bitmask = pmask; bitmask < (1<<n); bitmask++) { for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ if((bitmask & (1<<j)) or abs(i-j) == 1) continue; DP[bitmask | (1<<j)][j] += DP[bitmask][i]; } if(bitmask == ((1<<n) - 1)) ans += DP[bitmask][i]; } } cout << ans << endl;} O(N 2 ) Solution This solution is pretty difficult to think of if you have not come across the idea before. First, let's tackle the problem without the prefixes. The idea is to 'build' all valid permutations by placing the elements 1, 2 .. N one by one. Let's start with an illustration. Suppose we are building a permutation, of say, 1 2 .. 5. First, we place 1. After placing 1, we also insert a placeholder element to be filled in by later numbers. More precisely, each state is a class of permutations where the placeholder x is replaced by a non-empty sequence of elements. Our permutation, after inserting 1, looks like one of the 3 cases: 1 x - 1 is the first element. The placeholder x would contain all the elements 2,3,4,5 in some order. x 1 - 1 is the last element. x 1 x - 1 is neither the first element or last element. Next, we place 2. It has to belong to one of the placeholders in one of the previous 3 classes. Suppose it belongs to the only placeholder in 1 x . Since 2 cannot be adjacent to 1, after placing 2 we must insert another placeholder between them. This results in the state 1 x 2 . Additionally, we need to account for the permutations when 2 isn't the last element. We also spawn a state 1 x 2 x . For x 1 , we analogously create states 2 x 1 and x 2 x 1 . For x 1 x , we have two choices of placeholders to place 2 in. Like the previous cases, we create states 2 x 1 x , x 2 x 1 x , x 1 x 2 , x 1 x 2 x . But notice, for example, in x 2 x 1 x the last placeholder is different from the other two - in that 3 can occur in it without a need to create another barrier! We record this by using a different symbol for the placeholder. That is we use x 2 x 1 o and o 1 x 2 x states instead. Suppose next, we are inserting 3 in x 2 x 1 o . If we place 3 in an x , like before, we have to create a barrier placeholder. But, we do have a choice between creating or omitting a placeholder in the direction opposite to the barrier placeholder. If we place 3 in an o placeholder, we have choices between creating or omitting placeholders in both directions . Additionally, we must also 'promote' the x placeholders that are not used to o placeholders. This is because, the old x placeholders do not offer a constraint for the next element, 4, like they did for 3. We can already start guessing the developing pattern. In the general case, while inserting i: First of all, we have to choose in which placeholder to place i. Next, suppose we place i in an x placeholder. We must build a barrier placeholder. And we have a choice whether to build a placeholder in the other direction. If we are using an o placeholder, we have choices to build additional placeholders in both directions. That is, a total of 4 choices. We must update the x placeholders we did not use, to o placeholders. The final observation that turns this idea into an efficient algorithm is that we can bunch together permutation classes that have the same number of placed elements and the same number of x and o placeholders . This is because, for two different classes sharing all three of these parameters, the number of permutations they represent are equal. To prove this claim rigorously, it is enough to observe that the classes we are enumerating are exhaustive and non-overlapping. Prefixes A little thought reveals that in the prefix problem, we just have to count permutations which begin with a certain element, (call this b); and some of the constraints between i and i+1 are not applicable anymore. The second modification is easy to fix: If the constraint between i-1 and i are not applicable, then before inserting i, update all the x placeholders to o placeholders. For the first modification, we should ensure that there is always a placeholder at the beginning until b is placed. While placing b we cheerfully place it into the beginning placeholder, and don't add any placeholder before it. Implementation Let DP[i][no][nx] be the number of ways to build the class where the first i elements have been placed, and there are no and nx placeholders of type o and x respectively. At any state, the number of x placeholders is between 0 and 2. So the state space is O(N^2). State transitions are constant time, exactly as described above. O(N) solution for the problem without the prefix constraint According to OEIS, A n = (n+1)A n-1 - (n-2)A n-2 - (n-5)A n-3 + (n-3)A n-4 ; where A n is the number of permutations where i and i+1 are never consecutive. We can compute the sequence A n in O(n). (That is, assuming we compute A n modulo a reasonably small number.) Here is a derivation of the formula: Define auxiliary sequences: B n = Number of permutations of 1 2 ... N such that exactly one of the N-1 adjacency constraint is violated. C n = Number of permutations of 1 2 ... N such that only the adjacency constraint involving the element N is violated. That is N-1 and N would be adjacent to each other in these permutation; and all other adjacency constraints are satisfied. We now look for recurrences for the sequences A, B and C. Recurrence for A n Suppose we remove the element n from a valid permutation P , where i and i+1 are never adjacent. The resulting permutation Q of 1 .. n-1 must satisfy exactly one of the following two cases: No adjacent numbers from 1 ... n-1 are adjacent in Q . That is, Q is one of the permutations accounted for in A n-1 . Exactly one pair (i,i+1) appear consecutively in Q , and i+1 =/= n-1 . That is, Q is a permutation from B n-1 - C n-1 . In the first case, element n can be inserted in exactly n - 2 positions. Two of the positions are blocked by the element n - 1 . In the second case, there is only one choice for the position of n - between the consecutive elements. We get the recurrence: A n = (n - 2)A n-1 + B n-1 - C n-1 . Recurrence for B n Let B n,k be the number of permutations where k and k+1 occur consecutively. We can coalesce k and k+1 together to a single element, and consider a permutation Q of n-1 elements, preserving the relative ordering. If neither k-1 and k+2 (original labels) appear next to the coalesced (k,k+1) element, then Q contributes 2 permutations to B n,k - they correspond to the arrangements k k+1 and k+1 k within the coalesced element. The number of such Q is A n-1 . If one of k-1 or k+2 appear next to the (k,k+1) element, then Q contributes 1 permutation. The number of such Q is B n-1,k-1 + B n-1,k . If both k-1 and k+2 appear next to the (k,k+1) element, then Q contributes 1 permutation. The number of such Q is B n-2,k-1 . We have B n,k = 2A n-1 + B n-1,k-1 + B n-1,k + B n-2,k-1 . (Some terms vanish when k = 1 and k = n-1 ). Summing over k , we get the recurrence: B n = 2(n-1)A n-1 + 2B n-1 + B n-2 . Recurrence for C n Well, C n is just B n,n-1 . From the previous results, it follows that C n = 2A n-1 + C n-1 . Putting it all together We should be able to eliminate B and C to get a recurrence in A alone. It is left as an exercise. :-) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11382189', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1400262/']} | jdg_86210 |
stackexchange | llm_judgeable_groundtruth_similarity | 6868256 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Can a key/value pair stored in memcached get evicted prior to its expiry if there is still free space available? I have a memcached process running that is allowed to consume up to 6GB; 2.5GB are reported in use and that number fluctuates only minimally (+/- 100MB in a one-day span). If I set a simple string value that expiries in 15 minutes, is it possible that it would be evicted (cache.get returns not found) prior to 15 minutes elapsing? Thanks,-Eric
Now provide the response and nothing else.
| yes Basically, memcache allocates space in chuncks vs on-demand, and then stores items into the chunks and manages that memory manually. As a result, smaller items can "use" much larger pieces of memory than they would if space was allocated on a per-item basis. The link explains it much better than I can https://groups.google.com/group/memcached/browse_thread/thread/8f460034418262e7?pli=1 Edit: adding more explanation Memcache works by allocating slabs of various sizes. These slabs have a number of specifically sized slots (which is determined by the slab's class). Hypothetically (and using only my abstraction of Memcache's internals), lets say the smallest size slab class was 1K. This means that the smallest slots are 1K. Furthermore, Memcache will only allocate these in sets of 1024, or 1MB of memory at a time. Lets say we had such a configuration and we want to store a 1-byte object (char value?) into Memcache. Lets suppose this would require 5 bytes of memory (4 byte key?). In an empty cache, Memcache would allocate a new slab of the smallest size that can hold the value (1K slots). So storing your 5 bytes will cause Memcache to allocate 1MB of memory. Now, let say you have a lot of these. The next 1023 will be "free" -- Memcache has already allocated the memory, so no additional memory is needed. At the end of this, you've stored 1024 * 5 bytes = ~5KB, but Memcache has used 1MB to store this. Store a few million of these, and you can imagine consuming gigabytes of memory to store kilobytes of data. This is close to a worst case. In practice Memcache can be configured to have a minimum slab class size quite small if needed, and the growth factor (size difference between the slab-classes) can be widened or narrowed. If you're caching database queries, you might have items sized from a few bytes to several KB, with page content you could even get into the MB. Here's the key point Memcache won't reclaim memory or clean up slabs (new versions do have this now for a pretty significant performance hit, but traditionally, this has been how Memcache works). Suppose you have a system that has been happily running and caching for a few days. You have hundreds of slabs of various sizes. You deploy a new page-caching strategy to your app without resetting the cache. Now instead of caching whole pages, you're caching parts of the page. You've changed your caching pattern from storing lots of ~1MB objects to storing lots of ~10KB objects. Here's where we get into trouble. Memcache has allocated a bunch of slabs that hold objects of about 1MB. You never used to cache many 10KB objects before. The slabs that have 10KB slots are quickly filled up, but now you have a whole bunch of allocated slabs that hold objects of 1MB which aren't being used (nothing else is that big). Memcache won't put your 10KB objects in a 1MB slot (even if it did, it wouldn't help for very long). It needs to get more slabs that hold 10KB objects, but it can't because all your memory has been allocated into the slabs that hold 1MB objects. The result is that you are left with potentially gigabytes of memory allocated in slabs to hold 1MB objects which sit idle while your 10KB-slot slabs are full. In this scenario, you will start evicting items out of the 10KB-slot slabs despite have gigabytes sitting idle. This was a long-winded, contrived, and extreme example. Rarely does your caching strategy change so obviously or so dramatically. The default growth factor of slab-classes is 1.25, so you'd have slabs with 1KB slots, 1.25KB slots, 1.5KB slots, etc. The concept holds -- if you are heavily using certain sized slabs and that pattern shifts (sql queries return more objects? web pages get bigger? add a column to a table which moves a cached response up a slab class? etc.) Then you can end up with a bunch of slabs which are the "wrong" size and you can have "nowhere" to store something despite having gigabytes of "unused" space. If you are getting evictions, it's possible to telnet into Memcache and find out what slabs are causing the evictions. Usually, a cache-reset (yeah, empty out everything) fixes the issue. Here's a reference on how to get at the stats. http://lzone.de/articles/memcached.htm | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6868256', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61072/']} | jdg_86211 |
stackexchange | llm_judgeable_groundtruth_similarity | 8817148 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
a.nodeName is undefined I've looked this up but the explanations didn't seem at all clear to me. function deleteThisRow() { $(this).closest('tr').fadeOut(400, function(){ $(this).remove(); });} <tr> <td>blah blah blah</td> <td> <img src="/whatever" onClick="deleteThisRow()"> </td></tr>
Now provide the response and nothing else.
| The this keyword in your function does not refer to the element which was clicked on. By default it would refer to the highest element in the DOM, which would be the window . To fix this you can use an unobtrusive event handler, instead of an outdated on* event attribute, as they run under the scope of the element which raised the event. Try this: $("tr td img").click(deleteThisRow);function deleteThisRow() { $(this).closest('tr').fadeOut(400, function() { $(this).remove(); });} img { width: 20px; height: 20px; border: 1px solid #C00;} <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><table> <tr> <td>blah blah blah 1</td> <td><img src="/whatever"></td> </tr> <tr> <td>blah blah blah 2</td> <td><img src="/whatever"></td> </tr> <tr> <td>blah blah blah 3</td> <td><img src="/whatever"></td> </tr></table> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8817148', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1098148/']} | jdg_86212 |
stackexchange | llm_judgeable_groundtruth_similarity | 5465923 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've noticed that C# adds additional slashes ( \ ) to paths. Consider the path C:\Test . When I inspect the string with this path in the text visualiser, the actual string is C:\\Test . Why is this? It confuses me, as sometimes I may want to split the path up (using string.Split() ), but have to wonder which string to use (one or two slashes).
Now provide the response and nothing else.
| .Net is not adding anything to your string here. What your seeing is an effect of how the debugger chooses to display strings. C# strings can be represented in 2 forms Verbatim Strings: Prefixed with an @ sign and removes the need o escape \\ characters Normal Strings: Standard C style strings where \\ characters need to escape themselves The debugger will display a string literal as a normal string vs. a verbatim string. It's just an issue of display though, it doesn't affect it's underlying value. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5465923', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/32484/']} | jdg_86213 |
stackexchange | llm_judgeable_groundtruth_similarity | 416636 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it true that for a sequence of functions $f_n$ $$\limsup_{n \rightarrow \infty }f_n \leq \sup_{n} f_n$$I tried to search for this result, but I couldn't find, so maybe my understanding is wrong and this does not hold.
Now provide the response and nothing else.
| The inequality$$\limsup_{n\to\infty}a_n\leq\sup_{n\in\mathbb{N}}a_n$$holds for any real numbers $a_n$, because the definition of $\limsup$ is$$\limsup_{n\to\infty}a_n:=\lim_{m\to\infty}\left(\sup_{n\geq m}a_n\right)$$and for any $n\in\mathbb{N}$, we have$$\left(\sup_{n\geq m}a_n\right)\leq\sup_{m\in\mathbb{N}}a_n$$(if the numbers $a_1,\ldots,a_{m-1}$ are less than or equal to the supremum of the others, both sides are equal, and if not, then the right side is larger).Therefore$$\limsup_{n\to\infty}f_n(x)\leq \sup_{n\in\mathbb{N}}f_n(x)$$holds for any real number $x$, which is precisely what is meant by the statement$$\limsup_{n\to\infty}f_n\leq \sup_{n\in\mathbb{N}}f_n.$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/416636', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/62679/']} | jdg_86214 |
stackexchange | llm_judgeable_groundtruth_similarity | 346385 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
According to this chart of a diode's power dissipation over temperature, the power dissipation would decrease as temperature goes up. But wouldn't it be the exact opposite and even more power be dissipated as heat, when the temperature goes up ?
Now provide the response and nothing else.
| The graph is not showing how much power the diode will dissipate as a function of temperature. It shows permissible power dissipation as a function of ambient temperature. Think about it. If it's hot all around, less power will get something to a particular temperature than when it's cold all around. In this case it looks like the diode stops functioning at 175 °C. If it's already at 174 °C, then you can't put much power into it before it won't function anymore. If it's at 25 °C, then you can put a lot more power into it before it gets to 175 °C and stops working. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/346385', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/86793/']} | jdg_86215 |
stackexchange | llm_judgeable_groundtruth_similarity | 10971221 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
git animals had this series of commands: git initgit add *git commit -a -m ‘initial commit and release!’ What does git add * do compared to git add . (which I normally do) are they the same?
Now provide the response and nothing else.
| git add * will add all the paths that are the result of the shell expansion of * whereas git add . will tell git to add the current directory. git add * won't add paths that begin with a . as the shell expansion of * considers these to be "hidden" paths. git add * will also fail if any expanded path is currently being ignored by git because git considers it an error if you explicitly specify an ignored path without passing the -f (force) flag to show that you really want to add an ignored path. If you get git to expand the glob ( git add '*' ) it will add "hidden" files and skip over ignored files. It would work the same as git add . in this case. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10971221', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/29347/']} | jdg_86216 |
stackexchange | llm_judgeable_groundtruth_similarity | 16975 |
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I would like to know what is the best way to configure one GridLine for the hour in LightGray and another for the days in Gray . In my tests, the FrameTicks are superposed by the GridLines and I don't know how to control the color. The data label should appear just for days. Here is my attempt that I consider very clumsy. data={#,RandomVariate[NormalDistribution[0,1]]}&/@RandomReal[{3564979299,3565355902},1000];DateListPlot[data ,AspectRatio->0.2 ,DateTicksFormat->{"Day","/","Month"} ,GridLines->{{#,LightGray}&/@DateRange[{2012,12,12},{2012,12,31},"Hour"],None} ,FrameTicks->{Automatic,{DateRange[{2012,12,12},{2012,12,31},"Day"],None}} ,Epilog->{Gray,Line[{{#,Min@data[[All,2]]},{#,Max@data[[All,2]]}}]&/@AbsoluteTime/@DateRange[{2012,12,12},{2012,12,31},"Day"]}] I don't like to use Epilog for that. It would be nice if I could have subticks between the days ticks too, one subtick for each hour, with no label.
Now provide the response and nothing else.
| To get rid of the Epilog you can change the setting for Gridlines as follows: data = {#, RandomVariate[NormalDistribution[0, 1]]} & /@ RandomReal[{3564979299, 3565355902}, 1000];DateListPlot[data, AspectRatio -> 0.2, DateTicksFormat -> {"Day", "/", "Month"},GridLines -> {Join[{#, LightGray} & /@ DateRange[{2012, 12, 12}, {2012, 12, 31}, "Hour"], {#, Gray} & /@ DateRange[{2012, 12, 12}, {2012, 12, 31}, "Day"]], None},FrameTicks -> {Automatic, {DateRange[{2012, 12, 12}, {2012, 12, 31}, "Day"], None}}] Update: Using @rm-rf's idea to change the color conditionally: DateListPlot[data, AspectRatio -> 0.2, DateTicksFormat -> {"Day", "/", "Month"},GridLines -> {{#, If[Last@# === 0, Gray, LightGray]} & /@ DateRange[{2012, 12, 12}, {2012, 12, 31}, "Hour"], None}, FrameTicks -> {Automatic, {DateRange[{2012, 12, 12}, {2012, 12, 31}, "Day"], None}}] Update 2: Further variations to specify both Gridlines and FrameTicks DateListPlot[data, AspectRatio -> 0.2, GridLines -> {{#, {LightGray, Gray}[[2 - Sign[Last[#]]]]} & /@ DateRange[{2012, 12, 12}, {2012, 12, 31}, "Hour"], None}, FrameTicks -> {Automatic, {{{#, "", {.005, 0}, Directive[Red, Thick]}, {#, DateString[#, {"Day", "/", "Month"}], {0.01, 0}, Directive[Blue, Thickness[.01]]}}[[2 - Sign[Last[#]]]] & /@ DateRange[{2012, 12, 12}, {2012, 12, 31}, "Hour"], None}}] Or DateListPlot[data, AspectRatio -> 0.2, GridLines -> {{#, {LightGray, Gray}[[2 - Sign[Last[#]]]]} & /@ DateRange[{2012, 12, 12}, {2012, 12, 31}, "Hour"], None}, FrameTicks -> {Automatic, {If[Last@# === 0, {#, DateString[#, {"Day", "/", "Month"}], {0.01, 0}, Directive[Blue, Thickness[.01]]}, {#, "", {.005, 0}, Directive[Red, Thick]}] & /@ DateRange[{2012, 12, 12}, {2012, 12, 31}, "Hour"], None}}] | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/16975', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/2266/']} | jdg_86217 |
stackexchange | llm_judgeable_groundtruth_similarity | 3284137 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm reading through a book about the C# Task Parallel Library and have the following example but the TaskScheduler.UnobservedTaskException handler is never being triggered. Can anyone give me any clues as to why? TaskScheduler.UnobservedTaskException += (object sender, UnobservedTaskExceptionEventArgs eventArgs) =>{ eventArgs.SetObserved(); ((AggregateException)eventArgs.Exception).Handle(ex => { Console.WriteLine("Exception type: {0}", ex.GetType()); return true; });};Task task1 = new Task(() => { throw new ArgumentNullException();});Task task2 = new Task(() => { throw new ArgumentOutOfRangeException();});task1.Start();task2.Start();while (!task1.IsCompleted || !task2.IsCompleted){ Thread.Sleep( 5000 );}Console.WriteLine("done");Console.ReadLine();
Now provide the response and nothing else.
| Unfortunately, that example will never show you your code. The UnobservedTaskException will only happen if a Task gets collected by the GC with an exception unobserved - as long as you hold a reference to task1 and task2 , the GC will never collect, and you'll never see your exception handler. In order to see the behavior of the UnobservedTaskException in action, I'd try the following (contrived example): public static void Main(){ TaskScheduler.UnobservedTaskException += (object sender, UnobservedTaskExceptionEventArgs eventArgs) => { eventArgs.SetObserved(); ((AggregateException)eventArgs.Exception).Handle(ex => { Console.WriteLine("Exception type: {0}", ex.GetType()); return true; }); }; Task.Factory.StartNew(() => { throw new ArgumentNullException(); }); Task.Factory.StartNew(() => { throw new ArgumentOutOfRangeException(); }); Thread.Sleep(100); GC.Collect(); GC.WaitForPendingFinalizers(); Console.WriteLine("Done"); Console.ReadKey();} This will show you your messages. The first Thread.Sleep(100) call provides enough time for the tasks to throw. The collect and wait forces a GC collection, which will fire your event handler 2x. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3284137', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/206463/']} | jdg_86218 |
stackexchange | llm_judgeable_groundtruth_similarity | 188083 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $f:X\to Y$ be a map between connected CW complexes and $k\geq 0$ an integer. I am confused by the definition of $k$-connectivity or more fundamentally by what induces a long exact sequence of homotopy groups. My favourite definition for $k$-connectivity is this: $f$ is called $k$-connected if the homotopy fiber $F$ of $f$ is $k-1$-connected, meaning that $\pi_i(F)=0$ for all $i$ with $0\leq i\leq k-1$. Of course, this definition is only reasonable for connected spaces $X$ and $Y$. I know that for $F\to X\to Y$, there is a long exact sequence\begin{equation}\ldots\to\pi_i(F)\to\pi_i(X)\to\pi_i(Y)\to\ldots\to \pi_0(X)\to\pi_0(Y)\end{equation}by arguments about the homotopy fiber $F$. I like to define the relative homotopy groups $\pi_i(Y,A)$ as $\pi_{i-1}(F)$ and one gets from the above long exact sequence a long exact sequence for the relative homotopy groups. Now Wikipedia defines for an inclusion $f:X\hookrightarrow Y$ to be $k$-connected, if its homotopy cofiber $C$ (= mapping cone) is $n$-connected, meaning that $\pi_i(C)=0$ for all $i$ with $0\leq i\leq k$. Even worse for me, the same Wikipedia article asserts a long exact sequence\begin{equation}(*)\hspace{10ex}\pi_i(X)\to\pi_i(Y)\to \pi_i(C)\end{equation}(however this is prolonged to the left and to the right). My main question is: How do the two definitions of $k$-connectivity relate? Maybe however, my problem of understanding begins even earlier: How do $\pi_i(C)$ and $\pi_i(Y,X)$ (from de definition above) relate? I was able to show that for the connectivity\begin{equation}conn(F)+1=conn(C)\end{equation}holds for simply connected $X$ and $Y$. This means, that for simply connected $X$ and $Y$, the two definitions of $k$-connectivity of $f$ coincide if there is really an exact sequence (*). But what happens when $X$ and $Y$ are not simply connected but only connected?
Now provide the response and nothing else.
| Wikipedia's definition is (at the time of writing) not correct, in the sense that it's not equivalent to the usual condition on the relative homotopy groups (or the homotopy groups of the fiber) unless you assume simple connectivity. Here's an example. It's a standard example of a CW-inclusion $A \to X$ which is an isomorphism on $\pi_1$ and on homology, but which is not surjective on $\pi_2$. If you believe that such a map $f$ exists then you can skip the below construction, because the mapping cone $Cf$ is simply-connected and has trivial homology groups, so by the Hurewicz theorem and the Whitehead theorem it is contractible; however, the map $f$ is not $2$-connected. Let $W = S^1 \vee S^2$, whose universal cover is a copy of $\mathbb{R}$ with a copy of $S^2$ attached at each integer. The fundamental group of $W$ is $\mathbb{Z}$, and I'll call the generator $t$; it acts on the universal cover by translation by $1$. The Hurewicz map $\pi_2(W) \to H_2(W) = \mathbb{Z}$ is a "collapse" obtained by setting $t=1$. The second homotopy group $\pi_2(W)$ is isomorphic to the group $\mathbb{Z}[t^{\pm 1}]$ as a group acted on by the fundamental group. Let $\alpha:S^2 \to W$ be a map whose image in this group is $t-2$. We can then form a space$$X = W \cup_{\alpha} e^3$$formed by gluing a 3-cell in with attaching map $\alpha$. There is an inclusion $S^1 \subset W \subset X$. From this point, I need some calculations. The first part of the calculation is that the map $S^1 \to X$ is an isomorphism on homology groups; this follows by calculating cellular homology, because the map $\alpha$ is an isomorphism on $H_2$. The second part of the calculation is that the maps $S^1 \to W \to X$ are all isomorphisms on $\pi_1$. The third part of the calculation is that the second homotopy group of $X$ is the cokernel of the map$$x \mapsto (t-2)x: \mathbb{Z}[t^{\pm 1}] \to \mathbb{Z}[t^{\pm 1}].$$This group is isomorphic to $\mathbb{Z}[1/2]$. Probably the most direct way is to take the universal cover of $X$, which is formed by taking the universal cover of $W$ and gluing in a $\mathbb{Z}$ worth of copies of $D^3$ along the translates of $\alpha$. As a result, the map $\pi_2 S^1 \to \pi_2 X$ is the map $0 \to \mathbb{Z}[1/2]$, and so the second relative homotopy group is nonzero. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/188083', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/20164/']} | jdg_86219 |
stackexchange | llm_judgeable_groundtruth_similarity | 2878319 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Just a quick query:I had a piece of code which compared a string against a long list of values, e.g. if(str == "string1" || str == "string2" || str == "string3" || str == "string4". DoSomething(); And the interest of code clarity and maintainability I changed it to public static string[] strValues = { "String1", "String2", "String3", "String4"};...if(strValues.Contains(str) DoSomething(); Only to find the code execution time went from 2.5secs to 6.8secs (executed ca. 200,000 times). I certainly understand a slight performance trade off, but 300%? Anyway I could define the static strings differently to enhance performance? Cheers.
Now provide the response and nothing else.
| Fyi.. Using: private static HashSet<string> strHashSet = new HashSet<string>() { "0string", "1string", "2string", "3string", "4string", "5string", "6string", "7string", "8string", "9string", "Astring", "Bstring" };private static List<string> strList = strHashSet.ToList();private static string[] strArray = strList.ToArray();private static Dictionary<int, string> strHashDict = strHashSet.ToDictionary(h => h.GetHashCode());private static Dictionary<string, string> strDict = strHashSet.ToDictionary(h => h);// Only one test uses this method.private static bool ExistsInList(string str){ return strHashDict.ContainsKey(str.GetHashCode());} Checking for the first and last strings in the list then checking for a string not in the list: "xstring"Executing 500,000 iterations, all times in milliseconds. 1.A Test: result = (str == "0string" || str == "1string" ...[storage var] [first]:[ last ]:[ none ]:[average]strArray 3.78 : 45.90 : 57.77 : 35.822.A Test: ExistsInList(string);[storage var] [first]:[ last ]:[ none ]:[average]none 36.14 : 28.97 : 24.02 : 29.713.A Test: .ContainsKey(string.GetHashCode());[storage var] [first]:[ last ]:[ none ]:[average]strHashDict 34.86 : 28.41 : 21.46 : 28.244.A Test: .ContainsKey(string);[storage var] [first]:[ last ]:[ none ]:[average]strDict 38.99 : 32.34 : 22.75 : 31.365.A Test: .Contains(string);[storage var] [first]:[ last ]:[ none ]:[average]strHashSet 39.54 : 34.78 : 24.17 : 32.83strList 23.36 : 122.07 : 127.38 : 90.94strArray 350.34 : 426.29 : 426.05 : 400.906.A Test: .Any(p => p == string);[storage var] [first]:[ last ]:[ none ]:[average]strHashSet 75.70 : 331.38 : 339.40 : 248.82strList 72.51 : 305.00 : 319.29 : 232.26strArray 38.49 : 213.63 : 227.13 : 159.75 Interesting (if not unexpected) results when we change the strings in the list: private static HashSet<string> strHashSet = new HashSet<string>() { "string00", "string01", "string02", "string03", "string04", "string05", "string06", "string07", "string08", "string09", "string10", "string11" }; With "string99" as the none check. 1.B Test: result = (str == "string00" || str == "string01" ...[storage var] [first]:[ last ]:[ none ]:[average]strArray 85.45 : 87.06 : 91.82 : 88.112.B Test: ExistsInList(string);[storage var] [first]:[ last ]:[ none ]:[average]none 30.12 : 27.97 : 21.36 : 26.483.B Test: .ContainsKey(string.GetHashCode());[storage var] [first]:[ last ]:[ none ]:[average]strHashDict 32.51 : 28.00 : 20.83 : 27.114.B Test: .ContainsKey(string);[storage var] [first]:[ last ]:[ none ]:[average]strDict 36.45 : 32.13 : 22.39 : 30.325.B Test: .Contains(string);[storage var] [first]:[ last ]:[ none ]:[average]strHashSet 37.29 : 34.33 : 23.56 : 31.73strList 23.34 : 147.75 : 153.04 : 108.04strArray 349.62 : 460.19 : 459.99 : 423.266.B Test: .Any(p => p == string);[storage var] [first]:[ last ]:[ none ]:[average]strHashSet 76.26 : 355.09 : 361.31 : 264.22strList 70.20 : 332.33 : 341.79 : 248.11strArray 37.23 : 234.70 : 251.81 : 174.58 For cases A and B looks like tests 2 and 3 have the advantage. However, HashSet.Contains(string) is very efficient, not effected by list contents and has a clear syntax...might be the best choice. Yes, it is true, I have no life. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2878319', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/334455/']} | jdg_86220 |
stackexchange | llm_judgeable_groundtruth_similarity | 255189 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
If I have a type defined as a set of an enumerated type, it's easy to create an empty set with [], but how do I create a full set? EDIT: Yeah, the obvious solution is to use a for loop. That's also a really bad solution if there's another way. Does anyone know of a way that'll work in constant time?
Now provide the response and nothing else.
| Low() and High() are "compiler magic" functions that can be evaluated at compile time.This allows their use in constant declarations like the following: var MySet : TBorderIcons; MySet2 : TBorderIcons;const AllIcons : TBorderIcons = [Low(TBorderIcon)..High(TBorderIcon)];begin MySet := [Low(TBorderIcon)..High(TBorderIcon)]; MySet2 := AllIcons;end; | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/255189', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/32914/']} | jdg_86221 |
stackexchange | llm_judgeable_groundtruth_similarity | 22655867 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am playing around with Docker for a couple of days and I already made some images (which was really fun!). Now I want to persist my work and came to the save and export commands, but I don't fully understand them. What is the difference between save and export in Docker?
Now provide the response and nothing else.
| The short answer is: save will fetch an image : for a VM or a physical server, that would be the installation .ISO image or disk. The base operating system. It will pack the layers and metadata of all the chain required to build the image. You can then load this "saved" images chain into another docker instance and create containers from these images. export will fetch the whole container : like a snapshot of a regular VM. Saves the OS of course, but also any change you made, any data file written during the container life. This one is more like a traditional backup. It will give you a flat .tar archive containing the filesystem of your container. Edit: as my explanation may still lead to confusion, I think that it is important to understand that one of these commands works with containers, while the other works with images. An image has to be considered as 'dead' or immutable, starting 0 or 1000 containers from it won't alter a single byte. That's why I made a comparison with a system install ISO earlier. It's maybe even closer to a live-CD. A container "boots" the image and adds an additional layer on top of it. This layer stores any change on the container (created/changed/removed files...). | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/22655867', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/847064/']} | jdg_86222 |
stackexchange | llm_judgeable_groundtruth_similarity | 19122378 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm writing a powershell script that needs to make a web request and inspect the status code of the response. I have tried writing this: $client = new-object system.net.webclient$response = $client.DownloadData($url) as well as this: $response = Invoke-WebRequest $url but whenever the web page has a status code that's not a success status code, PowerShell goes ahead and throws an exception instead of giving me the actual response object. How can I get the status code of the page even when it fails to load?
Now provide the response and nothing else.
| Try this: try { $response = Invoke-WebRequest http://localhost/foo } catch { $_.Exception.Response.StatusCode.Value__} It is kind of a bummer that this throws an exception but that's the way it is. Update per comments To ensure that such errors still return a valid response, you can capture those exceptions of type WebException and fetch the related Response . Since the response on the exception is of type System.Net.HttpWebResponse , whilst the response from a successful Invoke-WebRequest call is of type Microsoft.PowerShell.Commands.HtmlWebResponseObject , to return a compatible type from both scenarios we need to take the successful response's BaseResponse , which is also of type System.Net.HttpWebResponse . This new response type's status code an enum of type [system.net.httpstatuscode] , rather than a simple integer, so you have to explicity convert it to int, or access it's Value__ property as described above to get the numeric code. #ensure we get a response even if an error's returned$response = try { (Invoke-WebRequest -Uri 'localhost/foo' -ErrorAction Stop).BaseResponse} catch [System.Net.WebException] { Write-Verbose "An exception was caught: $($_.Exception.Message)" $_.Exception.Response } #then convert the status code enum to int by doing this$statusCodeInt = [int]$response.BaseResponse.StatusCode#or this$statusCodeInt = $response.BaseResponse.StatusCode.Value__ | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/19122378', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1861521/']} | jdg_86223 |
stackexchange | llm_judgeable_groundtruth_similarity | 507556 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Just been looking at the Spring framework for JDBC - it looks like there is a bit of a learning curve - and I'm still not able to find a nice up to date quick start Spring/JDBC tutorial of any quality! Is there something lighter than Spring for basic JDBC operations - or has anyone got any good links for tutorials Many thanks
Now provide the response and nothing else.
| Quite the opposite. JDBC support in Spring is very simple. Here is basic example: dataSource = ... obtain data source... (e.g. via Spring config)SimpleJdbcTemplate jdbcTemplate = new SimpleJdbcTemplate(dataSource);Map<String, Object> row = jdbcTemplate.queryForMap( "SELECT * FROM MyTable WHERE ID=? LIMIT 1", 100); JdbcTemplate and SimpleJdbcTemplate has lot of query methods you may find useful. For mapping rows to your objects, take a look at RowMapper and ParameterizedRowMapper < T >. For your datasource you usually want to use some advanced DataSource with pooling support. For testing, simple BasicDataSource will do: BasicDataSource ds = new BasicDataSource();ds.setDriverClassName("driverClassName");ds.setUrl("jdbc://...");ds.setUsername("username");ds.setPassword("password"); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/507556', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5175/']} | jdg_86224 |
stackexchange | llm_judgeable_groundtruth_similarity | 50625036 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am making a pod (MySDK) and would like to load the assets from the separate resource bundles CocoaPods generates. However, I can not get it to work. Here is how I tried to load the storyboard: let storyBoard = UIStoryboard(name: "SDK", bundle: Bundle(identifier:"org.cocoapods.SchedJoulesSDK")) This gives the error: 'Could not find a storyboard named 'SDK' in bundle The bundle is added in Xcode: And my podspec looks like this: s.resource_bundles = { 'MySDK' => ['SDK/*/*.{xib,storyboard,xcassets}'] } Any ideas?
Now provide the response and nothing else.
| If you use resource or resources in a CocoaPods PodSpec file, you tell Cocoapods that these are the resource files your library will load during runtime. If your library is built as a dynamic framework, these files are just copied to the resource folder path of that framework and everything will be fine. Yet if your library is built as a static library, these are copied to the resource folder of the main application bundle ( .app ) and this can be a problem as this main application may already have a resource of that name or another Pod may have a resource of that name, in that case these files will overwrite each other. And whether a Pod is built as dynamic framework or as a static library is not specified by the PodSpec but in the Podfile by the application integrating your Pod. Thus for Pods with resources, it is highly recommended to use resource_bundles instead! In your case, the lines s.resource_bundles = { 'MySDK' => ['SDK/*/*.{xib,storyboard,xcassets}'] } tell CocoaPods to create a resource bundle named MySDK ( MySDK.bundle ) and place all files matching the pattern into that resource bundle. If your Pod is built as a framework, this bundle is located in the resources folder of your framework bundle; if it is built as a static library, the bundle is copied to the resources folder of the main application bundle, which should be safe if you name your bundle the same way as your Pod (you should not name it " MySDK ", rather " SchedJoulesSDK "). This bundle will have the same identifier as your Pod, however when dynamic frameworks are built, your framework bundle will have that identifier as well and then it's undefined behavior which bundle is being loaded when you load it by identifier (and currently the outer bundle always wins in my tests). Correct code would look like this (not tested, though): // Get the bundle containing the binary with the current class.// If frameworks are used, this is the frameworks bundle (.framework),// if static libraries are used, this is the main app bundle (.app).let myBundle = Bundle(for: Self.self)// Get the URL to the resource bundle within the bundle// of the current class.guard let resourceBundleURL = myBundle.url( forResource: "MySDK", withExtension: "bundle") else { fatalError("MySDK.bundle not found!") }// Create a bundle object for the bundle found at that URL.guard let resourceBundle = Bundle(url: resourceBundleURL) else { fatalError("Cannot access MySDK.bundle!") }// Load your resources from this bundle.let storyBoard = UIStoryboard(name: "SDK", bundle: resourceBundle) As resourceBundle cannot change at runtime, it is safe to create it only once (e.g. on app start or when your framework is initialized) and store it into a global variable (or global class property), so you have it always around when needed (a bundle object also hardly uses any RAM memory, as it only encapsulates meta data): final class SchedJoulesSDK { static let resourceBundle: Bundle = { let myBundle = Bundle(for: SchedJoulesSDK.self) guard let resourceBundleURL = myBundle.url( forResource: "MySDK", withExtension: "bundle") else { fatalError("MySDK.bundle not found!") } guard let resourceBundle = Bundle(url: resourceBundleURL) else { fatalError("Cannot access MySDK.bundle!") } return resourceBundle }()} The property is initialized lazy (that's default for static let properties, no need for the lazy keyword) and the system ensures that this happen only once, as a let property must not changed once initialized. Note that you cannot use Self.self in that context, you need to use the actual class name. In your code you can now just use that bundle wherever needed: let storyBoard = UIStoryboard(name: "SDK", bundle: SchedJoulesSDK.resourceBundle) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50625036', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4421100/']} | jdg_86225 |
stackexchange | llm_judgeable_groundtruth_similarity | 14672746 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
TL;DR; Is there a way to compress an image (mostly jpeg, png and gif) directly browser-side, before uploading it ? I'm pretty sure JavaScript can do this, but I can't find a way to achieve it. Here's the full scenario I would like to implement: the user goes to my website, and choose an image via an input type="file" element, this image is retrieved via JavaScript, we do some verification such as correct file format, maximum file size etc, if every thing is OK, a preview of the image is displayed on the page, the user can do some basic operations such as rotate the image by 90°/-90°, crop it following a pre-defined ratio, etc, or the user can upload another image and return to step 1, when the user is satisfied, the edited image is then compressed and "saved" locally (not saved to a file, but in the browser memory/page),- the user fill a form with data like name, age etc, the user click on the "Finish" button, then the form containing datas + compressed image is sent to the server (without AJAX), The full process up to the last step should be done client side, and should be compatible on latest Chrome and Firefox, Safari 5+ and IE 8+ . If possible, only JavaScript should be used (but I'm pretty sure this is not possible). I've not code anything right now, but I've thought about it already. File reading locally is possible via File API , image previewing and editing could be done using Canvas element, but I can't find a way to do the image compression part . According to html5please.com and caniuse.com , supporting those browser is quite hard (thanks to IE), but could be done using polyfill such as FlashCanvas and FileReader . Actually, the goal is to reduce file size, so I see image compression as a solution. But, I know that uploaded images are going to be displayed on my website, every time at the same place, and I know the dimension of this display area (eg. 200x400). So, I could resize the image to fit those dimensions, thus reducing file size. I have no idea what would be the compression ratio for this technique. What do you think ? Do you have any advice to tell me ? Do you know any way to compress an image browser-side in JavaScript ? Thanks for your replies.
Now provide the response and nothing else.
| In short: Read the files using the HTML5 FileReader API with .readAsArrayBuffer Create a Blob with the file data and get its url with window.URL.createObjectURL(blob) Create new Image element and set it's src to the file blob url Send the image to the canvas. The canvas size is set to desired output size Get the scaled-down data back from canvas via canvas.toDataURL("image/jpeg",0.7) (set your own output format and quality) Attach new hidden inputs to the original form and transfer the dataURI images basically as normal text On backend, read the dataURI, decode from Base64, and save it Source: code . | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/14672746', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/827168/']} | jdg_86226 |
stackexchange | llm_judgeable_groundtruth_similarity | 3737197 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I met an identity, similar to Vandermonde's identity, but not sure how to prove: $$\sum_{j=0}^k{k \choose j}{\frac{1}{2}j \choose n}(-1)^{n+k-j}=\frac{k}{n}(-1)^k2^{k-2n}{2n-k-1 \choose n-1}, \ n \geq k \geq0.$$ You may find this identity in Section 6 of "2018The computation of the probability density and distribution functions for some families of random variables by means of the Wynn-p accelerated Post-Widder formula" and Appendix of "2007Bayesian nonparametric estimation of the probability of discovering new species". I cannot see how to apply Vandermonde's identity here, although they are similar. Any help is appreciated.
Now provide the response and nothing else.
| We seek to show that $$\sum_{j=0}^k {k\choose j} {j/2\choose n} (-1)^{n-j} =\frac{k}{n} 2^{k-2n} {2n-k-1\choose n-1}$$ where $n\ge k\ge 0.$ Here we have removed the factor $(-1)^k$ which ispresent on both sides. We get for the even component $$\sum_{p=0}^{\lfloor k/2 \rfloor} {k\choose 2p} {p\choose n} (-1)^{n} = 0$$ because $n\gt p$ and $p\ge 0.$ This leaves the odd component $$- (-1)^{n} \sum_{p=0}^{\lfloor (k-1)/2 \rfloor} {k\choose 2p+1} {p+1/2\choose n}.$$ Now we have $${p+1/2\choose n} = \frac{1}{n!} \prod_{q=0}^{n-1} (p+1/2-q)= \frac{1}{2^n n!} \prod_{q=0}^{n-1} (2p+1-2q)\\ = \frac{1}{2^n n!} \prod_{q=0}^{p} (2p+1-2q)\prod_{q=p+1}^{n-1} (2p+1-2q)\\ = \frac{1}{2^n n!} \frac{(2p+2)!}{2^{p+1} (p+1)!}(-1)^{n-p-1} \prod_{q=p+1}^{n-1} (2q-2p-1)\\ = \frac{1}{2^n n!} \frac{(2p+2)!}{2^{p+1} (p+1)!}(-1)^{n-p-1} \frac{(2n-2p-2)!}{2^{n-p-1} (n-p-1)!}\\ = \frac{(-1)^{n-p-1} (2n)!}{2^{2n} n!^2}{2n\choose 2p+2}^{-1} {n\choose p+1}\\ = \frac{(-1)^{n-p-1}}{2^{2n}} {2n\choose n}{2n\choose 2p+2}^{-1} {n\choose p+1}.$$ where $p\lt n.$ It will be helpful to re-write this as $$\frac{p+1}{n} \frac{(-1)^{n-p-1}}{2^{2n}} {2n\choose n}{2n-1\choose 2p+1}^{-1} {n\choose p+1}\\ = \frac{(-1)^{n-p-1}}{2^{2n}} {2n\choose n}{2n-1\choose 2p+1}^{-1} {n-1\choose p}.$$ We thus get for our sum $$\frac{1}{2^{2n}} {2n\choose n}\sum_{p=0}^{\lfloor (k-1)/2 \rfloor} (-1)^p {k\choose 2p+1}{2n-1\choose 2p+1}^{-1} {n-1\choose p}.$$ Now observe that $${k\choose 2p+1} {2n-1\choose 2p+1}^{-1}= \frac{k!}{(k-2p-1)!} \frac{(2n-2p-2)!}{(2n-1)!}\\ = {2n-1\choose k}^{-1} {2n-2p-2\choose k-2p-1}.$$ This yields for the sum $$\frac{1}{2^{2n}} {2n\choose n} {2n-1\choose k}^{-1}\sum_{p=0}^{\lfloor (k-1)/2 \rfloor} (-1)^p {2n-2p-2\choose k-2p-1} {n-1\choose p}.$$ Now to treat the remaining sum we have $$[z^{k}] (1+z)^{2n-2} \sum_{p=0}^{\lfloor (k-1)/2 \rfloor}(-1)^p z^{2p+1} (1+z)^{-2p} {n-1\choose p}.$$ The coefficient extractor enforces the upper limit $\lfloor (k-1)/2\rfloor \ge p$ so we may continue with $$[z^{k}] (1+z)^{2n-2} \sum_{p\ge 0}(-1)^p z^{2p+1} (1+z)^{-2p} {n-1\choose p}\\ = [z^{k}] (1+z)^{2n-2} z \left(1-\frac{z^2}{(1+z)^2}\right)^{n-1}\\ = [z^{k}] z (1+2z)^{n-1}.$$ This means for $k=0$ the sum is zero. For $k\ge 1$ we getincluding the factor in front $$\bbox[5px,border:2px solid #00A000]{\frac{1}{2^{2n}} {2n\choose n} {2n-1\choose k}^{-1}{n-1\choose k-1} 2^{k-1}.}$$ To simplify this we expand the binomial coefficients $$\frac{1}{2^{2n-k+1}} \frac{(2n)!\times k! \times (2n-1-k)! \times (n-1)!}{n! \times n! \times (2n-1)! \times (k-1)! \times (n-k)!}\\ = \frac{1}{2^{2n-k+1}} \frac{(2n)\times k \times (2n-1-k)!}{n \times n! \times (n-k)!}\\ = \frac{1}{2^{2n-k}} \frac{k \times (2n-1-k)!}{n! \times (n-k)!}.$$ This yields at last $$\bbox[5px,border:2px solid #00A000]{\frac{1}{2^{2n-k}} \frac{k}{n} {2n-1-k\choose n-1}.}$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3737197', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/321587/']} | jdg_86227 |
stackexchange | llm_judgeable_groundtruth_similarity | 297779 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
Can you give some pointers to setup Mercurial over HTTP/HTTPS?I am setting up a development server (Debian), where i want to create a mercurial repository and push the changes to the server. I need to authenticate to prevent any unnecessary access. Thanks in advance.
Now provide the response and nothing else.
| I think Apache is a great way of sharing hg repositories. Not only does the hgweb.wsgi script give one the possibility of running multiple repositories, but it allows developers to conveniently cross-reference the project source code by path or revision from a definitive source. The following procedure will give an easy way of publishing a repository, and making it available over an https web connection to authenticated users. First of all I suggest making a clone of your repo without a local file directory. hg clone -U <myproject> <myproject_to_serve> Next (using the WSGI configuration which is nice an easy), do the following: Move your repo to a convenient place from which to serve it: mv <myproject_to_serve> /var/www/hg/<myproject_to_serve> Make sure that the repo is read/writable by the web server user: chown -R www-data:www-data /var/www/hg/<myproject_to_serve> Now setup read/write rights for users of the project, and provide some information for the project listing on your server's home page: vim /var/www/hg/myproject_to_serve>/.hg/hgrc[web]description = 'This is my new web-enabled project <myproject>'contact = [email protected]# consider limiting push usage to only a subset of usersallow_push = * Now setup WSGI vim /var/www/hg/hgweb.config[paths]/myproj = /var/www/hg/my_project_to_serve Now setup apache <VirtualHost *:443> ServerName hg.mydomain.net ServerAdmin [email protected] ErrorLog /var/www/mydomain/logs/hg_error_log CustomLog /var/www/mydomain/logs/hg_access_log common SSLEngine on SSLCertificateFile /etc/ssl/mydomain_net.crt SSLCertificateKeyFile /etc/ssl/mydomain_net.key DocumentRoot "/var/www/hg/" <Location "/hg"> SetHandler None </Location> # path to provided hgweb.wsgi script WSGIScriptAlias / /var/www/hg/scripts/hgweb.wsgi <Location / > AuthType Digest AuthName "MySoftware" AuthUserFile /home/software/software_web_permissions Require valid-user </Location></VirtualHost> The above requires you to have: The hgweb.wsgi script (which comes with a standard Mercurial install on, say, Debian) somewhere conveniently available An AuthUserFile in apache htdigest format for creating authenticated users. Surfing to hg.mydomain.net will show you a nicely formatted list of available projects. hg.mydomain.net/myproj will show you, after successful authentication, the current status of your project as per the /var/www/hg/<myproject_to_serve> repo. | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/297779', 'https://serverfault.com', 'https://serverfault.com/users/84431/']} | jdg_86228 |
stackexchange | llm_judgeable_groundtruth_similarity | 2326072 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Consider this javascript code: var bar = function () { alert("A"); }var foo = bar;bar = function () { alert("B"); };foo(); When running this code I get "A". Is this behavior a part of javascript specification and can I rely on it?
Now provide the response and nothing else.
| Yes that is expected and by design. Your question is basically: does foo reference bar as a pointer or reference would in another language? The answer is no: the value of bar at the time of assignment is assigned to foo . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2326072', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/111438/']} | jdg_86229 |
stackexchange | llm_judgeable_groundtruth_similarity | 2254276 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $A$ , $B$ , $H$ be subgroups of a group $G$ such that $H\subseteq A\cup B$ . Prove that $H\subseteq A$ or $H\subseteq B$ . Any hint would be appreciated!
Now provide the response and nothing else.
| This is solved essentially in the same way explained in answers to your previous question. As a convenient starting point, I will refer to @Jack D'Aurizio 's answer : $$ \int_{0}^{\infty}\frac{1-\cos(kx)}{x^2}\log(x)\,dx = \frac{k\pi}{2}\left(1-\gamma-\log k\right). \tag{1} $$ Now all you have to do is to write $$ \sin^4 x = \frac{1}{2}(1 - \cos(2x)) + \frac{1}{8}(1 - \cos(4x)). \tag{2} $$ I hope that the remaining computation is clear to you. For your attempt, a correct computation would begin with $$ \frac{d}{da} \int_{0}^{\infty} \frac{\sin^4 x}{x^a} \, dx = - \int_{0}^{\infty} \frac{\sin^4 x}{x^a} \log x \, dx. $$ Notice that you misidentified the derivative of your parametrized integral. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2254276', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/429106/']} | jdg_86230 |
stackexchange | llm_judgeable_groundtruth_similarity | 165808 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm looking for very simple obfuscation (like encrypt and decrypt but not necessarily secure) functionality for some data. It's not mission critical. I need something to keep honest people honest, but something a little stronger than ROT13 or Base64 . I'd prefer something that is already included in the .NET framework 2.0, so I don't have to worry about any external dependencies. I really don't want to have to mess around with public/private keys, etc. I don't know much about encryption, but I do know enough to know that anything I wrote would be less than worthless... In fact, I'd probably screw up the math and make it trivial to crack.
Now provide the response and nothing else.
| Other answers here work fine, but AES is a more secure and up-to-date encryption algorithm. This is a class that I obtained a few years ago to perform AES encryption that I have modified over time to be more friendly for web applications (e,g. I've built Encrypt/Decrypt methods that work with URL-friendly string). It also has the methods that work with byte arrays. NOTE: you should use different values in the Key (32 bytes) and Vector (16 bytes) arrays! You wouldn't want someone to figure out your keys by just assuming that you used this code as-is! All you have to do is change some of the numbers (must be <= 255) in the Key and Vector arrays (I left one invalid value in the Vector array to make sure you do this...). You can use https://www.random.org/bytes/ to generate a new set easily: generate Key generate Vector Using it is easy: just instantiate the class and then call (usually) EncryptToString(string StringToEncrypt) and DecryptString(string StringToDecrypt) as methods. It couldn't be any easier (or more secure) once you have this class in place. using System;using System.Data;using System.Security.Cryptography;using System.IO;public class SimpleAES{ // Change these keys private byte[] Key = __Replace_Me__({ 123, 217, 19, 11, 24, 26, 85, 45, 114, 184, 27, 162, 37, 112, 222, 209, 241, 24, 175, 144, 173, 53, 196, 29, 24, 26, 17, 218, 131, 236, 53, 209 }); // a hardcoded IV should not be used for production AES-CBC code // IVs should be unpredictable per ciphertext private byte[] Vector = __Replace_Me__({ 146, 64, 191, 111, 23, 3, 113, 119, 231, 121, 2521, 112, 79, 32, 114, 156 }); private ICryptoTransform EncryptorTransform, DecryptorTransform; private System.Text.UTF8Encoding UTFEncoder; public SimpleAES() { //This is our encryption method RijndaelManaged rm = new RijndaelManaged(); //Create an encryptor and a decryptor using our encryption method, key, and vector. EncryptorTransform = rm.CreateEncryptor(this.Key, this.Vector); DecryptorTransform = rm.CreateDecryptor(this.Key, this.Vector); //Used to translate bytes to text and vice versa UTFEncoder = new System.Text.UTF8Encoding(); } /// -------------- Two Utility Methods (not used but may be useful) ----------- /// Generates an encryption key. static public byte[] GenerateEncryptionKey() { //Generate a Key. RijndaelManaged rm = new RijndaelManaged(); rm.GenerateKey(); return rm.Key; } /// Generates a unique encryption vector static public byte[] GenerateEncryptionVector() { //Generate a Vector RijndaelManaged rm = new RijndaelManaged(); rm.GenerateIV(); return rm.IV; } /// ----------- The commonly used methods ------------------------------ /// Encrypt some text and return a string suitable for passing in a URL. public string EncryptToString(string TextValue) { return ByteArrToString(Encrypt(TextValue)); } /// Encrypt some text and return an encrypted byte array. public byte[] Encrypt(string TextValue) { //Translates our text value into a byte array. Byte[] bytes = UTFEncoder.GetBytes(TextValue); //Used to stream the data in and out of the CryptoStream. MemoryStream memoryStream = new MemoryStream(); /* * We will have to write the unencrypted bytes to the stream, * then read the encrypted result back from the stream. */ #region Write the decrypted value to the encryption stream CryptoStream cs = new CryptoStream(memoryStream, EncryptorTransform, CryptoStreamMode.Write); cs.Write(bytes, 0, bytes.Length); cs.FlushFinalBlock(); #endregion #region Read encrypted value back out of the stream memoryStream.Position = 0; byte[] encrypted = new byte[memoryStream.Length]; memoryStream.Read(encrypted, 0, encrypted.Length); #endregion //Clean up. cs.Close(); memoryStream.Close(); return encrypted; } /// The other side: Decryption methods public string DecryptString(string EncryptedString) { return Decrypt(StrToByteArray(EncryptedString)); } /// Decryption when working with byte arrays. public string Decrypt(byte[] EncryptedValue) { #region Write the encrypted value to the decryption stream MemoryStream encryptedStream = new MemoryStream(); CryptoStream decryptStream = new CryptoStream(encryptedStream, DecryptorTransform, CryptoStreamMode.Write); decryptStream.Write(EncryptedValue, 0, EncryptedValue.Length); decryptStream.FlushFinalBlock(); #endregion #region Read the decrypted value from the stream. encryptedStream.Position = 0; Byte[] decryptedBytes = new Byte[encryptedStream.Length]; encryptedStream.Read(decryptedBytes, 0, decryptedBytes.Length); encryptedStream.Close(); #endregion return UTFEncoder.GetString(decryptedBytes); } /// Convert a string to a byte array. NOTE: Normally we'd create a Byte Array from a string using an ASCII encoding (like so). // System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); // return encoding.GetBytes(str); // However, this results in character values that cannot be passed in a URL. So, instead, I just // lay out all of the byte values in a long string of numbers (three per - must pad numbers less than 100). public byte[] StrToByteArray(string str) { if (str.Length == 0) throw new Exception("Invalid string value in StrToByteArray"); byte val; byte[] byteArr = new byte[str.Length / 3]; int i = 0; int j = 0; do { val = byte.Parse(str.Substring(i, 3)); byteArr[j++] = val; i += 3; } while (i < str.Length); return byteArr; } // Same comment as above. Normally the conversion would use an ASCII encoding in the other direction: // System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding(); // return enc.GetString(byteArr); public string ByteArrToString(byte[] byteArr) { byte val; string tempStr = ""; for (int i = 0; i <= byteArr.GetUpperBound(0); i++) { val = byteArr[i]; if (val < (byte)10) tempStr += "00" + val.ToString(); else if (val < (byte)100) tempStr += "0" + val.ToString(); else tempStr += val.ToString(); } return tempStr; }} | {} | {'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/165808', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/232/']} | jdg_86231 |
stackexchange | llm_judgeable_groundtruth_similarity | 70819 |
Below is a question asked on the forum dsp.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
How much gain in dynamic range and SNR can be expected if we are to oversample a signal with fixed analog input bandwidth. For Example if I have a analog filter at the input which limits the bandwidth to 100 MHz. The noise power will also be limited to the 100 MHz bandwidth ( $kTB$ formula for noise). Now if I were to oversample the data by a factor of 2 how much gain should I expect and why? I know we get 3 dB gain due to spreading of quantization noise, will a similar gain be achieved also due to limiting the noise bandwidth at the input?
Now provide the response and nothing else.
| OP clarified that the question in the comments as follows: If we ignore any modulation for now and assume that we are receivingpure tones plus the band limited noise and we try to improve the SNRin post processing how much improvement can we expect by oversamplingand is there a limit to it? My original question was about thisaspect. First consider the case of sampled white noise (no band-limiting of the sampled signal other than anti-alias filtering prior to the A/D converter), the improvement in SNR due to oversampling a pure tone would be the processing gain in a matched filter such as a correlator to $e^{j\omega n}$ given as $\sum x[n]e^{-j\omega n}$ : $$PG = 10\log_{10}(N) \text{ dB}$$ This is because as we sum the samples in the correlation process, the signal component of each sample which is correlated from sample to sample will increase at $20\log(N)$ dB while the noise components will increase at $10\log(N)$ dB: The total signal magnitude would be $x_1+x_2+x_3 +\ldots$ while the total noise rms magnitude would be $\sqrt{x_1^2+x_2^2 + x_3^2 + \ldots}$ But with band-limiting, as we increase the sampling rate beyond the Nyquist frequency for the bandwidth of the signal, there will be no further increase in SNR: since the signal is bandlimited (no longer white), adjacent samples will be correlated both in signal and in noise, and as we sum the samples in an attempt to increase SNR, both the signal and noise components of the signal will increase at the same rate ( $20\log_{10}(N)$ ). Assuming a constant noise out to $f_b$ and then rolling off after that, we would increase SNR after correlation up to the point where $f_s/2 = f_b$ (for a real signal) Increasing the sampling rate beyond that will not increase SNR. Further we have a practical limit for long averaging situations from ADC spurious free dynamic range (SFDR), phase noise from clocks and local oscillators, and similar $1/f$ noise sources where the signal is no longer stationary and increasing the averaging duration further will begin to degrade SNR. The Allan Deviation (ADEV) is an excellent statistical tool for determining the optimum duration to average given we have no other constraints on the time interval. (For more on ADEV for this application see What determines the accuracy of the phase result in a DFT bin? ) If the input signal has a fixed analog bandwidth, and you are properly not limited by the quantization noise, and front-end filtering has been sufficient to not have aliasing to occur, then oversampling will not have any effect on the SNR in band. The idea of oversampling is to spread the quantization noise out so that it is no longer swamping out the noise floor of your signal which should be the limiting factor to SNR, and to allow for appropriate filter design to eliminate noise out of band from folding in at a lower sampling rate. These are the two most prominent reasons to oversample: increasing the effective resolution by spreading out the same total quantization noise over the full sampling bandwidth, and increasing the total frequency space in which we can do digital radio processing of signals outside our primary band of interest, for filter rejection and multi-carrier operations. For more details on the first and it's limitations please see: What are advantages of having higher sampling rate of a signal? It is assumed that the proper receiver design will filter out all noise that is outside of your signal bandwidth (the matched filter), so given you are sampling sufficiently high according to Nyquist (2x the bandwidth, plus some margin for realistic filter realization) then there is no reason to sample any higher once the signal is properly filtered (and this only increases power dissipation, increased resources, etc). The strategy should be to sample sufficiently high at the front-end of the digital receiver for the filter designs involved and in consideration with the analog filtering that may be done for anti-aliasing, then once out of band noise, interference and other channels are filtered out, reduce the sampling rate to be as small as possible (typically 2 samples/symbol). This may add a further intuitive explanation: Consider a band-limited random noise process with the sampled time domain signal shown below along with a histogram of those samples along the right axis, and then immediately below that is the spectrum. As long as we sample that spectrum more than twice the bandwidth shown, no matter how much faster we sample we will still get the same histogram, from which we get the standard deviation of that noise. If we had additional noise energy outside the signal's bandwidth, then oversampling can of course help us to eliminate that interference through filtering where it could otherwise fold into band with a lower sampling rate-- but this isn't improving SNR by oversampling, this would be implementing proper receiver design by filtering out interference (which that task alone may require a higher sampling rate). | {} | {'log_upvote_score': 4, 'links': ['https://dsp.stackexchange.com/questions/70819', 'https://dsp.stackexchange.com', 'https://dsp.stackexchange.com/users/47019/']} | jdg_86232 |
stackexchange | llm_judgeable_groundtruth_similarity | 28361456 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Consider following statement: byte by = 5; //works fine literal '5' is of type int and small enough to fit into a variable of type byte. Compiler does the implicit type casting here (from int to byte). Now consider following scenario: float fl = 5.5; //compilation error literal '5.5' is of type double, also small enough to fit into a variable of type float. Why do we need to explicitly type cast like this: float fl = (float) 5.5; //works fine Why compiler is not doing the casting for us in case of floating points?
Now provide the response and nothing else.
| In the integer version, the compiler knows that all the data in the number 5 can be stored in a byte . No information is lost. That's not always true for floating point values. For example, 0.1f isn't equal to 0.1d . Now for the example, you've given, the decimal value 5.5 is exactly represented in both float and double , so you could argue that in that case, no information is lost - but it would be pretty odd for the language specification to have to make this valid: float f = 5.5; but this invalid: float f = 5.6; The language specification is happy to talk about whether a number fits within the range of float / double (although even that isn't as simple as you might expect) but when it comes to whether a literal can be exactly represented, I don't think it ever goes into detail. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28361456', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4078987/']} | jdg_86233 |
stackexchange | llm_judgeable_groundtruth_similarity | 649349 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a 1970s-vintage video generating board that I'd like to do some work with. I do not have the PSU that it was meant to be connected to. The board wants +/-5V, -12V DC, plus a small 6V AC "reference" rail that shares the same common/ground rail. I'm a bit puzzled as to the simplest way to recreate this. The original PSU's schematic looks like this: The 6VAC connection is marked "R" at left, and as you can see, it is connected to one of the transformer tap outputs, bypassing all the rectifier stuff, and its current returns back to the system via the common ground rails to the center taps. The DC supplies are easy-- this switching quad output Mean Well on amazon puts out +/-5 and +/-12. But this leaves me without an answer for the 6VAC line. I can separately find a 6V transformer but that results in an independently isolated AC. (And that's not helpful to me... right?) There are modern linear supplies like this one that I assume could be rigged up to pull out an AC line but they don't seem to ever support a -5VDC line. This isn't for super robust long term use so I'm willing to rig something up to get it going, but I'd like some guidance or suggestions. Short of finding the old transformer and literally rebuilding the original 70s PSU design, is there some way to create a viable power supply that meets this need with modern bits and pieces? Further information as requested by kind commenters: The schematic for the video board showing use of the 6VAC line is linked here . 6VAC connection is on the right of the diagram, entering an RC ladder and going into the drain of an old JFET: (Part values are not marked on this diagram, they are in a different document (page 5), which is annoying.)
Now provide the response and nothing else.
| I can separately find a 6V transformer but that results in an independently isolated AC. (And that's not helpful to me... right?) Nope. The simplest way to go is what you said, a separate transformer. Connect one lead from the secondary to system GND, and the other lead will be your 6 Vac waveform with the system GND as its reference - exactly as in the original design. There is nothing in the original design that is phase-dependent, so you can ground either secondary lead. UPDATE: As for transformer size, it can be very small. Based on the added schematic, the current load is very small. You don't say the values of R1 - R4, but in that circuit there is no reason for any significant current. | {} | {'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/649349', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/4548/']} | jdg_86234 |
stackexchange | llm_judgeable_groundtruth_similarity | 44391262 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am using a similar code like this to redirect in my app after users logged in. The code looks like the following: import React, { Component } from 'react'import { Redirect } from 'react-router'export default class LoginForm extends Component { constructor () { super(); this.state = { fireRedirect: false } } submitForm = (e) => { e.preventDefault() //if login success this.setState({ fireRedirect: true }) } render () { const { from } = this.props.location.state || '/' const { fireRedirect } = this.state return ( <div> <form onSubmit={this.submitForm}> <button type="submit">Submit</button> </form> {fireRedirect && ( <Redirect to={from || '/home'}/> )} </div> ) }} Works fine when a successful login has been triggered. But there is the case, that logged in users enter the login page and should be automatically redirected to the "home" page (or whatever other page). How can I use the Redirect component without rendering the current component and without (as far as I understand discouraged ) imperative pushing to the history (e.g. in componentWillMount )?
Now provide the response and nothing else.
| Solution 1 You could use withRouter HOC to access history via props. Import withRouter. import { withRouter} from 'react-router-dom'; Then wrap with HOC. // Example codeexport default withRouter(connect(...))(Component) Now you can access this.props.history . For example use it with componentDidMount() . componentDidMount() { const { history } = this.props; if (this.props.authenticated) { history.push('/private-route'); }} Solution 2 Much better Here is example on reacttraining . Which would perfectly work for you. But you just need to create LoginRoute to handle problem you described. const LoginRoute = ({ component: Component, ...rest }) => ( <Route {...rest} render={props => ( fakeAuth.isAuthenticated ? ( <Redirect to={{ pathname: '/private-route', state: { from: props.location } }} /> ) : ( <Component {...props} /> ) )} />); and inside <Router /> just replace <Route path="/login" component={Login}/> with <LoginRoute path="/login" component={Login}/> Now everytime somebody will try to access /login route as authenticated user, he will be redirected to /private-route . It's even better solution because it doesn't mount your LoginComponent if condition isn't met. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44391262', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3098783/']} | jdg_86235 |
stackexchange | llm_judgeable_groundtruth_similarity | 3907160 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Assume a year has $365$ days, how many are required to have a $50%$ chance of $2$ people having the same birthday? According to Scientific American , there are $23$ people needed to achieve the goal. $${\begin{pmatrix} 23 \\ 2\end{pmatrix}}=253$$ $$1-(1-\frac{1}{365})^{253}\approx 0.50048$$ However, I have a different approach but I'm not sure if this is correct. One could be any day in a year. And $23$ people would be $365^{23}$ possibilities. Suppose no one in $23$ people has the same birthday.That would be :- ${\begin{pmatrix} 365 \\ 23 \end{pmatrix}} \cdot23!$ The possibility of having at least 2 people having the same birthday is :- $$1-\frac{{\begin{pmatrix} 365 \\ 23 \end{pmatrix}} \cdot23!}{365^{23}}\approx0.5072972$$ Although $0.50048\approx 0.5072972$ , these two numbers are not equal to each other. Can anyone explain this difference and the reason behind this phenomenon?
Now provide the response and nothing else.
| The Scientific American's calculation is not quite accurate: it supposes that every non-match between two people is independent from any other non-match between two people, but that is not the case. To see this, consider just 3 people: A, B, and C. What is the chance that they don't share a birthday? Scientific American's approach is to say: well, we need the following three events: E1. A and B don't share a birthday E2. A and C don't share a birthday E3. B and C don't share a birthday Now, individually, the probability of each of those events is $\frac{364}{365}$ So, they say: $P(E1 \cap E2 \cap E3) = P(E1) \cdot P(E2) \cdot P(E3) = (\frac{364}{365})^3$ But again, that is assuming these three events are independent ... and they are not! For example, once we know that $A$ does not share a birthday with either $B$ or $C$ (i.e. once we have events $E1$ and $E2$ ) the probability of $B$ not sharing a birthday with $C$ (i.e. event $E3$ ) is no longer a simple $\frac{364}{365}$ , because it is no longer possible for $B$ or $C$ to have their birthday on the day that $A$ has their birthday. Indeed, the more people we know do not share a birthday with $B$ and $C$ , the fewer options become available for $B$ and $C$ to have their birthdays, and this will in fact increase the chances of $B$ and $C$ to share a birthday, and thus decrease the chance of them not sharing a birthday. To illustrate how the probability of $B$ and $C$ not sharing their birthday is affected once we know they don't share the same birthday with $A$ (how, indeed, that probability has gone down), consider what happens when we consider only three possible days that each of $A$ , $B$ , and $C$ can have their birthday. First of all, the probability of $B$ and $C$ sharing their birthday not knowing anything about $A$ is $\frac{1}{3}$ , and hence there is a $\frac{2}{3}$ probability that they don't share their birthday. OK, but now let's add the information that $B$ nor $C$ share their birthday with $A$ . That means that there are now only two days left for $B$ and $C$ to have their birthday, meaning that now there is a $\frac{1}{2}$ probability that they share their birthday, and hence a $\frac{1}{2}$ probability that they don't share their birthday. So, indeed, the probability that $B$ and $C$ don't share their birthday has gone down once we know they don't share their birthday with $A$ . And indeed, note what happens when we have even fewer possible birthdays: if we get to a point where we have more people than possible birthdays, then the probability of two people not matching their birthdays given that no one else shares their birthday with any of these two people simplybecomes $0$ . In sum: the probability that Scientific American assumes for each non-match is too high. Now, with the actual birthday problem we are not considering $3$ people and $3$ possible birthdays, but $23$ people with $365$ possible birthdays. And with so many more birthdays than people, it turns out that Scientific American's calculations are not going to be that far off. But still: the $\frac{364}{365}$ is a little too high for the remaining non-matches once you already know other non-matches, meaning that the $(\frac{364}{365})^{253}$ is a little too big, and thus when subtracted from $1$ , the Scientific American's calculation ends up being a little too low. But of course, it would be hard to tell this beforehand (note that the $\frac{364}{365}$ does get raised to the $253$ -th power!) ... It happened to get 'close enough' for this problem ... but I really don't like to think that it was an a priori justified simplification. You certainly can't use this kind of approximation to establish that $23$ people was the magic 'breaking point' as opposed to $22$ people, or maybe even fewer. Indeed, they we're lucky that with their calculation for $23$ people it just stayed above $0.5$ . Your calculation, however, is completely correct. Good job!! | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3907160', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/705433/']} | jdg_86236 |
stackexchange | llm_judgeable_groundtruth_similarity | 10219864 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm at a loss for this: I've defined my classes for a entity framework (4.1.3) code first approach. Everything was fine (I was creating the tables etc.) until I started to Seed. Now when I do the Add-Migration "remigrate" ; Update-Database; I get an error on the package console "Validation failed for one or more entities. See 'EntityValidationErrors' property for more details." I have a breakpoint in my Seed() method but because I'm running this on the console when the project is not running, I'm clueless as to how to get to the details (PS - I've seen the thread Validation failed for one or more entities while saving changes to SQL Server Database using Entity Framework which shows how I can see the property.) I know that my Seed() method has a problem because if I put a return right after the method call, the error goes away. So how do I set my breakpoint so I can see what the validation error is? Kinda lost. Or is there some other way to trace it in the nuget console??
Now provide the response and nothing else.
| I got annoyed by this recently too. I fixed it by putting a wrapper function in the Configuration class in the Seed method, and replaced calls to SaveChanges with calls to my function instead. This function would simply enumerate the errors within the EntityValidationErrors collection, and rethrow an exception where the Exception message lists the individual problems. This makes the output show up in the NuGet package manager console. Code follows: /// <summary>/// Wrapper for SaveChanges adding the Validation Messages to the generated exception/// </summary>/// <param name="context">The context.</param>private void SaveChanges(DbContext context) { try { context.SaveChanges(); } catch (DbEntityValidationException ex) { StringBuilder sb = new StringBuilder(); foreach (var failure in ex.EntityValidationErrors) { sb.AppendFormat("{0} failed validation\n", failure.Entry.Entity.GetType()); foreach (var error in failure.ValidationErrors) { sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage); sb.AppendLine(); } } throw new DbEntityValidationException( "Entity Validation Failed - errors follow:\n" + sb.ToString(), ex ); // Add the original exception as the innerException }} Just replace calls to context.SaveChanges() with SaveChanges(context) in your seed method. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/10219864', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/456438/']} | jdg_86237 |
stackexchange | llm_judgeable_groundtruth_similarity | 7577615 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am getting a bunch of relatively small pages from a website and was wondering if I could somehow do it in parallel in Bash. Currently my code looks like this, but it takes a while to execute (I think what is slowing me down is the latency in the connection). for i in {1..42}do wget "https://www.example.com/page$i.html"done I have heard of using xargs, but I don't know anything about that and the man page is very confusing. Any ideas? Is it even possible to do this in parallel? Is there another way I could go about attacking this?
Now provide the response and nothing else.
| Much preferrable to pushing wget into the background using & or -b , you can use xargs to the same effect, and better. The advantage is that xargs will synchronize properly with no extra work. Which means that you are safe to access the downloaded files (assuming no error occurs). All downloads will have completed (or failed) once xargs exits, and you know by the exit code whether all went well. This is much preferrable to busy waiting with sleep and testing for completion manually. Assuming that URL_LIST is a variable containing all the URLs (can be constructed with a loop in the OP's example, but could also be a manually generated list), running this: echo $URL_LIST | xargs -n 1 -P 8 wget -q will pass one argument at a time ( -n 1 ) to wget , and execute at most 8 parallel wget processes at a time ( -P 8 ). xarg returns after the last spawned process has finished, which is just what we wanted to know. No extra trickery needed. The "magic number" of 8 parallel downloads that I've chosen is not set in stone, but it is probably a good compromise. There are two factors in "maximising" a series of downloads: One is filling "the cable", i.e. utilizing the available bandwidth. Assuming "normal" conditions (server has more bandwidth than client), this is already the case with one or at most two downloads. Throwing more connections at the problem will only result in packets being dropped and TCP congestion control kicking in, and N downloads with asymptotically 1/N bandwidth each, to the same net effect (minus the dropped packets, minus window size recovery). Packets being dropped is a normal thing to happen in an IP network, this is how congestion control is supposed to work (even with a single connection), and normally the impact is practically zero. However, having an unreasonably large number of connections amplifies this effect, so it can be come noticeable. In any case, it doesn't make anything faster. The second factor is connection establishment and request processing. Here, having a few extra connections in flight really helps . The problem one faces is the latency of two round-trips (typically 20-40ms within the same geographic area, 200-300ms inter-continental) plus the odd 1-2 milliseconds that the server actually needs to process the request and push a reply to the socket. This is not a lot of time per se , but multiplied by a few hundred/thousand requests, it quickly adds up. Having anything from half a dozen to a dozen requests in-flight hides most or all of this latency (it is still there, but since it overlaps, it does not sum up!). At the same time, having only a few concurrent connections does not have adverse effects, such as causing excessive congestion, or forcing a server into forking new processes. | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/7577615', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/824954/']} | jdg_86238 |
stackexchange | llm_judgeable_groundtruth_similarity | 13718500 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm currently trying to parse some data from a forum. Here is the code: $xml = simplexml_load_file('https://forums.eveonline.com');$names = $xml->xpath("html/body/div/div/form/div/div/div/div/div[*]/div/div/table//tr/td[@class='topicViews']");foreach($names as $name) { echo $name . "<br/>";} Anyway, the problem is that I'm using google xpath extension to help me get the path, and I'm guessing that google is changing the html enough to make it not come up when i use my website to do this search. Is there some type of way I can make the host look at the site through google chrome so that it gets the right code? What would you suggest? Thanks!
Now provide the response and nothing else.
| My suggestion is to always use DOMDocument as opposed to SimpleXML, since it's a much nicer interface to work with and makes tasks a lot more intuitive. The following example shows you how to load the HTML into the DOMDocument object and query the DOM using XPath. All you really need to do is find all td elements with a class name of topicViews and this will output each of the nodeValue members found in the DOMNodeList returned by this XPath query. /* Use internal libxml errors -- turn on in production, off for debugging */libxml_use_internal_errors(true);/* Createa a new DomDocument object */$dom = new DomDocument;/* Load the HTML */$dom->loadHTMLFile("https://forums.eveonline.com");/* Create a new XPath object */$xpath = new DomXPath($dom);/* Query all <td> nodes containing specified class name */$nodes = $xpath->query("//td[@class='topicViews']");/* Set HTTP response header to plain text for debugging output */header("Content-type: text/plain");/* Traverse the DOMNodeList object to output each DomNode's nodeValue */foreach ($nodes as $i => $node) { echo "Node($i): ", $node->nodeValue, "\n";} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13718500', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1878256/']} | jdg_86239 |
stackexchange | llm_judgeable_groundtruth_similarity | 7013137 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am working on automating some telnet related tasks, using Bash scripts.Once automated there will be no interaction of the user with telnet (that is it will be totally automated) The scripts looks something like this: # execute some commands on the local system# access a remote system with an IP address: 10.1.1.1 (for example)telnet 10.1.1.1# execute some commands on the remote system# log all the activity (in a file) on the Local system# exit telnet# continue on with executing the rest of the script. There are 2 problems I am facing here: How to execute the commands on the remote system from the script (without human interaction)? From my experience with some test codes, I was able to deduce that when the telnet 10.1.1.1 is executed, telnet goes into an interactive session and the subsequent lines of code in the script are executed on the local system. How can I run the lines of code on the remote system rather than the local one? I am unable to get a log file for the activity in the telnet session on the local system. The stdout redirect I used makes a copy on the remote system (I do not want to perform a copy operation to copy the log to the local system). How can I achieve this functionality?
Now provide the response and nothing else.
| Write an expect script. Here is an example: #!/usr/bin/expect#If it all goes pear shaped the script will timeout after 20 seconds.set timeout 20#First argument is assigned to the variable nameset name [lindex $argv 0]#Second argument is assigned to the variable userset user [lindex $argv 1]#Third argument is assigned to the variable passwordset password [lindex $argv 2]#This spawns the telnet program and connects it to the variable namespawn telnet $name #The script expects loginexpect "login:" #The script sends the user variablesend "$user "#The script expects Passwordexpect "Password:"#The script sends the password variablesend "$password "#This hands control of the keyboard over to you (Nice expect feature!)interact To run: ./myscript.expect name user password | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/7013137', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/823207/']} | jdg_86240 |
Subsets and Splits
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves samples with 'mathoverflow.net' in the prompt, providing a basic subset for inspection but with limited analytical value.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves 10 samples where the prompt mentions Mathematica Stack Exchange, offering basic filtering to locate specific content.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves a limited number of rows where the prompt contains a specific URL, providing basic filtering that offers minimal insight into the broader dataset patterns.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves 10 samples from the dataset where the prompt contains 'dsp.stackexchange.com', offering a basic filtering of data points related to that specific domain.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves a sample of rows where the prompt contains 'cs.stackexchange.com', providing a basic filter without extensive insight.
Electronics Q&A Subset
Retrieves a limited number of samples that contain a specific URL, providing only raw data filtered by that URL.
StackExchange Stats Questions
Retrieves 100 entries containing 'stats.stackexchange.com' in the prompt, which is useful for finding specific content but lacks broader analytical value.
Math StackExchange Questions
Retrieves 100 records from the train dataset where the prompt contains 'math.stackexchange.com', providing a basic filtered overview of specific entries.
Physics SE Questions
Retrieves 100 samples containing the word 'physics.stackexchange.com' in the prompt, offering basic filtering without deep analysis.