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 | 20983 |
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:
Let's say I've gone and done a silly thing, such as using 'chsh' to change the root user's shell to a bad file path. Future logins to the root account will abruptly fail, citing /bin/whatever not being found, and boot you back out to the login screen. Barring a recovery mode or inserting a LiveCD to edit /etc/passwd, what are my options for getting my system back? Let's also assume (for fun?) that there are no other users in wheel. Thoughts?
Now provide the response and nothing else.
| When booting, append init=/bin/bash (or a path to any other functional shell) to your boot options - you will be dropped straight to a single user shell. You might need to do mount -o remount,rw / before modifying the /etc/passwd entry in that environment. After that, just reboot or do exec /sbin/init 3 . Just do not type exit or press Ctrl+D, as these would result in kernel panic*. One additional variation of this method might be necessary on some systems loaded in two-stage mode (with an initrd image). If you notice that the boot options contain init= and, most importantly, real_init= , then the place to put /bin/bash should be the latter parameter (i.e. real_init=/bin/bash ). * This is because in that environment, the shell is seen by the kernel as the init program - which is the only process that kernel knows - it represents a running system underneath to the kernel's eye. Suddenly ending that process, without telling the kernel to shutdown the system, must result in kernel panic. (Wouldn't you panic if suddenly everything around you went black and silent?) | {} | {'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/20983', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/10834/']} | jdg_381541 |
stackexchange | llm_judgeable_groundtruth_similarity | 12505892 |
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 just cleaning up some code we wrote a while back and noticed that for a udp socket, 0 is being treated as the connection closed. I'm quite sure this was the result of porting the same recv loop from the equivalent tcp version. But it makes me wonder. Can recv return 0 for udp? on tcp it signals the other end has closed the connection. udp doesn't have the concept of a connection so can it return 0? and if it can, what is it's meaning? Note: the man page in linux does not distinguish udp and tcp for a return code of zero which may be why we kept the check in the code.
Now provide the response and nothing else.
| udp doesn't have the concept of a connection so can it return 0? and if it can, what is it's meaning It means a 0-length datagram was received. From the great UNP : Writing a datagram of length 0 is acceptable. In the case of UDP, this results in an IP datagram containing an IP header (normally 20 bytes for IPv4 and 40 bytes for IPv6), an 8-byte UDP header, and no data. This also means that a return value of 0 from recvfrom is acceptable for a datagram protocol : It does not mean that the peer has closed the connection, as does a return value of 0 from read on a TCP socket. Since UDP is connectionless, there is no such thing as closing a UDP connection. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12505892', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/134702/']} | jdg_381542 |
stackexchange | llm_judgeable_groundtruth_similarity | 12123960 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
From the JavaDoc of TreeMap : Note that the ordering maintained by a sorted map (whether or not an explicit comparator is provided) must be consistent with equals if this sorted map is to correctly implement the Map interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Map interface is defined in terms of the equals operation, but a map performs all key comparisons using its compareTo (or compare) method, so two keys that are deemed equal by this method are, from the standpoint of the sorted map, equal. The behavior of a sorted map is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Map interface. Can some one give an concrete example to demonsrate the problem that might occur if ordering is not consistent with equals ? Take for example User defined class that has a natural ordering i.e it implements Comparable . Also do all internal classes in JDK maintain this invariant?
Now provide the response and nothing else.
| The contract of the Comparable interface allows for non-consistent behaviour: It is strongly recommended (though not required) that natural orderings be consistent with equals. So in theory, it is possible that a class in the JDK had a compareTo not consistent with equals . One good example is BigDecimal . Below is a contrived example of a comparator that is not consistent with equals (it basically says that all strings are equal). Output: size: 1 content: {a=b} public static void main(String[] args) { Map<String, String> brokenMap = new TreeMap<String, String> (new Comparator<String>() { @Override public int compare(String o1, String o2) { return 0; } }); brokenMap.put("a", "a"); brokenMap.put("b", "b"); System.out.println("size: " + brokenMap.size()); System.out.println("content: " + brokenMap);} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12123960', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1527084/']} | jdg_381543 |
stackexchange | llm_judgeable_groundtruth_similarity | 708 |
Below is a question asked on the forum hermeneutics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Leviticus 11:13-19 has a list of non-kosher birds that match a list in Deuteronomy 14:11-18 ( NJPS ): You may eat any clean bird. The following you may not eat: the eagle, the vulture, and the black vulture; the kite, the falcon, and the buzzard of any variety; every variety of raven; the ostrich, the nighthawk, the sea gull, and the hawk of any variety; the little owl, the great owl, and the white owl; the pelican, the bustard, and the cormorant; the stork, any variety of heron, the hoopoe, and the bat. My casual reading of both passages is that any bird not listed in these passages is kosher . (Which means birds that weren't known to Moses such as turkey and emu would be considered clean.) But the odd thing is that the other types of animals are divided based on certain physical characteristics. So verse 3 : "any animal that has true hoofs, with clefts through the hoofs, and that chews the cud—such you may eat." Verse 9 : "These you may eat of all that live in water: anything in water, whether in the seas or in the streams, that has fins and scales—these you may eat." Verse 21 : "But these you may eat among all the winged swarming things that walk on fours: all that have, above their feet, jointed legs to leap with on the ground." So if you find a new species of land animal or fish or insect, you can apply the rules and get an answer about whether it's kosher . What's going on with the list of birds that makes providing distinguishing characteristics unnecessary?
Now provide the response and nothing else.
| There is an obvious implied rule from the actual listed forbidden birds, that you can use to infer the rules: birds that eat seeds or insects are fine, birds that eat meat, fish, or carrion are not. It's basically an injunction against birds of prey, sea-birds, and carrion birds, and (I believe) this is how it is interpreted. So that if you ask is an emu ok, it probably is fine, because it is vegetarian. But an osprey would be forbidden, since it is a fish eating predator. | {} | {'log_upvote_score': 4, 'links': ['https://hermeneutics.stackexchange.com/questions/708', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/68/']} | jdg_381544 |
stackexchange | llm_judgeable_groundtruth_similarity | 291173 |
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 $B, C, D, E$ are sets Prove/Disprove: $(B \backslash C)\backslash (D\backslash E) = (B\backslash D)\backslash (C\backslash E)$ Any help would be much appreciated
Now provide the response and nothing else.
| These are fairly complicated-looking sets, so it may be easier to try to prove equality and see whether anything goes wrong. Suppose that $x\in(B\setminus C)\setminus(D\setminus E)$. Then $x\in B\setminus C$, and $x\notin D\setminus E$. From the fact that $x\in B\setminus C$ we conclude that $x\in B$ and $x\notin C$. From the fact that $x\notin D\setminus E$ we conclude that either $x\notin D$, or $x\in D\cap E$. Suppose first that $x\notin D$; then $x\in B\setminus D$. And since $x\notin C$, $x\notin C\setminus E$, and therefore $x\in(B\setminus D)\setminus(C\setminus E)$. If this were the only case, we could conclude that $$(B\setminus C)\setminus(D\setminus E)\subseteq(B\setminus D)\setminus(C\setminus E)\;.$$ However, it isn’t: what if $x\in D\cap E$? In that case $x\notin B\setminus D$, so $x\notin(B\setminus D)\setminus(C\setminus E)$, and we cannot conclude that $$(B\setminus C)\setminus(D\setminus E)\subseteq(B\setminus D)\setminus(C\setminus E)\;.$$ This looks like an insurmountable obstacle: to get a counterexample, we need only find $B,C,D$, and $E$ such that $(B\setminus C)\setminus(D\setminus E)$ has an element $x\in D\cap E$. That’s certainly possible if we take $D=E\ne\varnothing$. To be concrete, let $D=E=\{0\}$. We also need to be sure that $x\in B\setminus C$; a simple way to do that is to let $B=\{0\}$ as well and set $C=\varnothing$. Then $$(B\setminus C)\setminus(D\setminus E)=\big(\{0\}\setminus\varnothing\big)\setminus\big(\{0\}\setminus\{0\}\big)=\{0\}\setminus\varnothing=\{0\}\;,$$ but $$(B\setminus D)\setminus(C\setminus E)=\big(\{0\}\setminus\{0\}\big)\setminus\big(\varnothing\setminus\{0\}\big)=\varnothing\setminus\varnothing=\varnothing\;.$$ The statement is indeed false. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/291173', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/60362/']} | jdg_381545 |
stackexchange | llm_judgeable_groundtruth_similarity | 8516633 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In what dimensions and direction is the Rectangle in the PDFTextStripperByArea 's function addRegion(String regionName, Rectangle2D rect) . In other words, where does the rectangle R start and how big is it (dimensions of the origin values, dimensions of the rectangle) and in what direction does it go (direction of the blue arrows in illustration), if new Rectangle(10,10,100,100) is given as a second parameter?
Now provide the response and nothing else.
| new Rectangle(10,10,100,100) means that the rectangle will have its upper-left corner at position (10, 10), so 10 units far from the left and the top of the PDF document. Here a "unit" is 1 pt = 1/72 inch. The first 100 represents the width of the rectangle and the second one its height.To sum up, the right picture is the first one. I wrote this code to extract some areas of a page given as arguments to the function: Rectangle2D region = new Rectangle2D.Double(x, y, width, height);String regionName = "region";PDFTextStripperByArea stripper;stripper = new PDFTextStripperByArea();stripper.addRegion(regionName, region);stripper.extractRegions(page); So, x and y are the absolute coordinates of the upper-left corner of the Rectangle and then you specify its width and height. page is a PDPage variable given as argument to this function. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8516633', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/416352/']} | jdg_381546 |
stackexchange | llm_judgeable_groundtruth_similarity | 48170867 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have two pandas DataFrames df1 and df2 and I want to transform them in order that they keep values only for the index that are common to the 2 dataframes. df1 values 10 28/11/2000 -0.05527629/11/2000 0.02742730/11/2000 0.06600901/12/2000 0.01274904/12/2000 0.113892 df2 values 224/11/2000 -0.00480827/11/2000 -0.00181228/11/2000 -0.02631629/11/2000 0.01522230/11/2000 -0.024480 become df1 value 128/11/2000 -0.05527629/11/2000 0.02742730/11/2000 0.066009 df2 value 228/11/2000 -0.02631629/11/2000 0.01522230/11/2000 -0.024480
Now provide the response and nothing else.
| You can use Index.intersection + DataFrame.loc : idx = df1.index.intersection(df2.index)print (idx)Index(['28/11/2000', '29/11/2000', '30/11/2000'], dtype='object') Alternative solution with numpy.intersect1d : idx = np.intersect1d(df1.index, df2.index)print (idx)['28/11/2000' '29/11/2000' '30/11/2000'] df1 = df1.loc[idx]print (df1) values 128/11/2000 -0.05527629/11/2000 0.02742730/11/2000 0.066009df2 = df2.loc[idx] | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48170867', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6603658/']} | jdg_381547 |
stackexchange | llm_judgeable_groundtruth_similarity | 182348 |
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:
For example, I have a data set contains 100,000 instances. There are only about 5,000 positive instances and negative instances are 95,000. I wish to fit the data using logistic regression or svm. How can I do it? Is this a cold boot problem?
Now provide the response and nothing else.
| In SVM you can assign a misclassification penalty per class. The most effective way to deal with unbalanced data sets is to increase the misclassification penalty on the minority class. Your class skew is not that large, so this approach will work fine. This functionality is available in LIBSVM, which is the most popular back-end for all SVM libraries. Hence, you should be able to do this. | {} | {'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/182348', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/95466/']} | jdg_381548 |
stackexchange | llm_judgeable_groundtruth_similarity | 53214434 |
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 comments on closure.rs are pretty great, however I can't make it work for returning a closure from a WebAssembly library. I have a function like this: #[wasm_bindgen]pub fn start_game( start_time: f64, screen_width: f32, screen_height: f32, on_render: &js_sys::Function, on_collision: &js_sys::Function,) -> ClosureTypeHere { // ...} Inside that function I make a closure, assuming Closure::wrap is one piece of the puzzle, and copying from closure.rs): let cb = Closure::wrap(Box::new(move |time| time * 4.2) as Box<FnMut(f64) -> f64>); How do I return this callback from start_game and what should ClosureTypeHere be? The idea is that start_game will create local mutable objects - like a camera, and the JavaScript side should be able to call the function Rust returns in order to update that camera.
Now provide the response and nothing else.
| This is a good question, and one that has some nuance too! It's worth calling out the closures example in the wasm-bindgen guide (and the section about passing closures to JavaScript ) as well, and it'd be good to contribute back to that as well if necessary! To get you started, though, you can do something like this: use wasm_bindgen::{Closure, JsValue};#[wasm_bindgen]pub fn start_game( start_time: f64, screen_width: f32, screen_height: f32, on_render: &js_sys::Function, on_collision: &js_sys::Function,) -> JsValue { let cb = Closure::wrap(Box::new(move |time| { time * 4.2 }) as Box<FnMut(f64) -> f64>); // Extract the `JsValue` from this `Closure`, the handle // on a JS function representing the closure let ret = cb.as_ref().clone(); // Once `cb` is dropped it'll "neuter" the closure and // cause invocations to throw a JS exception. Memory // management here will come later, so just leak it // for now. cb.forget(); return ret;} Above the return value is just a plain-old JS object (here as a JsValue ) and we create that with the Closure type you've seen already. This will allow you to quickly return a closure to JS and you'll be able to call it from JS as well. You've also asked about storing mutable objects and such, and that can all be done through normal Rust closures, capturing, etc. For example the declaration of FnMut(f64) -> f64 above is the signature of the JS function, and that can be any set of types such as FnMut(String, MyCustomWasmBindgenType, f64) ->Vec<u8> if you really want. For capturing local objects you can do: let mut camera = Camera::new();let mut state = State::new();let cb = Closure::wrap(Box::new(move |arg1, arg2| { // note the `move` if arg1 { camera.update(&arg2); } else { state.update(&arg2); }}) as Box<_>); (or something like that) Here the camera and state variables will be owned by the closure and dropped at the same time. More info about just closures can be found in the Rust book . It's also worth briefly covering the memory management aspect here. In theexample above we're calling forget() which leaks memory and can be a problem if the Rust function is called many times (as it would leak a lot of memory). The fundamental problem here is that there's memory allocated on the WASM heap which the created JS function object references. This allocated memory in theory needs to be deallocated whenever the JS function object is GC'd, but we have no way of knowing when that happens (until WeakRef exists !). In the meantime we've chosen an alternate strategy. The associated memory isdeallocated whenever the Closure type itself is dropped, providingdeterministic destruction. This, however, makes it difficult to work with as we need to figure out manually when to drop the Closure . If forget doesn't work for your use case, some ideas for dropping the Closure are: First, if it's a JS closure only invoked once, then you can use Rc / RefCell to drop the Closure inside the the closure itself (using some interiormutability shenanigans). We should also eventuallyprovide native supportfor FnOnce in wasm-bindgen as well! Next, you can return an auxiliary JS object to Rust which has a manual free method. For example a #[wasm_bindgen] -annotated wrapper. This wrapper wouldthen need to be manually freed in JS when appropriate. If you can get by, forget is by far the easiest thing to do fornow, but this is definitely a pain point! We can't wait for WeakRef to exist :) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/53214434', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/784519/']} | jdg_381549 |
stackexchange | llm_judgeable_groundtruth_similarity | 65480947 |
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 to encode the electron charge, which is -1.602*10 -19 C, using IEEE-754. I did it manually and verified my result using this site. So I know my representation is good. My problem is that, if I try to build a C program showing my number in scientific notation, I get the wrong number. Here is my code: #include <stdio.h>int main(int argc, char const *argv[]){ float q = 0xa03d217b; printf("q = %e", q); return 0;} Here is the result: $ ./test.exeq = 2.688361e+09 My question: Is there another representation that my CPU might be using internally for floating point other than IEEE-754?
Now provide the response and nothing else.
| The line float q = 0xa03d217b; converts the integer (hex) literal into a float value representing that number (or an approximation thereof); thus, the value assigned to your q will be the (decimal) value 2,688,360,827 (which is what 0xa03d217b equates to), as you have noted. If you must initialize a float variable with its internal IEEE-754 (HEX) representation, then your best option is to use type punning via the members of a union (legal in C but not in C++): #include <stdio.h>typedef union { float f; unsigned int h;} hexfloat;int main(){ hexfloat hf; hf.h = 0xa03d217b; float q = hf.f; printf("%lg\n", q); return 0;} There are also some 'quick tricks' using pointer casting, like: unsigned iee = 0xa03d217b;float q = *(float*)(&iee); But, be aware, there are numerous issues with such approaches, like potential endianness conflicts and the fact that you're breaking strict aliasing requirements . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/65480947', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5480092/']} | jdg_381550 |
stackexchange | llm_judgeable_groundtruth_similarity | 644548 |
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 am not a physicist, and I have a hard time getting an intuitive idea of the Lorentz contraction. Supposing a train gets accelerated from rest to close to the speed a light, its length will be contracted by a certain factor. As observed from an observer in the initial rest frame, will the contraction bring both sides of the train closer to the center (looking like the rear is moving a bit faster, and the front a bit slower)? What about two trains, one just in front of the other, both accelerated with the same acceleration, starting at the same time. Will the observer at rest observe a gap growing between them as they gain speed? Or will they just both shrink as a single object? Does the location where the force is applied (the engine of the train) affects the contraction center?
Now provide the response and nothing else.
| Supposing a train gets accelerated Let's pause there for a moment. In Special Relativity, simultaneity is relative. That means that two event that appear simultaneous in one inertial reference frame are generally not simultaneous in another reference frame. This means that if two ends of a train began accelerating together in one inertial reference frame, they will not have started accelerating together in a difference inertial reference frame. Things will get very confusing if we don't follow this simple rule. RULE Whenever attempting to solve problems in Special Relativity, always use the full Lorentz transformation to find out what the space and time coordinates are for each event in each coordinate system that is of interest. Don't simply use the abbreviated ideas such as "length" contracts, or "time" dilates. While these abbreviated ideas are true, then leave a lot of important information about what is happening out of view. End of Rule. As observed from an observer in the initial rest frame, will the contraction bring both sides of the train closer to the center (looking like the rear is moving a bit faster, and the front a bit slower)? The answer depends upon how the two ends of the train move in the initial rest frame. ONE possibility is that the two ends will not accelerate simultaneously in the rest frame. The back end may accelerate first, causing the back end to accelerate to a speed sooner than the front. The advantage of this type of acceleration is that the train does not get stretched in its own frame (which might cause it to break apart). Another possibility is that the two ends accelerate "simultaneously" according the the initial rest frame. While this has an appeal to the naive understanding, this means that the two ends will always have the same distance in the rest frame. That means that the train will get stretched in its own frames. Also from its own frames (while moving), the front began accelerating first. (This second possibility is probably not what you mean when you describe a train as accelerating.) What about two trains, one just in front of the other, both accelerated with the same acceleration, starting at the same time. We must ask "both accelerated with the same acceleration" and "starting at the same time" in what inertial frames? Will the observer at rest observe a gap growing between them as they gain speed? As before the answer depends upon what you mean by "starting at the same time", and "with the same acceleration". | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/644548', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/303972/']} | jdg_381551 |
stackexchange | llm_judgeable_groundtruth_similarity | 6187914 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
is it possible to export data in iif format using php? like we export data in csv or excel format? Thanks
Now provide the response and nothing else.
| It isn't possible to dynamically define a struct that is identical to a compile-time struct. It is possible, but difficult, to create dynamic structures that can contain the information equivalent to a struct. The access to the data is less convenient than what is available at compile-time. All else apart, you cannot access a member somestruct.not_seen_at_compile_time using the dot . or arrow -> notation if it was not defined at compile-time. With network communications, there are other issues to address - notably 'endianness'. That is, the data on the wire will probably include multi-byte (2, 4, 8) integers, and either the MSB or the LSB will be sent first, but if one machine is little-endian (IA-32, IA-64, x86/64) and the other is big-endian (SPARC, PPC, almost anything not from Intel), then the data will need to be transformed. Floating-point formats can also be problematic. There are numerous standards dedicated to defining how data will be sent across the network - it is not trivial. Some are specific: IP, TCP, UDP; others are general, such as ASN.1. However, the 'cannot do dynamic data structures' part limits things - you have to agree beforehand on what the data structures are, and how they will be interpreted. How do you do that? gerty3000 asks: It is possible, but difficult, to create dynamic structures that can contain the information equivalent to a struct. — How do you do that? I would like to pass dynamically-defined structs off to other C code (assume same compiler and other settings) without having to duplicate the struct memory layout routines from the compiler. I won't be accessing fields of these structs inside my process much (just initializing them once), so convenient syntax is not a concern. You can't do it without duplicating the memory layout in some shape or form. It might not have to be exactly the same, but it is likely best if it is. Here's some sample code that shows roughly how it might be done. dynstruct.c This contains the basic structure manipulation material — structures to describe structures and (simple) members. Handling full arrays (as opposed to strings) would require more work, and there's a good deal of make-work replication to be managed for other types. It also contains a main() program that tests the code. It makes a call to other_function() , which demonstrates that the structure I've defined in the data structures does match the structure exactly. The data does assume a 64-bit machine where double must be aligned on an 8-byte boundary (so there's a 4-byte hole in the structure); you will have to tweak the data for a machine where double can be on a 4-byte boundary. #include <assert.h>#include <stdio.h>#include <stdlib.h>#include <string.h>/* This is the type that will be simulated dynamically *//*struct simulated{ int number; double value; char string[32];};*//* SOF structure.h */typedef enum Type { INT, DOUBLE, STRING } Type;typedef struct Descriptor{ size_t offset; Type type; size_t type_size; size_t array_dim; char name[32];} Descriptor;typedef struct Structure{ size_t size; char name[32]; Descriptor *details;} Structure;extern void *allocate_structure(const Structure *structure);extern void deallocate_structure(void *structure);extern void *pointer_to_element(void *p, const Descriptor *d);extern int get_int_element(void *p, const Descriptor *d);extern void set_int_element(void *p, const Descriptor *d, int newval);extern double get_double_element(void *p, const Descriptor *d);extern void set_double_element(void *p, const Descriptor *d, double newval);extern char *get_string_element(void *p, const Descriptor *d);extern void set_string_element(void *p, const Descriptor *d, char *newval);/* EOF structure.h */static Descriptor details[] ={ { 0, INT, sizeof(int), 1, "number" }, { 8, DOUBLE, sizeof(double), 1, "value" }, { 16, STRING, sizeof(char), 32, "string" },};static Structure simulated = { 48, "simulated", details };void *allocate_structure(const Structure *structure){ void *p = calloc(1, structure->size); return p;}void deallocate_structure(void *structure){ free(structure);}void *pointer_to_element(void *p, const Descriptor *d){ void *data = (char *)p + d->offset; return data;}int get_int_element(void *p, const Descriptor *d){ assert(d->type == INT); int *v = pointer_to_element(p, d); return *v;}void set_int_element(void *p, const Descriptor *d, int newval){ assert(d->type == INT); int *v = pointer_to_element(p, d); *v = newval;}double get_double_element(void *p, const Descriptor *d){ assert(d->type == DOUBLE); double *v = pointer_to_element(p, d); return *v;}void set_double_element(void *p, const Descriptor *d, double newval){ assert(d->type == DOUBLE); double *v = pointer_to_element(p, d); *v = newval;}char *get_string_element(void *p, const Descriptor *d){ assert(d->type == STRING); char *v = pointer_to_element(p, d); return v;}void set_string_element(void *p, const Descriptor *d, char *newval){ assert(d->type == STRING); assert(d->array_dim > 1); size_t len = strlen(newval); if (len > d->array_dim) len = d->array_dim - 1; char *v = pointer_to_element(p, d); memmove(v, newval, len); v[len] = '\0';}extern void other_function(void *p);int main(void){ void *sp = allocate_structure(&simulated); if (sp != 0) { set_int_element(sp, &simulated.details[0], 37); set_double_element(sp, &simulated.details[1], 3.14159); set_string_element(sp, &simulated.details[2], "Absolute nonsense"); printf("Main (before):\n"); printf("Integer: %d\n", get_int_element(sp, &simulated.details[0])); printf("Double: %f\n", get_double_element(sp, &simulated.details[1])); printf("String: %s\n", get_string_element(sp, &simulated.details[2])); other_function(sp); printf("Main (after):\n"); printf("Integer: %d\n", get_int_element(sp, &simulated.details[0])); printf("Double: %f\n", get_double_element(sp, &simulated.details[1])); printf("String: %s\n", get_string_element(sp, &simulated.details[2])); deallocate_structure(sp); } return 0;} other.c This code knows nothing about the structure description material in dynstruct.c ; it knows about the struct simulated that the simulation code simulates. It prints the data it is passed and modifies it. #include <stdio.h>#include <string.h>extern void other_function(void *p);struct simulated{ int number; double value; char string[32];};void other_function(void *p){ struct simulated *s = (struct simulated *)p; printf("Other function:\n"); printf("Integer: %d\n", s->number); printf("Double: %f\n", s->value); printf("String: %s\n", s->string); s->number *= 2; s->value /= 2; strcpy(s->string, "Codswallop");} Sample output Main (before):Integer: 37Double: 3.141590String: Absolute nonsenseOther function:Integer: 37Double: 3.141590String: Absolute nonsenseMain (after):Integer: 74Double: 1.570795String: Codswallop Clearly, this code is not production-ready. It is a sufficient demonstration of what can be done. One issue you'd have to deal with is initializing the Structure and Descriptor data correctly. You can't put too many assertions into that sort of code. For example, I should really have assert(d->size == sizeof(double); in get_double_element() . It would also be sensible to include assert(d->offset % sizeof(double) == 0); to ensure that the double element is properly aligned. Or you might have a validate_structure(const Structure *sp); function that did all these validation checks. You'd need a function void dump_structure(FILE *fp, const char *tag, const Structure *sp); to dump the defined structure to the given file preceded by the tag, to assist in debugging. Etc. This code is pure C; it is not compilable by a C++ compiler as C++. There aren't enough casts to satisfy a C++ compiler. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6187914', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/651016/']} | jdg_381552 |
stackexchange | llm_judgeable_groundtruth_similarity | 35914 |
Below is a question asked on the forum astronomy.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I understand that solar radiation causes material to vaporize out of a comet into dust but why does the dust then trail behind the comet like a "tail"? Assuming gravity is the only applied force acting on the comet, shouldn't all of the material, including the dust, be travelling at the same speed due to conservation of momentum? What causes the dust to travel slower than the comet's nucleus? In other words, why does the dust form a "tail" and not a "cloud"?
Now provide the response and nothing else.
| There are two forces that can cause the formation of a tail: the solar wind and radiation pressure. The first misconception in your question is "the dust [travels] slower than the nucleus". The tail is not left trailing behind the comet, it is pushed away from the comet by the sun. When the comet is moving away from the sun, the tail is in front of the comet. Now radiation pressure is small but real. When light shines on something there is a small force. This pushes dust back from the comet in the direction opposite to the sun. The dust is still affected by gravity and a curved dust tail results. The ultraviolet light from the Sun ionises the gas and gives it an electric charge. The solar wind carries magnetic fields and the gas (or more properly plasma ) follows these fields in a straight line back from the sun. So space around the Sun is not empty. There is powerful light and magnetic fields that are strong enough to push the dust and gas released by the comet away from the coma, and form the tail. | {} | {'log_upvote_score': 6, 'links': ['https://astronomy.stackexchange.com/questions/35914', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/33486/']} | jdg_381553 |
stackexchange | llm_judgeable_groundtruth_similarity | 3298526 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Say I have a table which I query like so: select date, value from mytable order by date and this gives me results: date value02/26/2009 14:03:39 1 02/26/2009 14:10:52 2 (a)02/26/2009 14:27:49 2 (b)02/26/2009 14:34:33 302/26/2009 14:48:29 2 (c)02/26/2009 14:55:17 302/26/2009 14:59:28 4 I'm interested in the rows of this result set where the value is the same as the one in the previous or next row, like row b which has value=2 the same as row (a). I don't care about rows like row (c) which has value=2 but does not come directly after a row with value=2 . How can I query the table to give me all rows like (a) and (b) only? This is on Oracle, if it matters.
Now provide the response and nothing else.
| Use the lead and lag analytic functions. create table t3 (d number, v number);insert into t3(d, v) values(1, 1);insert into t3(d, v) values(2, 2);insert into t3(d, v) values(3, 2);insert into t3(d, v) values(4, 3);insert into t3(d, v) values(5, 2);insert into t3(d, v) values(6, 3);insert into t3(d, v) values(7, 4);select d, v, case when v in (prev, next) then '*' end match, prev, next from ( select d, v, lag(v, 1) over (order by d) prev, lead(v, 1) over (order by d) next from t3)order by d; Matching neighbours are marked with * in the match column, | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3298526', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/397842/']} | jdg_381554 |
stackexchange | llm_judgeable_groundtruth_similarity | 1973353 |
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:
So in my notes it says it is $l=p_1 \times p_2$. I don't quite understand that, for example, suppose the points are $p_1=(1,1,1)$, $p_2=(2,2,1)$. Then the cross product would give a line perpendicular to these points, in other words perpendicular to the plane in orange as seen in the image below:
Now provide the response and nothing else.
| In 2D, the equation of any line $\ell$ has the form $a x + by + c = 0$. Similar to one can use homogeneous coordinate $\vec{p} = (x,y,1)$ to represent a point $p = (x,y)$ in 2D, one can use homogeneous coordinates $\vec{\ell} = (a,b,c)$ to represent a line $\ell$ in 2D. The condition that $p$ lies on $\ell$ (i.e. $a x + by + c = 0$ ) can be rewritten as $\vec{\ell} \cdot \vec{p} = 0$.In short, point $p$ lies on line $\ell$ in 2D $\quad\iff\quad$ $\vec{p}$ perpendicular to $\vec{\ell}$ in 3D. A consequence of this is if $\ell$ is a line passing through 2 points $p_1, p_2$, we will have $$\vec{\ell}\cdot\vec{p_1} = 0\quad\text{ and }\quad \vec{\ell}\cdot\vec{p_2} = 0\quad\implies\quad \vec{\ell} \propto \vec{p_1} \times \vec{p_2}$$ i.e the determination of a line by 2 points in 2D corresponds to cross product of corresponding 3D vectors of homogeneous coordinates. Another interesting consequence is if $p$ is the intersection of two lines $\ell_1$ and $\ell_2$, then $\vec{p} \propto \vec{\ell}_1 \times \vec{\ell}_2$. It is this sort of correspondences between geometric operations in 2D and vectoroperations in 3D that make homogeneous coordinates useful in analysis of 2D problems. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1973353', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/172492/']} | jdg_381555 |
stackexchange | llm_judgeable_groundtruth_similarity | 21330807 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Should I use noexcept method modifier for getters always in C++11? I mean simple getters here that just return members.At least in all my getters I have here an exception can't possiblybe thrown. One downside is that a getter gets too verbose: const std::string& getName() const noexcept{ return name; } The good side as pointed out in Stroustrup's book is that the compilermight do some optimizations here and there.
Now provide the response and nothing else.
| noexcept is a promise that is very hard to take back. For example, you could later do something as simple as change the return type to std::string (for whatever reason), but because that needs to allocate a copy of the string, it can throw. So the standard went the way of "add noexcept only when it's necessary or highly beneficial", and I think that's a good rule to follow. The question you need to ask yourself is, will the callers of this method need it to not throw? | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21330807', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3111311/']} | jdg_381556 |
stackexchange | llm_judgeable_groundtruth_similarity | 1211311 |
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:
Find limit: $$\lim_{x\to 0}\frac{x}{\sin x - x} = ???$$ Any help would be thoroughly appreciated.
Now provide the response and nothing else.
| An idea: you can write $$\frac x{\sin x-x}=\frac1{\frac{\sin x}x-1}$$ and use now that $\dfrac{\sin x}x\xrightarrow[x\to 0]{}1\;$ to show the limit doesn't exist finitely . | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1211311', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/117251/']} | jdg_381557 |
stackexchange | llm_judgeable_groundtruth_similarity | 23962 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
For example,Look at the code that calculates the n-th Fibonacci number: fib(int n){ if(n==0 || n==1) return 1; return fib(n-1) + fib(n-2);} The problem with this code is that it will generate stack overflow error for any number greater than 15 (in most computers). Assume that we are calculating fib(10). In this process, say fib(5) is calculated a lot of times. Is there some way to store this in memory for fast retrieval and thereby increase the speed of recursion? I am looking for a generic technique that can be used in almost all problems.
Now provide the response and nothing else.
| Yes your insight is correct.This is called dynamic programming . It is usually a common memory runtime trade-off. In the case of fibo, you don't even need to cache everything : [edit]The author of the question seems to be looking for a general method to cache rather than a method to compute Fibonacci. Search wikipedia or look at the code of the other poster to get this answer. Those answers are linear in time and memory. **Here is a linear-time algorithm O(n), constant in memory ** in OCaml:let rec fibo n = let rec aux = fun | 0 -> (1,1) | n -> let (cur, prec) = aux (n-1) in (cur+prec, cur) let (cur,prec) = aux n in prec;;in C++:int fibo(int n) { if (n == 0 ) return 1; if (n == 1 ) return 1; int p = fibo(0); int c = fibo(1); int buff = 0; for (int i=1; i < n; ++i) { buff = c; c = p+c; p = buff; }; return c;}; This perform in linear time. But log is actually possible !!!Roo's program is linear too, but way slower, and use memory. Here is the log algorithm O(log(n)) Now for the log-time algorithm (way way way faster), here is a method :If you know u(n), u(n-1), computing u(n+1), u(n) can be done by applying a matrix: | u(n+1) | = | 1 1 | | u(n) || u(n) | | 1 0 | | u(n-1) | So that you have : | u(n) | = | 1 1 |^(n-1) | u(1) | = | 1 1 |^(n-1) | 1 || u(n-1) | | 1 0 | | u(0) | | 1 0 | | 1 | Computing the exponential of the matrix has a logarithmic complexity. Just implement recursively the idea : M^(0) = IdM^(2p+1) = (M^2p) * MM^(2p) = (M^p) * (M^p) // of course don't compute M^p twice here. You can also just diagonalize it (not to difficult), you will find the gold number and its conjugate in its eigenvalue, and the result will give you an EXACT mathematical formula for u(n). It contains powers of those eigenvalues, so that the complexity will still be logarithmic. Fibo is often taken as an example to illustrate Dynamic Programming, but as you see, it is not really pertinent. @John:I don't think it has anything to do with do with hash. @John2:A map is a bit general don't you think? For Fibonacci case, all the keys are contiguous so that a vector is appropriate, once again there are much faster ways to compute fibo sequence, see my code sample over there. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23962', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/184/']} | jdg_381558 |
stackexchange | llm_judgeable_groundtruth_similarity | 1554620 |
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 a favicon to be requested from a static file server instead of the main web server for performance optimization. If I specify a <link rel="shortcut icon" href="http://cdn.site.com/favicon.ico"> but also have a /favicon.ico in my site root as a fallback, which will browsers prefer? Will browsers (and which?) still look for /favicon.ico , making the move to a static file server useless?
Now provide the response and nothing else.
| I did the test suggested above. I placed a /favicon.ico in the root of a domain, and a link, and fired up the page in: Opera 10 Opera 9.64 Firefox 3.5 IE 6 IE 7 IE 8 Safari 4 They all showed the icon loaded with <link rel="shortcut icon" href="http://cdn.site.com/favicon.ico"> (located on an external server). I checked access.log , and there were no requests to /favicon.ico ! I then commented out the <link> , checked again in all browsers, and they showed the /favicon.ico icon and corresponding entries in access.log . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1554620', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/114168/']} | jdg_381559 |
stackexchange | llm_judgeable_groundtruth_similarity | 3833229 |
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 run a query against a legacy table that stores URL encoded text. I need this text to be decoded in my results. How do I achieve this?
Now provide the response and nothing else.
| Try one of these: CREATE FUNCTION dbo.UrlDecode(@url varchar(3072))RETURNS varchar(3072)ASBEGIN DECLARE @count int, @c char(1), @cenc char(2), @i int, @urlReturn varchar(3072) SET @count = Len(@url) SET @i = 1 SET @urlReturn = '' WHILE (@i <= @count) BEGIN SET @c = substring(@url, @i, 1) IF @c LIKE '[!%]' ESCAPE '!' BEGIN SET @cenc = substring(@url, @i + 1, 2) SET @c = CHAR(CASE WHEN SUBSTRING(@cenc, 1, 1) LIKE '[0-9]' THEN CAST(SUBSTRING(@cenc, 1, 1) as int) ELSE CAST(ASCII(UPPER(SUBSTRING(@cenc, 1, 1)))-55 as int) END * 16 + CASE WHEN SUBSTRING(@cenc, 2, 1) LIKE '[0-9]' THEN CAST(SUBSTRING(@cenc, 2, 1) as int) ELSE CAST(ASCII(UPPER(SUBSTRING(@cenc, 2, 1)))-55 as int) END) SET @urlReturn = @urlReturn + @c SET @i = @i + 2 END ELSE BEGIN SET @urlReturn = @urlReturn + @c END SET @i = @i +1 END RETURN @urlReturnENDGO from http://sqlblog.com/blogs/peter_debetta/archive/2007/03/09/t-sql-urldecode.aspx CREATE FUNCTION dbo.fnDeURL( @URL VARCHAR(8000))RETURNS VARCHAR(8000)ASBEGIN DECLARE @Position INT, @Base CHAR(16), @High TINYINT, @Low TINYINT, @Pattern CHAR(21) SELECT @Base = '0123456789abcdef', @Pattern = '%[%][0-9a-f][0-9a-f]%', @URL = REPLACE(@URL, '+', ' '), @Position = PATINDEX(@Pattern, @URL) WHILE @Position > 0 SELECT @High = CHARINDEX(SUBSTRING(@URL, @Position + 1, 1), @Base COLLATE Latin1_General_CI_AS), @Low = CHARINDEX(SUBSTRING(@URL, @Position + 2, 1), @Base COLLATE Latin1_General_CI_AS), @URL = STUFF(@URL, @Position, 3, CHAR(16 * @High + @Low - 17)), @Position = PATINDEX(@Pattern, @URL) RETURN @URLEND from http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=88926 | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3833229', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/245914/']} | jdg_381560 |
stackexchange | llm_judgeable_groundtruth_similarity | 34028511 |
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 excel data that i read in with python pandas: import pandas as pddata = pd.read_csv('..../file.txt', sep='\t' ) the mock data looks like this: unwantedjunkline1unwantedjunkline2unwantedjunkline3 ID ColumnA ColumnB ColumnC 1 A B C 2 A B C 3 A B C... the data in this case contains 3 junk lines(lines i don't want to read in) before hitting the header and sometimes it contains 4 or more suck junk lines. so in this case i read in the data : data = pd.read_csv('..../file.txt', sep='\t', skiprows = 3 ) data looks like: ID ColumnA ColumnB ColumnC 1 A B C 2 A B C 3 A B C... But each time the number of unwanted lines is different , is there a way to read in a table file using pandas without using 'skiprows=' but instead using some command that matches the header so it knows to start reading from the header? so I don't have to click open the file to count how many unwanted lines the file contains each time and then manually change the 'skiprows=' option.
Now provide the response and nothing else.
| If you know what the header startswith: def skip_to(fle, line,**kwargs): if os.stat(fle).st_size == 0: raise ValueError("File is empty") with open(fle) as f: pos = 0 cur_line = f.readline() while not cur_line.startswith(line): pos = f.tell() cur_line = f.readline() f.seek(pos) return pd.read_csv(f, **kwargs) Demo: In [18]: cat test.txt1,23,4The,headerfoo,barfoobar,fooIn [19]: df = skip_to("test.txt","The,header", sep=",")In [20]: dfOut[20]: The header0 foo bar1 foobar foo By calling .tell we keep track of where the pointer is for the previous line so when we hit the header we seek back to that line and just pass the file object to pandas. Or using the junk if they all started with something in common: def skip_to(fle, junk,**kwargs): if os.stat(fle).st_size == 0: raise ValueError("File is empty") with open(fle) as f: pos = 0 cur_line = f.readline() while cur_line.startswith(junk): pos = f.tell() cur_line = f.readline() f.seek(pos) return pd.read_csv(f, **kwargs) df = skip_to("test.txt", "junk",sep="\t") | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34028511', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5516874/']} | jdg_381561 |
stackexchange | llm_judgeable_groundtruth_similarity | 17256934 |
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 attempted to do this both in Visual Studio 2010 and Visual Studio 2012. If my Gruntfile.js file is in the root of my project I can run the "grunt" command from the post build event command line and it runs without a problem. grunt or grunt.cmd But if it's in a sub directory $(ProjectDir)Public\grunt or $(ProjectDir)Public\grunt.cmd It gives me this error The command "c:\web\Public\grunt.cmd" exited with code 9009. I've been researching this but I'm not finding any much help out there. I did find in the grunt documentation that I need to use "grunt.cmd" instead of just calling "grunt" but thats not helping me much.
Now provide the response and nothing else.
| What's happening is you're specifying an exact path for grunt, which doesn't actually reside at $(ProjectDir)Public\. When you're in that directory on a command prompt and type grunt, it executes because you've set your path environment variable to include the directory where grunt lives. Luckily the post build commands in VS act like a command window, so you can put this in your post build commands: CD $(ProjectDir)Public\grunt And that should work (assuming a default grunt task is defined). | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17256934', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2512730/']} | jdg_381562 |
stackexchange | llm_judgeable_groundtruth_similarity | 8867871 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
It's a simple question, but I keep seeing conflicting answers: should the main routine of a C++ program return 0 or EXIT_SUCCESS ? #include <cstdlib>int main(){return EXIT_SUCCESS;} or int main(){return 0;} Are they the exact same thing? Should EXIT_SUCCESS only be used with exit() ? I thought EXIT_SUCCESS would be a better option because other software may want to deem zero as failure, but I also heard that if you return 0 , the compiler is capable of changing it to a different value anyway.
Now provide the response and nothing else.
| EXIT_FAILURE , either in a return statement in main or as an argument to exit() , is the only portable way to indicate failure in a C or C++ program. exit(1) can actually signal successful termination on VMS, for example. If you're going to be using EXIT_FAILURE when your program fails, then you might as well use EXIT_SUCCESS when it succeeds, just for the sake of symmetry. On the other hand, if the program never signals failure, you can use either 0 or EXIT_SUCCESS . Both are guaranteed by the standard to signal successful completion. (It's barely possible that EXIT_SUCCESS could have a value other than 0, but it's equal to 0 on every implementation I've ever heard of.) Using 0 has the minor advantage that you don't need #include <stdlib.h> in C, or #include <cstdlib> in C++ (if you're using a return statement rather than calling exit() ) -- but for a program of any significant size you're going to be including stdlib directly or indirectly anyway. For that matter, in C starting with the 1999 standard, and in all versions of C++, reaching the end of main() does an implicit return 0; anyway, so you might not need to use either 0 or EXIT_SUCCESS explicitly. (But at least in C, I consider an explicit return 0; to be better style.) (Somebody asked about OpenVMS. I haven't used it in a long time, but as I recall odd status values generally denote success while even values denote failure. The C implementation maps 0 to 1 , so that return 0; indicates successful termination. Other values are passed unchanged, so return 1; also indicates successful termination. EXIT_FAILURE would have a non-zero even value.) | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/8867871', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/908939/']} | jdg_381563 |
stackexchange | llm_judgeable_groundtruth_similarity | 278397 |
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:
This is a complex analysis problem.Let $f$ be an entire function and $f^2+2f+1$ be a polynomial. Prove that $f$ is a polynomial.
Now provide the response and nothing else.
| We have $(f(z)+1)^2=p(z)$ where p(z) is a polynomial. Then $$\infty=\lim\limits_{z\to \infty} |p(z)|=\lim\limits_{z\to \infty}|f(z)+1|^2\implies \lim\limits_{z\to \infty}|f(z)|=\infty $$ Therefore $f$ is an entire function with a pole at $\infty$. So $f$ is a polynomial. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/278397', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/16418/']} | jdg_381564 |
stackexchange | llm_judgeable_groundtruth_similarity | 87456 |
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 have a cubic equation (corresponding to the band structure of a physical system) given by w in the code below. M = {{s - w, ab, ac}, {ab, s - w, bc}, {ac, bc, s - w}};w = w /. Solve[Det[M] == 0, w];f[e_] := 2 Norm[e]^-3 (1 - 3 Sin[θ]^2 Cos[ϕ - ArcTan[e[[1]],e[[2]]]]^2) Cos[{x,y}.e];ab = f[{1, 0}];ac = f[{0, 1}];bc = f[{1, 1}] + f[{-1, 1}];s = f[{2, 0}] + f[{0, 2}]; With 0<=θ<=Pi and 0<=ϕ<=2Pi tuneable parameters. I would like to develop a code that finds the coordinates {x,y} at which the three different solutions (the three bands) touch for a given {θ,ϕ} . For example, for {θ,ϕ}={0,0} the band structure is given below. I already know the touching point here is {x,y}={Pi/2,Pi/2} from previous studies. However I would really like to be able to find the touching points (if there are any) for any arbitrary {θ, ϕ} . There are three basic ways I can think to approach this are (though none of them have worked for me): 1) Use the known properties of cubic equations. When the discriminant of the cubic equation equals zero then the equation has a multiple root and all of its roots are real. Thus some sort of code such as c = ab^2 + ac^2 + bc^2;d = 2 ab ac bc;discriminant = Chop[4 c^3 + 27 d^2];{θ, ϕ} = {0, 0};Solve[discriminant == 0 && 0 <= θ <= Pi && 0 <= ϕ <= 2 Pi, {x, y}] However this process spits out some horrendously complicated expression that I can't seem to simplify. 2) Using the explicit expression for the three solutions w to find where they touch. {θ, ϕ} = {0, 0};Solve[w[[1]] == w[[2]] == w[[3]], {x, y}] 3) Use some kind of numerical approach with FindRoot. Either with the discriminant==0 condition or explicit touching condition. Start with a known solution, for example {x,y}={Pi/2,Pi/2} when {θ,ϕ}={0,0} . Then slowly varying theta and phi using the previous found touching point as the starting point to look for a solution and then in this way map out the touching point for the whole parameter space of theta and phi. Any suggestions greatly appreciated
Now provide the response and nothing else.
| Further edited to simplify results It is not difficult to show that the three eigenvalues, w , of M are equal if and only if M is diagonal; i.e., ab = ac = bc = 0 . f[e_] := 2 Norm[e]^-3 (1 - 3 Sin[θ]^2 Cos[ϕ - ArcTan[e[[1]], e[[2]]]]^2) Cos[{x, y}.e]abeval = f[{1, 0}](* 2 Cos[x] (1 - 3 Cos[ϕ]^2 Sin[θ]^2) *)aceval = f[{0, 1}](* 2 Cos[y] (1 - 3 Sin[θ]^2 Sin[ϕ]^2) *)bceval = Simplify[TrigExpand[f[{1, 1}] + f[{-1, 1}]]](* (Cos[x] Cos[y] (1 + 3 Cos[2 θ]) + 6 Sin[x] Sin[y] Sin[θ]^2 Sin[2 ϕ])/(2 Sqrt[2]) *) Solutions can be obtained in an orderly manner as follows. For {Cos[x] -> 0, Cos[y] -> 0} , abeval and aceval are zero, and bceval reduces to Sin[θ] Sin[2 ϕ] == 0 For {Sin[x] -> 0, Cos[y] -> 0} , aceval and bceval are zero, and abeval reduces to 1 - 3 Cos[ϕ]^2 Sin[θ]^2 == 0 Finally, for {Cos[x] -> 0, Sin[y] -> 0} , abeval and bceval are zero, and aceval reduces to (1 - 3 Sin[θ]^2 Sin[ϕ]^2) == 0 These curves are plotted below and indicate where solutions are located in θ and ϕ . ContourPlot[{Sin[θ] Sin[2 ϕ] == 0, (1 - 3 Cos[ϕ]^2 Sin[θ]^2) == 0, (1 - 3 Sin[θ]^2 Sin[ϕ]^2) == 0}, {θ, 0, Pi + .01}, {ϕ, 0, 2 Pi + .01}, Frame -> False, Axes -> True, Ticks -> {{0, Pi}, {0, Pi, 2 Pi}}, AxesLabel -> {"θ", "ϕ"}, ContourStyle -> Directive[Black, Thick], AxesStyle -> Directive[Black, Bold, Thick, 12]] Other values of x and y give rise to discrete points in θ and ϕ , located at the intersections of curves in this plot. Band Structure Plot With the information just presented, generating band structure plots is straightforward. To do so, evaluate s seval = f[{2, 0}] + f[{0, 2}](* 1/4 Cos[2 x] (1 - 3 Cos[ϕ]^2 Sin[θ]^2) + 1/4 Cos[2 y] (1 - 3 Sin[θ]^2 Sin[ϕ]^2) *) define mplt[θ0_, ϕ0_] := Module[{meval = Det[M] /. {ab -> abeval, ac -> aceval, bc -> bceval, s -> seval} /. {θ -> θ0, ϕ -> ϕ0} // Simplify}, Plot3D[Evaluate[w /. Solve[meval == 0, w]], {x, -Pi, Pi}, {y, -Pi, Pi}, AxesLabel -> {"x", "y"}, AxesStyle -> Directive[Black, Bold, 12], Ticks -> {{-Pi, 0, Pi}, {-Pi, 0, Pi}, Automatic}, ImageSize -> Large, ViewPoint -> {1.4, -3.0, .35}]] and invoke it with any pair {θ0, ϕ0} from the plot above or from the three equations that the plot represents. For instance mplt[Pi/2, ArcSin[Sqrt[1/3]]] or mplt[Pi/2, ArcCos[Sqrt[1/3]]] Plots for values corresponding to interior curve intersections from the {θ0, ϕ0} plot are in a sense degenerate. mplt[ArcSin[Sqrt[1/3]], Pi] mplt[0, 0] , of course, gives the plot in the Question. Addendum At the request of the OP in a comment below, here is a more detailed argument that M must be diagonal for its three eigenvalues to be equal. To begin, its Determinant must be proportional to [-(w - w0)^3 , where w0 is the three-fold-repeated eigenvalue. eq0 = Expand[-(w - w0)^3](* -w^3 + 3 w^2 w0 - 3 w w0^2 + w0^3 *) The Determinant of M actually is eq = Collect[Det[M], w, Simplify](* 2 ab ac bc - ab^2 s - s (ac^2 + bc^2 - s^2) + (ab^2 + ac^2 + bc^2 - 3 s^2) w + 3 s w^2 - w^3 *) Equating the two yields Collect[eq - eq0, w, Simplify](* 2 ab ac bc - ab^2 s - ac^2 s - bc^2 s + s^3 + 3 w^2 (s - w0) - w0^3 + w (ab^2 + ac^2 + bc^2 - 3 s^2 + 3 w0^2) *) and the coefficient of every power of w must vanish. Thus, w0 must be equal to s . With that substitution, Collect[% /. w0 -> s, {w, s}, Simplify](* 2 ab ac bc + (-ab^2 - ac^2 - bc^2) s + (ab^2 + ac^2 + bc^2) w *) The coefficient of w in the last expression vanishes if and only if all three of ab , ac , and bc vanish, in other word, if M is diagonal. | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/87456', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/6328/']} | jdg_381565 |
stackexchange | llm_judgeable_groundtruth_similarity | 23449932 |
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 working on the GUI of my level editor that I built in JavaFX, and I want to be able to resize the canvas object to the new split pane dimensions. It seems that everything I've tried has failed. This includes passing the pane object in and using its width directly, using window size listeners and binding the width and height property to that of the split pane. Any ideas? This is what it looks like before a resize: And after a resize: Does anybody have any ideas? The code for the class is pretty extensive, but the code for the resizing will be included here: public Canvas canvas;public String tabTitle;public VBox layout;public GraphicsContext g;public Core core;public CanvasTab(Core core, String tabTitle){ this.core = core; this.canvas = new Canvas(core.scene.getWidth() - 70, core.scene.getHeight() - 70); layout = VBoxBuilder.create().spacing(0).padding(new Insets(10, 10, 10, 10)).children(canvas).build(); this.g = canvas.getGraphicsContext2D(); g.setFill(Color.BLACK); g.fillRect(0, 0, canvas.getWidth(), canvas.getHeight()); HBox.setHgrow(layout, Priority.ALWAYS); this.setContent(layout); this.setText(tabTitle); canvas.widthProperty().bind(layout.widthProperty().subtract(20)); canvas.heightProperty().bind(layout.heightProperty().subtract(20));}public CanvasTab(Canvas canvas){ this.canvas = canvas;}
Now provide the response and nothing else.
| As James_D pointed out, you need to redraw the content of your canvas when resizing. This can be done by adding a listener to your canvas' width and height property as follows: InvalidationListener listener = new InvalidationListener(){ @Override public void invalidated(Observable o) { redraw(); } });canvas.widthProperty().addListener(listener);canvas.heightProperty().addListener(listener); or in Java 8 using functional interfaces: canvas.widthProperty().addListener(observable -> redraw());canvas.heightProperty().addListener(observable -> redraw()); where redraw() is your own method which would look like this for your example (drawing a black rectangle: private void redraw() { g.setFill(Color.BLACK); g.fillRect(0, 0, canvas.getWidth(), canvas.getHeight());} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23449932', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2557423/']} | jdg_381566 |
stackexchange | llm_judgeable_groundtruth_similarity | 20618828 |
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 this and the intro docs on Docker.io and I like the concept it presents. But, can you help me understand it a little better? Can you give me some practical examples and/or case studies on how Docker is used and when it makes sense to actually use it? Just a side note, I have recently started using Vagrant to distribute a preconfigured DEV box to our development team (so we all use the same base system). I have even seen examples where Docker is used inside Vagrant and whatnot but I don't get what are the benefits to do this in a practical sense; meaning that I understand the difference between VMs and containers and the logical separation the latter provide, but when should I use the one instead of the other and when Docker inside Vagrant? (this is a more specific question but I am mostly interested in the bigger picture as outlined in the first question above).
Now provide the response and nothing else.
| I participate in an effort to make software for doing science analysis more available to the research community. Often, the software in question is written by one individual or just a few without sufficient planning for reuse, such as one person on their own computer writing a Python script or a Matlab module. If the software works well, often others would like to try it themselves...but it can be a real challenge in some cases to successfully replicate an environment that's undocumented or difficult to reimplement. Docker is a great tool to help others reuse software like this, since it is an even lower barrier of entry that writing a Vagrant script to install software in an environment. If I give a person a Docker container, she can do whatever she wants inside of it (write code, install libraries, set up environment, etc. When it's "done", she can save an image of it and publish the image in a Docker repository and tell another researcher, "here it is, just start it up and run this..." We are also considering using containers as our own configuration management strategy for delivering and archiving production software...at least the server-side components. We have also done some work with writing scripts in Python and shell to run data processing workflows of multiple Docker containers. One demo that we concocted was to run OpenCV on an image to extract faces of people, then ImageMagick to crop out the faces, and finally ImageMagick again to make a collage of all of the faces. We built a container for OpenCV and a container for ImageMagick, then wrote a Python script to execute a "docker run ..." on each of the containers with the requisite parameters. The Python scripting was accomplished using the docker-py project which worked well for what we needed from it. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20618828', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1107118/']} | jdg_381567 |
stackexchange | llm_judgeable_groundtruth_similarity | 1102359 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How can I programmatically detect that a deadlock has occurred in a Java program?
Now provide the response and nothing else.
| You can do this programmatically using the ThreadMXBean that ships with the JDK: ThreadMXBean bean = ManagementFactory.getThreadMXBean();long[] threadIds = bean.findDeadlockedThreads(); // Returns null if no threads are deadlocked.if (threadIds != null) { ThreadInfo[] infos = bean.getThreadInfo(threadIds); for (ThreadInfo info : infos) { StackTraceElement[] stack = info.getStackTrace(); // Log or store stack trace information. }} Obviously you should try to isolate whichever thread is performing this deadlock check - Otherwise if that thread deadlocks it won't be able to run the check! Incidentally this is what JConsole is using under the covers. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1102359', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_381568 |
stackexchange | llm_judgeable_groundtruth_similarity | 3621464 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In my answer to this question , I mentioned that we used UpperCamelCase parsing to get a description of an enum constant not decorated with a Description attribute, but it was naive, and it didn't work in all cases. I revisited it, and this is what I came up with: var result = Regex.Replace(camelCasedString, @"(?<a>(?<!^)[A-Z][a-z])", @" ${a}");result = Regex.Replace(result, @"(?<a>[a-z])(?<b>[A-Z0-9])", @"${a} ${b}"); The first Replace looks for an uppercase letter, followed by a lowercase letter, EXCEPT where the uppercase letter is the start of the string (to avoid having to go back and trim), and adds a preceding space. It handles your basic UpperCamelCase identifiers, and leading all-upper acronyms like FDICInsured. The second Replace looks for a lowercase letter followed by an uppercase letter or a number, and inserts a space between the two. This is to handle special but common cases of middle or trailing acronyms, or numbers in an identifier (except leading numbers, which are usually prohibited in C-style languages anyway). Running some basic unit tests, the combination of these two correctly separated all of the following identifiers: NoDescription, HasLotsOfWords, AAANoDescription, ThisHasTheAcronymABCInTheMiddle, MyTrailingAcronymID, TheNumber3, IDo3Things, IAmAValueWithSingleLetterWords, and Basic (which didn't have any spaces added). So, I'm posting this first to share it with others who may find it useful, and second to ask two questions: Anyone see a case that would follow common CamelCase-ish conventions, that WOULDN'T be correctly separated into a friendly string this way? I know it won't separate adjacent acronyms (FDICFCUAInsured), recapitalize "properly" camelCased acronyms like FdicInsured, or capitalize the first letter of a lowerCamelCased identifier (but that one's easy to add - result = Regex.Replace(result, "^[a-z]", m=>m.ToString().ToUpper()); ). Anything else? Can anyone see a way to make this one statement, or more elegant? I was looking to combine the Replace calls, but as they do two different things to their matches it can't be done with these two strings. They could be combined into a method chain with a RegexReplace extension method on String, but can anyone think of better?
Now provide the response and nothing else.
| So while I agree with Hans Passant here, I have to say that I had to try my hand at making it one regex as an armchair regex user. (?<a>(?<!^)((?:[A-Z][a-z])|(?:(?<!^[A-Z]+)[A-Z0-9]+(?:(?=[A-Z][a-z])|$))|(?:[0-9]+))) Is what I came up with. It seems to pass all the tests you put forward in the question. So var result = Regex.Replace(camelCasedString, @"(?<a>(?<!^)((?:[A-Z][a-z])|(?:(?<!^[A-Z]+)[A-Z0-9]+(?:(?=[A-Z][a-z])|$))|(?:[0-9]+)))", @" ${a}"); Does it in one pass. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3621464', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/436376/']} | jdg_381569 |
stackexchange | llm_judgeable_groundtruth_similarity | 36870847 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In my Ionic2 project, I put my fonts (ttf format) in the folder www/build/fonts.But when I build the app, the fonts disappear. How can I do ?
Now provide the response and nothing else.
| Don't place your fonts in node_modules or build folder. node_modules folder gets update on npm install or npm update and build folder gets created with each build command. Best possible way, that i am currently using with a production app is to put your fonts inside www/fonts folder and reference them inside your /app/themes/app.core.scss like below. @font-face { font-family: 'gurbaniakharregular'; src: url('../../fonts/gurbaniakhar.ttf.eot'); src: url('../../fonts/gurbaniakhar.ttf.eot?#iefix') format('embedded-opentype'), url('../../fonts/gurbaniakhar.ttf.woff2') format('woff2'), url('../../fonts/gurbaniakhar.ttf.woff') format('woff'), url('../../fonts/gurbaniakhar.ttf.ttf') format('truetype'), url('../../fonts/gurbaniakhar.ttf.svg#gurbaniakharregular') format('svg'); font-weight: normal; font-style: normal;} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36870847', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_381570 |
stackexchange | llm_judgeable_groundtruth_similarity | 8122748 |
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 develop a route that polls a directory containing CSV files, and for every file it unmarshals each row using Bindy and queues it in activemq. The problem is files can be pretty large (a million rows) so I'd prefer to queue one row at a time, but what I'm getting is all the rows in a java.util.ArrayList at the end of Bindy which causes memory problems. So far I have a little test and unmarshaling is working so Bindy configuration using annotations is ok. Here is the route: from("file://data/inbox?noop=true&maxMessagesPerPoll=1&delay=5000") .unmarshal() .bindy(BindyType.Csv, "com.ess.myapp.core") .to("jms:rawTraffic"); Environment is: Eclipse Indigo, Maven 3.0.3, Camel 2.8.0 Thank you
Now provide the response and nothing else.
| If you use the Splitter EIP then you can use streaming mode which means Camel will process the file on a row by row basis. from("file://data/inbox?noop=true&maxMessagesPerPoll=1&delay=5000") .split(body().tokenize("\n")).streaming() .unmarshal().bindy(BindyType.Csv, "com.ess.myapp.core") .to("jms:rawTraffic"); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8122748', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1045679/']} | jdg_381571 |
stackexchange | llm_judgeable_groundtruth_similarity | 41665629 |
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 swift for my project. I have an array of structs named Instrument . Later on I made a function that returns specific Instrument from array. Then I wanted to change value on one of its property, but this change is not reflected inside the array. I need to have this array to include all the changes on the elements inside. What do you think is the best practice here? Change Instrument from struct to class . Somehow rewrite the function that returns Instrument from array. Right now I use this function: func instrument(for identifier: String) -> Instrument? { if let instrument = instruments.filter({ $0.identifier == identifier }).first { return instrument } return nil} I start with the struct because swift is known to be language for structs and I want to learn when to use struct of class . thanks
Now provide the response and nothing else.
| With an array of struct Instrument, you can obtain the index for the Instrument with a particular identifier, and use that to access and modify a property of the Instrument. struct Instrument { let identifier: String var value: Int}var instruments = [ Instrument(identifier: "alpha", value: 3), Instrument(identifier: "beta", value: 9),]if let index = instruments.index(where: { $0.identifier == "alpha" }) { instruments[index].value *= 2}print(instruments) // [Instrument(identifier: "alpha", value: 6), Instrument(identifier: "beta", value: 9)] | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/41665629', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1236334/']} | jdg_381572 |
stackexchange | llm_judgeable_groundtruth_similarity | 11206393 |
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 arrays: http://jsfiddle.net/3NZsK/ I need to sort the arrays by their length. How to find out which one is the largest, the second largest, the third largest, and the least array? For example, I have the following dummy function, that can get us the second largest array: http://jsfiddle.net/WPRYf/ What is the above dummy function algorithm? Thank you in advance
Now provide the response and nothing else.
| var a = ["a", "a"]; b = ["b", "b", "b", "b"], c = ["c", "c", "c"], d = ["d"], container = [a, b, c, d];container.sort(function (a, b) { return b.length - a.length;});console.log(container); container will be sorted from longest (most elements) to shortest (least number of elements). Access it as: container[0] // longestcontainer[1] // 2nd longest// ... http://jsfiddle.net/pSRVq/ | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11206393', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/626063/']} | jdg_381573 |
stackexchange | llm_judgeable_groundtruth_similarity | 628632 |
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:
Why does thunder, that is heard about five or ten seconds after the lightning is seen, start as relatively quiet high pitched 'crackling' thunder which is, about five or ten seconds later than that, followed/replaced/drowned out by much louder lower pitched 'booming' thunder? I am under the impression that loud low frequency sound travels much faster than quiet mid range frequency sounds (by a factor of approximately two in the case of the sound/blast of a large nuclear explosion, meaning that the blast wave of a large nuclear explosion travels at twice the 'speed of sound' i.e about 600 meters per second). So I would have expected the loud low frequency sound from the lightning to reach me earlier and not later. But the low frequency sound does seem to reach me later. Edit: Another thing I find strange is that in many cases the later sounds (the loud booms of thunder) are remarkably distinct (or brief, being at most about 0.1 seconds in duration each, say), like a series of large bombs going off, as if coming from points or small volumes, rather than a continuous roar/rumble that gets louder and quieter at random. The latter might be what is expected if the loud later sound is coming from a randomly oriented line (with or without branches) with a length of five hundred meters to twenty kilometers.
Now provide the response and nothing else.
| I'm not an expert, but I spent some time with references 1 and 2 several years ago. This answer is based on some notes I took. Measurements using the radio waves produced by lightning indicate that lightning bolts inside thunderclouds (the ones that we can't see directly) are often mostly horizontal, and they can be anywhere from 1/2 km in length to 20 km in length, spanning a large portion of a large thundercloud. That says that the most distant part of the lightning bolt can be several kilometers farther away than the closest part. That is at least part of the reason why thunder lasts so much longer than the flash of lightning that produced it. Also, lightning typically has a jagged, branching shape. Experiments with smaller sparks have shown that the sound from a given segment is typically directional (louder in some directions than in others), so different segments of a jagged lightning bolt will tend to contribute different amounts to the overall sound because they're oriented differently. This is at least part of the reason for the sound's rich texture. Based on that information, here's a guess about why the sound from moderately distant lightning often starts with a quieter higher-pitched part. I'm picturing the shape of lightning as similar to the shape of a river with many smaller tributaries contributing to it. If we're closer to one of those small tributaries than to the main part of the river, then we'll hear the sound from that small tributary first (especially if its orientation is favorable, because the sound is directional), followed by the sounds from the more substantial parts that are farther away. This at least seems to explain the quiet-to-loud trend, and maybe it also helps explain the frequency trend: smaller sparks apparently don't produce as much lower-frequency sound as larger sparks, so most of the lower frequencies will come from the larger parts, which are farther away in this scenario. Frequency-dependent attenuation in the atmosphere and in the ground might also play a role (reference 3). References: Rakov and Uman (2003), Lightning: Physics and Effects (Cambridge University Press) Holmes et al (1971), "On the power spectrum and mechanism of thunder" ( https://doi.org/10.1029/JC076i009p02106 ) Lamancusa (2000), "Outdoor sound propagation" ( https://www.mne.psu.edu/lamancusa/me458/10_osp.pdf ) | {} | {'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/628632', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/295887/']} | jdg_381574 |
stackexchange | llm_judgeable_groundtruth_similarity | 49650184 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
var a = Math.floor(Math.random() * 10)var b = 10 - avar c = Math.floor(Math.random() * b )var d = a + cconsole.log("Jupiter threw " + a + " for the first round!")console.log("Jupiter threw " + c + " for the second round!")console.log("Jupiter scored a total of " + d + " points!")console.log("Jupiter threw " + a + " for the first round!")console.log("Jupiter threw " + c + " for the second round!")console.log("Jupiter scored a total of " + d + " points!") I'm a beginner to javascript trying to make a game and was wondering if you could use the same variable multiple times or do I have to make a new variable for each round? Thanks in advance!
Now provide the response and nothing else.
| There's a problem with your code as well as the string you're trying to parse. I'd try to figure out where that string is being generated, or if you're doing it yourself post that code as well. Valid Json uses "" around names, and "" around strings. Your string uses nothing around names and '' around strings. If you paste this into DartPad, the first will error out while the second will succeed: import 'dart:convert';void main() { JsonCodec codec = new JsonCodec(); try{ var decoded = codec.decode("[{id:1, text:'fdsf', completed: false},{id:2, text:'qwer', completed: true}]"); print("Decoded 1: $decoded"); } catch(e) { print("Error: $e"); } try{ var decoded = codec.decode("""[{"id":1, "text":"fdsf", "completed": false},{"id":2, "text":"qwer", "completed": true}]"""); print("Decoded 2: $decoded"); } catch(e) { print("Error: $e"); }} The issue with your code is that you expect the decoder to decode directly to a List. It will not do this; it will decode to a dynamic which happens to be a List<dynamic> whose items happen to be Map<String, dynamic> . See flutter's Json documentation for information on how to handle json in Dart. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49650184', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9596481/']} | jdg_381575 |
stackexchange | llm_judgeable_groundtruth_similarity | 9446184 |
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 working with Solr 3.5.0. I am importing from a JDBC data source and have a delimited field that I would like split into individual values. I'm using the RegexTransformer but my field isn't being split. sample value Bob,Carol,Ted,Alice data-config.xml <dataConfig> <dataSource driver="..." /> <document> <entity name="ent" query="SELECT id,names FROM blah" transformer="RegexTransformer"> <field column="id" /> <field column="names" splitBy="," /> </entity> </document></dataConfig> schema.xml <schema name="mytest" version="1.0"> <types> <fieldType name="string" class="solr.StrField" sortMissingLast="true" omitNorms="true"/> <fieldType name="integer" class="solr.IntField" omitNorms="true"/> </types> <fields> <field name="id" type="integer" indexed="false" stored="true" multiValued="false" required="true" /> <field name="name" type="string" indexed="true" stored="true" multiValued="true" required="true" /> </fields></schema> When I search : I get a result doc element like this: <doc> <int name="id">22</int> <arr name="names"> <str>Bob,Carol,Ted,Alice</str> </arr></doc> I was hoping to get this instead: <doc> <int name="id">22</int> <arr name="names"> <str>Bob</str> <str>Carol</str> <str>Ted</str> <str>Alice</str> </arr></doc> It's quite possible I misunderstand the RegexTransformer section of the wiki. I've tried changing my delimiter and I've tried using a different field for the parts (as shown in the wiki)... <field column="name" splitBy="," sourceColName="names" /> ...but that resulted in an empty name field. What am I doing wrong?
Now provide the response and nothing else.
| I handled a similar issue by creating a fieldtype in the schema file: <fieldType name="commaDelimited" class="solr.TextField"> <analyzer> <tokenizer class="solr.PatternTokenizerFactory" pattern=",\s*" /> </analyzer></fieldType> Then I applied that type to the field to the data field like: <field name="features" type="commaDelimited" indexed="true" stored="true"/> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9446184', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/185034/']} | jdg_381576 |
stackexchange | llm_judgeable_groundtruth_similarity | 34668012 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there a way in Go to combine URL paths similarly as we can do with filepaths using path.Join() ? For example see e.g. Combine absolute path and relative path to get a new absolute path . When I use path.Join("http://foo", "bar") , I get http:/foo/bar . See in Golang Playground .
Now provide the response and nothing else.
| The function path.Join expects a path, not a URL. Parse the URL to get a path and join with that path: u, err := url.Parse("http://foo")if err != nil { log.Fatal(err) }u.Path = path.Join(u.Path, "bar.html")s := u.String()fmt.Println(s) // prints http://foo/bar.html Use the url.JoinPath function in Go 1.19 or later: s, err := url.JoinPath("http://foo", "bar.html")if err != nil { log.Fatal(err) }fmt.Println(s) // prints http://foo/bar.html Use ResolveReference if you are resolving a URI reference from a base URL . This operation is different from a simple path join: an absolute path in the reference replaces the entire base path; the base path is trimmed back to the last slash before the join operation. base, err := url.Parse("http://foo/quux.html")if err != nil { log.Fatal(err)}ref, err := url.Parse("bar.html")if err != nil { log.Fatal(err)}u := base.ResolveReference(ref)fmt.Println(u.String()) // prints http://foo/bar.html Notice how quux.html in the base URL does not appear in the resolved URL. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/34668012', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/772000/']} | jdg_381577 |
stackexchange | llm_judgeable_groundtruth_similarity | 42828297 |
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 say I "want" 6 elements from an array which only contains 3. If the end is reached, start over. Example: let arr = ["a", "b", "c"];let wanted = 5;for(let i = 0; i < wanted; i++) { console.log(arr[i]);} Which of course returns: abcundefinedundefined Instead, I need: abcab Is there a way to start from the beginning of the array after the elements are over?
Now provide the response and nothing else.
| Get the remainder using % (Remainder) operator. console.log(arr[i % arr.length]); The remainder value would be within the array index range. For example: when i reaches to 3 => 3 % 3 = 0 4 => 4 % 3 = 1 0 => 0 % 3 = 0 . let arr = ["a", "b", "c"];let wanted = 5;for (let i = 0; i < wanted; i++) { console.log(arr[i % arr.length]);} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42828297', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4271469/']} | jdg_381578 |
stackexchange | llm_judgeable_groundtruth_similarity | 267543 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Among the papers indexed by MathSciNet and Zentralblatt MATH,I occasionally have seen papers which consist essentially onlyof text copied from elsewhere without proper attribution and withoutadding any significant value. I would be interested whether anyonehas an idea what the frequency of such papers among those indexed inthe mentioned databases roughly is. -- Are these extremely rare cases, or are such papers more common than one usually thinks, and perhaps even not easy to keep out of the databases ifone doesn't want to be too restrictive in which journals to cover? --Is there any data known on this? Also, if one spots such a paper -- should one report this to theauthors or copyright holders of the pieces of text from which the paper is composed, to the editorial board of the journal in which the paper is published, or to MathSciNet / Zentralblatt MATH --or rather just ignore it? What is common practice in such case?
Now provide the response and nothing else.
| On behalf of zbMATH (which is certainly also the case for MathSciNet), we would very much appreciate a notification of such cases, if they have not yet been detected at the level of editors or reviewers. There is the general impression of our editors (which has been discussed with our MathSciNet colleagues who seem to share this) that this behaviour has become significantly more widespread recently, and that such papers make it frequently into journals which usually have shown a level of decent peer review (which should generally filter such submissions). The notification could either be done by an email to [email protected] or to volunteer to write a short review about this case https://zbmath.org/become-a-reviewer/ . We would then evaluate the level of copying and 1) Inform the editorial board,2) our colleagues of MathSciNet,3) Add a review or editorial remark mentioning the degree of overlap, ideally taking into account statements of the editorial board and, possibly, the author(s) if provided. We do not display automated warnings like on arXiv because all existing tools (known to us) produce too many false positives when applied to math content, which seem unsatisfactory for public statements (e.g., arXiv claims overlap for arXiv:1609.02231 and arXiv:1412.0555 where the same problem is considered for genus three and even genus). Searching for "plagiarism" will not result in all cases, because that means that intention and priority has been clearly identified, which is not always clear especially when things are under investigation (indeed, we had various cases where the paper which was published, or even submitted, first turned out to be a copy of ongoing unpublished other work published later). Hence, the documents will be usually labeled as "identical", "almost identical", "parts are almost identical" etc. - the results https://zbmath.org/?t=&s=0&q=%28%28%22reviewer%27s+remark%22%7C+%22editorial+remark%22%29+%26+%28identical+%7C+plagiarism%29 may give an impression. Olaf Teschke, Managing Editor, zbMATH | {} | {'log_upvote_score': 7, 'links': ['https://mathoverflow.net/questions/267543', 'https://mathoverflow.net', 'https://mathoverflow.net/users/28104/']} | jdg_381579 |
stackexchange | llm_judgeable_groundtruth_similarity | 1392640 |
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:
Why does $$\sqrt{\log_x{\exp{\sqrt{\log_x{\exp{\sqrt{\log_x{\exp{\cdots}}}}}}}}}=\log_x{e}=\frac{1}{\ln{x}}$$ There only seems to be a relation when using square roots, but not for cubed roots or anything else. Why does this equation work and why does it only work for square roots? (The $e$ is not significant, by the way. You could give the exponential function a different base, $a$, and say the equation equals $log_x{a}$).
Now provide the response and nothing else.
| $$y=\sqrt{\log_x{\exp{\sqrt{\log_x{\exp{\sqrt{\log_x{\exp{\cdots}}}}}}}}}\implies y=\sqrt{\log_x\exp(y)}=\sqrt{y\log_xe}\\\therefore y=\log_xe$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1392640', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/193034/']} | jdg_381580 |
stackexchange | llm_judgeable_groundtruth_similarity | 24150713 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In Chrome and Firefox, typeof foo evalulates to 'undefined' . But typeof (function() { return foo; })() throws an error: ReferenceError: foo is not defined This destroys the notions that I have of susbstitutability of expressions! Until now, I knew of no conditions for which foo and (function() { return foo; })() are not the same. Is this standard behavior? If so, it would be helpful to quote the relevant part of the ECMAScript standard. EDIT: Another example: typeof (foo)typeof (foo + 0) I would have expect (foo) and (foo + 0) to throw an error. But the first one has no error; the second one does.
Now provide the response and nothing else.
| Basically, the typeof operator checks whether a variable¹ is unresolvable and returns "undefined" . That is, typeof returns a defined value for undeclared variables¹ before reaching the GetValue algorithm which throws for undeclared variables¹. Quoting ECMAScript 5.1 § 11.4.3 The typeof Operator (emphasis added): 11.4.3 The typeof Operator The production UnaryExpression : typeof UnaryExpression is evaluated as follows: Let val be the result of evaluating UnaryExpression . If Type ( val ) is Reference , then 2.1. If IsUnresolvableReference ( val ) is true , return "undefined" . 2.2 Let val be GetValue ( val ). Return a String determined by Type ( val ) according to Table 20 . In the other hand, the return statement -- like most operators and statements which read the value from identifier(s) -- will always call GetValue which throws on unresolvable identifiers (undeclared variables). Quoting ECMAScript 5.1 § 8.7.1 GetValue (V) (emphasis added): 8.7.1 GetValue (V) If Type (V) is not Reference, return V. Let base be the result of calling GetBase (V). If IsUnresolvableReference (V), throw a ReferenceError exception. Now, analyzing the code: typeof (function() { return foo; })() This code will instantiate a function object, execute it and only then typeof will operate on the function's return value (function call takes precedence over the typeof operator). Hence, the code throws while evaluating the IIFE's return statement, before the typeof operation can be evaluated. A similar but simpler example: typeof (foo+1) The addition is evaluated before typeof . This will throw an error when the Addition Operator calls GetValue on foo , before typeof comes into play. Now: typeof (foo) Does not throw an error as the grouping operator (parentheses) does not "evaluate" anything per se, it just forces precedence. More specifically, the grouping operator does not call GetValue . In the example above it returns an (unresolvable) Reference . The annotated ES5.1 spec even adds a note about this: NOTE This algorithm does not apply GetValue to the result of evaluating Expression. The principal motivation for this is so that operators such as delete and typeof may be applied to parenthesised expressions. N.B. I've wrote this answer with the focus on providing a simple and understandable explanation, keeping the technical jargon to a minimum while still being sufficiently clear and providing the requested ECMAScript standard references, which I hope to be a helpful resource to developers who struggle with understanding the typeof operator. ¹ The term "variable" is used for ease of understanding. A more correct term would be identifier , which can be introduced into a Lexical Environment not only through variable declarations, but also function declarations, formal parameters, calling a function ( arguments ), with / catch blocks, assigning a property to the global object, let and const statements (ES6), and possibly a few other ways. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24150713', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1212596/']} | jdg_381581 |
stackexchange | llm_judgeable_groundtruth_similarity | 645008 |
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 ran this command: grep -i 'bro*' shows.csv and got this as output 1845307,2 Broke Girls,2011,138,6.7,890931702042,An Idiot Abroad,2010,21,8.3,29759903747,Breaking Bad,2008,62,9.5,14025772249364,Broadchurch,2013,24,8.4,893781733785,Bron/Broen,2011,38,8.6,563572467372,Brooklyn Nine-Nine,2013,145,8.4,2095717569592,Chilling Adventures of Sabrina,2018,36,7.6,690417221388,Cobra Kai,2018,31,8.7,729931355642,Fullmetal Alchemist: Brotherhood,2009,69,9.1,111111118360,Johnny Bravo,1997,67,7.2,32185455275,Prison Break,2005,91,8.3,465246115341,Sabrina the Teenage Witch,1996,163,6.6,334581312171,The Umbrella Academy,2019,20,8,1408003339966,Unbreakable Kimmy Schmidt,2015,51,7.6,61891 Where is bro in breaking bad? In fact, o doesn't even appear in "Breaking bad". I tried it once more, and got the same result. It is not accounting for the last character. Is there something wrong in the way I am writing it? You can download the file shows.csv from https://cdn.cs50.net/2021/x/seminars/linux/shows.csv
Now provide the response and nothing else.
| In your code o* means "zero or more occurrences of o ". It seems you confused regular expressions with glob syntax (where o* means "one o and zero or more whatever characters"). In Breaking Bad there is exactly zero o characters after Br , so it matches bro* (case-insensitively). grep -i bro shows.csv will do what (I think) you want. | {} | {'log_upvote_score': 7, 'links': ['https://unix.stackexchange.com/questions/645008', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/466667/']} | jdg_381582 |
stackexchange | llm_judgeable_groundtruth_similarity | 41454333 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Recently I created a new Rails 5 app, without a git repository. The auto-generated Gemfile contains a new block I had not seen before: git_source(:github) do |repo_name| repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/") "https://github.com/#{repo_name}.git"end What's the meaning of it? Is it mandatory for every new app?
Now provide the response and nothing else.
| Its a workaround for a bug in Bundler which can cause sources from github to be loaded via HTTP and not HTTPS - which makes it vulnerable to man in the middle attacks. git_source adds a source which you can use so that the gem is downloaded from a git repository instead of a package from rubygems.org . git_source(:github) do |repo_name| repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/") "https://github.com/#{repo_name}.git"end Would make it so that when you declare: gem 'foo_bar', :github => 'foo/bar' Bundler would attempt to download the gem from https://github.com/foo/bar.git . Since fixing this would be a breaking change as it would invalidate any existing Gemfile.lock it is fixed in Bundler 2.x. At that point it should be safe to remove this workaround. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/41454333', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/955594/']} | jdg_381583 |
stackexchange | llm_judgeable_groundtruth_similarity | 26264939 |
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 kinda new to angular and I want to get some data from a webservice I wrote. I am sending some variable with it as a post. But how can I get the http variable in the function. It can maybe be a stupid question, but I cannot find the soluction. I need it in a function because I want to call it a couple of times. kljControllers.controller('CalendarPageController', ['$scope', function($scope, $http) { $scope.GetEvents = function() { var dataToPost = Array(); dataToPost.push($scope.month); dataToPost.push($scope.year); $scope.http.post('http://localhost:8080/webservice/calendarevent'). success(function(data, status, headers, config) { $scope.events = data.events; }). error(function(data, status, headers, config) { document.write("status"); }); } }}
Now provide the response and nothing else.
| The problem is that pytz : … differs from the documented Python API for tzinfo implementations; if you want to create local wallclock times you need to use the localize() method documented in this document … Further down, it says: Unfortunately using the tzinfo argument of the standard datetime constructors "does not work" with pytz for many timezones. >>> datetime(2002, 10, 27, 12, 0, 0, tzinfo=amsterdam).strftime(fmt)'2002-10-27 12:00:00 LMT+0020' So, you need to do what the docs suggest—using normalize , constructing UTC times and using astimezone , etc. Which one you want depends on exactly what you're trying to do. For example: >>> from datetime import datetime>>> from pytz import timezone>>> utc = timezone('UTC')>>> eastern = timezone('US/Eastern')>>> datetime(2014, 10, 6, 18, tzinfo=eastern).isoformat()'2014-10-06T18:00:00-04:56'>>> eastern.normalize(datetime(2014, 10, 6, 18, tzinfo=eastern)).isoformat()'2014-10-06T18:56:00-04:00'>>> datetime(2014, 10, 6, 18, tzinfo=utc).astimezone(eastern).isoformat()'2014-10-06T14:00:00-04:00'>>> eastern.localize(datetime(2014, 10, 6, 18)).isoformat()'2014-10-06T18:00:00-04:00' I think it's the last you want. As the docs for localize say: Convert naive time to local time. This method should be used to construct localtimes, rather than passing a tzinfo argument to a datetime constructor. And I think constructing a local time is exactly what you wanted here. If you're wondering why … well, if you look at the data that's in your Olson database, or just print out eastern._utcoffset , you'll see -1 day, +68640 minutes. That's 19.0166+ hours, not 19. Why? Because every timezone is defined with its starting offset, with adjustments from there. Eastern is based on New York's timezone as of 1883 Nov 18 12:03:58, at which point it was -04:56:02 from GMT. There's an adjustment for dates starting in 1920 that subtracts the extra 00:03:58. And of course the yearly adjustments back and forth one hour for DST. So, as of right now, Eastern is -04:00, but without any idea of what date it's supposed to represent, it's -04:56. And, because datetime just asks a timezone for its offset, rather than its offset at a particular time, that's what it gets. One last thing: EST is Eastern Standard Time, which is -05:00. That's not the time zone of any location in the US on 6 October 2014, because in 2014, the US's daylight saving time goes to 2 November. (There used to be counties in Indiana that were on EST during the summer, but there no longer are.) What you're looking for is EDT, Eastern Daylight Time, which is -04:00. Or, of course, ET, which is EDT during the summer and EST during the winter, which is what you get from looking up 'US/Eastern' or 'America/New_York' . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/26264939', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1423434/']} | jdg_381584 |
stackexchange | llm_judgeable_groundtruth_similarity | 365380 |
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 using Centos 7 Server And I Would Like To Save ip Rule And Route Whenever Server Rebooted. ip rule add from x.x.x.x table 128ip route add table 128 to y.y.y.y/y dev eth0ip route add table 128 default via z.z.z.z The mentioned Rule and Route lose once i reboot the server which means i need to run the 3 commands each time server rebooted. I need to make ip rule and route persist whenever server is rebooted.
Now provide the response and nothing else.
| Take a look at /etc/rc.d/rc.local . The file states Please note that you must run chmod +x /etc/rc.d/rc.local to ensure that this script will be executed during boot. So: chmod +x /etc/rc.d/rc.local Then place your commands above the last line touch /var/lock/subsys/local There is better way using relevant configuration files. Rules and routes can be specified using corresponding file names. All the relevant configuration files are given below. (The device names may differ.) /etc/iproute2/rt_tables/etc/sysconfig/network/etc/sysconfig/network-scripts/ifcfg-eth0/etc/sysconfig/network-scripts/ifcfg-eth1/etc/sysconfig/network-scripts/route-eth0/etc/sysconfig/network-scripts/route-eth1/etc/sysconfig/network-scripts/rule-eth0/etc/sysconfig/network-scripts/rule-eth1 To create a named routing table, use /etc/iproute2/rt_tables . I added 128 mynet . ## reserved values#255 local254 main253 default0 unspec## local#128 mynet The EL 7.x /etc/sysconfig/network file. The default route is GATEWAY . NETWORKING=yesHOSTNAME=hostname.sld.tldGATEWAY=10.10.10.1 THE EL 7.x /etc/sysconfig/network-scripts/ifcfg-eth0 file, without HWADDR and "UUID". This configures a static IP address for eth0 without using NetworkManager . DEVICE=eth0TYPE=EthernetONBOOT=yesNM_CONTROLLED=noBOOTPROTOCOL=noneIPADDR=10.10.10.140NETMASK=255.255.255.0NETWORK=10.10.10.0BROADCAST=10.10.10.255 THE EL 7.x /etc/sysconfig/network-scripts/ifcfg-eth1 file, without HWADDR and UUID . This configures a static IP address for eth1 without using NetworkManager . DEVICE=eth0TYPE=EthernetONBOOT=yesNM_CONTROLLED=noBOOTPROTOCOL=noneIPADDR=192.168.100.140NETMASK=255.255.255.0NETWORK=192.168.100.0BROADCAST=192.168.100.255 The EL 7.x /etc/sysconfig/network-scripts/route-eth1 file. The default route was already specified in /etc/sysconfig/network . 192.168.100.0/24 dev eth1 table mynetdefault via 192.168.100.1 dev eth1 table mynet The EL 7.x /etc/sysconfig/network-scripts/rule-eth1 file: from 192.168.100.0/24 lookup mynet Update for RHEL8 This method described above works with RHEL 6 & RHEL 7 as well as the derivatives, but for RHEL 8 and derivatives, one must first install network-scripts to use the method described above. dnf install network-scripts The installation produces a warning that network-scripts will be removed in one of the next major releases of RHEL and that NetworkManager provides ifup / ifdown scripts as well. | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/365380', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/227199/']} | jdg_381585 |
stackexchange | llm_judgeable_groundtruth_similarity | 54278 |
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:
Consider a continuous time real-valued Markov process $X_t$ given by an SDE:$$dX_t = \mu(X_t)dt+\sigma (X_t)dW_t.$$ Let $\mu,\sigma\in C^1(\mathbb R)$ and $\sigma\ge0$. Moreover let us assume that $\mu,\sigma$ are such that there exists a unique solution for any initial value $X_0 = x$. I guess that if for some $x\in \mathbb R$ we have $\sigma(x)>0$ then there exist such a neighborhood $U(x)$ that for all $y\in U(x)$ and for any neighborhood $U(y)$ there exists $t'>0$ such that $$\mathsf P\{X_t \in U(y)|X_0 = x\}>0$$ for all $0<t\leq t'$. Does anybody have an idea how to prove it?
Now provide the response and nothing else.
| Yes, your guess is correct, but we can say a lot more than that. If $\sigma,\mu$ are continuous, $X_0=x$ and $\sigma > 0$ on some connected neighbourhood $U$ of $x$, then $\mathbb{P}(X_t\in V) > 0$ for all positive times $t$ and nonempty open sets $V\subseteq U$.We can go even further than this though. If $\gamma\colon[0,t^\prime]\to\mathbb{R}$ is continuous with $\gamma(0)=x$ and $\sigma(\gamma(t)) > 0$, then $\mathbb{P}(\sup_{t\le t^\prime}\vert X_t-\gamma(t)\vert < \epsilon) > 0$ for all positive $\epsilon$. Stated another way, the support of the paths of $X$ (over a finite time interval) contains all continuous paths starting from $x$ along which $\sigma$ is positive. These statements also hold in the more general case of diffussions in $\mathbb{R}^n$. In fact, it is not necessary to assume that $X$ is a diffusion at all, only that it can be expressed as a stochastic integral. That is, $\sigma,\mu$ do not have to be specified as functions of $X$. In the $n$-dimensional case, we can write$$dX^i=\sum_{j=1}^m\sigma^{ij}_t\,dW^j_t+\mu^i_t\,dt.$$Here, $X=(X^1,\ldots,X^n)$ is an $n$-dimensional process with $X_0=x\in\mathbb{R}^n$ and $W=(W^1,\ldots,W^m)$ is an $m$-dimensional Brownian motion. You can consider $\sigma^{ij}_t$ and $\mu^i_t$ to be functions of $X_t$ if you like, but that is not necessary. All that matters is that they are predictable processes (which includes all continuous and adapted processes). First, supposing that $\mu,\sigma$ satisfy some boundedness conditions whenever $X$ is close to $x$, then there is a positive probability of $X$ remaining arbitrarily close to $x$. I will use $\Vert\cdot\Vert$ to denote the Euclidean norms on $\mathbb{R}^n$ and on the $n\times n$ matrices. 1) Suppose there exists $K > 0$ such that $\Vert(\sigma_t\sigma_t^T)^{-1}\Vert\le K$, $\Vert(\sigma_t\sigma_t^T)^{-1}\mu_t\Vert\le K$ and $\Vert\sigma_t\sigma^T_t\Vert\le K$ whenever $\Vert X_t - x\Vert < \delta$ (some positive $\delta$). Then, $\mathbb{P}(\sup_{t\le t^\prime}\Vert X_t-x\Vert < \epsilon) > 0$ for all positive $\epsilon$. In the one dimensional case, we need only suppose that $\sigma^{-2}\mu\le K$ and $\sigma^2\le K$ (there is no need to assume that $\sigma$ is bounded away from zero). I'll prove (1) in a moment. First, it has the following consequence. 2) Let $\gamma\colon[0,t^\prime]\to\mathbb{R}^n$ be continuous such that $\gamma(0)=x$ and there is $K > 0$ with $\Vert(\sigma_t\sigma_t^T)^{-1}\Vert\le K$, $\Vert(\sigma_t\sigma_t^T)^{-1}\mu_t\Vert\le K$ and $\Vert\sigma_t\sigma^T_t\Vert\le K$ whenever $\Vert X_t-\gamma(t)\Vert < \delta$ (some positive $\delta$). Then, $\mathbb{P}(\sup_{t\le t^\prime}\Vert X_t-\gamma(t)\Vert < \epsilon) > 0$ for all positive $\epsilon$. In particular, the conditions are satisfied if $\sigma_t=\sigma(X_t),\mu_t=\mu(X_t)$ are continuous functions of $X_t$ and $\sigma(\gamma_t)\sigma(\gamma_t)^T$ is nonsingular, implying the statements in the first paragraph of this post. To see that (2) follows from (1), consider the case where $\gamma$ is continuously differentiable (this is enough, as all continuous functions can be uniformly approximated by smooth ones). Supposing that the requirements of (2) are met, look at $\tilde X_t=X_t-\gamma(t)$. This satisfies the requirements of (1) with $\mu$ replaced by $\mu-\gamma^\prime$. So, by (1), $\tilde X$ has positive probability of remaining arbitrarily close to 0, and $X$ has positive probability of remaining arbitrarily close to $\gamma$. Now, let's prove (1). We can suppose that $\epsilon < \delta$ and, by stopping $X$ as soon as $\Vert X-x\Vert$ hits $\delta$, we can suppose that $\Vert(\sigma_t\sigma_t^T)^{-1}\Vert$, $\Vert(\sigma_t\sigma_t^T)^{-1}\mu_t\Vert$ and $\Vert\sigma_t\sigma_t^T\Vert$ are always bounded by $K$. Then, there is a predictable process $\nu$ with $\Vert\nu\Vert\le K$ and $\mu_t=\sigma_t\sigma_t^T\nu_t$. Define a new measure $\mathbb{Q}$ by the Girsanov transform$$\frac{d\mathbb{Q}}{d\mathbb{P}}=\exp\left(-\sum_{j=1}^m\int_0^{t^\prime}(\sigma^T_t\nu_t)^j\,dW^j_t-\frac12\int_0^{t^\prime}\nu_t^T\sigma_t\sigma^T_t\nu_t\,dt\right)$$This is an equivalent measure to $\mathbb{P}$ and, by the theory of Girsanov transforms, $\tilde W_t=W_t+\int_0^t\sigma^T_s\nu_s\,ds$ is a $\mathbb{Q}$-Brownian motion. As we have$$dX^i_t=\sum_{j=1}^m\sigma^{ij}_t\,d\tilde W^j_t$$this reduces the problem to the case where $\mu$ is zero. So, let's suppose that that $\mu=0$ from now on. In the one dimensional case, where $dX_t=\sigma_t\,dW_t$, it is enough to suppose that $\sigma_t^2\le K$. This is because a stochastic time change can be used to write the local martingale $X$ as $X_t=x+B_{A_t}$ where $B$ is a Brownian motion with respect to its natural filtration and $A_t=\int_0^t\sigma_s^2\,ds\le Kt$. Then, $\sup_{t\le t^\prime}\vert X_t-x\vert < \epsilon$ whenever $\sup_{t\le Kt^\prime}\vert B_t\vert < \epsilon$. However, standard Brownian has nonzero probability of remaining within a positive distance $\epsilon$ of the origin (see the answers to this math.SE question), so $\{\sup_{t\le t^\prime}\vert X_t-x\vert < \epsilon\}$ has positive probability. In the multidimensional case we need to also assume that $\Vert(\sigma\sigma^T)^{-1}\Vert\le K$. We can then reduce to the one-dimensional case. Setting $Y=\Vert X-x\Vert^2$, integration by parts gives$$\begin{align}dY_t&=\tilde\sigma_t\,d\tilde W+\tilde\mu_t\,dt,\\\tilde\sigma_t&=2\sqrt{(X_t-x)^T\sigma_t\sigma_t^T(X_t-x)},\\\tilde\mu_t&={\rm Tr}(\sigma_t\sigma^T_t),\\\tilde W_t&=2\sum_{i,j}\int_0^t1_{\{X_s\not=x\}}\tilde\sigma_s^{-1}(X^i_s-x^i)\sigma^{ij}_s\,dW^j_s.\end{align}$$You can check that $\tilde W$ has quadratic variation $[\tilde W]_t=t$ so that, by Lévy's characterization of Brownian motion, $\tilde W$ is a standard Brownian motion. Then, $\tilde\sigma_t$, $\tilde\sigma_t^{-1}$ and $\tilde\mu_t$ are bounded for $Y_t$ lying in any given compact subset of $(0,\infty)$. If we let $\tau$ be the first time at which $Y$ hits $\epsilon^2/2$ then, applying (1) in the one-dimensional case to $Y_{\tau+t}$, there is a positive probability that $\sup_{t\le t^\prime}\vert Y_{\tau+t}-\epsilon^2/2\vert < \epsilon^2/2$. However, in this case, we have $\sup_{t\le t^\prime}\Vert X_t-x\Vert < \epsilon$. Finally, in the $n$-dimensional case, I'll give an example to show that $X$ need not have a positive probability of remaining close to its starting point, even when $\mu=0$ and $\sigma$ is bounded. Consider the two dimensional case, $n=2$, with $m=1$ and $\sigma_t=R\hat X_t$, where $R$ is the linear map giving a rotation by 90 degrees and $\hat x\equiv1_{\{x\not=0\}}x/\Vert x\Vert$. So,$$dX_t=R\hat X_t\,dW_t$$for a Brownian motion $W$. Then, $X^T\,dX=0$ and integration by parts shows that if $X_0\not=0$ then $\Vert X\Vert$ increases deterministically,$$\begin{align}\Vert X_t\Vert^2&=\Vert X_0\Vert^2+\sum_{i=1}^2[X^i]_t=\Vert X_0\Vert^2+\int_0^t\hat X_s^TR^TR\hat X_s\,ds\\&=\Vert X_0\Vert^2+t.\end{align}$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/54278', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/5887/']} | jdg_381586 |
stackexchange | llm_judgeable_groundtruth_similarity | 24133797 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
We can declare block as below in Objective-C. typedef void (^CompletionBlock) (NSString* completionReason); I'm trying to do this in swift, it give error. func completionFunction(NSString* completionReason){ }typealias CompletionBlock = completionFunction Error : Use of undeclared 'completionFunction' Definition : var completion: CompletionBlock = { } How to do this? Update: According to @jtbandes's answer, I can create closure with multiple arguments as like typealias CompletionBlock = ( completionName : NSString, flag : Int) -> ()
Now provide the response and nothing else.
| The syntax for function types is (in) -> out . typealias CompletionBlock = (NSString?) -> Void// ortypealias CompletionBlock = (result: NSData?, error: NSError?) -> Void var completion: CompletionBlock = { reason in print(reason) }var completion: CompletionBlock = { result, error in print(error) } Note that the parentheses around the input type are only required as of Swift 3+. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/24133797', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2223390/']} | jdg_381587 |
stackexchange | llm_judgeable_groundtruth_similarity | 2891356 |
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 programming application using libpcap. when I debug the application in normal mode, pcap cannot get the network device. it seems that I have to debug the application in root.How can I debug the application in root? I have the root password.I think eclipse has such an option that can add root for the debugging application,but I don't know how to do it.please help.
Now provide the response and nothing else.
| Enable your user to run gdb as root without being asked for anypassword: sudo visudo Add the following line after all other rules: <youruser> ALL=(root) NOPASSWD:/usr/bin/gdb Create or modify a debug configuration in eclipse to run gdb as root e.g. in Run > Debug Configurations > C/C++ Application > YourProject Debug: change Debugger > Main > GDB debugger from gdb to sudo -u <youruser> gdb Update (and warning!): In his comment nategoose pointed out that this answer should come with a warning: Enabling a user to use sudo for gdb like suggested in my answer in fact gives admin privileges to him/her which in many cases might be an undesired side effect. I therefore consider the answer appropriate in an environment where it's not assumed that the user would try to harm the system (e.g. it's your own personal computer or a virtual machine) For a multi-(non-trusted)-user environment I think it might be a better idead to utilize unix' file capabilities to enable gdb to debug an application without the need of admin privileges | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2891356', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/348220/']} | jdg_381588 |
stackexchange | llm_judgeable_groundtruth_similarity | 1858762 |
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 wrote some modules, and trying to run them. How I tell where to take the module from? I am writing in Windows, and tried to put it in c:\perl\lib but it didn't help. Can I put it in the same directory, as the file that calls the module?
Now provide the response and nothing else.
| Perl uses the paths in: @INC to search for modules. (.pm files) If you: perl -e 'print join "\n", @INC;' you'll see what paths are currently being searched for modules. (This @INC list is compiled into the perl executable) Then you can: BEGIN { unshift @INC, 'C:\mylibs' } or use lib 'C:\mylibs' and place MyModule.pm inside C:\mylibs to enable: use MyModule; | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1858762', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/140100/']} | jdg_381589 |
stackexchange | llm_judgeable_groundtruth_similarity | 37718329 |
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 an example to set borders on a frameless window, however it's not draggable. How can I make a frameless window draggable? Especially if I can see an example it'll be awesome. Here is my example code(normally the code is longer, that's why there are much libraries just don't mind them); from PyQt5.QtWidgets import (QMessageBox,QApplication, QWidget, QToolTip, QPushButton, QDesktopWidget, QMainWindow, QAction, qApp, QToolBar, QVBoxLayout, QComboBox,QLabel,QLineEdit,QGridLayout,QMenuBar,QMenu,QStatusBar, QTextEdit,QDialog,QFrame,QProgressBar )from PyQt5 import QtCore, QtWidgets, QtGuifrom PyQt5.QtGui import QIcon,QFont,QPixmap,QPalettefrom PyQt5.QtCore import QCoreApplication, Qt,QBasicTimerimport sysclass cssden(QMainWindow): def __init__(self): super().__init__() self.mwidget = QMainWindow(self) self.setWindowFlags(QtCore.Qt.FramelessWindowHint) #size self.setFixedSize(320, 450) self.center #label self.lbl = QLabel(self) self.lbl.setText("test") self.lbl.setStyleSheet("background-color: rgb(0,0,0);" "border: 1px solid red;" "color: rgb(255,255,255);" "font: bold italic 20pt 'Times New Roman';") self.lbl.setGeometry(5,5,60,40) self.show() #center def center(self): qr = self.frameGeometry() cp = QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) self.move(qr.topLeft())app = QApplication(sys.argv)app.setStyleSheet("QMainWindow{background-color: darkgray;border: 1px solid black}")ex = cssden()sys.exit(app.exec_())
Now provide the response and nothing else.
| You need to handle the mouse events yourself. We will need to add an event on mousePressEvent , which will keep the place where we last clicked on the window Then, we will add a mouseMoveEvent , which will calculate the distance between the last clicked point and the current mouse location. We will move the window according to this distance. This is the fixed code: import sysfrom PyQt5.QtCore import Qt, QPointfrom PyQt5.QtWidgets import QApplication, QMainWindow, QLabelclass cssden(QMainWindow): def __init__(self): super().__init__() # <MainWindow Properties> self.setFixedSize(320, 450) self.setStyleSheet("QMainWindow{background-color: darkgray;border: 1px solid black}") self.setWindowFlags(Qt.FramelessWindowHint) self.center() # </MainWindow Properties> # <Label Properties> self.lbl = QLabel(self) self.lbl.setText("test") self.lbl.setStyleSheet("QLabel{background-color: rgb(0,0,0); border: 1px solid red; color: rgb(255,255,255); font: bold italic 20pt 'Times New Roman';}") self.lbl.setGeometry(5, 5, 60, 40) # </Label Properties> self.oldPos = self.pos() self.show() def center(self): qr = self.frameGeometry() cp = QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) self.move(qr.topLeft()) def mousePressEvent(self, event): self.oldPos = event.globalPos() def mouseMoveEvent(self, event): delta = QPoint (event.globalPos() - self.oldPos) self.move(self.x() + delta.x(), self.y() + delta.y()) self.oldPos = event.globalPos()if __name__ == '__main__': app = QApplication(sys.argv) ex = cssden() sys.exit(app.exec_()) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/37718329', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4302226/']} | jdg_381590 |
stackexchange | llm_judgeable_groundtruth_similarity | 13582906 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
We're using the (almost completley undocumented) 'public API' for Web Deploy 3 to create a .zip package of our website and then sync it to a server: DeploymentBaseOptions destinationOptions = new DeploymentBaseOptions(){ UserName = //username, Password = //password, ComputerName = //a server};using (var deploymentObject = DeploymentManager.CreateObject(DeploymentWellKnownProvider.Package, "C:/MyWebsitePackage.zip")){ deploymentObject.SyncParameters.Load(packageParametersFile); \\ contains some connection string information and nothing more. DeploymentSyncOptions syncOptions = new DeploymentSyncOptions(); syncOptions.WhatIf = false; deploymentObject.SyncTo(destinationOptions, syncOptions);} This code worked perfectly until we installed .NET 4.5 on our production and build servers and upgraded the project we are deploying to 4.5 also. Now we're getting the following error: The application pool that you are trying to use has the 'managedRuntimeVersion' property set to 'v4.0'. This application requires 'v4.5'. Learn more at: http://go.microsoft.com/fwlink/?LinkId=221672#ERROR_APPPOOL_VERSION_MISMATCH . Our server definately has .Net 4.5 installed and the and the IIS web site application pool version is '.NET Framework v4.0.30319' (I know it says v4 but .NET 4.5 is an 'in-place' upgrade and replaces 4.0 DLLs with the new version number .30319). It is possible to resolve this issue when deploying via MSBuild.exe command line (not by creating a package but by syncing directly to a server) by adding the /p:VisualStudioVersion=11.0 flag (which causes a different web application targets file to be used which somehow allows deployment of a .NET 4.5 application). Does anyone know why Web Deploy API complains like this and how I can resolve this error in the same way as the MSBuild solution?
Now provide the response and nothing else.
| Easiest would probably be just including IgnoreDeployManagedRuntimeVersion property from Microsoft.Web.Publishing.targets into the .csproj or as a parameter to MSBuild during /t:package step. Other option might be parameters.xml in project root to make managedRuntimeVersion overwriteable with MSDeploy parameters, or setting it directly in .zip in archive.xml as a predeployment step. Update (too long to reply as comment): Well, it's less of a hack than what VS 2012 itself does. Do a publish to IIS from VS (the Web Deploy option) and the package it'll generate will ll be the content of temp folder and a parameters xml, not a zip you get when doing a generic packaging, and runtime version wil be set to 4 even though project is 4.5. IgnoreDeployManagedRuntimeVersion simply will omit it completely. If you do Web Deploy Package option from VS you'll get a zip with 4.5 in the archive.xml and if you try to manually import that VS outputted zip into IIS directly, you'll get the error popup with 4.0 vs 4.5 app pool error, same as the one you get from running msbuild /t:package and msdeploy :sync from command line. VS (devenv) doesn't do it "right", it quietly overwrites the project setting, and it's not MSDeploy's fault as version is set during compilation/packaging (MSBuild/devenv) not during deployment. By the way, re API docs, yes they are practically nonexistent, but I find the command line docs tolerable (called Web Deploy not MSDeploy, eg http://technet.microsoft.com/en-us/library/dd569089.aspx and others) and mentally mapping those to dotPeek output helps a little. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13582906', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/761294/']} | jdg_381591 |
stackexchange | llm_judgeable_groundtruth_similarity | 625 |
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:
Classical mechanics: $t\mapsto \vec x(t)$, the world is described by particle trajectories $\vec x(t)$ or $x^\mu(\lambda)$, i.e. the Hilbert vector is the particle coordinate function $\vec x$ (or $x^\mu$), which is then projected into the space parametrized by the "coordinate" time $t$ or the relativistic parameter $\lambda$ (which is not necessarily monotonous in $t$). Interpretation: For each parameter value, the coordinate of a particle is described. Deterministic: The particle position itself Quantum mechanics: $x^\mu\mapsto\psi(x^\mu)$, (sometimes called "the first quantization ") yields Quantum mechanics , where the Hilbert vector is the wave function (being a field) $|\Psi\rangle$ that is for example projected into coordinate space so the parameters are $(\vec x,t)$ or $x^\mu$. Interpretation: For each coordinate, the quantum field describes the charge density (or the probability of measuring the particle at that position if you stick with the non-relativistic theory). Deterministic: The wave function Non-deterministic: The particle position Quantum Field Theory : $\psi(x^\mu)\mapsto \Phi[\psi]$, (called the second quantization despite the fact that now the wave field is quantized, not the coordinates for a second time) basically yields a functional $\Phi$ as Hilbert vector projected into quantum field space parametrized by the wave functions $\psi(x^\mu)$. Interpretation: For each possible wave function, the (to my knowledge nameless) $\Phi$ describes something like the probability of that wave function to occur (sorry, I don't know how to formulate this better, it's not really a probability). One effect is for example particle generation, thus the notion "particle" is fishy now Deterministic: The functional $\Phi$ Non-deterministic: The wave function $\psi$ and the "particle" position Now, could there be a third quantization $\Phi[\psi(x^\mu)] \mapsto \xi\{\Phi\}$? What would it mean? And what about fourth, fifth, ... quantization? Or is second quantization something ultimate?
Now provide the response and nothing else.
| One more answer against “second quntization”, because I think it is a good demonstration of how a lame notation can obscure a physical meaning. The first statement is : there is no second quantization. For example, here is citation from Steven Weinberg's book “ The Quantum Theory of Fields ” Vol.I: It would be a good thing if the misleading expression ‘second quantization’ were permanently retired. [I would even say that there is no quantization at all, as a procedure to pass from classical theory to quantum one, because (for example) quantum mechanics of single particle is more fundamental than the classical mechanics, therefore you can derive all “classical” results from QM but not vice versa. But I understand that it is a too speculative answer.] There is a procedure called “canonical quantization”, which is used to construct a quantum theory for a classical system which has Hamiltonian dynamics, or more generally, to construct a quantum theory which has a certain classical limit. In this case, if by the “canonical quantization” of a Hamiltonian system with finite number of degrees of freedom (classical mechanics) you imply quantum mechanics (QM) with fixed number of particles, then quantum field theory (QFT) is the “canonical quantization” of a classical Hamiltonian system with infinite number of degrees of freedom - classical field theory, not quantum mechanics . For such procedure, there is no difference between quantization of the electro-magnetic field modes and quantization of vibrational modes of the surface of the droplet of superfluid helium. One more citation from Weinberg's book: The wave fields $\phi$, $\varphi$, etc, are not probability amplitudes at all... It is useful to keep in mind the following analogy: the coordinates are the “classical configuration” of a particle. QM wave function $\psi(x)$ corresponds to the “smearing” of a quantum particle over all possible “classical configurations”. QFT wave function $\Psi(A)$ corresponds to “smearing” of a quantum field over all possible configurations of a classical field $A$. Operator $\hat{A}$ corresponds to the observable $A$ in the same way as observable $x$ is represented by Hermitian operators $\hat{x}$ in QM. The second statement is : “canonical quantization” is irrelevant in the context of fundamental theory. QFT is the only way to marry quantum mechanics to special relativity and can be contracted without a reference to any "classical crutches" Conclusion : There is not any sequence of “quantizations” (1st, 2nd,.. nth). | {} | {'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/625', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/97/']} | jdg_381592 |
stackexchange | llm_judgeable_groundtruth_similarity | 7688644 |
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 a Java EE application in which I need Base64 Encoding/Decoding So I added commons-codec-1.5.jar in WEB-INF/lib folder of my application and used import org.apache.commons.codec.binary.Base64; in the Java file. During compile time, when I type Base64 , it shows encodeBase64String method is available. But during runtime it is throwing an exception like this: java.lang.NoSuchMethodError:org.apache.commons.codec.binary.Base64.encodeBase64String I have the JAR in the buildpath, but still I don't understand why it throws me the above error.
Now provide the response and nothing else.
| That method was introduced in Commons Codec 1.4. This exception indicates that you've an older version of Commons Codec somewhere else in the webapp's runtime classpath which got precedence in classloading. Check all paths covered by the webapp's runtime classpath. This includes among others the Webapp/WEB-INF/lib , YourAppServer/lib , JRE/lib and JRE/lib/ext . Finally remove or upgrade the offending older version. Update : as per the comments, you can't seem to locate it. I can only suggest to outcomment the code using that newer method and then put the following line in place: System.out.println(Base64.class.getProtectionDomain().getCodeSource().getLocation()); That should print the absolute path to the JAR file where it was been loaded from during runtime. Update 2 : this did seem to point to the right file. Sorry, I can't explain your problem anymore right now. All I can suggest is to use a different Base64 method like encodeBase64(byte[]) and then just construct a new String(bytes) yourself. Or you could drop that library and use a different Base64 encoder, for example this one . | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7688644', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/907190/']} | jdg_381593 |
stackexchange | llm_judgeable_groundtruth_similarity | 10795982 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Possible Duplicate: getting nullpointer exception when clicking on checkdata button nullpointer exception raises when i click on the button i was unable to handle null pointer exception in my code getting an error in this line as DataManipulator.createCertificatesEntry( (Certificates) testCertificates); this is my createCertificatesEntry public void createCertificatesEntry(Certificates certificates) { ByteArrayOutputStream out = new ByteArrayOutputStream(); certificates.getBitmap().compress(Bitmap.CompressFormat.PNG, 100, out); ContentValues cv = new ContentValues(); cv.put(KEY_IMG, out.toByteArray()); mDb.insert(CERTIFICATES_TABLE, null, cv); } is anything wrong with this code this is logcat05-29 12:57:42.577: E/AndroidRuntime(625): FATAL EXCEPTION: main05-29 12:57:42.577: E/AndroidRuntime(625): java.lang.RuntimeException: Unable to start activity ComponentInfo{list.certificates/list.certificates.CheckData}: java.lang.NullPointerException05-29 12:57:42.577: E/AndroidRuntime(625): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1955)05-29 12:57:42.577: E/AndroidRuntime(625): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)05-29 12:57:42.577: E/AndroidRuntime(625): at android.app.ActivityThread.access$600(ActivityThread.java:122)05-29 12:57:42.577: E/AndroidRuntime(625): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)05-29 12:57:42.577: E/AndroidRuntime(625): at android.os.Handler.dispatchMessage(Handler.java:99)05-29 12:57:42.577: E/AndroidRuntime(625): at android.os.Looper.loop(Looper.java:137)05-29 12:57:42.577: E/AndroidRuntime(625): at android.app.ActivityThread.main(ActivityThread.java:4340)05-29 12:57:42.577: E/AndroidRuntime(625): at java.lang.reflect.Method.invokeNative(Native Method)05-29 12:57:42.577: E/AndroidRuntime(625): at java.lang.reflect.Method.invoke(Method.java:511)05-29 12:57:42.577: E/AndroidRuntime(625): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)05-29 12:57:42.577: E/AndroidRuntime(625): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)05-29 12:57:42.577: E/AndroidRuntime(625): at dalvik.system.NativeStart.main(Native Method)05-29 12:57:42.577: E/AndroidRuntime(625): Caused by: java.lang.NullPointerException05-29 12:57:42.577: E/AndroidRuntime(625): at list.certificates.DataManipulator.createCertificatesEntry(DataManipulator.java:61)05-29 12:57:42.577: E/AndroidRuntime(625): at list.certificates.CheckData.onCreate(CheckData.java:28)05-29 12:57:42.577: E/AndroidRuntime(625): at android.app.Activity.performCreate(Activity.java:4465)05-29 12:57:42.577: E/AndroidRuntime(625): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)05-29 12:57:42.577: E/AndroidRuntime(625): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1919)05-29 12:57:42.577: E/AndroidRuntime(625): ... 11 more
Now provide the response and nothing else.
| This one is actually a doosie and I can't make it happen without some *nix shell magic. First, we want to get the x tic labels and y tic labels: XTICS="`awk 'BEGIN{getline}{printf "%s ",$1}' test.dat`"YTICS="`head -1 test.dat`" At this point, XTICS is the string "F G H I J" and YTICS is the string "A B C D E". Now, we want to set the xtics by iteration: set for [i=1:words(XTICS)] xtics ( word(XTICS,i) i-1 )set for [i=1:words(YTICS)] ytics ( word(YTICS,i) i-1 ) We've used 2 gnuplot builtin functions ( word and words ). words(string) counts how many words there are in the given string (a word is a character sequence separated by spaces). word(string,n) returns the n'th word in the string. Now, we can plot your datafile ... The only problem is that matrix wants to use all rows and columns in your datafile . You might be able to cut down the rows/columns actually read by using the every keyword, but I don't know how to do that on matrix files -- and I think it's probably easier to just keep on relying on shell utilities ( awk and sed ) plot "<awk '{$1=\"\"}1' test.dat | sed '1 d'" matrix w image#######^ replace the first field with nothing################################## ^ delete first line And now your plot (hopefully) looks the way you want it to. Also note that since we have used iteration, this script will only work in gnuplot 4.3 or higher -- Since the current stable is 4.6, hopefully that's Ok. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10795982', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1411777/']} | jdg_381594 |
stackexchange | llm_judgeable_groundtruth_similarity | 3027504 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
There seems to be a problem with the JS Code for Opera browsers, as it only removes the last option tag that is selected within a multiple select tag, can someone please help me. Here is the HTML for this: <select id="actions_list" name="layouts" multiple style="height: 128px; width: 300px;"> <option value="forum">forum</option> <option value="collapse">collapse</option> <option value="[topic]">[topic]</option> <option value="[board]">[board]</option></select> Of course it's within a form tag, but there's a ton more code involved with this form, but here is the relevant info for this. Here is the JS that should handle this, but only removes the last selected option in Opera, not sure about other browsers, but it really needs to remove all selected options, not just the last selected option... var action_list = document.getElementById("actions_list");var i = action_list.options.length;while(i--){ if (action_list.options[i].selected) { action_list.remove(i); }} What is wrong with this? I can't figure it out one bit.
Now provide the response and nothing else.
| It's easiest to do this with jQuery but it you want to do this using plain Javascript you can. The problem you are experiencing is that when you remove an item from the options list in Opera it deselects all the selected items, so only the first is removed. A workaround is to first remember which items were selected before removing any. var action_list = document.getElementById("actions_list");// Remember selected items.var is_selected = [];for (var i = 0; i < action_list.options.length; ++i){ is_selected[i] = action_list.options[i].selected;}// Remove selected items.i = action_list.options.length;while (i--){ if (is_selected[i]) { action_list.remove(i); }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3027504', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/304853/']} | jdg_381595 |
stackexchange | llm_judgeable_groundtruth_similarity | 33636925 |
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 installed the tensorflow docker container on an ubuntu machine. The tensorflow docker setup instructions specify: docker run -it b.gcr.io/tensorflow/tensorflow This puts me into the docker container terminal, and I can run python and execute the Hello World example. I can also manually run .\run_jupyter.sh to start the jupyter notebook. However, I can't reach the notebook from host. How do I start the jupyter notebook such that I can use the notebook from the host machine? Ideally I would like to use docker to launch the container and start jupyter in a single command.
Now provide the response and nothing else.
| For a Linux host Robert Graves answer will work, but for Mac OS X or Windows there is more to be done because docker runs in a virtual machine. So to begin launch the docker shell (or any shell if you are using Linux) and run the following command to launch a new TensorFlow container: docker run -p 8888:8888 -p 6006:6006 b.gcr.io/tensorflow/tensorflow ./run_jupyter.sh Then for Mac OS X and Windows you need to do the following only once: Open VirtualBox Click on the docker vm (mine was automatically named "default") Open the settings by clicking settings In the network settings open the port forwarding dialog Click the + symbol to add another port and connect a port from your mac to the VM by filling in the dialog as shown below. In this example I chose port 8810 because I run other notebooks using port 8888. then open a browser and connect to http://localhost:8810 (or whichever port you set in the host port section Make your fancy pants machine learning app! | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/33636925', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/276310/']} | jdg_381596 |
stackexchange | llm_judgeable_groundtruth_similarity | 740523 |
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:
On the one hand, Planck constant $\hbar$ seems to fundamentally enter quantum theory via the path integral, in the factor $e^{iS/\hbar}$ . Or via the Schrodinger or Dirac equations, in those versions of the theory. But we know that when you measure the spin of a fundamental particle you also get an integer or half-integer multiple of $\hbar$ . Can the second fact be derived from the first? Or does $\hbar$ appear yet again in the specific form of the Lagrangian, in such a way as to ensure the spin measurement is $\hbar$ as well? Or is spin measurement being $\hbar$ an independent postulate? I read this question whose answers seem to imply the derivation of spin from first principles is very complicated and esoteric, possibly involving Grassmann variables, so I guess I'm looking for something a bit more conceptual if possible, but anything is appreciated.
Now provide the response and nothing else.
| Yes. Briefly speaking, the $\color{red}{i\hbar}$ in the CCR s $$\begin{align} [\hat{q}^j,\hat{q}^k]~=~&0, \cr [\hat{q}^j,\hat{p}_k]~=~&+\color{red}{i\hbar}\delta^j_k\hat{\bf 1},\cr[\hat{p}_j,\hat{q}^k]~=~&-\color{red}{i\hbar}\delta^k_j\hat{\bf 1},\cr[\hat{p}_j,\hat{p}_k]~=~&0,\end{align}\tag{A}$$ is directly correlated with: The $so(3)$ Lie algebra $$[\hat{L}_j,\hat{L}_k]~=~\color{red}{i\hbar}\epsilon_{jk\ell}\hat{L}_{\ell}\tag{B}$$ and the eigenvalues $\in\color{red}{\hbar}\mathbb{Z}$ of the orbital angular momentum operator $$\hat{L}_i~=~\epsilon_{ijk} \hat{q}^j \hat{p}_k, \tag{C}$$ cf. e.g. my Phys.SE answer here . (It turns out that the eigenvalues $\in\frac{\color{red}{\hbar}}{2}\mathbb{Z}$ for spin angular momentum.) The free propagator/2-point function $$ \begin{align}\langle T[\hat{q}^j(t)\hat{q}^k(t^{\prime})]\rangle~=~& 0,\cr \langle T[\hat{q}^j(t)\hat{p}_k(t^{\prime})]\rangle~=~&+\frac{\color{red}{i\hbar}}{2}{\rm sgn}(t\!-\!t^{\prime}) \delta^j_k,\cr\langle T[\hat{p}_j(t)\hat{q}^k(t^{\prime})]\rangle~=~&-\frac{\color{red}{i\hbar}}{2}{\rm sgn}(t\!-\!t^{\prime}) \delta^k_j,\cr\langle T[\hat{p}_j(t)\hat{p}_k(t^{\prime})]\rangle~=~& 0,\end{align}\tag{D}$$ if we treat the Hamiltonian as a perturbation, i.e. eq. (D) is the diabatic/short time approximation. The argument $\frac{i}{\color{red}{\hbar}}S$ of the exponential in the path integral because of the $\int \!dt ~p_j \dot{q}^j$ term in the action $S$ , cf. point 2 and my Phys.SE answer here . | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/740523', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/230823/']} | jdg_381597 |
stackexchange | llm_judgeable_groundtruth_similarity | 3009284 |
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 directory with lots of folders, sub-folder and all with files in them. The idea of my project is to recurse through the entire directory, gather up all the names of the files and replace invalid characters (invalid for a SharePoint migration). However, I'm completely unfamiliar with Regular Expressions. The characters i need to get rid in filenames are: ~, #, %, &, *, { } , \, /, :, <>, ?, -, | and "" I want to replace these characters with a blank space. I was hoping to use a string.replace() method to look through all these file names and do the replacement. So far, the only code I've gotten to is the recursion. I was thinking of the recursion scanning the drive, fetching the names of these files and putting them in a List<string> . Can anybody help me with how to find/replace invalid chars with RegEx with those specific characters?
Now provide the response and nothing else.
| string pattern = "[\\~#%&*{}/:<>?|\"-]";string replacement = " ";Regex regEx = new Regex(pattern);string sanitized = Regex.Replace(regEx.Replace(input, replacement), @"\s+", " "); This will replace runs of whitespace with a single space as well. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3009284', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/102398/']} | jdg_381598 |
stackexchange | llm_judgeable_groundtruth_similarity | 27193560 |
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 currently have a root index.html with a single ui-view which gets replaced depending on which "page" the user is on, e.g. Books, Games etc. Taking the Books page as an example, this view has content that I'd like to display on all pages which are part of the "Books" space, but the central content will differ depending on if the user is on the Books "homepage" or looking at a specific book. To facilitate this, my books.html has a nested state which either includes books_list.html or books_detail.html. The url structure I'd like to have is: /books - Shows left/right sidepanels plus a list of books in the middle of the page. /books/1 - Shows left/right sidepanels plus the details for the book with ID 1 in the middle of the page (list of books is not displayed). How can I set up my states to have the books.html template AND books_list.html template in the nested view when navigating to /books, but have books.html AND books_detail.html when navigating to /books/1 ? I'm currently getting round this problem by having a "home" sub-state, but this means that I have to have /books/home, and /books displays no central content so is currently useless. .state('books', { url: '/books', templateUrl: CONFIG.static_url + '/html/books.html', ...}).state('books.home', { url: '/home', templateUrl: CONFIG.static_url + '/html/books_list.html', ...}).state('books.detail', { url: '/:bookId', templateUrl: CONFIG.static_url + '/html/books_detail.html', ...})
Now provide the response and nothing else.
| I achieved what I needed by declaring an abstract state: .state('books', { abstract: true, url: '/books', templateUrl: CONFIG.static_url + '/html/books.html', ...}).state('books.home', { url: '', templateUrl: CONFIG.static_url + '/html/books_list.html', ...}).state('books.detail', { url: '/:bookId', templateUrl: CONFIG.static_url + '/html/books_detail.html', ...}) This means that /books loads both 'books' and 'books.home' states, and /books/1 loads both 'books' and 'books.detail' states, which is what I needed. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27193560', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/262218/']} | jdg_381599 |
stackexchange | llm_judgeable_groundtruth_similarity | 2453773 |
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 prove that, if $\rho:S^n\times S^n\to \Bbb{R}$ is the distance induced by the Riemannian metric on the sphere $S^n\subset \Bbb{R}^{n+1}$, then $$\rho(p,q)=\arccos \langle p,q\rangle,\,\,\,\forall p,q\in S^n$$with $\arccos$ defined from $[-1,1]$ to $[0,\pi]$. If $p=q$, then the formula is trivial. We have then two cases: $p=-q$ and $p\neq- q$. I am having trouble even with the apparently easier case, $p=-q$. If $p=-q$, then let $v\in S^n$ be any vector orthogonal to $p$. Then $\alpha:[0,\pi]\to S^n$, $\alpha(t)=(\cos t)p+(\sin t)v$ is a well defined differentiable path from $p$ to $q$ such that $\ell_0^\pi(\alpha)=\pi$ ("length of $\alpha$"). This guarantees that $\rho(p,q)\leq \pi (=\arccos \langle p,q\rangle$, in this case). In order to show that $\rho(p,q)=\pi$, I must consider an arbitrary differentiable by parts path $\beta:[a,b]\to S^n$ from $p$ to $q$ and show that$$\pi\leq \ell_a^b(\beta)=\int_a^b|\beta'(t)|\,dt.$$ I've done some geometric observations and computations, but without success. How can I do this? I wish I could do it without using any facts about geodesics (they appear later in the book I'm studying with).
Now provide the response and nothing else.
| Let $p=(1,0,\dots,0)$ and $q=(-1,0,\dots,0)$ . Then any path from $p$ to $q$ is of the form $\gamma(t)=(t,h(t))$ ,where $h(t)\in \Bbb{R}^n$ . Then the length of the path is $$L=\int_{-1}^{1}|\gamma'(t)|dt.$$ But $\gamma'(t)=(1,h'(t))$ , and so $|\gamma'(t)|=\sqrt{1+|h'(t)|^2}$ . Now $t^2+\langle h(t),h(t)\rangle=\langle \gamma(t),\gamma(t)\rangle=1$ , so we get $$2t+2\langle h(t),h'(t)\rangle=0$$ by differentiating both sides with respect to t. By Cauchy Schwartz we have $|h'(t)|^2|h(t)|^2\ge |\langle h(t),h'(t)\rangle|^2=|t|^2$ ,and so $$1+|h'(t)|^2\ge \frac{t^2}{|h(t)|^2}+1$$ but $|h(t)|^2=1-t^2$ , hence $$\sqrt{1+|h'(t)|^2}\ge \sqrt{1+\frac{t^2}{1-t^2}}=\sqrt{\frac{1}{1-t^2}},$$ and so $$L=\int_{-1}^{1}\sqrt{1+|h'(t)|^2}dt\ge\int_{-1}^1 \sqrt{\frac{1}{1-t^2}}dt=\pi.$$ A similar reasoning applies for any other point:Assume $p=(1,0,\dots,0)$ , then you can assume that the other point $q$ is of the form $(a,s,0,\dots,0)$ .The path $\gamma(t)=(t,\sqrt{1-t^2},0,\dots,0)$ has length $$L=\int_{a}^{1}|\gamma'(t)|dt=\int_{a}^1 \sqrt{\frac{1}{1-t^2}}dt=-arccos(t)|_{a}^1=arccos(a)=arccos(\langle p,q\rangle).$$ By a similar argument as above, any other path has the form $(t,h(t))$ with $\sqrt{1+|h'(t)|^2}\ge \sqrt{\frac{1}{1-t^2}}$ , so the result follows. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2453773', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/177211/']} | jdg_381600 |
stackexchange | llm_judgeable_groundtruth_similarity | 58772 |
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 testing the parallel regression assumption in ordinal logistic regression I find there are several approaches. I've used both the graphical approach (as detailed in Harrell´s book) and the approach detailed using the ordinal package in R. However I would also like to run the Brant test (from Stata) for both the individual variables and also for the total model. I've looked around but cannot find it implemented in R. Is there an implementation of the Brant test in R?
Now provide the response and nothing else.
| I implemented the brant test in R. The package and function is called brant and it's now available on CRAN. The brant test was defined by Rollin Brant to test the parallel regression assumption (Brant, R. (1990) Assessing proportionality in the proportional odds model for ordinal logistic regression. Biometrics , 46 , 1171–1178). Here is a code example: data = MASS::surveydata$Smoke = ordered(MASS::survey$Smoke, levels=c("Never","Occas","Regul","Heavy"))model1 = MASS::polr(Smoke ~ Sex + Height, data=data, Hess=TRUE)brant(model1) In the example, the parallel regression assumption holds, because all p-values are above 0.05. The Omnibus is for the whole model, the rest for the indvidual coefficents. | {} | {'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/58772', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/1291/']} | jdg_381601 |
stackexchange | llm_judgeable_groundtruth_similarity | 837598 |
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 am migrating my website to another platform, but while I finish developing all the pages of the new website, I need my users to navigate between the 2 platforms. So I need to make a 301 redirect of all the URLs that contain 1 word in specific, but that do not contain other words: Example: Old site: www2.misite.com New site: www.misite.com I need to redirect all URLs that contain the word "www2.misite.com/travel(.*)" but do not contain the words "reservation" and "hotel". My server is Nginx, I do not know if this is done with a regular expression or with nginx statements. Thank you very much.
Now provide the response and nothing else.
| I was able to solve my problem in the following way: location ~ /travel(.*)+/(.*)$ { if ($uri !~ "^(.*)/(reservation|hotel|faq)(.*)"){ return 301 https://www.misite.com$request_uri; } autoindex on; root /usr/share/nginx/html/sites/; index index.php index.html index.htm; try_files $uri $uri/ /index.php?$args;} Thank you. | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/837598', 'https://serverfault.com', 'https://serverfault.com/users/404892/']} | jdg_381602 |
stackexchange | llm_judgeable_groundtruth_similarity | 26899595 |
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 JayDeBeAPI in PySpark (the Apache Spark Python API), and here's the beginning of my code (note, I'm actually running all this through an interactive shell with PySpark). import jaydebeapiimport jpypeconn = jaydebeapi.connect('org.apache.phoenix.jdbc.PhoenixDriver', ['jdbc:phoenix:hostname', '', '']) I am querying Apache Phoenix , which is an SQL "front-end" for Apache HBase. Here's my Python code for the SQL query: curs = conn.cursor()curs.execute('select "username",count("username") from "random_data" GROUP BY "username"')curs.fetchall() The output I'm getting is like this for all the rows: (u'Username', <jpype._jclass.java.lang.Long object at 0x25d1e10>) How can I fix it so that it actually shows the value of that returned column (the count column)? From the Apache Phoenix datatypes page , the datatype of the count column is BIGINT, which is mapped to java.lang.Long , but for some reason jpype is not displaying the result. I got JayDeBeAPI 0.1.4 and JPype 0.5.4.2 by python setup.py install when I downloaded them.
Now provide the response and nothing else.
| The object returned by JPype is a Python version of Java's java.lang.Long class. To get the value out of it, use the value attribute: >>> n = java.lang.Long(44)>>> n<jpype._jclass.java.lang.Long object at 0x2377390>>>> n.value44L JayDeBeApi contains a dict ( _DEFAULT_CONVERTERS ) that maps types it recognises to functions that convert the Java values to Python values. This dict can be found at the bottom of __init__.py in the JayDeBeApi source code . BIGINT is not included in this dict, so objects of that database type don't get mapped out of Java objects into Python values. It's fairly easy to modify JayDeBeApi to add support for BIGINT s. Edit the __init__.py file that contains most of the JayDeBeApi code and add the line 'BIGINT': _java_to_py('longValue'), to the _DEFAULT_CONVERTERS dict. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26899595', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2767757/']} | jdg_381603 |
stackexchange | llm_judgeable_groundtruth_similarity | 26994330 |
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 image of size as RGB uint8(576,720,3) where I want to classify each pixel to a set of colors. I have transformed using rgb2lab from RGB to LAB space, and then removed the L layer so it is now a double(576,720,2) consisting of AB. Now, I want to classify this to some colors that I have trained on another image, and calculated their respective AB-representations as: Cluster 1: -17.7903 -13.1170Cluster 2: -30.1957 40.3520Cluster 3: -4.4608 47.2543Cluster 4: 46.3738 36.5225Cluster 5: 43.3134 -17.6443Cluster 6: -0.9003 1.4042Cluster 7: 7.3884 11.5584 Now, in order to classify/label each pixel to a cluster 1-7, I currently do the following (pseudo-code): clusters;for each x for each y ab = im(x,y,2:3); dist = norm(ab - clusters); // norm of dist between ab and each cluster [~, idx] = min(dist); endend However, this is terribly slow (52 seconds) because of the image resolution and that I manually loop through each x and y. Are there some built-in functions I can use that performs the same job? There must be. To summarize: I need a classification method that classifies pixel images to an already defined set of clusters.
Now provide the response and nothing else.
| Approach #1 For a N x 2 sized points/pixels array, you can avoid permute as suggested in the other solution by Luis , which could slow down things a bit, to have a kind of "permute-unrolled" version of it and also let's bsxfun work towards a 2D array instead of a 3D array, which must be better with performance. Thus, assuming clusters to be ordered as a N x 2 sized array, you may try this other bsxfun based approach - %// Get a's and b'sim_a = im(:,:,2);im_b = im(:,:,3);%// Get the minimum indices that correspond to the cluster IDs[~,idx] = min(bsxfun(@minus,im_a(:),clusters(:,1).').^2 + ... bsxfun(@minus,im_b(:),clusters(:,2).').^2,[],2);idx = reshape(idx,size(im,1),[]); Approach #2 You can try out another approach that leverages fast matrix multiplication in MATLAB and is based on this smart solution - d = 2; %// dimension of the problem sizeim23 = reshape(im(:,:,2:3),[],2);numA = size(im23,1);numB = size(clusters,1);A_ext = zeros(numA,3*d);B_ext = zeros(numB,3*d);for id = 1:d A_ext(:,3*id-2:3*id) = [ones(numA,1), -2*im23(:,id), im23(:,id).^2 ]; B_ext(:,3*id-2:3*id) = [clusters(:,id).^2 , clusters(:,id), ones(numB,1)];end[~, idx] = min(A_ext * B_ext',[],2); %//'idx = reshape(idx, size(im,1),[]); %// Desired IDs What’s going on with the matrix multiplication based distance matrix calculation? Let us consider two matrices A and B between whom we want to calculate the distance matrix. For the sake of an easier explanation that follows next, let us consider A as 3 x 2 and B as 4 x 2 sized arrays, thus indicating that we are working with X-Y points. If we had A as N x 3 and B as M x 3 sized arrays, then those would be X-Y-Z points. Now, if we have to manually calculate the first element of the square of distance matrix, it would look like this – first_element = ( A(1,1) – B(1,1) )^2 + ( A(1,2) – B(1,2) )^2 which would be – first_element = A(1,1)^2 + B(1,1)^2 -2*A(1,1)* B(1,1) + ... A(1,2)^2 + B(1,2)^2 -2*A(1,2)* B(1,2) … Equation (1) Now, according to our proposed matrix multiplication, if you check the output of A_ext and B_ext after the loop in the earlier code ends, they would look like the following – So, if you perform matrix multiplication between A_ext and transpose of B_ext , the first element of the product would be the sum of elementwise multiplication between the first rows of A_ext and B_ext , i.e. sum of these – The result would be identical to the result obtained from Equation (1) earlier. This would continue for all the elements of A against all the elements of B that are in the same column as in A . Thus, we would end up with the complete squared distance matrix. That’s all there is!! Vectorized Variations Vectorized variations of the matrix multiplication based distance matrix calculations are possible, though there weren't any big performance improvements seen with them. Two such variations are listed next. Variation #1 [nA,dim] = size(A);nB = size(B,1);A_ext = ones(nA,dim*3);A_ext(:,2:3:end) = -2*A;A_ext(:,3:3:end) = A.^2;B_ext = ones(nB,dim*3);B_ext(:,1:3:end) = B.^2;B_ext(:,2:3:end) = B;distmat = A_ext * B_ext.'; Variation #2 [nA,dim] = size(A);nB = size(B,1);A_ext = [ones(nA*dim,1) -2*A(:) A(:).^2];B_ext = [B(:).^2 B(:) ones(nB*dim,1)];A_ext = reshape(permute(reshape(A_ext,nA,dim,[]),[1 3 2]),nA,[]);B_ext = reshape(permute(reshape(B_ext,nB,dim,[]),[1 3 2]),nB,[]);distmat = A_ext * B_ext.'; So, these could be considered as experimental versions too. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26994330', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1085291/']} | jdg_381604 |
stackexchange | llm_judgeable_groundtruth_similarity | 69 |
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 $n$ an integer greater than $2$ , Can one always get a complete theory over a finite language with exactly $n$ models (up to isomorphism)? There’s a theorem that says that $2$ is impossible. My understanding is this should be doable in a finite language, but I don’t know how. If you switch to a countable language, then you can do it as follows. To get $3$ models, take the theory of unbounded dense linear orderings together with a sequence of increasing constants $\langle c_i: i < \omega\rangle$ . Then the $c_i$ ’s can either have no upper bound, an upper bound but no sup, or have a sup. This gives exactly $3$ models. To get a number bigger than $3$ , we include a way to color all elements, and require that each color is unbounded and dense. (The $c_i$ ’s can be whatever color you like.) Then, we get one model for each color of the sup plus the two sup-less models.
Now provide the response and nothing else.
| You can refine Ehrenfeucht’s example getting rid of the constants. Here is what John Baldwin suggested: Consider the theory in the language $L=\{\le\}$ , saying $\le$ is a total preorder (transitive, total [hence reflexive], not necessarily anti-symmetric) without least or last element. (Notice that the binary relation defined by $x\le y \land y\le x$ is an equivalence relation. Call it $E$ .) For each $n$ , $E$ has exactly one class of size $n$ . Call it $C_n$ . $C_i\le C_j$ (for $i\le j$ ) setwise. $E$ -classes are densely ordered: for any two points there is a point $\le$ -between them and not $E$ -equivalent to any of them. Check that this theory is complete. Note that each finite equivalence class in this new theory plays the role of one of the constants in the classical example, so you get three countable models the same way. | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/69', 'https://mathoverflow.net', 'https://mathoverflow.net/users/27/']} | jdg_381605 |
stackexchange | llm_judgeable_groundtruth_similarity | 39962732 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am using bootstrap multiselect plugin to add dynamically code into an select. Here is my code: Html: <label> <span>Underlyings</span> <select class="multiselect" multiple></select></label> Javascript var name = ['joe', 'mary', 'rose'];R.map(function (x) { return $('.multiselect', d.el).append("<option>" + x + "</option>");}, name);$('.multiselect', d.el).multiselect({ allSelectedText: 'All', maxHeight: 200, includeSelectAllOption: true}); When the multiple select is instancied, it appears as such in the browser (there is some css formatting explaining its aspect): Whereas I would like it to appear as (with all checkbox selected at instanciation, without to click on 'select all'): I looked into the doc, but did not find it ... Bootstrap multiple select documentation
Now provide the response and nothing else.
| You need to run both selectAll (with false as second parameter - this indicate that all values will be selected, even non-visible values) and updateButtonText (to change the text that appear in the drop-down menu). Check this example: $(function() { var name = ['joe', 'mary', 'rose']; $.map(name, function (x) { return $('.multiselect').append("<option>" + x + "</option>"); }); $('.multiselect') .multiselect({ allSelectedText: 'All', maxHeight: 200, includeSelectAllOption: true }) .multiselect('selectAll', false) .multiselect('updateButtonText');}); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.2/css/bootstrap.min.css" /><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/css/bootstrap-multiselect.css" /><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.min.js"></script><label> <span>Underlyings</span> <select class="multiselect" multiple="multiple"></select></label> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39962732', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3628236/']} | jdg_381606 |
stackexchange | llm_judgeable_groundtruth_similarity | 16620 |
Below is a question asked on the forum datascience.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm looking for a good explanation of how convolutions in deep learning work when applied to multi-channel images. For example, let's say I have a 100 x 100 pixel image with three channels, RGB. The input tensor would then have dimensions 100 x 100 x 3. If I apply a convolution with N filters and a stride of one, will the output dimension be: 100 x 100 x 3 x N ? or 100 x 100 x N ? In other words, does the convolution that is applied "flatten" the image, or is the convolution applied on a channel by channel basis?
Now provide the response and nothing else.
| In all the implementations for CNNs processing images that I have seen, the output in any layer is Width x Height x Channels or some permutation. This is the same number of dimensions as the input, no additional dimensions are added by the convolutional layers. Each feature map channel in the output of a CNN layer is a "flattened" 2D array created by adding the results of multiple 2D kernels (one for each channel in the input layer). Usually even greyscale input images are expected to be represented as Width x Height x 1 so that they fit the same pattern and the same layer model can be used. It is entirely feasible to build a layer design which converts a standard 2D+channels input layer into a 3D+channels layer. It is not something I have seen done before, but you can never rule out that it could be useful in a specific problem. You may also see 3D+channels convolutions in CNNs applied to video, but in that case, the structure will be some variation of Width x Height x Frames x Channels | {} | {'log_upvote_score': 4, 'links': ['https://datascience.stackexchange.com/questions/16620', 'https://datascience.stackexchange.com', 'https://datascience.stackexchange.com/users/28449/']} | jdg_381607 |
stackexchange | llm_judgeable_groundtruth_similarity | 18015978 |
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 sites on mac and every time I create some folder (or file in that folder) .DS_Store is created in that folder. How to prevent creating .DS_Store file ?
Now provide the response and nothing else.
| Its is possible by using mach_inject . Take a look at Death to .DS_Store I found that overriding HFSPlusPropertyStore::FlushChanges() with a function that simply did nothing, successfully prevented the creation of .DS_Store files on both Snow Leopard and Lion. DeathToDSStore source code NOTE: On 10.11 you can not inject code into system apps. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18015978', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1370370/']} | jdg_381608 |
stackexchange | llm_judgeable_groundtruth_similarity | 22062037 |
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 do a lescan using hcitool on the raspberry pi. The command prints out Set scan parameters failed: Input/output error. I'm not sure, what exactly happens here. My iPhone is advertising here. I'm using a BLE dongle from IOGear. However, if I restart my machine, it shows the a MAC address after I issue the lescan command, and starts showing the same error after I issue the lescan command a couple of more times. Is it like, the lescan command cannot be issued more than once?
Now provide the response and nothing else.
| That happens often really often to me. I'm developing with it and it just happens from time to time. I was also able to reproduce your error within 5 minutes ;-) I'm running bluez v.5.17.However i can run lescan more than one time without this error. hcitool lescanSet scan parameters failed: Input/output error try: hciconfig hci0 downhciconfig hci0 up and check the status afterwords. if this doesn't work or it hangs in DOWN status, try: service bluetooth restartservice dbus restart (all commands as superuser) And close all application that may access bluetooth. For example hcidump. If that doesn't work you normally have to unplug it. But there is another dirty hack to do this. It works by setting the authorized to 0 and than 1 again. This forces the usb dongle to init. lsusbBus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hubBus 001 Device 002: ID 0424:9512 Standard Microsystems Corp. Bus 001 Device 003: ID 0424:ec00 Standard Microsystems Corp. Bus 001 Device 004: ID 0a5c:21e8 Broadcom Corp. cd /sys/bus/usb/devices/grep -i -s -r 0a5c *…1-1.2/idVendor:0a5c…cd 1-1.2echo 0 > authorizedecho 1 > authorized | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/22062037', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1621600/']} | jdg_381609 |
stackexchange | llm_judgeable_groundtruth_similarity | 3850486 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Can you give me an example of implementation of .NET 'try' pattern? Edit: I don't mean a "try-catch" statement, I mean a try patterns, like those used in TryParse() , and TryGetObjectByKey() methods. Most specifically what to do with raised exceptions in custom 'try' pattern methods. Should I log it, should I ignore It. Does' anybody know what is the practice with those methods?
Now provide the response and nothing else.
| Here is an example of using a TryXxx method: string s = Console.ReadLine();int x;if (int.TryParse(s, out x)){ Console.WriteLine("You entered the valid integer {0}", x);}else{ Console.WriteLine("Invalid input!");} Here is an example of defining the method: bool TryParse(string s, out int x) // out parameter for result{ if (!allCharactersAreValid(s)) { x = 0; return false; } // More checks... // Parse the string... x = 42; return true;} Exception handling Most specificly what to do with rised exceptions in custom 'try' pattern methods Your method probably should avoid throwing any exceptions - if your user wanted exceptions they would use the non-Try version. You should therefore try to avoid calling methods which can throw when implementing your TryXxx. However some exceptions are unavoidable and could be thrown out of your control - for example OutOfMemoryException , StackOverflowException , etc... There is nothing you can do about this and you should not try to catch these exceptions, just let them propagate to the caller. Don't swallow them, don't log them - that's the caller's responsibility. An example of this is Dictionary<TKey, TValue>.TryGetValue when the key object provided to this method throws an exception when GetHashCode is called. Then the resulting exception is not caught inside the TryGetValue method - the caller will see the exception. This code demonstrates this happening: using System;using System.Collections.Generic;class Foo{ public override int GetHashCode() { throw new NotImplementedException(); }}class Program{ public static void Main() { Dictionary<object, object> d = new Dictionary<object, object>(); d["bar"] = 42; object s; Foo foo = new Foo(); if (d.TryGetValue(foo, out s)) // results in NotImplementedException { Console.WriteLine("found"); } }} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3850486', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/251931/']} | jdg_381610 |
stackexchange | llm_judgeable_groundtruth_similarity | 40713752 |
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 trying to figure out how to write a npm script that will culminate with the application being launched in the user's browser without them having to manually open the browser and go to localhost:1234 . Right now my script reads as: "start": "npm run build && npm run dev","build": "npm run clean && npm run mkdir && npm run build:html && npm run build:css && npm run build:js","dev": "webpack-dev-server --inline --hot --content-base build --history-api-fallback", Wanting to add "open": <some code here>, So when someone goes to GitHub and clones or forks off my repository they are given the instructions for how to run the application. I just thought that automating this would be a nice little addition. Anyone know how this is possible? I'm pretty sure it is and think it has something to do with calling a command in bash. Thanks in advance for the help!
Now provide the response and nothing else.
| This can be achieved by including a couple of additional packages in your project. Additional packages Install http-server : $ npm install http-server --save-dev and concurrently : $ npm install concurrently --save-dev npm scripts Add the following open script to package.json : "scripts": { "start": "npm run open", "open": "concurrently \"http-server -a localhost -p 1234\" \"open http://localhost:1234/build\"" } Note start will actually be defined as follows to include the tasks you currently have: "start": "npm run build && npm run dev && npm run open", The code in the open script above which reads: open http://localhost:1234/build ...assumes that the build task you have previously defined outputs a index.html to a build folder. If the file is named differently you will need to define it. E.g. open http://localhost:1234/build/the_html_file_name.html You may need to add a delay between launching the server and opening the file, just to wait a bit til the server starts up. If that's the case then also install sleep-ms : $ npm install sleep-ms --save-dev and change the open script to: "open": "concurrently \"http-server -a localhost -p 1234\" \"sleepms 1000 && open http://localhost:1234/build\"" Cross platform Unfortunately, the open command is not supported cross-platform. To overcome this issue check out opener or opn-cli and replace the command accordingly. However, both packages, ( opener and opn-cli ), utilize Object.assign() so will not run in older versions of nodejs . Edit: To open a browser window after starting the server, http-server now accepts the -o option . This can be utilized instead of either the opener or opn-cli packages. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/40713752', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6520579/']} | jdg_381611 |
stackexchange | llm_judgeable_groundtruth_similarity | 8259 |
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I think I'm not understanding it, but $\eta$-conversion looks to me as a $\beta$-conversion that does nothing, a special case of $\beta$-conversion where the result is just the term in the lambda abstraction because there is nothing to do, kind of a pointless $\beta$-conversion. So maybe $\eta$-conversion is something really deep and different from this, but, if it is, I don't get it, and I hope you can help me with it. (Thank you and sorry, I know this is part of the very basics in lambda calculus)
Now provide the response and nothing else.
| Update [2011-09-20]: I expanded the paragraph about $\eta$-expansion and extensionality. Thanks to Anton Salikhmetov for pointing out a good reference. $\eta$-conversion $(\lambda x . f x) = f$ is a special case of $\beta$- conversion only in the special case when $f$ is itself an abstraction, e.g., if $f = \lambda y . y y$ then $$(\lambda x . f x) = (\lambda x . (\lambda y . y y) x) =_\beta (\lambda x . x x) =_\alpha f.$$ But what if $f$ is a variable, or an application which does not reduce to an abstraction? In a way $\eta$-rule is like a special kind of extensionality, but we have to be a bit careful about how that is stated. We can state extensionality as: for all $\lambda$-terms $M$ and $N$, if $M x = N x$ then $M = N$, or for all $f, g$ if $\forall x . f x = g x$ then $f = g$. The first one is a meta-statement about the terms of the $\lambda$-calculus. In it $x$ appears as a formal variable, i.e., it is part of the $\lambda$-calculus. It can be proved from $\beta\eta$-rules, see for example Theorem 2.1.29 in "Lambda Calculus: its Syntax and Semantics" by Barendregt (1985). It can be understood as a statement about all the definable functions, i.e., those which are denotations of $\lambda$-terms. The second statement is how mathematicians usually understand mathematical statements. The theory of $\lambda$-calculus describes a certain kind of structures, let us call them " $\lambda$-models ". A $\lambda$-model might be uncountable, so there is no guarantee that every element of it corresponds to a $\lambda$-term (just like there are more real numbers than there are expressions describing reals). Extensionality then says: if we take any two things $f$ and $g$ in a $\lambda$-model, if $f x = g x$ for all $x$ in the model, then $f = g$. Now even if the model satisfies the $\eta$-rule, it need not satisfy extensionality in this sense. (Reference needed here, and I think we need to be careful how equality is interpreted.) There are several ways in which we can motivate $\beta$- and $\eta$-conversions. I will randomly pick the category-theoretic one, disguised as $\lambda$-calculus, and someone else can explain other reasons. Let us consider the typed $\lambda$-calculus (because it is less confusing, but more or less the same reasoning works for the untyped $\lambda$-calculus). One of the basic laws that should holds is the exponential law $$C^{A \times B} \cong (C^B)^A.$$ (I am using notations $A \to B$ and $B^A$ interchangably, picking whichever seems to look better.) What do the isomorphisms $i : C^{A \times B} \to (C^B)^A$ and $j : (C^B)^A \to C^{A \times B}$ look like, written in $\lambda$-calculus? Presumably they would be $$i = \lambda f : C^{A \times B} . \lambda a : A . \lambda b : B . f \langle a, b \rangle$$ and $$j = \lambda g : (C^B)^A . \lambda p : A \times B . g (\pi_1 p) (\pi_2 p).$$A short calculation with a couple of $\beta$-reductions (including the $\beta$-reductions $\pi_1 \langle a, b \rangle = a$ and $\pi_2 \langle a, b \rangle = b$ for products) tells us that, for every $g : (C^B)^A$ we have $$i (j g) = \lambda a : A . \lambda b : B . g a b.$$Since $i$ and $j$ are inverses of each other, we expect $i (j g) = g$, but to actually prove this we need to use $\eta$-reduction twice: $$i(j g) = (\lambda a : A . \lambda b : B . g a b) =_\eta (\lambda a : A . g a) =_\eta g.$$So this is one reason for having $\eta$-reductions. Exercise: which $\eta$-rule is needed to show that $j (i f) = f$? | {} | {'log_upvote_score': 6, 'links': ['https://cstheory.stackexchange.com/questions/8259', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/6577/']} | jdg_381612 |
stackexchange | llm_judgeable_groundtruth_similarity | 318733 |
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 to get the sum of the values in a $N \times N$ table (without adding repeating products such as $6 \times 7$ and $7 \times 6$ twice and without counting perfect squares)? Figured out that $1 \cdot 0+2 \cdot 1+3 \cdot (1+2)+4 \cdot (1+2+3)+\dots+n\cdot (1+2+3+\dots+(n-1))=1\dbinom{1}{2}+2\dbinom{2}{2}+3\dbinom{3}{2}+4\dbinom{4}{2}+\dots+n\dbinom{n}{2}$ At this point I'm completely stuck. What do I do to get an exact number e. g. for $n=50$, $n=100$ etc.?
Now provide the response and nothing else.
| If I understand correctly, you want $$\begin{align*}\sum_{i=1}^{N-1}\sum_{k=i+1}^Nik&=\sum_{k=2}^N\sum_{i=1}^{k-1}ik\\&=\sum_{k=2}^Nk\sum_{i=1}^{k-1}i\\&=\sum_{k=2}^Nk\left(\frac{k(k-1)}2\right)\\&=\frac12\sum_{k=2}^N\left(k^3-k^2\right)\\&=\frac12\sum_{k=2}^Nk^3-\frac12\sum_{k=2}^Nk^2\\&=\frac12\left(\frac14N^2(N+1)^2-1\right)-\frac12\left(\frac16N(N+1)(2N+1)-1\right)\\&=\frac18N^2(N+1)^2-\frac1{12}N(N+1)(2N+1)\\&=\frac{N(N+1)}{24}\Big(3N(N+1)-2(2N+1)\Big)\\&=\frac1{24}N(N-1)(N+1)(3N+2)\;,\end{align*}$$ if I made no careless algebraic errors. This is the sum of all products of unordered pairs of integers from the set $\{1,\dots,N\}$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/318733', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/64683/']} | jdg_381613 |
stackexchange | llm_judgeable_groundtruth_similarity | 659001 |
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've stumbled upon the following question while studying for a test in complex analysis: Given the following Taylor series: $\tan {\pi z \over 2} = \sum \limits _{n=0}^{\infty} a_{2n+1} z ^ {2n+1}$ Prove that: $\lim \limits_{n\to\infty} a_{2n+1}={4\over\pi}$. I've tried using Cauchy's integral formula for the $n^{th}$ derivative of $\tan {\pi z \over 2}$, but didn't get much progress. If it helps, this is the third part of the question. The two others are: Find all the singularity points of $\tan {\pi z \over 2}$, classify them and find the residues. (There are singularities at $\{1 + 2k; k \in \Bbb Z\}$, all are simple poles with residue $-{2\over\pi}$) What is the radius of convergence of the Taylor series: $\tan {\pi z \over 2} = \sum \limits _{n=0}^{\infty} a_{2n+1} z ^ {2n+1}$? (It's 1 because $\tan {\pi z \over 2}$ has singularities in -1, 1) I'm struggling with this question for several hours, so any help would be appreciated.
Now provide the response and nothing else.
| We note that$$\mathrm{Res}(\tan(\frac{\pi z}{2}),1) = \frac{\sin(\frac{\pi}{2})}{-\frac{\pi}{2}\sin(\frac{\pi}{2})} = -\frac{2}{\pi} = \frac{\sin(-\frac{\pi}{2})}{-\frac{\pi}{2}\sin(-\frac{\pi}{2})} = \mathrm{Res}(\tan(\frac{\pi z}{2}),-1)$$This implies that $f(z):=\tan(\frac{\pi z}{2})+\frac{2}{\pi(z-1)}+\frac{2}{\pi(z+1)}$ is holomorphic in $D_2(0)$. Note$$\frac{2}{\pi(z-1)}+\frac{2}{\pi(z+1)} = \frac{4z}{\pi(z^2-1)},$$so we know that that for $z\in\Bbb D$ we have$$f(z)=\tan(\frac{\pi z}{2})-\frac{4z}{\pi(1-z^2)} = \sum_{n=0}^\infty a_{2n+1}z^{2n+1} - \frac{4z}{\pi}\sum_{n=0}^\infty z^{2n} = \sum_{n=0}^\infty \left(a_{2n+1}-\frac{4}{\pi}\right)z^{2n+1}.$$This is $f$'s Taylor series in $\Bbb D$, but since $f$ has no singularities in $D_2(0)$ it converges there as well, and in particular at $z=1$. Since the coefficients of a convergent series tend to zero, we're done. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/659001', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/125309/']} | jdg_381614 |
stackexchange | llm_judgeable_groundtruth_similarity | 13526883 |
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 had checked Using a percentage margin in CSS but want a minimum margin in pixels? . It had how to implement a minimum margin when using percentage. But i am using width:80%;margin:5px auto; How to set a minimum margin on the left side. i had used auto margin as per Reducing the space equally when resizing browser window Thanks
Now provide the response and nothing else.
| It might take another div to accomplish this task. I will refer to the div you are talking about as the #content div. I know that yours will have a bit more css. This is just my example of the margin in question. Next we would put the #content div in a div we will call #container. We will set the margins to auto in this div as well. The added aspect will be that we will add padding (right and left) to the #container div. #content { margin: auto;}#container { padding-right: 5px; padding-left: 5px;} I think that this would achieve what you are looking for. Keep in mind a min-width for the #content div and it could work nicely. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13526883', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1688631/']} | jdg_381615 |
stackexchange | llm_judgeable_groundtruth_similarity | 2613343 |
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:
Find the sum of infinite series $$\frac{1}{5}+\frac{1}{3}.\frac{1}{5^3}+\frac{1}{5}.\frac{1}{5^5}+...$$ I'm trying by consider this sum as S and then multiply $\frac{1}{5}$ and substract from S but i can't found any sum....
Now provide the response and nothing else.
| Let $\frac{1}{5}=x$ and $f(x)=x+\frac{1}{3}x^3+\frac{1}{5}x^5+...$ Thus, $$f'(x)=1+x^2+x^4+...=\frac{1}{1-x^2}$$ and$$f(x)=\int\limits_0^x\frac{1}{1-t^2}dt=\ln\sqrt{\frac{1+x}{1-x}},$$which after substitution $x=\frac{1}{5}$ gives the answer:$$\frac{1}{2}\ln1.5.$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2613343', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/377379/']} | jdg_381616 |
stackexchange | llm_judgeable_groundtruth_similarity | 45489349 |
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 be able to do the git pull-commit-push action in 1 shortcut (clicking 1 option) in Android Studio / IntelliJ. It would be such a convenient solution. Can I do it?
Now provide the response and nothing else.
| The key property for goBack() is a dynamically created string, created by react-navigation whenever it navigates to a new route. for example: It is stored in this.props.navigation.state.key . So if you want to go from EditPage to Cover , what you have to do is to pass the key of EditCover down to EditPage , and then call goBack() with the key. Why not key of Cover but EditCover ? Because react-navigation only provides the method goBack(key) , it's go back from key , not go back to key . Optionally provide a key, which specifies the route to go back from. By default, goBack will close the route that it is called from. If the goal is to go back anywhere, without specifying what is getting closed, call .goBack(null); EditCover.js render() { const { state, navigate } = this.props.navigation; return ( <View> <Button title="Go to Page" onPress={ () => { /* pass key down to *EditPage* */ navigate('EditPage', { go_back_key: state.key }); }} /> </View> );} EditPage.js render() { const { state, goBack } = this.props.navigation; const params = state.params || {}; return ( <View> <Button title="Back to Cover" onPress={ () => { /* go back from *EditCover* to *Cover* */ goBack(params.go_back_key); }} /> </View> );} | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/45489349', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1573765/']} | jdg_381617 |
stackexchange | llm_judgeable_groundtruth_similarity | 487971 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there a straightforward way to list the names of all modules in a package, without using __all__ ? For example, given this package: /testpkg/testpkg/__init__.py/testpkg/modulea.py/testpkg/moduleb.py I'm wondering if there is a standard or built-in way to do something like this: >>> package_contents("testpkg")['modulea', 'moduleb'] The manual approach would be to iterate through the module search paths in order to find the package's directory. One could then list all the files in that directory, filter out the uniquely-named py/pyc/pyo files, strip the extensions, and return that list. But this seems like a fair amount of work for something the module import mechanism is already doing internally. Is that functionality exposed anywhere?
Now provide the response and nothing else.
| Using python2.3 and above , you could also use the pkgutil module: >>> import pkgutil>>> [name for _, name, _ in pkgutil.iter_modules(['testpkg'])]['modulea', 'moduleb'] EDIT: Note that the parameter for pkgutil.iter_modules is not a list of modules, but a list of paths, so you might want to do something like this: >>> import os.path, pkgutil>>> import testpkg>>> pkgpath = os.path.dirname(testpkg.__file__)>>> print([name for _, name, _ in pkgutil.iter_modules([pkgpath])]) | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/487971', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/51025/']} | jdg_381618 |
stackexchange | llm_judgeable_groundtruth_similarity | 4325327 |
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:
They tell me to find the sum of the series $$\sum a_n :=\sum_{n=1}^{\infty}\frac{n+12}{n^3+5n^2+6n}$$ Since $\sum a_n$ is absolutely convergent, hence we can manipulate it the same way we would do with finite sums. I've tried splitting the general term and I get $$\frac{n+12}{n(n+2)(n+3)}=\frac{A}{n}+\frac{B}{n+2}+\frac{C}{n+3}=\frac{2}{n}+\frac{-5}{n+2}+\frac{3}{n+3}$$ and so $$\sum a_n =\sum \frac{2}{n}-\frac{5}{n+2}+\frac{3}{n+3}$$ Now, if I was to split the series in the sum of three different series I would get three different divergent series and so, obviously $\sum a_n$ wouldn't converge.I also suspect about being a telescopic series althought the numerators of each fraction makes it difficult to find the cancellation terms. I also know that I can rearrange the terms in my series, althought I cannot see how would this solve the problem. If anyone could give me a hint I would really appreciate it.
Now provide the response and nothing else.
| As you said, for every $N \in \mathbb{N}^*$ , one has \begin{align*}\sum_{n=1}^N a_n &=\sum_{n=1}^N \frac{2}{n}-\frac{5}{n+2}+\frac{3}{n+3}\\&=2 \sum_{n=1}^N \frac{1}{n} - 5 \sum_{n=3}^{N+2} \frac{1}{n} + 3 \sum_{n=4}^{N+3} \frac{1}{n}\\&=2 \left(1 + \frac{1}{2} + \frac{1}{3} + \sum_{n=4}^N \frac{1}{n} \right) - 5 \left( \frac{1}{3} + \sum_{n=4}^N \frac{1}{n} + \frac{1}{N+1} + \frac{1}{N+2} \right)\\&\quad + 3 \left( \sum_{n=4}^N \frac{1}{n} + \frac{1}{N+1} + \frac{1}{N+2} + \frac{1}{N+3} \right)\\&= 2 - 5 \left( \frac{1}{N+1} + \frac{1}{N+2} \right) + 3 \left( \frac{1}{N+1} + \frac{1}{N+2} + \frac{1}{N+3} \right)\end{align*} Now just let $N$ tend to $+\infty$ to see that $$\boxed{\sum_{n=1}^{\infty} a_n = 2}$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4325327', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/758761/']} | jdg_381619 |
stackexchange | llm_judgeable_groundtruth_similarity | 61129773 |
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 reading the MDS attack paper RIDL: Rogue In-Flight Data Load . They discuss how the Line Fill Buffer can cause leakage of data. There is the About the RIDL vulnerabilities and the "replaying" of loads question that discusses the micro-architectural details of the exploit. One thing that isn't clear to me after reading that question is why we need a Line Fill Buffer if we already have a store buffer. John McCalpin discusses how the store buffer and Line Fill Buffer are connected in How does WC-buffer relate to LFB? on the Intel forums, but that doesn't really make things clearer to me. For stores to WB space, the store data stays in the store buffer until after the retirement of the stores. Once retired, data can written to the L1 Data Cache (if the line is present and has write permission), otherwise an LFB is allocated for the store miss. The LFB will eventually receive the "current" copy of the cache line so that it can be installed in the L1 Data Cache and the store data can be written to the cache. Details of merging, buffering, ordering, and "short cuts" are unclear.... One interpretation that is reasonably consistent with the above would be that the LFBs serve as the cacheline-sized buffers in which store data is merged before being sent to the L1 Data Cache. At least I think that makes sense, but I am probably forgetting something.... I've just recently started reading up on out-of-order execution so please excuse my ignorance. Here is my idea of how a store would pass through the store buffer and Line Fill Buffer. A store instruction get scheduled in the front-end. It executes in the store unit. The store request is put in the store buffer (an address and the data) An invalidate read request is sent from the store buffer to the cache system If it misses the L1d cache, then the request is put in the Line Fill Buffer The Line Fill Buffer forwards the invalidate read request to L2 Some cache receives the invalidate read and sends its cache line The store buffer applies its value to the incoming cache line Uh? The Line Fill Buffer marks the entry as invalid Questions Why do we need the Line Fill Buffer if the store buffer already exists to track outsanding store requests? Is the ordering of events correct in my description?
Now provide the response and nothing else.
| Why do we need the Line Fill Buffer if the store buffer already exists to track outsanding store requests? The store buffer is used to track stores, in order, both before they retire and after they retire but before they commit to the L1 cache 2 . The store buffer conceptually is a totally local thing which doesn't really care about cache misses. The store buffer deals in "units" of individual stores of various sizes. Chips like Intel Skylake have store buffers of 50+ entries . The line fill buffers primary deal with both loads and stores that miss in the L1 cache . Essentially, it is the path from the L1 cache to the rest of the memory subsystem and deals in cache line sized units. We don't expect the LFB to get involved if the load or store hits in the L1 cache 1 . Intel chips like Skylake have many fewer LFB entries, probably 10 to 12 (testing points to 12 for Skylake ). Is the ordering of events correct in my description? Pretty close. Here's how I'd change your list: A store instructions gets decoded and split into store-data and store-address uops, which are renamed, scheduled and have a store buffer entry allocated for them. The store uops execute in any order or simultaneously (the two sub-items can execute in either order depending mostly on which has its dependencies satisfied first). The store data uop writes the store data into the store buffer. The store address uop does the V-P translation and writes the address(es) into the store buffer. At some point when all older instructions have retired, the store instruction retires . This means that the instruction is no longer speculative and the results can be made visible. At this point, the store remains in the store buffer and is called a senior store. The store now waits until it is at the head of the store buffer (it is the oldest not committed store), at which point it will commit (become globally observable) into the L1, if the associated cache line is present in the L1 in MESIF Modified or Exclusive state. (i.e. this core owns the line) If the line is not present in the required state (either missing entirely, i.e,. a cache miss, or present but in a non-exclusive state), permission to modify the line and the line data (sometimes) must be obtained from the memory subsystem: this allocates an LFB for the entire line, if one is not already allocated. This is a so-called request for ownership (RFO), which means that the memory hierarchy should return the line in an exclusive state suitable for modification, as opposed to a shared state suitable only for reading (this invalidates copies of the line present in any other private caches). An RFO to convert Shared to Exclusive still has to wait for a response to make sure all other caches have invalidated their copies. The response to such an invalidate doesn't need to include a copy of the data because this cache already has one. It can still be called an RFO; the important part is gaining ownership before modifying a line.6. In the miss scenario the LFB eventually comes back with the full contents of the line, which is committed to the L1 and the pending store can now commit 3 . This is a rough approximation of the process. Some details may differ on some or all chips, including details which are not well understood. As one example, in the above order, the store miss lines are not fetched until the store reaches the head of the store queue. In reality, the store subsystem may implement a type of RFO prefetch where the store queue is examined for upcoming stores and if the lines aren't present in L1, a request is started early (the actual visible commit to L1 still has to happen in order, on x86, or at least "as if" in order). So the request and LFB use may occur as early as when step 3 completes (if RFO prefetch applies only after a store retires), or perhaps even as early as when 2.2 completes, if junior stores are subject to prefetch. As another example, step 6 describes the line coming back from the memory hierarchy and being committed to the L1, then the store commits. It is possible that the pending store is actually merged instead with the returning data and then that is written to L1. It is also possible that the store can leave the store buffer even in the miss case and simply wait in the LFB, freeing up some store buffer entries. 1 In the case of stores that hit in the L1 cache, there is a suggestion that the LFBs are actually involved: that each store actually enters a combining buffer (which may just be an LFB) prior to being committed to the cache, such that a series of stores targeting the same cache line get combined in the cache and only need to access the L1 once. This isn't proven but in any case it is not really part of the main use of LFBs (more obvious from the fact we can't even really tell if it is happening or not). 2 The buffers that hold stores before and retirement might be two entirely different structures, with different sizes and behaviors, but here we'll refer to them as one structure. 3 The described scenarios involves the store that misses waiting at the head of the store buffer until the associated line returns. An alternate scenario is that the store data is written into the LFB used for the request, and the store buffer entry can be freed. This potentially allows some subsequent stores to be processed while the miss is in progress, subject to the strict x86 ordering requirements. This could increase store MLP. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/61129773', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/582010/']} | jdg_381620 |
stackexchange | llm_judgeable_groundtruth_similarity | 52476328 |
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 a newbie in scala. Please be patient. I have this code. import org.apache.spark.sql.{DataFrame, Dataset, SparkSession}import org.apache.spark.ml.clustering.KMeansimport org.apache.spark.ml.evaluation._import org.apache.spark.ml.linalg.Vectorsimport org.apache.spark.ml.evaluation.ClusteringEvaluator// create spark sessionimplicit val spark = SparkSession.builder().appName("clustering").getOrCreate()// read fileval fileName = """file:///some_location/head_sessions_sample.csv"""// create DF from fileval df = spark.read.format("csv").option("header", "true").option("inferSchema", "true").load(fileName)def inputKmeans(df: DataFrame,spark: SparkSession): DataFrame = { try { val a = df.select("id", "start_ts", "duration", "ip_dist").map(r => (r.getInt(0), Vectors.dense(r.getDouble(1), r.getDouble(2), r.getDouble(3)))).toDF("id", "features") a } catch { case e: java.lang.ClassCastException => spark.emptyDataFrame }}val t = inputKmeans(df).filter( _ != null )t.foreach(r => if (r.get(0) != null) println(r.get(0))) For the moment, i want to ignore my conversion errors. But somehow, I still have them. 2018-09-24 11:26:22 ERROR Executor:91 - Exception in task 0.0 in stage 4.0 (TID 6) java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Double I dont think there is any point to give a snapshot of the csv. At this point, i just want to ignore conversion errors. Any ideas why this is happening?
Now provide the response and nothing else.
| The easiest way to revoke/invalidate is probably just to remove the token on the client and pray nobody will hijack it and abuse it. Your approach with "accessCode" column would work but I would be worried about the performance. The other and probably the better way would be to black-list tokens in some database. I think Redis would be the best for this as it supports timeouts via EXPIRE so you can just set it to the same value as you have in your JWT token. And when the token expires it will automatically remove. You will need fast response time for this as you will have to check if the token is still valid (not in the black-list or different accessCode) on each request that requires authorization and that means calling your database with invalidated tokens on each request. Refresh tokens are not the solution Some people recommend using long-lived refresh tokens and short-lived access tokens. You can set access token to let's say expire in 10 minutes and when the password change, the token will still be valid for 10 minutes but then it will expire and you will have to use the refresh token to acquire the new access token. Personally, I'm a bit skeptical about this because refresh token can be hijacked as well: http://appetere.com/post/how-to-renew-access-tokens and then you will need a way to invalidate them as well so, in the end, you can't avoid storing them somewhere. ASP.NET Core implementation using StackExchange.Redis You're using ASP.NET Core so you will need to find a way how to add custom JWT validation logic to check if the token was invalidated or not. This can be done by extending default JwtSecurityTokenHandler and you should be able to call Redis from there. In ConfigureServices add: services.AddSingleton<IConnectionMultiplexer>(ConnectionMultiplexer.Connect("yourConnectionString"));services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(opt => { opt.SecurityTokenValidators.Clear(); // or just pass connection multiplexer directly, it's a singleton anyway... opt.SecurityTokenValidators.Add(new RevokableJwtSecurityTokenHandler(services.BuildServiceProvider())); }); Create your own exception: public class SecurityTokenRevokedException : SecurityTokenException{ public SecurityTokenRevokedException() { } public SecurityTokenRevokedException(string message) : base(message) { } public SecurityTokenRevokedException(string message, Exception innerException) : base(message, innerException) { }} Extend the default handler : public class RevokableJwtSecurityTokenHandler : JwtSecurityTokenHandler{ private readonly IConnectionMultiplexer _redis; public RevokableJwtSecurityTokenHandler(IServiceProvider serviceProvider) { _redis = serviceProvider.GetRequiredService<IConnectionMultiplexer>(); } public override ClaimsPrincipal ValidateToken(string token, TokenValidationParameters validationParameters, out SecurityToken validatedToken) { // make sure everything is valid first to avoid unnecessary calls to DB // if it's not valid base.ValidateToken will throw an exception, we don't need to handle it because it's handled here: https://github.com/aspnet/Security/blob/beaa2b443d46ef8adaf5c2a89eb475e1893037c2/src/Microsoft.AspNetCore.Authentication.JwtBearer/JwtBearerHandler.cs#L107-L128 // we have to throw our own exception if the token is revoked, it will cause validation to fail var claimsPrincipal = base.ValidateToken(token, validationParameters, out validatedToken); var claim = claimsPrincipal.FindFirst(JwtRegisteredClaimNames.Jti); if (claim != null && claim.ValueType == ClaimValueTypes.String) { var db = _redis.GetDatabase(); if (db.KeyExists(claim.Value)) // it's blacklisted! throw the exception { // there's a bunch of built-in token validation codes: https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/blob/7692d12e49a947f68a44cd3abc040d0c241376e6/src/Microsoft.IdentityModel.Tokens/LogMessages.cs // but none of them is suitable for this throw LogHelper.LogExceptionMessage(new SecurityTokenRevokedException(LogHelper.FormatInvariant("The token has been revoked, securitytoken: '{0}'.", validatedToken))); } } return claimsPrincipal; }} Then on your password change or whatever set the key with jti of the token to invalidate it. Limitation!: all methods in JwtSecurityTokenHandler are synchronous, this is bad if you want to have some IO-bound calls and ideally, you would use await db.KeyExistsAsync(claim.Value) there. The issue for this is tracked here: https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/issues/468 unfortunately no updates for this since 2016 :( It's funny because the function where token is validated is async: https://github.com/aspnet/Security/blob/beaa2b443d46ef8adaf5c2a89eb475e1893037c2/src/Microsoft.AspNetCore.Authentication.JwtBearer/JwtBearerHandler.cs#L107-L128 A temporary workaround would be to extend JwtBearerHandler and replace the implementation of HandleAuthenticateAsync with override without calling the base so it would call your async version of validate. And then use this logic to add it. The most recommended and actively maintained Redis clients for C#: StackExchange.Redis (also used on stackoverflow) ( Using StackExchange.Redis in a ASP.NET Core Controller ) ServiceStack.Redis (commercial with limits) Might help you to choose one: Difference between StackExchange.Redis and ServiceStack.Redis StackExchange.Redis has no limitations and is under the MIT license. So I would go with the StackExchange's one | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/52476328', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3600237/']} | jdg_381621 |
stackexchange | llm_judgeable_groundtruth_similarity | 703373 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
Stopping websites using Stop-Website is, apparently, not the same as stopping them using the IIS Manager. Stop-Website 'Some site'iisreset.exe# site is started again Using IIS Manager, the state is the same after a reset/reboot. I guess stopping a site using IIS Manager modifies some sort of persistent configuration (the registry?). Can anyone tell me how I can use PowerShell to stop a site permanently, so that a reset/reboot does not bring the site online again? (Stop-WebAppPool exhibits exactly the same behavior.)
Now provide the response and nothing else.
| Joseph's answer makes perfect sense, but it doesn't seem to work. The attribute 'serverAutoStart' on the site node in applicationHost.config is not changed. One way to change is: Set-WebConfigurationProperty -pspath 'MACHINE/WEBROOT/APPHOST' -filter "system.applicationHost/sites/site[@name='Default Web Site']" -name "serverAutoStart" -value "False" but that's a mouthful. Another way is: Set-ItemProperty "IIS:\Sites\Default Web Site" serverAutoStart False It's also interesting that this attribute is not directly editable in IIS Manager, you have to go into the Configuration Editor to change it. Yes, starting or stopping the site in IIS Manager changes that attribute, but that's not obvious to the user. | {} | {'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/703373', 'https://serverfault.com', 'https://serverfault.com/users/107959/']} | jdg_381622 |
stackexchange | llm_judgeable_groundtruth_similarity | 6061080 |
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 UIWebView on the bottom of a UITableView: [self.tableView setTableFooterView:webview]; I need to add some buttons at the end of the UIWebView. The height of the UIWebView isn’t constant. If I do something like [webview addSubview:button]; The button will overlap the webview, since the coordinates of the button's frame are based on the beginning of the UIWebView.I thought about defining the button’s frame after finishing load the UIWebView: - (void)webViewDidFinishLoad:(UIWebView *)webView { CGRect frame = CGRectMake(10, webView.bounds.size.height, 280, 21); But the problem is that I also have some data in the UITableView and it’s height isn’t constant. Of course I could keep the height of the UITableView in a variable while I’m building it, but I think that’s a very ugly solution.I also thought about having 2 footers in the UITableView, but it doesn’t look like it is possible...Just in case it is relevant, the UIWebView loads a HTML string before the buttons are added.Any ideas? Thanks.
Now provide the response and nothing else.
| Yes, SSIS can perform the requirements that you have specified in the question. Following example should give you an idea of how it can be done. Example uses SQL Server as the back-end. Some of the basic test scenarios performed on the package are provided below. Sorry for the lengthy answer. Step-by-step process: In the SQL Server database, create two tables namely dbo.ItemInfo and dbo.Staging . Create table queries are available under Scripts section. Structure of these tables are shown in screenshot # 1 . ItemInfo will hold the actual data and Staging table will hold the staging data to compare and update the actual records. Id column in both these tables is an auto-generated unique identity column. IsProcessed column in the table ItemInfo will be used to identify and delete the records that are no longer valid. Create an SSIS package and create 5 variables as shown in screenshot # 2 . I have used .txt extension for the tab delimited files and hence the value *.txt in the variable FileExtension . FilePath variable will be assigned with value during run-time. FolderLocation variable denotes where the files will be located. SQLPostLoad and SQLPreLoad variables denote the stored procedures used during the pre-load and post-load operations. Scripts for these stored procedures are provided under the Scripts section. Create an OLE DB connection pointing to the SQL Server database. Create a flat file connection as shown in screenshots # 3 and # 4 . Flat File Connection Columns section contains column level information. Screenshot # 5 shows the columns data preview. Configure the Control Flow Task as shown in screenshot # 6 . Configure the tasks Pre Load , Post Load and Loop Files as shown in screenshots # 7 - # 10 . Pre Load will truncate staging table and set IsProcessed flag to false for all rows in ItemInfo table. Post Load will update the changes and will delete rows in database that are not found in the file. Refer the stored procedures used in those tasks to understand what is being done in these Execute SQL tasks. Double-click on the Load Items data flow task and configure it as shown in screenshot # 11 . Read File is a flat file source configured to use the flat file connection. Row Count is derived column transformation and its configuration is shown in screenshto # 12 . Check Exist is a lookup transformation and its configurations are shown in screenshots # 13 - # 15 . Lookup No Match Output is redirected to Destination Split on the left side. Lookup Match Output is redirected to Staging Split on the left side. Destination Split and Staging Split have the exact same configuration as shown in screenshot # 16 . The reason for 9 different destinations for both destination and staging table is to improve the performance of the package. All the destination tasks 0 - 8 are configured to insert data into table dbo.ItemInfo as shown in screenshot # 17 . All the staging tasks 0 - 8 are configured to insert data into dbo.Staging as shown in screenshot # 18 . On the Flat File connection manager, set the ConnectionString property to use the variable FilePath as shown in screenshot # 19 . This will enable the package to use the value set in the variable as it loops through each file in a folder. Test scenarios: Test results may vary from machine to machine. In this scenario, file was located locally on the machine. Files on network might perform slower. This is provided just to give you an idea. So, please take these results with grain of salt. Package was executed on a 64-bit machine with Xeon single core CPU 2.5GHz and 3.00 GB RAM. Loaded a flat file with 1 million rows . Package executed in about 2 mins 47 seconds . Refer screenshots # 20 and # 21 . Used the queries provided under Test queries section to modify the data to simulate update, delete and creation of new records during the second run of the package. Loaded the same file containing the 1 million rows after the following queries were executed in the database. Package executed in about 1 min 35 seconds . Refer screenshots # 22 and # 23 . Please note the number of rows redirected to destination and staging table in screenshot # 22 . Hope that helps. Test queries: . --These records will be deleted during next run --because item ids won't match with file data.--(111111 row(s) affected)UPDATE dbo.ItemInfo SET ItemId = 'DEL_' + ItemId WHERE Id % 9 IN (3)--These records will be modified to their original item type of 'General'--because that is the data present in the file.--(222222 row(s) affected)UPDATE dbo.ItemInfo SET ItemType = 'Testing' + ItemId WHERE Id % 9 IN (2,6)--These records will be reloaded into the table from the file.--(111111 row(s) affected)DELETE FROM dbo.ItemInfo WHERE Id % 9 IN (5,9) Flat File Connection Columns . Name InputColumnWidth DataType OutputColumnWidth---------- ---------------- --------------- -----------------Id 8 string [DT_STR] 8ItemId 11 string [DT_STR] 11ItemName 21 string [DT_STR] 21ItemType 9 string [DT_STR] 9 Scripts: (to create both tables and stored procedures) . CREATE TABLE [dbo].[ItemInfo]( [Id] [int] IDENTITY(1,1) NOT NULL, [ItemId] [varchar](255) NOT NULL, [ItemName] [varchar](255) NOT NULL, [ItemType] [varchar](255) NOT NULL, [IsProcessed] [bit] NULL, CONSTRAINT [PK_ItemInfo] PRIMARY KEY CLUSTERED ([Id] ASC), CONSTRAINT [UK_ItemInfo_ItemId] UNIQUE NONCLUSTERED ([ItemId] ASC)) ON [PRIMARY]GOCREATE TABLE [dbo].[Staging]( [Id] [int] IDENTITY(1,1) NOT NULL, [ItemId] [varchar](255) NOT NULL, [ItemName] [varchar](255) NOT NULL, [ItemType] [varchar](255) NOT NULL, CONSTRAINT [PK_Staging] PRIMARY KEY CLUSTERED ([Id] ASC)) ON [PRIMARY]GOCREATE PROCEDURE [dbo].[PostLoad]ASBEGIN SET NOCOUNT ON; UPDATE ITM SET ITM.ItemName = STG.ItemName , ITM.ItemType = STG.ItemType , ITM.IsProcessed = 1 FROM dbo.ItemInfo ITM INNER JOIN dbo.Staging STG ON ITM.ItemId = STG.ItemId; DELETE FROM dbo.ItemInfo WHERE IsProcessed = 0;ENDGOCREATE PROCEDURE [dbo].[PreLoad]ASBEGIN SET NOCOUNT ON; TRUNCATE TABLE dbo.Staging; UPDATE dbo.ItemInfo SET IsProcessed = 0;ENDGO Screenshot #1: Screenshot #2: Screenshot #3: Screenshot #4: Screenshot #5: Screenshot #6: Screenshot #7: Screenshot #8: Screenshot #9: Screenshot #10: Screenshot #11: Screenshot #12: Screenshot #13: Screenshot #14: Screenshot #15: Screenshot #16: Screenshot #17: Screenshot #18: Screenshot #19: Screenshot #20: Screenshot #21: Screenshot #22: Screenshot #23: | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6061080', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/715417/']} | jdg_381623 |
stackexchange | llm_judgeable_groundtruth_similarity | 43814132 |
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 get the "mycred" balance of a customer through the order while using WP ALL Export to export the customer balance based on orders to a spreadsheet. It's actually probably quite simple. I'm able to get the Order ID, but not the Customer ID Here is what I'm doing to test if I can get the customer ID: function get_customeruserid($value){ global $woocommerce, $post; $order = new WC_Order($post->ID); $order_id = $order->get_order_number(); $customer = new WC_Customer($post->ID); $user_id = $customer->get_ID(); $value = $user_id; return $value;} This returns a 0. However, I can get the order number easily enough by doing this: function get_customerorderid($value){ global $woocommerce, $post; $order = new WC_Order($post->ID); $order_id = $order->get_order_number(); $value = $order_id; return $value;} This returns the customer's order number which is great, but only half the battle. I now want the Customer ID so I call call the mycred balance function to show their balance. Any ideas? I'm a newbie at php and probably very bad.
Now provide the response and nothing else.
| To get the User ID from the Order ID, you can use many ways, Here are 2 of them:In WooCommerce 3.0+ you can use WC_Order Class methods this way: function get_customerorderid(){ global $order, $post; if( ! is_a($order, 'WC_Order') ) { $order_id = $post->ID; // Get an instance of the WC_Order object $order = wc_get_order($order_id); } else { $order_id = $order->id; } // Get the user ID from WC_Order methods $user_id = $order->get_user_id(); // or $order->get_customer_id(); return $user_id;} Before WooCommerce 3.0 version, you can use get_post_meta() function this way: function get_customerorderid(){ global $order, $post; if( ! is_a($order, 'WC_Order') ) { $order_id = $post->ID; } else { $order_id = $order->id; } // Get the user ID $user_id = get_post_meta($order_id, '_customer_user', true); return $user_id;} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43814132', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7971004/']} | jdg_381624 |
stackexchange | llm_judgeable_groundtruth_similarity | 14150 |
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:
I want to evalualte the quantum relative entropy $S(\rho|| \sigma)=-{\rm tr}(\rho {\rm log}(\sigma))-S(\rho)$ , where $\sigma=|\Psi\rangle\langle\Psi|$ is a density matrix corresponding to a pure state and $\rho$ is a density matrix corresponding to an arbitrary mixed state. Here, $S(\rho)$ simply denotes the Von Neumann entropy of $\rho$ . Given that $\sigma$ is diagonal, with eigenvalues $0$ and $1$ it seems that the first term in the quantum relative entropy will in general be infinite. As $S(\rho)\leq {\rm log}(d)$ , where $\rho \in L({\mathcal H}^{d})$ , the first term dominates and the quantum relative entropy is also infinite. Is this correct? And if so, what's the intuition behind this fact?
Now provide the response and nothing else.
| A qubit is a two-level quantum system and hence it can be written as: $$ |\psi \rangle = \alpha |0\rangle + \beta|1\rangle $$ where $|0 \rangle$ and $|1\rangle$ are the computational basis and they defined as $$ |0\rangle = \begin{pmatrix} 1 \\ 0 \end{pmatrix} \ \ \ \ |1\rangle = \begin{pmatrix} 0 \\ 1 \end{pmatrix} $$ and $\alpha, \beta \in \mathbb{C}$ . So we have that $|\psi \rangle \in \mathbb{C}^2 $ and you can think of $\mathbb{C}^2$ as $\mathbb{R}^4$ . However, the overall phase in the quantum state doesn't matter, that is, $|\psi\rangle $ is equivalent to $e^{i\phi} |\psi \rangle$ . Thus, you can factor this overall phase out of $|\psi\rangle$ and have only 3 parameters left. Essentially now you are considering the space $\mathbb{R}^3$ . Along with the normalization requirement, that a quantum state must have unit norm, this forces it to be a unit-sphere, which we call the Bloch-Sphere. | {} | {'log_upvote_score': 4, 'links': ['https://quantumcomputing.stackexchange.com/questions/14150', 'https://quantumcomputing.stackexchange.com', 'https://quantumcomputing.stackexchange.com/users/9082/']} | jdg_381625 |
stackexchange | llm_judgeable_groundtruth_similarity | 4541574 |
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 comprehension question. This method is given: - (NSArray*)test { NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://stackoverflow.com/"]]; NSString *result = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSMacOSRomanStringEncoding]; result = [result stringByAppendingString:@"something"]; NSArray *arr = [NSArray arrayWithObject:result]; //[result release]; return arr;} If I uncomment the release the App would crash and say it cannot access a released object. By not release ing the result string Instruments would report a leak (NSPlaceholderString). I can autorelease it on the same line I alloc it, that would solve the problem (which I'm currently doing in my App). If I understand it correctly stringByAppendingString: should create an autoreleased object so the 'old' result could be deallocated. Then the method arrayWithObject: should copy the object into an array. So my thought was to release the string after it was copied to the array. Am I missing something or something wrong with my knowledge?
Now provide the response and nothing else.
| Let's go through your code line by line. - (NSArray*)test { NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://stackoverflow.com/"]]; This creates a data object. You don't own it, but it will stick around for the rest of the method's time. So far, so good. NSString *result = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSMacOSRomanStringEncoding]; This creates a string object that you own. Again, no problem here — we just need to release it later. result = [result stringByAppendingString:@"something"]; You throw away your reference to the string object that was in result and store a new string object that you do not own. This is a leak because you can no longer release the original string. Also, you're correct in noting that the new string can be treated as an autoreleased object — which means you should not release it. NSArray *arr = [NSArray arrayWithObject:result]; Contrary to your belief, this does not copy anything. It merely keeps a reference to the new string and retains it. //[result release]; You should not release result at this point, because the object it contains is not one you own — you got it from stringByAppendingString: , not from a method with new , alloc , retain or copy in its name. Releasing this object that you do not own will almost certainly result in a crash at some point. The old object that you own and should release was lost two lines earlier, and releasing something else in its place won't help. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4541574', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_381626 |
stackexchange | llm_judgeable_groundtruth_similarity | 90648 |
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:
L1 penalized regression (aka lasso) is presented in two formulations. Let the two objective functions be$$Q_1 = \frac{1}{2}||Y - X\beta||_2^2 \\Q_2 =\frac{1}{2}||Y - X\beta||_2^2 + \lambda ||\beta||_1.$$Then the two different formulations are $$\text{argmin}_\beta \; Q_1$$subject to$$||\beta||_1 \leq t,$$and, equivalently$$\text{argmin}_\beta \; Q_2.$$Using the Karush-Kuhn-Tucker (KKT) conditions, it's easy to see how the stationarity condition for the first formulation is equivalent to taking the gradient of the second formulation and setting it equal to 0. What I can not find, nor figure out, is how the complementary slackness condition for the first formulation, $\lambda\left(||\beta||_1 - t\right) = 0$, is guaranteed to be fulfilled by the solution to the second formulation.
Now provide the response and nothing else.
| The two formulations are equivalent in the sense that for every value of $t$ in the first formulation, there exists a value of $\lambda$ for the second formulation such that the two formulations have the same minimizer $\beta$. Here's the justification: Consider the lasso formulation:$$f(\beta)=\frac{1}{2}||Y - X\beta||_2^2 + \lambda ||\beta||_1$$Let the minimizer be $\beta^*$ and let $b=||\beta^*||_1$. My claim is that if you set $t=b$ in the first formulation, then the solution of the first formulation will also be $\beta^*$. Here's the proof: Consider the first formulation $$\min \frac{1}{2}||Y - X\beta||_2^2 \text{ s.t.} ||\beta||_1\leq b$$If possible let this second formulation have a solution $\hat{\beta}$ such that $||\hat{\beta}||_1<||\beta^*||_1=b$ (note the strictly less than sign). Then it is easy to see that $f(\hat{\beta})<f(\beta^*)$ contradicting the fact that $\beta^*$ is a solution for the lasso. Thus, the solution to the first formulation is also $\beta^*$. Since $t=b$, the complementary slackness condition is satisfied at the solution point $\beta^*$. So, given a lasso formulation with $\lambda$, you construct a constrained formulation using a $t$ equal to the value of the $l_1$ norm of the lasso solution. Conversely, given a constrained formulation with $t$, you find a $\lambda$ such that the solution to the lasso will be equal to the solution of the constrained formulation. (If you know about subgradients, you can find this $\lambda$ by solving the equation $X^T(y-X\beta^*)=\lambda z^*$, where $z^* \in \partial ||\beta^*||_1)$ | {} | {'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/90648', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/21298/']} | jdg_381627 |
stackexchange | llm_judgeable_groundtruth_similarity | 4366105 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
We are a couple of newbies in MFC and we are building a multi-threded application. We come across the article in the URL that warns us not to use CCriticalSection since its implementation is broken. We are interested to know if anyone has any experience in using CCriticalSection and do you come across any problems or bugs? Is CCriticalSection usable and production ready if we use VC++ 2008 to build our application? http://www.flounder.com/avoid_mfc_syncrhonization.htm thx
Now provide the response and nothing else.
| I think that article is based on a fundamental misunderstanding of what CSingleLock is for and how to use it. You cannot lock the same CSingleLock multiple times, but you are not supposed to. CSingleLock, as its name suggests, is for locking something ONCE. Each CSingleLock just manages one lock on some other object (e.g. a CCriticalSection which you pass it during construction), with the aim of automatically releasing that lock when the CSingleLock goes out of scope. If you want to lock the underlying object multiple times you would use multiple CSingleLocks; you would not use a single CSingleLock and try to lock it multiple times. Wrong (his example): CCriticalSection crit;CSingleLock lock(&crit);lock.Lock();lock.Lock();lock.Unlock();lock.Unlock(); Right: CCriticalSection crit;CSingleLock lock1(&crit);CSingleLock lock2(&crit);lock1.Lock();lock2.Lock();lock2.Unlock();lock1.Unlock(); Even better (so you get RAII): CCriticalSection crit;// Scope the objects{ CSingleLock lock1(&crit, TRUE); // TRUE means it (tries to) locks immediately. // Do stuff which needs the lock (if IsLocked returns success) CSingleLock lock2(&crit, TRUE); // Do stuff which needs the lock (if IsLocked returns success)}// crit is unlocked now. (Of course, you would never intentionally get two locks on the same underlying critical section in a single block like that. That'd usually only happen as a result of calling functions which get a lock while inside something else that already has its own lock.) (Also, you should check CSingleLock.IsLocked to see if the lock was successful. I've left those checks out for brevity, and because they were left out of the original example.) If CCriticalSection itself suffers from the same problem then that certainly is a problem, but he's presented no evidence of that that I can see. (Maybe I missed something. I can't find the source to CCriticalSection in my MFC install to verify that way, either.) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4366105', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/532230/']} | jdg_381628 |
stackexchange | llm_judgeable_groundtruth_similarity | 1038263 |
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:
Calculate the definite integral $$I=\int_0^{\pi} \frac{\sin^2 x}{a^2+b^2-2ab \cos x}\;\mathrm dx$$ given that $a>b>0$. My Attempt: If we replace $x$ by $C$, then $$I = \int_{0}^{\pi}\frac{\sin^2 C}{a^2+b^2-2ab\cos C}\;\mathrm dC$$ Now we can use the Cosine Formula ($A+B+C=\pi$). Applying the formula gives $$\begin{align}\cos C &= \frac{a^2+b^2-c^2}{2ab}\\a^2+b^2-2ab\cos C &= c^2\end{align}$$ From here we can use the formula $\dfrac{\sin A}{a} = \dfrac{\sin B}{b} = \dfrac{\sin C}{c}$ to transform the integral to $$\begin{align}I &= \int_{0}^{\pi}\frac{\sin^2 C}{c^2}\;\mathrm dC\\&= \int_{0}^{\pi}\frac{\sin^2A}{a^2}\;\mathrm dC\\&= \int_{0}^{\pi}\frac{\sin^2 B}{b^2}\;\mathrm dC\end{align}$$ Is my process right? If not, how can I calculate the above integral?
Now provide the response and nothing else.
| We have$$\eqalign{I_m(a,b)=\int_0^\pi\frac{\cos(mx)}{a^2-2ab\cos x+b^2}\,\mathrm dx&=\left\{\matrix{\frac{\pi}{a^2-b^2}&\hbox{if}&m=0\\\cr\frac{\pi}{a^2-b^2}\left(\frac{b}{a}\right)^m&\hbox{if}&m\ne0}\right.}$$Proof can be seen here . Hence\begin{align}\int_0^{\pi} \frac{\sin^2 x}{a^2+b^2-2ab \cos x}\,\mathrm dx&=\frac{1}{2}\int_0^{\pi} \frac{1-\cos2 x}{a^2+b^2-2ab \cos x}\,\mathrm dx\\&=\frac{1}{2}\left[\frac{\pi}{a^2-b^2}-\frac{\pi}{a^2-b^2}\left(\frac{b}{a}\right)^2\right]\\&=\frac{\pi}{2 a^2}\end{align} | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1038263', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/14311/']} | jdg_381629 |
stackexchange | llm_judgeable_groundtruth_similarity | 635318 |
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 recently came across Yet Another RP2040 Trinket (the Beetle RP2040 .) In their linked schematic something caught my attention: It is R10 below - a 10k resistor straight between VUSB and GND . I can't come up with a reason why you'd want it to be there. I've built several USB-powered microcontroller devices myself and I've never included this feature. Is this something I should have been doing, or did the designer just mess up? Any ideas? My rambling thoughts about it: Normally I'd expect something like this in parallel with some capacitors you'd want to discharge, but the caps are all on the 5V/3.3V rails and the diode prevents R10 from draining them. If it were doubling as a fuse, I'd expect it to be in series with the protection diode, not tying the supply to ground. It's only about 0.5mA of always-on waste, but that's still more than the RP2040 itself draws in sleep mode. The connector is USB-C, but I don't know of any USB guidelines saying that gadgets should put a resistor between VUSB and GND. Looking at the schematic for the official Pico board , there's a GPIO attached to the VUSB through a 5k/10k pulldown divider, presumably to detect when the board is powered over USB. Maybe this designer looked at this and assumed the pulldown was required even without the GPIO?
Now provide the response and nothing else.
| It might appear useless, but it is not. The 5V node at the regulator input goes to an IO pad which can be used both as an input and as an output. As an output it can be used for powering external devices from USB. As an input, it can be used to power the device from an external 5V supply, so USB is not required to power it. When the device is powered externally, there is a diode D1 which prevents back-feeding of the external supply back into PC via USB. Except that the diode is a Schottky diode, and while Schottky diodes have better efficiency due to lower voltage in the forward biased direction, they have much larger reverse leakage current than standard diodes. This means that if you feed 5V externally to power the device, and measure the USB VBUS voltage with a multimeter, it will read roughly 5V, because the multimeter is a very high impedance input device. If you measure with an oscilloscope that has 1Mohm input impedance, it would measure much less voltage because measuring loads the diode more. Usually few hundred nanoamps is not a big issue, but on USB-C, it might be. The USB specs require that the USB host must check that the VBUS voltage is safely near zero before 5V is turned on. Due to high impedance, the diode leakage current may raise the VBUS voltage out of the safe 0V zone and it will not turn on or try comnunicating at all, because a device was not safely detected. The extra 10k resistor is there as a load for the Schottky leakage current, to keep the VBUS at connector within the safe 0V level so that host will turn 5V on when plugged in and enable communicating with the device. | {} | {'log_upvote_score': 7, 'links': ['https://electronics.stackexchange.com/questions/635318', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/4131/']} | jdg_381630 |
stackexchange | llm_judgeable_groundtruth_similarity | 11873570 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Angular does provide some support for a for loop using numbers within its HTML directives: <div data-ng-repeat="i in [1,2,3,4,5]"> do something</div> But if your scope variable includes a range that has a dynamic number then you will need to create an empty array each time. In the controller var range = [];for(var i=0;i<total;i++) { range.push(i);}$scope.range = range; In the HTML <div data-ng-repeat="i in range"> do something</div> This works, but it is unnecessary since we won't be using the range array at all within the loop. Does anyone know of setting a range or a regular for min/max value? Something like: <div data-ng-repeat="i in 1 .. 100"> do something</div>
Now provide the response and nothing else.
| I tweaked this answer a bit and came up with this fiddle . Filter defined as: var myApp = angular.module('myApp', []);myApp.filter('range', function() { return function(input, total) { total = parseInt(total); for (var i=0; i<total; i++) { input.push(i); } return input; };}); With the repeat used like this: <div ng-repeat="n in [] | range:100"> do something</div> | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/11873570', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/340939/']} | jdg_381631 |
stackexchange | llm_judgeable_groundtruth_similarity | 58648747 |
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 display a button only if there is history. Is this the correct way to do it? browserCheck.jsx helper identifies the browser and version const browserCheck = (function () { const { userAgent } = navigator; let browserNumber; let M = userAgent.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || []; if (/trident/i.test(M[1])) { browserNumber = /\brv[ :]+(\d+)/g.exec(userAgent) || []; return `IE ${browserNumber[1] || ''}`; } if (M[1] === 'Chrome') { browserNumber = userAgent.match(/\b(OPR|Edge?)\/(\d+)/); if (browserNumber != null) return browserNumber.slice(1).join(' ').replace('OPR', 'Opera').replace('Edg ', 'Edge '); } M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?']; if ((browserNumber = userAgent.match(/version\/(\d+)/i)) != null) M.splice(1, 1, browserNumber[1]); return M.join(' ');}());export default browserCheck; browserHistory.jsx sets the initial history length based on the browser import browserCheck from './browserCheck';const browserHistory = (function () { const browsers = ['chrome', 'safari', 'firefox', 'msie', 'opera']; let currentBrowser; browsers.forEach((browser) => { if (browserCheck.toLowerCase().indexOf(browser) !== -1) { currentBrowser = browser; } }); // Internet Explorer and Opera start at 0, while Firefox, Chrome, and Safari start at 1. // Refer to: https://www.w3schools.com/jsref/prop_his_length.asp let initialValue = 0; if (currentBrowser === 'chrome') initialValue = 1; if (currentBrowser === 'firefox') initialValue = 1; if (currentBrowser === 'Safari') initialValue = 1; return initialValue;}());export default browserHistory; component.jsx {(history.length > browserHistory) ? <button className={css.backButton} onClick={history.goBack} style={{ color: theme.bodyColour }} ><Back</button> : null} UPDATE : please see: w3schools.com/jsref/prop_his_length.asp Note: Internet Explorer and Opera start at 0, while Firefox, Chrome, and Safari start at 1 NEW UPDATE :helpers added. browserHistory contains the default browser history length to compare against.
Now provide the response and nothing else.
| Fast Version (Checking the package only) The code below calls the package with an unavailable version like pip install package_name==random . The call returns all the available versions. The program reads the latest version. The program then runs pip show package_name and gets the current version of the package. If it finds a match, it returns True, otherwise False. This is a reliable option given that it stands on pip import subprocessimport sysdef check(name): latest_version = str(subprocess.run([sys.executable, '-m', 'pip', 'install', '{}==random'.format(name)], capture_output=True, text=True)) latest_version = latest_version[latest_version.find('(from versions:')+15:] latest_version = latest_version[:latest_version.find(')')] latest_version = latest_version.replace(' ','').split(',')[-1] current_version = str(subprocess.run([sys.executable, '-m', 'pip', 'show', '{}'.format(name)], capture_output=True, text=True)) current_version = current_version[current_version.find('Version:')+8:] current_version = current_version[:current_version.find('\\n')].replace(' ','') if latest_version == current_version: return True else: return False Edit 2021: The code below no longer works with the new version of pip The following code calls for pip list --outdated : import subprocessimport sysdef check(name): reqs = subprocess.check_output([sys.executable, '-m', 'pip', 'list','--outdated']) outdated_packages = [r.decode().split('==')[0] for r in reqs.split()] return name in outdated_packages | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/58648747', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9079074/']} | jdg_381632 |
stackexchange | llm_judgeable_groundtruth_similarity | 17655264 |
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 created a CircularImageView with this question: Create circular image view in android Download project on GitHub 1) This is the CircularImageView class : public class CircularImageView extends ImageView { public CircularImageView(Context context) { super(context); } public CircularImageView(Context context, AttributeSet attrs) { super(context, attrs); } public CircularImageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override protected void onDraw(Canvas canvas) { Drawable drawable = getDrawable(); if (drawable == null) { return; } if (getWidth() == 0 || getHeight() == 0) { return; } Bitmap b = ((BitmapDrawable)drawable).getBitmap() ; Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true); Bitmap roundBitmap = getCroppedBitmap(bitmap, getWidth()); canvas.drawBitmap(roundBitmap, 0, 0, null); } public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) { Bitmap sbmp; if(bmp.getWidth() != radius || bmp.getHeight() != radius) sbmp = Bitmap.createScaledBitmap(bmp, radius, radius, false); else sbmp = bmp; Bitmap output = Bitmap.createBitmap(sbmp.getWidth(), sbmp.getHeight(), Bitmap.Config.ARGB_8888); final Rect rect = new Rect(0, 0, sbmp.getWidth(), sbmp.getHeight()); Paint paint = new Paint(); paint.setAntiAlias(true); paint.setFilterBitmap(true); paint.setDither(true); paint.setColor(Color.parseColor("#BAB399")); Canvas c = new Canvas(output); c.drawARGB(0, 0, 0, 0); c.drawCircle(sbmp.getWidth() / 2+0.7f, sbmp.getHeight() / 2+0.7f, sbmp.getWidth() / 2+0.1f, paint); paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); c.drawBitmap(sbmp, rect, rect, paint); return output; }} 2) I use in my layout like this : <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#cccccc" android:gravity="center" android:orientation="vertical" android:padding="10dp" > <com.mikhaellopez.circularimageview.CircularImageView android:id="@+id/imageViewCircular" android:layout_width="@dimen/image_view_size" android:layout_height="@dimen/image_view_size" android:layout_gravity="center" android:background="@drawable/border" android:src="@drawable/image" /></LinearLayout> 3) Current result in picture : How do I change this code to have a shadow and a circular border around my imageView? Objectif result : Edit 10/15/2015 : You can used or download my GitHub library CircularImageView with all the fixes by using gradle dependency : compile 'com.mikhaellopez:circularimageview:2.0.1'
Now provide the response and nothing else.
| I modified the CircularImageView found here to achieve what you want. To create a shadow around the border, I simply used these two lines: this.setLayerType(LAYER_TYPE_SOFTWARE, paintBorder);paintBorder.setShadowLayer(4.0f, 0.0f, 2.0f, Color.BLACK); You need setLayerType due to hardware acceleration on HoneyComb and up. It didn't work without it when I tried it. Here is the full code: import android.annotation.SuppressLint;import android.content.Context;import android.graphics.Bitmap;import android.graphics.BitmapShader;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.graphics.Shader;import android.graphics.drawable.BitmapDrawable;import android.util.AttributeSet;import android.widget.ImageView;public class CircularImageView extends ImageView{ private int borderWidth = 4; private int viewWidth; private int viewHeight; private Bitmap image; private Paint paint; private Paint paintBorder; private BitmapShader shader; public CircularImageView(Context context) { super(context); setup(); } public CircularImageView(Context context, AttributeSet attrs) { super(context, attrs); setup(); } public CircularImageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); setup(); } private void setup() { // init paint paint = new Paint(); paint.setAntiAlias(true); paintBorder = new Paint(); setBorderColor(Color.WHITE); paintBorder.setAntiAlias(true); this.setLayerType(LAYER_TYPE_SOFTWARE, paintBorder); paintBorder.setShadowLayer(4.0f, 0.0f, 2.0f, Color.BLACK); } public void setBorderWidth(int borderWidth) { this.borderWidth = borderWidth; this.invalidate(); } public void setBorderColor(int borderColor) { if (paintBorder != null) paintBorder.setColor(borderColor); this.invalidate(); } private void loadBitmap() { BitmapDrawable bitmapDrawable = (BitmapDrawable) this.getDrawable(); if (bitmapDrawable != null) image = bitmapDrawable.getBitmap(); } @SuppressLint("DrawAllocation") @Override public void onDraw(Canvas canvas) { // load the bitmap loadBitmap(); // init shader if (image != null) { shader = new BitmapShader(Bitmap.createScaledBitmap(image, canvas.getWidth(), canvas.getHeight(), false), Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); paint.setShader(shader); int circleCenter = viewWidth / 2; // circleCenter is the x or y of the view's center // radius is the radius in pixels of the cirle to be drawn // paint contains the shader that will texture the shape canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth, circleCenter + borderWidth - 4.0f, paintBorder); canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth, circleCenter - 4.0f, paint); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int width = measureWidth(widthMeasureSpec); int height = measureHeight(heightMeasureSpec, widthMeasureSpec); viewWidth = width - (borderWidth * 2); viewHeight = height - (borderWidth * 2); setMeasuredDimension(width, height); } private int measureWidth(int measureSpec) { int result = 0; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); if (specMode == MeasureSpec.EXACTLY) { // We were told how big to be result = specSize; } else { // Measure the text result = viewWidth; } return result; } private int measureHeight(int measureSpecHeight, int measureSpecWidth) { int result = 0; int specMode = MeasureSpec.getMode(measureSpecHeight); int specSize = MeasureSpec.getSize(measureSpecHeight); if (specMode == MeasureSpec.EXACTLY) { // We were told how big to be result = specSize; } else { // Measure the text (beware: ascent is a negative number) result = viewHeight; } return (result + 2); }} I hope it helps! . EDIT I forked your CircularImageView and added support for selector overlays. I also improved drawing performance significantly... https://github.com/Pkmmte/CircularImageView | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/17655264', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1832221/']} | jdg_381633 |
stackexchange | llm_judgeable_groundtruth_similarity | 18994669 |
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 pdo via php to update my sql.When I put primary values in the DB the encoding seems to be fine.but for some or other reason when I use sql UPDATE commandto change the data im getting gibrish.to be sure nothing is wrong with the way im passing the data I changed the query im sending to be static data that I control, and it still gives me gibrish as a result after updating. This is how im sending my data: function ConnectToSQLAndGetDBConnSTRVar() { try { $dbname = "db"; $serverName = ".\SQLEXPRESS"; $username = "user"; $pw = "pass"; $dbh = new PDO ("sqlsrv:server=$serverName;Database=$dbname","$username","$pw" ); return $dbh; } catch (PDOException $e) { print "Failed to get DB handle: " . $e->getMessage() . "\n"; exit; } } $db = ConnectToSQLAndGetDBConnSTRVar; $NewQuery = "UPDATE subtopics SET SubTopic_Name = 'תוכן' WHERE SubTopic_ID=1"; $db->query($NewQuery); its possible you will see my content as giberish to but I assure u it is not, its just in another language.. Note: that I can't use charset=utf-8 it gives me an error :An invalid keyword charset was specified in the dsn string
Now provide the response and nothing else.
| There are many things that could be causing this issue, but here's a few things you could try: Make sure the /media directory and all subdirectories have your Apache's user's group (usually 'www-data' or 'httpd'): sudo chgrp -R www-data /path/to/magento/media Make sure the /media directory and all subdirectories have appropriate permissions given to your Apache's user's group: sudo chmod -R 775 /path/to/magento/media In System->Configuration->General->Web, make sure "Base URL" and "Base Media URL" are correct under both "Secure" and "Unsecure" In your Magento database, the table core_config_data contains the raw values for your {{secure_base_url}} and {{unsecure_base_url}} Make sure these values are correct and have trailing slashes, like http://example.com/ In the system configuration above, make sure those values are correct accounting for the trailing slash in the raw value. This means they should look like {{secure_base_url}}media for example, with no slashes In System->Cache Management, disable caching Take the .htaccess files from a fresh download of your version of Magento (including the .htaccess in your document root, and any .htaccess files in /media and all subdirectories of /media), back up your current .htaccess files, then explicitly copy the fresh .htaccess files to replace them. Because .htaccess starts with the '.' character, it will be ignored by certain Linux commands, which can cause people to think they've copied or overwritten a .htaccess file when they actually haven't, so do this carefully. Now try again, and if you get the same error, that'll rule out .htaccess. If you're using SSL, try disabling SSL and if you get the same error, that'll rule out SSL Navigate to app/code/local and app/code/community and make note of the namespaces in those directories. Now go to app/etc/modules and edit every *.xml file in that directory matching the namespaces you noted with the following value for the <active> node: <?xml version="1.0"?><config> <modules> <Namespace_*> <!-- set this value to "false" --> <active>false</active> <!-- more nodes here, just leave every node alone except <active> --> </Namespace_*> </modules><config> Now try again, and if you get the same error, that'll rule out module conflicts If the images are large enough, you may be restricted by your PHP settings: Identify your loaded php.ini: <?phpphpinfo(); // Look for "Loaded Configuration File" Edit your php.ini (if you're on Ubuntu it was probably in /etc/php5/apache2/php.ini ): sudo vi /path/to/php.ini# Make these three values higher than the filesize of the images you're# trying to upload:upload_max_filesize = 200Mpost_max_size = 200Mmemory_limit = 200M Restart your webserver: sudo /etc/init.d/apache2 restart If you've gotten this far and nothing has worked, here are some time-intensive things you could do to narrow down what kind of problem it is: Create a fresh install of Magento on the same webserver and test image uploads. If they still don't work, it's a problem with Apache or PHP configuration (or possibly even version) If they do work, it was probably a problem with your Magento core files or your Magento configuration or Magento database or Apache virtual host. Take these steps to help determine which: Create a new database Delete everything in /path/to/new/magento/var/* sudo rm -rf /path/to/new/magento/var/* In your older Magento admin, go to System->Tools->Backups and click Create Backup . Once that's done, go to /path/to/old/magento/var/backup/ and insert your backup into the new database you created: mysql -p -u username database_name < backup_file In your new Magento file system, navigate to /path/to/new/magento/app/etc/local.xml and edit it to point to your new database: <username>{{db_user}}</username><password>{{db_pass}}</password><dbname>{{db_name}}</dbname> Try image uploads on the fresh Magento install again, and if you get the error, the problem is in your Magento configuration or your Magento database. If you don't get the error, the problem was in your Magento core files or your Apache virtual host. If you'd like to provide more information, probably the most useful pieces would be a copy of your loaded php.ini , apache2.conf and/or httpd.conf , and copies of your .htaccess files from document root through all subdirectories of /media , with any sensitive information obfuscated of course. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18994669', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2803295/']} | jdg_381634 |
stackexchange | llm_judgeable_groundtruth_similarity | 5211 |
Below is a question asked on the forum economics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
From what I understand after reading mainstream media, quantitative easing increases the supply of money in the economy without direct government spending (fiscal policy). It seems to have all the benefits of monetary policy (decreasing interest rates), but can still be done with rock-bottom interest rates . Is my understanding correct? What's the downside I'm missing?
Now provide the response and nothing else.
| Before the edit, you wrote "qualitative easing", but I think you refer to quantitative easing. I'll discuss both. Quantitative Easing Quantitative easing corresponds to the central bank (CB) expanding its balance sheets by "buying" assets. This is typically done in secondary markets. It mainly injects liquidity into the system. To the extent that there is an additional buyer of assets now, the price of assets/investment (interest rates) decreases. However, the quantitative impact should be negligible: Through its demand, the CB increases value and liquidity in the markets it is operating. However, the scale of its operations should be too small to affect the aggregate interest rate. Qualitative Easing Qualitative easing is a relatively new expression and refers to the riskiness of the stocks that the CB is investing in. In contrast to quantitative easing, which is about the magnitude of assets on the CB's balance sheets, qualitative easing is about the riskiness on the CB's balance sheets, and hence the decrease in aggregate risk (on the banks' balance sheets). Downsides Independence of a central bank When the CB holds assets, it is interested in their value. This may lead it to commit policies that infract its primary directive (e.g. inflation stability). Even if it does not do so , effectiveness of a CB comes from its capacity to control expectations. It suffices for households and firms to expect the CB to commit " bad " policies, to decrease the effectiveness of the CB. Number of Goals I don't have sources on this, but I seem to remember that central banks with one clear goal (i.e. monetary stability) are more effective than those with a basket of goals (i.e. monetary stability, GDP growth, decrease of unemployment rate). A general criticism can be that QE are not operations that help with the important margin, monetary stability - and that the central bank should focus on that instead. Note that these are not just esoteric points. In fact, the academics and central bankers at the "Rethinking Macro Policy" conference agreed that ( quoting Blanchard ) Throughout the conference, e.g., in Gill Marcus’ talk, and actually throughout the various meetings which took place during the IMF meetings in the following days, policy makers remarked and complained about the heavy burden placed on monetary policy in this crisis, and the danger of a political backlash against central banks. Even as the crisis recedes, it is clear that central banks will end up with substantially more responsibilities—whether they are given in full or shared—for financial regulation, financial supervision, and the use of macro prudential tools. While even the use of the policy rate has distributional implications, these implications are much more salient in the case of regulation or macro prudential tools, such as the loan-to-value ratio. The general consensus was that these distributional implications could not be ignored, and that while central banks should retain full independence with respect to traditional monetary policy, this cannot be the case for regulation or macro prudential tools. | {} | {'log_upvote_score': 4, 'links': ['https://economics.stackexchange.com/questions/5211', 'https://economics.stackexchange.com', 'https://economics.stackexchange.com/users/100/']} | jdg_381635 |
stackexchange | llm_judgeable_groundtruth_similarity | 8074152 |
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 playing around with the Web Audio API & trying to find a way to import an mp3 (so therefore this is only in Chrome), and generate a waveform of it on a canvas. I can do this in real-time, but my goal is to do this faster than real-time. All the examples I've been able to find involve reading the frequency data from an analyser object, in a function attached to the onaudioprocess event: processor = context.createJavascriptNode(2048,1,1);processor.onaudioprocess = processAudio;...function processAudio{ var freqByteData = new Uint8Array(analyser.frequencyBinCount); analyser.getByteFrequencyData(freqByteData); //calculate magnitude & render to canvas} It appears though, that analyser.frequencyBinCount is only populated when the sound is playing (something about the buffer being filled). What I want is to be able to manually/programmatically step through the file as fast as possible, to generate the canvas image. What I've got so far is this: $("#files").on('change',function(e){ var FileList = e.target.files, Reader = new FileReader(); var File = FileList[0]; Reader.onload = (function(theFile){ return function(e){ context.decodeAudioData(e.target.result,function(buffer){ source.buffer = buffer; source.connect(analyser); analyser.connect(jsNode); var freqData = new Uint8Array(buffer.getChannelData(0)); console.dir(analyser); console.dir(jsNode); jsNode.connect(context.destination); //source.noteOn(0); }); }; })(File); Reader.readAsArrayBuffer(File);}); But getChannelData() always returns an empty typed array. Any insight is appreciated - even if it turns out it can't be done. I think I'm the only one the Internet not wanting to do stuff in real-time. Thanks.
Now provide the response and nothing else.
| There is a really amazing 'offline' mode of the Web Audio API that allows you to pre-process an entire file through an audio context and then do something with the result: var context = new webkitOfflineAudioContext();var source = context.createBufferSource();source.buffer = buffer;source.connect(context.destination);source.noteOn(0);context.oncomplete = function(e) { var audioBuffer = e.renderedBuffer;};context.startRendering(); So the setup looks exactly the same as the real-time processing mode, except you set up the oncomplete callback and the call to startRendering() . What you get back in e.redneredBuffer is an AudioBuffer . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8074152', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/251859/']} | jdg_381636 |
stackexchange | llm_judgeable_groundtruth_similarity | 1557058 |
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 a tutor at university, and one of my students brought me this question, which I was unable to work out. It is from a past final exam in calculus II, so any response should be very basic in what machinery it uses, although it may be complicated. The series is: $$\sum \limits_{n=1}^{\infty} \frac{(-1)^n}{(2n+3)(3^n)}.$$ Normally I'm pretty good with infinite series. It is clear enough to me that this sum converges. None of the kind of obvious rearrangements yielded anything, and I couldn't come up with any smart tricks in the time we had. I put it into Wolfram and got a very striking answer indeed. Wolfram reports the value to be $\frac{1}{6}(16-3\sqrt{3} \pi)$. It does this using something it calls the "Lerch Transcendent" ( link here about Lerch) . After looking around, I think maybe I can understand how the summing is done, if you knew about this guy and special values it takes. But how could I do it as a calculus II student, never having seen anything like this monstrosity before?
Now provide the response and nothing else.
| Note that we can write the sum as $f(1/3)$ where $$f(x)=x^{-3/2}\sum_{n=1}^{\infty}(-1)^n\frac{\left(\sqrt{x}\right)^{2n+3}}{2n+3}\tag 1$$ Now, denote the series in $(1)$ by $g(x)$. Then, we have $$g'(x)=\frac12\sqrt{x}\,\,\sum_{n=1}^\infty (-1)^n x^n=- \frac{x^{3/2}}{2(x+1)} \tag 2$$ Integrating both sides of $(2)$ yields $$g(x)=-\frac13 \sqrt{x}(x-3)-\arctan(\sqrt{x}) \tag 3$$ Now, simply substitute $g(x)$ in $(3)$ into $(1)$ and evaluate at $x=1/3$. Proceeding, we find $$f(1/3)=\frac83-\frac{\pi\sqrt{3}}{2}$$ | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/1557058', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/112357/']} | jdg_381637 |
stackexchange | llm_judgeable_groundtruth_similarity | 2141 |
Below is a question asked on the forum astronomy.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Comets have tails. We all know that, and a lucky few have seen the better known. So why don't the planets (e.g. Earth, Mars) have tails? Why don't asteroids don't have tails?
Now provide the response and nothing else.
| See Jeans Escape . If the average velocity of the volatile molecules is above escape velocity, volatiles will escape. And the with the shallow gravity wells of comets, escape velocity is very low. The earth and Mars have lots volatile gases and ice. But with their deeper gravity wells, sublimated volatile ices aren't hurled into space as they are with comets. A lot of asteroids have high enough temperatures that any volatiles would exceed their tiny escape velocity. Which is why a lot of asteroids in our neighborhood have little or no volatile ices. If they ever had ice, it would have long since boiled off. For example, after Comet Wilson Harrington outgassed much of its volatiles, it'd no longer have a tail when coming near the sun. They thought they had lost the comet when they stopped sighting it. Then later they discovered asteroid 1979 VA. Then they noticed they were the same object. It's speculated there are more "dead" comets like Asteroid 1979 VA. Former comets who've outgassed most their volatiles. | {} | {'log_upvote_score': 4, 'links': ['https://astronomy.stackexchange.com/questions/2141', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/1377/']} | jdg_381638 |
stackexchange | llm_judgeable_groundtruth_similarity | 19647012 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to create an activity model in order to show a timeline kind of thing with my application, but I don't know exactly how to dynamically reference a collection in a mongoose schema. Im using mongoose (3.6.20) In what I have so far the actor is always a user, but the _object can be a user or a post. This is kind of what I have: userSchema = new Schema({ _id: ObjectId; name: String});postSchema = new Schema({ _id: ObjectId; author_id: String, ref: User}); What I want to do is: activitySchema = new Schema({ _object: { String: Id of the thing, ref:'can be user or post'} // Object that the verb occurred on... can be a post or a user actor: { type: String, ref: 'User' }, action: { type: String, default: ""}, //ex: has replied to:, or started following:}); How can I solve this using dynamic references with mongoose if possible, and how will I populate it? Thank you!
Now provide the response and nothing else.
| updated 2017.. you can now have dynamic refs using refPath or even multiple dynamic refs. var userSchema = new Schema({ name: String, connections: [{ kind: String, item: { type: ObjectId, refPath: 'connections.kind' } }] }); The refPath property above means that mongoose will look at the connections.kind path to determine which model to use for populate(). In other words, the refPath property enables you to make the ref property dynamic. http://mongoosejs.com/docs/populate.html Dynamic References | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19647012', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/590100/']} | jdg_381639 |
stackexchange | llm_judgeable_groundtruth_similarity | 34053315 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
React Native has a TextInput component to accept user inputs and I'm interested in the difference between onEndEditing Callback that is called when text input ends. onBlur Callback that is called when the text input is blurred. Is there a scenario where it can't be solved just with onBlur , when is onEndEditing useful?
Now provide the response and nothing else.
| First let me say I was struggling finding the answer to this question! I believe this is rooted in history since it originates from iOS which has the native event UIControlEventEditingDidEnd . That's probably the naming before blur was introduced as an abstraction. TL:DR; onEndEditing should really be deprecated in my opinion, but as of right now you should use it because it is the most platform agnostic version of blur. See below. Both onBlur and onEndEditing get an event. On iOS both of these seem to do the exact same thing, and the event has the native text. In Android, it is two different events, and only one of them has access to the text. To me this seems like a bug. Notice the differences between Android onEndEditing and Android onBlur . // this is undefined on AndroidonBlur={(e) => alert(e.nativeEvent.text)} So if reading the text during a blur, you get cross-platform usability with onEndEditing for now. See this rnplay to see the differences in OS | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/34053315', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1125029/']} | jdg_381640 |
Subsets and Splits