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
751277
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: Last night, my MySQL server went down unexpectedly. On attempting to restart (with service mysql restart - I'm root) it merely hangs. With the mysql -u root -p command, I get ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2) . I then tried to start the daemon manually ( mysqld ). The prompt would hang for about 2 seconds, and then return. On closer inspection of the error logs, I got: 2016-01-22T19:18:32.399584Z 0 [ERROR] Could not create unix socket lock file /var/run/mysqld/mysqld.sock.lock. 2016-01-22T19:18:32.399622Z 0 [ERROR] Unable to setup unix socket lock file. 2016-01-22T19:18:32.399646Z 0 [ERROR] Aborting I then tried chown mysql /var/run/mysqld , chmod -R 775 /var/run/mysqld , touch /var/run/mysqld/mysqld.sock.lock and apt-get install mysql-community-server --reinstall . No luck. I have looked around, and couldn't find a solution. Any help here? Note: I am Running Debian 8 (Jessie) with MySQL community Server 5.7.10 Now provide the response and nothing else.
Note to future travelers: It depends on your specific configuration but this is very likely an issue with apparmor. If you don't want to disable locking take a look at syslog and see if you're getting apparmor denies on that file. You'll see something like: apparmor="DENIED" operation="open" parent=29871 profile="/usr/sbin/mysqld" name="/run/mysqld/mysqld.sock.lock" And can fix it by adding /run/mysqld/mysqld.sock.lock rw to /etc/apparmor.d/usr.sbin.mysqld near the other /run/* entries and reloading apparmor.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/751277', 'https://serverfault.com', 'https://serverfault.com/users/333596/']}
jdg_381741
stackexchange
llm_judgeable_groundtruth_similarity
27081795
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'd like to make simple ribbon animation and here's my outcome: http://jsfiddle.net/eg5zC/50/ Everything works as intended, but after implementing this in my menu it just stopped working.I had to change the syntax from div's to ul's but it should not make any differences. I have added the neccessary function to my private.js file and I can view the function at my site's footer.here's the IP of my digitalocean dev server: http://178.62.215.130/SV/#home Any ideas? I tried to put the code directly in the footer but that doesn't work either. Now provide the response and nothing else.
You should implement the OnItemClickListener in your ViewHolder class, and pass the current item to the ViewHolder instances on every onBindViewHolder() . From this post : public static class ViewHolder extends RecyclerView.ViewHolder { public View view; public Item currentItem; public ViewHolder(View v) { super(v); view = v; view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // item clicked } }); }}@Override public void onBindViewHolder(ViewHolder viewHolder, int i) { viewHolder.currentItem = items.get(i);}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27081795', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_381742
stackexchange
llm_judgeable_groundtruth_similarity
3246400
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 following function will not load: charName :: a -> StringcharName 'a' = "Alpha"charName 'b' = "Bravo"charName 'c' = "Charlie"charName 'd' = "Delta"charName 'e' = "Echo"charName 'f' = "Foxtrot"charName 'g' = "Golf"charName 'h' = "Hotel"charName 'i' = "India"charName 'j' = "Juliet"charName 'k' = "Kilo"charName 'l' = "Lima"charName 'm' = "mike"charName 'n' = "November"charName 'o' = "Oscar"charName 'p' = "Papa"charName 'q' = "Quebec"charName 'r' = "Romeo"charName 's' = "Sierra"charName 't' = "Tango"charName 'u' = "Uniform"charName 'v' = "Victor"charName 'w' = "Whiskey"charName 'x' = "X-ray"charName 'y' = "Yankee"charName 'z' = "Zulu"charName 0 = "Zero"charName 1 = "One"charName 2 = "Two"charName 3 = "Three"charName 4 = "Four"charName 5 = "Five"charName 6 = "Six"charName 7 = "Seven"charName 8 = "Eight"charName 9 = "Nine"charName x = "" It gives me the following error: [1 of 1] Compiling Main ( baby.hs, interpreted ) baby.hs:41:9: Couldn't match expected type a' against inferred type Char' a' is a rigid type variable bound by the type signature for charName' at baby.hs:40:12 In the pattern: 'a' In the definition of `charName': charName 'a' = "Alpha" baby.hs:67:9: No instance for (Num Char) arising from the literal 0' at baby.hs:67:9 Possible fix: add an instance declaration for (Num Char) In the pattern: 0 In the definition of charName': charName 0 = "Zero" Failed, modules loaded: none. Not sure how I can get this to work. Does anybody have any ideas? Now provide the response and nothing else.
With new data type The simple way to pass either Char or Int as a function argument, is to define a new data type to encapsulate them: data (Num a) => CharOrNum a = C Char | N acharName (C 'z') = "Zulu"charName (N 0) = "Zero" Then you can use it like ghci> charName $ C 'z'"Zulu"ghci> charName $ N 0"Zero" With this change the type of charName is (Num t) => CharOrNum t -> [Char] . With new type class Another way is to define a common type class for both of the argument types, like Show . class Nameable a where nameit :: a -> Stringinstance Nameable Char where nameit 'z' = "Zulu" nameit _ = ""instance Nameable Integer where nameit 0 = "Zero" nameit _ = "" Then you can use it like this: ghci> (nameit 0, nameit 'z')("Zero","Zulu")
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3246400', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/45160/']}
jdg_381743
stackexchange
llm_judgeable_groundtruth_similarity
42004939
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Question Is there something wrong with my benchmark? How can Immutable.js find() be 8 times slower than array.find()? Ok, not entirely fair, since I'm using Immutable.Map inside of the Immutable.List. But to me this is a real world example. If I use Immutable.js it's to protect immutability and to gain performance in some aspects (where structural sharing come to play). The would be no point in using Immutable.js only at the root of the object. The below benchmark is actually from another question (mine as well). I was so surprised by the results, I had to post it separately to get it straight. Have I done something wrong in my benchmarks, or is the performance difference really this big? Background Some of the data in my app could be considered app metadata. The original data lives in a database at the server. Updates to the metadata will not be done often. The app will check for updated metadata on startup. I'm using Immutable.js everywhere, but I will go back to plain js for the metadata. There is no need for fancy structural sharing for this kind of data. The test is to find values by key in a collection Collection of 10 items Find a value one million times Mac mini core i7 2.6 Result: Plain JS object with coerced keys: 8 ms Plain JS array using find(): 127 ms Immutable.Map with numeric keys: 185 ms Immutable.List using find(): 972 ms !! I'm baffled As I'm using React Native I always have to look out for the 16 ms limit if I want to achieve 60 fps. The benchmark values does not seem to be linear. Running the test with only 100 lookups takes 1 ms with Map and 2 ms with List. That's quite expensive. Test code let Immutable = require('immutable');let mapTest = Immutable.Map() .set(1, Immutable.Map({value: 'one'})) .set(2, Immutable.Map({value: 'two'})) .set(3, Immutable.Map({value: 'three'})) .set(4, Immutable.Map({value: 'four'})) .set(5, Immutable.Map({value: 'five'})) .set(6, Immutable.Map({value: 'six'})) .set(7, Immutable.Map({value: 'seven'})) .set(8, Immutable.Map({value: 'eight'})) .set(9, Immutable.Map({value: 'nine'})) .set(10, Immutable.Map({value: 'ten'}));let listTest = Immutable.fromJS([ {key: 1, value: 'one'}, {key: 2, value: 'two'}, {key: 3, value: 'three'}, {key: 4, value: 'four'}, {key: 5, value: 'five'}, {key: 6, value: 'six'}, {key: 7, value: 'seven'}, {key: 8, value: 'eight'}, {key: 9, value: 'nine'}, {key: 10, value: 'ten'}])let objTest = { 1: {value: 'one'}, 2: {value: 'two'}, 3: {value: 'three'}, 4: {value: 'four'}, 5: {value: 'five'}, 6: {value: 'six'}, 7: {value: 'seven'}, 8: {value: 'eight'}, 9: {value: 'nine'}, 10: {value: 'ten'}};let arrayTest = [ {key: 1, value: 'one'}, {key: 2, value: 'two'}, {key: 3, value: 'three'}, {key: 4, value: 'four'}, {key: 5, value: 'five'}, {key: 6, value: 'six'}, {key: 7, value: 'seven'}, {key: 8, value: 'eight'}, {key: 9, value: 'nine'}, {key: 10, value: 'ten'}];const runs = 1e6;let i;let key;let hrStart;console.log(' ')console.log('mapTest -----------------------------')key = 1;hrstart = process.hrtime();for(i=0; i<runs; i++) { let result = mapTest.getIn([key, 'value'] ) key = (key >= 10) ? 1 : key + 1;}hrend = process.hrtime(hrstart);console.info("Execution time (hr): %dms", hrend[0] * 1000 + hrend[1]/1000000);console.log(' ')console.log('listTest -----------------------------')key = 1;hrstart = process.hrtime();for(i=0; i<runs; i++) { let result = listTest .find(item => item.get('key') === key) .get('value'); key = (key >= 10) ? 1 : key + 1;}hrend = process.hrtime(hrstart);console.info("Execution time (hr): %dms", hrend[0] * 1000 + hrend[1]/1000000);console.log(' ')console.log('arrayTest -----------------------------')key = 1;hrstart = process.hrtime();for(i=0; i<runs; i++) { let result = arrayTest .find(item => item.key === key) .value key = (key >= 10) ? 1 : key + 1;}hrend = process.hrtime(hrstart);console.info("Execution time (hr): %dms", hrend[0] * 1000 + hrend[1]/1000000);console.log(' ')console.log('objTest -----------------------------')key = 1;hrstart = process.hrtime();for(i=0; i<runs; i++) { let result = objTest[key].value key = (key >= 10) ? 1 : key + 1;}hrend = process.hrtime(hrstart);console.info("Execution time (hr): %dms", hrend[0] * 1000 + hrend[1]/1000000); Now provide the response and nothing else.
The short answer is that the representation of data structures used by Immutable.js requires a lot of additional overhead to iterate through the elements of a List, compared to a native JS array. Benchmarking Immutable.List.find and Array.find Your benchmark is good, but we can simplify matters a bit by getting rid of the nested map; you're right to consider performance for realistic problems, but it can be helpful in understanding performance differences to simplify the problem as much as possible. It's also often useful in benchmarking to consider how performance changes over different input sizes. For instance, it's possible that in Immutable.js, List.prototype.find is implemented in such a way that the intitial call and setup take awhile but that the subsequent iterating through the List performs similarly to native JS Arrays; in this case, the difference in performance between native JS Arrays and Immutable.js lists would decrease for long input lengths (this turns out not to be the case). Let's also create our own find function for native JS arrays, Array.prototype.ourFind to compare to the native Array.prototype.find to determine if the difference could in part be due to the performance of JS functions themselves vs. performance of functions built-in to the implementation. Array.prototype.ourFind = function(predicate) { for (let i = 0; i < this.length; i++) { if (predicate(this[i])) return this[i]; }}function arrayRange(len) { return new Array(len).fill(null).map((_, i) => i);}function immutListRange(len) { return Immutable.fromJS(arrayRange(len));}function timeFind(coll, find, iters) { let startTime = performance.now(); for (let i = 0; i < iters; i++) { let searchVal = i % coll.length, result = find.call(coll, item => item === searchVal); } return Math.floor(performance.now() - startTime);}const MIN_LEN = 10, MAX_LEN = 1e4, ITERS = 1e5;console.log('\t\tArray.find\tArray.ourFind\tList.find');for (let len = MIN_LEN; len <= MAX_LEN; len *= 10) { console.log(`${len}\t\t\t` + `${timeFind(arrayRange(len), Array.prototype.find, ITERS)}\t\t\t` + `${timeFind(arrayRange(len), Array.prototype.ourFind, ITERS)}\t\t\t` + `${timeFind(immutListRange(len), Immutable.List.prototype.find, ITERS)}`)} <script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.1/immutable.js"></script> In Chrome, I get: Length . Array.find Array.ourFind List.find10 28 13 96100 60 44 3421000 549 342 301610000 5533 3142 36423 I got roughly similar results in Firefox and Safari. A few points to note: The difference between List.find vs. Array.find is not simply due to native (i.e. interpreter built-in) implementations vs. JS implementations, because a JS implementation of Array.ourFind performs at least as well as Array.find . All implementations work in O(n) time (i.e. execution time is linear with respect to input length). This is to be expected, since a find algorithm will always have to work by iterating through the collection elements until it finds one for which the predicate returns true. Immutable.List.find is ~6-fold slower than Array.find , consistent with your benchmarking results. Immutable.List data representation To understand why Immutable.List.find is so much slower, you first have to consider how Immutable.List represents the list contents. A quick way to do this is to generate an Immutable.List and examine it in the console: console.log(immutListRange(1000)); // immutListRange defined above So essentially it looks like Immutable.List represents the contents as a tree with a branching factor of 32. Now consider what it will take to run a find operation on data that are represented in this way. You will have to start at the root node, and traverse the tree down to the first leaf node (which contains an Array with the actual data), and iterate through the contents of the leaf; if the element is not found, you have to go to the next leaf node and search that Array, and so on. It's a more complex operation than merely searching through a single array, and it requires overhead to execute. Watching Immutable.List.find at work A great way to appreciate the work that Immutable.List.find does is to set a break point in your debugger of choice and step through the operation. You'll see that Immutable.List.Find is not nearly as simple an operation as merely looping through a single Array. Additional comments The tree representation of data in Immutable.js presumably accelerates other operations, but entails a performance penalty with some functions, such as find. As a side note, I don't think in most cases that the choice to use immutable data structures is driven by performance considerations. There may be some cases where immutable data structures perform better than mutable ones (and certainly immutable data structures make parallel computing less complex, which enables significant performance gain), but there will be many cases when the opposite is true. Rather, the choice of immutability is, in most cases, driven by design considerations--i.e. using immutable data structures forces program designs that will be more robust and, in the long run, increase developer productivity.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/42004939', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3532729/']}
jdg_381744
stackexchange
llm_judgeable_groundtruth_similarity
200830
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: The Van Wijngaarden adaptation of the Euler transform is used to accelerate convergence of an alternating series. An efficient algorithm for this appears in Numerical Recipes . Unfortunately, that numerical recipe appears to be written in C language. Does someone have an equivalent encoding in Mathematica language, or alternatively can someone translate from Numerical Recipes ? Now provide the response and nothing else.
I believe there is a more concise way to express this in Mathematica. AltSum[f_Function, n_Integer /; n > 1] := With[ {row = Accumulate@Table[f[k], {k, 0, n}]}, Last@Nest[ListConvolve[{1/2, 1/2}, #] &, row, Floor[2/3 n]]] The only two parameters this function gets is a function f that returns the single terms of the alternating sum and the parameter n that says how many terms we want to use to approximate the sum. Referring to the wiki page of the Van Wijngaarden transformation , the two lines of code do the following: The row = ... part calculates the first row as given in the table on the wiki page. It uses a simple Table to calculate a list of each term and employs Accumulate to compute the list of partial sums {s0, s0+s1, s0+s1+s2, ...} In the second line, we use a convolution with the kernel {1/2, 1/2} to calculate the mean of neighboring elements. This call is done over and over again using Nest and per definition of Adriaan van Wijngaarden, is not to carried out through to the very end, but it stops two-thirds of the way ( Floor[2/3*n] ). The final call to Last gives then the highlighted number of the 9th row in the example of the wiki page. To use this function with the example from the wikipedia page, you can do AltSum[Function[k, (-1)^k/(2 k + 1)], 12] // N(* 0.785398 *) Note that if you use only exact numbers in your function, then Mathematica will compute the result exactly which leads to very large rational expressions. If you want to use approximate numbers from the start, then simply replace one of the numbers with either a machine precision real or with a number that has a specified accuracy. Here is the log(2) example given by Mats: AltSum[Function[k, (-1``100)^(k + 2)/(k + 1)], 100](* 0.693147180559945309417232121458176568075500134360314076823448273125712684836516 *)% - Log[2](* 5.8822702768263632319062866821*10^-50 *)
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/200830', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/42558/']}
jdg_381745
stackexchange
llm_judgeable_groundtruth_similarity
17973970
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 tried both the examples in Oracle's Java Tutorials . They both compile fine, but at run time, both come up with this error: Exception in thread "main" java.lang.NoClassDefFoundError: graphics/shapes/Square at Main.main(Main.java:7)Caused by: java.lang.ClassNotFoundException: graphics.shapes.Square at java.net.URLClassLoader$1.run(URLClassLoader.java:366) at java.net.URLClassLoader$1.run(URLClassLoader.java:355) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:354) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ... 1 more I think I might have the Main.java file in the wrong folder. Here is the directory hierarchy: graphics├ Main.java├ shapes| ├ Square.java| ├ Triangle.java├ linepoint| ├ Line.java| ├ Point.java├ spaceobjects| ├ Cube.java| ├ RectPrism.java And here is Main.java : import graphics.shapes.*;import graphics.linepoint.*import graphics.spaceobjects.*;public class Main { public static void main(String args[]) { Square s = new Square(2, 3, 15); Line l = new Line(1, 5, 2, 3); Cube c = new Cube(13, 32, 22); }} What am I doing wrong here? UPDATE After I put put the Main class into the graphics package (I added package graphics; to it), set the classpath to "_test" (folder containing graphics), compiled it, and ran it using java graphics.Main (from the command line), it worked. Really late UPDATE #2 I wasn't using Eclipse (just Notepad++ and the JDK), and the above update solved my problem. However, it seems that many of these answers are for Eclipse and IntelliJ IDEA , but they have similar concepts. Now provide the response and nothing else.
After you compile your code, you end up with .class files for each class in your program. These binary files are the bytecode that Java interprets to execute your program. The NoClassDefFoundError indicates that the classloader (in this case java.net.URLClassLoader ), which is responsible for dynamically loading classes, cannot find the .class file for the class that you're trying to use. Your code wouldn't compile if the required classes weren't present (unless classes are loaded with reflection), so usually this exception means that your classpath doesn't include the required classes. Remember that the classloader (specifically java.net.URLClassLoader ) will look for classes in package a.b.c in folder a/b/c/ in each entry in your classpath. NoClassDefFoundError can also indicate that you're missing a transitive dependency of a .jar file that you've compiled against and you're trying to use. For example, if you had a class com.example.Foo , after compiling you would have a class file Foo.class . Say for example your working directory is .../project/ . That class file must be placed in .../project/com/example , and you would set your classpath to .../project/ . Side note: I would recommend taking advantage of the amazing tooling that exists for Java and JVM languages. Modern IDEs like Eclipse and IntelliJ IDEA and build management tools like Maven or Gradle will help you not have to worry about classpaths (as much) and focus on the code! That said, this link explains how to set the classpath when you execute on the command line.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/17973970', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2397327/']}
jdg_381746
stackexchange
llm_judgeable_groundtruth_similarity
12050460
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 the following code, from the PyBrain tutorial: from pybrain.datasets import SupervisedDataSetfrom pybrain.supervised.trainers import BackpropTrainerfrom pybrain.tools.shortcuts import buildNetworkfrom pybrain.structure.modules import TanhLayerds = SupervisedDataSet(2, 1)ds.addSample((0,0), (0,))ds.addSample((0,1), (1,))ds.addSample((1,0), (1,))ds.addSample((1,1), (0,))net = buildNetwork(2, 3, 1, bias=True, hiddenclass=TanhLayer)trainer = BackpropTrainer(net, ds)for inp, tar in ds: print [net.activate(inp), tar]errors = trainer.trainUntilConvergence()for inp, tar in ds: print [net.activate(inp), tar] However the result is a neural network that is not trained well. When looking at the error output the network gets trained properly however it uses the 'continueEpochs' argument to train some more and the network is performing worse again. So the network is converging, but there is no way to get the best trained network. The documentation of PyBrain implies that the network is returned which is trained best, however it returns a Tuple of errors. Whens etting continueEpochs to 0 I get an error (ValueError: max() arg is an empty sequence) so continueEpochs must be larger than 0. Is PyBrain actually maintained because it seems there is a big difference in documentation and code. Now provide the response and nothing else.
After some more digging I found that the example on the PyBrain's tutorial is completely out of place. When we look at the method signature in the source code we find: def trainUntilConvergence(self, dataset=None, maxEpochs=None, verbose=None, continueEpochs=10, validationProportion=0.25): This means that 25% of the training set is used for validation. Although that is a very valid method when training a network on data you are not going to do this when you have the complete range of possiblities at your disposal, namely a 4-row XOR 2-in-1-out solution set. When one wants to train an XOR set and you remove one of the rows for validation that has as an immediate consequence that you get a very sparse training set where one of the possible combinations is omitted resulting automatically into those weights not being trained. Normally when you omit 25% of the data for validation you do this by assuming that those 25% cover 'most' of the solution space the network already has encountered more or less. In this case this is not true and it covers 25% of the solution space completely unknown to the network since you removed it for validation. So, the trainer was training the network correctly, but by omitting 25% of the XOR problem this results in a badly trained network. A different example on the PyBrain website as a quickstart would be very handy, because this example is just plain wrong in this specific XOR case. You might wonder if they tried the example themselves, because it just outputs random badly trained networks.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12050460', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/646996/']}
jdg_381747
stackexchange
llm_judgeable_groundtruth_similarity
208770
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm working on reviving a C++ codebase that hasn't been touched since '97. It's academic software for text analysis, and originally it was non-functional, it wouldn't even compile. I fixed the code so that it works, and added some new functionality of my own. I'm doing this privately for someone else, and they will pay me over a student contract. I signed nothing with them, so ultimately, my work belongs to me. Given that they agree (I don't want to be rude), would I be able to relicense this code under GPL, and post it on a site like GitHub? The current license is as follows: Copyright (C) 1997, Carnegie Mellon University. All rights reserved. This software is made available for research purposes only. It may be redistributed freely for this purpose, in full or in part, provided that this entire copyright notice is included on any copies of this software and applications and derivations thereof. This software is provided on an "as is" basis, without warranty of any kind, either expressed or implied, as to any matter including, but not limited to warranty of fitness of purpose, or merchantability, or results obtained from use of this software. Seems like I would have to include that notice as well. Now provide the response and nothing else.
IANAL! The License of the code is incompatible with the provisions of the GPL, so you cannot put the GPL on it. Or rather you can put the GPL on your code but users would still be bound by the stricter provisions of the original License, making the legal situation a real mess. The only option if you want to relicense the code is to get permission from the original authors of the code (in writing).
{}
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/208770', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/54627/']}
jdg_381748
stackexchange
llm_judgeable_groundtruth_similarity
89804
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: What is forward scattering? If it is equivalent to no scattering, then why not call it "no scattering"? Now provide the response and nothing else.
Forward scattering need not be equivalent to "no scattering" - and, indeed, will only rarely be indistinguishable from it. In the usual scattering-theory setup, you have an electron coming in in a plane wave $$\psi(\mathbf{r})=e^{i\mathbf{k}\cdot\mathbf{r}}=e^{ikz}$$and impinging on some short-range potential. This will add to the wavefunction a scattered wave$$\psi_\text{scattered}(\mathbf{r})=F(\theta,\phi)\frac 1r e^{ikr}.$$The form factor $F(\theta,\phi)$ governs the angular structure of the scattered wave, and the case where $\theta=0$ is called forward scattering. Note that: The forward-scattered wave is part of a spherical wave and its amplitude decays with the distance from the scattering centre in a different way to the incoming wave. In practice, the incoming beam will also suffer from wavepacket spreading, but in general the forward-scattered wave will be weaker unless special scattering conditions are at play. The form factor in general includes a phase. This means that the forward-scattered wave will interfere nontrivially with the incoming beam, providing a delay in the phase of the final wave.
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/89804', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/31965/']}
jdg_381749
stackexchange
llm_judgeable_groundtruth_similarity
8778863
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: First of all there is a question with the same title here on SO but its not what I'm looking for and it doesn't have a complete answer either. So here's my question. Say I have this URL which directs to an image. https://fbcdn-photos-a.akamaihd.net/hphotos-ak-ash4/299595_10150290138650735_543370734_8021370_355110168_n.jpg Once I put this parameter ?dl=1 to the end of the URL, it becomes downloadable. https://fbcdn-photos-a.akamaihd.net/hphotos-ak-ash4/299595_10150290138650735_543370734_8021370_355110168_n.jpg?dl=1 I'm trying to do this task through a userscript. So I used XMLHttpRequest for that. var url = "https://fbcdn-photos-a.akamaihd.net/hphotos-ak-ash4/299595_10150290138650735_543370734_8021370_355110168_n.jpg?dl=1";var request = new XMLHttpRequest(); request.open("GET", url, false); request.send(null); if (request.status === 200) { alert(request.statusText);} Here is a fiddle . But it does not work. Now provide the response and nothing else.
XMLHttpRequest will not work cross-domain, but since this is a userscript Chrome now supports GM_xmlhttpRequest() in userscripts only. Something like this should work, note that it is asynchronous: GM_xmlhttpRequest ( { method: 'GET', url: 'https://fbcdn-photos-a.akamaihd.net/hphotos-ak-ash4/299595_10150290138650735_543370734_8021370_355110168_n.jpg?dl=1', onload: function (responseDetails) { alert(responseDetails.statusText); }} ); As for getting and using the actual image data , that is a major pain to work out. You can use the new .responseType = "blob"; functionality in Firefox but Chrome does not yet support it . In Chrome or Firefox, for the same domain only , you can use the new XHR2 like so: See it in action at jsBin. BlobBuilder = window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder;var url = "http://jsbin.com/images/gear.png";var request = new XMLHttpRequest();request.open ("GET", url, false);request.responseType = "arraybuffer";request.send (null);if (request.status === 200) { var bb = new BlobBuilder (); bb.append (request.response); // Note: not request.responseText var blob = bb.getBlob ('image/png'); var reader = new FileReader (); reader.onload = function (zFR_Event) { $("body").prepend ('<p>New image: <img src="' + zFR_Event.target.result + '"></p>') }; reader.readAsDataURL (blob);} Unfortunately, GM_xmlhttpRequest() does not (yet) support setting responseType . So, for GM script or userscript applications, we have to use a custom base64 encoding scheme like in "Javascript Hacks: Using XHR to load binary data" . The script code becomes something like: var imgUrl = "http://jsbin.com/images/gear.png";GM_xmlhttpRequest ( { method: 'GET', url: imgUrl, onload: function (respDetails) { var binResp = customBase64Encode (respDetails.responseText); /*-- Here, we just demo that we have a valid base64 encoding by inserting the image into the page. We could just as easily AJAX-off the data instead. */ var zImgPara = document.createElement ('p'); var zTargetNode = document.querySelector ("body *"); //1st child zImgPara.innerHTML = 'Image: <img src="data:image/png;base64,' + binResp + '">'; zTargetNode.parentNode.insertBefore (zImgPara, zTargetNode); }, overrideMimeType: 'text/plain; charset=x-user-defined'} );function customBase64Encode (inputStr) { var bbLen = 3, enCharLen = 4, inpLen = inputStr.length, inx = 0, jnx, keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "0123456789+/=", output = "", paddingBytes = 0; var bytebuffer = new Array (bbLen), encodedCharIndexes = new Array (enCharLen); while (inx < inpLen) { for (jnx = 0; jnx < bbLen; ++jnx) { /*--- Throw away high-order byte, as documented at: https://developer.mozilla.org/En/Using_XMLHttpRequest#Handling_binary_data */ if (inx < inpLen) bytebuffer[jnx] = inputStr.charCodeAt (inx++) & 0xff; else bytebuffer[jnx] = 0; } /*--- Get each encoded character, 6 bits at a time. index 0: first 6 bits index 1: second 6 bits (2 least significant bits from inputStr byte 1 + 4 most significant bits from byte 2) index 2: third 6 bits (4 least significant bits from inputStr byte 2 + 2 most significant bits from byte 3) index 3: forth 6 bits (6 least significant bits from inputStr byte 3) */ encodedCharIndexes[0] = bytebuffer[0] >> 2; encodedCharIndexes[1] = ( (bytebuffer[0] & 0x3) << 4) | (bytebuffer[1] >> 4); encodedCharIndexes[2] = ( (bytebuffer[1] & 0x0f) << 2) | (bytebuffer[2] >> 6); encodedCharIndexes[3] = bytebuffer[2] & 0x3f; //--- Determine whether padding happened, and adjust accordingly. paddingBytes = inx - (inpLen - 1); switch (paddingBytes) { case 1: // Set last character to padding char encodedCharIndexes[3] = 64; break; case 2: // Set last 2 characters to padding char encodedCharIndexes[3] = 64; encodedCharIndexes[2] = 64; break; default: break; // No padding - proceed } /*--- Now grab each appropriate character out of our keystring, based on our index array and append it to the output string. */ for (jnx = 0; jnx < enCharLen; ++jnx) output += keyStr.charAt ( encodedCharIndexes[jnx] ); } return output;}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8778863', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1077789/']}
jdg_381750
stackexchange
llm_judgeable_groundtruth_similarity
13793399
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 the following code, using pscyopg2: sql = 'select %s from %s where utctime > %s and utctime < %s order by utctime asc;'data = (dataItems, voyage, dateRangeLower, dateRangeUpper)rows = cur.mogrify(sql, data) This outputs: select 'waterTemp, airTemp, utctime' from 'ss2012_t02' where utctime > '2012-05-03T17:01:35+00:00'::timestamptz and utctime < '2012-05-01T17:01:35+00:00'::timestamptz order by utctime asc; When I execute this, it falls over - this is understandable, as the quotes around the table name are illegal. Is there a way to legally pass the table name as a parameter, or do I need to do a (explicitly warned against) string concatenation, ie: voyage = 'ss2012_t02'sql = 'select %s from ' + voyage + ' where utctime > %s and utctime < %s order by utctime asc;' Cheers for any insights. Now provide the response and nothing else.
According to the official documentation: If you need to generate dynamically an SQL query ( for instancechoosing dynamically a table name ) you can use the facilitiesprovided by the psycopg2.sql module. The sql module is new in psycopg2 version 2.7. It has the following syntax: from psycopg2 import sqlcur.execute( sql.SQL("insert into {table} values (%s, %s)") .format(table=sql.Identifier('my_table')), [10, 20]) More on: https://www.psycopg.org/docs/sql.html#module-usage [Update 2017-03-24: AsIs should NOT be used to represent table or fields names, the new sql module should be used instead: https://stackoverflow.com/a/42980069/5285608 ] Also, according to psycopg2 documentation: Warning : Never, never , NEVER use Python string concatenation ( + ) or string parameters interpolation ( % ) to pass variables to a SQL query string. Not even at gunpoint.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/13793399', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/768778/']}
jdg_381751
stackexchange
llm_judgeable_groundtruth_similarity
19155
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'm implementing, as a hobby, a simple data logger. I previously asked a question about running a ~10m cable to the MCU for a Dallas/Maxim 1Wire sensor (and therefore 3 wires, since I'm not going to be using parasitic power), and now I'm considering connector and cable. I'd like to, if possible, use something that is easy and cheap to find and use. In that vein, I've come up with a couple possibilities: 3.5mm stereo audio jack and stereo audio cable 6P4C modular jack (RJ11) and telephone wire Both these ideas use widely-available connectors and cheap multiconductor cable. I'm wondering if one or both of these is grossly unsuitable for some reason, or whether they would work for my purposes. Perhaps there is something much more suitable that I haven't considered? Now provide the response and nothing else.
Both choices seem acceptable. I'd tend towards the RJ11 solution and use 6P6C for flexibility unless you were absolutely certain no extra facilities would be needed subsequently. Both systems run the risk of other equipment being plugged in by careless users in an uncontrolled environment. Cannon a.k.a. XLR connector (see below) is a superb solution if you need the robustness. Stereo audio cable has the advantage of shielded balanced pairs being available if desired. While I'd expect a 10 metre cable length to be no problem in a benign environment, the shielding is a bonus in severe environments. Balanced pair is less of an issue as you will be using an unbalanced against ground data circuit. Reasonable cost. Cables are available that stand up well to use as a flexible lead. 4 pole versions are available. Connectors tend to short momentarily on insertion and removal - not usually an issue but worth noting. Some risk of connector damage from ham fisted users. "RJ11" 6P4C or 6P6C cable and connectors has the advantages of low cost, good availability, balanced pairs, additional pair for "something else that turned out to be handy" if 6P6C is used. (Even 6P4C gives an extra wire (unbalanced against ground) for "other use". Cable is designed for use as a flexible cord within reason so is damage resistant. Current carrying capability is reasonable (not a major issue here). Shielding not usually provided. Locking tab connectors. Cheap versions prone to lock tab damage but otherwise resistant to user abuse. Versions can be had which allow pullout without damage - cheaper versions tend to break locking tabs off if abused. Not so good for inline connections usually (but parts are available if this is required). Other: Nothing stands out except perhaps Cannon microphone connectors. "Cannon" a.k.a. XLR*: Possibly the most professional solution at a reasonable price if robustness matters. 3 pin and ground and higher pin count versions. Larger connectors than RJ11 or 3.5mm. Connectors available from cheap plastic with modest robustness to reasonably priced near bulletproof full-metal-jacket versions. Latchable. Can use variations on shielded or unshielded cable Many versions 6.5mm microphone connectors . Very available. Good prices. Larger connectors. Various number of poles. More user damage resistant than 3.5mm. (The photo below actually shows adaptors but the plug barrels are the same.) Video cable with DB15 connectors . Thicker, more expensive. Available premade in various lengths to beyond 10m. Some shielded pairs or whole cable may be shielded. Quality connector. Larger connectors. Not usually good for inline connection. Mini-DIN and similar: Small. Dearer. Damage prone. More connections but no real advantage. Std DIN . Larger. Less damage prone. More connections but no real advantage. Cannon / XLR: "The XLR connector was invented by James H. Cannon, founder of Cannon Electric in Los Angeles, California (now part of ITT Corporation), and for this reason it is sometimes colloquially known as a cannon plug or cannon connector. Originally manufactured as the Cannon X series, subsequent versions added a latch (Cannon XL) and then surrounded the female contacts with a resilient polychloroprene, which resulted in the part number prefix XLR Source - Wikipedia.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/19155', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/3240/']}
jdg_381752
stackexchange
llm_judgeable_groundtruth_similarity
2935759
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Facelets relies on XML namespaces to work with XHTML. How are HTML 4, and as far as I know, HTML 5 do not support namespaces. Also HTML 5 has some new elements that are not available in XHTML. Even HTML 4 and XHTML have some differences regarding elements and attributes they support. The question is: Is it possible to render HTML 4/5 documents using Facelets? If so, how? Now provide the response and nothing else.
Since Facelets is a XML based view technology which eats and emits in essence XML markup, you cannot use it with a HTML4 doctype. The HTML4 doctype describes several elements which cannot be self-closing, like <link> , <meta> , <br> and <hr> . However, with XML you're forced to close them like <link/> , <meta/> , etc. So using a HTML4 doctype is absolutely not an option for Facelets (that is, when you respect the standards and/or fear the w3 validator, it will however work perfectly on the most if not all webbrowsers). HTML5, on the other hand, allows XML markup. This is specified in chapter 3.2.2 - Elements : Example: <link type="text/css" href="style.css"/> Authors may optionally choose to use this same syntax for void elements in the HTML syntax as well. Some authors also choose to include whitespace before the slash, however this is not necessary. (Using whitespace in that fashion is a convention inherited from the compatibility guidelines in XHTML 1.0, Appendix C.) I myself use <!DOCTYPE html> all the way, also with JSF/Facelets, even without a <?xml?> declaration in top of the page. It works perfectly in all browsers. With a XHTML doctype you should as per the specification be using a Content-Type of application/xhtml+xml which would only make MSIE to choke (it doesn't understand it). And since that's still one of the most widely used browsers... Replacing the XHTML content type by text/html is considered harmful , you also don't want to do this. As per your arguments: HTML 5 do not support namespaces. This doesn't matter. The namespaces are only of interest for the XML based server side view technology (like as Facelets) which in turn can generate pure HTML with those tags. The following example is legitimately valid for Facelets: <!DOCTYPE html><html lang="en" xmlns:f="http://xmlns.jcp.org/jsf/core" xmlns:h="http://xmlns.jcp.org/jsf/html"> <h:head> <title>Title</title> </h:head> <h:body> <h:outputText value="#{bean.text}" /> </h:body></html> This renders legitimately valid HTML5 (for the client side): <!DOCTYPE html><html lang="en"> <head> <title>Title</title> </head> <body> Some text </body></html> You see, Facelets already removes the XHTML declarations since they have no meaning in the client side. And, Also HTML 5 has some new elements that are not available in XHTML this make also no sense. It's all about the generated output. Which can be HTML5 as good. Your only problem may be the browser support and the availability of 3rd party JSF components which renders HTML5 specific elements. Since JSF 2.2, it's possible to use the new passthrough elements feature to turn custom elements into a JSF component. Simply give the HTML5 element a jsf:id attribute. It'll transparently internally be interpreted as a UIPanel instance in the JSF component tree (like <h:panelGroup> ). <!DOCTYPE html><html lang="en" xmlns:jsf="http://xmlns.jcp.org/jsf" xmlns:f="http://xmlns.jcp.org/jsf/core" xmlns:h="http://xmlns.jcp.org/jsf/html"> <h:head> <title>Title</title> </h:head> <h:body> <header jsf:id="header">Header</header> <nav jsf:id="nav">Nav</nav> <main jsf:id="main">Main</main> <footer jsf:id="footer">Footer</footer> </h:body></html> You can even reference it from ajax as in <f:ajax render="main"> . Actually, XHTML is overhyped. Its sole intent is to ease HTML development using XML based tools which can manipulate/transform/generate HTML pages on the server side (like as Facelets). But some starters also use it without using any XML tool and output it plain as-is, because it's "so cool" -for some unclear reason. Don't get me wrong. XHTML is great as server side view technology. But simply not as client side markup technology. It has utterly no value at the client side. See also: Our XHTML wiki page How should a <!DOCTYPE> section look in JSF? HTML5 or XHTML? JavaServer Faces 2.2 and HTML5 support, why is XHTML still being used
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/2935759', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/309683/']}
jdg_381753
stackexchange
llm_judgeable_groundtruth_similarity
41244981
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This is my dataframe (where the values in the authors column are comma separated strings): authors bookJim, Charles The Greatest Book in the WorldJim An OK bookCharlotte A book about booksCharlotte, Jim The last book How do I transform it to a long format, like this: authors bookJim The Greatest Book in the WorldJim An OK bookJim The last bookCharles The Greatest Book in the WorldCharlotte A book about booksCharlotte The last book I've tried extracting the individual authors to a list, authors = list(df['authors'].str.split(',')) , flatten that list, matched every author to every book, and construct a new list of dicts with every match. But that doesn't seem very pythonic to me, and I'm guessing pandas has a cleaner way to do this. Now provide the response and nothing else.
You can split the authors column by column after setting the index to the book which will get you almost all the way there. Rename and sort columns to finish. df.set_index('book').authors.str.split(',', expand=True).stack().reset_index('book') book 00 The Greatest Book in the World Jim1 The Greatest Book in the World Charles0 An OK book Jim0 A book about books Charlotte0 The last book Charlotte1 The last book Jim And to get you all the way home df.set_index('book')\ .authors.str.split(',', expand=True)\ .stack()\ .reset_index('book')\ .rename(columns={0:'authors'})\ .sort_values('authors')[['authors', 'book']]\ .reset_index(drop=True)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41244981', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2908879/']}
jdg_381754
stackexchange
llm_judgeable_groundtruth_similarity
2880520
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 developing a web app for the iPad, to run in Safari. I don't yet have an iPad to test on. Does anyone know the usable screen size - after any space for the safari/ipad controls is takes up? Now provide the response and nothing else.
You should just follow TN2262 and write dimension-invariant code. In case you need a logical pixel size, document.body.client[Width|Height] is always 980×1208. In terms of absolute pixels you can use, the navigation bar of Mobile Safari takes up roughly 78px, so in portrait orientation it is 768×946, and in landscape it is 1024×690. There can be a keyboard (308px in height in portrait, 397px in landscape) as well. Update: The above absolute numbers are correct only for iOS 4.x or before. In iOS 5.x Apple introduced the tab bar which increases the height of navigation bar + status bar to 96px. Actually, even before iOS 5.x, the presence of the bookmark bar can affect the viewport as well.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2880520', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/77775/']}
jdg_381755
stackexchange
llm_judgeable_groundtruth_similarity
5061299
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: My project (in Ruby on Rails 3) is to develop a "social network" site with the following features: Users can be friends. It's mutual friendships; not asymetric like Twitter. Users can publish links, to share them. Friends of a user can see what this user has shared. Friends can comment on those shared links. So basically we have Users, Links, and Comments, and all that is connected. An interesting thing in social networks is that the User table has kind of a many-to-many relation with itself. I think I can handle that level of complexity with SQL and RoR. My question is: would it be a good idea to use MongoDB (or CouchDB) for such a site? To be honest, I think the answer is no. MongoDB doesn't seem to fit really well with many-to-many relationships. I can't think of a good MongoDB way to implement the friendship relationships. And I've read that Diaspora started with MongoDB but then switched back to classic SQL. But some articles on the web defend MongoDB for social networks, and above all I want to make a well-informed decision, and not miss a really cool aspect of MongoDB that would change my life. Also, I've heard about graph DB, which are probably great, but they really seem too young to me, and I don't know how they'd fit with RoR (and not mentioning heroku). So, am I missing something? Now provide the response and nothing else.
I like MongoDB and use it a lot, but I am of the opinion that if you are dealing with relational data, you should use the right tool for it. We have relational databases for that. Mongo and Couch are document stores. Mongo has a serious disadvantage if you are going to be maintaining a lot of inter-document links. Writes are only guaranteed to be atomic for one document. So you could have inconsistent updates for relations if you are not careful with your schema. The good thing about MongoDB is that it is very good at scaling. You can shard and create replica sets. Foursquare currently uses MongoDB and it has been working pretty well for them. MongoDB also does map-reduce and has decent geospatial integration. The team that develops MongoDB is excellent, and I live in NY where they are based and have met them. You probably are not going to have scaling issues though I would think starting out. As far as Diaspora switching... I would not want to follow anything they are doing :) Your comment about graph dbs is interesting though. I would probably not use a graph DB as my primary DB either, but when dealing with relationships, you can do amazing things with them. In fact usually the demo the guys from graph DB companies will give you is extracting relationship knowledge from a social network. However, there is nothing preventing you from playing with these in the future for network analysis. In conclusion, when you are starting out here, you are not running into the problems of massive scale yet, and are probably limited on time and money. Keep in mind that even Facebook does not use just one technology, they have basically expanded to NoSQL for certain functionality (like Facebook messaging). There is nothing stopping you in the future from using say Mongo and gridFS for handling image uploads or geo-location etc. It is good to grow as your needs change. I think your gut feeling that you have an SQL app here is right, and the benefits gained with MongoDB would not be realized for a while.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5061299', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/486930/']}
jdg_381756
stackexchange
llm_judgeable_groundtruth_similarity
68623965
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: By playing with a ModalBottomSheet in Compose, I get the following issue: java.lang.IllegalArgumentException: The initial value must have an associated anchor. My composable function has: a ModalBottomSheetState and a CoroutinScope, a ModalBottomSheetLayout with, a Scaffold as bottom sheet content. // 1.val sheetState = rememberModalBottomSheetState(ModalBottomSheetValue.Hidden)val coroutineScope = rememberCoroutineScope()// 2. ModalBottomSheetLayout( sheetContent = { /* sheetContent */ }, sheetState = sheetState, // modifier = Modifier.fillMaxSize() --> it doesn't change the result) { // 3. Scaffold { /* scaffold content */ }} By setting the initial state of the bottom sheet to ModalBottomSheetValue.Expanded, the issue disappears. Note the exception is also thrown for ModalBottomSheetValue.HalfExpanded and without any initial value (the default is Hidden, so it seems logic). Is there a known workaround or a version of the library where it is working (version of compose I use: 1.0.0 and I tried with 1.0.0-rc2) ? UPDATE After some investigation, it seems that the issue is due to a dynamic content in the sheet content. I have there a Column/LazyColumn that recomposes when data are available. By having a fixed content, the issue disappear for any ModalBottomSheetValue. FIX With "null" content (understand a content with a height of 0 dp), the composable function has probably not enough information to compose the modal bottom sheet. It is the case with dynamic column content (starting with no content, so height = 0 dp). To fix this, set a minimal height of 1 dp somewhere in the sheet content hierarchy: val sheetState = rememberModalBottomSheetState(ModalBottomSheetValue.Hidden)val coroutineScope = rememberCoroutineScope()ModalBottomSheetLayout( sheetContent = { Box(modifier.defaultMinSize(minHeight = 1.dp)) { /* sheet content */ } }, sheetState = sheetState, // modifier = Modifier.fillMaxSize() --> it doesn't change the result) { Scaffold { /* scaffold content */ }} Now provide the response and nothing else.
With "null" content (understand a content with a height of 0 dp), the composable function has probably not enough information to compose the modal bottom sheet. It is the case with dynamic column content (starting with no content, so height = 0 dp). To fix this, set a minimal height of 1 dp somewhere in the sheet content hierarchy: val sheetState = rememberModalBottomSheetState(ModalBottomSheetValue.Hidden)val coroutineScope = rememberCoroutineScope()ModalBottomSheetLayout( sheetContent = { Box(modifier.defaultMinSize(minHeight = 1.dp)) { /* sheet content */ } }, sheetState = sheetState, // modifier = Modifier.fillMaxSize() --> it doesn't change the result) { Scaffold { /* scaffold content */ }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/68623965', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15182499/']}
jdg_381757
stackexchange
llm_judgeable_groundtruth_similarity
21861366
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 know that the System.Text.StringBuilder in .NET has an AppendLine() method, however, I need to pre-append a line to the beginning of a StringBuilder . I know that you can use Insert() to append a string, but I can't seem to do that with a line, is there a next line character I can use? I am using VB.NET, so answers in that are preferable, but answers in C# are ok as well. Now provide the response and nothing else.
is there a next line character I can use? You can use Environment.NewLine Gets the newline string defined for this environment. For example: StringBuilder sb = new StringBuilder();sb.AppendLine("bla bla bla..");sb.Insert(0, Environment.NewLine); Or even better you can write a simple extension method for that: public static class MyExtensions{ public static StringBuilder Prepend(this StringBuilder sb, string content) { return sb.Insert(0, content); }} Then you can use it like this: StringBuilder sb = new StringBuilder();sb.AppendLine("bla bla bla..");sb.Prepend(Environment.NewLine);
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/21861366', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1066445/']}
jdg_381758
stackexchange
llm_judgeable_groundtruth_similarity
8257
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: How many even positive integers are there that are divisors of 720 ? I know how to compute the number of divisors but how to compute the number of even or odd positive divisors of a number ? If we list the divisors of 720 (using mathematica) : {1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24, 30, 36, 40, 45,48, 60, 72, 80, 90, 120, 144, 180, 240, 360, 720} among these only 24 are even,I am looking for some tricks that can be used in solving similar kinds of problems during exam (under a minute solution). Now provide the response and nothing else.
An even number $2m$ is a factor of $720$ iff $m$ is a factor of $360$.So it's the same problem as counting divisors of $360$. Forthat it helps to consider the prime factorization of $360$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/8257', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/2109/']}
jdg_381759
stackexchange
llm_judgeable_groundtruth_similarity
17871338
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 keep getting these errors when compiling. I modified the code that runs on an arduino to run on my raspberry pi. test1.c: In function ‘loop’:test1.c:24:3: warning: implicit declaration of function ‘rotateDeg’ [-Wimplicit-function-declaration]test1.c:33:3: warning: implicit declaration of function ‘rotate’ [-Wimplicit-function-declaration]test1.c: At top level:test1.c:42:6: warning: conflicting types for ‘rotate’ [enabled by default]test1.c:33:3: note: previous implicit declaration of ‘rotate’ was heretest1.c: In function ‘rotate’:test1.c:46:3: warning: implicit declaration of function ‘abs’ [-Wimplicit-function-declaration]test1.c: At top level:test1.c:61:6: warning: conflicting types for ‘rotateDeg’ [enabled by default]test1.c:24:3: note: previous implicit declaration of ‘rotateDeg’ was here/usr/lib/gcc/arm-linux-gnueabihf/4.6/../../../arm-linux-gnueabihf/crt1.o: In function `_start':(.text+0x34): undefined reference to `main'collect2: ld returned 1 exit status Here is my source code: #include <wiringPi.h>#include <stdio.h>#include <stdio.h>#define DIR_PIN 0#define STEP_PIN 3void setup() { pinMode(DIR_PIN, OUTPUT); pinMode(STEP_PIN, OUTPUT); } void loop(){ rotateDeg(360, 1); delay(1000); rotateDeg(-360, .1); //reverse delay(1000); rotate(1600, .5); delay(1000); rotate(-1600, .25); //reverse delay(1000); }void rotate(int steps, float speed){ //rotate a specific number of microsteps (8 microsteps per step) - (negitive for reverse movement) //speed is any number from .01 -> 1 with 1 being fastest - Slower is stronger int dir = (steps > 0)? HIGH:LOW; steps = abs(steps); digitalWrite(DIR_PIN,dir); float usDelay = (1/speed) * 70; for(int i=0; i < steps; i++){ digitalWrite(STEP_PIN, HIGH); delayMicroseconds(usDelay); digitalWrite(STEP_PIN, LOW); delayMicroseconds(usDelay); } } void rotateDeg(float deg, float speed){ //rotate a specific number of degrees (negitive for reverse movement) //speed is any number from .01 -> 1 with 1 being fastest - Slower is stronger int dir = (deg > 0)? HIGH:LOW; digitalWrite(DIR_PIN,dir); int steps = abs(deg)*(1/0.225); float usDelay = (1/speed) * 70; for(int i=0; i < steps; i++){ digitalWrite(STEP_PIN, HIGH); delayMicroseconds(usDelay); digitalWrite(STEP_PIN, LOW); delayMicroseconds(usDelay); } } Now provide the response and nothing else.
You get an implicit declaration warning when there is an implicitly declared function. An implicitly declared function is a function which has neither a prototype nor a definition and that's why a compiler cannot verify that what do you want to do with the function. If no prior declaration of a function is available then its first instance is assumed to be a declaration implicitly with return type int and nothing is assumed about the parameters. Just leave a declaration of functions rotate and rotatedeg like this : void rotate (int , float ); and void rotateDeg (float , float ); Before using it in loop : void loop(){ rotateDeg(360, 1); .... .... rotate(1600, .5); ... rotate(-1600, .25); //reverse delay(1000); } Also use #include<math.h> before using any mathematical functions like abs(); . The bottom line is , you have to make your compiler know about the functions you are using.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17871338', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1748918/']}
jdg_381760
stackexchange
llm_judgeable_groundtruth_similarity
3335385
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 am kind of lost when I try to understand the definition of the free abelian group on a set $X$ I read the question here What is the definition of a free abelian group According to this question, the free abelian group of $\{A,B,C,D\}$ is $\mathbb{Z}^4$ . However, I think that they have to be linearly independent to make that group isomorphic to $\mathbb{Z}^4$ . For example, what if there is an implicit relation $2A+B=0$ . Then obviously it is not $\mathbb{Z}^4$ , since $(2,1,0,0)$ and $(4,2,0,0)$ are the same thing. What is wrong with my argument? I also read Serge Lang's algebra book. It seems that if we say a free abelian group on $X$ , then we assume $X$ form a basis. All elements of $X$ are linearly independent. I am confused. For example, if we take the free abelian group on $\{1,2,3\}$ , is it still $\mathbb{Z}^{3}$ (instead of $\mathbb{Z}$ )? $2\times1+(-1)\times2+1\times3=4\times1+(-2)\times2+1\times3$ , but still $(2,-1,1)$ and $(4,-2,1)$ are diffrent? Now provide the response and nothing else.
One way to think about the free abelian group on a set $X$ is that you are taking the elements of $X$ as a starting point, and then making a group operation on those elements that is abelian, but where the elements don't satisfy any relations other than the ones that they absolutely have to to make an abelian group. In particular, the elements of $X$ are viewed here as something like "atoms", and we're building a totally new group operation on them. It doesn't matter at all what they are, just how many of them there are. In your second example the fact that we built a group from the numbers $1, 2, 3$ doesn't mean that the group operation we're building has anything to do with the usual arithmetic on those numbers. It might help to give the new group operation a new name, say $\ast$ . Then elements of the free abelian group on $\{1, 2, 3\}$ will have the form $(a1)\ast(b2)\ast(c3)$ , with $a, b, c \in \mathbb{Z}$ , and with no further simplification possible. The group we get this way is isomorphic to $\mathbb{Z}^3$ , via the function that sends $(a1)\ast(b2)\ast(c3)$ to $(a, b, c)$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3335385', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/553563/']}
jdg_381761
stackexchange
llm_judgeable_groundtruth_similarity
51003027
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 been following a tutorial that shows how to make a word2vec model. This tutorial uses this piece of code: similarity = merge([target, context], mode='cos', dot_axes=0) (no other info was given, but I suppose this comes from keras.layers ) Now, I've researched a bit on the merge method but I couldn't find much about it.From what I understand, it has been replaced by a lot of functions like layers.Add(), layers.Concat()... . What should I use? There's .Dot() , which has an axis parameter (which seems to be correct) but no mode parameter. What can I use in this case? Now provide the response and nothing else.
There are a few things that are unclear from the Keras documentation that I think are crucial to understanding: For each function in the keras documentation for Merge , there is a lower case and upper case one defined i.e. add() and Add() . On Github, farizrahman4u outlines the differences: Merge is a layer.Merge takes layers as inputMerge is usually used with Sequential modelsmerge is a function.merge takes tensors as input.merge is a wrapper around Merge.merge is used in Functional APIUsing Merge:left = Sequential()left.add(...)left.add(...)right = Sequential()right.add(...)right.add(...)model = Sequential()model.add(Merge([left, right]))model.add(...)using merge:a = Input((10,))b = Dense(10)(a)c = Dense(10)(a)d = merge([b, c])model = Model(a, d) To answer your question, since Merge has been deprecated, we have to define and build a layer ourselves for the cosine similarity . In general this will involve using those lowercase functions, which we wrap within a Lambda to create a layer that we can use within a model. I found a solution here: from keras import backend as Kdef cosine_distance(vests): x, y = vests x = K.l2_normalize(x, axis=-1) y = K.l2_normalize(y, axis=-1) return -K.mean(x * y, axis=-1, keepdims=True)def cos_dist_output_shape(shapes): shape1, shape2 = shapes return (shape1[0],1)distance = Lambda(cosine_distance, output_shape=cos_dist_output_shape)([processed_a, processed_b]) Depending on your data, you may want to remove the L2 normalization. What is important to note about the solution is that it is built using the Keras function api e.g. K.mean() - I think this is necessary when defining custom layer or even loss functions. Hope I was clear, this was my first SO answer!
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/51003027', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5500312/']}
jdg_381762
stackexchange
llm_judgeable_groundtruth_similarity
9345
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 interested in the way Linux mmaps files into the main memory (in my context its for executing, but I guess the mmap process is the same for writing and reading as well) and which size it uses. So I know Linux uses paging with usually 4kB pagesize (where in the kernel can I find this size?). But what exactly does this mean for the memory allocated: Assume you have a binary of size of a few thousned bytes, lets just say 5812B and you execute it.What happens in the kernel: Does it allocate 2*4kB and then copy the 5812B into this space, wasting >3KB of main memory in the 2nd page? It would be great if anyone knew the file in the kernel source where the pagesize is defined. My 2nd question is also very simple I guess: I assumed 5812B as a filesize. Is it right, that this size is simply taken from the inode? Now provide the response and nothing else.
There is no direct relationship between the size of the executable and the size in memory. Here's a very quick overview of what happens when a binary is executed: The kernel parses the file and breaks it into section. Some sections are directly loaded into memory, in separate pages. Some sections aren't loaded at all (e.g. debugging symbols). If the executable is dynamically linked, the kernel calls the dynamic loader, and it loads the required shared libraries and performs link edition as required. The program starts executing its code, and usually it will request more memory to store data. For more information about executable formats, linking, and executable loading, you can read Linkers and Loaders by John R. Levine . In a 5kB executable, it's likely that everything is code or data that needs to be loaded into memory except for the header. The executable code will be at least one page, perhaps two, and then there will be at least one page for the stack, probably one page or for the heap (other data), plus memory used by shared libraries. Under Linux, you can inspect the memory mappings for an executable with cat /proc/$pid/maps . The format is documented in the proc(5) man page; see also Understanding Linux /proc/id/maps .
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/9345', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/-1/']}
jdg_381763
stackexchange
llm_judgeable_groundtruth_similarity
53015242
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 been running containers on ECS, and using AWS Cloudwatch events to notify me when my tasks complete. All of the infrastructure has been created using Terraform. However, I'm unable to get the correct syntax in my event pattern so that I am only notified for non-zero exit codes. The following resource works great, and sends notifications to SNS every time one of my containers exits: resource "aws_cloudwatch_event_rule" "container-stopped-rule" { name = "container-stopped" description = "Notification for containers that exit for any reason. (error)." event_pattern = <<PATTERN{ "source": [ "aws.ecs" ], "detail-type": [ "ECS Task State Change" ], "detail": { "lastStatus": [ "STOPPED" ],"stoppedReason" : [ "Essential container in task exited" ]}}PATTERN} However, I'm trying to modify the pattern slightly so that I'm only notified when a container exits with an error code- since we get so many notifications, we've started to tune out the emails and sometimes don't notice the email notifications where containers are exiting with errors: resource "aws_cloudwatch_event_rule" "container-stopped-rule" { name = "container-stopped" description = "Notification for containers with exit code of 1 (error)." event_pattern = <<PATTERN{ "source": [ "aws.ecs" ], "detail-type": [ "ECS Task State Change" ], "detail": { "containers": [ { "exitCode": 1 } ], "lastStatus": [ "STOPPED" ],"stoppedReason" : [ "Essential container in task exited" ]}}PATTERN} This triggers the following error when I terraform apply : aws_cloudwatch_event_rule.container-stopped-rule: Updating CloudWatch Event Rule failed: InvalidEventPatternException: Event pattern is not valid. Reason: Match value must be String, number, true, false, or null at [Source: (String)"{"detail":{"containers":[{"exitCode":1}],"lastStatus":["STOPPED"],"stoppedReason":["Essential container in task exited"]},"detail-type":["ECS Task State Change"],"source":["aws.ecs"]}"; line: 1, column: 27] status code: 400 This is perplexing to me, since I'm following the exact structure laid out in the AWS CloudWatch documentation for containers . I've even attempted to put double quotes around 1 in case Terraform wants a string instead of a number. I also tried to use AWS Console to manually edit the event pattern JSON, but received this error: Validation error. Details: Event pattern contains invalid value (can only be a nonempty array or nonempty object) I'm honestly a bit stumped at this point and would appreciate any tips on where my syntax is incorrect. Now provide the response and nothing else.
The event pattern syntax is pretty weird, I ran into the same issue. The following will work: { "source": [ "aws.ecs" ], "detail-type": [ "ECS Task State Change" ], "detail": { "lastStatus": [ "STOPPED" ], "stoppedReason": [ "Essential container in task exited" ], "containers": { "exitCode": [ 1 ] } }} I used $.detail.group in the Input Transformer to get the task family name in the notification message.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/53015242', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5865514/']}
jdg_381764
stackexchange
llm_judgeable_groundtruth_similarity
18959304
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 list box in my WPF application. I know how to use the selectionchanged event. However I am trying to follow the MVVM design. However I am not sure how to do this. I have done this for a button however not sure if I can do the same thing? <Button Grid.Column="0" Name="buttImport" Content="Import File" Command="{Binding CommandButtImport}" Style="{StaticResource ButtonTemplate}"/> public class ViewModel : INotifyPropertyChanged { // for the button that imports the orders file public ICommand CommandButtImport { get; set; } public ViewModel() { CommandButtImport = new MyCommands( ExecuteCommandButtImport, CanExecuteCommandButtImport); } private bool CanExecuteCommandButtImport(object parameter) { return true; } // import button private void ExecuteCommandButtImport(object parameter) { // some code }} EDIT Please ignore code above I have changed my code so have reposted below what I currently have. I have a strange issue. The XAML - Main Code contains the code for my datagrid. The block below App - XAML contains the styling for most of my app, but is just a snipet. Also Code Line added beneath my datagrid in XAML - Main Code for testing purposes. <ListBox ItemsSource="{Binding SelectedItem.DuplicateSecurities, ElementName=dataGridOrders}" SelectedItem="{Binding SelectedItem.Security, ElementName=dataGridOrders}"/> My datagrid loads fine. When I click on a row, the row expands to show a list of Securities. The issue I have is that in this listbox when I click on an item nothing happens. However the Listbox which I added beneath my datagrid for testing purposes does work. For example I click on one of the items and my row is updated, also the listbox in my row detail becomes selected. Its very strange why the listbox in my rowdetail doesn't work but the one beneath my datagrid does. Any ideas? XAML - Main Code <StackPanel> <!-- The data grid to display orders--> <DataGrid DataContext="{Binding OrderBlock}" x:Name="dataGridOrders" ItemsSource="{Binding Orders}" Style="{StaticResource DataGridTemplate}" ColumnHeaderStyle="{StaticResource DG_ColumnHeader}" RowHeaderStyle="{StaticResource DG_RowHeader}" RowStyle="{StaticResource DG_Row}" CellStyle="{StaticResource DG_Cell}" RowDetailsTemplate="{StaticResource DG_RowDetail}" AutoGenerateColumns="False" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Background="Silver" RowHeaderWidth="30" Margin="25,5,20,15"> <DataGrid.Columns> <DataGridComboBoxColumn Header="Action"> <DataGridComboBoxColumn.ElementStyle> <Style TargetType="ComboBox"> <Setter Property="ItemsSource" Value="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}, Path=DataContext.StatusList}"/> <Setter Property="IsReadOnly" Value="True"/> <Setter Property="SelectedValue" Value="{Binding StatusGood}"/> </Style> </DataGridComboBoxColumn.ElementStyle> <DataGridComboBoxColumn.EditingElementStyle> <Style TargetType="ComboBox"> <Setter Property="ItemsSource" Value="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}, Path=DataContext.StatusList}"/> <Setter Property="IsReadOnly" Value="True"/> <Setter Property="SelectedValue" Value="{Binding StatusGood}"/> </Style> </DataGridComboBoxColumn.EditingElementStyle> </DataGridComboBoxColumn> <DataGridTextColumn Header="Fund" Binding="{Binding Account}" IsReadOnly="True"/> <DataGridTextColumn Header="Security ID" Binding="{Binding Security.ID}" IsReadOnly="True"/> <DataGridTextColumn Header="ThinkFolio Security ID" Binding="{Binding ThinkFolioSecurityID}" IsReadOnly="True"/> <DataGridTextColumn Header="Security Name" Binding="{Binding Security.Name}" IsReadOnly="True"/> <DataGridTextColumn Header="Buy/Sell" Binding="{Binding TransType}" IsReadOnly="True"/> <DataGridTextColumn Header="Quantity" Binding="{Binding OrderQunatity, StringFormat=\{0:N0\}}" IsReadOnly="False"/> <DataGridTextColumn Header="Currency" Binding="{Binding BuyCurrency}" IsReadOnly="False"/> <DataGridTextColumn Header="Manager" Binding="{Binding FundManager}" IsReadOnly="True"/> <DataGridTextColumn Header="Order Reason" Binding="{Binding OrderReason}" IsReadOnly="True"/> <DataGridTextColumn Header="Reject Reason" Binding="{Binding RejectReason}" IsReadOnly="True" Width="*"/> </DataGrid.Columns> </DataGrid> <ListBox ItemsSource="{Binding SelectedItem.DuplicateSecurities, ElementName=dataGridOrders}" SelectedItem="{Binding SelectedItem.Security, ElementName=dataGridOrders}"/> </StackPanel> App XAML <!-- Row Detail Template for Data Grid --> <DataTemplate x:Key="DG_RowDetail"> <Grid x:Name="RowDetailGrid" Margin="5" HorizontalAlignment="Left"> <Border HorizontalAlignment="Left" VerticalAlignment="Top" Width="500" Height="80" CornerRadius="5"> <Border.Background> <LinearGradientBrush StartPoint="0,0" EndPoint="0,1"> <GradientStop Offset="0" Color="Transparent"/> <GradientStop Offset="1" Color="Transparent"/> </LinearGradientBrush> </Border.Background> <Grid> <Grid.RowDefinitions> <RowDefinition Height="*"/> <RowDefinition Height="2.5*"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <TextBlock Grid.Row="0" Grid.ColumnSpan="3" Margin="5,0,0,5" HorizontalAlignment="Left" FontSize="12" FontWeight="Bold" Foreground="Black" Text="Select Security Identifier"> </TextBlock> <ListBox Grid.Row="1" Grid.ColumnSpan="3" Name="lbIdentifier" ItemsSource="{Binding DuplicateSecurities}" SelectedItem="{Binding Security}" SelectionMode="Single" HorizontalContentAlignment="Stretch"> <ListBox.ItemTemplate> <DataTemplate> <Grid Margin="0,2"> <Grid.ColumnDefinitions> <ColumnDefinition/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <TextBlock Grid.Column="0" Text="{Binding Path=ID}" FontSize="10" HorizontalAlignment="Left" Margin="5,0,0,0"/> <TextBlock Grid.Column="1" Text="{Binding Path=Name}" FontSize="10" HorizontalAlignment="Left" Margin="5,0,0,0"/> </Grid> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </Grid> </Border> </Grid> </DataTemplate> ViewModel public class ViewModel : INotifyPropertyChanged { public ICommand CommandButtImport { get; set; } // for the button that imports the orders file public ICommand CommandButtSend { get; set; } // the button where the user sends the orders in our data grid to thinkFolio public ICommand CommandButtExit { get; set; } // exit application private QoEMain _QoEManager; // manages the Model public QoEMain QoEManager { get { return this._QoEManager; } set { _QoEManager = value; } } private OrderBlocks _orderBlock; // order block - contains all the order information public OrderBlocks OrderBlock { get { return this._orderBlock; } set { this._orderBlock = value; OnPropertyChanged("OrderBlock"); } } } OrderBlocks Class which contains the other classes public class OrderBlocks : INotifyPropertyChanged{ private List<Order> _orders; [XmlElement("tF_Transactions")] public List<Order> Orders { get { return _orders; } set { _orders = value; OnPropertyChanged("Orders"); } }} Orders Class public class Order : INotifyPropertyChanged { Security security; public Security Security { get { return security; } set { security = value; OnPropertyChanged("Security"); } } List<Security> duplicateSecurities; public List<Security> DuplicateSecurities { get { return duplicateSecurities; } set { duplicateSecurities = value; OnPropertyChanged("DuplicateSecurities"); } } Security Class public class Security : INotifyPropertyChanged { private string _id; public string ID { get { return _id; } set { _id = value; OnPropertyChanged("ID"); } } private string _name; public string Name { get { return _name; } set { _name = value; OnPropertyChanged("Name"); } } public Security() { } public Security(string newID, string newName) { ID = newID; Name = newName; } Edit - My code now works please see the code snippet below that works for me <DataGrid Grid.Row="1" Grid.Column="0" ItemsSource="{Binding SelectedItem.DuplicateSecurities, ElementName=dataGridOrders}" SelectedItem="{Binding SelectedItem.Security, ElementName=dataGridOrders}"> Now provide the response and nothing else.
Example of binding ListBox SelectionChanged Event to command in your ViewModel <ListBox x:Name="myListBox" ItemsSource="{Binding SomeCollection}"> <ie:Interaction.Triggers> <ie:EventTrigger EventName="SelectionChanged"> <ie:InvokeCommandAction Command="{Binding SelectedItemChangedCommand}" CommandParameter="{Binding ElementName=myListBox, Path=SelectedItem}"/> </ie:EventTrigger> </ie:Interaction.Triggers></ListBox > In your ViewModel : public class myViewModel{ public myViewModel() { SelectedItemChangedCommand = new DelegateCommand<object>((selectedItem) => { // Logic goes here }); } public List<SomeData> SomeCollection { get; set; } public DelegateCommand<object> SelectedItemChangedCommand { get; set; }} This particular example uses Prism MVVM Framework, but you can apply the same idea with any other MVVM framework you are using as well. Hope this helps
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/18959304', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2730554/']}
jdg_381765
stackexchange
llm_judgeable_groundtruth_similarity
8629410
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Given a file with data like this (ie stores.dat file) sid|storeNo|latitude|longitude2tt|1|-28.0372000t0|153.429216709|2t|-33tt.85t09t0000|15t1.03274200 What is the command that would return the number of occurrences of the 't' character per line? eg. would return: count lineNum 4 1 3 2 6 3 Also, to do it by count of occurrences by field what is the command to return the following results? eg. input of column 2 and character 't' count lineNum 1 1 0 2 1 3 eg. input of column 3 and character 't' count lineNum 2 1 1 2 4 3 Now provide the response and nothing else.
To count occurrence of a character per line you can do: awk -F'|' 'BEGIN{print "count", "lineNum"}{print gsub(/t/,"") "\t" NR}' filecount lineNum4 13 26 3 To count occurrence of a character per field/column you can do: column 2: awk -F'|' -v fld=2 'BEGIN{print "count", "lineNum"}{print gsub(/t/,"",$fld) "\t" NR}' filecount lineNum1 10 21 3 column 3: awk -F'|' -v fld=3 'BEGIN{print "count", "lineNum"}{print gsub(/t/,"",$fld) "\t" NR}' filecount lineNum2 11 24 3 gsub() function's return value is number of substitution made. So we use that to print the number. NR holds the line number so we use it to print the line number. For printing occurrences of particular field, we create a variable fld and put the field number we wish to extract counts from.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/8629410', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/688412/']}
jdg_381766
stackexchange
llm_judgeable_groundtruth_similarity
28029929
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 gulp.js file that includes: gulp.task('default', ['watch']); Which starts up the watch task gulp.task('watch', function(){ gulp.watch(productionScripts, ['autoConcat']);}); Then on any saved changes to files in productionScripts, the watch task will concat the files. What I would like to do, is in my package.json, I would like to spool up this watch when I type npm start (this already starts my node server). package.json "start": "node server.js", UPDATE -------- Ben(b3nj4m.com), I tried what you stated. The watch and server start up. However, everything runs twice (probably due to the editor, not related), but I do lose my server log when I start it up with gulp. [15:31:18] Starting 'autoConcat'...[15:31:18] Finished 'autoConcat' after 147 ms[15:31:19] Starting 'autoConcat'...[15:31:19] Finished 'autoConcat' after 138 ms[15:31:20] Starting 'autoConcat'...[15:31:20] Finished 'autoConcat' after 127 ms[15:31:23] Starting 'autoConcat'... It's like there is a loop between the server restarting on a change, and the concatenated file changing. Now provide the response and nothing else.
You could run your server from your gulpfile: var child = require('child_process');var fs = require('fs');gulp.task('default', ['server', 'watch']);gulp.task('server', function() { var server = child.spawn('node', ['server.js']); var log = fs.createWriteStream('server.log', {flags: 'a'}); server.stdout.pipe(log); server.stderr.pipe(log);});gulp.task('watch', function(){ gulp.watch(productionScripts, ['autoConcat']);}); Then change your npm start definition to look like: "scripts": { "start": "gulp"}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28029929', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2063096/']}
jdg_381767
stackexchange
llm_judgeable_groundtruth_similarity
3976342
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 been working on a SWT-based project which is intended to be deployed as Java Web Start, and thus be used on multiple platforms. So far I have managed to tackle the exporting problem that arises due to the system-specific libraries SWT depends on (see relevant thread ). The resultant jar seems to work start fine on 32/64-bit linux and 64-bit windows, however execution fails on a Mac with the following output: $ java -jar dist/test.jar Adding { file:/Volumes/LaCie/ChiBE_Local/swt/swt-cocoa-macosx-x86_64-3.6.1.jar } to the classpath***WARNING: Display must be created on main thread due to Cocoa restrictions.Exception in thread "main" java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58)Caused by: java.lang.ExceptionInInitializerError at org.eclipse.gef.tools.MarqueeSelectionTool.<init>(MarqueeSelectionTool.java:99) at org.gvt.MarqueeZoomTool.<init>(MarqueeZoomTool.java:16) at org.gvt.action.MarqueeZoomToolAction$1.<init>(MarqueeZoomToolAction.java:28) at org.gvt.action.MarqueeZoomToolAction.createTool(MarqueeZoomToolAction.java:28) at org.gvt.action.AbstractGEFToolAction.<init>(AbstractGEFToolAction.java:24) at org.gvt.action.MarqueeZoomToolAction.<init>(MarqueeZoomToolAction.java:20) at org.gvt.TopMenuBar.createBarMenu(TopMenuBar.java:113) at org.gvt.ChisioMain.createMenuManager(ChisioMain.java:617) at org.eclipse.jface.window.ApplicationWindow.addMenuBar(ApplicationWindow.java:235) at org.gvt.ChisioMain.main(ChisioMain.java:149) at org.gvt.RuntimeMain.main(RuntimeMain.java:14) ... 5 moreCaused by: org.eclipse.swt.SWTException: Invalid thread access at org.eclipse.swt.SWT.error(Unknown Source) at org.eclipse.swt.SWT.error(Unknown Source) at org.eclipse.swt.SWT.error(Unknown Source) at org.eclipse.swt.widgets.Display.error(Unknown Source) at org.eclipse.swt.widgets.Display.createDisplay(Unknown Source) at org.eclipse.swt.widgets.Display.create(Unknown Source) at org.eclipse.swt.graphics.Device.<init>(Unknown Source) at org.eclipse.swt.widgets.Display.<init>(Unknown Source) at org.eclipse.swt.widgets.Display.<init>(Unknown Source) at org.eclipse.swt.widgets.Display.getDefault(Unknown Source) at org.eclipse.swt.widgets.Display$1.run(Unknown Source) at org.eclipse.swt.graphics.Device.getDevice(Unknown Source) at org.eclipse.swt.graphics.Resource.<init>(Unknown Source) at org.eclipse.swt.graphics.Cursor.<init>(Unknown Source) at org.eclipse.draw2d.Cursors.<clinit>(Cursors.java:170) ... 16 more I have checked a number of relevant threads: ( Can't get SWT Display on Mac OS X , Problems With SWT on Mac ) as well as the UI Thread entry on the SWT FAQ and tutorials such as Bringing your Java App to Mac and Deploying SWT applications on Mac OSX . It's my understanding that the problem originates from thread handling on Mac OSX, and I should try to implement the JVM argument -XstartOnFirstThread at the execution. Is this right? Assuming that my understanding of the problem is accurate, I am a bit confused as this software is intended to be cross-platform and run on javaws. Do I need to create an info.plist file, if so where in the package and how, otherwise how can I "conditionally" pass that argument to JVM at the time of execution? Thanks in advance, Now provide the response and nothing else.
Yes, you will definitely need -XstartOnFirstThread to get this working on Mac OS X. Since it's a VM parameter, you can only specify it when launching your application, so detecting the OS from you code and setting it if it's Mac OS X is not possible. The solution on the Eclipse site creates a proper Mac OS X My Application.app , which is platform specific and, again, not feasible in your case. However, I just tried running an Eclipse RCP application on Windows XP with the -XstartOnFirstThread argument specified, and it didn't complain at all. This means that you can specify this argument in your JNLP file and presumably it will be ignored on all other platforms and picked up on Mac OS X. UPDATE: If for some reason -XstartOnFirstThread causes trouble on any platform, or you just want to Do The Right Thing , there is another possible solution. You could detect the user's OS in the browser — assuming that the application is launched from a web page —, and supply a different JNLP for Mac OS X and other platforms. UPDATE 2: As pointed out in the comments, there is a tutorial on deploying SWT applications with Java Web Start . I simply launched the JNLP on Mac OS X (10.6.x), and it worked. Looking at the example JNPL I found the following: <?xml version="1.0" encoding="utf-8"?><jnlp spec="1.0+" codebase="http://www.eclipse.org/swt/jws/" href="controlexample.jnlp"><information> <title>Control Example</title> <vendor>eclipse.org</vendor> <homepage href="http://www.eclipse.org/swt/jws/" /> <description>A demonstration of SWT Widgets</description> <description>Control Example</description></information><security> <all-permissions /></security><resources> <extension href="swt.jnlp"/> <jar href="controlexample.jar" /></resources><application-desc main-class="org.eclipse.swt.examples.controlexample.ControlExample" /></jnlp> Note the <extension href="swt.jnlp"/> line towards the end, pointing to the platform-specific SWT JNLP file (some parts omitted here): <?xml version="1.0" encoding="utf-8"?><jnlp spec="1.0+" codebase="http://www.eclipse.org/swt/jws/" href="swt.jnlp"><information> <title>SWT</title> <vendor>eclipse.org</vendor> <homepage href="http://www.eclipse.org/swt/jws/" /> <description>SWT</description></information><security> <all-permissions /></security><resources os="Windows" arch="x86"> <j2se version="1.4+" /> <jar href="swt-win32-windows-x86.jar" /></resources>...<resources os="Mac\ OS\ X"> <j2se version="1.5*" java-vm-args="-XstartOnFirstThread"/> <jar href="swt-carbon-osx-universal.jar" /></resources><component-desc/></jnlp> There it is towards the end of the file: the Mac OS X specific -XstartOnFirstThread argument.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3976342', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/328725/']}
jdg_381768
stackexchange
llm_judgeable_groundtruth_similarity
3998798
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 used FireBug to test the two cases and they seem pretty similar by result: >>> var x = {"active": "yes"}>>> x.active"yes">>> var x = {active: "yes"}>>> x.active"yes" But I'm pretty sure there is some difference between these two, maybe even performance related difference. Bottom line - I'd like to know if there is a difference between {active: "yes"} and {"active": "yes"}. Now provide the response and nothing else.
Both are valid. However there are certain keywords you cant use like delete so in order to avoid that you wrap them in quotes so they are not treated literally by the ECMAScript parser and instead are explicitly specified as strings. Additionally, the JSON spec requires that keys have quotes around them: A string begins and ends with quotation marks So {key:'value'} is not valid JSON but is valid JS, while {"key":"value"} is valid JS and JSON. Examples of keywords and invalid/ambiguous keys: >>> ({delete:1})SyntaxError: Unexpected token delete>>> ({'delete':1})Object Another example: >>> ({first-name:'john'})SyntaxError: Unexpected token ->>> ({'first-name':'john'})Object>>> ({'first-name':'john'})['first-name']"john"
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3998798', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/109687/']}
jdg_381769
stackexchange
llm_judgeable_groundtruth_similarity
24751350
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 installing my app to Android L preview it fails with error: INSTALL_FAILED_NO_MATCHING_ABIS. My app uses arm only library, features that uses library is disabled on x86. It works perfectly before Android L, but now i can't even install it. How to disable this error for my app? Now provide the response and nothing else.
Posting this because I could not find a direct answer and had to look at a couple of different posts to get what I wanted done... I was able to use the x86 Accelerated (HAXM) emulator by simply adding this to my Module's build.gradle script Inside android{} block: splits { abi { enable true reset() include 'x86', 'armeabi-v7a' universalApk true } } Run (build)... Now there will be a (yourapp)-x86-debug.apk in your output folder. I'm sure there's a way to automate installing upon Run but I just start my preferred HAXM emulator and use command line: adb install (yourapp)-x86-debug.apk
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24751350', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1314910/']}
jdg_381770
stackexchange
llm_judgeable_groundtruth_similarity
39567382
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 implement alarm manager to my application but confused because my alarm manager won't start when my application closed/diedi was searching in google many suggestion in there but no one suggestion work.this my secenario open application-> automatic start service/alarm manger when application open every 10 minutes the application check to server to download data and insert to database when application close every 10 minutes the application check to server to download data and insert to database the problem is when the application is close the service also stop.this my example code MainActivity.java AlarmReceiver alarm = new AlarmReceiver();@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); alarm.setAlarm(this);} AlarmReceiver.Java public class AlarmReceiver extends WakefulBroadcastReceiver {private AlarmManager alarmMgr;private PendingIntent alarmIntent;@Overridepublic void onReceive(Context context, Intent intent) { Intent service = new Intent(context, SchedulingService.class); startWakefulService(context, service);}public void setAlarm(Context context) { alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(context, AlarmReceiver.class); alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0); alarmMgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, 10000, 10000, alarmIntent); ComponentName receiver = new ComponentName(context, SampleBootReceiver.class); PackageManager pm = context.getPackageManager(); pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP); }public void cancelAlarm(Context context) { // If the alarm has been set, cancel it. if (alarmMgr!= null) { alarmMgr.cancel(alarmIntent); } ComponentName receiver = new ComponentName(context, BootReceiver.class); PackageManager pm = context.getPackageManager(); pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);} } BootReceiver.java public class BootReceiver extends BroadcastReceiver {AlarmReceiver alarm = new AlarmReceiver();@Overridepublic void onReceive(Context context, Intent intent) { if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) { alarm.setAlarm(context); }}} ScheduleService.java public class SchedulingService extends IntentService {public SchedulingService() { super("SchedulingService");}public static final String TAG = "Scheduling Demo";public static final int NOTIFICATION_ID = 1;public static final String SEARCH_STRING = "Active";public static final String URL = "http://localhost/TMALive";private NotificationManager mNotificationManager;NotificationCompat.Builder builder;@Overrideprotected void onHandleIntent(Intent intent) { String urlString = URL; String result =""; try { result = loadFromNetwork(urlString); } catch (IOException e) { Log.i(TAG, getString(R.string.connection_error)); } if (result.indexOf(SEARCH_STRING) != -1) { sendNotification(getString(R.string.live_found)); Log.i(TAG, "Your Post Live!!"); } else { sendNotification(getString(R.string.no_live)); Log.i(TAG, "Your Post Off. :-("); } AlarmReceiver.completeWakefulIntent(intent);}private void sendNotification(String msg) { mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_launcher) .setContentTitle(getString(R.string.pos_alert)) .setStyle(new NotificationCompat.BigTextStyle() .bigText(msg)) .setContentText(msg); mBuilder.setContentIntent(contentIntent); mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());}private String loadFromNetwork(String urlString) throws IOException { InputStream stream = null; String str =""; try { stream = downloadUrl(urlString); str = readIt(stream); } finally { if (stream != null) { stream.close(); } } return str;}private InputStream downloadUrl(String urlString) throws IOException { URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("GET"); conn.setDoInput(true); // Start the query conn.connect(); InputStream stream = conn.getInputStream(); return stream;}private String readIt(InputStream stream) throws IOException { StringBuilder builder = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); for(String line = reader.readLine(); line != null; line = reader.readLine()) builder.append(line); reader.close(); return builder.toString();}} thats code work fine when application open but when application closed no notification showing and after restart also. can you give me suggestion witch better using this approach or using service approach? many thanks Now provide the response and nothing else.
you just need to install and require gulp locally , you probably only installed it globally At the command line cd <project-root> && npm install --save-dev gulp In your gulpfile.js var gulp = require('gulp'); this is a different dependency than the command line dependency (that you installed globally). More specifically, it is the same NPM package, but the command line program will execute code usually from a different entry point in the NPM package then what require('X') will return. If we go to the package.json file in the Gulp project on Github, it will tell the whole story: { "name": "gulp", "description": "The streaming build system", "version": "3.9.1", "homepage": "http://gulpjs.com", "repository": "gulpjs/gulp", "author": "Fractal <[email protected]> (http://wearefractal.com/)", "tags": [ ], "files": [ // ... ], "bin": { "gulp": "./bin/gulp.js" }, "man": "gulp.1", "dependencies": { // ... }, "devDependencies": { // ... }, "scripts": { "prepublish": "marked-man --name gulp docs/CLI.md > gulp.1", "lint": "eslint . && jscs *.js bin/ lib/ test/", "pretest": "npm run lint", }, "engines": { "node": ">= 0.9" }, "license": "MIT"} so at the command line: $ gulp default will execute this: "bin": { "gulp": "./bin/gulp.js" }, on the other hand, require('gulp') in your code will return the value of this: https://github.com/gulpjs/gulp/blob/master/index.js normally we see this in a package.json file as: "main": "index.js" but since this is the default, they just omitted it (which is dumb IMO, better to be explicit, but they aren't the first project I have seen take the lame shorthand route.).
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/39567382', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6703142/']}
jdg_381771
stackexchange
llm_judgeable_groundtruth_similarity
279693
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 new to cryptography and modular arithmetic. So, I'm sure it's a silly question, but I can't help it. How do I calculate a from pow( a , q ) = 1 (mod p ), where p and q are known? I don't get the "1 (mod p )" part, it equals to 1, doesn't it? If so, than what is "mod p " about? Is this the same as pow( a , -q ) (mod p ) = 1? Now provide the response and nothing else.
The (mod p) part refers not to the right hand side, but to the equality sign: it says that modulo p, pow(a,q) and 1 are equal . For instance, "modulo 10, 246126 and 7868726 are equal" (and they are also both equal to 6 modulo 10): two numbers x and y are equal modulo p if they have the same remainder on dividing by p, or equivalently, if p divides x-y. Since you seem to be coming from a programming perspective, another way of saying it is that pow(a,q)%p=1, where "%" is the "remainder" operator as implemented in several languages (assuming that p>1). You should read the Wikipedia article on Modular arithmetic , or any elementary number theory book (or even a cryptography book, since it is likely to introduce modular arithmetic). To answer your other question: there is no general formula for finding such an a (to the best of my knowledge) in general. Assuming that p is prime, and using Fermat's little theorem to reduce q modulo p-1, and assuming that q divides p-1 (or else no such a exists), you can produce such an a by taking a primitive root of p and raising it to the power (p-1)/q. [And more generally, when p is not prime, you can reduce q modulo φ(p), then assuming it divides φ(p) and you know a primitive root (say r) mod p, you can take r to the power of φ(p)/q, where φ is the totient function -- this comes from Euler's theorem .]
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/279693', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/24622/']}
jdg_381772
stackexchange
llm_judgeable_groundtruth_similarity
315004
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: Just for clarification, with the function $k_n(x) = \left\{ \begin{array}{ll} 0 & \mbox{if } x \leq n \\ x-n & \mbox{if } x \geq n \end{array}\right.$ I've shown the function is uniformly convergent on $[a,b]$, and it asks if the function is uniformly convergent on $\mathbb{R}$ or not. My thinking is that since $\displaystyle\lim_{n \to \infty} k_n(x) = k(x) = 0 \ \ \forall x \in \mathbb{R}$ It's sufficient to show $|k_n(x) - k (x)| = |k_n(x)| > \epsilon$ for given $\epsilon > 0 \ $ and for some $x \in \mathbb{R}$, $n \in \mathbb{N}$. So, given some $\epsilon$ and for fixed $n$, there exists some $x \in \mathbb{R}$ such that $x \geq n + \epsilon$ giving $|k_n(x)| = |x-n| > \epsilon$ and hence $k_n$ is not uniformly convergent at this point (or for all $p > x$) hence $k_n$ is not uniformly convergent on $\mathbb{R}$ Thanks again for all the help. Now provide the response and nothing else.
Using the residue theorem, you can show that $$\sum_{n=-\infty}^{\infty} \frac{1}{n^2+a^2} = \frac{\pi}{a} \coth{\pi a}$$ This is equivalent to saying that $$\sum_{n=1}^{\infty} \frac{1}{n^2+a^2} = \frac{1}{2} \left (\frac{\pi}{a} \coth{\pi a} - \frac{1}{a^2}\right )$$ You can also derive this by considering the Maclurin expansion of $z \coth{z}$: $$z \coth{z} = 1 + \sum_{k=1}^{\infty} \frac{B_{2 k} (2 z)^{2 k}}{(2 k)!}$$ where $B_{2 k}$ is a Bernoulli number , which also shows up in Riemann zeta functions of even, positive argument: $$\zeta(2 k) = (-1)^{k+1} \frac{B_{2 k} (2 \pi)^{2 k}}{2 (2 k)!}$$ To evaluate the sum, factor out $n^2$ from the denominator and Taylor expand: $$\begin{align}\sum_{n=1}^{\infty} \frac{1}{n^2+a^2} &= \frac{1}{n^2} \frac{1}{1+ \frac{a^2}{n^2}}\\ &= \sum_{n=1}^{\infty} \frac{1}{n^2} \sum_{k=0}^{\infty} (-1)^k \left (\frac{a^2}{n^2}\right )^{k} \\ &=\sum_{k=0}^{\infty} (-1)^k a^{2 k}\sum_{n=1}^{\infty} \frac{1}{n^{2 k+2}} \\ &=\sum_{k=0}^{\infty} (-1)^k a^{2 k} \zeta(2 k+2)\\ &= \frac{1}{2 a^2}\sum_{k=1}^{\infty} \frac{B_{2 k} (2 \pi a)^{2 k}}{(2 k)!} \\ &= \frac{1}{2 a^2} ( \pi a \coth{\pi a} - 1)\\ \end{align}$$ The result follows.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/315004', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/63446/']}
jdg_381773
stackexchange
llm_judgeable_groundtruth_similarity
13324297
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 created my own annotation, which I utilize via reflection to make a decision in my code. The annotation has a default value set for its sole element. Is there a way I can access the default value via reflection? PageableRequestMapping.java (Annotation) package org.tothought.controllers.annotations;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;@Retention(RetentionPolicy.RUNTIME)public @interface PageableRequestMapping { String variablePath() default "/";} Psuedo Code to Retrieve Default Value private int parsePageNumber(StringBuffer requestURL, PageableRequestMapping pageableRequestMapping) { String variablePath = pageableRequestMapping.variablePath(); //Psuedo code doesn't work in Java, included to illustrate intentions if(variablePath.equalsIgnoreCase(pageableRequestMapping.variablePath().default())){ //handle default case }else{ //handle different case } return 0;} My research of the issue has turned up no examples. I theorized this value could be accessed in a static manner through the class, but it cannot. So I am left with two questions. Is it possible to get the default value of an element within an annotation? If so, how? Also, I know I could hard code this value, however I would like to make the program slightly more robust. Now provide the response and nothing else.
You can use reflection to get the Method object, and then utilize Method#getDefaultValue() . Method method = pageableReqMapping.annotationType().getMethod("variablePath");String variablePath = (String) method.getDefaultValue(); Here's a concrete example: public class AnnotationTest { public static void main(String[] args) throws Exception { Class<?> clazz = Annotation.class; Method method = clazz.getDeclaredMethod("value"); String value = (String) method.getDefaultValue(); System.out.println(value); } public @interface Annotation { String value() default "default value"; }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13324297', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/714969/']}
jdg_381774
stackexchange
llm_judgeable_groundtruth_similarity
82834
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I understand that this might be a loaded question.For example, in Sql Server 2008, doing DECLARE @someNum NUMERIC(10); means that the range of the variable will be limited by 10 digits. In other languages such as C, Java, etc. the standards for representing whole and fractional numbers are different. The range of the values is being sliced by multiples of bytes, and this is understandable, due to the way hardware works. A language could provide something that most hardware does not yet support, such as a 256-bit integer type, which will work fast on a 64-bit computer, if it is implemented correctly. The numeric types in the databases seem to be not tied to underlying hardware. I understand that the values might need to be null-ablle, which can cost a bit or two, but why such arbitrary precision that does not seem to optimize storage or calculation speed? Perhaps databases do not need to perform numeric computations often. Perhaps digit width of a column is a natural extension of character width. Perhaps SQL was supposed to be a non-programmers language (because it sounds like English :) )?Perhaps history took a weird turn, such as one that allowed the inferior VHS format to prosper. Please help me understand this. Now provide the response and nothing else.
doing DECLARE @someNum NUMERIC(10); means that the range of the variable will be limited by 10 digits. Actually, you're either very wrong in that assertion, or SQL server is hugely incompatible with other DB engines. Typically, you have: NUMERIC(precision, scale) NUMERIC(precision) In the second case, scale is zero, i.e. you can only handle integers; precision is the maximum total number of digits with the specified scale (meaning integers in the second case). By contrast, you seem to be reading numeric(10) as meaning "any number as long as there are 10 digits or less", for which there is no (best I'm aware anyway) SQL construct short of single/double float types (whose name differ per DB engine). The numeric types in the databases seem to be not tied to underlying hardware. Indeed, they're not. Numeric/Decimal is an arbitrary precision number , stored very much like a varchar of huge length (1000+ digits). You can actually use it to store 1e100 + 1 as an exact value. You'll get 1 followed by zeros, and finally a 1 . You sound like you need a float... The latter would store 1e100 when given 1e100 + 1 , and would yield 1e100 .
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/82834', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/934/']}
jdg_381775
stackexchange
llm_judgeable_groundtruth_similarity
1656762
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`m currently having some issues with a seemingly innocent problem. I would like to show that $$\Bigg\|\int_\mathbb{R}\begin{pmatrix}A(x)\\B(x)\end{pmatrix}dx\Bigg\|_2 \leq \int_{\mathbb{R}}\Bigg\|\begin{pmatrix}A(x)\\B(x)\end{pmatrix}\Bigg\|_2dx$$ Where $A(x),B(x) \in L^2(\mathbb{R})$ and the two norm is defined as $$\Bigg\|\begin{pmatrix}A(x)\\B(x)\end{pmatrix}\Bigg\|_2=\sqrt{|A(x)|^2+|B(x)|^2}$$ I've asked around and people have tended to say "that's very simple" and then spent half an hour staring at it. I've tried plugging stuff in and it seems to hold but I do need a proof. Any help would be much appreciated! Thanks in advance Now provide the response and nothing else.
It's very simple. hehe... (Note you actually want to assume $A,B\in L^1(\Bbb R)$, not $L^2$.) Edit: Morally the same argument works for a Banach-space valued function; see Below . To make things easier to type I'm going to revise the notation. Suppose that $f:\Bbb R\to\Bbb R^2$; we want to show that $$\left|\left|\int f(x)\,dx\right|\right|_2\le\int||f(x)||_2\,dx.$$Let $$v=\int f(x)\,dx\in\Bbb R^2.$$Then $$||v||_2^2=v\cdot v=v\cdot\int f(x)\,dx=\int v\cdot f(x)\,dx\le\int||v||_2||f(x)||_2\,dx=||v||_2\int||f(x)||_2\,dx.$$Divide by $||v||_2$: $$||v||_2\le\int||f(x)||_2\,dx.$$ Below One can give a similar argument if $f:S\to X$ where $X$ is a Banach space and $\mu$ is a measure on $S$. Let $$v=\int_Sf(t)\,d\mu(t)\in X.$$Suppose $\Lambda\in X^*$ and $||\Lambda||=1$. Then $$\Lambda v=\int\Lambda f(t)\,d\mu(t)\le\int||\Lambda||_{X^*}||f(t)||_X\,d\mu(t)=\int||f(t)||\,d\mu(t).$$Since this holds for every such $\Lambda$, Hahn-Banach shows that $||v||\le\int||f||\,d\mu$.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1656762', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/314650/']}
jdg_381776
stackexchange
llm_judgeable_groundtruth_similarity
2324658
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 do you determine what version of the C++ standard is implemented by your compiler? As far as I know, below are the standards I've known: C++03 C++98 Now provide the response and nothing else.
From the Bjarne Stroustrup C++0x FAQ : __cplusplus In C++11 the macro __cplusplus will be set to a value that differs from (is greater than) the current 199711L . Although this isn't as helpful as one would like. gcc (apparently for nearly 10 years) had this value set to 1 , ruling out one major compiler, until it was fixed when gcc 4.7.0 came out . MSVC also doesn't set this macro correctly, to this very day. By default it's defined to 199711L regardless of the language version, and you either need to add /Zc:__cplusplus to compiler flags, or check a MSVC-specific macro _MSVC_LANG instead, which always has the right value. These are the C++ standards and what value you should be able to expect in __cplusplus : C++ pre-C++98: __cplusplus is 1 . C++98: __cplusplus is 199711L . C++98 + TR1: This reads as C++98 and there is no way to check that I know of. C++11: __cplusplus is 201103L . C++14: __cplusplus is 201402L . C++17: __cplusplus is 201703L . C++20: __cplusplus is 202002L . If the compiler might be an older gcc , we need to resort to compiler specific hackery (look at a version macro, compare it to a table with implemented features) or use Boost.Config (which provides relevant macros ). The advantage of this is that we actually can pick specific features of the new standard, and write a workaround if the feature is missing. This is often preferred over a wholesale solution, as some compilers will claim to implement C++11, but only offer a subset of the features. The Stdcxx Wiki hosts a comprehensive matrix for compiler support of C++0x features (archive.org link) (if you dare to check for the features yourself). Unfortunately, more finely-grained checking for features (e.g. individual library functions like std::copy_if ) can only be done in the build system of your application (run code with the feature, check if it compiled and produced correct results - autoconf is the tool of choice if taking this route).
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/2324658', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/223465/']}
jdg_381777
stackexchange
llm_judgeable_groundtruth_similarity
152081
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Let L/K be a (separable?) field extension, let A be a finite dimensional algebra over K, and let M and N be two A-modules. Let $A' = L \otimes_K A$ be the algebra given by extension of scalars, and let $M' = L \otimes_K M$ and $N' = L \otimes_K N$ be the A'-modules given by extension of scalars. Does $M' \cong N'$ (as A'-modules) imply that $M \cong N$ (as A-modules)? ( This question is obviously related. Note that just as for that question it is easy to see that base extension reflects isomorphisms in the sense that if a map $f: M \rightarrow N$ has the property that $f' : M' \rightarrow N'$ is an isomorphism then f is an isomorphism. This is asking about the more subtle question of whether it reflects the property of being isomorphic.) I apologize if this is standard (I have a sinking suspicion that I've seen a theorem along these lines before), but I haven't been able to find it. There's a straightforward proof in the semisimple setting, but I have made no progress in the non-semisimple setting. Now provide the response and nothing else.
I hope I'm not misunderstanding the question. Here goes: We'll show that if $M,N$ are finite-dimensional over $K$, then they are isomorphic over $K$. Think of the linear space $X=\mathrm{Hom}_{A}(M,N)$as a variety over $K$. Inside $X$ look at the $K$-subvariety $X'$ of maps that are not isomorphisms $M \rightarrow N$.Now $X' \neq X$,because there is an $L$-point of $X$ not in $X'$. Therefore, over an infinite field $K$, there will certainly exist a $K$-point of $X$that doesnt lie in the proper subvariety $X'$. If $K$ is finite: $M,N$ are both $K$-forms of the same module $M'$ over $L$. The $L$-automorphisms of $M'$ are a connected group, becausethey amount to the complement of the hypersurface $X'$ inside the linear space $X$. So its Galois cohomology vanishes, thus thesame conclusion.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/152081', 'https://mathoverflow.net', 'https://mathoverflow.net/users/22/']}
jdg_381778
stackexchange
llm_judgeable_groundtruth_similarity
41808763
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Given a tag `latest`, we want to find out another tag with the same image ID on Docker Hub. Here is how to find out all tags for a repo with the Docker Hub API v2: TOKEN=$(curl -s -H "Content-Type: application/json" -X POST -d '{"username": "'${UNAME}'", "password": "'${UPASS}'"}' https://hub.docker.com/v2/users/login/ | jq -r .token)curl -s -H "Authorization: JWT ${TOKEN}" https://hub.docker.com/v2/repositories/fluent/fluentd/tags/?page_size=100 | jq (See gist.github.com/kizbitz ) Unfortunately, it doesn't contain the image ID but always a `null` value for this key: $ curl -s -H "Authorization: JWT ${TOKEN}" https://hub.docker.com/v2/repositories/fluent/fluentd/tags/?page_size=100 | jq{ "count": 36, "next": null, "previous": null, "results": [... { "name": "v0.14.11", "full_size": 11964464, "id": 7084687, "repository": 219785, "creator": 2923, "last_updater": 2923, "last_updated": "2016-12-27T07:16:41.294807Z", "image_id": null, "v2": true, "platforms": [ 5 ] },... Unfortunately, the image ID is something different than the `id` in the JSON above. $ docker images | grep fluentdocker.io/fluent/fluentd v0.14.11 1441d57beff9 3 weeks ago 38.25 MB Theoretically, it should be possible to access the Docker Manifests and along with the the image ID with this Docker Registry call but it doesn't help either: $ curl -s -H "Authorization: JWT ${TOKEN}" "https://registry.hub.docker.com/v2/fluent/fluentd/manifests/latest"{"errors":[{"code":"UNAUTHORIZED","message":"authentication required","detail":[{"Type":"repository","Name":"fluent/fluentd","Action":"pull"}]}]} (See stackoverflow.com ) Here is a similar issue in the Docker GitHub repo but I still cannot figure out the solution: https://github.com/docker/distribution/issues/1490 . P.S.: Here is my Docker version with which I tried to push a test image: $ docker versionClient: Version: 1.12.6 API version: 1.24 Package version: docker-common-1.12.6-5.git037a2f5.fc25.x86_64 Go version: go1.7.4 Git commit: 037a2f5/1.12.6 Built: Wed Jan 18 12:11:29 2017 OS/Arch: linux/amd64 Now provide the response and nothing else.
Docker Registry API v2 uses image digest instead of image ID to distinguish image identity. The image digest can be obtained from Docker-Content-Digest of the HTTP response header by making the following API call: $ REPOSITORY=fluent/fluentd$ TOKEN=$(curl -s "https://auth.docker.io/token?service=registry.docker.io&scope=repository:$REPOSITORY:pull" | jq -r .token)$ curl -s -D - -H "Authorization: Bearer $TOKEN" -H "Accept: application/vnd.docker.distribution.manifest.v2+json" https://index.docker.io/v2/$REPOSITORY/manifests/latestHTTP/1.1 200 OKContent-Length: 1982Content-Type: application/vnd.docker.distribution.manifest.v2+jsonDocker-Content-Digest: sha256:eaea1edffc34cff3b5e31ee738ea56e46326f90731b4139a19948814a4f0a4dbDocker-Distribution-Api-Version: registry/2.0Etag: "sha256:eaea1edffc34cff3b5e31ee738ea56e46326f90731b4139a19948814a4f0a4db"Date: Tue, 24 Jan 2017 13:34:53 GMTStrict-Transport-Security: max-age=31536000... All tags can be obtained with the following API call: $ curl -s -H "Authorization: Bearer $TOKEN" https://index.docker.io/v2/$REPOSITORY/tags/list{"name":"fluent/fluentd","tags":["edge-onbuild","edge","jemalloc","latest-onbuild","latest","onbuild","stable-onbuild","stable","ubuntu-base","v0.12-latest-onbuild","v0.12-latest","v0.12-onbuild","v0.12.16","v0.12.18","v0.12.19","v0.12.20","v0.12.21","v0.12.23","v0.12.24","v0.12.26-2","v0.12.26-onbuild","v0.12.26","v0.12.27-onbuild","v0.12.27","v0.12.28-onbuild","v0.12.28","v0.12.29-onbuild","v0.12.29","v0.12.30-onbuild","v0.12.30","v0.12.31-onbuild","v0.12.31","v0.12","v0.14-latest-onbuild","v0.14-latest","v0.14-onbuild","v0.14.1","v0.14.10-onbuild","v0.14.10","v0.14.11-onbuild","v0.14.11","v0.14.2","v0.14.6","v0.14.8","v0.14"]} Based on the above, to find the same digest as a specific tag, it will be a script like the following. #!/bin/bashREPOSITORY=$1TARGET_TAG=$2# get authorization tokenTOKEN=$(curl -s "https://auth.docker.io/token?service=registry.docker.io&scope=repository:$REPOSITORY:pull" | jq -r .token)# find all tagsALL_TAGS=$(curl -s -H "Authorization: Bearer $TOKEN" https://index.docker.io/v2/$REPOSITORY/tags/list | jq -r .tags[])# get image digest for targetTARGET_DIGEST=$(curl -s -D - -H "Authorization: Bearer $TOKEN" -H "Accept: application/vnd.docker.distribution.manifest.v2+json" https://index.docker.io/v2/$REPOSITORY/manifests/$TARGET_TAG | grep Docker-Content-Digest | cut -d ' ' -f 2)# for each tagsfor tag in ${ALL_TAGS[@]}; do # get image digest digest=$(curl -s -D - -H "Authorization: Bearer $TOKEN" -H "Accept: application/vnd.docker.distribution.manifest.v2+json" https://index.docker.io/v2/$REPOSITORY/manifests/$tag | grep Docker-Content-Digest | cut -d ' ' -f 2) # check digest if [[ $TARGET_DIGEST = $digest ]]; then echo "$tag $digest" fidone The result is as follows: $ ./find_same_digest.sh fluent/fluentd latestlatest sha256:eaea1edffc34cff3b5e31ee738ea56e46326f90731b4139a19948814a4f0a4dbstable sha256:eaea1edffc34cff3b5e31ee738ea56e46326f90731b4139a19948814a4f0a4dbv0.12.31 sha256:eaea1edffc34cff3b5e31ee738ea56e46326f90731b4139a19948814a4f0a4dbv0.12 sha256:eaea1edffc34cff3b5e31ee738ea56e46326f90731b4139a19948814a4f0a4db If you want to check the digest of the local image, you can get it with docker images --digests : $ docker images --digests | grep fluentdfluent/fluentd latest sha256:eaea1edffc34cff3b5e31ee738ea56e46326f90731b4139a19948814a4f0a4db 1788ee7dcfcc 14 hours ago 35.41 MB
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/41808763', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2339010/']}
jdg_381779
stackexchange
llm_judgeable_groundtruth_similarity
1214518
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 G be a group of order $10$. Then which one satisfies?$(a)$ G is an abelian group $(b)$ G is a cyclic group $(c)$ there is a normal proper subgroup $(d)$ none of these Now provide the response and nothing else.
By Cauchy's theorem, any group of order $10$ contains an element of order $5$, which generates a subgroup of order $5$, which is of index $2$, and thus normal. As others above have indicated, the subgroup: $\langle (1\ 2\ 3\ 4\ 5), (2\ 5)(3\ 4)\rangle$ of $S_5$ has order $10$, and is non-abelian.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1214518', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/191884/']}
jdg_381780
stackexchange
llm_judgeable_groundtruth_similarity
384860
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: For which integers x, y is $2^x + 3^y$ a square of a rational number? (Of course $(x,y)=(0,1),(3,0)$ work) Now provide the response and nothing else.
Your definition of $S$ is a little ambiguous, as stated. I am going to assume that the following is meant: $S$ is the set of all points $x\in[0,1]$ such that $x=\sum_{n=1}^\infty\frac{d_n}{10^n}$ for some sequence of $d_n$ s with each $d_n\in\{4,7\}.$ We can then construct $S$ in a similar fashion to the famous Cantor ternary set . We define a sequence of sets $S_k$ recursively as follows: Let $S_0=[0,1]$ . Given $S_k$ , we define $S_{k+1}$ to be the points $x$ of $S_k$ such that $x=\sum_{n=1}^\infty\frac{d_n}{10^n}$ where each $d_n\in\{0,1,2,...,8,9\}$ and in particular $d_n\in\{4,7\}$ for all $1\le n\le k+1.$ For example: $$S_1=\left[\frac4{10},\frac5{10}\right]\cup\left[\frac7{10},\frac8{10}\right]$$ $$S_2=\left[\frac{44}{100},\frac{45}{100}\right]\cup\left[\frac{47}{100},\frac{48}{100}\right]\cup\left[\frac{74}{100},\frac{75}{100}\right]\cup\left[\frac{77}{100},\frac{78}{100}\right],$$ and so on. More generally, you should verify that each $S_k$ will be the disjoint union of $2^k$ closed intervals, each of length $10^{-k}$ . Hence, each $S_k$ has total length $2^k\cdot 10^{-k}=5^{-k}$ . As a union of finitely-many closed sets, each $S_k$ is closed. You should be able to see that $S$ is precisely the intersection of all the $S_k$ s. Why can we then conclude that $S$ is closed? $S$ is certainly not dense in $[0,1]$ , since it is a closed proper subset of $[0,1]$ . In fact, it is nowhere dense there, since it is closed, and contains no open set but the empty set. Indeed, if $U$ is a non-empty open set, then it contains an open interval $I$ of positive length, but we can make the total length of the $S_k$ as small as we like by taking $k$ large enough, so $I$ isn't contained in all the $S_k$ , whence $I$ can't be contained in $S$ , and so $U$ can't be contained in $S$ , either. To see that $S$ is in fact uncountable , let $f:\{4,7\}\to\{0,1\}$ be given by $f(4)=0,f(7)=1$ , and define a function $g$ on $S$ by $$g\left(\sum_{n=1}^\infty\frac{d_n}{10^n}\right)=\sum_{n=1}^\infty\frac{f(d_n)}{2^n}.$$ I leave it to you to show that $g$ maps $S$ bijectively to $[0,1]$ --you must show that $g$ is one-to-one, and maps $S$ into and onto $[0,1]$ --so is uncountable. Some basic knowledge of series will come in handy, here. To show that $S$ is perfect, you need to show that all points of $S$ are accumulation points. Take any point $x=\sum_{n=1}^\infty\frac{d_n}{10^n}$ in $S$ , and let $r>0$ . There exists $N$ large enough so that $\frac3{10^N}<r$ . (Why?) Let $b_n=d_n$ for all integers $n\ge1$ with $n\ne N$ , and let $b_N\in\{4,7\}$ with $b_N\ne d_N$ . Putting $$y=\sum_{n=1}^\infty\frac{b_n}{10^n},$$ it should then be clear that $y\in S,$ $y\ne x$ , and $|y-x|<r$ . Since $r>0$ was arbitrary, then $x$ is an accumulation point of $S$ . Since $x\in S$ was arbitrary, all points of $S$ are accumulation points. Once you've worked through the details of the above, test your understanding by adapting the arguments to show that the following set is uncountable, compact, perfect, and nowhere dense: Let $T$ be the set of all points $x$ in $[0,1]$ such that $x=\sum_{n=1}^\infty\frac{q_n}{4^n}$ for some sequence of $q_n$ s with each $q_n\in\{1,3\}$ .
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/384860', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/70520/']}
jdg_381781
stackexchange
llm_judgeable_groundtruth_similarity
34140847
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 multiple checkboxes and a button that has to be enabled only if at least one checkbox is selected <input type="checkbox">VALUE1<input type="checkbox">VALUE2<input type="checkbox">VALUE3<input type="checkbox">VALUE4<button>Proceed</button> How is this achieved using Angular2. P.S: found similar questions but not using Angular2. Now provide the response and nothing else.
One way is to use ngModel on each checkbox, then control the button's disabled property via a method that examines each checkbox model state: @Component({ template: ` <label *ngFor="let cb of checkboxes"> <input type="checkbox" [(ngModel)]="cb.state">{{cb.label}} </label> <p><button [disabled]="buttonState()">button</button> `})class App { checkboxes = [{label: 'one'},{label: 'two'}]; constructor() {} buttonState() { return !this.checkboxes.some(_ => _.state); }} Plunker
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/34140847', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1657309/']}
jdg_381782
stackexchange
llm_judgeable_groundtruth_similarity
3403986
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 I want to do is use one PC to test an application on another on the same 19.2.168.X.X I would like to make it seem like SOAP requests are coming from a variety of different PCs, just to make the applciations log file easier to read and I have been told that virtual IP Addresses are the way to go. So, how do I defien a range and then use them one by one in VB? (I guss that this is effectively IP header spooging?) Now provide the response and nothing else.
I believe there's even more efficient method, but for now, try from numpy import copynewArray = copy(theArray)for k, v in d.iteritems(): newArray[theArray==k] = v Microbenchmark and test for correctness: #!/usr/bin/env python2.7from numpy import copy, random, arangerandom.seed(0)data = random.randint(30, size=10**5)d = {4: 0, 9: 5, 14: 10, 19: 15, 20: 0, 21: 1, 22: 2, 23: 3, 24: 0}dk = d.keys()dv = d.values()def f1(a, d): b = copy(a) for k, v in d.iteritems(): b[a==k] = v return bdef f2(a, d): for i in xrange(len(a)): a[i] = d.get(a[i], a[i]) return adef f3(a, dk, dv): mp = arange(0, max(a)+1) mp[dk] = dv return mp[a]a = copy(data)res = f2(a, d)assert (f1(data, d) == res).all()assert (f3(data, dk, dv) == res).all() Result: $ python2.7 -m timeit -s 'from w import f1,f3,data,d,dk,dv' 'f1(data,d)'100 loops, best of 3: 6.15 msec per loop$ python2.7 -m timeit -s 'from w import f1,f3,data,d,dk,dv' 'f3(data,dk,dv)'100 loops, best of 3: 19.6 msec per loop
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3403986', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/192910/']}
jdg_381783
stackexchange
llm_judgeable_groundtruth_similarity
31189756
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 executing a file upload to the path: C:\Code\Portal\Portal\Files\CT\Test\Test\Lighthouse-2015_07_02_11_46_43_813.jpg But when I click on the file on the website I get a 404 error because it is trying to go to the path: C:\Code\Portal\Portal\Comment\CT\Test\Test\Lighthouse-2015_07_02_11_46_43_813.jpg 'Comment' is the name of the controller, but I am trying to get it to go to 'Files' when clicked, which is the name of the folder that holds the picture. This is the link for the file: <a target='_blank' href="@Url.Action(file.path)">@file.name</a> file.path specifies the path after '/comment/' . I am having trouble understanding how to make the comment part of the path disappear. Then I could just add 'Files/' to the file.path. If I do that now, then the path is 'comment/files' . Thanks! Now provide the response and nothing else.
By using User.getClass , you are referring to the class companion object that Scala by default creates for the case class, and not the case class itself. To get the class object of the case class, use classOf[User] . Alternatively, you could use Scala's reflection API to get the metadata of a case class, which gives you much more information: import scala.reflect.runtime.universe._def classAccessors[T: TypeTag]: List[MethodSymbol] = typeOf[T].members.collect { case m: MethodSymbol if m.isCaseAccessor => m}.toList Test in sbt console: scala> case class User(name: String, age: Int)defined class Userscala> classAccessors[User]res0: List[reflect.runtime.universe.MethodSymbol] = List(value age, value name)
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/31189756', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4661184/']}
jdg_381784
stackexchange
llm_judgeable_groundtruth_similarity
8972737
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 do I access the Symfony 2 container within a Unit test? My libraries need it so it's essential. The test classes extend \PHPUnit_Framework_TestCase so there is no container. Now provide the response and nothing else.
Support is now built into Symfony. See http://symfony.com/doc/master/cookbook/testing/doctrine.html Here's what you could do: namespace AppBundle\Tests;use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;class MyDatabaseTest extends KernelTestCase{ private $container; public function setUp() { self::bootKernel(); $this->container = self::$kernel->getContainer(); }} For a bit more modern and re-usable technique see https://gist.github.com/jakzal/a24467c2e57d835dcb65 . Note that using container in unit tests smells. Generally it means your classes depend on the whole container (whole world) and that is not good. You should rather limit your dependencies and mock them.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/8972737', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/283055/']}
jdg_381785
stackexchange
llm_judgeable_groundtruth_similarity
2585
Below is a question asked on the forum earthscience.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Odd question, but what data would be needed to to calculate how far winds will carry a strong odor (such as the smells of a restaurant, pizza parlor or burning wood/building? There is wind direction and wind speed. But how does one measure the strength of an odor and predict how far it will travel or how far the winds will carry it before it disappears? Now provide the response and nothing else.
The first problem to tackle is "what is an odor"? An odor is a chemical aerosol or gas, which are small molecules suspended in the atmosphere. To track the odors of pizza or burning wood you would first need to identify the molecules associated with the scent. One example is α-pinene , which is the molecule that gives pine trees their scent. Food cooking typically gives off other volatile organic compounds (VOCs) and the particular matter associated with it. VOCs physically and chemically combine to form more types of aerosols and there can also be increases in ozone. Meteorology, emissions sources, and atmospheric photochemistry are combined in chemical transport models (CTMs) so that the air quality can be predicted. One example is WRF-Chem , which is used for large regions and many sources. Another example is CALPUFF , which is better suited for near-source impacts and capturing the effects of complex terrain. The reason you want a model with chemistry is that molecules can be reactive and will change as they interact with other molecules turning them into things that no longer smell like pizza or wood burning. The reason you need a meteorological model is so that pollutants will be advected with the wind and interact with the moisture budget, solar radiation, terrain, etc. For large-scale plumes you can simulate your molecules as being emitted at a constant rate from a point source and see how this plume evolves with time. For smaller scale flows like a pizzeria, you may need use a model that can accommodate small scale features like buildings that will have an effect on atmospheric flows. Lastly, you'll also need to account for other emission sources as the perceived strength of the smell is also going to depend on what else you are smelling (e.g. car exhaust) and these other aerosols may be reactive or combined with the odors you are interested in tracking. Once you have done this you will have a time varying plume of "smell" as output from your model. This will likely be output as a number concentration of aerosol molecules per unit volume per grid box. To turn this into "odor strength" is probably a harder problem and one I am not familiar with. As a first order approximation though, wherever the plume is located, so is the smell; and the higher the concentration of molecules, the stronger the odor.
{}
{'log_upvote_score': 4, 'links': ['https://earthscience.stackexchange.com/questions/2585', 'https://earthscience.stackexchange.com', 'https://earthscience.stackexchange.com/users/945/']}
jdg_381786
stackexchange
llm_judgeable_groundtruth_similarity
19760829
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 dynamically create _id's for my Mongoose models by counting the documents in the db, and using that number to create the _id (assuming the first _id is 0). However, I can't get the _id to set from my values. Here's my code: //Schemasvar Post = new mongoose.Schema({ //_id: Number, title: String, content: String, tags: [ String ]});var count = 16;//Modelsvar PostModel = mongoose.model( 'Post', Post );app.post( '/', function( request, response ) { var post = new PostModel({ _id: count, title: request.body.title, content: request.body.content, tags: request.body.tags }); post.save( function( err ) { if( !err ) { return console.log( 'Post saved'); } else { console.log( err ); } }); count++; return response.send(post);}); I've tried to set the _id a number of different ways, but it's not working for me. Here's the latest error: { message: 'Cast to ObjectId failed for value "16" at path "_id"', name: 'CastError', type: 'ObjectId', value: 16, path: '_id' } If you know what's going on, please let me know. Now provide the response and nothing else.
You either need to declare the _id property as part of your schema (you commented it out), or use the _id option and set it to false (you're using the id option, which creates a virtual getter to cast _id to a string but still created an _id ObjectID property, hence the casting error you get). So either this: var Post = new mongoose.Schema({ _id: Number, title: String, content: String, tags: [ String ]}); Or this: var Post = new mongoose.Schema({ title: String, content: String, tags: [ String ]}, { _id: false });
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/19760829', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2802626/']}
jdg_381787
stackexchange
llm_judgeable_groundtruth_similarity
1365692
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'm not exactly sure how to get started computing the limit of the improper Riemann integral $$\lim_{\epsilon \rightarrow 0} \int_0^\infty \frac{\sin x}{x} \arctan\left(\frac{x}{\epsilon}\right)dx.$$ Using the result that $\int_0^\infty \frac{\sin x}{x} dx = \pi/2$, is there a way to interchange the limit and the integral to get $\pi^2/4$? Now provide the response and nothing else.
By the dominated convergence theorem$$\lim_{\epsilon \to 0} \int_0^\pi \frac{\sin x}{x} \arctan\frac{x}{\epsilon}\,dx=\frac{\pi}{2}\int_0^\pi \frac{\sin x}{x}\,dx.$$Now$$\int_\pi^\infty \frac{\sin x}{x}\,\arctan\frac{x}{\epsilon}\,dx=\frac{\pi}{2}\int_\pi^\infty \frac{\sin x}{x}\,dx+\int_\pi^\infty \frac{\sin x}{x}\Bigl(\arctan\frac{x}{\epsilon}-\frac{\pi}{2}\Bigr)\,dx.$$Let's stimate the second integral:$$\Bigl|\arctan\frac{x}{\epsilon}-\frac{\pi}{2}\Bigr|=\int_{x/\epsilon}^\infty\frac{dt}{1+t^2}\le\frac{\epsilon}{x},$$and$$\int_\pi^\infty \Bigl|\frac{\sin x}{x}\Bigl(\arctan\frac{x}{\epsilon}-\frac{\pi}{2}\Bigr)\Bigr|\,dx\le\epsilon\int_\pi^\infty\frac{|\sin x|}{x^2}\,dx.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1365692', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/41421/']}
jdg_381788
stackexchange
llm_judgeable_groundtruth_similarity
1462
Below is a question asked on the forum quantumcomputing.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: A string of $n$ qutrits has a state-space spanned by the $3^n$ different states $\lvert x \rangle $ for strings $x \in \{0,1,2\}^n$ (or $x \in \{-1,0,+1\}^n$, equivalently), while $n $ qubits can only represent $2^n$ computational basis states. According to the Wikipedia article on qutrits , "qutrits ... are more robust to decoherence under certain environmental interactions". Does the increase of possible simultaneous states represented, result in robustness to decoherence? Now provide the response and nothing else.
No , a superposition of two different states is a completely different beast than a mixture of the same states.While it may appear from your example that $\rho_1$ and $\rho_2$ produce the same measurement outcomes (and that is indeed the case), as soon as you measure in a different basis they will give measurably different results . A "superposition" like $\newcommand{\up}{|\!\!\uparrow\rangle}\newcommand{\down}{|\!\!\downarrow\rangle}|\psi\rangle=\frac{1}{\sqrt2}(\up+\down)$ is a pure state . This means that it is a completely characterised state.In other words, there is no amount of information that, added to its description, could make it "less undetermined".Note that every pure state can be written as superposition of other pure states.Writing a given state $|\psi\rangle$ as a superposition of other states is literally the same thing as writing a vector $\boldsymbol v$ in terms of some basis: you can always change the basis and find a different representation of $\boldsymbol v$. This is in direct contrast to a mixed state like $\rho_1$ in your question.In the case of $\rho_1$, the probabilistic nature of the outcomes depends on our ignorance about the state itself . This means that, in principle, it is possible to acquire some additional information that will tell us whether $\rho_2$ is indeed in the state $\up$ or in the state $\down$. A mixed state cannot, in general, be written as a pure state.This should be clear from the above physical intuition: mixed states represent our ignorance about a physical state, while pure states are completely defined states, which just so happen to still give probabilistic outcomes due to the way quantum mechanics work. Indeed, there is a simple criterion to tell whether a given (generally mixed) state $\rho$ can be written as $|\psi\rangle\langle\psi|$ for some (pure) state $|\psi\rangle$: computing its purity .The purity of a state $\rho$ is defined as $\operatorname{Tr} \,(\rho^2)$, and it is a standard result that the purity of state is $1$ if and only if the state is pure (and lesser than $1$ otherwise).
{}
{'log_upvote_score': 5, 'links': ['https://quantumcomputing.stackexchange.com/questions/1462', 'https://quantumcomputing.stackexchange.com', 'https://quantumcomputing.stackexchange.com/users/-1/']}
jdg_381789
stackexchange
llm_judgeable_groundtruth_similarity
20361428
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 just updated to rails 4.0.2 and I'm getting this warning: [deprecated] I18n.enforce_available_locales will default to true in the future. If you really want to skip validation of your locale you can set I18n.enforce_available_locales = false to avoid this message. Is there any security issue in setting it to false? Now provide the response and nothing else.
Important : Make sure your app is not using I18n 0.6.8, it has a bug that prevents the configuration to be set correctly . Short answer In order to silence the warning edit the application.rb file and include the following line inside the Rails::Application body config.i18n.enforce_available_locales = true The possible values are: false : if you want to skip the locale validation don't care about locales true : if you want the application to raise an error if an invalid locale is passed (or) want to default to the new Rails behaviors (or) care about locale validation Note: The old default behavior corresponds to false , not true . If you are setting the config.i18n.default_locale configuration or other i18n settings, make sure to do it after setting the config.i18n.enforce_available_locales setting. If your use third party gems that include I18n features, setting the variable through the Application config object, may not have an effect. In this case, set it directly to I18n using I18n.config.enforce_available_locales . Caveats Example require File.expand_path('../boot', __FILE__)# ...module YouApplication class Application < Rails::Application # ... config.i18n.enforce_available_locales = true # or if one of your gem compete for pre-loading, use I18n.config.enforce_available_locales = true # ... endend Long answer The deprecation warning is now displayed both in Rails 4 (>= 4.0.2) and Rails 3.2 (>= 3.2.14). The reason is explained in this commit . Enforce available locales When I18n.config.enforce_available_locales is true we'll raise an I18n::InvalidLocale exception if the passed locale is unavailable. The default is set to nil which will display a deprecation error. If set to false we'll skip enforcing available locales altogether (old behaviour). This has been implemented in the following methods : I18n.config.default_locale= I18n.config.locale= I18n.translate I18n.localize I18n.transliterate Before this change, if you passed an unsupported locale, Rails would silently switch to it if the locale is valid (i.e. if there is a corresponding locale file in the /config/locales folder), otherwise the locale would default to the config.i18n.default_locale configuration (which defaults to :en). The new version of the I18n gem, forces developers to be a little bit more conscious of the locale management. In the future, the behavior will change and if a locale is invalid, the Rails app will raise an error. In preparation of such change (that may potentially break several applications that until today were relying on silent defaults), the warning is forcing you to explicitly declare which validation you want to perform, during the current transition period. To restore the previous behavior, simply set the following configuration to false config.i18n.enforce_available_locales = false otherwise, set it to true to match the new Rails defaults or if you want to be more rigid on domain validation and avoid switching to the default in case of invalid locale. config.i18n.enforce_available_locales = true Caveat If you are setting the config.i18n.default_locale configuration or using any of the previously mentioned methods ( default_locale= , locale= , translate , etc), make sure to do it after setting the config.i18n.enforce_available_locales setting. Otherwise, the deprecation warning will keep on popping up. (Thanks Fábio Batista ). If you use third party gems that include I18n features, setting the variable through may not have effect. In fact, the issue is the same as described in the previous point, just a little bit harder to debug. This issue is a matter of precedence. When you set the config in your Rails app, the value is not immediately assigned to the I18n gem. Rails stores each config in an internal object, loads the dependencies (Railties and third party gems) and then it passes the configuration to the target classes. If you use a gem (or Rails plugin) that calls any of the I18n methods before the config is assigned to I18n, then you'll get the warning. In this case, you need to skip the Rails stack and set the config immediately to the I18n gem by calling I18n.config.enforce_available_locales = true instead of config.i18n.enforce_available_locales = true The issue is easy to prove. Try to generate a new empty Rails app and you will see that setting config.i18n in the application.rb works fine. If in your app it does not, there is an easy way to debug the culprit. Locate the i18n gem in your system, open the i18n.rb file and edit the method enforce_available_locales! to include the statement puts caller.inspect . This will cause the method to print the stacktrace whenever invoked. You will be able to determine which gem is calling it by inspecting the stacktrace (in my case it was Authlogic). ["/Users/weppos/.rvm/gems/ruby-2.0.0-p247@application/gems/i18n-0.6.9/lib/i18n.rb:150:in `translate'", "/Users/weppos/.rvm/gems/ruby-2.0.0-p247@application/gems/authlogic-3.1.0/lib/authlogic/i18n/translator.rb:8:in `translate'", "/Users/weppos/.rvm/gems/ruby-2.0.0-p247@application/gems/authlogic-3.1.0/lib/authlogic/i18n.rb:79:in `translate'", "/Users/weppos/.rvm/gems/ruby-2.0.0-p247@application/gems/authlogic-3.1.0/lib/authlogic/acts_as_authentic/email.rb:68:in `validates_format_of_email_field_options'", "/Users/weppos/.rvm/gems/ruby-2.0.0-p247@application/gems/authlogic-3.1.0/lib/authlogic/acts_as_authentic/email.rb:102:in `block in included'", "/Users/weppos/.rvm/gems/ruby-2.0.0-p247@application/gems/authlogic-3.1.0/lib/authlogic/acts_as_authentic/email.rb:99:in `class_eval'", "/Users/weppos/.rvm/gems/ruby-2.0.0-p247@application/gems/authlogic-3.1.0/lib/authlogic/acts_as_authentic/email.rb:99:in `included'", "/Users/weppos/.rvm/gems/ruby-2.0.0-p247@application/gems/authlogic-3.1.0/lib/authlogic/acts_as_authentic/base.rb:37:in `include'", "/Users/weppos/.rvm/gems/ruby-2.0.0-p247@application/gems/authlogic-3.1.0/lib/authlogic/acts_as_authentic/base.rb:37:in `block in acts_as_authentic'", "/Users/weppos/.rvm/gems/ruby-2.0.0-p247@application/gems/authlogic-3.1.0/lib/authlogic/acts_as_authentic/base.rb:37:in `each'", "/Users/weppos/.rvm/gems/ruby-2.0.0-p247@application/gems/authlogic-3.1.0/lib/authlogic/acts_as_authentic/base.rb:37:in `acts_as_authentic'", "/Users/weppos/Projects/application/app/models/user.rb:8:in `<class:User>'", "/Users/weppos/Projects/application/app/models/user.rb:1:in `<top (required)>'",
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/20361428', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2643172/']}
jdg_381790
stackexchange
llm_judgeable_groundtruth_similarity
491338
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In my regression problem I have numeric input columns "A", "B" and "C" and the numeric target "Target". The relationship is: The higher "C", the more impact has "B" - the lower "C" the more impact has "A" in order to predict "Target". Now that relationship is non-linear, but more like quadratic. Which regression models are in theory able to learn that kind of interaction relationships without manually adding interaction terms? Now provide the response and nothing else.
Any universal approximators can do it.You need a term like $A(\beta_A+\beta_{A\times C}\times C)$ to appear, so the interaction between $A$ and $C$ suffices. $$A\times C = \frac{(A+C)^2-A^2-C^2}{2}$$ If you have an universal approximator, it can (locally) approximate the quadratic form somewhere in its formulation, giving you the interaction without explicitly multiplying $A$ and $C$ . Then, the only thing that matters is selecting a universal approximator. Neural Networks are in general universal approximator, and so are kernel machines with infinite dimensional kernel spaces (like the radial basis function, for example) too. On neural networks, if you have as inputs $A,B,C$ , then with two hidden layers and the square as the activation function you already achieves the possibility of interactions. Consider the column vector $x = [A, B, C]$ : $$\hat y = W_2\sigma (W_1 x+b_1)+b_ 2$$ $W_1 x$ passes weighted sums of the initial features, $h_1 = \sigma(W_1 x+b_1)$ square them and finally $W_2h_1+b_ 2$ makes weighted sums of the squared items.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/491338', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/68386/']}
jdg_381791
stackexchange
llm_judgeable_groundtruth_similarity
43175529
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 update the version of make on my mac but am running into issues. The minimum project dependency is 4.1 but my version seems to be 3.81. I've updated Xcode to the latest version and installed the command line tools but it still seems to be the older version. Has anyone run into this issue or know of a way to resolve it? Now provide the response and nothing else.
Here is what I did, and it works on my MacOS: Step1: Install homebrew (installation command comes from https://brew.sh/ ): /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" Step2: Use homebrew to install make brew install make --with-default-names just incase it doesn't work, try this: brew install homebrew/dupes/make --with-default-names Step3: You need to change the default command to use correct make instead of the default one from your MacBook or Mac. For example, if you type make --version You will see: GNU Make 3.81Copyright (C) 2006 Free Software Foundation, Inc.This is free software; see the source for copying conditions.There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR APARTICULAR PURPOSE.This program built for i386-apple-darwin11.3.0 Which is the default path for default version. So, now, in your .bash_profile (which should be under your home dir /Users/your_name), add the following line: export PATH="/usr/local/bin:$PATH" Note: If you see the following message when you installed make: GNU "make" has been installed as "gmake". If you need to use it as "make", you can add a "gnubin" directory to your PATH from your bashrc like: PATH="/usr/local/opt/make/libexec/gnubin:$PATH" then instead run, export PATH="/usr/local/opt/make/libexec/gnubin:$PATH" Then source your .bash_profile. Now try to check your version: make --version It should show: GNU Make 4.2.1Built for x86_64-apple-darwin16.5.0Copyright (C) 1988-2016 Free Software Foundation, Inc.License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>This is free software: you are free to change and redistribute it.There is NO WARRANTY, to the extent permitted by law. Cheers.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43175529', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1527457/']}
jdg_381792
stackexchange
llm_judgeable_groundtruth_similarity
58496270
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 read the documentation but I can not figure out how to configure Traefik v2 to replace Nginx as a reverse proxy for web sites (virtual hosts) without involving Docker. Ideally there would be let'sencrypt https as well. I have a service running at http://127.0.0.1:4000 which I would like to reverse proxy to from http://myhost.com:80 This is the configuration i've come up with so far: [Global]checkNewVersion = true[log] level = "DEBUG" filePath = "log-file.log"[accessLog] filePath = "log-access.log" bufferingSize = 100[entrypoints] [entrypoints.http] address = ":80"[http] [http.routers] [http.routers.my-router] rule = "Host(`www.myhost.com`)" service = "http" entrypoint=["http"] [http.services] [http.services.http.loadbalancer] [[http.services.http.loadbalancer.servers]] url = "http://127.0.0.1:4000" Now provide the response and nothing else.
I figured it out, the first part to note is that in traefik v2 there are two types of configuration, static and dynamic. So I created two files, traefik.toml and traefik-dynamic.toml. contents of traefik.toml: [log] level = "DEBUG" filePath = "log-file.log"[accessLog] filePath = "log-access.log" bufferingSize = 100[providers] [providers.file] filename = "traefik-dynamic.toml"[api] dashboard = true debug = true[entryPoints] [entryPoints.web] address = ":80" [entryPoints.web-secure] address = ":443" [entryPoints.dashboard] address = ":8080"[certificatesResolvers.sample.acme] email = "[email protected]" storage = "acme.json" [certificatesResolvers.sample.acme.httpChallenge] # used during the challenge entryPoint = "web" traefik-dynamic.toml: [http] # Redirect to https [http.middlewares] [http.middlewares.test-redirectscheme.redirectScheme] scheme = "https" [http.routers] [http.routers.my-router] rule = "Host(`www.example.com`)" service = "phx" entryPoints = ["web-secure"] [http.routers.my-router.tls] certResolver = "sample" [http.services] [http.services.phx.loadbalancer] [[http.services.phx.loadbalancer.servers]] url = "http://127.0.0.1:4000"
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/58496270', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/41829/']}
jdg_381793
stackexchange
llm_judgeable_groundtruth_similarity
131350
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 solving a set of differential equations for the variables H(t), x(t) and a(t). Then I construct a function z(t) from these, and another function w(t) from z(t). w(t) contains terms such as the third time derivative of x(t) (x'''(t)), and it has some funny behaviour (see plot): even though z'(t) seems smooth, z''(t) and consequently w(t) has some jumps. Why does this happen? How can I fix it? Code: (*Parameters*)ti = 1;xp = 10;mp = (8*Pi)^(-1/2);mu = 10^(-5)*mp;(*Background potential*)V[x_, n_] := mu^2*x^n;(*Dynamical eqs*)eq1[x_, H_, t_, n_] := H^2 - 1/(3 mp^2)*(1/2 D[x, t]^2 + V[x, n])eq2[x_, H_, t_, n_] := D[x, {t, 2}] + 3 D[x, t]*H + D[V[x, n], x](*Solve the dynamical equations*)solution = NDSolve[ {eq1[x[t], H[t], t, 2] == 0, eq2[x[t], H[t], t, 2] == 0, xp - Sqrt[2/3]*mp*Log[ti] == x[ti], -Sqrt[2/3]*mp/ti == x'[ti], 1/(3*ti) == H[ti], H'[ti] == 1/3, a'[t]/a[t] == H[t]}, {H, x, a}, {t, 0.1, 10^8}, AccuracyGoal -> Infinity, MaxSteps -> Infinity];z[t_] = a[t]*x'[t]/H[t] /. solution;w[t_] = (D[z[t], {t, 2}]* (a[t]^2 /. solution) + z'[t]*(a'[t] /. solution)*(a[t] /. solution))/z[t];Plot[{z[t], z'[t], z''[t], w[t]}, {t, 1, 10}, PlotLegends -> "Expressions"] Plot produced: Now provide the response and nothing else.
It may be of interest to present a solution requiring minimal changes to the code in the question, namely adding a[ti] == 1 (so that the code runs on Ver 11.0.1; DSolve chooses a[ti] == 1 by default in earlier versions) and InterpolationOrder -> 5 (to eliminate the spiky behavior of some of the curves in the question, as I noted in an early comment). With these changes only, the curves are the same as in the solution by Michael E2 , apart from a small spike in w at about t == 3.4 (which can be eliminated with the Plot option PlotPoints -> 20 . Curves of the three functions obtained directly from NDSolve are, LogLogPlot[(H /. Flatten@solution)[t], {t, 1, 10^8}] LogLogPlot[(a /. Flatten@solution)[t], {t, 1, 10^8}] Plot[(x /. Flatten@solution)[t], {t, 1, 10^8}, PlotRange -> {-.05, .05}] The small PlotRange is used to make visible the late-time oscillations.
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/131350', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/44607/']}
jdg_381794
stackexchange
llm_judgeable_groundtruth_similarity
67475399
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 found by accident that the following compiles: #include <string>#include <iostream>class A{ int i{}; std::string s{}; public: A(int _i, const std::string& _s) : i(_i), s(_s) { puts("Called A(int, const std::string)"); }};A foo(int k, const char* cstr){ return {k, cstr}; // (*)}int main(){ auto a = foo(10, "Hi!"); return 0;} The line of interest is (*). I guess the function foo is equivalent to: A foo(int k, const char* str){ return A(k, cstr);} However, is there a special name for this mechanism in (*)? Or is it just the simple fact that the compiler knows which constructor to call due to the return type? Now provide the response and nothing else.
return {k, cstr}; means that {k, cstr} is the initializer for the return value. Also, it indicates "return an object of the function's return type initialized with k and cstr , which means that the exact behavior depends on the returned object's type". The return value can be initialized in two different ways: return A(k, cstr); - the return value is copy-initialized from k, cstr return {k, cstr}; - the return value is copy list initialized from the class A .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/67475399', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15347394/']}
jdg_381795
stackexchange
llm_judgeable_groundtruth_similarity
31517786
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 of CLBeacon objects which all have a property .proximity. I want to order the array by this property which contains the CLProximity enum. So I want all objects to be in order IMMEDIATE, NEAR, FAR, UNKNOWN. Is there a way to do this neatly without resorting to a bunch of if statements? Now provide the response and nothing else.
If you define a (computed read-only) property sortIndex of CLProximity extension CLProximity { var sortIndex : Int { switch self { case .Immediate: return 0 case .Near: return 1 case .Far: return 2 case .Unknown: return 3 } }} then you can sort an array of beacons with let sortedBeacons = sorted(beacons) { $0.proximity.sortIndex < $1.proximity.sortIndex } If .Unknown is the only CLProximity value that needs"special treatment" and all other possible values are in the desiredrelative order then you can simplify the property definition to extension CLProximity { var sortIndex : Int { return self == .Unknown ? Int.max : rawValue }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31517786', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/102315/']}
jdg_381796
stackexchange
llm_judgeable_groundtruth_similarity
13315585
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: writing things out helps me to understand better. I’m trying to figure out how (or the best way) to do this. I need to write a script that connects the language of a country to the particular country within a table. User clicks on a country name (td) Language list appears (in a td in a separate table) Language of that particular country and the country name is blue and bolded (active state) in both tables Current TD “active” state is returned to normal when user clicks on a different TD in the country table. Manually creating the table in HTML and using individual classes of each TD pair to associate the country to the language. Thing is, I’d have to write a code for each TD because of the classes. This works, but I only want the selected TDs to be "active" and the others to return to normal. CSS td {cursor:pointer;}td.active {color:blue;font-weight:bold;} HTML <table id=tbl-country><tr><td class=”esp”>Espana</td></tr><tr><td class=”france”>France</td> </tr><tr><td class=”italia”>Italy</td></tr></table><table id=tbl-language> <tr>< td class=”espanol">Espanol</td></tr> <tr> <td class=”francais”>Francais</td> </tr> <tr> <td class=”italiano”>Italiano</td></tr></table> JS $(document).ready(function(){ $(".tbl-language").hide(); $("#tbl-country td").click(function(){ $(".tbl-language").show(); }); $("td.espana").click(function(){ $(this).toggleClass("active"); $("td.espanol").toggleClass("active"); $("td.france").click(function(){ $(this).toggleClass("active"); $("td.francais").toggleClass("active"); }); $("td.italia").click(function(){ $(this).toggleClass("active"); $("td.italiano").toggleClass("active"); });}); Now provide the response and nothing else.
You need to pass the address of a void * variable to pthread_join -- it will get filled in with the exit value. That void * then should be cast back to whatever type was originally stored into it by the pthread_exit call: for(j = 0 ; j < i ; ++j) { void *returnValue; pthread_join( tid[j], &returnValue); /* BLOCK */ printf("%zd\n", (size_t)(off_t)returnValue);}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13315585', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/773202/']}
jdg_381797
stackexchange
llm_judgeable_groundtruth_similarity
198387
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 famous Green-Tao theorem says that there exist arbitrarily long sequences of primes in arithmetic progression.I am wondering: How dense can a subset $S \subset \mathbb{N}$ be and still avoidarbitrarily long sequences of elements of $S$ in arithmetic progression?To make this more precise (following a comment by Robert Israel), Q . What is the cardinality of the largest subset $S_n$ of $[1,n]=\{1,2,3,\ldots,n\}$ that avoids $k$-term arithmetic progressions of elements in $S_n$, as a function of $n$ and $k$? As $n \to \infty$, can the density be significantly more dense than the primes density, $n / \log_e n$? I suspect this is a well-studied question, in which case quotes and/or pointers would suffice. Thanks! Now provide the response and nothing else.
You are essentially asking for quantitative estimates on Szemerédi's theorem, which states that the largest subset of $[1,n]$ without a k-term arithmetic progression has size $o(n)$. To be precise, let us define $r_k(n)$ to be the largest subset of [1,n] with no k-term arithmetic progression. Then a construction due to Behrend (essentially projecting a high-dimensional sphere onto the integers) shows that $$r_3(n) = \Omega\left(n e^{-c \sqrt{\log n}}\right),$$while a result of Bloom (moderately improving on a result of Sanders), shows that$$r_3(n) = O\left(n \frac{(\log \log n)^4}{\log n}\right). $$For general $k$, the best known upper bound is due to Gowers and says that$$r_k(n) = O\left(\frac{n}{(\log \log n)^{c_k}}\right)$$for an appropriate $c_k$. Behrend's construction clearly provides a lower bound in this case as well, but may be improved a little by projecting a collection of concentric spheres. There is some evidence (see, for example, http://arxiv.org/pdf/1408.2568.pdf ) to believe that the lower bound is closer to the truth.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/198387', 'https://mathoverflow.net', 'https://mathoverflow.net/users/6094/']}
jdg_381798
stackexchange
llm_judgeable_groundtruth_similarity
1210787
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 the relation between shared object( .so ) file and object( .o ) file? can you please explain via example? Now provide the response and nothing else.
Let's say you have the following C source file, call it name.c #include <stdio.h>#include <stdlib.h>void print_name(const char * name){ printf("My name is %s\n", name);} When you compile it, with cc name.c you generate name.o . The .o contains the compiled code and data for all functions and variables defined in name.c, as well as index associated their names with the actual code. If you look at that index, say with the nm tool (available on Linux and many other Unixes) you'll notice two entries: 00000000 T print_name U printf What this means: there are two symbols (names of functions or variables, but not names of classes, structs, or any types) stored in the .o. The first, marked with T actually contains its definition in name.o . The other, marked with U is merely a reference . The code for print_name can be found here, but the code for printf cannot. When your actual program runs it will need to find all the symbols that are references and look up their definitions in other object files in order to be linked together into a complete program or complete library. An object file is therefore the definitions found in the source file, converted to binary form, and available for placing into a full program. You can link together .o files one by one, but you don't: there are generally a lot of them, and they are an implementation detail. You'd really prefer to have them all collected into bundles of related objects, with well recognized names. These bundles are called libraries and they come in two forms: static and dynamic. A static library (in Unix) is almost always suffixed with .a (examples include libc.a which is the C core library, libm.a which is the C math library) and so on. Continuing the example you'd build your static library with ar rc libname.a name.o . If you run nm on libname.a you'll see this: name.o:00000000 T print_name U printf As you can see it is primarily a big table of object files with an index finding all the names in it. Just like object files it contains both the symbols defined in every .o and the symbols referred to by them. If you were to link in another .o (e.g. date.o to print_date ), you'd see another entry like the one above. If you link in a static library into an executable it embeds the entire library into the executable. This is just like linking in all the individual .o files. As you can imagine this can make your program very large, especially if you are using (as most modern applications are) a lot of libraries. A dynamic or shared library is suffixed with .so . It, like its static analogue, is a large table of object files, referring to all the code compiled. You'd build it with cc -shared libname.so name.o . Looking at with nm is quite a bit different than the static library though. On my system it contains about two dozen symbols only two of which are print_name and printf : 00001498 a _DYNAMIC00001574 a _GLOBAL_OFFSET_TABLE_ w _Jv_RegisterClasses00001488 d __CTOR_END__00001484 d __CTOR_LIST__00001490 d __DTOR_END__0000148c d __DTOR_LIST__00000480 r __FRAME_END__00001494 d __JCR_END__00001494 d __JCR_LIST__00001590 A __bss_start w __cxa_finalize@@GLIBC_2.1.300000420 t __do_global_ctors_aux00000360 t __do_global_dtors_aux00001588 d __dso_handle w __gmon_start__000003f7 t __i686.get_pc_thunk.bx00001590 A _edata00001594 A _end00000454 T _fini000002f8 T _init00001590 b completed.5843000003c0 t frame_dummy0000158c d p.5841000003fc T print_name U printf@@GLIBC_2.0 A shared library differs from a static library in one very important way: it does not embed itself in your final executable. Instead the executable contains a reference to that shared library that is resolved, not at link time, but at run-time. This has a number of advantages: Your executable is much smaller. It only contains the code you explicitly linked via the object files. The external libraries are references and their code does not go into the binary. You can share (hence the name) one library's bits among multiple executables. You can, if you are careful about binary compatibility, update the code in the library between runs of the program, and the program will pick up the new library without you needing to change it. There are some disadvantages: It takes time to link a program together. With shared libraries some of this time is deferred to every time the executable runs. The process is more complex. All the additional symbols in the shared library are part of the infrastructure needed to make the library link up at run-time. You run the risk of subtle incompatibilities between differing versions of the library. On Windows this is called "DLL hell". (If you think about it many of these are the reasons programs use or do not use references and pointers instead of directly embedding objects of a class into other objects. The analogy is pretty direct.) Ok, that's a lot of detail, and I've skipped a lot, such as how the linking process actually works. I hope you can follow it. If not ask for clarification.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1210787', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/144300/']}
jdg_381799
stackexchange
llm_judgeable_groundtruth_similarity
376689
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I took over 5 hours in sprint planning for a week long sprint. That seems like too much. We discuss things in detail in sprint planning, as most of team members are not senior. If we don't it will lead to mistakes during implementation and redesign during sprint. How do we deal with this? How much detail should I discuss during planning to fit it to just 2 hours long per a week sprint? Now provide the response and nothing else.
You're right - 5 hours in Sprint Planning for a 1 week Sprint does seem like a long time. The Scrum Guide time-boxes Sprint Planning to 8 hours for 1 month Sprints and says that "for shorter Sprints, the event is usually shorter". If you consider the ratio, a good target may be 2 hours of Sprint Planning for a 1 week Sprint, but there's no fixed timebox. So, how can you address a long Sprint Planning? As a Scrum Master, I would take these following steps: First, I'd work with the Product Owner to make sure that the Product Backlog is properly ordered. It is essential to effective Backlog Refinement and Sprint Planning to make sure that the most important work and their dependencies are at the top of the Product Backlog so that way the Scrum Team can focus their energies on defining, refining, and preparing the right work. Second, I'd make sure that the team is spending sufficient time on Backlog Refinement. The Scrum Guide indicates that refinement activities generally take no more than 10% of a Development Team's capacity. As an example, a Development Team of 4 working a standard 40 hour week should plan on about 16 hours of Backlog Refinement. This may be done individually, in small groups, or as a team. I've found that having a planned Backlog Refinement session for the team and then breaking out to do any research or investigation or planning tends to work the best. Third, make sure that the team realizes that they don't need to get every detail right in Sprint Planning. The goal of Sprint Planning is to produce a plan to completing the Sprint Goals. Don't try to do big design up front at a Sprint Planning session. Understand how different work fits in, dependencies, and objectives and use time outside of the Sprint Planning sessions with the right people to do the design, implementation, and testing required to deliver the work. More steps may fall out of these, but this would be a good starting point.
{}
{'log_upvote_score': 6, 'links': ['https://softwareengineering.stackexchange.com/questions/376689', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/200689/']}
jdg_381800
stackexchange
llm_judgeable_groundtruth_similarity
15758201
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 this table structure with data: INSERT INTO `test` (`id`, `email`, `id_user_ref`, `name`) VALUES(1, '[email protected]', NULL, 'Mike'),(2, '[email protected]', '1', 'Jhonny'),(3, '[email protected]', '1', 'Michael'),(4, '[email protected]', '2', 'Jorhe'),(5, '[email protected]', '3', 'Mia'); I need to count the id_user_ref for all users with this query: SELECT id, COUNT(name) AS refNr FROM test GROUP BY id_user_refHAVING id_user_ref IS NOT NULL; This works but the problem is that i need to display all results even if the count result is 0. I tried several left joins with the same table but without any success. The output should be: id refNr1 22 13 14 05 0 Now provide the response and nothing else.
Try this: SELECT t1.id, IFNULL(COUNT(t2.name), 0) AS refNr FROM test AS t1LEFT JOIN test AS t2 ON t1.id = t2.id_user_refGROUP BY t1.id; SQL Fiddle DEmo This will give you: | ID | REFNR |--------------| 1 | 2 || 2 | 1 || 3 | 1 || 4 | 0 || 5 | 0 |
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15758201', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/961154/']}
jdg_381801
stackexchange
llm_judgeable_groundtruth_similarity
1940528
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 a site currently (first one solo) and went to go make an index page. I have been attempting to follow django best practices as I go, so naturally I go search for this but couldn't a real standard in regards to this. I have seen folks creating apps to serve this purpose named various things (main, home, misc) and have seen a views.py in the root of the project. I am really just looking for what the majority out there do for this. The index page is not static, since I want to detect if the user is logged in and such. Thanks. Now provide the response and nothing else.
If all of your dynamic content is handled in the template (for example, if it's just simple checking if a user is present on the request), then I recommend using a generic view, specificially the direct to template view: urlpatterns = patterns('django.views.generic.simple', (r'^$', 'direct_to_template', {'template': 'index.html'}),) If you want to add a few more bits of information to the template context, there is another argument, extra_context , that you can pass to the generic view to include it: extra_context = { 'foo': 'bar', # etc}urlpatterns = patterns('django.views.generic.simple', (r'^$', 'direct_to_template', {'template': 'index.html', 'extra_context': extra_context }),)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1940528', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/230614/']}
jdg_381802
stackexchange
llm_judgeable_groundtruth_similarity
23376816
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 zip files uploaded to S3. I'd like to download them for processing. I don't need to permanently store them, but I need to temporarily process them. How would I go about doing this? Now provide the response and nothing else.
Because working software > comprehensive documentation : Boto2 import zipfileimport botoimport io# Connect to s3# This will need your s3 credentials to be set up # with `aws configure` using the aws CLI.## See: https://aws.amazon.com/cli/conn = boto.s3.connect_s3()# get hold of the bucketbucket = conn.get_bucket("my_bucket_name")# Get hold of a given filekey = boto.s3.key.Key(bucket)key.key = "my_s3_object_key"# Create an in-memory bytes IO bufferwith io.BytesIO() as b: # Read the file into it key.get_file(b) # Reset the file pointer to the beginning b.seek(0) # Read the file as a zipfile and process the members with zipfile.ZipFile(b, mode='r') as zipf: for subfile in zipf.namelist(): do_stuff_with_subfile() Boto3 import zipfileimport boto3import io# this is just to demo. real use should use the config # environment variables or config file.## See: http://boto3.readthedocs.org/en/latest/guide/configuration.htmlsession = boto3.session.Session( aws_access_key_id="ACCESSKEY", aws_secret_access_key="SECRETKEY")s3 = session.resource("s3")bucket = s3.Bucket('stackoverflow-brice-test')obj = bucket.Object('smsspamcollection.zip')with io.BytesIO(obj.get()["Body"].read()) as tf: # rewind the file tf.seek(0) # Read the file as a zipfile and process the members with zipfile.ZipFile(tf, mode='r') as zipf: for subfile in zipf.namelist(): print(subfile) Tested on MacOSX with Python3.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23376816', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1802143/']}
jdg_381803
stackexchange
llm_judgeable_groundtruth_similarity
3421167
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: Suppose X is a solution to following equation over positive definite matrices $A$ , $B$ $$XA+AX=2B$$ The following seems to hold ( numerically ) $$\text{tr}(X)=\text{tr}(A^{-1} B)$$ Can anyone see the way to prove this? Now provide the response and nothing else.
Since $A$ is positive definite, it has an inverse. Hence $$ +=2 \\ \Rightarrow A^{-1}XA +X=2A^{-1}B.$$ Taking $Tr(\cdot)$ on both sides leads to $$Tr(A^{-1}XA) + Tr(X) = 2Tr(A^{-1}B)\\\Rightarrow Tr(AA^{-1}X) + Tr(X) = 2Tr(A^{-1}B)\\\Rightarrow Tr(X) + Tr(X) = 2Tr(A^{-1}B) \\\Rightarrow Tr(X) = Tr(A^{-1}B) $$ The second line above is due to the rotation property of the $Tr(\cdot)$ operation.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3421167', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/998/']}
jdg_381804
stackexchange
llm_judgeable_groundtruth_similarity
1165658
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 obfuscating a library with ProGuard using the Ant task. I'm keeping particular class names and their method names when they have a particular annotation (@ApiAll) and I'm requesting that the InnerClasses attribute be kept: <keepattribute name="InnerClasses" /> <keep annotation="com.example.ApiAll"/> <keepclassmembers annotation="com.example.ApiAll"> <constructor access="public protected"/> <field access="public protected"/> <method access="public protected"/> <constructor access="protected"/> </keepclassmembers> If I check the mapping output file I can see that my inner class that has the annotation and it's members are keeping their names unobfuscated. However when I look in the generated jar file I can't find the class. Am I missing something? Why is the mapping telling me it's keeping this class when it's not? Now provide the response and nothing else.
You need to specify that you want to keep the inner class using the proper notation.In the proguard parlance, that means -keep class my.outer.Class$MyInnerClass . The key here is using the dollar-sign ( $ ) as the separator between inner and outer class. To do this, you also have to specify -keepattributes InnerClasses , so that the name MyInnerClass doesn't get obfuscated. These two settings together should allow your inner classes to be kept intact.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1165658', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5303/']}
jdg_381805
stackexchange
llm_judgeable_groundtruth_similarity
577230
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: When using grep with wildcards as in grep -in github */* for each directory grep shows lots of messages like grep: dir1/dir2: Is a directory How to suppress these messages? Using the flag --exclude-dir does't work to my surprise. I'm using grep (BSD grep) 2.5.1-FreeBSD on MacOS. Now provide the response and nothing else.
-d skip will make grep skip directories: grep -in -d skip github / According to this MaxOS man page that option should work for MacOS grep. If it turns out that this doesn't work with the MacOS grep you can install then Homebrew MacOS package manager and then use Homebrew to install the GNU version of grep , since GNU grep supports -d skip (though in that case you'll have to make the directory containing GNU grep the first in your PATH environmental variable).
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/577230', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/127813/']}
jdg_381806
stackexchange
llm_judgeable_groundtruth_similarity
358420
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I'm using this simple .htaccess file in a media uploads folder to allow the customer to see what's been uploaded. Options +IndexesIndexOptions +FancyIndexing Is it possible to add a directive to restrict access to only a few IP's? Generally we're not overly worried about the security of these, which is why we're not protecting them with a user/pass setup. However, a tiny bit of security wouldn't hurt :) Bonus Question... (really giving away my lack of apache config stuff here): Is it possible to have an if..else type setup so that IF the visitor doesn't have a recognised IP, they are re-directed to a specific page. Cheers!Ben Now provide the response and nothing else.
If you want to restrict by IP , simply add <Directory /path/to/the/folder> Options +Indexes IndexOptions +FancyIndexing Order deny,allow Deny from all Allow from X.X.X.X</Directory> If you have pattern in IP address, you could concise the rule also. Like if you want to allow IP begining with 192. then Allow from 192 will allow all the IP beginning with 192. Bonus question: you don't want to just prevent page loads from the external networks, but want to send them to a different page, mod_rewrite module of apache can come to rescue. Assuming your local net is 192.168.1.0/24: RewriteEngine OnRewriteCond %{REMOTE_ADDR} !^192\.168\.1RewriteCond !^/page_to_redirectRewriteRule .* /page_to_redirect [R,L] Play around with it.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/358420', 'https://serverfault.com', 'https://serverfault.com/users/109050/']}
jdg_381807
stackexchange
llm_judgeable_groundtruth_similarity
1606655
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: Show that: $$f\left(x\right) =\int^{x}_{0}\sin\left( e^{t^{2}}\right)d\,\mathrm{d}t$$ Is uniformly continuous I have tried to integrate it and bound it by using its limits, but a little unsure about what to do from there. Now provide the response and nothing else.
If the derivative is bounded then it is uniformly continuous, can you see how that would apply here? We have that the $\sin$ function is bounded by $1$, i.e. $|\sin(x)| \leq 1$. Using the fundamental theorem of calculus we obtain that $f'(x)=\sin(e^{x^2})$, and applying our knowledge of $\sin(x)$ we get $|\sin(e^{x^2})|\leq 1$. By the mean value theorem we get that $|\sin(e^{x^2})-\sin(e^{y^2})|\leq (1)|x-y|$. Hence our function is uniformly continuous since for any $\epsilon>0$ we only need to choose $\delta<\epsilon$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1606655', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/236210/']}
jdg_381808
stackexchange
llm_judgeable_groundtruth_similarity
6214902
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 set a timeout on an HTTP client that uses http.request with no luck. So far what I did is this: var options = { ... }var req = http.request(options, function(res) { // Usual stuff: on(data), on(end), chunks, etc...}/* This does not work TOO MUCH... sometimes the socket is not ready (undefined) expecially on rapid sequences of requests */req.socket.setTimeout(myTimeout); req.socket.on('timeout', function() { req.abort();});req.write('something');req.end(); Any hints? Now provide the response and nothing else.
2019 Update There are various ways to handle this more elegantly now. Please see some other answers on this thread. Tech moves fast so answers can often become out of date fairly quickly. My answer will still work but it's worth looking at alternatives as well. 2012 Answer Using your code, the issue is that you haven't waited for a socket to be assigned to the request before attempting to set stuff on the socket object. It's all async so: var options = { ... }var req = http.request(options, function(res) { // Usual stuff: on(data), on(end), chunks, etc...});req.on('socket', function (socket) { socket.setTimeout(myTimeout); socket.on('timeout', function() { req.abort(); });});req.on('error', function(err) { if (err.code === "ECONNRESET") { console.log("Timeout occurs"); //specific error treatment } //other error treatment});req.write('something');req.end(); The 'socket' event is fired when the request is assigned a socket object.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6214902', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/27958/']}
jdg_381809
stackexchange
llm_judgeable_groundtruth_similarity
12872204
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 creating a foreground service with a notification that appears in the notification bar when the service starts. If the service stops, the notification dismisses. My question is, is there a way to stop the service when "clear all notifications" or a dismiss of the notification (swipe) occurs? Updated to include implementation of notification: public int onStartCommand(Intent intent, int flags, int startId){ Log.d(CLASS, "onStartCommand service started."); if (getString(R.string.service_start_action) == intent.getAction()) { Intent intentForeground = new Intent(this, ServiceMain.class) .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); PendingIntent pendIntent = PendingIntent.getActivity(getApplicationContext(), 0, intentForeground, 0); Notification notification; Notification.Builder builder = new Notification.Builder(getApplicationContext()) .setSmallIcon(android.R.drawable.btn_star) .setTicker("Service started...") .setContentIntent(pendIntent) .setDefaults(Notification.DEFAULT_ALL) .setOnlyAlertOnce(true) .setOngoing(false); notification = builder.build(); notification.flags |= Notification.FLAG_FOREGROUND_SERVICE; startForeground(SERV_NOTIFY, notification); player.start(); } else { Log.d(CLASS, "onStartCommand unable to identify acition."); } return START_STICKY; } Now provide the response and nothing else.
The user is not allowed to swipe away a notification generated by an ongoing foreground service. Hence, stopForeground(false) first, which allows the notification to be swiped away by the user thereafter (at least on Lollipop+). For pre-Lollipop, you may have to stopForeground(true) , which stops foreground and removes the notification, then re-issue the notification with notificationManager.notify(yourNotificationID, yourNotificationObject) , so that your notification is visible but swipeable. Crucially, set up the notification object with a delete intent that is triggered when the user swipes it away. (new NotificationCompat.builder(this).setDeleteIntent(deletePendingIntent)).build() where deletePendingIntent is something like Intent deleteIntent = new Intent(this, YourService.class);deleteIntent.putExtra(someKey, someIntValue);PendingIntent deletePendingIntent = PendingIntent.getService(this,someIntValue, deleteIntent, PendingIntent.FLAG_CANCEL_CURRENT); When the user swipes it away, the intent with its extra is delivered to the service. Handle the delivered extra within onStartCommand , i.e. check that intent != null , intent.getExtras() != null , then extract the value from the extras bundle given someKey , and if it matches someIntValue , then call stopSelf() .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12872204', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/701560/']}
jdg_381810
stackexchange
llm_judgeable_groundtruth_similarity
14190410
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 developing an Android app in which I have to implement chat messaging . I would like one to one chat or a group chat . But I have no idea how to start. Please help me with this stuff. Any help will be appreciated. Now provide the response and nothing else.
A simple chat mechanism will have 2 basic functionalities Send the message to server (with info about the recipient) Receive the message from server (designated for my user name) First step is simple, we can create a web service which will accept the message with additional information about recipient(s). We can create it using any server side language. Step 2, that is fetching the message from server can be done using 2 techniques, Pull the message (using polling) from server, or Push the message from server to android phone Polling: In this, the android device will keep accessing server after a few seconds to check if there is a message available for user. This again can be implemented using a simple async task at the client side which will keep calling a web service after say 2-3 seconds. This is fine to use if we are planning to enable chatting only when user is accessing the app (no notifications like gmail or facebook), so that we can kill the polling service when not in use (otherwise it will eat up resources). Push notifications: a better option is to use push notifications. Android provide Google cloud messaging or GCM ( http://developer.android.com/google/gcm/index.html ) which will help achieve push from server easily. Otherwise you can try a third party API like urbanairship or pushwoosh depending on your requirement. Push notifications will help the user to receive messages even when he is not using the app. So in nutshell, a webservice to receive the messages and a push notification mechanism should be sufficient to implement a chat service in android. Little bit about UrbanAirship I used UA in one of my projects for push notifications as I needed to support both iOS and Android. If you just want to support Android GCM might also be a good option. Coming back to UA, check this for sample code and usage: https://docs.urbanairship.com/display/DOCS/Home The way it works is simple, when someone installs the app and is connected to internet, app registers itself to the UA service. A unique code is specified for each installed app (this is the time when you can capture the user name and unique code and store somewhere in your DB). Next UA provides an API using which you can push a message to designated recipient(s), using the unique codes which are available with UA. These messages can be received by android app and used as per the requirement. Even if the app is not running we can show a notification just like when we receive an email or a message
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14190410', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_381811
stackexchange
llm_judgeable_groundtruth_similarity
32574310
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 set the highlight color for a ListViewItem to be the same color as if the ListView is currently in focus even though it isn't. After setting the HideSelection property to False, when I selected an item and then focusing on another view, the color is grayed out. I want to disable this. How can I do this? Similar to this WPF-related question (including screenshots to demonstrate): WPF ListView Inactive Selection Color Now provide the response and nothing else.
Since Windows Forms ListView doesn't have SelectionBackColor or such property (as far as I know) I think the most simple way is: Setting the HideSelection property of the listview to true and then: private void listView1_SelectedIndexChanged(object sender, EventArgs e){ this.listView1.Items.Cast<ListViewItem>() .ToList().ForEach(item => { item.BackColor = SystemColors.Window; item.ForeColor = SystemColors.WindowText; }); this.listView1.SelectedItems.Cast<ListViewItem>() .ToList().ForEach(item => { item.BackColor = SystemColors.Highlight; item.ForeColor = SystemColors.HighlightText; });}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32574310', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5334496/']}
jdg_381812
stackexchange
llm_judgeable_groundtruth_similarity
60203
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: For a given sequence of real numbers $(x_n)_{n=1}^\infty \subset [0,1]$, let $A(a,b,N)$ to be the number of terms $x_n$ of the sequence up to index $N$ such that $a \leq x_n \leq b$. A sequence of real numbers $(x_n)_{n=1}^\infty$ is said to be uniformly distributed modulo 1 if $\displaystyle \frac{A(a,b,N)}{N}$ tends to $b-a$ as $N \rightarrow \infty$ for every $0 \leq a < b \leq 1$. My question concerns whether or not the following sequence is uniformly distributed. Define $x_n = H_n - \lfloor H_n \rfloor$, where $H_n = \displaystyle \sum_{k=1}^n \frac{1}{k}$ is the $n$-th harmonic number. Then is $(x_n)_{n=1}^\infty$ uniformly distributed? What if we instead defined $x_n$ to be a random element of the interval $[H_{n-1}, H_n]$ with respect to a uniform distribution, and ask if the random sequence $(x_n - \lfloor x_n \rfloor)_{n=1}^\infty$ is uniformly distributed? Now provide the response and nothing else.
$H_n$ is a asymptotic to $\log n+\gamma+O(1/n)$. This means that the values of $x_n$ for $e^k \leq n\leq e^{k+1/2}$ all fall into the same interval of length about $1/2$. The sequence is not equidistributed (the proportion of $x_n$ in that interval for $n\leq e^k$ and for $n\leq e^{k+1/2}$ differ much).
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/60203', 'https://mathoverflow.net', 'https://mathoverflow.net/users/10898/']}
jdg_381813
stackexchange
llm_judgeable_groundtruth_similarity
2694582
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: Everyone learns about the two "special" right triangles at some point in their math education—the $45-45-90$ and $30-60-90$ triangles—for which we can calculate exact trig function outputs. But are there others? To be specific, are there any values of $y$ and $x$ such that: $y=\sin(x)$; $x$ (in degrees) is not an integer multiple of $30$ or $45$; $x$ and $y$ can both be written as radical expressions? By radical expression, I mean any finite formula involving only integers, addition/subtraction, multiplication/division, and $n$th roots. [Note that I require $x$ also be a radical expression so that we can't simply say "$\arcsin(1/3)$" or something like that as a possible value of $x$, which would make the question trivial.] If yes, are they all known and is there a straightforward way to generate them? If no, what's the proof? Now provide the response and nothing else.
There is$$\cos\frac{\pi}5=\frac{\sqrt5+1}4$$and similar for cosines and sines of multiples of this. Gauss proved thatone can find expressions for $\cos \pi/p$ involving iterated square rootswhere $p$ is prime if and only if $p$ is a Fermat prime (of form $2^{2^k}+1$), so for $p=2$, $3$, $5$, $17$, $257$ and $65537$ (but to date no others are known).
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/2694582', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/477746/']}
jdg_381814
stackexchange
llm_judgeable_groundtruth_similarity
1572732
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 just had my first week of topology, and I have a question that is rather basic. Why must the empty set be an element of any given topology? (For reference, the definition of a topology T I am working with, for a set X: 1. X and the empty set must be in T. 2. the union of elements of any subset in T, is also in T. 3. the intersection of elements of any finite subcollection in T, is also in T.) Now provide the response and nothing else.
It's more convenient this way.$\def\less{\smallsetminus}$ Usually in math when you have definitions that involve the empty set, the reason they do is that it's more elegant, convenient, economical to phrase things this way. Suppose you didn't want to deal with the empty set. You could define topology to be a collection of nonempty subsets of X that satisfy a few axioms. But then your axioms would have to be more complicated and include special cases. You'd have to say that only a nonempty finite intersection of open sets is open. You could modify the 3rd axiom to say that. But the reason you need that axiom in the first place is that very frequently in proofs you take a few open sets, and rely on the fact that their intersection is still open (and therefore has some qualities useful to you). In the new version, every time you need to intersect two open sets in a proof, you'd have to list two cases: a) if they're disjoint, then their intersection is empty and therefore... b) if they're not disjoint, then their intersection is open and therefore... Your proofs would be longer and more tedious. Similarly, normally you define a subset $Y$ of $X$ to be closed if $X \less Y$ is open. Then under the usual definition the whole space $X$ is a closed set. There're many reasons why you want that to be the case and why that corresponds to the intuition of "closed set". But if you don't consider the empty set to be open by definition, you don't get $X$ to be closed. Again, you can patch it up by modifying the definition of closed set: "A subset $Y$ of $X$ is closed if $Y=X$ or $Y$ is the complement of an open set". This will work. But, again, your proofs will become more complicated: when you have a closed set $Y$ about which you know little, you can't just assume anymore that $X \less Y$ is open and work with that, now you have to consider two cases. These are just two examples, but there're more. Basically, it turns out that while making the empty set open by definition may not look a priori very natural to you, it makes all kinds of objects and properties "click together" more naturally and economically than otherwise.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1572732', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/276212/']}
jdg_381815
stackexchange
llm_judgeable_groundtruth_similarity
13772704
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 getting the following errors using some generic functions within OpenCV for Android 12-05 21:08:55.486: E/cv::error()(6658): OpenCV Error: Assertion failed (src.dims == 2 && info.height == (uint32_t)src.rows && info.width == (uint32_t)src.cols) in void Java_org_opencv_android_Utils_nMatToBitmap2(JNIEnv*, jclass, jlong, jobject, jboolean), file /home/oleg/sources/opencv/modules/java/generator/src/cpp/utils.cpp, line 10712-05 21:08:55.486: E/org.opencv.android.Utils(6658): nMatToBitmap catched cv::Exception: /home/oleg/sources/opencv/modules/java/generator/src/cpp/utils.cpp:107: error: (-215) src.dims == 2 && info.height == (uint32_t)src.rows && info.width == (uint32_t)src.cols in function void Java_org_opencv_android_Utils_nMatToBitmap2(JNIEnv*, jclass, jlong, jobject, jboolean)12-05 21:08:55.486: E/CameraBridge(6658): Mat type: Mat [ 144*192*CV_8UC3, isCont=true, isSubmat=false, nativeObj=0x1024c0, dataAddr=0x44783010 ]12-05 21:08:55.486: E/CameraBridge(6658): Bitmap type: 384*28812-05 21:08:55.486: E/CameraBridge(6658): Utils.matToBitmap() throws an exception: /home/oleg/sources/opencv/modules/java/generator/src/cpp/utils.cpp:107: error: (-215) src.dims == 2 && info.height == (uint32_t)src.rows && info.width == (uint32_t)src.cols in function void Java_org_opencv_android_Utils_nMatToBitmap2(JNIEnv*, jclass, jlong, jobject, jboolean) I'm not sure if this is the error itself or if it's caused by another problem. Now provide the response and nothing else.
The assertion error is telling you that one or more of the following tests is failing: src.dims == 2info.height == (uint32_t)src.rowsinfo.width == (uint32_t)src.cols I'm guessing info contains the dimensions of the destination bitmap. In that case, either your source Mat is not 2 dimensions or the dimensions of the destination bitmap don't match the dimensions of the source Mat. These two lines 12-05 21:08:55.486: E/CameraBridge(6658): Mat type: Mat [ 144*192*CV_8UC3, isCont=true, isSubmat=false, nativeObj=0x1024c0, dataAddr=0x44783010 ]12-05 21:08:55.486: E/CameraBridge(6658): Bitmap type: 384*288 suggest that your Mat is 144x192 and your bitmap is 384x288. It looks like one is portrait and the other landscape plus your bitmap is twice the resolution of your Mat.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13772704', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/568355/']}
jdg_381816
stackexchange
llm_judgeable_groundtruth_similarity
10423
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: I just studied about SURF and I'm going for its implementation, but I still didn't understand why we use descriptors. I understand what keypoints are and their purpose, but when we extract the keypoints than why do we need to use descriptors ? What is their importance and role in recognition? Now provide the response and nothing else.
One important thing to understand is that after extracting the keypoints, you only obtain information about their position , and sometimes their coverage area (usually approximated by a circle or ellipse) in the image. While the information about keypoint position might sometimes be useful, it does not say much about the keypoints themselves. Depending on the algorithm used to extract keypoint (SIFT, Harris corners, MSER), you will know some general characteristics of the extracted keypoints (e.g. they are centered around blobs, edges, prominent corners...) but you will not know how different or similar one keypoint is to the other. Here's two simple examples where only the position and keypoint area will not help us: If you have an image A (of a bear on a white background), and another image B, exact copy of A but translated for a few pixels: the extracted keypoints will be the same (on the same part of that bear). Those two images should be recognized as same, or similar. But, if the only information we have is their position, and that changed because of the translation, you can not compare the images. If you have an image A (let's say, of a duck this time), and another image B, exactly the same duck as in A except twice the size: the extracted keypoints will be the same (same parts of the duck). Those are also same (similar) images. But all their sizes (areas) will be different: all the keypoints from the image B will be twice the size of those from image A. So, here come descriptors : they are the way to compare the keypoints. They summarize, in vector format (of constant length) some characteristics about the keypoints. For example, it could be their intensity in the direction of their most pronounced orientation. It's assigning a numerical description to the area of the image the keypoint refers to. Some important things for descriptors are: they should be independent of keypoint position If the same keypoint is extracted at different positions (e.g. because of translation) the descriptor should be the same. they should be robust against image transformations Some examples are changes of contrast (e.g. image of the same place during a sunny and cloudy day) and changes of perspective (image of a building from center-right and center-left, we would still like to recognize it as a same building). Of course, no descriptor is completely robust against all transformations (nor against any single one if it is strong, e.g. big change in perspective). Different descriptors are designed to be robust against different transformations which is sometimes opposed to the speed it takes to calculate them. they should be scale independent The descriptors should take scale in to account. If the "prominent" part of the one keypoint is a vertical line of 10px (inside a circular area with radius of 8px), and the prominent part of another a vertical line of 5px (inside a circular area with radius of 4px) -- these keypoints should be assigned similar descriptors. Now, that you calculated descriptors for all the keypoinst, you have a way to compare those keypoints . For a simple example of image matching (when you know the images are of the same object, and would like to identify the parts in different images that depict the same part of the scene, or would like to identify the perspective change between two images), you would compare every keypoint descriptor of one image to every keypoint descriptor of the other image. As the descriptors are vectors of numbers, you can compare them with something as simple as Euclidian distance . There are some more complex distances that can be used as a similarity measure, of course. But, in the end, you would say that the keypoints whose descriptors have the smallest distance between them are matches , e.g. same "places" or "parts of objects" in different images. For more complex use of keypoints/descriptors, you should take a look at this question -- especially the "low-level local approach" in my answer and "Bag-of-words" approach in @Maurits answer. Also, links provided in those answers are useful.
{}
{'log_upvote_score': 6, 'links': ['https://dsp.stackexchange.com/questions/10423', 'https://dsp.stackexchange.com', 'https://dsp.stackexchange.com/users/5057/']}
jdg_381817
stackexchange
llm_judgeable_groundtruth_similarity
32569860
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Let's suppose I have the following variable: System.Net.HttpStatusCode status = System.Net.HttpStatusCode.OK; How can I check if this is a success status code or a failure one? For instance, I can do the following: int code = (int)status;if(code >= 200 && code < 300) { //Success} I can also have some kind of white list: HttpStatusCode[] successStatus = new HttpStatusCode[] { HttpStatusCode.OK, HttpStatusCode.Created, HttpStatusCode.Accepted, HttpStatusCode.NonAuthoritativeInformation, HttpStatusCode.NoContent, HttpStatusCode.ResetContent, HttpStatusCode.PartialContent};if(successStatus.Contains(status)) //LINQ{ //Success} None of these alternatives convinces me, and I was hoping for a .NET class or method that can do this work for me, such as: bool isSuccess = HttpUtilities.IsSuccess(status); Now provide the response and nothing else.
If you're using the HttpClient class, then you'll get a HttpResponseMessage back. This class has a useful property called IsSuccessStatusCode that will do the check for you. using (var client = new HttpClient()){ var response = await client.PostAsync(uri, content); if (response.IsSuccessStatusCode) { //... }} In case you're curious, this property is implemented as: public bool IsSuccessStatusCode{ get { return ((int)statusCode >= 200) && ((int)statusCode <= 299); }} So you can just reuse this algorithm if you're not using HttpClient directly. You can also use EnsureSuccessStatusCode to throw an exception in case the response was not successful.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/32569860', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2401769/']}
jdg_381818
stackexchange
llm_judgeable_groundtruth_similarity
1250935
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: Evaluate the integral $$\int\frac{1}{x^2\left(x^4+1\right)^{3/4}}\,dx$$ My Attempt: Let $x = \frac{1}{t}$. Then $dx = -\frac{1}{t^2}\,dt$. Then the integral converts to $$-\int \frac{t^3}{(1+t^4)^{3/4}}\,dt$$ Now Let $(1+t^4) = u$. Then $t^3\,dt = \frac{1}{4}du$. This changes the integral to $$\begin{align}-\frac{1}{4}\int t^{-3/4}\,dt &= -u^{1/4}+\mathcal{C}\\&= -\left(1+t^4\right)^{1/4}+\mathcal{C}\end{align}$$ So we arrive at the solution $$\int\frac{1}{x^2\left(x^4+1\right)^{3/4}}\,dx = - \left(\frac{1+x^4}{x^4}\right)^{1/4}+\mathcal{C.}$$ Question: Is there any other method for solving this problem? Now provide the response and nothing else.
The following method feels more systematic to me: $$\begin{align}\int\frac{\mathrm{d}x}{x^2\left(1+x^4\right)^{3/4}}&=\frac14\int\frac{4x^3\,\mathrm{d}x}{x^5\left(1+x^4\right)^{3/4}}\\&=\frac14\int\frac{\mathrm{d}t}{t^{5/4}\left(1+t\right)^{3/4}};~~~\small{x^4=t}\\&=\frac14\int\left(\frac{1+t}{t}\right)^{-3/4}\cdot\frac{1}{t^2}\,\mathrm{d}t\\&=-\frac14\int u^{-3/4}\,\mathrm{d}u;~~~\small{\frac{1+t}{t}=u}\\&=-\sqrt[4]{u}+\color{grey}{constant}\\&=-\sqrt[4]{\frac{1+t}{t}}+\color{grey}{constant}\\&=-\sqrt[4]{\frac{1+x^4}{x^4}}+\color{grey}{constant}\\&=-\frac{\sqrt[4]{1+x^4}}{x}+\color{grey}{constant}.\\\end{align}$$ But the result is of course the same.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1250935', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/14311/']}
jdg_381819
stackexchange
llm_judgeable_groundtruth_similarity
3977500
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 using the following PHP code to list all files and folders under the current directory: <?php $dirname = "."; $dir = opendir($dirname); while(false != ($file = readdir($dir))) { if(($file != ".") and ($file != "..") and ($file != "index.php")) { echo("<a href='$file'>$file</a> <br />"); } }?> The problem is list is not ordered alphabetically (perhaps it's sorted by creation date? I'm not sure). How can I make sure it's sorted alphabetically ? Now provide the response and nothing else.
The manual clearly says that: readdir Returns the filename of the next file from the directory. The filenames are returned in the order in which they are stored by the filesystem . What you can do is store the files in an array, sort it and then print it's contents as: $files = array();$dir = opendir('.'); // open the cwd..also do an err check.while(false != ($file = readdir($dir))) { if(($file != ".") and ($file != "..") and ($file != "index.php")) { $files[] = $file; // put in array. } }natsort($files); // sort.// print.foreach($files as $file) { echo("<a href='$file'>$file</a> <br />\n");}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3977500', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/377031/']}
jdg_381820
stackexchange
llm_judgeable_groundtruth_similarity
58595395
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 getting quite an unexpected behaviour using pandas' pd.to_datetime . My pd.Series is as follows: 0 2017-01-06 14:37:161 2017-01-27 00:00:002 2017-01-18 00:00:003 2017-01-26 00:00:004 None ... 454823 2019-10-22 11:20:03454824 None454825 2019-07-11 00:00:00454826 None454827 2019-07-15 00:00:00Name: colx, Length: 454828, dtype: object And when casting to datetime I'm getting: pd.to_datetime(df.colx, errors='coerce') InvalidIndexError: Reindexing only valid with uniquely valued Index objects While this seems to indicate that there are duplicate values in the index, I ran the following tests to check if that was the cause: all(df.colx.index == range(df.colx.shape[0]))# Truedf.index.duplicated().any()# False So apparently there aren't any duplicate indexes. What could be causing this error? Now provide the response and nothing else.
The error you are receiving isn't related to your Index . It's related to this issue which should have been fixed as of 0.25.0 . The issue was related to the following inconsistent handling of multiple null types when using pd.to_datetime import pandas as pdpd.core.algorithms.unique([pd.NaT, None])#array([NaT, None], dtype=object) # That is, `pd.NaT` and `None` are uniquepd.Index([pd.NaT, None]).is_unique#False # However, Index.unique considers them duplicated The handling of this different behavior should have been fixed with 0.25.0 . If it's still giving you a problem the solution is to ensure you have a single representation of null values in the column you need to convert. In this case you can .fillna with the datetime null value. pd.to_datetime(df.colx.fillna(pd.NaT), errors='coerce') pd.__version__#'0.25.0'pd.to_datetime([pd.NaT, None])#DatetimeIndex(['NaT', 'NaT'], dtype='datetime64[ns]', freq=None)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/58595395', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9698684/']}
jdg_381821
stackexchange
llm_judgeable_groundtruth_similarity
16080655
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 I call for getCurrentConditions it tries to return data before requestData has completed and therefore doesn't find data.currently. I am definately getting data returned from the URL, I have tried adding a timeout loop to wait for the XHR to load, but that just broke the script all together. I am kind of confused why the second function is not waiting for this.requestData(latitude, longitude); to finish before continuing. this.requestData = function(latitude, longitude) { request_url = self.API_ENDPOINT + api_key + '/' + latitude + ',' + longitude + '?units=auto'; var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if(xhr.readyState==4 && xhr.status==200) { content = xhr.responseText; if(content != '' && (content)) { return JSON.parse(content); } else { return false; } } } xhr.open('GET', 'proxy.php?url='+request_url, true); xhr.send(null);}/** * Will return the current conditions * * @param float $latitude * @param float $longitude * @return \ForecastIOConditions|boolean */this.getCurrentConditions = function(latitude, longitude) { data = this.requestData(latitude, longitude); if(data !== false) { return new ForecastIOConditions(data.currently); } else { return false; }}var forecast = new ForecastIO(api_key);var condition = forecast.getCurrentConditions(latitude, longitude); Now provide the response and nothing else.
Because ajax is asynchronous, means once the request is sent it will continue executing without waiting for the response. One easy solution is to turn off the asynchronous nature by passing the 3rd parameter to the .open() method as false, but it has drawbacks like the browser thread will be blocked till the request is completed means UI will remain unresponsive till the request is completed. xhr.open('GET', 'proxy.php?url='+request_url, false); The correct solution will be is to use a callback method this.requestData = function(latitude, longitude, callback) { request_url = self.API_ENDPOINT + api_key + '/' + latitude + ',' + longitude + '?units=auto'; var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if(xhr.readyState==4 && xhr.status==200) { content = xhr.responseText; if(content != '' && (content)) { callback(JSON.parse(content)); } else { callback(false); } } } xhr.open('GET', 'proxy.php?url='+request_url, true); xhr.send(null);}/** * Will return the current conditions * * @param float $latitude * @param float $longitude * @return \ForecastIOConditions|boolean */this.getCurrentConditions = function(latitude, longitude, callback) { this.requestData(latitude, longitude, function(data) { if(data !== false) { callback(ForecastIOConditions(data.currently)); } else { callback(false); } });}var forecast = new ForecastIO(api_key);forecast.getCurrentConditions(latitude, longitude, function(condition){ if(condition !== false) { } else { }});
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16080655', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1178638/']}
jdg_381822
stackexchange
llm_judgeable_groundtruth_similarity
7863618
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 limit the number of model Objects a user can create. I've tried the below but it is not working. I understand some changes have happened in rails 3.1 and not sure how to accomplish this now. class User < ActiveRecord::Base has_many :things, :limit => 5, :dependent => :destroy # This doesn't workendclass Things <ActiveRecord::Base belongs_to :userend Now provide the response and nothing else.
Try something like this: class User < ActiveRecord::Base has_many :thingsendclass Things <ActiveRecord::Base belongs_to :user validate :thing_count_within_limit, :on => :create def thing_count_within_limit if self.user.things(:reload).count >= 5 errors.add(:base, "Exceeded thing limit") end endend Edit : updated for Rails 3
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7863618', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/892583/']}
jdg_381823
stackexchange
llm_judgeable_groundtruth_similarity
38465146
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 an error that "The provided key element does not match the schema". uuid is my primary partition key. I also have a primary sort key for version . I figured I can use batchWrite ( docs ) to delete all items with same uuid . My ES6 code is as follows: delete(uuid) { const promise = new Promise(); const params = { RequestItems: { [this.TABLE]: [ { DeleteRequest: { Key: { uuid: uuid } } } ] } }; // this._client references the DocumentClient this._client.batchWrite(params, function(err, data) { if (err) { // this gets hit with error console.log(err); return promise.reject(err); } console.log(result); return promise.resolve(result); }); return promise;} Not sure why it is erroring on the key that is the primary. I have seen posts about needing other indexes for times when I am searching by something that isn't a key. But I don't believe that's the case here. Now provide the response and nothing else.
Here is the batch write delete request sample. This code has been tested and working fine. If you change this code for your requirement, it should work. Table Definition:- Bag - Table Name bag - Hash Key No partition key in 'Bag' table Batch Write Code:- var AWS = require("aws-sdk");AWS.config.update({ region : "us-west-2", endpoint : "http://localhost:8000"});var documentclient = new AWS.DynamoDB.DocumentClient();var itemsArray = [];var item1 = { DeleteRequest : { Key : { 'bag' : 'b1' } }};itemsArray.push(item1);var item2 = { DeleteRequest : { Key : { 'bag' : 'b2' } }};itemsArray.push(item2);var params = { RequestItems : { 'Bag' : itemsArray }};documentclient.batchWrite(params, function(err, data) { if (err) { console.log('Batch delete unsuccessful ...'); console.log(err, err.stack); // an error occurred } else { console.log('Batch delete successful ...'); console.log(data); // successful response }}); Output:- Batch delete successful ...{ UnprocessedItems: {} }
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/38465146', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/511501/']}
jdg_381824
stackexchange
llm_judgeable_groundtruth_similarity
3883627
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 would like to know if there is a nice proof of the fact that every continuous map $f:\mathbb{C}P(2) \to \mathbb{C}P(2)$ has a fixed point, without use of the Lefschetz fixed point theorem. Now provide the response and nothing else.
Through any two distinct points in $\mathbb{C}P^n$ there is a unique (complex) geodesic. Therefore from any fix point free self map $f$ , we have a 1 dimensional complex subbundle of the tangent bundle by taking the subspace above a point $p$ to be the tangent space of the geodesic from $p$ to $f(p)$ at $p$ . This implies that the total Chern class of $\mathbb{C}P^n$ has a linear factor. If $n=2$ this implies that the total Chern class $1+3x+3x^2$ has two real (integer) roots. However, this is easily checked to be false since the discriminant is negative. As a sanity check, this should be different if $n=3$ . In that case the total Chern class is $1+4x +6x^2 +4x^3$ and this equals $(2 x + 1) (2 x^2 + 2 x + 1)$ , as expected. I imagine if you are better with polynomials than I, you can get this to work for any even $n$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3883627', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_381825
stackexchange
llm_judgeable_groundtruth_similarity
30348356
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 came across this in our codebase: foreach (var evtType in EventLocator.GetTypes()) and remembering Shlemiel the painter's algorithm does the method EventLocator.GetTypes() get called on each loop or just the once? Now provide the response and nothing else.
The expession designating collection being iterated is conceptually captured into a local variable before the loop starts. It is executed only once. You can derive this fact just by logic. Imagine the source was an IEnumerable<T> that is stateful. How would you continue the loop if you discarded the old object and reexecuted the source expression? You can't index into a sequence.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30348356', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2366046/']}
jdg_381826
stackexchange
llm_judgeable_groundtruth_similarity
60994
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 want to grep smb.conf and see only lines which are not commented. Now provide the response and nothing else.
grep "^[^#;]" smb.conf The first ^ refers to the beginning of the line, so lines with comments starting after the first character will not be excluded. [^#;] means any character which is not # or ; . In other words, it reports lines that start with any character other than # and ; . It's not the same as reporting the lines that don't start with # and ; (for which you'd use grep -v '^[#;]' ) in that it also excludes empty lines, but that's probably preferable in this case as I doubt you care about empty lines. If you wanted to ignore leading blank characters, you could change it to: grep '^[[:blank:]]*[^[:blank:]#;]' smb.conf or grep -vxE '[[:blank:]]*([#;].*)?' smb.conf Or awk '$1 ~ /^[^;#]/' smb.conf
{}
{'log_upvote_score': 9, 'links': ['https://unix.stackexchange.com/questions/60994', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/17424/']}
jdg_381827
stackexchange
llm_judgeable_groundtruth_similarity
2928728
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: string = "abcd" I'm looking for the formula which gives all the possible substrings but the substrings are limited in length. For example all possible substrings for "abcd" are 4*(4+1)/2 = 10But here I'm looking for all the possible substrings which have a max length of 2,the result is 7 but what is the formula ? thanks a lot for your help EDIT: I'm interested of the number of substring possible, in order , with a max length of 2, for example"abcd" => a, b, c, d, ab, bc, cd => 7"1111" => 1, 1, 1, 1, 11, 11, 11 => 7 A comment from @lulu that makes my question more clear: I believe the OP is requiring the substring to consist of consecutive elements of the string. Furthermore, judging from the answer to my question about 1111, the OP isn't interested in the string itself...just in its start and end location Now provide the response and nothing else.
To sum up the discussion in the comments: the reference to substrings is misleading as the OP is not interested in the characters that make up the substring, only in the possible locations of their first and last elements. Thus, the question is asking "given two natural numbers $m≤n$ , how many pairs $(i,j)$ are possible with $1≤i<j≤n$ and $j-i≤m$ ?" Let $F(n,m)$ denote the desired answer. Example: for $m=2$ , there are $n$ places that might be the first element of a length $1$ substring, and there are $n-1$ that might be the first element of a continuous length $2$ substring. Thus $$F(n,2)=n+(n-1)=2n-1$$ In general, there are $n-(k-1)$ places that might be the start of a continuous length $k$ substring. Thus the answer is $$F(n,m)=n+(n-1)+\cdots + (n-(m-1))=m\times n -\sum_{i=0}^{m-1} i=m\times n-T_{m-1}$$ Where $T_i$ denotes the $i^{th}$ Triangular Number . Thus $$T_i=\frac {i(i+1)}2$$ Examples: $$F(n,2)=2n-T_1=2n-1$$ $$F(4,4)=4\times 4-T_3=16-6=10$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2928728', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/596554/']}
jdg_381828
stackexchange
llm_judgeable_groundtruth_similarity
33126159
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Code: Python version 2.7.x and airflow version 1.5.1 my dag script is this from airflow import DAGfrom airflow.operators import BashOperatorfrom datetime import datetime, timedeltadefault_args = {'owner': 'xyz','depends_on_past': False,'start_date': datetime(2015,10,13),'email': ['[email protected]'],'schedule_interval':timedelta(minutes=5),'email_on_failure': True,'email_on_retry': True,'retries': 1,'retry_delay': timedelta(minutes=5),}dag = DAG('testing', default_args=default_args)run_this_first = BashOperator(task_id='Start1',bash_command='date', dag=dag)for i in range(5): t = BashOperator(task_id="Orders1"+str(i), bash_command='sleep 5',dag=dag) t.set_upstream(run_this_first) From that you could see that I am creating a DAG with 6 tasks the first task(Start1) starts first after which all the other five tasks starts Currently I have given 5 minutes time delay between DAG's starting It has ran perfectly for all the six tasks the first type but after five minutes the DAG is not re-initiated It has been more then 1 hour still the DAG is not re-initiated I really don't know were I am wrong . It would be really nice if some one could point me out what is wrong .I tried clearing using airflow testing clear then to the same thing happen.It ran first instance then just stood there. The only thing the command line shows is Getting all instance for DAG testing When I change the position of the schedule_interval it just runs with out any schedule interval parallel.That is with in 5 minutes 300 or more task instance has been completed. There is no 5 minute schedule interval Code 2: from airflow import DAGfrom airflow.operators import BashOperatorfrom datetime import datetime, timedeltadefault_args = {'owner': 'xyz','depends_on_past': False,'start_date': datetime(2015,10,13),'email': ['[email protected]'],'email_on_failure': True,'email_on_retry': True,'retries': 1,'retry_delay': timedelta(minutes=5),}dag = DAG('testing',schedule_interval=timedelta(minutes=5),default_args=default_args)#Schedule hererun_this_first = BashOperator(task_id='Start1',bash_command='date', dag=dag)for i in range(5): t = BashOperator(task_id="Orders1"+str(i), bash_command='sleep 5',dag=dag) t.set_upstream(run_this_first) Now provide the response and nothing else.
For Code 2, I guess the reason why it runs every minute is: The start time is 2015-10-13 00:00 The schedule interval is 5 minutes Every heartbeat of scheduler(5 seconds by default), your DAG will be checked First check: start date(no last execution date found) + schedulerinterval < current time? If yes the DAG will be executed and lastexecution time will be recorded. (eg. 2015-10-13 00:00 + 5min < current?) Second check on next heartbeat: last execution time + schedulerinterval < current time? If so the DAG will be executed again. .... The solution is set the DAG start_date as datetime.now() - schedule_interval . And also if you want to debug: Setting the LOGGINGLEVEL to debug in settings.py Modify class method is_queueable() of airflow.models.TaskInstance to : def is_queueable(self, flag_upstream_failed=False): logging.debug('Checking whether task instance is queueable or not!') if self.execution_date > datetime.now() - self.task.schedule_interval: logging.debug('Too early to execute: execution_date {0} + task.schedule_interval {1} > datetime.now() {2}'.format(self.execution_date, self.task.schedule_interval, datetime.now())) return False ...
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33126159', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4251775/']}
jdg_381829
stackexchange
llm_judgeable_groundtruth_similarity
114280
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 know roughly how a turbine engine (let's say a gas turbine producing no jet thrust) is supposed to work: The compressor forces fresh air into a combustion chamber, where it reacts with fuel to become hot exhaust gas. On its way out of the engine, the exhaust gas drives a turbine, and the turbine both makes the compressor go, and has enough leftover torque to do useful work. However, how do the exhaust gases know they're supposed to push on the turbine blades to drive the shaft, rather than push back on the compressor blades to retard the drive shaft in equal measure? In a piston engine there are valves that force things to flow in the correct direction at the right times. But with the turbine engine everything is openly connected all the time. Shouldn't that mean that the pressure differential the compressor must work against is exactly the same as that which is available to drive the turbine? Something magical and irreversible seems to happen in the combustion chamber. The descriptions I can find that go deeper than the three-step explanation above all seem to jump directly to a very detailed model with lots of thermodynamics and fluid dynamics that make my head spin. Is there an idealized system with fewer variables that I could think of to convince myself we're not getting something for nothing here (e.g., might the working fluid be incompressible, or massless, or have infinite heat capacity or whatever)? Now provide the response and nothing else.
I just had an epiphany. The engine works because the turbine is "larger" than the compressor. For extreme simplicity, let's assume that the working fluid is incompressible and effectively massless (it has pressure, but its inertia is negligible compared to the pressure).Assume further that the actual combustion is so finely tuned that the pressure stays constant during the combustion -- the gas simply expands at constant pressure, doing work against its own pressure as it does so. Then the compressor and turbine really do operate across the same pressure differential, namely the difference between ambient pressure and pressure inside the combustion chamber. At both ends of the engine, the power delivered to (or taken from) the drive shaft is the (common) pressure difference times the volume flow through the compressor/turbine. At this ideal level they are both the same kind of thing, except that one of them runs in reverse. However, the torque is not necessarily the same. The turbine is constructed such that one revolution of the drive shaft will allow a certain volume of air to escape from the combustion chamber. (I suppose that is a matter of the turbine blades being mounted at a different angle than the compressor blades). At the other end of the shaft, one revolution of the shaft will push a certain smaller volume of air into the combustion chamber. It must be so because the gas expands during combustion. This difference in volume-per-revolution means that the same pressure difference translates to different torques at the two ends of the engine. As a completely idealized toy example we can imagine that the compressor and turbine are both made of the same kind of ideal reversible fan assemblies -- for each such unit, one crank of the handle will make a certain volume of air change places, and how hard the handle is to crank depends on the pressure difference. The units that make up the compressor are mounted such that turning the drive shaft clockwise corresponds to air moving into the engine; the ones that make up the turbine are mounted opposite. Since the pressure difference is the same everywhere, the torque output from one turbine unit can drive exactly one compressor unit. But there are more turbine units than compressor units, and the additional ones produce surplus torque that can do work. This corresponds to the fact that there's a net outflow of air from the combustion chamber, because new volumes of gas come into being as the fuel burns.
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/114280', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/10027/']}
jdg_381830
stackexchange
llm_judgeable_groundtruth_similarity
919230
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 am trying to solve the question: $\cos{z}+\sin{z}=2$ Where $z \in \mathbb{C}$ I think I know how to solve $\cos{z}+\sin{z}=-1$: $1+2\cos^2{\frac{z}{2}}-1+2\sin \frac{z}{2}\cos{\frac{z}{2}}=0\\2\cos{\frac{z}{2}}(\cos{\frac{z}{2}}+\sin{\frac{z}{2}})=0$ etc... (that is, if the double angle identity holds true when the 'angle' is a complex number - I might be wrong about this) My other methods involve: trying to substitute $\cos{z}=\frac{e^{iz}+e^{-iz}}{2}$ and $\sin{z}=\frac{e^{iz}-e^{-iz}}{2i}$. This seems to be the most obvious method, but I can't work out the next step after $$e^{iz}-e^{-iz}+(e^{iz}+e^{-iz})i=4i$$ substituting $2=2(\sin^2{z}+\cos^2{z})$ substituting $\sin{z}=\cos(\frac{\pi}{2}-z)$ (again, not really sure if this can be done) Now provide the response and nothing else.
Recall that the addition formula for cosines reads $$\cos(z+z')=\cos z\cos z'-\sin z\sin z',$$ and that, for $z'=-\pi/4$, one gets $$\cos(z-\pi/4)=(\cos z+\sin z)/\sqrt2.$$ Hence the equation to be solved is $$\cos(z-\pi/4)=\sqrt2.$$ To go further, consider $$u=\mathrm e^{\mathrm i(z-\pi/4)},$$ then $u\ne0$ and the equation above reads $$u+u^{-1}=2\sqrt2,$$ that is, $$u^2-2\sqrt2u+1=0=(u-\sqrt2)^2-1,$$ that is, $$u=\sqrt2\pm1.$$ Thus, the complex number $$\mathrm i(z-\pi/4)-\log(\sqrt2\pm1)$$ must be a multiple of $2\mathrm i\pi$, that is, finally, and since $\sqrt2\pm1$ are respective inverses, $$z=\pm\mathrm i\log(\sqrt2+1)+\pi/4+2n\pi,\qquad n\in\mathbb Z.$$ Note that here, $\log$ is the usual function logarithm defined on the positive real half-line.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/919230', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/151595/']}
jdg_381831
stackexchange
llm_judgeable_groundtruth_similarity
25174144
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So far, I have a div fixed to the bottom of the page, with the bottom margin set to a minus number, so as to hide most of it below the screen. I'd like to create a Jquery button that made it all slide up onto the page, but everything I have tried so far hasn't worked. I'm not so experienced with it, so I've probably been doing it worng. Anyway, here's my CSS: .foot { border-top: 1px solid #999999; position:fixed; width: 600px; z-index: 10000; text-align:center; height: 500px; font-size:18px; color: #000; background: #FFF; display: flex; justify-content: center; /* align horizontal */ border-top-left-radius:25px; border-top-right-radius:25px; right: 0; left: 0; margin-right: auto; margin-left: auto; bottom: -475px;} And my HTML: <div class="foot">Copyright 2014 &copy; Tom Gibbs web design. <div class="clocker">hi</div><br /><br />Line 1<br />Line 2<br />Line 3<br />Line 4</div> Code I already tried. It just made the div slide down off the page: <script>$(document).ready(function(){ $(".clocker").click(function(){ $(".foot").slideUp(2000); });});</script> Now provide the response and nothing else.
What if you had another class: .slide-up{ bottom: 0px !important;}.slide-down{ bottom: -475px !important;} which you could add on click: $(document).ready(function() { $('.foot').click(function() { if($('.foot').hasClass('slide-up')) { $('.foot').addClass('slide-down', 1000, 'easeOutBounce'); $('.foot').removeClass('slide-up'); } else { $('.foot').removeClass('slide-down'); $('.foot').addClass('slide-up', 1000, 'easeOutBounce'); } });}); Make sure you have jQuery UI imported first. Updated JSFiddle
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25174144', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3779981/']}
jdg_381832
stackexchange
llm_judgeable_groundtruth_similarity
32699
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Problem Consider two d x d complex matrices, R and S , whose entries lie in the unit disk: $\quad |R_{i,j}|<1 \quad$ and $\quad |S_{i,j}|<1 $. Say that R is constructed by randomly choosing complex numbers from the unit disk, but S is constructed as $\quad S_{i,j} = f(i/d,j/d)$ where $f(x,y)$ is a smooth function for $x,y \in [0,1]$, with $|f(x,y)|<1$. In other words, the entries of S are smooth functions of the indices (in the limit of large d ), but those of R are not. Question How do the trace norms $\quad ||R||=Tr[\sqrt{R^\dagger R}] \quad$ and $\quad ||S||=Tr[\sqrt{S^\dagger S}]$ of these matrices behave as $d \to \infty$ ? Numerical Evidence A few lines of Mathematica strongly suggest that $\quad ||R|| \propto d^{3/2}$ but $\quad ||S|| \propto d$ for large d . (The proportionality constants depend on the probability distribution used to pick numbers from the unit disk for R and the function $f(x,y)$ used to pick entries for S , respectively.) What explains this behavior? Addendum After Willie's excellent answer below, I thought I'd mention that it's really fast to see the scaling behavior once you discretize the function. Let $F$ be some matrix of discrete values for the function, and let $J_n$ be the $n \times n$ matrix with all elements equal to unity. $||F \otimes J_n|| = \mathrm{Tr} \sqrt {(F^\dagger \otimes J_n)( F \otimes J_n)} = \mathrm{Tr} \sqrt {(F^\dagger F) \otimes (J_n J_n)} = ||F|| \cdot ||J_n|| = n ||F||$ Basically, the idea is that once the dimension of $F$ is large enough to capture the important detail in the function, increasing the dimension is really just increasing the dimension of $J$. Now provide the response and nothing else.
To flesh out Helge's answer a bit before I go to bed: Assume that $f(x,y)$ is a smooth function on the unit square. Define the functions $f_n(x,y) = f(\frac{\lfloor nx \rfloor}{n}, \frac{\lfloor ny\rfloor}{n})$. This is a piecewise step function. Observe that the operator $S$ of dimension $d$ is the same if you define it relative to $f$ or $f_d$. It is elementary to show that $f_n\to f$ uniformly (as functions). Define an action of $f_n$ on $L^2[0,1]$ by $$ g(x) \mapsto \int_0^1 f_n(x,y)g(y) dy $$and note that for a $n$-vector $v = (v_1,\ldots, v_n)$ we can associate $$ g_v(x) = \sum v_i \chi_{[\frac{i-1}{n},\frac{i}{n})} $$ we observe that $$ f_n(g_v(x)) = \frac{1}{n} g_{Sv}(x)$$the $1/n$ factor coming from the fact that the length of the segment $[(i-1) / n, i/n)$ is $1/n$. Now consider $V^n$ as the subspace of $L^2[0,1]$ spanned by $\chi_{[\frac{i-1}{n},\frac{i}{n})}$. By definition $f_n$ annihilates its orthogonal complement, and $f_n$ restricted to $V^n$ is equivalent to a rescaled version of $S$, so in particular you have that the trace norms of $f_n$ (acting on $L^2$) is the same as $1/n$ times the trace norm of $S$ (acting on $\mathbb{R}^n$). To finish you just need to note that via some functional analysis voodoo the corresponding operators $f_n\to f$, and so the trace norms of $f_n$ converges. Therefore you have that $1/n$ times the trace norm of $S$ converges to a constant (which may be zero). Note that the regularity for $f$ is only needed in this last step, and you probably just need uniform continuity to assure that the operators converge in a strong enough sense. [Addendum: all the functional analysis voodoo you need (which is not very much for this problem) can be found in Reed & Simon, volume 1, chapter 6.]
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/32699', 'https://mathoverflow.net', 'https://mathoverflow.net/users/5789/']}
jdg_381833
stackexchange
llm_judgeable_groundtruth_similarity
3209829
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 i have a datatable dt and it has a column DateofOrder , DateofOrder07/01/201007/05/201007/06/2010 I want to format these dates in DateOfOrder column to this DateofOrder01/Jul/201005/Jul/201006/Jul/2010 Any suggestion.. Now provide the response and nothing else.
The smartest thing to do would be to make sure your DataTable is typed, and this column is of type DateTime. Then when you go to actually print the values to the screen, you can set the format at that point without mucking with the underlying data. If that's not feasible, here's an extension method I use often: public static void Convert<T>(this DataColumn column, Func<object, T> conversion){ foreach(DataRow row in column.Table.Rows) { row[column] = conversion(row[column]); }} You could use in your situation like: myTable.Columns["DateOfOrder"].Convert( val => DateTime.Parse(val.ToString()).ToString("dd/MMM/yyyy")); It only works on untyped DataTables (e.g. the column type needs to be object, or possibly string).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3209829', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/146857/']}
jdg_381834
stackexchange
llm_judgeable_groundtruth_similarity
23766658
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 been working on getting some distributed tasks working via RabbitMQ. I spent some time trying to get Celery to do what I wanted and couldn't make it work. Then I tried using Pika and things just worked, flawlessly, and within minutes. Is there anything I'm missing out on by using Pika instead of Celery? Now provide the response and nothing else.
What pika provides is just a small piece of what Celery is doing. Pika is Python library for interacting with RabbitMQ. RabbitMQ is a message broker; at its core, it just sends messages to/receives messages from queues. It can be used as a task queue, but it could also just be used to pass messages between processes, without actually distributing "work". Celery implements an distributed task queue, optionally using RabbitMQ as a broker for IPC. Rather than just providing a way of sending messages between processes, it's providing a system for distributing actual tasks/jobs between processes. Here's how Celery's site describes it: Task queues are used as a mechanism to distribute work across threads or machines. A task queue’s input is a unit of work, called a task, dedicated worker processes then constantly monitor the queue for new work to perform. Celery communicates via messages, usually using a broker to mediate between clients and workers. To initiate a task a client puts a message on the queue, the broker then delivers the message to a worker. A Celery system can consist of multiple workers and brokers, giving way to high availability and horizontal scaling. Celery has a whole bunch of functionality built-in that is outside of pika's scope. You can take a look at the Celery docs to get an idea of the sort of things it can do, but here's an example: >>> from proj.tasks import add>>> res = add.chunks(zip(range(100), range(100)), 10)()>>> res.get()[[0, 2, 4, 6, 8, 10, 12, 14, 16, 18], [20, 22, 24, 26, 28, 30, 32, 34, 36, 38], [40, 42, 44, 46, 48, 50, 52, 54, 56, 58], [60, 62, 64, 66, 68, 70, 72, 74, 76, 78], [80, 82, 84, 86, 88, 90, 92, 94, 96, 98], [100, 102, 104, 106, 108, 110, 112, 114, 116, 118], [120, 122, 124, 126, 128, 130, 132, 134, 136, 138], [140, 142, 144, 146, 148, 150, 152, 154, 156, 158], [160, 162, 164, 166, 168, 170, 172, 174, 176, 178], [180, 182, 184, 186, 188, 190, 192, 194, 196, 198]] This code wants to add every x+y where x is in range(0, 100) and y is in range(0,100) . It does this by taking a task called add , which adds two numbers, and distributing the work of adding 1+1 , 2+2 , 3+3 , etc, into chunks of 10, and distributing each chunk to as many Celery workers as there are available. Each worker will run add on its 10 item chunk, until all the work is complete. Then the results are gathered up by the res.get() call. I'm sure you can imagine a way to do this using pika, but I'm sure you can also imagine how much work would be required. You're getting that functionality out of the box with Celery. You can certainly use pika to implement a distributed task queue if you want, especially if you have a fairly simple use-case. Celery is just providing a "batteries included" solution for task scheduling, management, etc. that you'll have to manually implement if you decide you want them with your pika solution.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/23766658', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/81515/']}
jdg_381835
stackexchange
llm_judgeable_groundtruth_similarity
42632154
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So, I'm trying to protect the access to several routes by using guards. I'm using the following routes to do so : const adminRoutes : Routes = [ { path: 'admin', component: AdminComponent, canActivate: [ AuthGuardService ], children : [ { path: '', canActivateChild: [ AuthGuardService ], children: [ { path: 'edit', component: DashboardComponent}, { path: '', component: DashboardComponent} ] } ] }]; Here's a look at what AuthGuardService looks like import { Injectable } from '@angular/core';import {CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot} from "@angular/router";@Injectable()export class AuthGuardService implements CanActivate{ constructor(private router: Router) { } canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot){ console.log("Guarding..."); return this.sessionValid(); } canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot){ console.log("Guarding children..."); return this.canActivate(route, state); } sessionValid() : boolean { //tests }} When I try to access to '/admin' and '/admin/edit' with canActivate only ( canActivateChild is commented) the console displays Guarding... When I remove canActivate and bring canActivateChild back the console displays Guarding children... When I keep both, it goes back to displaying Guarding... .So, my question is what's the purpose of having canActivateChild when canActivate protects both the root element and the children ? PS : I get it that canActivateChild runs before the child route is activated. But what are the benefits of that ? Isn't keeping only one of them sufficient ? Now provide the response and nothing else.
Both are important because you may have differing requirements where a user can get to the root component, but may not meet conditions for child components. Example: You could have a situation where a user must be authenticated to navigate to the root component, but must have permission 'x' to get to child components. In cases like this, canActivateChild saves a lot of typing from having to add canActivate guards to each of the children. EDIT: For example, you may have an Admin Module where all routes need to be guarded against unauthorized entry: { path: 'admin', component: AdminComponent, canActivate: [ AuthGuardService ], children : [ { path: '', component: ..., }, { path: 'manage-users', component: ..., }, { path: 'manage-roles', component: ..., } ] } This would need to be protected from the top down. No unauthorized access to any of the routes, including the root and children. In this situation canActivate at the root level works great to protect everything. But you may also have times where you have a Feature module where only certain children need to be guarded: { path: 'featureA', component: ..., canActivateChild: [ AuthGuardService ], children : [ { path: 'manage-feature', component: ..., }, { path: 'manage-members', component: ..., } ], {path: 'featureB', component: ...} } In this situation, maybe all users need to get to the root components 'featureA' and 'featureB', but only certain users need to be able to navigate to the child routes of 'featureA'. In this case it is easier to use one guard at the root level to protect the children, but not the root itself. The alternative is to put canActivate guards on each child route, which could get tedious. It really all depends upon your requirements, but it can be nice to have both options of canActivate and canActivateChild .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/42632154', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5781747/']}
jdg_381836
stackexchange
llm_judgeable_groundtruth_similarity
26445
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: According to molecular orbital theory s and p orbitals can mix if they are close enough in energy to each other. For period 2 diatomics, this occurs for $\ce{Li}$, $\ce{Be}$, $\ce{B}$, $\ce{C}$ and $\ce{N}$ - in the case of oxygen and fluorine the s and p orbitals are two far apart in energy. The effect can be seen by realizing that s-p mixing causes the $2\sigma_\mathrm{g}$ orbital to be higher in energy than the $1\pi_\mathrm{u}$ orbital. My question is: Does the mixing of the s and p orbitals occur between the orbitals of one atom (basically hybridization right?) or does the s orbital of one atom mix with the p orbital of the other (and vice versa)? This has confused me because I realize that concept of hybridization is widely used and functions well so I initially believed that the mixing should occur in one atom - forming hybrid atomic orbitals - and then bonding. However, after I thought about it some more I began to doubt that this is the case. Firstly, the s and p orbitals on one atom do not have the correct symmetry to mix effectively (the s orbital would simultaneously constructively interference with one lobe of the p orbital and destructively interfere with the other). Also, the molecular orbital diagram of carbon monoxide reveals that s-p mixing must be occurring since the $3\sigma$ orbital is higher in energy than the $1\pi$ orbital. This also seems to contradict the idea that the s and p orbitals mix on the same atom because in $\ce{O_2}$ there is no s-p mixing so why would oxygen mix its s and p orbitals when it's bonding with carbon. Now provide the response and nothing else.
According to molecular orbital theory s and p orbitals can mix if they are close enough in energy to each other. We can make that statement a bit more general so that we can apply it to all orbitals, atomic and molecular, by saying, According to molecular orbital theory orbitals can mix if they are close enough in energy to each other, and have the same symmetry Does the mixing of the s and p orbitals occur between the orbitals of one atom (basically hybridization right?) or does the s orbital of one atom mix with the p orbital of the other (and vice versa)? Good question, you are really thinking about this! First off, yes, mixing of the s and p orbitals occurring between the orbitals of one atom is called hybridization. When I think of these problems I first, hybridize the atomic orbitals (s and p) on an atom to generate hybrid atomic orbitals second, mix these hybrid atomic orbitals that exist on separate atoms to form a bond, a molecular orbital But that's not how it really happens. It is important to realize that hybridization only occurs in response to some type of interaction between two atoms. In other words, only when atoms begin to approach and interact with one another does hybridization start to occur. When hybridization starts to occur, bonding between the atoms starts to occur at the same time. To first hybridize and then bond (like I think of it in my mind) is an artificial construct that allows me to sort things out. Hybridization on an atom and bonding between two atoms both occur simultaneously. the s and p orbitals on one atom do not have the correct symmetry to mix effectively (the s orbital would simultaneously constructively interference with one lobe of the p orbital and destructively interfere with the other). Yes they do. As this picture shows we can add and subtract an s and a p atomic orbital to form two $\ce{sp}$ hybridized atomic orbitals. picture source in $\ce{O2}$ there is no s-p mixing so why would oxygen mix its s and p orbitals when it's bonding with Carbon. I think they are leaving oxygen unhybridized. So, for example, they are mixing (adding and subtracting) a carbon $\ce{sp}$ orbital with an oxygen s orbital to form the $\ce{1\sigma}$ and $\ce{2\sigma}$ molecular orbitals in your MO diagram. Edit: Response to OP's comment Do you know why s-p mixing raises the energy of the $\ce{2σ_{g}}$ orbital? (it lowers the $\ce{1σ_{g}}$) Nice diagrams and a helpful explanation can be found here . Basically, It has to do with the symmetry of the orbitals, like I mentioned above. Look at your $\ce{1σ}$ orbital, when you add or subtract it with the $\ce{3σ}$ orbital, the symmetry is such that there is no constructive or destructive overlap. Therefore there is no interaction and there energies will not change. On the other hand, the symmetries of the $\ce{2σ}$ and $\ce{3σ}$ orbitals are such that they can constructively and destructively overlap. As a result they interact and their energies change, one is pushed up and one is pushed down.
{}
{'log_upvote_score': 5, 'links': ['https://chemistry.stackexchange.com/questions/26445', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/6925/']}
jdg_381837
stackexchange
llm_judgeable_groundtruth_similarity
15680422
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 the difference between thread state WAIT and thread state BLOCKED? The Thread.State documentation : Blocked A thread that is blocked waiting for a monitor lock is in this state. Waiting A thread that is waiting indefinitely for another thread to perform a particular action is in this state does not explain the difference to me. Now provide the response and nothing else.
A thread goes to wait state once it calls wait() on an Object. This is called Waiting State. Once a thread reaches waiting state, it will need to wait till some other thread calls notify() or notifyAll() on the object. Once this thread is notified, it will not be runnable. It might be that other threads are also notified (using notifyAll() ) or the first thread has not finished his work, so it is still blocked till it gets its chance. This is called Blocked State. A Blocked state will occur whenever a thread tries to acquire lock on object and some other thread is already holding the lock. Once other threads have left and its this thread chance, it moves to Runnable state after that it is eligible pick up work based on JVM threading mechanism and moves to run state.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/15680422', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1114773/']}
jdg_381838
stackexchange
llm_judgeable_groundtruth_similarity
45188798
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 was trying to get all the users which in radius for the user who made request. I created a gps(geometry type) to store latitude and longitude. I've used this code: SELECT * From UserAddresses WHERE ST_DWithin( (Select gps from useraddresses where ID=(Select UserAddressID FROM Users WHERE ID=1)), (Select gps from useraddresses WHERE ID IN (SELECT UserAddressID FROM Users WHERE ID!=1)), 1609*(Select DiscoveryDistance From Users WHERE ID=1),true) but it returns this error: ERROR: more than one row returned by a subquery used as an expression I know that this error comes from SELECT UserAddressID FROM Users WHERE ID!=1 part but I couldn't fixed it. All I want to do is compare GPS of ID=1 to all user and if they're in the radius get their data. Can anyone help me with the syntax? Now provide the response and nothing else.
Why not use the standard library? #include <bitset>int bits_in(std::uint64_t u){ auto bs = std::bitset<64>(u); return bs.count();} resulting assembler (Compiled with -O2 -march=native ): bits_in(unsigned long): xor eax, eax popcnt rax, rdi ret It is worth mentioning at this point that not all x86 processors have this instruction so (at least with gcc) you will need to let it know what architecture to compile for. @tambre mentioned that in reality, when it can, the optimiser will go further: volatile int results[3];int main(){ results[0] = bits_in(255); results[1] = bits_in(1023); results[2] = bits_in(0x8000800080008000); } resulting assembler: main: mov DWORD PTR results[rip], 8 xor eax, eax mov DWORD PTR results[rip+4], 10 mov DWORD PTR results[rip+8], 4 ret Old-school bit-twiddlers like me need to find new problems to solve :) Update Not everyone was happy that the solution relies on cpu help to compute the bitcount. So what if we used an autogenerated table but allowed the developer to configure the size of it? (warning - long compile time for the 16-bit table version) #include <utility>#include <cstdint>#include <array>#include <numeric>#include <bitset>template<std::size_t word_size, std::size_t...Is>constexpr auto generate(std::integral_constant<std::size_t, word_size>, std::index_sequence<Is...>) { struct popcount_type { constexpr auto operator()(int i) const { int bits = 0; while (i) { i &= i - 1; ++bits; } return bits; } }; constexpr auto popcnt = popcount_type(); return std::array<int, sizeof...(Is)> { {popcnt(Is)...} };}template<class T>constexpr auto power2(T x) { T result = 1; for (T i = 0; i < x; ++i) result *= 2; return result;}template<class TableWord>struct table { static constexpr auto word_size = std::numeric_limits<TableWord>::digits; static constexpr auto table_length = power2(word_size); using array_type = std::array<int, table_length>; static const array_type& get_data() { static const array_type data = generate(std::integral_constant<std::size_t, word_size>(), std::make_index_sequence<table_length>()); return data; };};template<class Word>struct use_table_word {};template<class Word, class TableWord = std::uint8_t>int bits_in(Word val, use_table_word<TableWord> = use_table_word<TableWord>()) { constexpr auto table_word_size = std::numeric_limits<TableWord>::digits; constexpr auto word_size = std::numeric_limits<Word>::digits; constexpr auto times = word_size / table_word_size; static_assert(times > 0, "incompatible"); auto reduce = [val](auto times) { return (val >> (table_word_size * times)) & (power2(table_word_size) - 1); }; auto const& data = table<TableWord>::get_data(); auto result = 0; for (int i = 0; i < times; ++i) { result += data[reduce(i)]; } return result;}volatile int results[3];#include <iostream>int main() { auto input = std::uint64_t(1023); results[0] = bits_in(input); results[0] = bits_in(input, use_table_word<std::uint16_t>()); results[1] = bits_in(0x8000800080008000); results[2] = bits_in(34567890); for (int i = 0; i < 3; ++i) { std::cout << results[i] << std::endl; } return 0;} Final Update This version allows the use of any number of bits in the lookup table and supports any input type, even if it's smaller than the number of bits in the lookup table. It also short-circuits if the high bits are zero. #include <utility>#include <cstdint>#include <array>#include <numeric>#include <algorithm>namespace detail { template<std::size_t bits, typename = void> struct smallest_word; template<std::size_t bits> struct smallest_word<bits, std::enable_if_t<(bits <= 8)>> { using type = std::uint8_t; }; template<std::size_t bits> struct smallest_word<bits, std::enable_if_t<(bits > 8 and bits <= 16)>> { using type = std::uint16_t; }; template<std::size_t bits> struct smallest_word<bits, std::enable_if_t<(bits > 16 and bits <= 32)>> { using type = std::uint32_t; }; template<std::size_t bits> struct smallest_word<bits, std::enable_if_t<(bits > 32 and bits <= 64)>> { using type = std::uint64_t; };}template<std::size_t bits> using smallest_word = typename detail::smallest_word<bits>::type;template<class WordType, std::size_t bits, std::size_t...Is>constexpr auto generate(std::index_sequence<Is...>) { using word_type = WordType; struct popcount_type { constexpr auto operator()(word_type i) const { int result = 0; while (i) { i &= i - 1; ++result; } return result; } }; constexpr auto popcnt = popcount_type(); return std::array<word_type, sizeof...(Is)> { {popcnt(Is)...} };}template<class T>constexpr auto power2(T x) { return T(1) << x;}template<std::size_t word_size>struct table { static constexpr auto table_length = power2(word_size); using word_type = smallest_word<word_size>; using array_type = std::array<word_type, table_length>; static const array_type& get_data() { static const array_type data = generate<word_type, word_size>(std::make_index_sequence<table_length>()); return data; }; template<class Type, std::size_t bits> static constexpr auto n_bits() { auto result = Type(); auto b = bits; while(b--) { result = (result << 1) | Type(1); } return result; }; template<class Uint> int operator()(Uint i) const { constexpr auto mask = n_bits<Uint, word_size>(); return get_data()[i & mask]; }};template<int bits>struct use_bits { static constexpr auto digits = bits;};template<class T>constexpr auto minimum(T x, T y) { return x < y ? x : y; }template<class Word, class UseBits = use_bits<8>>int bits_in(Word val, UseBits = UseBits()) { using word_type = std::make_unsigned_t<Word>; auto uval = static_cast<word_type>(val); constexpr auto table_word_size = UseBits::digits; constexpr auto word_size = std::numeric_limits<word_type>::digits; auto const& mytable = table<table_word_size>(); int result = 0; while (uval) { result += mytable(uval);#pragma clang diagnostic push#pragma clang diagnostic ignored "-Wshift-count-overflow" uval >>= minimum(table_word_size, word_size);#pragma clang diagnostic pop } return result;}volatile int results[4];#include <iostream>int main() { auto input = std::uint8_t(127); results[0] = bits_in(input); results[1] = bits_in(input, use_bits<4>()); results[2] = bits_in(input, use_bits<11>()); results[3] = bits_in(input, use_bits<15>()); for (auto&& i : results) { std::cout << i << std::endl; } auto input2 = 0xabcdef; results[0] = bits_in(input2); results[1] = bits_in(input2, use_bits<4>()); results[2] = bits_in(input2, use_bits<11>()); results[3] = bits_in(input2, use_bits<15>()); for (auto&& i : results) { std::cout << i << std::endl; } auto input3 = -1; results[0] = bits_in(input3); results[1] = bits_in(input3, use_bits<4>()); results[2] = bits_in(input3, use_bits<11>()); results[3] = bits_in(input3, use_bits<15>()); for (auto&& i : results) { std::cout << i << std::endl; } return 0;} example output: 77771717171732323232 The resulting assembly output for a call to bits_in(int, use_bits<11>()) for example, becomes: .L16: mov edx, edi and edx, 2047 movzx edx, WORD PTR table<11ul>::get_data()::data[rdx+rdx] add eax, edx shr edi, 11 jne .L16 Which seems reasonable to me.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/45188798', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3559801/']}
jdg_381839
stackexchange
llm_judgeable_groundtruth_similarity
533382
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 need to generate code for a method at runtime. It's important to be able to run arbitrary code and have a docstring. I came up with a solution combining exec and setattr , here's a dummy example: class Viking(object): def __init__(self): code = ''' def dynamo(self, arg): """ dynamo's a dynamic method! """ self.weight += 1 return arg * self.weight ''' self.weight = 50 d = {} exec code.strip() in d setattr(self.__class__, 'dynamo', d['dynamo'])if __name__ == "__main__": v = Viking() print v.dynamo(10) print v.dynamo(10) print v.dynamo.__doc__ Is there a better / safer / more idiomatic way of achieving the same result? Now provide the response and nothing else.
Based on Theran's code, but extending it to methods on classes: class Dynamo(object): passdef add_dynamo(cls,i): def innerdynamo(self): print "in dynamo %d" % i innerdynamo.__doc__ = "docstring for dynamo%d" % i innerdynamo.__name__ = "dynamo%d" % i setattr(cls,innerdynamo.__name__,innerdynamo)for i in range(2): add_dynamo(Dynamo, i)d=Dynamo()d.dynamo0()d.dynamo1() Which should print: in dynamo 0in dynamo 1
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/533382', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8206/']}
jdg_381840