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 | 2180404 |
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 C function to find the second occurrence of sub-string in string? i.e. String - "213 File status 550 Access Denied. 550 Access Denied." This function would return "550 found twice"....
Now provide the response and nothing else.
| Use strstr . Since strstr returns a pointer to the first occurrence of the needle, you can use the result to find the next occurrence. For example, to count occurrences of the string "550" : #include <string.h>int count_550s(const char *str){ const char *ptr = str; int count = 0; while ((ptr = strstr(ptr, "550")) != NULL) { // ptr is pointing at "550...", so we skip // over the "550". ptr += 3; count++; } return count;} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2180404', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/52256/']} | jdg_86341 |
stackexchange | llm_judgeable_groundtruth_similarity | 8807799 |
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 take a photo, find out its orientation, draw it on canvas and rotate the canvas. I need help to find out orientation of the photo
Now provide the response and nothing else.
| You need to use the EXIF tag embedded in the photo: private int getExifOrientation() { ExifInterface exif; int orientation = 0; try { exif = new ExifInterface( mImagePath ); orientation = exif.getAttributeInt( ExifInterface.TAG_ORIENTATION, 1 ); } catch ( IOException e ) { e.printStackTrace(); } Log.d(TAG, "got orientation " + orientation); return orientation;} However, the actual EXIF value returned is sorta weird. It allows for all variety of rotation and mirroring. The best reference I've found is here . In general, after you get the orientation, you'll want to run it through a lookup function to get the rotation in degrees: private int getBitmapRotation() { int rotation = 0; switch ( getExifOrientation() ) { case ExifInterface.ORIENTATION_ROTATE_180: rotation = 180; break; case ExifInterface.ORIENTATION_ROTATE_90: rotation = 90; break; case ExifInterface.ORIENTATION_ROTATE_270: rotation = 270; break; } return rotation;} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8807799', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/44533/']} | jdg_86342 |
stackexchange | llm_judgeable_groundtruth_similarity | 10005544 |
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 encountered the following interview question on the Internet. Describe a data structure for which getValue(int index), setValue(int index, int value), and setAllValues(int value) are all O(1). Though array is good enough for the first and second operations to be performed in O(1), what can be proposed for the third (setAllValues)?
Now provide the response and nothing else.
| How about an array of tuples {timestamp, value} , with an additional {timestamp, value} called all . Since you only care about the relative time of insertions, you can use a monotonically increasing id for the values of timestamp: type Entry { int timestamp, int value}type structure { int id Entry all Entry[] array} Initialise all fields to 0. Then the following should work for you: setValue(index i, value v): array[i] = {id++, value} value getValue(index i) if(all.timestamp > array[i].timestamp) return all.valueelse return array[i].value setAll(value v) all = {id++, value} A problem with this approach is that eventually you'll run out of ids for timestamp, and might wrap around. If you chose a 64 bit value to store timestamps, then this gives you 18,446,744,073,709,551,616 insertions or setAlls before this happens. Depending on the expected use of the datastructure, an O(n) cleanup phase might be appropriate, or you could just throw an exception. Another issue that might need to be considered is multi-threading. Three obvious problems: if id++ isn't atomic and two threads obtained a new id at the same time then you could get two entries with the same id. if the incrementation of id and the assignment of the created tuple aren't atomic together (they're probably not) and there were two simultaneous inserts, then you could get a race condition where the older id wins. if the assignment of the tuple isn't atomic, and there's an insert() at the same time as a get() then you might end up in a position where you've got say {new_id, old_value} in the array, causing the wrong value to be returned. If any of these are problems, the absolute easiest solution to this is to put "not thread safe" in the documentation (cheating). Alternatively, if you can't implement the methods atomically in your language of choice, you'd need to put some sort of synchronisation locks around them. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/10005544', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/468125/']} | jdg_86343 |
stackexchange | llm_judgeable_groundtruth_similarity | 8257735 |
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 new to SQuirrel SQL. I need some help to translating CCSID 65535 into ASCII, UNICODE (or anything human readable) I am using the JDBC driver per the following guide . According to IBM's website : What character conversion issues must my program deal with? The IBM i database uses EBCDIC to store text. Java uses Unicode. The JDBC driver handles all conversion between character sets, so your program should not have to worry about it. but I think they refer to CCSID 37 and not 65535(Hex). I have got the following info, from my DB2 DB Doing DSPFD gives me: Coded character set identifier . . . . . . : CCSID 65535 Doing DSPFFD gives me: TXT CHAR 3 3 41 Both Text Field text . . . . . . . . . . . . . . . : Text Coded CharacterSet Identifier . . . . . : 65535 But the SQuirrel query result for the TXT field is: 5c c1 c4 c4 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 c1 40 7e 40 c2 40 4e 40 c3 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 Which should be translated to something like: *ADD A = B + C
Now provide the response and nothing else.
| From the JDBC FAQ: Why is the Toolbox JDBC returning EBCDIC characters to my Java program? Normally, the Toolbox JDBC driver will translate EBCDIC characters to Unicode Strings automatically. If it appears to be returning untranslated EBCDIC characters instead, then it is likely that the field in the IBM i database is tagged with CCSID 65535. The Toolbox JDBC driver recognizes this CCSID as a field that should not be translated. To avoid this behavior, tag fields on the IBM i that you want to be translated, with a valid CCSID. Alternately, you can set the "translate binary" connection property to "true", which instructs the JDBC driver to translate all fields, including those tagged with CCSID 65535. The easiest way to do this is to add ";translate binary=true" to the end of the URL used when connecting to the database. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8257735', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/939583/']} | jdg_86344 |
stackexchange | llm_judgeable_groundtruth_similarity | 2917360 |
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:
You go to school in a building located six blocks east and seven blocks northof your home. So, in walking to school each day you go thirteen blocks. All streets in a rectangular pattern are available to you for walking.In how many different paths can you go from home to school, walking only thirteenblocks? I want to say that the answer can be found knowing that there are $6!$ ways east and $7!$ ways north. Then, the answer would be $6!+ 7!$ . I feel like this is way too simple of a solution to be correct.
Now provide the response and nothing else.
| Consider this: You have to go north 7 times and go east 6 times. How can you slip in the 6 "east moves" into 7 "north moves"? The answer is then $\binom{6+7}6=\binom{13}6=1716$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2917360', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/591622/']} | jdg_86345 |
stackexchange | llm_judgeable_groundtruth_similarity | 14257979 |
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 one of my models I have code like this: def lendable_category=(i) set_category(i)enddef free_category=(i) set_category(i)enddef skill_category=(i) set_category(i)end The methods are virtual parameters which I've added so I can save an object using a params hash without coercing the hash in my controller. It doesn't feel great to say the same thing three times. Is there a better way to create identical methods like this?
Now provide the response and nothing else.
| %w(lendable free skill).each do |name| define_method "#{name}_category" do |i| set_category(i) endend | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14257979', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/687677/']} | jdg_86346 |
stackexchange | llm_judgeable_groundtruth_similarity | 361099 |
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 the set Gaussian integer $\mathbb{Z}[i]$. Show that $(2+i)$ is a prime ideal. I try to come out with a quotient ring such that the set Gaussian integers over the ideal $(2+i)$ is either a field or integral domain. But I failed to see what is the quotient ring.
Now provide the response and nothing else.
| Use that $\mathbb Z[i]\simeq \mathbb Z[X]/(X^2+1)$. Via this isomorphism $i$ corresponds to $\hat X$ (the residue class of $X$), and therefore the ideal $(2+i)$ corresponds to $(2+\hat X)=(2+X,X^2+1)/(X^2+1)$. Now $$\frac{\mathbb Z[X]/(X^2+1)}{(2+X,X^2+1)/(X^2+1)}\simeq \frac{\mathbb Z[X]}{(2+X,X^2+1)}\simeq \frac{\mathbb Z[X]/(2+X)}{(2+X,X^2+1)/(2+X)}.$$ But $\mathbb Z[X]/(2+X)\simeq \mathbb Z$, by sending $X$ to $-2$, so $$\frac{\mathbb Z[X]/(2+X)}{(2+X,X^2+1)/(2+X)}\simeq \mathbb Z/((-2)^2+1)=\mathbb Z/(5).$$ Remark. This answer has the "advantage" that doesn't use the arithmetical properties of $\mathbb Z[i]$ and can be used in many other situations, like this one . | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/361099', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/54398/']} | jdg_86347 |
stackexchange | llm_judgeable_groundtruth_similarity | 239294 |
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 want to build something with my unused fan. I am planning to put a lighting circuit using LEDs and a microcontroller (ATmega, Arduino Nano, or something), thus creating some kind of image from the rotating LEDs. However, I have no idea about how to power the circuit. It would be nice if I can power it through 220V from the fan + regulator + cable to circuit (I prefer not to use a battery), but the cable used to power the circuit in this case will always be twisted. Any idea?
Now provide the response and nothing else.
| As well as slip rings being an option, you could also use a commutator. When I made a large globe, I found it easier to source commutators from DC motors than slip rings. You can get them in all shapes and sizes. Make sure to get one with at least 4 phases. The one I got had 12 so I joined adjacent phases together to form 4 groups of 3. Then, in order to prevent shorting or dead time in the supply, you use a 4 phase bridge rectifier. That allows for a smooth DC supply without gaps or shorts that would normally happen during commutation. What I also did was to use a higher voltage supply and then build a switching regulator on the globe arm. This reduces losses from the commutation and with plenty of capacitance gives a nice smooth output. I went with 24V as the supply switched down to 5V. You can also feed mains AC on to the brushes and you'll get rectified DC on the arm. You can then get some nice high voltage DC-DC converter modules to step it down. However I would advise against using mains AC directly - much too dangerous. I'd get something like a 24V power supply brick (of 48V), both are considered safe low voltage. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/239294', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/113104/']} | jdg_86348 |
stackexchange | llm_judgeable_groundtruth_similarity | 13650450 |
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 Rails app in DB i have some query. # [email protected] # => 'blabla' and i want put this string in google or yahoo in simple ruby file i use require ... all gemsCapybara.app_host = 'http://www.google.com/' and class Google include Capybara::DSL def search visit('/') fill_in "q", :with => "blah blah" click_button("Google") ... but how can I put this code in controller (or model method)?
Now provide the response and nothing else.
| I see three issues: the way you use a DataReader negates it's big single-item-in-memory advantage by converting it to list, you're running the benchmark in an environment that differs significantly from production in a way that favors the DataTable, and you're spending time converting DataReader record to Artifact objects that is not duplicated in the DataTable code. The main advantage of a DataReader is that you don't have to load everything into memory at once. This should be a huge advantage for DataReader in web apps, where memory, rather than cpu, is often the bottleneck, but by adding each row to a generic list you've negated this. That also means that even after you change your code to only use one record at a time, the difference might not show up on your benchmarks because you're running them on a system with lot of free memory, which will favor the DataTable. Also, the DataReader version is spending time parsing the results into Artifact objects that the DataTable has not done yet. To fix the DataReader usage issue, change List<ArtifactString> to IEnumerable<ArtifactString> everywhere, and in your DataReader DAL change this line: artifactList.Add(artifact); to this: yield return artifact; This means you also need to add code that iterates over the results to your DataReader test harness to keep things fair. I'm not sure how to adjust the benchmark to create a more typical scenario that is fair to both DataTable and DataReader, except to build two versions of your page, and serve up each version for an hour under a similar production-level load so that we have real memory pressure... do some real A/B testing. Also, make sure you cover converting the DataTable rows to Artifacts... and if the argument is that you need to do this for a DataReader, but not for a DataTable, that is just plain wrong. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13650450', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1601351/']} | jdg_86349 |
stackexchange | llm_judgeable_groundtruth_similarity | 4834821 |
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 a nice little Ruby script a while back that I'm rather fond of. I'd like to improve its robustness by checking for the proper number of arguments: if ARGV.length != 2 then puts "Usage: <command> arg1 arg2"end Of course that's pseudocode. Anyways, in C or C++ I could use argv[0] to get the name that the user used to get to my command, whether they called it like ./myScript.rb or myScript.rb or /usr/local/bin/myScript.rb . In Ruby, I know that ARGV[0] is the first true argument, and ARGV does not contain the command name. Is there any way that I can get this?
Now provide the response and nothing else.
| Ruby has three ways of giving us the name of the called script: #!/usr/bin/env rubyputs "$0 : #{$0}"puts "__FILE__ : #{__FILE__}"puts "$PROGRAM_NAME : #{$PROGRAM_NAME}" Saving that code as "test.rb" and calling it a couple ways shows that the script receives the name as it was passed to it by the OS. A script only knows what the OS tells it: $ ./test.rb $0 : ./test.rb__FILE__ : ./test.rb$PROGRAM_NAME : ./test.rb$ ~/Desktop/test.rb $0 : /Users/ttm/Desktop/test.rb__FILE__ : /Users/ttm/Desktop/test.rb$PROGRAM_NAME : /Users/ttm/Desktop/test.rb$ /Users/ttm/Desktop/test.rb $0 : /Users/ttm/Desktop/test.rb__FILE__ : /Users/ttm/Desktop/test.rb$PROGRAM_NAME : /Users/ttm/Desktop/test.rb Calling it using the ~ shortcut for $HOME in the second example shows the OS replacing it with the expanded path, matching what is in the third example. In all cases it's what the OS passed in. Linking to the file using both hard and soft links shows consistent behavior. I created a hard link for test1.rb and a soft link for test2.rb: $ ./test1.rb $0 : ./test1.rb__FILE__ : ./test1.rb$PROGRAM_NAME : ./test1.rb$ ./test2.rb $0 : ./test2.rb__FILE__ : ./test2.rb$PROGRAM_NAME : ./test2.rb Launching ruby test.rb with any of the variations on the script name returns consistent results. If you only want the called filename, you can use File's basename method with one of the variables or split on the delimiter and take the last element. $0 and __FILE__ have some minor differences but for single scripts they're equivalent. puts File.basename($0) There are some benefits to using the File.basename , File.extname and File.dirname suite of methods. basename takes an optional parameter, which is the extension to strip, so if you need just the basename without the extension File.basename($0, File.extname($0)) does it without reinventing the wheel or having to deal with variable-length or missing extensions or the possibility of incorrectly truncating extension chains " .rb.txt " for instance: ruby-1.9.2-p136 :004 > filename = '/path/to/file/name.ext' => "/path/to/file/name.ext" ruby-1.9.2-p136 :005 > File.basename(filename, File.extname(filename)) => "name" ruby-1.9.2-p136 :006 > filename = '/path/to/file/name.ext' << '.txt' => "/path/to/file/name.ext.txt" ruby-1.9.2-p136 :007 > File.basename(filename, File.extname(filename)) => "name.ext" | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/4834821', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/211176/']} | jdg_86350 |
stackexchange | llm_judgeable_groundtruth_similarity | 1892037 |
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 was thinking about the wheat and chessboard story and thinking of the total number of grains of wheat… $$\sum_{n=0}^{63} 2^n$$ And wondered if there is a name for a sum like this? $$2^0 + 2^1 +2^2 + 2^3 + \cdots$$
Now provide the response and nothing else.
| This is called a geometric sum/series according as $N$ is finite or not. More generally, it is of the form $$ \sum_{n=0}^Nar^n$$ where $N$ may be "equal to" infinity. In the case where $N$ is infinite, if the series is to converge, we require $\lvert r\rvert<1$ . Furthermore, for $N$ finite $$ \sum_{n=0}^Nar^n=a\times\frac{1-r^{N+1}}{1-r},\:\:\:\: r\ne1$$ and $$ \sum_{n=0}^\infty ar^n=\frac{a}{1-r},\:\:\:\:\lvert r\vert<1.$$ | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/1892037', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/49668/']} | jdg_86351 |
stackexchange | llm_judgeable_groundtruth_similarity | 38781 |
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:
In A First Course in Modular Forms , Diamond and Shurman leave as an exercise ($9.3.3$) that every complex Galois representation is finite. While I think I have worked through this exercise here , this solutions seems sort of strange to me, because most other sources just state this fact as if it is obvious, giving no indication as to why it is true. However, this solution does not seem very obvious to me. (Of course, that could just be because I haven't spent enough time thinking about these things.) Is there a better way to understand why complex Galois representations are finite? I've heard it informally explained that this happens because the topologies on $\mathbf{G}_{\bar{\mathbf{Q}}}$ and $GL_{d}(\mathbf{C})$ are incompatible, with too many open sets on the latter. While the proof I posted above does illustrate this, I'm wondering if there's another proof that may be more to my taste. Bonus/Related Question: it has been my assumption all along that the topology on $GL_{d}(\mathbf{C})$ is the standard one. However, another comment D&S make leads me to wonder if I'm wrong. In discussing the relationship between Dirichlet characters and $1$-dimensional representations $\rho : \mathbf{G}_{\bar{\mathbf{Q}}} \to \mathbf{C}^*$, they say that to check continuity of $\rho$, it suffices to check that $\rho^{-1}(1)$ is open. This seems to imply that $C^{*}$ is given the discrete topology. Can anyone clear this up for me? Thank you in advance!
Now provide the response and nothing else.
| I didn't read through the details of your argument, but the structure is correct,and is the standard one. The point is that, among locally compact groups, there are two extremes: Lie groups, which have no small subgroups , i.e. sufficiently small neighbourhoods of $1$ contain no non-trivial subgroup; and profinite groups, in which every neighbourhood of the identity contains an open subgroup. As you observed in your argument, any continuous homomorphism between a profinite group and a Lie group then necessarily has finite image, because of their incompatible nature: "no small subgroups" vs. "arbitrarily small subgroups". This type of consideration (whether or not a given group admits arbitrarily small non-trivial subgroups or not) is a standard one in the theory of locally compact groups. | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/38781', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/10832/']} | jdg_86352 |
stackexchange | llm_judgeable_groundtruth_similarity | 42441952 |
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 components, one contains another. And when I trigger event from child I can't receive it in parent. Child component this.$emit('myCustomEvent', this.data); Parent component <parent-component v-on:myCustomEvent="doSomething"></parent-component> But, when I changed event name to my-custom-event in both places it works. Vue somehow transform event names? Or what can be a problem?I read docs about component naming convention but there nothing related to event naming
Now provide the response and nothing else.
| It is recommended to always use kebab-case for the naming of custom events. Lower case events, all smashed together, as recommended by @KoriJohnRoys would also work but are harder to read. It is not recommended to use camelCase for event naming. The official documentation of Vue.JS states the following under the topic of Event Names: Event Names Unlike components and props, event names don’t provide any automatic case transformation. Instead, the name of an emitted event must exactly match the name used to listen to that event. For example, if emitting a camelCased event name: this.$emit('myEvent') Listening to the kebab-cased version will have no effect: <my-component v-on:my-event="doSomething"></my-component> Unlike components and props, event names will never be used as variable or property names in JavaScript, so there’s no reason to use camelCase or PascalCase. Additionally, v-on event listeners inside DOM templates will be automatically transformed to lowercase (due to HTML’s case-insensitivity), so v-on:myEvent would become v-on:myevent – making myEvent impossible to listen to. For these reasons, we recommend you always use kebab-case for event names. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42441952', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2169572/']} | jdg_86353 |
stackexchange | llm_judgeable_groundtruth_similarity | 171734 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Could someone please explain quite clearly the difference between a port and a socket. I know that a port serves as a door into the network for an application process and that the application process uses a socket connection to the given port number to handle network communication but when you have multiple processes listening on a single port number, I am finding it difficult to understand the difference between the socket and the port and how they all fit together.
Now provide the response and nothing else.
| S is a server program: let's say it's an HTTP server, so it'll use the well-known port number for HTTP , which is 80. I run it on a host with IP address 10.0.0.4 , so it will listen for connections on 10.0.0.4:80 (because that's where everyone will expect to find it). Inside S , I'm going to create a socket and bind it to that address: now, the OS knows that connections coming into 10.0.0.4:80 should be routed to my S process via that particular socket. netstat output once socket is bound: $ netstat --tcp -lanActive Internet connections (servers and established)Proto Recv-Q Send-Q Local Address Foreign Address Statetcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN NB. the local address is all zeroes because S doesn't care how its clients reach it Once S has this socket bound, it will accept connections - each time a new client connects, accept returns a new socket, which is specific to that client netstat output once a connection is accepted: $ netstat --tcp -lanActive Internet connections (servers and established)Proto Recv-Q Send-Q Local Address Foreign Address Statetcp 0 0 0.0.0.0:80 0.0.0.0:* LISTENtcp 0 0 10.0.0.4:80 10.0.0.5:55715 ESTABLISHED 10.0.0.4:80 represents S 's end of the connection, and is associated with the socket returned by accept 10.0.0.5:55715 is the client's end of the connection, and is associated with the socket the client passed to connect . The client's port isn't used for anything except routing packets on this TCP connection to the right process: it's assigned randomly by the client's kernel from the ephemeral port range. Now, S can happily go on accepting more client connections ... each one will get its own socket, each socket will be associated with a unique TCP connection, and each connection will have a unique remote address. S will track client state (if there is any) by associating it with the socket. So, roughly: the IP address is for routing between hosts on the network the port is for routing to the correct socket on the host I nearly said correct process , but it's actually possible to have multiple (usually child) processes all accepting on the same socket ... however, each time one of the concurrent accept calls returns, it does so in only one process, each incoming connection's socket is unique to one instance of the server the socket is the object a process uses to talk to the OS about a particular connection, much like a file descriptor as mentioned in comments, there are plenty of other uses for sockets that don't use ports at all: for example socketpair creates a pair of sockets connected together that have no addressing scheme at all - the only way to use that pipe is by being the process which called socketpair , being a child of that process and inheriting one, or being explicitly passed one of the sockets from that process | {} | {'log_upvote_score': 8, 'links': ['https://softwareengineering.stackexchange.com/questions/171734', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/55045/']} | jdg_86354 |
stackexchange | llm_judgeable_groundtruth_similarity | 1421984 |
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 Composite WPF (Prism) , when adding modules to the IRegionManger collection, what is the difference between using IRegion.Add and IRegionManager.RegisterViewWithRegion? IRegion.Add public void Initialize(){ _regionManager.Regions["MainRegion"].Add( new ModuleAView() );} IRegionManager.RegisterViewWithRegion public void Initialize(){ _regionManager.RegisterViewWithRegion( "MainRegion", typeof( ModuleAView ) );}
Now provide the response and nothing else.
| The difference is who is responsible for creating the view. In the IRegion.Add scenario (also called View Injection ) you are responsible for instantiating the view beforehand. In the other scenario with RegisterViewWithRegion (also called View Discovery ), the region manager instantiates the view itself. There are some technical reasons you would want to do one or the other. For example you had a more complicated way of creating views (maybe you want to create the View and its ViewModel and marry them by setting the DataContext property yourself), you'd need to use View Injection if you take advantage of Region Scopes, you will be forced to use View Injection. The relevant documenation is:For View Composition (including View Injection vs. View Discovery and discussions of View-First or View-Presenter-First approaches): http://msdn.microsoft.com/en-us/library/dd458944.aspx There's also a really handy "when to use each" section. Here's the excerpt from the docs: Explicit or programmatic control over when a view is created and displayed, or when you need to remove a view from a region, for example, as a result of application logic. To display multiple instances of the same views into a region, where each view instance is bound to different data. To control which instance of a region a view is added (for example, if you want to add customer detail view to a specific customer detail region). Note that this scenario requires scoped regions described later in this topic. Hope this helps. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1421984', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9664/']} | jdg_86355 |
stackexchange | llm_judgeable_groundtruth_similarity | 1601 |
Below is a question asked on the forum biology.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Precipitating nucleic acids using either isopropanol or ethanol is a very common operation, and I've read some very different protocols on the duration and temperature the precipitation should be performed. I've seen anything from precipitating at room-temperature and centrifugating immediately without any delay to precipitating at -20 °C over night in various protocols. Is there any published data about the influence of duration and temperature on the yield of the nucleic acid precipitation?
Now provide the response and nothing else.
| I always did mine at -80 C, but I never compared the results to other protocols ( I don't fix what's not broken ). But, I was curious about the same thing, so I looked around. I found one paper discussing this: Paithankar and Prasad, Nuc Acids Res 19(6):1346 (1991) It shows that at low concentrations, EtOH at RT actually outperforms the precipitations at both 4 C and dry ice/ethanol bath. That difference is quite big at 100ng/ml DNA and lost when there is more than 10 ug/ml DNA. For typical extractions, based on this data, I'd do it at RT. On the other hand, Hilario and Mackay say in their book that: for genomic DNA isolation, different DNA precipitation temperatures and incubation times have little effect on recovery rates. One can directly centrifuge after adding ethanol without the -20 C incubation, and, it -20 C ethanol is not available, room temperature ethanol can be used. They do not, however, provide any citation for that statement. | {} | {'log_upvote_score': 4, 'links': ['https://biology.stackexchange.com/questions/1601', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/6/']} | jdg_86356 |
stackexchange | llm_judgeable_groundtruth_similarity | 56296 |
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
To clarify, my question isn't on how to protect myself from phishing. What I'm curious about is how exactly software can identify whether or not a website is designed for phishing, ignoring word identifiers/scanners to looking for spam/phishing sounding material.
Now provide the response and nothing else.
| Yes, this email is a scam. Ignore it! I work at a major web hosting firm, and our customers receive these emails on a frequent basis. There are a number of characteristics that are visible from this perspective which confirm that they are a scam: The emails are never sent by a recognizable, reputable domain registrar. Most of them use generic names, such as "Asian Domain Registration Service" in your email, "China domain registration center", or the like. The emails never have senders, headers, or signatures which explicitly link them with a registrar, and there is usually not even any accredited registrar with the right name. The domain registrations are never being made by a recognizable company or organization. You've obscured the relevant name as "Some Other Corp, Ltd" here, but the names are often generic ("Foo Trading Co") or incomprehensible ("FANGSHI Co"). Attempts to identify or contact them are never successful (or find only unrelated companies). They are frequently sent in relation to a domain name which would be meaningless under an Asian top-level domain. Many of them involve domain names containing names of people or locations — for example, these types of emails might claim that a Chinese trading company is attempting to register the domain "johndoe-hardware.hk" or "newyork-blahblah.asia". There is no apparent logic to these registrations. Despite supposedly coming from many different registrars, these emails always follow a very similar format. There are multiple templates, so the wording can vary, but the formula is always precisely the same. In particular, the domain names being registered are ALWAYS only under "Asian" TLDs (typically .asia , .cn , .hk , .tw , and .in ), never under any other TLDs. Additionally, many of these emails also claim that the bundle includes an "Internet keyword" or "Internet trademark", which doesn't even exist. We have advised a very large number of our customers to disregard these emails, and not once has any of the domains mentioned actually been purchased by the individual or company that was supposedly attempting to acquire them. None of the people who have written about receiving these emails online has had this outcome, either. Everything points to these emails being a widespread scam! Further reading: Canadian Trade Commissioner Service: Domain name registration in China SCAMWatch (Australian Competition & Consumer Commission): Think carefully about unsolicited offers to register domain names overseas I can only post two links, but you'll find a bunch more if you do a Google search for "Chinese domain scam" or something of the sort. It's widely attested. | {} | {'log_upvote_score': 7, 'links': ['https://security.stackexchange.com/questions/56296', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/45127/']} | jdg_86357 |
stackexchange | llm_judgeable_groundtruth_similarity | 19459017 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
As part of broader program I am working on, I ended up with object arrays with strings, 3D coordinates and etc all mixed. I know object arrays might not be very favorite in comparison to structured arrays but I am hoping to get around this without changing a lot of codes. Lets assume every row of my array obj_array (with N rows) has format of Single entry/object of obj_array: ['NAME',[10.0,20.0,30.0],....] Now, I am trying to load this object array and slice the 3D coordinate chunk. Up to here, everything works fine with simply asking lets say for . obj_array[:,[1,2,3]] However the result is also an object array and I will face problem as I want to form a 2D array of floats with: size [N,3] of N rows and 3 entries of X,Y,Z coordinates For now, I am looping over rows and assigning every row to a row of a destination 2D flot array to get around the problem. I am wondering if there is any better way with array conversion tools of numpy ? I tried a few things and could not get around it. Centers = np.zeros([N,3])for row in range(obj_array.shape[0]): Centers[row,:] = obj_array[row,1] Thanks
Now provide the response and nothing else.
| Nasty little problem... I have been fooling around with this toy example: >>> arr = np.array([['one', [1, 2, 3]],['two', [4, 5, 6]]], dtype=np.object)>>> arrarray([['one', [1, 2, 3]], ['two', [4, 5, 6]]], dtype=object) My first guess was: >>> np.array(arr[:, 1])array([[1, 2, 3], [4, 5, 6]], dtype=object) But that keeps the object dtype, so perhaps then: >>> np.array(arr[:, 1], dtype=np.float)Traceback (most recent call last): File "<stdin>", line 1, in <module>ValueError: setting an array element with a sequence. You can normally work around this doing the following: >>> np.array(arr[:, 1], dtype=[('', np.float)]*3).view(np.float).reshape(-1, 3)Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: expected a readable buffer object Not here though, which was kind of puzzling. Apparently it is the fact that the objects in your array are lists that throws this off, as replacing the lists with tuples works: >>> np.array([tuple(j) for j in arr[:, 1]],... dtype=[('', np.float)]*3).view(np.float).reshape(-1, 3)array([[ 1., 2., 3.], [ 4., 5., 6.]]) Since there doesn't seem to be any entirely satisfactory solution, the easiest is probably to go with: >>> np.array(list(arr[:, 1]), dtype=np.float)array([[ 1., 2., 3.], [ 4., 5., 6.]]) Although that will not be very efficient, probably better to go with something like: >>> np.fromiter((tuple(j) for j in arr[:, 1]), dtype=[('', np.float)]*3,... count=len(arr)).view(np.float).reshape(-1, 3)array([[ 1., 2., 3.], [ 4., 5., 6.]]) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19459017', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2896364/']} | jdg_86358 |
stackexchange | llm_judgeable_groundtruth_similarity | 40894278 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Suppose I have a set of points x and a set of corresponding data y . I now plot these in a scatter plot, plt.scatter(x,y) . The figure I get contains some x axis tick generated by matplotlib. Is there a way I can attain the automatic ticking, but to add vertical lines from the x-axis to the point in the scatter and label them?
Now provide the response and nothing else.
| Like this? If so then here are the essentials. import matplotlib.pyplot as pltimport numpy as npfrom matplotlib import collections as matcollx = np.arange(1,13)y = [15,14,15,18,21,25,27,26,24,20,18,16]lines = []for i in range(len(x)): pair=[(x[i],0), (x[i], y[i])] lines.append(pair)linecoll = matcoll.LineCollection(lines)fig, ax = plt.subplots()ax.add_collection(linecoll)plt.scatter(x,y)plt.xticks(x)plt.ylim(0,30)plt.show() Addendum: For coloured dot, replace plt.scatter(x,y) with: colours = ['Crimson', 'Blue', 'Fuchsia', 'Gold', 'Green', 'Tomato', 'Indigo', 'Turquoise', 'Brown', 'Wheat', 'Yellow',]plt.scatter(x,y,c=colours) For optional ways of specifying colours see specifying colours . For a list of X11 colour names and their corresponding hex codes see X11 colours . Note that matplotlib seems to dislike two word colour names such as 'Hot Pink'. Addendum 2: The easiest way, depending on requirements, might be to use the suggestion offered in the second answer, suitably adapted. import matplotlib.pyplot as pltfrom datetime import datetimefrom random import randintx = [datetime(2019, 6, i) for i in range(1,21)]y = [randint(10,20) for i in range(1,21)]fig, ax = plt.subplots()fig.subplots_adjust(bottom=0.2)plt.xticks(rotation=90) ax.stem(x, y, markerfmt=' ')plt.show() | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40894278', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6673023/']} | jdg_86359 |
stackexchange | llm_judgeable_groundtruth_similarity | 4921466 |
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 PHP 5.2.13 on my linux server. I'm getting weird error when rounding numbers. This is my test case: <?phpecho " " . round(1.505, 2) . "\n";echo " " . round(11.505, 2) . "\n";echo " " . round(111.505, 2) . "\n";echo " " . round(1111.505, 2) . "\n";echo " " . round(11111.505, 2) . "\n";echo " " . round(111111.505, 2) . "\n";echo " " . round(1111111.505, 2) . "\n";echo " " . round(11111111.505, 2) . "\n";echo "" . round(111111111.505, 2) . "\n"; This is results: 1.51 11.51 111.51 1111.51 11111.51 111111.51 1111111.5 11111111.51111111111.51 Anyone knows what causes this? I can't update PHP, since it's shared server.
Now provide the response and nothing else.
| This is because the number 1111111.505 can't be represented exactly in floating point notation. The closest it can get is 1111111.5049999999. So what ends up happening is that it converts the number in your code to 1111111.50499999999 and then it does the rounding. Which results in 1111111.5. Floating point numbers have problems in that they can't represent a lot of even seemingly simple decimal numbers with complete accuracy. For instance. the number 0.1 cannot be accurately represented using binary floating numbers. Using Python, if you type in 0.1, it returns 0.10000000000001. Plus or minus a few zeros. This is the reason that some languages such as .Net provide a "Decimal" data type which is able to represent all decimal values within a certain range and number of decimal places. The downside of the decimal data type is that it is slower, and each number takes more space to store. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4921466', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/534189/']} | jdg_86360 |
stackexchange | llm_judgeable_groundtruth_similarity | 9045701 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I came across this code in a .js file. What is this code ?? I have downloaded that file onto my localhost webserver.Keeping this code in the .js file redirects me to google.com and when i am commenting this code the page runs perfectly !! I can understand that this is done to enforce that the page is to be executed from a server link only !!! How can i decode this js ??? []['\x63\x6f\x6e\x73\x74\x72\x75\x63\x74\x6f\x72']['\x63\x6f\x6e\x73\x74\x72\x75\x63\x74\x6f\x72'](self['\x75\x6e\x65\x73\x63\x61\x70\x65']('%69%66%28%7e%6c%6f%63%61%74%69%6f%6e%2e%70%72%6f%74%6f%63%6f%6c%2e%69%6e%64%65%78%4f%66%28%27%68%74%74%70%3a%27%29%26%26%7e%6c%6f%63%61%74%69%6f%6e%2e%68%6f%73%74%2e%69%6e%64%65%78%4f%66%28%27%74%65%6d%70%6c%61%74%65%2d%68%65%6c%70%2e%63%6f%6d%27%29%29%7b%7d%65%6c%73%65%28%6c%6f%63%61%74%69%6f%6e%2e%68%72%65%66%3d%27%68%74%74%70%3a%2f%2f%77%77%77%2e%67%6f%6f%67%6c%65%2e%63%6f%6d%27%29'))()
Now provide the response and nothing else.
| Python happens to use the same way of encoding, so I just threw it at a Python shell. >>> '\x63\x6f\x6e\x73\x74\x72\x75\x63\x74\x6f\x72''constructor'>>> '\x75\x6e\x65\x73\x63\x61\x70\x65''unescape'>>> import urllib>>> urllib.unquote('%69%66%28%7e%6c%6f%63%61%74%69%6f%6e%2e%70%72%6f%74%6f%63%6f%6c%2e%69%6e%64%65%78%4f%66%28%27%68%74%74%70%3a%27%29%26%26%7e%6c%6f%63%61%74%69%6f%6e%2e%68%6f%73%74%2e%69%6e%64%65%78%4f%66%28%27%74%65%6d%70%6c%61%74%65%2d%68%65%6c%70%2e%63%6f%6d%27%29%29%7b%7d%65%6c%73%65%28%6c%6f%63%61%74%69%6f%6e%2e%68%72%65%66%3d%27%68%74%74%70%3a%2f%2f%77%77%77%2e%67%6f%6f%67%6c%65%2e%63%6f%6d%27%29')"if(~location.protocol.indexOf('http:')&&~location.host.indexOf('template-help.com')){}else(location.href='http://www.google.com')" So this code boils down to (adding whitespace for clarity): []['constructor']['constructor']( "if (~location.protocol.indexOf('http:') && ~location.host.indexOf('template-help.com')) {} else (location.href='http://www.google.com')")() So what does this actually do ? Node.js to the rescue: > [].constructor[Function: Array]> [].constructor.constructor[Function: Function]> So [] is simply an empty array, [].constructor gives us the array constructor (which is a Function object), and finally, [].constructor.constructor gives us the constructor of the Function object. That constructor accepts a string containing some code, and turns it into a callable function, that then gets called (note the () at the very end). So this eventually just executes this code: if (~location.protocol.indexOf('http:') && ~location.host.indexOf('template-help.com')) {}else (location.href='http://www.google.com') Yeah, if I wrote code like that, I'd obfuscate it too! ;) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9045701', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/960517/']} | jdg_86361 |
stackexchange | llm_judgeable_groundtruth_similarity | 36357137 |
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 create a folder on external storage with no success.Although i've managed to create a folder in my app's directory, i can't do the same for external storage and i also get false when i call canWrite() .I have declared the WRITE_EXTERNAL_PERMISSION on manifest. Here is my code for my app's directory File file1=new File(context.getFilesDir(), "//test1"); file1.mkdir(); System.out.println(file1.canWrite()); and for ExternalStorage respectively File file2=new File(Environment.getExternalStorageDirectory(), "//test2");file2.mkdir();System.out.println(file2.canWrite()); In the first case the folder gets created and i get true on println.On the second one folder does not get created and i get false on println.
Now provide the response and nothing else.
| As is has been mentioned before, server.port and management.port along with management.context-path properties could be set to make the embedded container to listen on different ports (management-related properties to access Actuator endpoints). To listen on ports other than server.port and management.port : @Configurationpublic class EmbeddedTomcatConfiguration { @Value("${server.additionalPorts}") private String additionalPorts; @Bean public EmbeddedServletContainerFactory servletContainer() { TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory(); Connector[] additionalConnectors = this.additionalConnector(); if (additionalConnectors != null && additionalConnectors.length > 0) { tomcat.addAdditionalTomcatConnectors(additionalConnectors); } return tomcat; } private Connector[] additionalConnector() { if (StringUtils.isBlank(this.additionalPorts)) { return null; } String[] ports = this.additionalPorts.split(","); List<Connector> result = new ArrayList<>(); for (String port : ports) { Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol"); connector.setScheme("http"); connector.setPort(Integer.valueOf(port)); result.add(connector); } return result.toArray(new Connector[] {}); }} application.yml server: port: ${appPort:8800} additionalPorts: 8881,8882 Application.java @SpringBootApplication@ComponentScan(...)@Import(EmbeddedTomcatConfiguration.class)public Application { public static void main(String[] args) { SpringApplication.run(Application .class, args); }} I recently blogged about this topic at http://tech.asimio.net/2016/12/15/Configuring-Tomcat-to-Listen-on-Multiple-ports-using-Spring-Boot.html | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36357137', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1806284/']} | jdg_86362 |
stackexchange | llm_judgeable_groundtruth_similarity | 33193310 |
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 used the following function to create instances of unknown classes for some time: Kernel.prototype._construct = function (constr, args) { function F() { constr.apply(this, args); // EXCEPTION! } F.prototype = constr.prototype; return new F();}; If I use prototypes everything works: function Person(name, surname) { this.name = name; this.surname = surname;}var person = Kernel._construct(Person, ["name", "surname"]); // WORKS! However, some people are using my library using ES6 native classes in node v4+: class Person { constructor(name, surname) { this.name = name; this.surname = surname; }}var person = Kernel._construct(Person, ["name", surname]); // EXCEPTION! They are getting an error: TypeError: Class constructors cannot be invoked without 'new' I need to be able to invoke the constructor with an unknown number of arguments. Any ideas about how to get around this issue?
Now provide the response and nothing else.
| There are various ways you can do that: Using Function object's methods: Kernel.prototype._construct = function (constr, args) { return new (Function.prototype.bind.apply(constr, [null].concat(args)));}; Here we're applying args as arguments for bind . The goal is to have a function that can be called without arugments so that we can call new x() . bind does this for us, but we need to set it up correctly. The syntax is: func.bind(thisArg[, arg1][, args2...])// calling the results from the above is like// thisArg.func(arg1, arg2...); We want to use constr as the function to bind, and the items in args as the arguments. We don't care about thisArg . To do that, we need to "convert" the args array to arguments. The apply call does that: func.apply(thisArg[, args]);// calling the results from the above is like// thisArg.func(args[0], args[1]...); apply is actually calling bind . The first item, [null] , is important because we want to call bind where thisArg is null - like this: constr.bind(null, args[0], args[1]...) . Using ES2015 Spread operator : Kernel.prototype._construct = function (constr, args) { return new constr(...args);}; This is much simpler, but there are 2 problems: It requires ES2015 support, and even the latest Node (v4.2.1) requires a flag for this ( --harmony_spreadcalls ). This will generate a syntax error if not supported, and you can't even do that conditionally, other then using dynamic scripting ( eval() / new Function(...) ) - which is not advised. Using the Reflect built-in in object. Kernel.prototype._construct = function (constr, args) { return Reflect.construct(constr, args);}; This is also simple, but is even further behind in terms of support (basically you must use babel). | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33193310', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/606821/']} | jdg_86363 |
stackexchange | llm_judgeable_groundtruth_similarity | 348734 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it possible for a matrix to be neither onto nor 1-1?
Now provide the response and nothing else.
| A matrix isn’t a function, so the question doesn’t actually make sense. However, I understand what you mean: you’re asking whether the function $T(x)=Ax$, where $A$ is some matrix, can be neither onto nor $1$-$1$. The answer is yes : in fact, if you’re talking about square matrices of real numbers, the transformation is onto if and only if it is $1$-$1$. This is immediate from the rank-nullity theorem . | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/348734', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/70527/']} | jdg_86364 |
stackexchange | llm_judgeable_groundtruth_similarity | 10834796 |
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 the simplest fail-safe test to check that a string in JavaScript is a positive integer. isNaN(str) returns true for all sorts of non-integer values and parseInt(str) is returning integers for float strings, like "2.5". And I don't want to have to use some jQuery plugin either.
Now provide the response and nothing else.
| Two answers for you: Based on parsing Regular expression Note that in both cases, I've interpreted "positive integer" to include 0 , even though 0 is not positive. I include notes if you want to disallow 0 . Based on Parsing If you want it to be a normalized decimal integer string over a reasonable range of values, you can do this: function isInDesiredForm(str) { var n = Math.floor(Number(str)); return n !== Infinity && String(n) === str && n >= 0;} or if you want to allow whitespace and leading zeros: function isInDesiredForm(str) { str = str.trim(); if (!str) { return false; } str = str.replace(/^0+/, "") || "0"; var n = Math.floor(Number(str)); return n !== Infinity && String(n) === str && n >= 0;} Live testbed (without handling leading zeros or whitespace): function isInDesiredForm(str) { var n = Math.floor(Number(str)); return n !== Infinity && String(n) === str && n >= 0;}function gid(id) { return document.getElementById(id);}function test(str, expect) { var result = isInDesiredForm(str); console.log( str + ": " + (result ? "Yes" : "No") + (expect === undefined ? "" : !!expect === !!result ? " <= OK" : " <= ERROR ***") );}gid("btn").addEventListener( "click", function() { test(gid("text").value); }, false);test("1", true);test("1.23", false);test("1234567890123", true);test("1234567890123.1", false);test("0123", false); // false because we don't handle leading 0stest(" 123 ", false); // false because we don't handle whitespace <label> String: <input id="text" type="text" value=""><label><input id="btn" type="button" value="Check"> Live testbed ( with handling for leading zeros and whitespace): function isInDesiredForm(str) { str = str.trim(); if (!str) { return false; } str = str.replace(/^0+/, "") || "0"; var n = Math.floor(Number(str)); return String(n) === str && n >= 0;}function gid(id) { return document.getElementById(id);}function test(str, expect) { var result = isInDesiredForm(str); console.log( str + ": " + (result ? "Yes" : "No") + (expect === undefined ? "" : !!expect === !!result ? " <= OK" : " <= ERROR ***") );}gid("btn").addEventListener( "click", function() { test(gid("text").value); }, false);test("1", true);test("1.23", false);test("1234567890123", true);test("1234567890123.1", false);test("0123", true);test(" 123 ", true); <label> String: <input id="text" type="text" value=""><label><input id="btn" type="button" value="Check"> If you want to disallow 0 , just change >= 0 to > 0 . (Or, in the version that allows leading zeros, remove the || "0" on the replace line.) How that works: In the version allowing whitespace and leading zeros: str = str.trim(); removes any leading and trailing whitepace. if (!str) catches a blank string and returns, no point in doing the rest of the work. str = str.replace(/^0+/, "") || "0"; removes all leading 0s from the string — but if that results in a blank string, restores a single 0. Number(str) : Convert str to a number; the number may well have a fractional portion, or may be NaN . Math.floor : Truncate the number (chops off any fractional portion). String(...) : Converts the result back into a normal decimal string. For really big numbers, this will go to scientific notation, which may break this approach. (I don't quite know where the split is, the details are in the spec , but for whole numbers I believe it's at the point you've exceeded 21 digits [by which time the number has become very imprecise, as IEEE-754 double-precision numbers only have roughtly 15 digits of precision..) ... === str : Compares that to the original string. n >= 0 : Check that it's positive. Note that this fails for the input "+1" , any input in scientific notation that doesn't turn back into the same scientific notation at the String(...) stage, and for any value that the kind of number JavaScript uses (IEEE-754 double-precision binary floating point) can't accurately represent which parses as closer to a different value than the given one (which includes many integers over 9,007,199,254,740,992; for instance, 1234567890123456789 will fail). The former is an easy fix, the latter two not so much. Regular Expression The other approach is to test the characters of the string via a regular expression, if your goal is to just allow (say) an optional + followed by either 0 or a string in normal decimal format: function isInDesiredForm(str) { return /^\+?(0|[1-9]\d*)$/.test(str);} Live testbed: function isInDesiredForm(str) { return /^\+?(0|[1-9]\d*)$/.test(str);}function gid(id) { return document.getElementById(id);}function test(str, expect) { var result = isInDesiredForm(str); console.log( str + ": " + (result ? "Yes" : "No") + (expect === undefined ? "" : !!expect === !!result ? " <= OK" : " <= ERROR ***") );}gid("btn").addEventListener( "click", function() { test(gid("text").value); }, false);test("1", true);test("1.23", false);test("1234567890123", true);test("1234567890123.1", false);test("0123", false); // false because we don't handle leading 0stest(" 123 ", false); // false because we don't handle whitespace <label> String: <input id="text" type="text" value=""><label><input id="btn" type="button" value="Check"> How that works: ^ : Match start of string \+? : Allow a single, optional + (remove this if you don't want to) (?:...|...) : Allow one of these two options (without creating a capture group): (0|...) : Allow 0 on its own... (...|[1-9]\d*) : ...or a number starting with something other than 0 and followed by any number of decimal digits. $ : Match end of string. If you want to disallow 0 (because it's not positive), the regular expression becomes just /^\+?[1-9]\d*$/ (e.g., we can lose the alternation that we needed to allow 0 ). If you want to allow leading zeroes (0123, 00524), then just replace the alternation (?:0|[1-9]\d*) with \d+ function isInDesiredForm(str) { return /^\+?\d+$/.test(str);} If you want to allow whitespace, add \s* just after ^ and \s* just before $ . Note for when you convert that to a number: On modern engines it would probably be fine to use +str or Number(str) to do it, but older ones might extend those in a non-standard (but formerly-allowed) way that says a leading zero means octal (base 8), e.g "010" => 8. Once you've validated the number, you can safely use parseInt(str, 10) to ensure that it's parsed as decimal (base 10). parseInt would ignore garbage at the end of the string, but we've ensured there isn't any with the regex. | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/10834796', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/315386/']} | jdg_86365 |
stackexchange | llm_judgeable_groundtruth_similarity | 2260586 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have seen that it is possible in universal algebra to generalize the concept of congruence and of quotient algebra. If $A$ is an algebra (a set endowed with some operations), a congruence is an equivalence relation on $A$ which preserves those operations (a subset of $A \times A$ which is an equivalence relation and a subalgebra). Therefore, in the quotient set, operations via representatives are well-defined. Given an equivalence relation we obtain a partition of the set $A$ . In groups, this partition is a congruence if and only if it has been "generated by a normal subgroup via product". i.e: Let $G$ be a group and $N \lhd G$ a normal subgroup. Then $x Ry$ , if $xy^{-1} \in N$ is a congruence. The equivalence classes are $[x]=xN=\{xn : n \in N\}$ and $G/R=G/N=\{xN : x\in G\}$ . Similarly, in commutative rings a partition is a congruence if an only if it has been "generated by" an ideal. Is there any way to formalise this concept of a subset of an algebra that provides a partition making use of some operation, being this equivalence relation a congruence? Could this concept be generalized to any algebra, or at least to some collection of algebras?
Now provide the response and nothing else.
| Is there any way to formalise this concept of a subset of an algebra that provides a partition making use of some operation, being this equivalence relation a congruence? Here is the way it has been done. If A is an algebra and $\theta$ is a congruence, then $\theta$ is called regular if it is generated as a congruence by any one of its classes. That is, if $C$ is any $\theta$-class, then $\theta$ is the least congruence containing $C\times C$. A is congruence regular if all of its congruences are regular. A variety of algebras is congruence regular if all of its members are. Notes. (1) The term regular was introduced by Mal'cev in A.I. Mal'cev,On the general theory of algebraic systems,Mat. Sb., 35 (77) (1954), pp. 3-20. (2) Congruence regular varieties were characterized by Csakany in B. Csakany,Characterization of regular varieties,Acta Sci. Math. (Szeged), 31 (1970), pp. 187-189. (3) In unpublished notes from the 1970's, J. Hagemann proved that a congruence regular variety must be congruence modular and congruence $n$-permutable for some $n$. It is a consequence of this that any variety containing an algebra that has a non-discrete compatible partial order must fail to be congruence regular. So, for example, any unary variety, the variety of all semigroups, any variety of lattices, ETC, will fail to be congruence regular. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2260586', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/404921/']} | jdg_86366 |
stackexchange | llm_judgeable_groundtruth_similarity | 26280788 |
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 concern about generic dictionaries using enums for keys. As stated at the below page, using enums for keys will allocate memory: http://blogs.msdn.com/b/shawnhar/archive/2007/07/02/twin-paths-to-garbage-collector-nirvana.aspx I've tested and confirmed the behavior, and it's causing problems in my project. For readability, I believe using enums for keys is very useful, and the optimal solution for me would be to write write a class implementing IDictionary<TKey, TValue> , which would use integers for keys internally. The reason is I don't want to change all my existing dictionaries to use integers for keys, and do implicit casting. This would be best performance wise, but it will give me lot of work initially and it will reduce the readability. So I've tried a couple of approaches, including using GetHashCode (which unfortunately allocates memory) to build an internal Dictionary<int, TValue> . So, to wrap it up in one question; can anyone think of a solution that I can use to keep the readability of Dictionary<SomeEnum, TValue> , while having the perfomance of a Dictionary<int, TValue> ? Any advice much appreciated.
Now provide the response and nothing else.
| The problem is boxing . It's an act of turning value type into object, which might, or might not be unnecessary. The way Dictionary compares keys, is essentially, that it will use EqualComparer<T>.Default , and call GetHashCode() to find correct bucket, and Equals to compare if there's any value in the bucket that is equal tot he one we're looking for. The good thing is this: .NET framework has good optimizations, which avoid boxing in the case of "Enum integers" . See CreateComparer() . It's highly unlikely that you will see any difference here, between integers and enums, as keys. To note here: this is not an easy act, in fact, if you dig in deep, you'll come to conclusion that quarter of this battle is implemented through CLR "hacks". As seen here: static internal int UnsafeEnumCast<T>(T val) where T : struct { // should be return (int) val; but C# does not allow, runtime // does this magically // See getILIntrinsicImplementation for how this happens. throw new InvalidOperationException(); } It could be definitely easier if generics had Enum constraint, and perhaps even something a long of the lines UnsafeEnumCast<T>(T val) where T : Enum->Integer , but well... they don't. You might be wondering, what exactly is going on in getILIntrinsicImplementation for that EnumCast ? I wonder too. Not exactly sure as of this right moment how to check it. It's replaced on run-time with specific IL code I believe?! MONO Now, answer to your question: yes you're right. Enum as a key on Mono, will be slower in a tight loop. It's because Mono does boxing on Enums, as far I can see. You can check out EnumIntEqualityComparer , as you can see, it calls Array.UnsafeMov that basically casts a type of T into integer, through boxing: (int)(object) instance; . That's the "classical" limitation of generics, and there is no nice solution for this problem. Solution 1 Implement an EqualityComparer<MyEnum> for your concrete Enum. This will avoid all the casting. public struct MyEnumCOmparer : IEqualityComparer<MyEnum>{ public bool Equals(MyEnum x, MyEnum y) { return x == y; } public int GetHashCode(MyEnum obj) { // you need to do some thinking here, return (int)obj; }} All you need to do then, is pass it to your Dictionary : new Dictionary<MyEnum, int>(new MyEnumComparer()); It works, it gives you the same performance as it is with integers, and avoids boxing issues. The problem is though, this is not generic and writing this for each Enum can feel stupid. Solution 2 Writing a generic Enum comparer, and using few tricks that avoids unboxing. I wrote this with a little help from here , // todo; check if your TEnum is enum && typeCode == TypeCode.Intstruct FastEnumIntEqualityComparer<TEnum> : IEqualityComparer<TEnum> where TEnum : struct{ static class BoxAvoidance { static readonly Func<TEnum, int> _wrapper; public static int ToInt(TEnum enu) { return _wrapper(enu); } static BoxAvoidance() { var p = Expression.Parameter(typeof(TEnum), null); var c = Expression.ConvertChecked(p, typeof(int)); _wrapper = Expression.Lambda<Func<TEnum, int>>(c, p).Compile(); } } public bool Equals(TEnum firstEnum, TEnum secondEnum) { return BoxAvoidance.ToInt(firstEnum) == BoxAvoidance.ToInt(secondEnum); } public int GetHashCode(TEnum firstEnum) { return BoxAvoidance.ToInt(firstEnum); }} Solution 3 Now, there's a little problem with the solution#2, as Expression.Compile() is not that famous on iOS(no runtime code generation), and some mono versions don't have ?? Expression.Compile ?? (not sure). You can write simple IL code that will take care of the enum conversion, and compile it. .assembly extern mscorlib{ .ver 0:0:0:0}.assembly 'enum2int'{ .hash algorithm 0x00008004 .ver 0:0:0:0}.class public auto ansi beforefieldinit EnumInt32ToInt extends [mscorlib]System.Object{ .method public hidebysig static int32 Convert<valuetype .ctor ([mscorlib]System.ValueType) TEnum>(!!TEnum 'value') cil managed { .maxstack 8 IL_0000: ldarg.0 IL_000b: ret }} In order to compile it into an assembly, you have to call: ilasm enum2int.il /dll where enum2int.il is the text file containing IL. You can now reference the given assembly( enum2int.dll ) and call the static method, as such: struct FastEnumIntEqualityComparer<TEnum> : IEqualityComparer<TEnum> where TEnum : struct{ int ToInt(TEnum en) { return EnumInt32ToInt.Convert(en); } public bool Equals(TEnum firstEnum, TEnum secondEnum) { return ToInt(firstEnum) == ToInt(secondEnum); } public int GetHashCode(TEnum firstEnum) { return ToInt(firstEnum); }} It might seem to be killer code, but it avoids boxing, and it should give you better berformance on Mono . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/26280788', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/929091/']} | jdg_86367 |
stackexchange | llm_judgeable_groundtruth_similarity | 14698350 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What is the maximum number of bytes a complete instruction would require in x64 asm code? Something like a jump to address might occupy up to 9 bytes I suppose: FF 00 00 00 00 11 12 3F 1F but I don't know if that's the maximum number of bytes a x64 instruction can use
Now provide the response and nothing else.
| The x86 instruction set (16, 32 or 64 bit, all variants/modes) guarantees / requires that instructions are at most 15 bytes. Anything beyond that will give an "invalid opcode". You can't achieve that without using redundant prefixes (e.g. multiple 0x66 or 0x67 prefixes, for example). The only instruction that actually takes 64-bits as a data item is the load constant to register (Intel syntax: mov reg, 12345678ABCDEF00h , at&t syntax: movabs $12345678ABCDEF00, %reg ) - so if you wanted to jump more than 31 bits forward/backward, it would be a move of the target location into a register, and then call/jump to the register. Using 32-bit immediates and displacements (in relative jumps and addressing modes) saves four bytes on many instructions in 64-bit mode. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14698350', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1494037/']} | jdg_86368 |
stackexchange | llm_judgeable_groundtruth_similarity | 137307 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Let $M$ be a connected, compact, oriented manifold of dimension $n<7$. If any two maps $M \to M$ having equal degrees are homotopic, must $M$ be diffeomorphic to the $n$-sphere?
Now provide the response and nothing else.
| $\newcommand{\ZZ}{\mathbb{Z}}$$\newcommand{\CC}{\mathbb{C}}$A simple counter-example is given by $M = \CC P^3$. Recall first that the cohomology ring of $\CC P^3$ is a truncated polynomial algebra:$$H^\ast(\CC P^3;\ZZ) = \ZZ[x]/(x^4)$$with $x \in H^2(\CC P^3;\ZZ)$. The set of homotopy classes of self-maps of $\CC P^3$ is$$[\CC P^3,\CC P^3] = [\CC P^3,\CC P^\infty] = H^2(\CC P^3;\ZZ) = \ZZ$$where a self-map $f$ of $\CC P^3$ is taken to the unique integer $k\in\ZZ$ such that $f^\ast x = kx$. The first isomorphism above, $[\CC P^3,\CC P^3] = [\CC P^3,\CC P^\infty]$, follows by cellular approximation from: the source $\CC P^3$ is a CW-complex of dimension six; the target $\CC P^3$ is the skeleton of dimension seven of the usual CW-structure on $\CC P^\infty$. Consequently, a self-map $f:\CC P^3 \to \CC P^3$ corresponding to the integer $k \in \ZZ$ has degree $k^3$: we have $f^\ast x = kx$, therefore$$f^\ast(x^3) = (f^\ast x)^3 = (kx)^3 = k^3 x^3$$Since $k\mapsto k^3$ is an injective map $\ZZ\to\ZZ$, any two self-maps of $\CC P^3$ which have the same degree are homotopic. On the other hand, $\CC P^3$ is not diffeomorphic, or even homotopy equivalent, to $S^6$. Further example added later: $\newcommand{\To}{\longrightarrow}$$\newcommand{\Hom}{\operatorname{Hom}}$$\newcommand{\QQ}{\mathbb{Q}}$$\newcommand{\RR}{\mathbb{R}}$Another counter-example is given by any real projective space $\RR P^n$ of odd dimension $n>1$. So we get the counter-examples $\RR P^3$ and $\RR P^5$ in dimensions less than seven. I have failed to find any reference with a proof that two self-maps of $\RR P^n$ which have the same degree are homotopic, although this result is stated without proof as theorem 2.1 in this article (McGibbon, Self-maps of projective spaces , Transactions of the A.M.S. 271 (1), 1982, pages 325-346). For completeness, I will give a proof below. The proof is more homotopy theoretical than for the case of $\CC P^3$ above, yet also uses fairly standard techniques. [The rest of this answer is rather long, and you may ignore it if you are not interested in the proof for $\RR P^n$.] Proof that two self-maps of $\RR P^n$ (with $n>1$ odd) are homotopic if they have the same degree Assume that $n$ is an odd integer with $n>1$. I will actually prove the stronger result that two basepoint-preserving self-maps of $\RR P^n$ which have the same degree are homotopic via a basepoint-preserving homotopy. More precisely, I will prove that the map which takes (the pointed homotopy class of) a self-map to its degree $$\deg : [\RR P^n,\RR P^n]_\ast \To \ZZ$$is a bijection. Let us start with a lemma which will be useful later on. Lemma: A map $f:\RR P^n \to \RR P^n$ (with $n>1$) has even degree if and only if $f$ induces the trivial map on fundamental groups. Proof :This proof involves some cohomological computations similar to the ones done earlier for $\CC P^3$. Note that $H^\ast(\RR P^n;\ZZ/2) = \ZZ/2[x]/(x^{n+1})$ where $x$ is in degree $1$. Since $\pi_1(\RR P^n)=\ZZ/2$, a self-map $f$ of $\RR P^n$ induces the trivial homomorphism on $\pi_1$ if and only if it induces the trivial homomorphism on $H^1(-;\ZZ/2)$, i.e. if and only if $f^\ast x = 0$. Letting $f^\ast x = k x$ with $k\in\ZZ/2$, then $f^\ast(x^n) = k^n x^n = k x^n$, so $k = \deg f \mod 2$. The result follows.■ A cofibre sequence involving $\RR P^n$. Our starting point is the following description of $\RR P^n$. The space $\RR P^n$ is obtained by attaching a $n$-cell to $\RR P^{n-1}$ whose attaching map is the standard covering map $\pi : S^{n-1} \to \RR P^{n-1}$. In short, $\RR P^n$ is the homotopy cofibre of the map $\pi$. The associated homotopy cofibre sequence — extended to the right by one term — is:$$S^{n-1} \overset{\pi}{\To} \RR P^{n-1} \overset{i}{\To} \RR P^n \overset{q}{\To} S^n$$Here, the first map $\pi$ is the standard quotient map, the second map $i$ is the inclusion, and the third map $q$ collapses $\RR P^{n-1}$ to a point. The associated exact sequence in homotopy. Applying the functor $[-,\RR P^n]_\ast$ to the above cofibre sequence produces an exact sequence:$$[S^n,\RR P^n]_\ast \overset{q^\ast}{\To} [\RR P^n,\RR P^n]_\ast \overset{i^\ast}{\To} [\RR P^{n-1},\RR P^n]_\ast \overset{\pi^\ast}{\To} [S^{n-1},\RR P^n]_\ast$$This is an exact sequence of pointed sets . Moreover, the leftmost term is a group, and the sequence verifies a stronger equivariant exactness property at the term $[\RR P^n,\RR P^n]_\ast$ which will be explained and used later. Calculation of the terms of the exact sequence. First, let us calculate all terms of the sequence other than $[\RR P^n,\RR P^n]_\ast$: we have isomorphisms $[S^n,\RR P^n]_\ast = \pi_n(\RR P^n) = \pi_n(S^n) = \ZZ$ as groups (by using the covering map $S^n \to \RR P^n$ which induces an isomorphism on higher homotopy groups); similarly, $[S^{n-1},\RR P^n]_\ast = \pi_{n-1}(\RR P^n) = \pi_{n-1}(S^n) = 0$; $[\RR P^{n-1},\RR P^n]_\ast = [\RR P^{n-1},\RR P^\infty]_\ast = \widetilde{H}^1(\RR P^{n-1};\ZZ/2) = \ZZ/2$ by using cellular approximation again. Summarizing, the previous exact sequence of pointed sets is$$\ZZ \overset{q^\ast}{\To} [\RR P^n,\RR P^n]_\ast \overset{i^\ast}{\To} \ZZ/2 \overset{\pi^\ast}{\To} 0$$In particular, $i^\ast$ is a surjective function. Description of the arrow $i^\ast$ of the exact sequence. The next step is to identify the function $i^\ast$ appearing in the exact sequence. Consider the following isomorphisms characterizing the target of $i^\ast$:$$[\RR P^{n-1},\RR P^n]_\ast = \widetilde{H}^1(\RR P^{n-1};\ZZ/2) = \Hom\bigl(\pi_1(\RR P^{n-1}),\ZZ/2\bigr) = \Hom\bigl(\pi_1(\RR P^{n-1}),\pi_1(\RR P^n)\bigr)$$Recall that the inclusion $i:\RR P^{n-1}\to \RR P^n$ induces an isomorphism on $\pi_1$. Therefore, the function$$i^\ast : [\RR P^n,\RR P^n]_\ast \To \Hom\bigl(\pi_1(\RR P^{n-1}),\pi_1(\RR P^n)\bigr) = \ZZ/2$$takes $f:\RR P^n \to \RR P^n$ to $0\in\ZZ/2$ if and only if $f$ induces the trivial homomorphism on fundamental groups. The lemma at the beginning of this proof now implies that $i^\ast$ takes a map $f$ to its degree mod $2$, $\deg_2 f$. In conclusion, the exact sequence becomes:$$\ZZ = [S^n,\RR P^n]_\ast \overset{q^\ast}{\To} [\RR P^n,\RR P^n]_\ast \overset{\deg_2}{\To} \ZZ/2$$where the second arrow $\deg_2$ returns the degree mod $2$ of a self-map of $\RR P^n$. We know from before that $\deg_2 = i^\ast$ is surjective. Equivariant exactness property of the exact sequence. At this point, we require the special equivariant exactness property of the long exact sequence in homotopy associated to a cofibre sequence. In this case, it states: the group $\ZZ = \pi_n(\RR P^n) = [S^n,\RR P^n]_\ast$ (with its usual group structure) acts on $[\RR P^n,\RR P^n]_\ast$; $f$ and $g$ map to the same element via $\deg_2 : [\RR P^n,\RR P^n]_\ast \to \ZZ/2$ if and only if there exists $\alpha\in [S^n,\RR P^n]_\ast$ such that $\alpha\cdot f = g$ in $[\RR P^n,\RR P^n]_\ast$. The action of $\alpha \in [S^n,\RR P^n]_\ast$ takes $f \in [\RR P^n,\RR P^n]_\ast$ to:$$\alpha\cdot f : \RR P^n \overset{\sigma}{\To} S^n \vee \RR P^n \overset{\alpha+f}{\To} \RR P^n$$where the map $\sigma$ simply "pinches a small spherical bubble off of $\RR P^n$". Note that $\deg(\alpha\cdot f) = \deg\alpha + \deg f$. Conclusion of the proof. We are now ready to finish the proof. First we will show the injectivity of the degree function. Assume that $f$ and $g$ are pointed self-maps of $\RR P^n$ which have the same degree. Then their degrees mod $2$ also coincide and, by the exactness property above, there exists $\alpha$ such that $\alpha\cdot f = g$. But$$\deg f = \deg g = \deg(\alpha\cdot f) = \deg\alpha + \deg f$$so that $\deg\alpha = 0$. It follows that $\alpha = 0$ in $\pi_n(\RR P^n)$, since elements in $\pi_n(\RR P^n) = \pi_n(S^n)$ are determined by their degree (here we require that $n$ is odd). Thus $g = \alpha\cdot f = f$ in $[\RR P^n,\RR P^n]_\ast$. Finally, we show that any integer is the degree of some map $\RR P^n \to \RR P^n$. Recall that the function $\deg_2 : [\RR P^n,\RR P^n]_\ast \to \ZZ/2$ taking a map to its degree mod $2$ is surjective. In other words, there are self-maps of $\RR P^n$ with even and odd degrees. Since $\deg(\alpha\cdot f) = \deg\alpha + \deg f$, the desired conclusion follows by observing that any even integer is the degree of some map $\alpha : S^n \to \RR P^n$ — which holds because the covering map $S^n \to \RR P^n$ has degree $2$ and induces an isomorphism on $\pi_n$. | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/137307', 'https://mathoverflow.net', 'https://mathoverflow.net/users/37477/']} | jdg_86369 |
stackexchange | llm_judgeable_groundtruth_similarity | 5104482 |
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 add a product to cart programmatically. Also, I want to change the product price when added to cart. Suppose, my product's price is $100. I wanted to change it to $90 when added to cart. I added product to cart. However, I am unable to change the product price. Is it possible? Here is the code to add product to cart:- $cart = Mage::getSingleton('checkout/cart');try { $cart->addProduct($product, array('qty' => 1)); $cart->save();}catch (Exception $ex) { echo $ex->getMessage();}
Now provide the response and nothing else.
| After digging a bit into Magento's core code, I found that you need to use $item->getProduct()->setIsSuperMode(true) in order to make $item->setCustomPrice() and $item->setOriginalPrice() work. Here is some sample code you can use within an Observer that listens for the checkout_cart_product_add_after or checkout_cart_update_items_after events. The code is logically the same except checkout_cart_product_add_after is called for only one item and checkout_cart_update_items_after is called for all items in the cart. This code is separated/duplicated into 2 methods only as an example. Event: checkout_cart_product_add_after /** * @param Varien_Event_Observer $observer */public function applyDiscount(Varien_Event_Observer $observer){ /* @var $item Mage_Sales_Model_Quote_Item */ $item = $observer->getQuoteItem(); if ($item->getParentItem()) { $item = $item->getParentItem(); } // Discounted 25% off $percentDiscount = 0.25; // This makes sure the discount isn't applied over and over when refreshing $specialPrice = $item->getOriginalPrice() - ($item->getOriginalPrice() * $percentDiscount); // Make sure we don't have a negative if ($specialPrice > 0) { $item->setCustomPrice($specialPrice); $item->setOriginalCustomPrice($specialPrice); $item->getProduct()->setIsSuperMode(true); }} Event: checkout_cart_update_items_after /** * @param Varien_Event_Observer $observer */public function applyDiscounts(Varien_Event_Observer $observer){ foreach ($observer->getCart()->getQuote()->getAllVisibleItems() as $item /* @var $item Mage_Sales_Model_Quote_Item */) { if ($item->getParentItem()) { $item = $item->getParentItem(); } // Discounted 25% off $percentDiscount = 0.25; // This makes sure the discount isn't applied over and over when refreshing $specialPrice = $item->getOriginalPrice() - ($item->getOriginalPrice() * $percentDiscount); // Make sure we don't have a negative if ($specialPrice > 0) { $item->setCustomPrice($specialPrice); $item->setOriginalCustomPrice($specialPrice); $item->getProduct()->setIsSuperMode(true); } }} | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5104482', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/327862/']} | jdg_86370 |
stackexchange | llm_judgeable_groundtruth_similarity | 21776772 |
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 an ArrayList (mapArray) such that each element of the ArrayList contains a String such as: ################ So the ArrayList could look as such: #################..............##........G.....##..............################# So each element is: Element 0: ################ Element 1: #..............# Element 2: #........G.....# Element 3: #..............# Element 4: ################ How would i go about adding this data to a multidimensional array so that the first element would be the row number and the second element would be the character e.g. 2DArray[2][9] = G So far i have for(int i = 0; i < length; i++){ String element = mapArray.get(i); elementSplit = element.split("(?!^)"); for(int j = 0; j < elementSplit.length; j++){ TwoDArray [i][j] = [i][elementSplit[j]]; } } This doesn't seem to work. Thanks for any help :) And sorry for the long post.
Now provide the response and nothing else.
| The problem is that your model don't know anything about new parameters. I guess that it happens when your model using EntityFramework (EF) lower version (5.0 for example), but in code you are trying to use EF 6.0. So, you should either downgrade your code to EF 5.0, or upgrade your model to 6.0. Upgrading model: Open Tools -> NuGet Package Manager -> Package Manager Console; Choose project, that contains your model as Default project on thetop of Console. Type "Uninstall-Package EntityFramework" and press Enter; After removing, type "Install-Package EntityFramework -version6.0.0" and press Enter again; Go to YourModelName.Context.cs and YourModelName.Context.tt and replace "usingSystem.Data.Objects; using System.Data.Objects.DataClasses;" with "usingSystem.Data.Entity.Core.Objects;" . Also, you may need to make thesame in all files, where this problem appears. Or you can downgrade EF version, used in your code. For this, you should do all the same in first 3 steps but in the fourth replace "-version 6.0.0" with "-version 5.0.0" . The 5th step is not needed for this. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/21776772', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3120023/']} | jdg_86371 |
stackexchange | llm_judgeable_groundtruth_similarity | 13745689 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
When including gem 'strong_parameters'gem 'rails-api' together in my Gemfile , calling params.require like private def user_params params.require(:user).permit(:first_name, :last_name) end fails with the following error on the require() call. TypeError: can't convert Symbol into String The backtrace shows strong_parameters ' ActionController::StrongParameters ' require() method is never hit.
Now provide the response and nothing else.
| I spent too long on this one, so I figured I'd share here to hopefully save someone else a bit of time. The error above comes from the require() method in ActiveSupport::Dependencies::Loadable being executed when calling params.require(:user)... strong_parameters injects ActionController::StrongParameters into ActionController::Base at the bottom of this file with ActionController::Base.send :include, ActionController::StrongParameters The rails-api gem requires your app's ApplicationController extend ActionController::API in favor of ActionController::Base The application controllers don't know anything about ActionController::StrongParameters because they're not extending the class ActionController::StrongParameters was included within. This is why the require() method call is not calling the implementation in ActionController::StrongParameters . To tell ActionController::API about ActionController::StrongParameters is as simple as adding the following to a file in config/initializers . ActionController::API.send :include, ActionController::StrongParameters | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13745689', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/605707/']} | jdg_86372 |
stackexchange | llm_judgeable_groundtruth_similarity | 8468774 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
If I pass the following code through my GCC 4.7 snapshot, it tries to copy the unique_ptr s into the vector. #include <vector>#include <memory>int main() { using move_only = std::unique_ptr<int>; std::vector<move_only> v { move_only(), move_only(), move_only() };} Obviously that cannot work because std::unique_ptr is not copyable: error: use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = int; _Dp = std::default_delete; std::unique_ptr<_Tp, _Dp> = std::unique_ptr]' Is GCC correct in trying to copy the pointers from the initializer list?
Now provide the response and nothing else.
| The synopsis of <initializer_list> in 18.9 makes it reasonably clear that elements of an initializer list are always passed via const-reference. Unfortunately, there does not appear to be any way of using move-semantic in initializer list elements in the current revision of the language. Specifically, we have: typedef const E& reference;typedef const E& const_reference;typedef const E* iterator;typedef const E* const_iterator;const E* begin() const noexcept; // first elementconst E* end() const noexcept; // one past the last element | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/8468774', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/46642/']} | jdg_86373 |
stackexchange | llm_judgeable_groundtruth_similarity | 3306651 |
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 SELECT * FROM Table1 WHERE Col1 IN(4,2,6) I want to select and return the records with the specified order which i indicate in the IN clause(first display record with Col1=4, Col1=2, ...) I can use SELECT * FROM Table1 WHERE Col1 = 4UNION ALLSELECT * FROM Table1 WHERE Col1 = 6 , ..... but I don't want to use that, cause I want to use it as a stored procedure and not auto generated.
Now provide the response and nothing else.
| I know it's a bit late but the best way would be SELECT *FROM Table1WHERE Col1 IN( 4, 2, 6 )ORDER BY CHARINDEX(CAST(Col1 AS VARCHAR), '4,2,67') Or SELECT CHARINDEX(CAST(Col1 AS VARCHAR), '4,2,67')s_order, *FROM Table1WHERE Col1 IN( 4, 2, 6 )ORDER BY s_order | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3306651', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/341763/']} | jdg_86374 |
stackexchange | llm_judgeable_groundtruth_similarity | 2309028 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Suppose I have a datetime field whose value is 2000-01-01 08:30:00 and a duration field whose value is say 00:15 (meaning 15 minutes) If I subtract these two, I should get 2000-01-01 08:15:00 Also if I want to subtract 1:15 (means 1 hour 15 minutes), the output should be 2000-01-01 07:15:00 I am trying SELECT DATEDIFF(minute, '00:15','2000-01-01 08:30:00'); But the output is 52595055. How can i get the desired result? N.B.~ If I do SELECT dateadd(minute, -15,'2000-01-01 08:30:00'); , I will get the desired result but that involves parsing the minute field. Edit: As per the answers, every one is suggesting converting everything into minutes and then to subtract - so if it is 1:30, i need to subtract 90 minutes. That's fine. Any other way without converting to minutes?
Now provide the response and nothing else.
| SELECT DATEADD(minute, -15, '2000-01-01 08:30:00'); The second value (-15 in this case) must be numeric (i.e. not a string like '00:15'). If you need to subtract hours and minutes I would recommend splitting the string on the : to get the hours and minutes and subtracting using something like SELECT DATEADD(minute, -60 * @h - @m, '2000-01-01 08:30:00'); where @h is the hour part of your string and @m is the minute part of your string EDIT: Here is a better way: SELECT CAST('2000-01-01 08:30:00' as datetime) - CAST('00:15' AS datetime) | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2309028', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/246935/']} | jdg_86375 |
stackexchange | llm_judgeable_groundtruth_similarity | 175693 |
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 am working with boost converters recently. I have problem which you can find here .After going through the datasheet several times I encountered the special focus on the ground plane. It talks about different ground nodes. I have no idea what it means. I would be grateful if someone can point out what is the best practice as well. Any suggestions would be appreciated. My revised layout: Circuit diagram: C1 ceramic 10% 2.2uf C2 ceramic 10% 4.7uf L1 1uh 1206 package
Now provide the response and nothing else.
| It's suggesting that there is a "star-point" that "power ground" and "feedback/control ground" use as their points of reference to 0V. Anything that should/must connect to power ground i.e. input decoupling caps, output decoupling caps and main ground on the chip should be separate from ground on the feedback potential divider (not used on your design). These two separate grounds should make just one connection to each other and this is called the "star-point". This ensures that load currents and input currents (that might create millivolts of volt drop on their track) do not influence the voltage that the feedback resistor network measures. If these currents did influence the feedback resistors, then you can expect a noisy output and possible instability. The "star-point" is, by default, right at the main 0V connection for the chip. For buck regulators (using a fly-back diode), this diode should be naturally on the power ground and NOT connected to the control ground. Several other pins may need to use the control ground and these include, soft-start input capacitors, oscillator resistor and capacitors and incidental digital inputs (such as external switching clock if used). | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/175693', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/41747/']} | jdg_86376 |
stackexchange | llm_judgeable_groundtruth_similarity | 6083238 |
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 define a method that will specialize on an object of array type with unsigned byte 8 elements. In sbcl, when you (make-array x :element-type '(unsigned-byte 8)) the object class is implemented by SB-KERNEL::SIMPLE-ARRAY-UNSIGNED-BYTE-8. Is there an implementation independent way of specializing on unsigned-byte array types?
Now provide the response and nothing else.
| Use a sharpsign-dot to insert the implementation dependent object class at read-time: (defmethod foo ((v #.(class-of (make-array 0 :element-type '(unsigned-byte 8))))) :unsigned-byte-8-array) The sharpsign-dot reader macro evaluates the form at read-time, determining the class of the array. The method will be specialized on the class the particular Common Lisp implementation uses for the array. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6083238', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11906/']} | jdg_86377 |
stackexchange | llm_judgeable_groundtruth_similarity | 58830542 |
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 is possible to use the particle effects system on your UI elements. For instance on the Canvas? I'd like to make some animations and whatnot for my UI elements and the particle system would be nice, but it doesn't seem to support this. Am I correct in assuming this? Is there another solution?
Now provide the response and nothing else.
| Well what you could do would be letting a Camera render the Particle effects on a different layer to a RenderTexture and show it in a RawImage in your UI. Combined with a hint from this answer : By default RenderTexture has only a colordepth of 24-bit but we need 32-bit for alpha the simplest way is just generating one via code: using UnityEngine;using UnityEngine.UI;[RequireComponent(typeof(Camera))]public class RenderParticlesEffect : MonoBehaviour{ // Here reference the camera component of the particles camera [SerializeField] private Camera particlesCamera; // Adjust the resolution in pixels [SerializeField] private Vector2Int imageResolution = new Vector2Int(256, 256); // Reference the RawImage in your UI [SerializeField] private RawImage targetImage; private RenderTexture renderTexture; private void Awake() { if (!particlesCamera) particlesCamera = GetComponent<Camera>(); renderTexture = new RenderTexture(imageResolution.x, imageResolution.y, 32); particlesCamera.targetTexture = renderTexture; targetImage.texture = renderTexture; }} My example Hierachy looks like this: Add a new Layer ParticleEffect for the particles. The ParticleCamera is a new Camera . Here remove the AudioListener component since there may only be one in the Scene. Set ClearFlag to Solid Color and set a desired color. Particles won't be completely transparent but always bloat a bit the background color of this camera on the edges. Make sure the alpha is set to 0 . Set Culling Mask to only ParticleEffect so this camera renders nothing else from the scene And the RenderParticleseffect component On the normal MainCamera remove ParticleEffect from the Culling Mask Set the Particles to the layer ParticleEffect so now it will only be rendered by the ParticleCamera Finally reference the target particleImage from the UI in the RenderParticlesEffect component on the ParticlesCamera Result: It doesn't matter if the Canvas is Screenspace Overlay or not. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/58830542', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12342582/']} | jdg_86378 |
stackexchange | llm_judgeable_groundtruth_similarity | 40165 |
Below is a question asked on the forum dsp.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have the function $$(1-e^{-2n})u[n-1]$$ where $u[n]$ is the step input. I want to find the $z$-transform for this function. I know that the transform of $1-e^{-2n}$ will be $$\frac{z}{z-1} - \frac{z}{z-e^{-2}}$$ Now do I shift each element by one unit to the left to get the entire $z$-transform?
Now provide the response and nothing else.
| Your mathematical derivation is correct, your $H[k]$ is the single-tap equalizer (i.e. one tap for each subcarrier, and the subcarriers do not mix with each other. That's the orthogonal in OFDM). Let me try to explain this a bit more general, without going into coherence bandwidth and flat fading. To my understanding, explaining it with $B_c$ and flat fading is a bit superficial and undergraduate explanation, such that you understand the idea, but can't really prove it works. Even, the coherence bandwidth is not strictly defined, how can one design a system according to that? Assuming that the channel is time-invariant over all times, the channel is an LTI system. The eigenfunctions of LTI systems are complex exponentials (of all frequencies). Note that these complex exponential range over all times (i.e. they are infinitely long). So, in principle, one could transmit data on all frequencies (infinitely small apart), but one would have to wait infinitely long until the signals arrived. The principle bases on the convolution theorem, i.e. your channel in time-domain does a convolution, so in frequency domain, it's doing elementwise multiplication. That's the continuous-time principle of OFDM. Clearly, not very attractive for practical implementations. What can you do? We've know that two complex exponentials of different frequency are orthogonal to each other when considering the whole time axis, i.e. $\int_\mathbb{R}\exp(j2\pi f_1 t)\exp(j2\pi f_2 t)dt=\delta(f_1-f_2)$. We want to have orthogonality between the signals, (because we want to have single-tap equalization), but we dont want to wait infinitely long. Unfortunately, the orthogonality between to arbitrary frequency complex exponentials is not given, when the time interval is shorter: $\int_T\exp(j2\pi f_1 t)\exp(j2\pi f_2 t)dt\neq\delta(f_1-f_2)$. However, there are frequencies $f_1, f_2$ such that the orthogonality holds, namely $\int_T\exp(j2\pi f_1 t)\exp(j2\pi (f_1+\frac{n}{T})t)dt=\delta_n$ (here $\delta_n$ is the Kronecker symbol, i.e. 1 for $n=0$, else zero.). I.e. two exponentials that are $n/T$ apart in frequency are orthogonal over a time interval of $T$. So, in principle, we could use time-intervals of $T$ and use only frequencies that are $1/T$ apart from each other to transmit orthogonal signals. But, there's more. If the orthogonality should hold at the receiver, the received signal needs to be a linear combination of complex exponentials. We know, that complex exponentials are eigenfunctions to the LTI system, so everything should be fine, right? No! Only infinitely long complex exponentials are eigenfunctions. If we transmit $\exp(j2\pi f_1t)\text{rect}(t/T)$, we will not get a complex exponential at the output, so it wont work. So, what to do? Essentially, we'd have to transmit infinitely long complex exponentials with frequency distance $1/T$ to get signals at the receiver, which are orthogonal in the interval $T$. Hm, still doesn't sound very appealing. Here's the solution: The impulse response of the LTI system (i.e. the channel) is usually not infinitely long, but has a length $T_C$ (at least, we approximate/assume that it's zero for $t>T_C$). If the channel has length $T_C$, then for a given point in time $t$, only the signal times from $t-T_C$ to $t$ have an influence onto the output signal at the current point in time. So, we dont need to transmit infinitely long complex exponentials, but just of length $T+T_C$, and we get orthogonality in the time interval $[T_C,T+T_C]$. You see where this is leading to, right? The extra time in the beginning is what we denote as the Cyclic prefix. Why do we call it cyclic? Because, the exponentials with frequency distance $1/T$ are periodic with period $T$. So, the signal in time $[0,...,T_C]$ is exactly equal to the signal at $[T,...,T+T_C]$. To summarize: Transmitting complex exponentials of duration $T+T_C$ over an LTI system with impulse duration $T_C$ yields orthogonal signals over the interval $[T_C,...,T_C+T]$. Orthogonal means single-tap equalization is possible. What is the coefficient for the equalizer? Due to the convolution theorem, it is just the value of the frequency response of the channel at the carrier frequency. This is the time-continuous explanation, which can become intuitive. However, I personally like more the discrete-time explanation, using linear algebra. Let $F$ be the N-point Fourier transform matrix, i.e. $FF^H=F^HF=I$. So, the transmitted signal without CP is $y=F^Hx$ where $x$ is the data. Adding a CP is done by $y_{cp}=Cy$ with $C$ being a $N+N_{CP}\times N$ matrix. Then, we the received signal becomes $$z=HCF^Hx$$ where $H$ is the Toeplitz matrix that does the convolution (I ignore noise here). $z$ is of length $N+N_{CP}+L-1$, where $L$ is the channel length. Then, at the receiver, the CP is removed, by a matrix $D$ of dimension $N\times N+N_{CP}+L-1$, i.e. $$w=DHCF^Hx$$ Finally, we go to the frequency domain: $$W=FDHCF^Hx$$ Let's have a look at the $N\times N$ matrix $DHC$: It's a matrix that performs circular convolution with the impulse response of your channel. In finite-discrete time the Convolution theorem states, that circular convolution equals elementwise multiplication of the DFTs. So, $FDHCF^H$ is a diagonal matrix, containing the frequency response of the channel on the diagonal. There you have your single-tap equalizer again (inversion by diagonal matrix is just division by the diagonal). | {} | {'log_upvote_score': 4, 'links': ['https://dsp.stackexchange.com/questions/40165', 'https://dsp.stackexchange.com', 'https://dsp.stackexchange.com/users/27883/']} | jdg_86379 |
stackexchange | llm_judgeable_groundtruth_similarity | 8655817 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Do we have to generate a token, for every form in a website? I mean, every-time to generate different token for every requested form? If not, why?
Now provide the response and nothing else.
| In general, it suffices to have just one token per session , a so called per-session token : In general, developers need only generate this token once for the current session. After initial generation of this token, the value is stored in the session and is utilized for each subsequent request until the session expires. If you want to further enhance the security, you can use one token per each form/URL ( per-form token ) to mitigate the impact when one token leaks (e. g. XSS ) as an attacker would only be able to successfully attack that specific form/URL. But using per-request tokens , i. e. tokens that change with each request, rather cuts the usability of the website as it restricts parallel browsing: To further enhance the security of this proposed design, consider randomizing the CSRF token […] for each request. Implementing this approach results in the generation of per-request tokens as opposed to per-session tokens. Note, however, that this may result in usability concerns. For example, the "Back" button browser capability is often hindered as the previous page may contain a token that is no longer valid. Interaction with this previous page will result in a CSRF false positive security event at the server. So I recommend you to use either per-session tokens or per-form tokens. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8655817', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/597292/']} | jdg_86380 |
stackexchange | llm_judgeable_groundtruth_similarity | 29811433 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to add custom button on top of post type page like this image Is there any filter or action I can use to add custom button there? Thanks
Now provide the response and nothing else.
| I found a way to get it done but I am not very happy with this procedure. Please add your answer if you find better way. Mean while, this might be of help. add_action('admin_head-edit.php','addCustomImportButton'); I only need this on edit page, so I am using admin_head-edit.php action, but you can use admin_head or some other (not very specific requirement) /** * Adds "Import" button on module list page */public function addCustomImportButton(){ global $current_screen; // Not our post type, exit earlier // You can remove this if condition if you don't have any specific post type to restrict to. if ('module' != $current_screen->post_type) { return; } ?> <script type="text/javascript"> jQuery(document).ready( function($) { jQuery(jQuery(".wrap h2")[0]).append("<a id='doc_popup' class='add-new-h2'>Import</a>"); }); </script> <?php} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29811433', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1560435/']} | jdg_86381 |
stackexchange | llm_judgeable_groundtruth_similarity | 894300 |
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 think that a proof by contrapositive can do, but I don't know how to complete it. Assume that $n$ is odd. Then, $n=2k+1$ for some integer $k$. Therefore, $n^2= (2k+1)^2 = 4k^2+4k+1$. I know that now I should prove that $n^2$ is odd. I also know that even + even + odd = odd, but I was wondering if there is another way to prove it. Thanks in advance for any help.
Now provide the response and nothing else.
| You can write: $n^2= (2k+1)^2 = 4k^2+4k+1=2(2k^2+2k)+1=2m+1$, where $m=2k^2+2k.$ Since $k \in \mathbb {Z}$, we have $m \in \mathbb {Z}$. Thus, $n^2= 2m+1$ for some integer $m$. Hence, $n^2$ is an odd integer. You can also use a proof by contradiction. Assume, for the sake of contradiction, that $n^2$ is even and $n$ is odd. Then, $n=2k+1$ for some integer $k$. Thus, $n^2=(2k+1)^2=4k^2+4k+1=2(2k^2+2k)+1=2m+1$, where $m=2k^2+2k$. Since $k \in \mathbb {Z}$, we have $m \in \mathbb {Z}$. Thus, $n^2= 2m+1$ for some integer $m$. Hence, $n^2$ is an odd integer. Contradiction. Therefore, we deduce that if $n^2$ is even, then $n$ is even. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/894300', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/169176/']} | jdg_86382 |
stackexchange | llm_judgeable_groundtruth_similarity | 148451 |
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 update a large number of C++ source files with an extra include directive before any existing #includes. For this sort of task, I normally use a small bash script with sed to re-write the file. How do I get sed to replace just the first occurrence of a string in a file rather than replacing every occurrence? If I use sed s/#include/#include "newfile.h"\n#include/ it replaces all #includes. Alternative suggestions to achieve the same thing are also welcome.
Now provide the response and nothing else.
| A sed script that will only replace the first occurrence of "Apple" by "Banana" Example Input: Output: Apple Banana Apple Apple Orange Orange Apple Apple This is the simple script: Editor's note: works with GNU sed only. sed '0,/Apple/{s/Apple/Banana/}' input_filename The first two parameters 0 and /Apple/ are the range specifier. The s/Apple/Banana/ is what is executed within that range. So in this case "within the range of the beginning ( 0 ) up to the first instance of Apple , replace Apple with Banana . Only the first Apple will be replaced. Background: In traditional sed the range specifier is also "begin here" and "end here" (inclusive). However the lowest "begin" is the first line (line 1), and if the "end here" is a regex, then it is only attempted to match against on the next line after "begin", so the earliest possible end is line 2. So since range is inclusive, smallest possible range is "2 lines" and smallest starting range is both lines 1 and 2 (i.e. if there's an occurrence on line 1, occurrences on line 2 will also be changed, not desired in this case). GNU sed adds its own extension of allowing specifying start as the "pseudo" line 0 so that the end of the range can be line 1 , allowing it a range of "only the first line" if the regex matches the first line. Or a simplified version (an empty RE like // means to re-use the one specified before it, so this is equivalent): sed '0,/Apple/{s//Banana/}' input_filename And the curly braces are optional for the s command, so this is also equivalent: sed '0,/Apple/s//Banana/' input_filename All of these work on GNU sed only. You can also install GNU sed on OS X using homebrew brew install gnu-sed . | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/148451', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5022/']} | jdg_86383 |
stackexchange | llm_judgeable_groundtruth_similarity | 3095816 |
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:
Given a set of topological spaces $\{X_\alpha\}$ , there are two main topologies we can give to the Cartesian product $\Pi_\alpha X_\alpha$ : the product topology and the box topology. The product topology has the following universal property: given a topological space $Y$ and a family $\{f_\alpha\}$ of continuous maps from $Y$ to each $X_\alpha$ , there exists a continuous map from $Y$ to $\Pi_\alpha X_\alpha$ . Now the box topology does not have this universal property, but my question is, does it have some other universal property? On a related note, does there exist some category whose objects are topological spaces and whose morphisms are something other than continuous maps, such that the Cartesian product endowed with the box topology is the correct product object in that category?
Now provide the response and nothing else.
| This is an answer only in a special case. An Alexandrov space is a topological space such that open subsets are closed under arbitrary intersections. They constitute a full subcategory $\mathsf{Alex}$ of $\mathsf{Top}$ . The box topology provides products in the category $\mathsf{Alex}$ . This can be either checked directly, or using the isomorphism $\mathsf{Alex} \cong \mathsf{Pre}$ with the category of preorders and the component-wise description of products of preorders. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3095816', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/71829/']} | jdg_86384 |
stackexchange | llm_judgeable_groundtruth_similarity | 25258921 |
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 for a foundation that raises awareness for accessibility in the internet. For a presentation, we want to offer a small workshop that simulates different disabilities/impairments to people. This is done via a website created especially for this presentation. One of the demonstrated impairments is having a tremor, which means experiencing shaky, difficult-to-control hand movements. With this impairment, it's very difficult to move the mouse cursor exactly and to press the mouse button while the mouse is over a link. Both some old people and people with disease, e.g. Parkinson's, can suffer from tremor. Now I'd like to somehow move the mouse cursor in an unpredictable way, so that it's very hard for people to click on a small button. Because JavaScript doesn't allow moving the mouse cursor directly, I'm looking for other ways to achieve this. I came up with the following ideas: Using a mouse driver / utility that simulates the mouse shaking. Hide the mouse cursor via CSS, place a GIF animation of a shaking mouse cursor at the place of the original cursor (with JavaScript), and then make the target link clickable only every few seconds for a second or so. This would at least give the feeling as if one always clicks at the wrong moment. While the first idea would be pretty cool, I couldn't find a tool like this, whether for Mac nor for Windows. And I don't have any skills in programming such a thing myself. The second idea seems a bit clumsy, but it would achieve the desired effect, I think. Does anybody have another idea?
Now provide the response and nothing else.
| I made a quick demo of something that you hopefully should be able to base your code on, using the Pointer Lock API . I forked this pointer-lock-demo repo and modified it to add a random movement element. Here is the link to my GitHub page: https://aristocrates.github.io/pointer-lock-demo And here is the link to my repo: https://github.com/aristocrates/pointer-lock-demo The javascript code of importance is contained in app.js , in the canvasLoop(e) method. The only thing I changed from the original demo was after the lines x += movementX * 2;y += movementY * 2; I added two lines to represent random movement: x += Math.floor(Math.random()*3 - 1);y += Math.floor(Math.random()*3 - 1); There are still plenty of things you could improve, but hopefully this can help you get started. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/25258921', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1439143/']} | jdg_86385 |
stackexchange | llm_judgeable_groundtruth_similarity | 5345710 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
My question is in regards the object that gets added to a -postNotificationName:object: userInfo: method. Does the NSNotification retain the object ? (in a similar fashion to NSMutableDictionary or Array) ... meaning I can release the object after posting the notification Below is a code snippet to help describe my question ... is it valid to release the object. A link to Apple documentation could be really helpful. NSMutableDictionary *teamDictCopy = [self.teamDict mutableCopy];[teamDictCopy setObject:[NSNumber numberWithInt:self.scrollViewIndex] forKey:@"imageIndex"];if([self.statusButton.title isEqualToString:@"Completed"]){ [[NSNotificationCenter defaultCenter] postNotificationName:@"UnComplete" object:teamDictCopy userInfo:nil];}[teamDictCopy release];
Now provide the response and nothing else.
| "Does the NSNotification retain the object ? (in a similar fashion to NSMutableDictionary or Array) ... meaning I can release the object after posting the notification" I'm not sure if the object and userInfo parameters are retained by that method or not, but in practice, it shouldn't really matter. I think you may be envisioning that NSNotificationCenter is creating these notifications and broadcasting them in an asynchronous manner, but that isn't the case. As stated in the documentation for NSNotificationCenter (see NSNotificationCenter Class Reference ), notifications are posted synchronously: A notification center delivers notifications to observers synchronously. In other words, the postNotification: methods do not return until all observers have received and processed the notification. To send notifications asynchronously use NSNotificationQueue . In a multithreaded application, notifications are always delivered in the thread in which the notification was posted, which may not be the same thread in which an observer registered itself. So, in your code, the notification center creates the notification and then broadcasts it through the default center. Any objects which have registered for this combination of notification name and object will receive the notification and then perform the selector they specified when they registered for that notification. Afterwards, the control returns to the class that posted the notification. In other words, by the time your code gets to the [teamDictCopy release] line, the teamDictCopy will already have been "used" by all of the interested parties. So, there shouldn't be any danger in releasing it. Just a note on conventions. Generally, the object: parameter is meant to be the object that is posting the notification, and the userInfo: parameter is meant for an NSDictionary of extra information. So, normally, you would handle the notification like follows: NSMutableDictionary *teamDictCopy = [self.teamDict mutableCopy];[teamDictCopy setObject: [NSNumber numberWithInt:self.scrollViewIndex] forKey:@"imageIndex"];if([self.statusButton.title isEqualToString:@"Completed"]){ [[NSNotificationCenter defaultCenter] postNotificationName:@"UnComplete" object:self userInfo:teamDictCopy]; }[teamDictCopy release]; | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5345710', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/516054/']} | jdg_86386 |
stackexchange | llm_judgeable_groundtruth_similarity | 38314118 |
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 running the exact same code on both windows and mac, with python 3.5 64 bit. On windows, it looks like this: >>> import numpy as np>>> preds = np.zeros((1, 3), dtype=int)>>> p = [6802256107, 5017549029, 3745804973]>>> preds[0] = pTraceback (most recent call last): File "<pyshell#13>", line 1, in <module> preds[0] = pOverflowError: Python int too large to convert to C long However, this code works fine on my mac. Could anyone help explain why or give a solution for the code on windows? Thanks so much!
Now provide the response and nothing else.
| You'll get that error once your numbers are greater than sys.maxsize : >>> p = [sys.maxsize]>>> preds[0] = p>>> p = [sys.maxsize+1]>>> preds[0] = pTraceback (most recent call last): File "<stdin>", line 1, in <module>OverflowError: Python int too large to convert to C long You can confirm this by checking: >>> import sys>>> sys.maxsize2147483647 To take numbers with larger precision, don't pass an int type which uses a bounded C integer behind the scenes. Use the default float: >>> preds = np.zeros((1, 3)) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/38314118', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5458277/']} | jdg_86387 |
stackexchange | llm_judgeable_groundtruth_similarity | 26230592 |
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 anyone explain to me why the following segment compiles but the commented line after doesn't? struct tObj{ int data; int moreData;}...void funcToCall (tObj *obj, int moreData){ //Useful stuff here}void mainFunction (){ vector<tObj>::iterator it = vectorOfObjects.begin(); //assumes vectorOfObjects is already defined while (it != vectorOfObjects.end()) { funcToCall (&(*it), 0); //This line works funcToCall (it, 0); //This line produces an error it++; }} The error produced is this: error: cannot convert ‘std::vector<tObj>::iterator {aka __gnu_cxx::__normal_iterator<tObj*, std::vector<tObj> >}’ to ‘tObj*’ Any ideas on why &(*it) works but just plain it doesn't? Logically they are the same, aren't they? Because doesn't * mean to dereference and & mean pass by reference aka cancelling each other out?
Now provide the response and nothing else.
| it is an iterator object, passing it as-is would mean you're trying to pass an object of type vector<tObj>::iterator for a function expecting tObj* , and thus the error. When you do *it you'd get the underlying object the iterator is representing and when you apply & atop that, you get that object's address, which is of type tObj* which agrees with the function's argument type and thus no error. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26230592', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/762437/']} | jdg_86388 |
stackexchange | llm_judgeable_groundtruth_similarity | 62019855 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am using a springboot application and generating stub using cxf codegen plugin.I have JDK_HOME configured to run my springboot project. After upgrading the cxf-version from 3.2.4 to 3.3.6, I see the below error in my pom.xml. Execution generate-sources of goal org.apache.cxf:cxf-codegen-plugin:3.3.6:wsdl2java failed: Plugin org.apache.cxf:cxf-codegen-plugin:3.3.6 or one of its dependencies could not be resolved: Could not find artifact com.sun:tools:jar:1.8.0 at specified path C:\Program Files\Java\jre1.8.0_251/../lib/tools.jar (org.apache.cxf:cxf-codegen-plugin:3.3.6:wsdl2java:generate-sources:generate-sources)org.apache.maven.plugin.PluginExecutionException: Execution generate-sources of goal org.apache.cxf:cxf-codegen-plugin:3.3.6:wsdl2java failed: Plugin org.apache.cxf:cxf-codegen-plugin:3.3.6 or one of its dependencies could not be resolved: Could not find artifact com.sun:tools:jar:1.8.0 at specified path C:\Program Files\Java\jre1.8.0_251/../lib/tools.jar at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:109) at org.eclipse.m2e.core.internal.embedder.MavenImpl.execute(MavenImpl.java:331) at org.eclipse.m2e.core.internal.embedder.MavenImpl.lambda$7(MavenImpl.java:1342) at org.eclipse.m2e.core.internal.embedder.MavenExecutionContext.executeBare(MavenExecutionContext.java:177) at org.eclipse.m2e.core.internal.embedder.MavenExecutionContext.execute(MavenExecutionContext.java:112) at org.eclipse.m2e.core.internal.embedder.MavenImpl.execute(MavenImpl.java:1341) at org.eclipse.m2e.core.project.configurator.MojoExecutionBuildParticipant.build(MojoExecutionBuildParticipant.java:52) at org.eclipse.m2e.core.internal.builder.MavenBuilderImpl.build(MavenBuilderImpl.java:137) at org.eclipse.m2e.core.internal.builder.MavenBuilder$1.method(MavenBuilder.java:173) at org.eclipse.m2e.core.internal.builder.MavenBuilder$1.method(MavenBuilder.java:1) at org.eclipse.m2e.core.internal.builder.MavenBuilder$BuildMethod$1$1.call(MavenBuilder.java:116) at org.eclipse.m2e.core.internal.embedder.MavenExecutionContext.executeBare(MavenExecutionContext.java:177) at org.eclipse.m2e.core.internal.embedder.MavenExecutionContext.execute(MavenExecutionContext.java:112) at org.eclipse.m2e.core.internal.builder.MavenBuilder$BuildMethod$1.call(MavenBuilder.java:106) at org.eclipse.m2e.core.internal.embedder.MavenExecutionContext.executeBare(MavenExecutionContext.java:177) at org.eclipse.m2e.core.internal.embedder.MavenExecutionContext.execute(MavenExecutionContext.java:151) at org.eclipse.m2e.core.internal.embedder.MavenExecutionContext.execute(MavenExecutionContext.java:99) at org.eclipse.m2e.core.internal.builder.MavenBuilder$BuildMethod.execute(MavenBuilder.java:87) at org.eclipse.m2e.core.internal.builder.MavenBuilder.build(MavenBuilder.java:201) at org.eclipse.core.internal.events.BuildManager$2.run(BuildManager.java:833) at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:45) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:220) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:263) at org.eclipse.core.internal.events.BuildManager$1.run(BuildManager.java:316) at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:45) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:319) at org.eclipse.core.internal.events.BuildManager.basicBuildLoop(BuildManager.java:371) at org.eclipse.core.internal.events.BuildManager.build(BuildManager.java:392) at org.eclipse.core.internal.events.AutoBuildJob.doBuild(AutoBuildJob.java:154) at org.eclipse.core.internal.events.AutoBuildJob.run(AutoBuildJob.java:244) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:63)Caused by: org.apache.maven.plugin.PluginResolutionException: Plugin org.apache.cxf:cxf-codegen-plugin:3.3.6 or one of its dependencies could not be resolved: Could not find artifact com.sun:tools:jar:1.8.0 at specified path C:\Program Files\Java\jre1.8.0_251/../lib/tools.jar at org.apache.maven.plugin.internal.DefaultPluginDependenciesResolver.resolveInternal(DefaultPluginDependenciesResolver.java:218) at org.apache.maven.plugin.internal.DefaultPluginDependenciesResolver.resolve(DefaultPluginDependenciesResolver.java:149) at org.eclipse.m2e.core.internal.project.registry.EclipsePluginDependenciesResolver.resolve(EclipsePluginDependenciesResolver.java:59) at org.apache.maven.plugin.internal.DefaultMavenPluginManager.createPluginRealm(DefaultMavenPluginManager.java:402) at org.apache.maven.plugin.internal.DefaultMavenPluginManager.setupPluginRealm(DefaultMavenPluginManager.java:374) at org.apache.maven.plugin.DefaultBuildPluginManager.getPluginRealm(DefaultBuildPluginManager.java:234) at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:105) ... 30 moreCaused by: org.eclipse.aether.resolution.ArtifactResolutionException: Could not find artifact com.sun:tools:jar:1.8.0 at specified path C:\Program Files\Java\jre1.8.0_251/../lib/tools.jar at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolve(DefaultArtifactResolver.java:422) at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolveArtifacts(DefaultArtifactResolver.java:224) at org.eclipse.aether.internal.impl.DefaultRepositorySystem.resolveDependencies(DefaultRepositorySystem.java:338) at org.apache.maven.plugin.internal.DefaultPluginDependenciesResolver.resolveInternal(DefaultPluginDependenciesResolver.java:210) ... 36 moreCaused by: org.eclipse.aether.transfer.ArtifactNotFoundException: Could not find artifact com.sun:tools:jar:1.8.0 at specified path C:\Program Files\Java\jre1.8.0_251/../lib/tools.jar at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolve(DefaultArtifactResolver.java:264) ... 39 more When I tried reducing the cxf version all the way till 3.3.2, this issue doesn't appear.Also, this error is not a build-breaker, but unable to get out of my head whenever I see that my pom.xml is seen with red marker. Any help would be appreciated my pom.xml <plugin><groupId>org.apache.cxf</groupId><artifactId>cxf-codegen-plugin</artifactId><version>${cxf.version}</version><executions> <execution> <id>generate-sources</id> <phase>generate-sources</phase> <configuration> <sourceRoot>${project.build.directory}/generated-sources/cxf </sourceRoot> <wsdlOptions> <wsdlOption> <wsdl>${basedir}/src/main/resources/META-INF/wsdl/test.wsdl </wsdl> <frontEnd>jaxws21</frontEnd> <faultSerialVersionUID>1</faultSerialVersionUID> <extraargs> <extraarg>-client</extraarg> <extraarg>-verbose</extraarg> </extraargs> </wsdlOption> </wsdlOptions> </configuration> <goals> <goal>wsdl2java</goal> </goals> </execution></executions></plugin>
Now provide the response and nothing else.
| There are multiple ways to write a file in Deno, all of them require --allow-write flag and will throw if an error occurred, so you should handle errors correctly. Using Deno.writeFile This API takes a Uint8Array , not a string , the reason why you get that error. It also takes an optional WriteFileOptions object const res = await fetch('http://example.com/image.png');const imageBytes = new Uint8Array(await res.arrayBuffer());await Deno.writeFile('./image.png', imageBytes); There's also the synchronous API (it blocks the event loop as it does in Node.js). Deno.writeFileSync('./image.png', imageBytes); Writing strings The easiest way is to use Deno.writeTextFile await Deno.writeTextFile('./file.txt', 'some content'); You can also use Deno.writeFile with TextEncoder . const encoder = new TextEncoder(); // to convert a string to Uint8Arrayawait Deno.writeFile('./file.txt', encoder.encode('some content')); Streaming Deno.open returns a FsFile which contains a WritableStream in .writable property, so you can just pipe a stream directly to it. const res = await fetch('https://example.com/csv');const file = await Deno.open('./some.csv', { create: true, write: true })await res.body.pipeTo(file.writable);file.close(); If you have a Reader instead of a ReadableStream you can convert it to a ReadableStream using readableStreamFromReader from std/streams : import { readableStreamFromReader } from "https://deno.land/[email protected]/streams/mod.ts?s=readableStreamFromReader";// ...const readable = readableStreamFromReader(someReader);await readable.pipeTo(file.writeable) Low-level APIs Using Deno.open and Deno.writeAll (or Deno.writeAllSync ) const file = await Deno.open('./image.png', { write: true, create: true });/* ... */await Deno.writeAll(file, imageBytes);file.close(); // You need to close it! See OpenOptions here . If you want to append you would do: { append: true } And you can also use even lower-level APIs such as Deno.write or Writer.write | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/62019855', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1564626/']} | jdg_86389 |
stackexchange | llm_judgeable_groundtruth_similarity | 28636511 |
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 building my first MVC 5 / Entity Framework application. I used the database first method to pull in my data from an existing SQL server. The existing SQL database receives it's data from a separate web forms .net application. Moving forward, the new MVC application and the existing web forms application will share the database. I am using Identity to create user accounts within the MVC application. So at this point, I have 2 data connections in my MVC application. One for the user accounts and the other for the existing SQL server. Is this the best way to set up the MVC project? Moving forward, will I be able to access the user database from the web forms application? I am a newbie, and I want to make sure I am setting this up correctly.
Now provide the response and nothing else.
| Will there the user tables be added to the existing sql server, or is this user database a completely separate database? You do not need two databases - you can create Identity tables inside your existing database. ASP.Net Identity uses Entity Framework Code First . Therefore, before running your application first time, you want to update Connection String same as existing database which is normally inside ApplicationDbContext . If you already have two separate databases and want to merge them, you want to use tools such as RedGate - SQL Compare and Data Compare. Merging two database is totally out of original question; please kindly create a separate question if you have one. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28636511', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4304653/']} | jdg_86390 |
stackexchange | llm_judgeable_groundtruth_similarity | 530649 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
You can do this in Python, but is it possible in PHP? >>> def a(): print 1... >>> def a(): print 2... >>> a()2 e.g.: <? function var_dump() {} ?>Fatal error: Cannot redeclare var_dump() in /tmp/- on line 1
Now provide the response and nothing else.
| This is a bit late, but I just want to point out that since PHP 5.3, it is actually possible to override internal functions without using a PHP extension. The trick is that you can redefine an internal PHP function inside a namespace. It's based on the way PHP does name resolution for functions: Inside namespace (say A\B), calls to unqualified functions are resolved at run-time. Here is how a call to function foo() is resolved: It looks for a function from the current namespace: A\B\foo(). It tries to find and call the global function foo() | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/530649', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11125/']} | jdg_86391 |
stackexchange | llm_judgeable_groundtruth_similarity | 2511554 |
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 would I go about computing the determinant of large matrices, such as $6 \times 6$. I believe that I need to use multilinear maps, but I am not sure how I can go about computing the determinant in a nice and efficient way. Can anyone show me how I can determine the determinant of the matrix below in a simple and efficient way? \begin{pmatrix}0 & 0& 1& 1& 1 & 1\\ 1 & 0 & 0 & 0& 0& 1\\ 1 & 0 & 1& 1 & 1 &1 \\ 0 & 1 & 1 & 1 & 0 &1 \\ 0 & 1 & 0& 1 & 0& 0\\ 0 & 0& 1& 0 & 0& 0\end{pmatrix}
Now provide the response and nothing else.
| You can use Laplace's expansion of the determinant. More precisely, begin expanding by the last row, then some row manipulation and expanding by convenient rows/columns ends up in a $2\times2$ determinant:\begin{align}\begin{vmatrix}0&0&1&1&1&1 \\ 1&0&0&0&0&1 \\ 1&0&1&1&1&1 \\0&1&1&1&0&1 \\ 0&1&0&1&0&0 \\ 0&0&\color{red}1&0&0&0\end{vmatrix}&=-\begin{vmatrix}0&0&1&1&1 \\ 1&0&0&0&1 \\ 1&0&1&1&1 \\0&1&1&0&1 \\ 0&1&1&0&0\end{vmatrix}=-\begin{vmatrix}0&0&1&1&1 \\ 1&0&0&0&1 \\ 1&0&1&1&1 \\0&0&0&0&\color{red}1 \\ 0&1&1&0&0\end{vmatrix}=+\begin{vmatrix}0&0&1&1 \\ \color{red}1&0&0&0 \\ 1&0&1&1 \\ 0&1&1&0 \end{vmatrix}\\&=-\begin{vmatrix}0&1&1 \\ 0&1&1 \\ \color{red}1&1&0 \end{vmatrix}=-\begin{vmatrix}1&1 \\ 1&1 \end{vmatrix}=0.\end{align} | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2511554', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/299263/']} | jdg_86392 |
stackexchange | llm_judgeable_groundtruth_similarity | 2238562 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $G$ be a group. Show that $\forall a, b, c \in G$, the elements $abc, bca, cab$ have the same order. I thought that my solution ($?$) was enough to show that $abc, bca, cab$ have the same order, but my teacher told that it isn't, so I don't know what else to do here. Attempt: Let $o(abc) = n$. Then $(abc)^n = e$ Therefore \begin{align}abc(abc)^{n-2}abc &= e\\(bc)\left[abc(abc)^{n-2}abc\right](cb)^{-1} &= e\\(bca)^n &=e\\bca(bca)^{n-2}bca &= e\\(ca)\left[abca(bca)^{n-2}bca\right](ac)^{-1} &=e\\(cab)^n &= e\end{align} Therefore $(abc)^n = (bca)^n = (cab)^n = e$ What else am I lacking after this?
Now provide the response and nothing else.
| In general, conjugate elements have the same order: $o(ghg^{-1}) = o(h)$ because $ x \mapsto gxg^{-1}$ is an automorphism. Now note that $bca = a^{-1} (abc) a$and$cab = c (abc) c^{-1}$are conjugates of $abc$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2238562', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/211806/']} | jdg_86393 |
stackexchange | llm_judgeable_groundtruth_similarity | 2372263 |
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 somehow got a weird result when proving it. Suppose $A \cup B = U$. Then by de Morgan's Law, $A^c \cap B^c = \emptyset$. Taking the intersection of both sides with $A$, $A\cap A^c \cap B^c = A \cap \emptyset = \emptyset$. $U \cap B^c = \emptyset$ $B^c = \emptyset$? $U$ is the universal set Where did I go wrong here?
Now provide the response and nothing else.
| It seems to me that the flaw occurs in this step:$$A\cap A^C\cap B^C=\varnothing\implies U\cap B^C=\varnothing$$Because it seems that you assumed $$A \cap A^C=U$$when, in reality,$$A\cap A^C=\varnothing$$because the intersection of any set with its complement is the empty set. You must have mistaken the $\cap$ for a $\cup$, because$$A\cup A^C=U$$really is a true statement. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2372263', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/424197/']} | jdg_86394 |
stackexchange | llm_judgeable_groundtruth_similarity | 965533 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $G$ be a group. A proper subgroup $H$ is called irreducible if $H$ can't be written as an intersection of two subgroups which contain it properly. I'd like to know if $(\mathbb Q,+)$ (and more general, any divisible abelian group) has irreducible subgroups.
Now provide the response and nothing else.
| How about the subgroup consisting of all fractions with odd denominator? Proof:Let $H$ be that subgroup of $\mathbb{Q}$, and let $K$ be any subgroup of $\mathbb{Q}$ containing $H$ properly. Then there exists an element $k$ of $K\setminus H$ which has to be of the form $k = \frac{u}{2^e v}$ where $e>0$ and $u$ and $v$ are odd and coprime. Since $u$ and $2^ev$ are coprime, there exist integers $a$ and $b$ with $a\cdot u+b\cdot 2^ev=1$. Now since $\mathbb{Z}\le H < K$, $K$ contains $avk+bv=(a\cdot u+b\cdot 2^e v)/2^e=1/2^e$. Therefore $K$ also contains $1/2$, i.e. the group $\langle H,1/2\rangle$ is contained in $K$, so $H$ is irreducible. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/965533', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/121097/']} | jdg_86395 |
stackexchange | llm_judgeable_groundtruth_similarity | 595469 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
MVVM is most commonly used with WPF because it is perfectly suited for it. But what about Windows Forms? Is there an established and commonly used approach / design pattern like this for Windows Forms too? One that works explicitly well with Windows Forms? Is there a book or an article that describes this well? Maybe MVP or MVC based?
Now provide the response and nothing else.
| I have tried MVP and it seems to work great with windows forms too.This book has an example of windows forms with MVP pattern (sample payroll application). The application is not that complex but will give you an idea about how to go about creating it. Agile Principles, Patterns, and Practices in C# ... You can get the source code at Source Code EDIT: There are two variations of the MVP pattern (a) Passive view and (b) supervising controller For complex databinding scenarios I prefer to go with the Supervising controller pattern.In supervising controller pattern the databinding responsibility rest with the view. So,for treeview/datagrid this should be in the respective views, only view agnostic logic should moved on to the presenter. I'll recommend having a look at the following MVP framework MVC# - An MVP framework Don't go by the name (it's an MVP framework). Simple winforms MVP video Winforms - MVP An example of dealing with dropdown list MVP - DropDownList Simple treeview binding example (poor man's binding). You can add any treeview specific logic in BindTree(). Below is the code snippet.... not tested, directly keyed in from thought.... public interface IYourView{ void BindTree(Model model);}public class YourView : System.Windows.Forms, IYourView{ private Presenter presenter; public YourView() { presenter = new YourPresenter(this); } public override OnLoad() { presenter.OnLoad(); } public void BindTree(Model model) { // Binding logic goes here.... }}public class YourPresenter{ private IYourView view; public YourPresenter(IYourView view) { this.view = view; } public void OnLoad() { // Get data from service.... or whatever soruce Model model = service.GetData(...); view.BindTree(model); }} | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/595469', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4227/']} | jdg_86396 |
stackexchange | llm_judgeable_groundtruth_similarity | 53956571 |
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 receive a get request using Flutter and HttpClient. This is complete code in what I'm trying to accomplish. getSuggest() async { try { var httpClient = new HttpClient(); var uri = new Uri.http( 'http://autocomplete.geocoder.api.here.com', '/6.2/suggest.json', { 'app_id': 'APP_ID', 'app_code': 'APP_CODE', 'query': '123 Main Street', 'country': 'USA', 'language': 'en', }); var request = await httpClient.getUrl(uri); var response = await request.close(); var responseBody = await response.transform(Utf8Decoder()).join(); Map data = jsonDecode(responseBody); print(data); } catch (error) { print(error); } } And I'm using import 'dart:io';import 'dart:convert'; But my code always gets sent to the print(error) and the error that gets printed is FormatException: Invalid radix-10 number Any ideas? Thanks!!
Now provide the response and nothing else.
| The problem is the scheme. You don't have to set it in Uri.http or Uri.https methods, it is set automatically, so change with the following: Uri.http( 'autocomplete.geocoder.api.here.com', '/6.2/suggest.json', { 'app_id': 'APP_ID', 'app_code': 'APP_CODE', 'query': '123 Main Street', 'country': 'USA', 'language': 'en', }); And I suggest using http package and do something like that: import 'package:http/http.dart' as http;import 'dart:convert';final json = const JsonCodec();getSuggest() async { try { var uri = Uri.http( 'autocomplete.geocoder.api.here.com', '/6.2/suggest.json', { 'app_id': 'APP_ID', 'app_code': 'APP_CODE', 'query': '123 Main Street', 'country': 'USA', 'language': 'en', }); var response = await http.get(uri); var data = json.decode(response.body); print(data); } catch (error) { print(error); } } and use its http client if you need to set much more things (e.g. User Agents ). | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/53956571', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4310761/']} | jdg_86397 |
stackexchange | llm_judgeable_groundtruth_similarity | 12672952 |
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 should extract data from an oracle database.How can I find out which schema are defined in the database?When I do not define any schema in the description of Metadata(), I find no tables.thanks for your help,
Now provide the response and nothing else.
| Default Oracle schema matches the username that was used in Oracle connection.If you don't see any tables - it means the tables are created in another schema. Looks like you have two questions here: 1) about Oracle schemas - how to find schema and tables in Oracle 2) about SQLAlchemy reflections - how to specify Oracle schema for table You can find answer for the first question in many places. I.e. here: https://stackoverflow.com/a/2247758/1296661 Answering second question:Table class constructor has schema argument to specify table's schema if it is different from default user's schema. See more here http://docs.sqlalchemy.org/en/rel_0_7/core/schema.html#sqlalchemy.schema.Table Here is the python code to answer second question. You will need to setup db connection and table name values to match your case: from sqlalchemy import Tablefrom sqlalchemy.ext.declarative import declarative_basefrom sqlalchemy import create_engineengine = create_engine('oracle://<user_name>:<password>@<hostname>:1521/<instance name>', echo=True)Base = declarative_base()reflected_table = Table('<Table name>', Base.metadata, autoload=True, autoload_with=engine, schema='<Schema name other then user_name>')print [c.name for c in reflected_table.columns]p = engine.execute("SELECT OWNER,count(*) table_count FROM ALL_OBJECTS WHERE OBJECT_TYPE = 'TABLE' GROUP BY OWNER");for r in p: print r Good luck with using sqlschema and reflection feature - it is a lot of fun. You get your python program working with existing database almost without defining schema information in your program. I'm using this feature with oracle db in production - the only thing I have to define were relations between tables explicitly setting foreign and primary keys. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12672952', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1711699/']} | jdg_86398 |
stackexchange | llm_judgeable_groundtruth_similarity | 284385 |
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:
Other than electrons, does light interact with the other subatomic particles? Also, do different elementary particles behave differently when interacting with light (X-rays or gammas)? Can you say, for example, that this is an up quark and this is charm?
Now provide the response and nothing else.
| Light, at the level of particles which you are asking, is composed out of a confluence of photons. Photons are elementary particles in the standard model of particle physics. These particles are at the underlying level of all matter as we presently know it. To first order, photons interact with the electromagnetic interaction with all charged particles in the table, and thus with all complex particles , atomic and molecular entities that contain them. For example the neutron is neutral, but the quarks contain in it are charged thus there is a first order interaction. Neutral elementary particles, other than the photon, are the neutrino and the Higgs. There is no first order interaction for these neutral elementary particles. But interactions of elementary particles go through higher order terms in the expansion for calculating the crossections. There exists photon-photon scattering whose crossection grows with energy. There also exists neutrino photon scattering through Z and W exchanges in higher order diagrams, this reaction is important for cosmological models. Equivalently there exists a higgs boson to two photon decay, so in cosmological studies the higher order diagrams would be again important. So the answer to your question is: Light interacts to first order ( higher crossections) with all charged elementary particles and through higher order diagrams with the neutral elementary particles. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/284385', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/12117/']} | jdg_86399 |
stackexchange | llm_judgeable_groundtruth_similarity | 3561388 |
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:
What is the interpretation of such statement: $$\mathbb P(X|Y) = \prod_{i=1}^{n} \mathbb P(X_i|Y)$$ where $X=(X_1, X_2, ..., X_n)$ ?
Now provide the response and nothing else.
| Let $n$ be a positive integer such that $n\equiv 3\pmod{4}$ . Then Ramanujan says that $$\zeta(n) =\frac{(2\pi)^n}{2(n+1)!}\sum_{k=0}^{(n+1)/2}(-1)^{k+1}\binom{n+1}{2k}B_{n+1-2k}B_{2k}-2S_{-}(n)$$ Further one should check the easily verifiable identity $$S_{-} (n, \alpha) - S_{+} (n, \alpha) =2S_{-}(n, 2\alpha)$$ where $$S_{\pm} (n, \alpha) =\sum_{k=1}^{\infty} \frac{1}{k^n(e^{2\alpha k} \pm 1)}$$ Using these results one can verify the identities given by Plouffe. The formula for the case when $n\equiv 1\pmod{4}$ is more complicated. Ramanujan deals with sums of type $\sum_{k\geq 1}k^nq^k/(1-q^k)$ for odd positive integer values of $n$ in great detail with simple proofs based on algebraic manipulation. Unfortunately he does not deal with negative odd values of $n$ in same manner. I believe he did have a proof based on algebraic manipulation which was far simpler than the later proofs based on Mellin Transform. You can also have a look at this paper by Bruce Berndt which gives some details and approaches to prove Ramanujan's formula. However a few key results have been provided here without proof. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3561388', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/685665/']} | jdg_86400 |
stackexchange | llm_judgeable_groundtruth_similarity | 15089190 |
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 find that using "aspnet_regiis" -pef or "aspnet_regiis -pe" to encrypt elements in web.cong works only on several elements and not the others. i.e. it works for "ConnectionStrings" and "appSettings" but not for "system.web" Can I encrypt all the elements somehow? Thanks.
Now provide the response and nothing else.
| You're having two separate problems here. Let's take the easy one first. javax.ejb.EJBTransactionRolledbackException: Entity not managed The List of objects returned by that query is not itself an Entity , and so you can't .refresh it. In fact, that's what the exception is complaining about. You're asking the EntityManager to do something with an object that is simply not a known Entity . If you want to .refresh a bunch of things, iterate through them and .refresh them individually. Refreshing the list of ItemStatus You're interacting with Hibernate's Session -level cache in a way that, from your question, you don't expect. From the Hibernate docs : For objects attached to a particular Session (i.e., in the scope of a Session)... JVM identity for database identity is guaranteed by Hibernate. The impact of this on Query.getResultList() is that you do not necessarily get back the most up to date state of the database. The Query you run is really getting a list of entity IDs that match that query. Any IDs that are already present in the Session cache are matched up to known entities, while any IDs that are not are populated based on database state. The previously known entities are not refreshed from the database at all. What this means is that in the case where, between two executions of the Query from within the same transaction, some data has changed in the database for a particular known entity, the second Query would not pick up that change. It would, however, pick up a brand new ItemStatus instance (unless you were using a query cache , which I assume you're not). Long story short: With Hibernate, whenever you want to, within a single transaction, load an entity and then pick up additional changes to that entity from the database, you must explicitly .refresh(entity) . How you want to deal with this depends a bit on your use case. Two options I can think of off the bat: Have are to have the DAO tied to the lifespan of the transaction, and lazily initialize the List<ItemStatus> . Subsequent calls to DAO.refreshList iterate through the List and .refresh(status) . If you also need newly added entities, you should run the Query and also refresh the known ItemStatus objects. Start a new transaction. Sounds like from your chat with @Perception though that that is not an option. Some additional notes There was discussion about using query hints. Here's why they didn't work: org.hibernate.cacheable=false This would only be relevant if you were using a query cache , which is only recommended in very particular circumstances. Even if you were using it though, it wouldn't affect your situation because the query cache contains object IDs, not data. org.hibernate.cacheMode=REFRESH This is a directive to Hibernate's second-level cache . If the second-level cache were turned on, AND you were issuing the two queries from different transactions, then you would have gotten stale data in the second query, and this directive would have resolved the problem. But if you're in the same Session in the two queries, the second level cache would only come in to play to avoid database loading for entities that are new to this Session . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15089190', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/450602/']} | jdg_86401 |
stackexchange | llm_judgeable_groundtruth_similarity | 2282181 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Every single flavor of regex I have ever used has always had the "." character match everything but a new line (\r or \n)... unless, of course, you enable the single-line flag. So when I tried the following C# code I was shocked: Regex rgx = new Regex(".");if (rgx.Match("\r\n").Success) MessageBox.Show("There is something rotten in the state of Redmond!"); It showed the message. Just to make sure I wasn't going insane, I tried the following JavaScript code: if (/./.test("\r\n")) alert("Something's wrong with JavaScript too."); The JavaScript didn't show the message, meaning it's working exactly as it should. Apparently, the "." character in .NET is matching the "\r" character. I checked the documentation to see if the mention anything about it: Wildcard: Matches any single character except \n. Wow... since when does a Regex flavor ever have the dot match a carriage return? You would think .NET would behave like all the rest of the Regex flavors... especially because it's in a Windows environment which uses "\r\n" as line delimiters. Is there any flag/setting I can enable to make it work as it does in other Regex flavors? Are there any alternative solutions which don't involve replacing all . characters with [^\r\n] ?
Now provide the response and nothing else.
| I ran into this same issue when writing Regex Hero. It is a little bizarre. I blogged about the issue here . And that led to me adding a feature to the tester to enable/disable CRLFs. Anyway, for some reason Microsoft chose to use \n (line feeds) to mark line endings. (UPDATE) The reason must be related to this: Microsoft .NET Framework regular expressions incorporate the most popular features of other regular expression implementations such as those in Perl and awk. Designed to be compatible with Perl 5 regular expressions , .NET Framework regular expressions include features not yet seen in other implementations, such as right-to-left matching and on-the-fly compilation. http://msdn.microsoft.com/en-us/library/hs600312.aspx And as Igor noted, Perl has the same behavior. Now, the Singleline and Multiline RegexOptions change behavior based around dots and line feeds. You can enable the Singleline RegexOption so that the dot matches line feeds. And you can enable the Multiline RegexOption so that ^ and $ mark the beginning and end of every line (denoted by line feeds). But you can't change the inherent behavior of the dot (.) operator to match everything except for \r\n. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2282181', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/35690/']} | jdg_86402 |
stackexchange | llm_judgeable_groundtruth_similarity | 1202391 |
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 game I am working on that has homing missiles in it. At the moment they just turn towards their target, which produces a rather dumb looking result, with all the missiles following the target around. I want to create a more deadly flavour of missile that will aim at the where the target "will be" by the time it gets there and I am getting a bit stuck and confused about how to do it. I am guessing I will need to work out where my target will be at some point in the future (a guess anyway), but I can't get my head around how far ahead to look. It needs to be based on how far the missile is away from the target, but the target it also moving. My missiles have a constant thrust, combined with a weak ability to turn. The hope is they will be fast and exciting, but steer like a cow (ie, badly, for the non HitchHiker fans out there). Anyway, seemed like a kind of fun problem for Stack Overflow to help me solve, so any ideas, or suggestions on better or "more fun" missiles would all be gratefully received. Next up will be AI for dodging them ...
Now provide the response and nothing else.
| What you are suggesting is called "Command Guidance" but there is an easier, and better way. The way that real missiles generally do it (Not all are alike) is using a system called Proportional Navigation. This means the missile "turns" in the same direction as the line-of-sight (LOS) between the missile and the target is turning, at a turn rate "proportional" to the LOS rate... This will do what you are asking for as when the LOS rate is zero, you are on collision course. You can calculate the LOS rate by just comparing the slopes of the line between misile and target from one second to the next. If that slope is not changing, you are on collision course. if it is changing, calculate the change and turn the missile by a proportionate angular rate... you can use any metrics that represent missile and target position. For example, if you use a proportionality constant of 2, and the LOS is moving to the right at 2 deg/sec, turn the missile to the right at 4 deg/sec. LOS to the left at 6 deg/sec, missile to the left at 12 deg/sec... In 3-d problem is identical except the "Change in LOS Rate", (and resultant missile turn rate) is itself a vector, i.e., it has not only a magnitude, but a direction (Do I turn the missile left, right or up or down or 30 deg above horizontal to the right, etc??... Imagine, as a missile pilot, where you would "set the wings" to apply the lift... Radar guided missiles, which "know" the rate of closure. adjust the proportionality constant based on closure (the higher the closure the faster the missile attempts to turn), so that the missile will turn more aggressively in high closure scenarios, (when the time of flight is lower), and less aggressively in low closure (tail chases) when it needs to conserve energy.Other missiles (like Sidewinders), which do not know the closure, use a constant pre-determined proportionality value). FWIW, Vietnam era AIM-9 sidewinders used a proportionality constant of 4. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1202391', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4012/']} | jdg_86403 |
stackexchange | llm_judgeable_groundtruth_similarity | 6435046 |
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 his seminal paper, Self-stabilizing systems in spite of distributed control . However, I don't quite get how the self-stabilizing algorithm works. I am most interested in his, 'solution' of k-state machines. The density of the paper is quite intense and I can't make much sense of it. How does this algorithm work in plain English?
Now provide the response and nothing else.
| I can try to explain it in plain English... First you should have a look at the link Jean-Francois Corbett wrote as a comment. Definition (from Wikipedia) A system is self-stabilizing if and only if: Starting from any state, it is guaranteed that the system will eventually reach a correct state (convergence). Given that the system is in a correct state, it is guaranteed to stay in a correct state, provided that no fault happens (closure). Notations Same as the one on the seminar paper Self Stabilizing system In his paper Dijkstra defines a self stabilizing system as follow: Consider a circle graph with N+1 nodes. (From 0 to N+1) Each node can be in different states. Each node can have different privilege. (for example xS = xR can be a privilege) At each step if in one node a privilege is present we will apply a certain rule : if privilege then "what to do" endif Legitimate States He defines a legitimate state to be a state with only one privilege present. Conclusion If you apply the different rules in Dijkstra's paper for the described system you will get a self-stabilizing system. (cf definition.) i.e. from any state with n privilege presents (even with multiple privileges for one node) you will reach in a finite number of states a state with only one privilege present, and stay in legitimate states after this state. And you will be able to reach any legitimate state. You can try yourself with a simple example. Example for the 4 states solution Let's take only a bottom node and a top node: starting point: (upT,xT) = (0,0) and (upB,xB) = (1,0)state1: (upT,xT) = (0,0) and (upB,xB) = (1,1) only one privilege present on B => legitimatestate2: (upT,xT) = (0,1) and (upB,xB) = (1,1) only one privilege present on T => legitimatestate3: (upT,xT) = (0,1) and (upB,xB) = (1,0) only one privilege present on B => legitimatestate4: (upT,xT) = (0,0) and (upB,xB) = (1,0) only one privilege present on T => legitimate and here is a result for 3 nodes: bottom (0) middle (1) top (2): I start with 2 privileges (not legitimate state, then once I get into a legitimate state I stay in it): {0: [True, False], 1: [False, False], 2: [False, True]}privilege in bottomprivilege in top================================{0: [True, True], 1: [False, False], 2: [False, False]}first privilege in middle================================{0: [True, True], 1: [True, True], 2: [False, False]}privilege in top================================{0: [True, True], 1: [True, True], 2: [False, True]}second privilege in middle================================{0: [True, True], 1: [False, True], 2: [False, True]}privilege in bottom================================{0: [True, False], 1: [False, True], 2: [False, True]}first privilege in middle================================{0: [True, False], 1: [True, False], 2: [False, True]}privilege in top================================{0: [True, False], 1: [True, False], 2: [False, False]}second privilege in middle================================{0: [True, False], 1: [False, False], 2: [False, False]}privilege in bottom... etc Here is a small python code (I am not very good at python so it's may be ugly) to test the 4 states methods with a system of n nodes, it stops when you find all the legitimate states: from copy import deepcopyimport randomn=int(raw_input("number of elements in the graph:"))-1L=[]D={}D[0]=[True,random.choice([True,False])]for i in range(1,n): D[i]=[random.choice([True,False]),random.choice([True,False])]D[n]=[False,random.choice([True,False])]L.append(D)D1=deepcopy(D)def nextStep(G): N=len(G)-1 print G Temp=deepcopy(G) privilege=0 if G[0][1] == G[1][1] and (not G[1][0]): Temp[0][1]=(not Temp[0][1]) privilege+=1 print "privilege in bottom" if G[N][1] != G[N-1][1]: Temp[N][1]=(not Temp[N][1]) privilege+=1 print "privilege in top" for i in range(1,N): if G[i][1] != G[i-1][1]: Temp[i][1]=(not Temp[i][1]) Temp[i][0]=True print "first privilege in ", i privilege+=1 if G[i][1] == G[i+1][1] and G[i][0] and (not G[i+1][0]): Temp[i][0]=False print "second privilege in ", i privilege+=1 print "number of privilege used :", privilege print '================================' return TempD=nextStep(D)while(not (D in L) ): L.append(D) D=nextStep(D) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6435046', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_86404 |
stackexchange | llm_judgeable_groundtruth_similarity | 86008 |
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:
This question (in Lagrangian mechanics) might be silly, but why is the Lagrangian $L$ defined as: $L = T - V$ ? I understand that the total mechanical energy of an isolated system is conserved, and that energy is: $E = T + V$ . This makes good sense to me, but why would we subtract $V$ from $T$ in the expression of the Lagrangian? What does the Lagrangian represent, after all? Every text or reference I consult just glosses over that and presents $L = T - V$ without explaining anything... Background: In classical mechanics class, there are often multiple ways to solve the problem at hand. For example, if the problem at hand is the motion of a physical pendulum, or some Atwood machine, you can solve by figuring out the forces, moments, and applying Newton's law. But you can also solve by considering that the total mechanical energy is conserved. Usually, it's faster that way. Then there is a third way, which would be to write the Lagrangian of the system and use Euler-Lagrange's equation. I am trying to understand how the third method should be interpreted and compared to the second one.
Now provide the response and nothing else.
| We have to point out some simple remark of capital importance. First of all, the lagrangian is not defined as $L = T - V$ . This turns out to be true only on a riemannian manifold; the fact this is almost always true in classical mechanics is an "accident" due to the postulates of classical (non relativistic) mechanics. For the most precise definition of the lagrangian, see my answer to this question . Here we are interested to the fact the lagrangian is by definition the function that satisfies the Euler-Lagrange equations along the curves of motions and so reproduce the equations of motion. In fact, if you follow, for example, Landau's treatment (see References), you can see how the form of lagrangian is established from a physical point of view. Assume the action principle and denote with $S$ the action for our system and with $q$ the set of generalized coordinates we are using. Then the lagrangian is, by definition, the function such that the integral $$S = \int_{t_0}^{t_1} L( \dot q, q, t ) \mbox{d}t$$ get an extremal value along the trajectories of the motion. By varying $S$ , we find Euler-Langrange equations and the fact that $L$ is defined up to a total derivative with respect to time of an arbitrary differentiable function of time and coordinates, $f(q,t)$ . Why is $L$ a function of $\dot q, q$ and $t$ but not, for example, of $\ddot q$ ? Because newtonian mechanics postulates state that the state of a system is completely determined by the knowledge of all positions and velocities of its constituents at a given instant. Now we would establish the functional form of $L$ . In order to do this, we consider the galilean postulate of relativity. We can rephrase it in a more suitable form for our goals: Postulate(Galilean relativity) There exists a class of frame of reference respect to which the space is homogeneus and isotropic. In those frames, equations of motion retain the same form. Consider a free-moving particle in an inertial frame of reference. Let's indicate with $\mathbf{r}$ its position and with $\mathbf{v}$ its velocity in such a frame. Since there are no preferred points in the space (nor in time: time flows in the same manner for all observers - i.e. in all frames - in newtonian mechanics), $L$ can't depend on $\mathbf{r}$ or $t$ . So it is a function of $\mathbf{v}$ only. Moreover, in virtues of absence of preferred directions, it depends only on $v^2$ . Hence $L = L(v^2)$ . It follows that $$ \frac{\partial L}{\partial{\mathbf{r}}} = 0 \implies \frac{\mbox{d}}{\mbox{d}t} \frac{\partial L}{\partial{\mathbf v}} = 0$$ . This implies that $\mathbf{v} = \mbox{constant}$ also. From here we obtain Galilei's transformations. Take two inertial frames of reference, $K$ and $K'$ , moving one respect to other with a small velocity $\mathbf{a}$ . In $K'$ lagrangian is $L'(v'^2)$ , while in $K$ is $L(v^2)$ . Since the form of equation of motion must be the same, $$L'(v'^2) = L(v^2) = L(v^2 + 2\mathbf{a \cdot v} + a^2)$$ Expanding the last member in series of powers of $\mathbf{a}$ and retaining only the first order term, we get $$L'(v'^2) = L(v^2) + \frac{\partial L}{\partial{v^2}} 2 \mathbf{a \cdot v}.$$ The last term in RHS is a total derivative with respect to time. From the above remark, this means that $\frac{\partial L}{\partial{v^2}}$ can't depend on $v^2$ and hence $$L = a v^2.$$ We reproduce known equation of motion for a free moving particle if we set $a=m/2$ . Now, if we take a compound system and we separate its constituents in such a way that interactions turn out to be negligible, then for each constituent we can write a free-body lagrangian and the lagrangian for the whole system will the sum of all of them. This means that the free-body lagrangian (in an inertial frame of reference) enjoys the expected characteristics for a kinetic energy. Finally, consider a system in which interactions between particles are not negligible. We make the following ansatz: $$L = \sum_\alpha \frac{m_\alpha v_\alpha^2}{2} - V( \mathbf{r_1,r_2 \dots} ).$$ ( $V$ is a differentiable function of coordinate.)Using Euler-Langrange equations, we get $$m_\alpha \frac{\mbox{d}\mathbf{v}_\alpha}{\mbox{d}t} = -\frac{\partial V}{\partial \mathbf{r_\alpha}},$$ that is Newton's Second Law. (at least when masses are fixed.) So our ansatz works. We have to note that in order to derive the form of $L$ , we have used the postulates of newtonian mechanics. So our result is no longer valid when those do not apply. In particular, $L = T - V$ is only a particular case and is not a good definition for $L$ . A side question is: does $L$ have a physical significance? No . We measurethe equations of motion, not the lagrangian! So the form of $L$ is not important, provided that it reproduces the equations of motion. Now, the energy. I think you would mean that the hamiltonian, often written as $H = T + V$ , makes more sense. In effect, energy is measured quantity, but the hamiltonian is not defined as $H = T + V$ . It is, by definition, the Legendre transform of $L$ with respect to $\mathbf{v}$ ( $\dot q$ in general). It turns out to be the energy only in the case $L = T - V$ and, in addition , $T$ takes the form $T = \sum_{i,j} a_{ij}(q, t) \dot q_i \dot q_j$ , i.e. is a symmetric quadratic form in $\dot q$ whose coefficients are function of $q$ and $t$ only and are symmetric in $i,j$ . References L. Landau, E. Lifshitz, Mechanics V. Arnold, Mathematical methods of classical mechanics | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/86008', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/9604/']} | jdg_86405 |
stackexchange | llm_judgeable_groundtruth_similarity | 22031128 |
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 entity and a Junit, I want to test that update method is working fine, but when I invoke save method from CrudRepository I get a new entry in my table instead of the updated entity. This is my entity: @Entity(name = "PERSON")public class Person { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "PERSON_ID") private Integer id; @Column(name = "FIRST_NAME") private String firstName; @Column(name = "LAST_NAME") private String lastName;//getters and setters} This is my service class: @Servicepublic class PersonServiceImpl implements PersonService { @Autowired private PersonRepository personRepository; @Override public Person updatePerson(Person oldPerson) throws Exception { return personRepository.save(oldPerson); }} This is my repository public interface PersonRepository extends CrudRepository<Person, String> {} This is my test: @RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(classes = { JPAConfigurationTest.class })@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)@Transactionalpublic class UpdatePersonServiceIntegrationTest { @Autowired PersonService personService; @Before public void setUp() throws Exception { Person person = new Person(1); person.setFirstName("Nicolas"); person.setLastName("Spessot"); personService.createPerson(person); //This invokes save } @Test public void updatingPerson() throws Exception{ Person person = new Person(1); person.setFirstName("Juan"); person.setLastName("Riquelme"); personService.updatePerson(person); Person retrieved = personService.retrievePerson(1); //This invokes findOne assertEquals(1, person.getId()); assertEquals("Juan", person.getFirstName()); assertEquals("Riquelme", person.getLastName()); }} Thanks in advance
Now provide the response and nothing else.
| The problem is in your updatePerson method in your service class. Specifically: return personRepository.save(oldPerson); All you are currently doing is saving a Person. That's why it is creating a second entry. What you should do is find the oldPerson first, Person p = personRepository.findOne(oldPerson.getId()) then update its attributes, and then save it like you did before.Hope that helps. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22031128', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3219470/']} | jdg_86406 |
stackexchange | llm_judgeable_groundtruth_similarity | 23221557 |
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 enter a decimal point in a text box. I want to restrict the user by entering more than 2 digits after the decimal point. I have written the code for achieving that in the Keypress event. function validateFloatKeyPress(el, evt) { var charCode = (evt.which) ? evt.which : event.keyCode; if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) { return false; } if (charCode == 46 && el.value.indexOf(".") !== -1) { return false; } if (el.value.indexOf(".") !== -1) { var range = document.selection.createRange(); if (range.text != ""){ } else { var number = el.value.split('.'); if (number.length == 2 && number[1].length > 1) return false; } } return true;}<asp:TextBox ID="txtTeamSizeCount" runat="server" onkeypress="return validateFloatKeyPress(this,event);" Width="100px" MaxLength="6"></asp:TextBox> The code is working but the issue is: if I enter ".75" and then change it to "1.75" , it is not possible. Only way to do it is delete it completely and then type "1.75" . This issue occurs if there are already 2 digits after decimal in the textbox. The conditions that I impose are a) After decimal is present, it must at least have 1 or 2 digits. For ex .75 or .7 or 10.75 or 333.55 or 333.2 is accepted. but not .753 or 12.3335 b) Before the decimal, it not a must for the user to enter a value. User must also be able to enter integer numbers also. Can you tell me what could be the issue? Thanks, Jollyguy
Now provide the response and nothing else.
| You were almost there. Just check that there are no more than 2 characters after the decimal. UPDATE 1 - check carat position to allow character insertion before the decimal. UPDATE 2 - correct issue pointed out by ddlab's comment and only allow one dot. function validateFloatKeyPress(el, evt) { var charCode = (evt.which) ? evt.which : event.keyCode; var number = el.value.split('.'); if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) { return false; } //just one dot (thanks ddlab) if(number.length>1 && charCode == 46){ return false; } //get the carat position var caratPos = getSelectionStart(el); var dotPos = el.value.indexOf("."); if( caratPos > dotPos && dotPos>-1 && (number[1].length > 1)){ return false; } return true;}//thanks: http://javascript.nwbox.com/cursor_position/function getSelectionStart(o) { if (o.createTextRange) { var r = document.selection.createRange().duplicate() r.moveEnd('character', o.value.length) if (r.text == '') return o.value.length return o.value.lastIndexOf(r.text) } else return o.selectionStart} http://jsfiddle.net/S9G8C/1/ http://jsfiddle.net/S9G8C/203/ | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/23221557', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3380088/']} | jdg_86407 |
stackexchange | llm_judgeable_groundtruth_similarity | 43211390 |
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 create this top header using flexbox. Basically I would like to center the <div class="header-title"> (Institution institution 1) on the line with the 3 other elements you see. (Institutioner, Ledere and Log ud) like you see on the image. .nav { background: #e1e1e1;}ol, ul { list-style: none; display: flex; flex-direction: row; align-items: center; justify-content: flex-start;}.header-title { justify-content: center; align-self: center; display: flex;}.nav ul li.logout { margin-left: auto;}.nav ul li a { text-decoration: none; padding: 0px 20px; font-weight: 600;} <div class="nav mobilenav"> <div class="header-title"> Institution institution 1 </div> <ul> <li><a href="/institutions/">Institutioner</a></li> <li> <a href="/leaders/">Ledere</a> </li> <li class="logout"> <a class="button-dark" href="/user/logout">Log ud</a> </li> </ul></div> Demo - JSFiddle
Now provide the response and nothing else.
| Use nested flex containers and flex-grow: 1 . This allows you to create three equal-width sections on the nav bar. Then each section becomes a (nested) flex container which allows you to vertically and horizontally align the links using flex properties. Now the left and right items are pinned to the edges of the container and the middle item is perfectly centered (even though the left and right items are different widths). .nav { display: flex; height: 50px; /* optional; just for demo */ background: white;}.links { flex: 1; /* shorthand for: flex-grow: 1, flex-shrink: 1, flex-basis: 0 */ display: flex; justify-content: flex-start; align-items: center; border: 1px dashed red;}.header-title { flex: 1; display: flex; justify-content: center; align-items: center; border: 1px dashed red;}.logout { flex: 1; display: flex; justify-content: flex-end; align-items: center; border: 1px dashed red;}.links a { margin: 0 5px; text-decoration: none;} <div class="nav mobilenav"> <div class="links"> <a href="/institutions/">Institutioner</a> <a href="/leaders/">Ledere</a> </div> <div class="header-title">Institution institution 1</div> <div class="logout"><a class="button-dark" href="/user/logout">Log ud</a></div></div> jsFiddle | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/43211390', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2554631/']} | jdg_86408 |
stackexchange | llm_judgeable_groundtruth_similarity | 22157456 |
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 extending Object like this: Object.prototype.is_a = function (x) { return this instanceof x;} All works as expected "foo".is_a(String) // true"foo".is_a(Object) // true"foo".is_a(Array) // false"foo".is_a(Function) // false"foo".is_a(Boolean) // false"foo".is_a(Date) // false"foo".is_a(Number) // false"foo".is_a(RegExp) // false but, when "foo" instanceof String // false this keyword on the is_a() function is same as foo right? Why does it return different results?
Now provide the response and nothing else.
| First of all, you cannot apply instanceof to primitive values, that's why "foo" instanceof String returns false . Primitives are not objects and hence cannot be an instance of a constructor function. * So why does it seem to work inside the is_a method? In non-strict mode, the value of this inside a function is always going to be an object (step 3). If this value is not an object, it is implicitly converted to one. You can test this with console.log(typeof this) . That means that the string primitive "foo" is converted to an String object new String("foo") and that's why you can use instanceof on it. In strict mode, the value of this doesn't have to be an object and is not automatically converted ( step 1 ). Your method would fail in that case: > Object.prototype.is_a = function (x) { 'use strict'; return this instanceof x; }> "foo".is_a(String)false *: That's a very simplified explanation. In reality, the instanceof operator delegates the evaluation to the constructor function's internal [[HasInstance]] method , which is defined to return false if the passed value is not an object. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22157456', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3376568/']} | jdg_86409 |
stackexchange | llm_judgeable_groundtruth_similarity | 6595 |
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:
$$\lim_{\epsilon \to 0} \int \frac1{x^{1+\epsilon}} \mathrm dx$$ How should I go about evaluating this integral?Does this integral converge to $\log_e x $ or to something else?
Now provide the response and nothing else.
| As it stands, the limit doesn't exist (see Tobias's answer).But if you consider the definite integral from 1 to $x$,then the limit is $\ln x$:$$ \int_1^x \frac{dt}{t^{1+\epsilon}} =\left[ \frac{t^{-\epsilon}}{-\epsilon} \right]_1^x =\frac{1-x^{-\epsilon}}{\epsilon} =\frac{1-e^{-\epsilon \ln x}}{\epsilon} =\frac{1-(1-\epsilon \ln x+O(\epsilon^2))}{\epsilon}\to \ln x$$as $\epsilon\to 0$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/6595', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/1798/']} | jdg_86410 |
stackexchange | llm_judgeable_groundtruth_similarity | 19057835 |
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 any way we can find about all the connected client details(IP & name) from another client? I know there is a topic "$SYS/broker/clients/active" which gives the number of currently connected clients but if I want to know more about each connected client, is there any way? I'm developing a solution where number of client will be connected (using Wireless network) to MQTT broker located on a server. I will also have another client running on the same machine and connected to the broker which will observe if any new client connected with the broker or for a gets disconnected client. I can see message on broker console when a new client connects or connected client gets disconnected. Can we get something similar from a client connected to the broker? Please suggest what would be the best possible way to achieve this? Thanks in advance. -Dilip
Now provide the response and nothing else.
| Your original question, nor responses to subsequent questions identify which broker implementation you are using. So there may be a more efficient answer to your question. Without that information, let's focus on what you can do in the protocol itself. MQTT supports RETAINED messages. This is where the broker will store the most recent retained message against each topic. When a client subscribes to the topic, it will receive the retained message (if one exists). There is also the Last Will and Testament (LWT) feature (that goetzchr refers to), that can be used to publish a message on behalf of the client if it abnormally disconnects. Combining these two features allows you to build a simple presence service on the broker, all within the protocol. It works like this: when a client connects, it publishes a RETAINED message to a topic unique to it, for example: clients/my_client_id/state with a payload of 1 . (substituting my_client_id with the client's own id. it also, on connect, sets a LWT message to be published to the same topic, but with a payload of 0 . This should also be a RETAINED message. when a client disconnects cleanly, it publishes a RETAINED message to the same topic with a payload of 0 This allows another client to subscribe to clients/# to receive all the messages indicating the changes in clients' connection state (the full topic identifying the client, and the value of the payload indicating the connection state). To obtain more information than just connected state, the clients can publish another retained message on connect, to another topic, eg clients/my_client_id/info that contains all of the information you're interested in. This only works if you have control of all the clients that are connecting to your broker and able to get them to behave like this. This is not an ideal approach; hopefully your broker implementation will provide some server-side means of doing this. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19057835', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2799257/']} | jdg_86411 |
stackexchange | llm_judgeable_groundtruth_similarity | 870253 |
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:
It is known that the distance between the centroid (center of mass) and the center of a unit semicircle is $\displaystyle\frac{4}{3\pi}$, whereas that of a unit hemisphere is $\displaystyle\frac{3}{8}$. I am interested in determining a closed general formula for the centroid of a unit n-hemisphere. I did some calculations and obtained $$\displaystyle\frac{1}{\sqrt{\pi}}\frac{\Gamma{(\frac{n+2}{2}})}{\Gamma{(\frac{n+3}{2}})}$$ which for $n=1, 2, 3, 4....$ gives the values $\displaystyle\frac{1}{2}, \frac{4}{3\pi},\frac{3}{8},\frac{16}{15\pi}....$. I obtained this formula using the Pappus' centroid theorem for the volume of solids of revolution, but would be happy to have confirmation of this by a proof based on integral calculations. I found a previous question on this topic, but no closed form expression was provided in the answer. If confirmed, an interesting and somewhat unexpected consequence of this formula would be that because $$\lim_{n \to \infty} \displaystyle\frac{1}{\sqrt{\pi}}\frac{\Gamma{(\frac{n+2}{2}})}{\Gamma{(\frac{n+3}{2}})}=0$$then the centroid of a n-hemisphere and that of the whole n-sphere tend to coincide as $n$ increases. Is this interpretation correct? Any hint would be very appreciated.
Now provide the response and nothing else.
| Yes, your consequence is correct. This is a manifestation of the concentration of measure phenomenon , which in the case of the sphere means that for any $\epsilon>0$ larger and larger fraction of its volume is concentrated in the $\epsilon$-neighborhood of the sphere's equator as $n\to\infty$. More informally, asymptotically almost all of sphere's volume is located near its equatorial section, and parts of the sphere away from it contribute almost nothing to the location of the centroid. But the same is true for the hemisphere, hence the coincidence in the limit. This is somewhat counterintuitive but can be explained like this. The unit sphere is specified by the equation $x_1^2+x_2^2+\dots x_n^2=1$, to get the hemisphere we also constrain $x_n\geq0$. But heuristically the more variables we have the less effect constraints on any individual variable have on the collective result, in this case location of the centroid or the volume. This idea is the basis for the measure concentration in general, which has many applications, there is a whole book about it. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/870253', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/90997/']} | jdg_86412 |
stackexchange | llm_judgeable_groundtruth_similarity | 4689090 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
this is the workflow I currently use for my svn projects (I never use svn branches, and some projects are actively worked on by other people as well): on the server, do the inital git svn fetch which might take hours. Also create a 'build' branch. on a development machine cloning is now fast: git clone srv://project.git, git checkout build followed by git update-refs ..., git svn fetch to restore the link to the svn repository work, commit, work commit, ... to check if things are sane, git push build to the server and trigger a build in Hudson for that branch to store work so that I can work on it from another machine, also push build branch when satisfied, join commits together in logical steps (eg one for each bug), commit to svn and reset everything like git checkout master, git merge build, git svn dcommit, git push, git checkout build, git rebase master, git push build Enter svn externals. I tried every script here already but all of them fail. My externals are setup like this: /path/to/x x/path/to/y/z y/z/path/to/a/b.file a/b.file and the scripts do things like trying to create /path/to/x in the root of the filesystem and git svn fetch /path/to/x . Also the single files seem to cause more problems. (subquestion 1: what is the svn:externals format these scripts were written for then?) It doesn't seem to hard modifying one of the scripts to handle my situation and replicate the directory structure I'm after correctly, but then I'm left with a major problem: if I change a file in both x and y/z directories, I don't see a way to join this into a single svn commit and that is one of the reasons I started using git in the first place. Hence the question: is there a way I can replicate the above workflow, using only parts of a certain svn repository, in such a way that I can do svn dcommit in the root? I'd prefer a ready-to-use solution that works both on linux and windows. edit I quickly hacked through one of the scripts I found and made it replicating the directory structure of the svn externals. I cannot clone single files though, here's output: git svn clone -r HEAD srv://svn/repo/path/to/projects.slnInitialized empty Git repository in xxx/projects.sln/.git/Invalid filesystem path syntax: REPORT request failed on '/svn/repo/!svn/vcc/default': Cannot replace a directory from within at yyy/git/libexec/git-core/git-svn line 5114 subquestion 2: is it not possible fetching a single file through git svn?
Now provide the response and nothing else.
| Unfortunately, svn's externals are quite flexible. I've run across a number of scripts that treat them as <path> <url>, but <url> <path> is also allowed. So I think some of the scripts are just broken in that regard. To answer your second subquestion: no. 'git svn fetch' needs to operate on a subtree of Subversion's repo, but it needs to be something it can treat like a branch. The only thing map well into that paradigm is a directory (trunk/, for example). FWIW, Bazaar and Mercurial suffer here too. At the end of the day, Subversion is just a versioned file system, whereas Git has a first class concept of a branch. This is one of those mismatches getting in the way. :-( | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4689090', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/128384/']} | jdg_86413 |
stackexchange | llm_judgeable_groundtruth_similarity | 47844808 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to write a DataFrame into Hive table (on S3 ) in Overwrite mode (necessary for my application) and need to decide between two methods of DataFrameWriter (Spark / Scala). From what I can read in the documentation , df.write.saveAsTable differs from df.write.insertInto in the following respects: saveAsTable uses column-name based resolution while insertInto uses position-based resolution In Append mode, saveAsTable pays more attention to underlying schema of the existing table to make certain resolutions Overall, it gives me the impression that saveAsTable is just a smarter version of insertInto . Alternatively, depending on use-case, one might prefer insertInto But do each of these methods come with some caveats of their own like performance penalty in case of saveAsTable (since it packs in more features)? Are there any other differences in their behaviours apart from what is told (not very clearly) in the docs? EDIT-1 Documentation says this regarding insertInto Inserts the content of the DataFrame to the specified table and this for saveAsTable In the case the table already exists, behavior of this function depends on the save mode, specified by the mode function Now I can list my doubts Does insertInto always expect the table to exist? Do SaveMode s have any impact on insertInto ? If above answer is yes, then what's the differences between saveAsTable with SaveMode.Append and insertInto given that table already exists? does insertInto with SaveMode.Overwrite make any sense?
Now provide the response and nothing else.
| DISCLAIMER I've been exploring insertInto for some time and although I'm far from an expert in this area I'm sharing the findings for greater good. Does insertInto always expect the table to exist? Yes (per the table name and the database). Moreover not all tables can be inserted into, i.e. a (permanent) table, a temporary view or a temporary global view are fine, but not: a bucketed table an RDD-based table Do SaveModes have any impact on insertInto? (That's recently been my question, too!) Yes, but only SaveMode.Overwrite . After you think about insertInto the other 3 save modes don't make much sense (as it simply inserts a dataset). what's the differences between saveAsTable with SaveMode.Append and insertInto given that table already exists? That's a very good question! I'd say none, but let's see by just one example (hoping that proves something ). scala> spark.versionres13: String = 2.4.0-SNAPSHOTsql("create table my_table (id long)")scala> spark.range(3).write.mode("append").saveAsTable("my_table")org.apache.spark.sql.AnalysisException: The format of the existing table default.my_table is `HiveFileFormat`. It doesn't match the specified format `ParquetFileFormat`.; at org.apache.spark.sql.execution.datasources.PreprocessTableCreation$$anonfun$apply$2.applyOrElse(rules.scala:117) at org.apache.spark.sql.execution.datasources.PreprocessTableCreation$$anonfun$apply$2.applyOrElse(rules.scala:76)...scala> spark.range(3).write.insertInto("my_table")scala> spark.table("my_table").show+---+| id|+---+| 2|| 0|| 1|+---+ does insertInto with SaveMode.Overwrite make any sense? I think so given it pays so much attention to SaveMode.Overwrite . It simply re-creates the target table. spark.range(3).write.mode("overwrite").insertInto("my_table")scala> spark.table("my_table").show+---+| id|+---+| 1|| 0|| 2|+---+Seq(100, 200, 300).toDF.write.mode("overwrite").insertInto("my_table")scala> spark.table("my_table").show+---+| id|+---+|200||100||300|+---+ | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/47844808', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3679900/']} | jdg_86414 |
stackexchange | llm_judgeable_groundtruth_similarity | 144751 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there anybody who can help me to prove that if $D$ is countable, and $f$ is a function whose domain is $D$, then $f(D)$ is either finite or countable?
Now provide the response and nothing else.
| Recall that $f$ is a collection of ordered pairs such that if $\langle a,b\rangle$ and $\langle a,c\rangle$ are both in $f$ then $b=c$. Furthermore, $f(D)=\{b\mid\exists a\in D:\langle a,b\rangle\in f\}$. Since for every $a\in D$ there is at most one ordered pair in $f$ in which $a$ appears in the left coordinate, we can define an injective function from $f(D)$ into $D$. Suppose $D=\{d_n\mid n\in\mathbb N\}$, then for $b\in f(D)$ define $\pi(b)=d_n$ where $n=\min\{k\in\mathbb N\mid f(d_k)=b\}$. You should verify that this is indeed an injective function. Recall that if we have an injective function from $A$ into $B$ then $|A|\leq |B|$ and if $|B|$ is countable then $A$ must be countable (or finite). From here the proof is about done. In fact this depends on your definition of countable or finite: If your definition of countable or finite is " has an injection from $A$ into $\mathbb N$ " you can prove that this is equivalent to " there is a surjection from $\mathbb N$ onto $A$ " via a similar argument to what I wrote above. Using the second definition you can simply argue: Since $D$ is countable (or finite) there is some $g\colon\mathbb N\to D$ which is a surjection, therefore $f\circ g\colon\mathbb N\to f(D)$ is a surjecitve function and therefore $f(D)$ is countable (or finite). A complete account of the proof of the equivalent definitions of countability can be found here . | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/144751', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/31293/']} | jdg_86415 |
stackexchange | llm_judgeable_groundtruth_similarity | 6655 |
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Aluminium oxide is amphoteric. It is easy to see that it is a Brønsted-Lowry base through the following reaction: $$\ce{Al_2O_3 + 6HCl \rightarrow 2AlCl_3 + 3H_2O}$$ The aluminum oxide splits and the oxygen accepts a proton, forming water. But what about the reaction with a base? In my textbook, they say: $$\ce{Al_2O_3 + NaOH \rightarrow 2NaAlO_2 + H_2O}$$ Now, the textbook claims that Aluminium oxide is an acid merely because it reacts with a base to form a salt and water, as is characteristic of a neutralization reaction. But I'm not satisfied with this definition. I mean, acids aren't defined as 'things that neutralize bases', we have well-established definitions for them. I tried to figure out for myself how this could be. Clearly, the Brønsted-Lowry theory cannot be applied here since the compound in question has no protons to donate. Therefore, the only alternative is the Lewis concept. I cannot see how that is applicable in this case.
Now provide the response and nothing else.
| The most basic definition of "acid" is that it is a proton donor (or one which accepts a lone pair) All of this stuff is done in an aqueous medium, so we can assume that all aqueous ions and molecules are present. With this assumption (in this case, we are assuming that $\ce{OH-}$ is available to react), we get the following equation: $$\ce{Al2O3 + OH- -> 2AlO2- + H+}$$ Similarly, we get: $$\ce{Al2O3 + 6H+ -> 2Al^3+ + H2O}$$ where it is acting like a proton acceptor (base). | {} | {'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/6655', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/1888/']} | jdg_86416 |
stackexchange | llm_judgeable_groundtruth_similarity | 94810 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm talking to a representative of a hardware company trying to sell me a new server and he's adamant that the E5504 CPU which is a Quad core 2Ghz with 4mb cache would be faster than our existing Q6600 CPU which is a Core2 Quad core 2.4Ghz with 8mb cache. http://ark.intel.com/Compare.aspx?ids=29765,40711 , Am i missing something? The system will be used to run a CPU intensive process which performs many simple calculations at the highest possible rate, storing the results in a database. The database is then used for many index scans and complex queries.
Now provide the response and nothing else.
| Then yes absolutely the E5504. The one big change is that the Nehalem based procs use Intel QPI As well as have much better Memory throughput. Although I would look at at least the E5520 given you use case so you have the added benefit of hyperthreading on each of the 4 cores allowing you to have 8 threads running. | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/94810', 'https://serverfault.com', 'https://serverfault.com/users/29022/']} | jdg_86417 |
stackexchange | llm_judgeable_groundtruth_similarity | 10200732 |
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 get this error ([Errno 2] No such file or directory) after I push the repo to heroku master. Here are my logs. 2012-04-17T18:24:53+00:00 app[web.1]: python: can't open file '/test/project/manage.py': [Errno 2] No such file or directory2012-04-17T18:24:54+00:00 heroku[web.1]: Process exited with status 22012-04-17T18:24:54+00:00 heroku[web.1]: State changed from starting to crashed2012-04-17T18:24:54+00:00 heroku[web.1]: State changed from crashed to created2012-04-17T18:24:54+00:00 heroku[web.1]: State changed from created to starting2012-04-17T18:24:57+00:00 heroku[web.1]: Starting process with command python /test/project/manage.py runserver 0.0.0.0:4473 --noreload 2012-04-17T18:24:57+00:00 app[web.1]: python: can't open file '/test/project/manage.py': [Errno 2] No such file or directory My Procfile looks like the following: web: python /test/project/manage.py runserver 0.0.0.0:$PORT --noreload I don't know why it can't open the file. It opens fine when I am using my development server. Any ideas? Thanks for reading.
Now provide the response and nothing else.
| Your current setup in your Procfile references an absolute path '/test/project/manage.py' that doesn't exist on Heroku. The '/test/ is the root of the instance you're running in and is incorrect. You should first change this to be the relative path, this is likely something like: web: python project/manage.py runserver 0.0.0.0:$PORT --noreload If this does not work you can explore the location of the project by running: heroku run bash This should place you in '/app' from here you can see what the path to start your project is. Since your initial push likely failed to start the process you'll likely need to scale a web process. You can then do this with: heroku scale web=1 | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10200732', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1171965/']} | jdg_86418 |
stackexchange | llm_judgeable_groundtruth_similarity | 476987 |
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 thought and read about color mixing today. I made some counterintuitive discoveries, and i now have some thought experiments which i cannot test. I could print a yellow image but i use a different printing technique on each half. On the left side i use color which is true yellow(so yellow pigments which reflect yellow wavelength), on the right i use small red and green squares next to each other(not overlapping) which from afar appear also as the same yellow. So both sides appear yellow to me because my cone cells on my retina are tricked. if i am now holding a monochromatic yellow filter in front of me, the right side would appear black because red and green cant get trough the filter, and the left side would be ... still the same yellow. So i could now distinguish between the left and right side. So my question is, what would i see when i took multiple monochromatic filters with me and look around? Are there materials which appear a specific color because they are(So that the atoms absorb every other color or just emits this specific color) and some materials which reflect or emit different wavelenghts which then appear as a specific color?
Now provide the response and nothing else.
| Every object has a spectrum of emitted light, which is a function $I(\lambda)$ that tells you the intensity $I$ of the light of wavelength $\lambda$ that is emitted by the object. Many different objects have many different spectra, and there are huge swaths of physics devoted to predicting, analyzing, and generally studying the spectra of various objects, from minerals to the atmosphere to stars and galaxies. This makes it difficult to say what color an object is , because it's always emitting light composed of a bunch of different colors. That said, we can reasonably say that an object "appears a certain color because it is that color" when its spectrum is relatively sharply peaked in one color. A great example of this is a sodium vapor lamp, which gets its yellow color from the electrons in sodium atoms jumping between two energy levels. As such, its spectrum is very sharply peaked at 590 nm: The above is an emission spectrum; the higher the points on the graph, the more intense the emitted light of that color is. For context, this is what the lamp looks like: And for some more context, here are the spectra of a lot of other common light sources. Though they all look basically white, you can see that there are clear differences in their spectra that our eyes generally can't resolve: In contrast, one of the green pigments in grass and most plants is chlorophyll b, which has a much broader and more complicated spectrum. Below I present the absorption spectrum, which tells you how much light is absorbed by the pigment. The convention is reversed: the higher the points on the graph, the more the light of that color is absorbed , so the parts of the graph that tell you the color that you see are the low points: You can see from this graph that there are actually three component colors to chlorophyll b in the visible range: there's the obvious green color between 500-600 nm, there's a red portion past 650 nm, and there's a purple contribution from light lower than 450 nm. Your eyes take in this complicated red-green-purple mix and output "this looks green." | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/476987', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/230723/']} | jdg_86419 |
stackexchange | llm_judgeable_groundtruth_similarity | 61108 |
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 remember reading that X-Rays are generated by 'braking' electrons in a Coolidge tube. Is it fundamentally a matter that the extreme gravity immediately before a star ignites is so strong that it affects the hydrogen atoms to the point the velocity of it's components must be let-off in the form of heat & light? How does a star ignite?
Now provide the response and nothing else.
| The nuclear fusion that powers stars has little to nothing to do with electrons. In the cores of stars, temperatures are high enough that all the electrons are stripped from the nuclei, leaving a pure plasma. As stars contract and condense out of interstellar dust, their gravitational potential energy is converted to heat faster than this heat can be radiated away. Once the temperature reaches roughly $10^7\ \mathrm{K}$, protons (hydrogen nuclei , stripped of their electrons) have a nonnegligible chance of sticking together when they colide, with one of them converting to a neutron along the way:$$ {}^1H + {}^1H \to {}^2H + e^+ + \nu_e. $$This is the first step of the PP chain , and it releases energy. There are more steps that ultimately turn four protons into a helium-4 nucleus. In more massive stars than the Sun, there are other ways (e.g. the CNO cycle ) to catalyze this process with the help of carbon, nitrogen, and oxygen. In any event, there is nothing extreme about the gravity. It just happened to pull matter from a huge distance close together. If you took infinitely spread apart particles totaling mass $M$ and formed a uniformly dense sphere of radius $R$, the gravitational potential energy released would be$$ \frac{3GM^2}{5R}, $$about half of which you expect to go into heating the material. Once hot, hydrogen naturally forms helium in exothermic processes. Stellar reactions are self-regulating in the sense that if the rate of fusion increases, the additional luminosity would push the outer layers of the star, causing the star to expand and cool, thus reducing the reaction rate. Thus as long as there is hydrogen in the core, stars more or less burn at a steady rate once ignited. | {} | {'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/61108', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/5265/']} | jdg_86420 |
stackexchange | llm_judgeable_groundtruth_similarity | 10714376 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Which of the following ways is an efficient way of determining substring containment? if (str.indexOf("/") > -1) or if (str.contains("/"))
Now provide the response and nothing else.
| Take a look at the java.lang.String source code. The contains method is implemented using a call to indexOf , so they are essentially the same. public boolean contains(CharSequence s) { return indexOf(s.toString()) > -1;} You should use whichever method makes your code more readable. If you are checking to see if a String contains a specific substring, use contains . If you are looking for the substring's starting index, use indexOf . Edit: A couple of answers mention that indexOf should be preferred over contains due to the fact that contains makes an additional method call, and is thus, less efficient. This is wrong. The overhead caused by an additional method call in this case is totally insignificant. Use whichever method makes the most sense in the context of your implementation. This will make your code more readable. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/10714376', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/223818/']} | jdg_86421 |
stackexchange | llm_judgeable_groundtruth_similarity | 18932549 |
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 building a little quiz game in PHP/MySQL. After asking questions I want a screen to display how many of the last round were answered correctly. Im storing whether they were answered correctly or not in a table that looks like this: rowID | questionid | playerid | answercorrect |1 | 1 | 1 | 1 |2 | 2 | 1 | 1 |3 | 3 | 1 | 1 |4 | 4 | 1 | 1 |5 | 5 | 1 | 0 |6 | 6 | 1 | 1 |7 | 7 | 1 | 1 | I want to see how many of the last x (usually 5) questions were answered correctly. I thought this would be simple. I'm trying this: SELECT sum( answercorrect ) FROM `answersgiven` ORDER BY id DESC LIMIT 5 I thought this would sum the answercorrect column for the last 5 rows, giving me an answer of 4, but it's giving me 7, which is the result for ALL of the rows. I feel like I'm missing something obvious. It seems like a simple thing to want to do. Any ideas?
Now provide the response and nothing else.
| Try this: SELECT sum(answercorrect) FROM (SELECT answercorrect FROM `answersgiven` ORDER BY rowID DESC LIMIT 5) t1 Example Fiddle In your query, the LIMIT clause affects the overall result: So first all are summed up (which results in one row - the sum over all rows) and then the first 5, if available, are taken (which again is just the one row). The easiest way of achieving your target is to first select just the first 5 rows (in the subselect) and then sum up afterwards. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18932549', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1453562/']} | jdg_86422 |
stackexchange | llm_judgeable_groundtruth_similarity | 24827733 |
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 gradle maven-publish plugin's documentation , it's clear that you set the groupId and version of the project directly in build.gradle : group = 'org.gradle.sample'version = '1.0' However, the artifactId appears to be taken from the name of the folder you are working within. Is there a way to set the artifactId explicitly?
Now provide the response and nothing else.
| From 36.2.3. Identity values in the generated POM publishing { publications { maven(MavenPublication) { groupId 'org.gradle.sample' artifactId 'project1-sample' version '1.1' from components.java } }} The artifact ID defaults to the project name configured in settings.gradle , which in turn defaults to the project directory's name. You'll need the appropriate plugin. plugins { id 'maven-publish'} | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/24827733', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/243164/']} | jdg_86423 |
stackexchange | llm_judgeable_groundtruth_similarity | 98046 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm reading a book on Windows Internals and there's something I don't understand: "The kernel handles software interrupts either as part of hardware interrupt handling or synchronously when a thread invokes kernel functions related to the software interrupt." So does this mean that software interrupts or exceptions will only be handled under these conditions: a. When the kernel is executing a function from said thread related to the software exception(trap) b. when it is already handling a hardware trap Is my understanding of this correct? The next bit: "In most cases, the kernel installs front-end trap handling functions that perform general trap handling tasks before and after transferring control to other functions that field the trap." I don't quite understand what it means by 'front-end trap handling functions' and 'field the trap'? Can anyone help me?
Now provide the response and nothing else.
| A couple of refinements to Rune's suggestion: if you use Cisco Catalyst 3750's, the stacking cable will eliminate spanning-tree between the switches, provide greater bandwidth and redundancy without using host ports. If the colo has Cisco 6500 core's with the sup720 VSS blades, then you can do Etherchannel on the 3750's to virtual-Etherchannel on the cores (switch1 -> core1 & switch2 -> core2) further reducing spanning-tree If supported by the colo: use HSRP, VRRP or GLBP for gateway redundancy implement UDLD aggressive on the uplinks (assuming they are fiber) consider using RPS units for power redundancy on the 3750's | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/98046', 'https://serverfault.com', 'https://serverfault.com/users/23852/']} | jdg_86424 |
stackexchange | llm_judgeable_groundtruth_similarity | 2215 |
Below is a question asked on the forum skeptics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
What's the truth surrounding the popular idea that genetically modified food is dangerous to consume? There's entire websites and institutions dedicated to popularizing the alleged dangers of eating genetically modified food, such as GMO Awareness , Food Revolution Network and the Institute for Responsible Technology . There's countless articles and even a TED Talk video. On the flipside, there are also lots of reputable articles saying that all evidences points to GM food being safe: This recent one in Forbes , Alleged Danger of GMOs Not Looking Very Real or this one from Slate , GMO Opponents Are the Climate Skeptics of the Left . Sites such as Sense about Science point out that we've been altering plant's genetic structures for thousands of years, and genetic modification is just a new way of doing this old process. A different argument I read in the Huffington Post states that Pesticide Use Proliferating With GMO Crops is the real source of danger. So even if GMO food itself is fine to eat, what about the secondary dangers from increased/stronger pesticide use that comes as a direct result of GMO crops? So much conflicting information, but what does the scientific evidence say?
Now provide the response and nothing else.
| Yes, genetically modified organisms (GMOs) are safe to consume. The American Association for the Advancement of Science , American Medical Association , World Health Organization , Food and Drug Administration , EU researchers all agree that GMOs are safe to eat. From the American Medical Association: Bioengineered foods have been consumed for close to 20 years, and during that time, no overt consequences on human health have been reported and/or substantiated in the peer-reviewed literature and from the World Health Organization: GM foods currently available on the international market have passed risk assessments and are not likely to present risks for human health. In addition, no effects on human health have been shown as a result of the consumption of such foods by the general population in the countries where they have been approved. Though some sources admit the possibility of risk from unexpected allergic reactions or gene transfer, they note that required testing for GMOs has meant that no GMOs on the market pose a risk to consumers. You may see people reference one study by a scientist named Séralini, which found that GMOs cause cancer in rats, but that study has been thoroughly debunked . Séralini had an insufficient sample size, used a strain of rats likely to develop cancer anyway, and released his paper to the press before he released it to peer review. His results do not match the scientific consensus. In summary: the scientific consensus is that GMOs are safe to consume, and not a single health problem has ever been attributed to genetically modified foods in the decades we've been eating them. UPDATE: The aforementioned debunked Séralini study has been retracted . | {} | {'log_upvote_score': 6, 'links': ['https://skeptics.stackexchange.com/questions/2215', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/1835/']} | jdg_86425 |
stackexchange | llm_judgeable_groundtruth_similarity | 13756999 |
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 very long time, I think what is the reason of using fragment in Android if I just develop the application for Android Phone only but not 10.1 . Is it necessary to use fragment? Also, what is the usage of fragment, I found that it may use for 'tab' and 'separate view'... I really think it is very confusing. Can anyone explain briefly and give example?
Now provide the response and nothing else.
| From documentation You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a "sub activity" that you can reuse in different activities ). Some advantages are.. A particular UI part, once done in fragment, can be reused insame/different activities. You can separate different sections of UI, hence code will be neat,and easy readable. The ability of fragment to be able to reuse is very helpful when you are creating applications for different kind of android devices (phones, tablets). A well designed fragment can be just plugged into your UI hierarchy. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13756999', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1505621/']} | jdg_86426 |
stackexchange | llm_judgeable_groundtruth_similarity | 35748656 |
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 I test real response from retrofit2beta4? Do i need Mockito or Robolectic? I don't have activities in my project, it will be a library and I need to test is server responding correctly.Now I have such code and stuck... @MockApiManager apiManager;@Captorprivate ArgumentCaptor<ApiCallback<Void>> cb;@Beforepublic void setUp() throws Exception { apiManager = ApiManager.getInstance(); MockitoAnnotations.initMocks(this);}@Testpublic void test_login() { Mockito.verify(apiManager) .loginUser(Mockito.eq(login), Mockito.eq(pass), cb.capture()); // cb.getValue(); // assertEquals(cb.getValue().isError(), false);} I can make fake response, but I need to test real. Is it success? Is it's body correct?Can you help me with code?
Now provide the response and nothing else.
| It is generally not a good idea to test real server requests. See this blog post for an interesting discussion on the topic. According to the author, using your real server is a problem because: Another moving piece that can intermittently fail Requires some expertise outside of the Android domain to deploy the server and keep it updated Difficult to trigger error/edge cases Slow test execution (still making HTTP calls) You can avoid all the issues above by using a mock server such as OkHttp's MockWebServer to simulate real response results. For example: @Testpublic void test() throws IOException { MockWebServer mockWebServer = new MockWebServer(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(mockWebServer.url("").toString()) //TODO Add your Retrofit parameters here .build(); //Set a response for retrofit to handle. You can copy a sample //response from your server to simulate a correct result or an error. //MockResponse can also be customized with different parameters //to match your test needs mockWebServer.enqueue(new MockResponse().setBody("your json body")); YourRetrofitService service = retrofit.create(YourRetrofitService.class); //With your service created you can now call its method that should //consume the MockResponse above. You can then use the desired //assertion to check if the result is as expected. For example: Call<YourObject> call = service.getYourObject(); assertTrue(call.execute() != null); //Finish web server mockWebServer.shutdown();} If you need to simulate network delays, you can customize your response as follows: MockResponse response = new MockResponse() .addHeader("Content-Type", "application/json; charset=utf-8") .addHeader("Cache-Control", "no-cache") .setBody("{}");response.throttleBody(1024, 1, TimeUnit.SECONDS); Alternatively, you can use MockRetrofit and NetworkBehavior to simulate API responses. See here an example of how to use it. Finally, if you just want to test your Retrofit Service, the easiest would be to create a mock version of it that emits mock results for your tests. For example, if you have the following GitHub service interface: public interface GitHub { @GET("/repos/{owner}/{repo}/contributors") Call<List<Contributor>> contributors( @Path("owner") String owner, @Path("repo") String repo);} You can then create the following MockGitHub for your tests: public class MockGitHub implements GitHub { private final BehaviorDelegate<GitHub> delegate; private final Map<String, Map<String, List<Contributor>>> ownerRepoContributors; public MockGitHub(BehaviorDelegate<GitHub> delegate) { this.delegate = delegate; ownerRepoContributors = new LinkedHashMap<>(); // Seed some mock data. addContributor("square", "retrofit", "John Doe", 12); addContributor("square", "retrofit", "Bob Smith", 2); addContributor("square", "retrofit", "Big Bird", 40); addContributor("square", "picasso", "Proposition Joe", 39); addContributor("square", "picasso", "Keiser Soze", 152); } @Override public Call<List<Contributor>> contributors(String owner, String repo) { List<Contributor> response = Collections.emptyList(); Map<String, List<Contributor>> repoContributors = ownerRepoContributors.get(owner); if (repoContributors != null) { List<Contributor> contributors = repoContributors.get(repo); if (contributors != null) { response = contributors; } } return delegate.returningResponse(response).contributors(owner, repo); }} You can then use the MockGitHub on your tests to simulate the kinds of responses you are looking for. For the full example, see the implementations of the SimpleService and SimpleMockService for this Retrofit example . Having said all this, if you absolutely must connect to the actual server, you can set Retrofit to work synchronously with a custom ImmediateExecutor : public class ImmediateExecutor implements Executor { @Override public void execute(Runnable command) { command.run(); }} Then apply it to the OkHttpClient you use when building the Retrofit: OkHttpClient client = OkHttpClient.Builder() .dispatcher(new Dispatcher(new ImmediateExecutor())) .build();Retrofit retrofit = new Retrofit.Builder() .client(client) //Your params .build(); | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/35748656', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2281717/']} | jdg_86427 |
stackexchange | llm_judgeable_groundtruth_similarity | 26534134 |
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 python doc and stackoverflow, I understand how to use the **kwargs in my def function. However, I have a case need two sets of **kwargs for two sub functions. Can someone show me how to separate the **kwargs properly? Here is my goal: to plot set of points and interpolated smooth curve, and my naive sample code: def smoothy(x,y, kind='cubic', order = 3, **kwargs_for_scatter, **kwargs_for_plot): yn_cor = interp1d(x, y, kind=kind, assume_sorted = False) xn = np.linspace(np.min(x), np.max(x), len(x) * order) plt.scatter(x,y, **kwargs_for_scatter) plt.plot(xn, yn_cor(xn), **kwargs_for_plot); return Thanks for help.
Now provide the response and nothing else.
| There is no such mechanism. There is a proposal, PEP-448 , whereby Python 3.5 and following generalize argument unpacking. Python 3.4 and previous don't support it. Best you can do in general: def smoothy(x,y, kind='cubic', order = 3, kwargs_for_scatter={}, kwargs_for_plot={}): yn_cor = interp1d(x, y, kind=kind, assume_sorted = False) xn = np.linspace(np.min(x), np.max(x), len(x) * order) plt.scatter(x,y, **kwargs_for_scatter) plt.plot(xn, yn_cor(xn), **kwargs_for_plot); return Then pass in those options as dictionaries, not kwargs, to smoothy . smoothy(x, y, 'cubic', 3, {...}, {...}) Because the variable names would then be possibly exposed to callers, you may want to rename them something shorter (perhaps scatter_options and plot_options ). Update : Python 3.5 and 3.6 are now mainstream, and they indeed support an extended unpacking syntax based on PEP-448. >>> d = {'name': 'joe'}>>> e = {'age': 20}>>> { **d, **e }{'name': 'joe', 'age': 20} This does not, however, help much in this kwargs-intended-for-multiple-destinations scenario. Even if the smoothy() function took a unified grab-bag of kwargs, you'd need to determine which of them were intended for which subfunctions. Messy at the very best. Multiple dict parameters, one intended to be passed to each kwarg-taking subfunction, still the best approach. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26534134', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3287545/']} | jdg_86428 |
stackexchange | llm_judgeable_groundtruth_similarity | 21890060 |
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 use $anchorScroll to scroll down the page to ensure that a row of a table is shown. I've read most of the SO threads and docs about $anchorScroll. I'm using it correctly, as far as I can tell. I've stepped through the code with Firebug, and it appears that the element id I'm using is correct. When I execute the function that should change the scroll location, it does change the scroll location, but it just scrolls up, going all the way to the top. My "target" element that I want to scroll to is further down the page from where I execute the function. There are no error messages, it just doesn't do what I need. Here is the simple function that I use: $scope.scrollTo = function (elementId) { console.log("element[" + angular.element(elementId) + "]"); $location.hash(elementId); $timeout(function() { $anchorScroll(); }); }; I've also tried changing the reference to this so that instead of targetting a table row, it targets the accordion div that encloses the table, but that made no difference. It still just jumps to the top of the page. Note that before I call "scrollTo", I first ensure that the accordion with the table is opened. In any case, it still doesn't scroll correctly even after it's manually opened. Update: Here's a portion of the HTML that I'm trying to scroll to: <div ng-controller="WorkflowDefsCtrl"> <pane accordion-group heading="Workflows" is-open="accordionActiveFlags.workflowDefs" id="workflowDefs"> <label for="workflowDefsTable">Workflow Definitions</label> <table id="workflowDefsTable" ng-table class="table"> <tr ng-repeat="workflowDef in sunlightConfig.workflowDefinitions | orderBy: workflowDef.order" id="workflowDef{{workflowDef.id}}"> <td data-title="'ID'">{{workflowDef.id}}</td> <td data-title="'Name'">{{workflowDef.name}}</td> <td data-title="'Label'">{{workflowDef.label}}</td> <td data-title="'Order'" class="text-right">{{workflowDef.order}}</td> <td data-title="'Render?'">{{workflowDef.render}}</td> <td data-title="'Query Fragment'">{{workflowDef.queryFragment}}</td> <td data-title="'Query Order'" class="text-right">{{workflowDef.queryOrder}}</td> </tr> </table> </pane> </div> The two testcases I'm trying are going to element "workflowDefs" and any of the "workflowDef{{workflowDef.id}}" elements. Update: I enhanced my "scrollTo" method to deal with scrolling to elements that had just become visible. This doesn't make any difference, however. It still just scrolls to the top no matter what. Update: Today I realized that a string argument to "angular.element" should be a CSS selector, not an element id, so I had to add "#" as a prefix. This resulted in the correct element being located, but unfortunately it still had no effect on the display. It still doesn't scroll to the element. My new "scrollTo" function looks like this: scrollTo: function (elementId) { $location.hash("#" + elementId); $timeout(function() { $anchorScroll(); }); },
Now provide the response and nothing else.
| I managed to figure this out. I correctly assumed that $anchorScroll has to be executed in the $timeout block, but that isn't sufficient. The call to $location.hash() also has to be in the $timeout block . Once I changed my scrollTo function to the following: scrollTo: function (elementId) { $timeout(function() { $location.hash(elementId); $anchorScroll(); }); }, It then started working consistently. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21890060', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10508/']} | jdg_86429 |
stackexchange | llm_judgeable_groundtruth_similarity | 2139208 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
The following code (packaged in a 'Console Application' Visual Studio project): using System;using System.Collections.Generic;using System.Text;using System.Reflection;namespace TestReflection{ class Program { static void Main(string[] args) { bool found = false; foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) { if (assembly.GetType("System.Diagnostics.Process") != null) { found = true; break; } } Console.WriteLine(found); Console.ReadKey(); } }} prints 'True' when running it in debug mode (F5), but 'False' when launching it without the debugger (Ctrl-F5). Other classes show similar behavior ( System.Text.RegularExpressions.Regex ), others are found in both cases ( System.IO.File ). I'm probably missing something obvious - why is this happenning? (same thing happens in both Visual Studio 2005 and 2008). UPDATE List of assemblies found: Debug mode: mscorlibTestReflectionSystemMicrosoft.VisualStudio.HostingProcess.UtilitiesSystem.Windows.Forms Run mode: mscorlibTestReflection As the answers imply, in run mode the System assembly is missing (not loaded). My problem was that I was assuming GetAssemblies() was also returning not loaded assemblies. While this explains the behavior for System.Diagnostics.Process , why is my code finding System.IO.File in both run and debug modes? Thanks! UPDATE 2 I've changed the code to loop through the loaded assemblies and the current assembly, collecting a list of assemblies referenced by these. If after iterating the loaded assemblies I can't find the type I'm looking for, I start loading and inspecting the referenced assemblies. It seems that even if I have a reference to System.dll in my project (I'm looking at the properties of the 'System' reference in Visual Studio), my executable file only references mscorlib.dll (according to Reflector). How do I add a 'real' reference to System.dll ? Placing a dummy line new System.Diagnostics.ProcessStartInfo(); at the start of Main does the trick (things work as expected, Reflector shows references for both mscorlib.dll and System.dll when inspecting the executable), but it is a hack. Thanks again!
Now provide the response and nothing else.
| AppDomain.GetAssemblies does not return all assemblies that you have referenced , rather it returns all assemblies that are currently loaded into the appdomain. Clearly, the Diagnostics.Process class is not directly used by your application and will thus not be loaded when running outside the debugger. So why do we find System.IO.File but not System.Diagnostics.Process?The reason is that the two classes, though they reside in the same top-level namespace System, actually lives in two different assemblies. This is easily seen if you look up the two classes in the Visual Studio Object Browser. The File class happens to live in the mscorlib dll while the Process class lives in the System dll. Since no .Net application can run without mscorlib that assembly will be loaded, while System.dll is not loaded since you are not referencing any types that lives in that dll. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2139208', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/35420/']} | jdg_86430 |
stackexchange | llm_judgeable_groundtruth_similarity | 680698 |
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 made a tiny application that responds to changes to files in a folder. But when I edit the file in Visual Studio 2008, it never detects anything. If I edit the file in Notepad instead, everything works as expected. Surely Visual Studio saves the file at some point, but the watcher does not even trigger when I close the studio. Do you have any idea what I'm missing here? This sample code (C#) should illustrate the problem: FileSystemWatcher fileSystemWatcher = new FileSystemWatcher("C:\Test", "*.cs");WaitForChangedResult changed = fileSystemWatcher.WaitForChanged(WatcherChangeTypes.All);Console.Out.WriteLine(changed.Name); I found a blog post by Ayende that describes the same problem, but unfortunately no solution.
Now provide the response and nothing else.
| This was really mind boggling... when you try my example program below and change the file in VS, you will notice two lines in your output window: Deleted Renamed So Visual Studio does never change an existing file, it saves the constents to a new file with a temporary name, then deletes the original file and renames the new file to the old name. Actually, this is a good practice, because if you do it the usual way (just writing the changed file, which would cause the Changed event to be fired), the event handler may be called before the writing process is complete. If the event handler processes the file contents, this may cause problems because it would process an incomplete file. In other words: It's not a bug, it's a feature ;-) static class Program { [STAThread] static void Main() { FileSystemWatcher FSW = new FileSystemWatcher("c:\\", "*.cs"); FswHandler Handler = new FswHandler(); FSW.Changed += Handler.OnEvent; FSW.Created += Handler.OnEvent; FSW.Deleted += Handler.OnEvent; FSW.Renamed += Handler.OnEvent; FSW.EnableRaisingEvents = true; System.Threading.Thread.Sleep(555000); // change the file manually to see which events are fired FSW.EnableRaisingEvents = false; } } public class FswHandler { public void OnEvent(Object source, FileSystemEventArgs Args) { Console.Out.WriteLine(Args.ChangeType.ToString()); } }} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/680698', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/58253/']} | jdg_86431 |
stackexchange | llm_judgeable_groundtruth_similarity | 18369844 |
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 UIPanGuestureRecognizer added to the entire view using this code: UIPanGestureRecognizer *pgr = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panAction:)];[[self view] addGestureRecognizer:pgr]; Within the main view I have a UITableView which has this code to enable the swipe to delete feature: - (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath { NSLog(@"RUNNING2"); return UITableViewCellEditingStyleDelete;}- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { if (indexPath.row >= _firstEditableCell && _firstEditableCell != -1) NSLog(@"RUNNING1"); return YES; else return NO;} Only RUNNING1 is printed to the log and the Delete button does not show up. I believe the reason for this is the UIPanGestureRecognizer, but I am not sure. If this is correct how should I go about fixing this. If this is not correct please provide the cause and fix. Thanks.
Now provide the response and nothing else.
| From the document : If a gesture recognizer recognizes its gesture, the remaining touches for the view are cancelled. Your UIPanGestureRecognizer recognizes the swipe gesture first, so your UITableView does not receive touches anymore. To make the table view receives touch simultaneously with the gesture recognizer, add this to the gesture recognizer's delegate: - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer { return YES;} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18369844', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1916721/']} | jdg_86432 |
stackexchange | llm_judgeable_groundtruth_similarity | 37172691 |
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 out Valet, it looks really nice from what I've heard. I've been trough the "whole" installation process, Valet is succesfully installed. But when I cd into my projects file and enter valet park and browse to http://blog.dev , I get "The DNS server address of blog.dev can not be found." I have no idea what I'm doing wrong. :)
Now provide the response and nothing else.
| When you run valet install it attempts to install dnsmasq. It requires sudo privileges. You can check that it's installed and running using brew services list You should see something like dnsmasq started root /Library/LaunchDaemons/homebrew.mxcl.dnsmasq.plist You may however need to tap brew/services first brew tap homebrew/services If it's not there, run brew install dnsmasqbrew services start dnsmasq Run valet install again to set up dnsmasq and keep an eye out for any errors. What this should do is append a line to the bottom of /usr/local/etc/dnsmasq.conf similar to conf-file=/Users/{YOURUSER}/.valet/dnsmasq.conf /Users/{YOURUSER}/.valet/dnsmasq.conf then should contain address=/.dev/127.0.0.1 Check that your dns server is responding to requests dig testing.dev @127.0.0.1 You should see a response like ;; ANSWER SECTION:testing.dev. 0 IN A 127.0.0.1 To actually ensure that your Mac knows that it should resolve *.dev using your local DNS server, it need to be told to do so. Valet also handles this for you but you can check if it's done it's job by doing the following. Inside the directory /etc/resolver , there should be a file entitled dev with the following contents nameserver 127.0.0.1 This creates a custom DNS resolver for *.dev and points all requests at your local DNS server. Restart dnsmasq with either of the following commands and then give it a try again. // thisbrew services restart dnsmasq// or thissudo launchctl stop homebrew.mxcl.dnsmasqsudo launchctl start homebrew.mxcl.dnsmasq If this is all working, you should be able to ping anything.dev ping anything.devPING anything.dev (127.0.0.1): 56 data bytes64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.039 ms64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.081 ms That ensures the DNS related bits are working. Ultimately the question is about DNS related problems but as this started off as a here's everything you need to have tried, I'll leave this below. That said, if you're unable to ping something.dev or get an error like "The DNS server address of blog.dev can not be found." as per the OP, it's something above to do with DNS which needs resolving. Since Caddy serves websites on port 80, you need to ensure that nothing else is running on port 80. sudo lsof -n -i:80 | grep LISTEN Ideally this should return caddy if valet is running as expected. You want to see the example below or nothing ideally; nothing because it means we can just start Valet. caddy 76234 root 3u IPv6 0x4f871f962e84fa95 0t0 TCP *:http (LISTEN) You may see other webservers, such as Apache or Nginx (and their child processes, _www and nobody ) in the example below. httpd 79 root 4u IPv6 0xf4641199930063c5 0t0 TCP *:http (LISTEN)httpd 239 _www 4u IPv6 0xf4641199930063c5 0t0 TCP *:http (LISTEN)nginx 4837 root 6u IPv4 0xf4641199a4e8e915 0t0 TCP 127.0.0.1:http (LISTEN)nginx 4838 nobody 6u IPv4 0xf4641199a4e8e915 0t0 TCP 127.0.0.1:http (LISTEN) Assuming you've installed Nginx with homebrew you can run the following to stop it. brew services stop nginx OSX ships with Apache installed so you can stop with with the following if it's running. sudo apachectl stop At this point you can likely start Valet with valet start and it'll work. You may get a further error which is caused by PHP being installed without FPM. You can check this using brew info php70 | grep php70-fpm Which should yield something along the lines of The control script is located at /usr/local/opt/php70/sbin/php70-fpm If it doesn't appear to be installed, use the following. brew uninstall homebrew/php/php70brew install homebrew/php/php70 --with-fpmvalet restart | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37172691', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5893422/']} | jdg_86433 |
stackexchange | llm_judgeable_groundtruth_similarity | 7938516 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm new to Android so sorry if the question is easy to answer. I have two buttons, a decrease and an increase button, and in the middle of them a TextView which displays a value. When I hit the decrease button, the value in the TextView decreases and increases when I hit the increase button, no problem with that, I got that working but the problem is the value only increases/decreases by 1 on a single click. What I'm trying to achieve is that as I continuously press the button (the increase button for example), the value is also continuously increasing and only stops when I release the increase button. Is that possible? If so, can you show some sample code or references on how to implement that? Thanks! Here is my main.xml <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="center" > <RelativeLayout android:layout_width="fill_parent" android:layout_height="44dp" android:gravity="center_horizontal" > <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:text="<" /> <TextView android:id="@+id/textView1" android:layout_width="50dp" android:layout_height="fill_parent" android:layout_alignBottom="@+id/button1" android:layout_toRightOf="@+id/button1" android:gravity="center" android:text="45" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_toRightOf="@+id/textView1" android:text=">" /> </RelativeLayout> </RelativeLayout> and here is my Main.java import android.app.Activity;import android.os.Bundle;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;public class Main extends Activity { private Button _decrease; private Button _increase; private TextView _value; private static int _counter = 45; private String _stringVal; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); _decrease = (Button) findViewById(R.id.button1); _increase = (Button) findViewById(R.id.button2); _value = (TextView) findViewById(R.id.textView1); _decrease.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Log.d("src", "Decreasing value..."); _counter--; _stringVal = Integer.toString(_counter); _value.setText(_stringVal); } }); _increase.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Log.d("src", "Increasing value..."); _counter++; _stringVal = Integer.toString(_counter); _value.setText(_stringVal); } }); }}
Now provide the response and nothing else.
| For that to work, you need a thread that will update the integer value when you long press on a button. Create a handler in your activity: private Handler repeatUpdateHandler = new Handler(); And 2 vars which will state: is it increment or decrement? Only one set at a time. private boolean mAutoIncrement = false;private boolean mAutoDecrement = false; And the present number value public int mValue; And a class that will run in another thread: class RptUpdater implements Runnable { public void run() { if( mAutoIncrement ){ increment(); repeatUpdateHandler.postDelayed( new RptUpdater(), REP_DELAY ); } else if( mAutoDecrement ){ decrement(); repeatUpdateHandler.postDelayed( new RptUpdater(), REP_DELAY ); } }} Add a long press listener to your button: mBTIncrement.setOnLongClickListener( new View.OnLongClickListener(){ public boolean onLongClick(View arg0) { mAutoIncrement = true; repeatUpdateHandler.post( new RptUpdater() ); return false; } } ); mBTIncrement.setOnTouchListener( new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { if( (event.getAction()==MotionEvent.ACTION_UP || event.getAction()==MotionEvent.ACTION_CANCEL) && mAutoIncrement ){ mAutoIncrement = false; } return false; } }); In the above case the button is the increment one. Create another button which will set mAutoDecrement to true. And decrement() will be a function, which will set your instance int variable like this: public void decrement(){ mValue--; _value.setText( ""+mValue );} You figure the increment out. Oh and REP_DELAY is a static int variable set to 50. I see this is an excerpt from Jeffrey Cole's open source NumberPicker available at http://www.technologichron.net/ Proper author's attribution must be added. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/7938516', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1018358/']} | jdg_86434 |
stackexchange | llm_judgeable_groundtruth_similarity | 51096280 |
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 in my model accessors and mutators for hash/rehash data in database table fields. For example: public function setFullNameAttribute($value){ $this->attributes['full_name'] = Helper::geted('encrypt', $value);}public function getFullNameAttribute($value){ return Helper::geted('decrypt', $value);} When I'll save data to database all sending datas saving in hashed form but on update data not hashed. My save/update code: $profile = [ 'full_name' => "John", 'address' => "United Kingdom"];$profile_save = new Profile($profile);$exist = Personal::where('user_id', Auth::id())->count();if($exist == 0) $user->profile()->save($profile_save);if($exist == 1) $user->profile()->update($profile); When I first time save this info to db: When I second time enter to current URL data will be updated: Why does not the information be stored in an encrypted form when updating information?
Now provide the response and nothing else.
| Your problem is in this line: $user->profile()->update($profile); Mutators and accessors work on eloquent and not on Query Builders. You are using update function which is a query builder function, so you are updating your database directly.Use this: $profile = [ 'full_name' => "John", 'address' => "United Kingdom"];$profile = auth()->user()->profile;if ($profile) { $profile->full_name = $profile['full_name']; $profile->address = $profile['address']; $profile->save();} else { auth()->user()->profile()->create($profile);} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51096280', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7496039/']} | jdg_86435 |
stackexchange | llm_judgeable_groundtruth_similarity | 41376 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have been interested in design patterns for a while and started reading "Head First Design Patterns". I started with the first pattern called the 'Strategy' pattern. I went through the problem outlined in the images below and first tried to propose a solution myself so I could really grasp the importance of the pattern. So my question is that why is my solution to the problem below not good enough. What are the good / bad points of my solution vs the pattern? What makes the pattern clearly the only viable solution? MY SOLUTION Parent Class: DUCK <?phpclass Duck{ public $swimmable; public $quackable; public $flyable; function display() { echo "A Duck Looks Like This<BR/>"; } function quack() { if($this->quackable==1) { echo("Quack<BR/>"); } } function swim() { if($this->swimmable==1) { echo("Swim<BR/>"); } } function fly() { if($this->flyable==1) { echo("Fly<BR/>"); } }}?> INHERITING CLASS: MallardDuck <?phpclass MallardDuck extends Duck{ function MallardDuck() { $this->quackable = 1; $this->swimmable = 1; } function display() { echo "A Mallard Duck Looks Like This<BR/>"; }}?> INHERITING CLASS: WoddenDecoyDuck <?phpclass WoddenDecoyDuck extends Duck{ function woddendecoyduck() { $this->quackable = 0; $this->swimmable = 0; } function display() { echo "A Wooden Decoy Duck Looks Like This<BR/>"; }}
Now provide the response and nothing else.
| Your code will break when, e.g. ducks quack with a different sounds. The boolean will only lead to other booleans into really hairy if-statements. The strategy pattern is simple though. Take in this instance the quack method and place it into it's own class or interface. An interface in php would be a class that does not contain any implementation other than methods that are stubs (i.e. nothing happens when you call them). class Quackable { function quack() {}} That way you can create several quackable implementations: class DuckQuack extends Quackable { function quack() { return "Quack!"; }}class SilentQuack extends Quackable { function quack() { return ""; // The decoy duck can't quack. It is silent. }} And because we did it strategy pattern wise, we can add more types of "quackery": class DoubleQuack extends Quackable { function quack() { return "Quackety-quack!" }} The same can be applied to fly and swim methods for the Duck class. The way you implement a Duck class with a quackable would be like this (the quackable interface is supplied through the constructor, which is sort of how dependency injection works): class Duck { protected $quackable; // The constructor function __construct($quackable) { $this->quackable = quackable; } function quack() { echo $this->quackable->quack(); }} Implementing the mallard duck and decoy duck will be simple since you only need to supply what kind of quacks the duck should do: class MallardDuck extends Duck { function __construct() { parent::__construct(new DuckQuack()); // we construct the mallard duck with a duck quack }}class DecoyDuck extends Duck { function __construct() { parent::__construct(new SilentQuack()); // we construct the decoy duck with a silent quack }} Using it all is simple: $duck1 = new MallardDuck();$duck2 = new DecoyDuck();$duck1.quack(); // echoes out "Quack!"$duck2.quack(); // echoes out "" (because decoy ducks don't quack) I hope this all makes sense to you. | {} | {'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/41376', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/14905/']} | jdg_86436 |
stackexchange | llm_judgeable_groundtruth_similarity | 59054 |
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to compute UV/Vis absorption spectrum for Ethene using Gaussian 09. I created the ethene molecule in GaussView 5, and cleaned it. Then I optimized the molecule and checked if I got the minimum energy conformation with the following: # freq=noraman cphf=noread b3lyp/6-31g(d) geom=connectivity formcheck integral=grid=ultrafine scf=maxcycle=1000 Next I performed the energy calculation as follows: # td b3lyp/6-31g(d) geom=connectivity As a result I got a single peak with the maximum at 134 nm (see picture below) which seems to be way off from what I googled around on the Internet, which is like 173 nm or 180 nm. Can anyone please help me figure out if I have done it correctly and whether I am way off the experimental data?
Now provide the response and nothing else.
| In short, there are two obvious problems with the setup OP uses for TD-DFT calculations: B3LYP functional is not a good choice for TD-DFT. 6-31G(d) basis is usually too small . At M06-2X/Def2-TZVP level I get a maximum at ~160 nm, which, taking the accuracy of the TD-DFT approximations into account, is close enough to the experimental value. | {} | {'log_upvote_score': 5, 'links': ['https://chemistry.stackexchange.com/questions/59054', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/34233/']} | jdg_86437 |
stackexchange | llm_judgeable_groundtruth_similarity | 491724 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let ABCDE be a convex pentagon. $AB = AE = CD = 1. $$\angle AED = \angle ABC = 90^{\circ}$. DE + BC = 1. I have very easily shown that area of triangles AED and ABC sum to half into 1/2. But it seems that I am only able to get there. To find the area of triangle ADC I have tried to take its sides in terms of ED but that seems to be too complex. I am stuck.
Now provide the response and nothing else.
| The area of the triangle is half the product of a side of the triangle and the height of the triangle on that side. So calling the area of the triangle $A$, the sides would have to be $$\frac{2\cdot A}{10}, \; \frac{2\cdot A}{7},\; \frac{2\cdot A}{4}.$$ But $$\frac{1}{4} > \frac{1}{7} + \frac{1}{10},$$ so these "sides" could not make a triangle, since the longest is longer than the sum of the two shorter. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/491724', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/93616/']} | jdg_86438 |
stackexchange | llm_judgeable_groundtruth_similarity | 2034276 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Where do you put unit tests for private functions in C# classes? An article in Wikipedia suggests: Putting tests in the same class as the members they're testing Using partial classes Personally, neither of these methods seem appropriate, and I much prefer to have unit tests located in a separate project altogether. Any thoughts on this? (I know there's a fair amount of debate on whether private methods should be tested at all. I'd like to hear both sides of the argument.)
Now provide the response and nothing else.
| Private methods do not necessarily need to be tested directly. You can determine their validity based on tests of public methods that utilize those private methods. However, you should take care to ensure that your public methods can easily inject mock dependencies into your private methods to facilitate testing and simulate all reasonable scenarios. Edit: As for where your other tests should be located, I suggest a separate subdirectory within your project to handle your tests. When writing tests for PHP applications, I have a tests directory in the root of my project whose directory structure is identical to that of my real application directory structure. In it, I have a test class for each real class. Just don't compile your test classes with the rest of your project when releasing to production (or in the case of an interpretted language like PHP, don't deploy the test classes to the production webserver). | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2034276', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/23341/']} | jdg_86439 |
stackexchange | llm_judgeable_groundtruth_similarity | 16933800 |
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 User object with properties Name and Surname. I want to search these fields using one query, and I found multi_match in the documentation, but I don't know how to properly use that with a wildcard. Is it possible? I tried with a multi_match query but it didn't work: { "query": { "multi_match": { "query": "*mar*", "fields": [ "user.name", "user.surname" ] } }}
Now provide the response and nothing else.
| Alternatively you could use a query_string query with wildcards. "query": { "query_string": { "query": "*mar*", "fields": ["user.name", "user.surname"] }} This will be slower than using an nGram filter at index-time (see my other answer), but if you are looking for a quick and dirty solution... Also I am not sure about your mapping, but if you are using user.name instead of name your mapping needs to look like this: "your_type_name_here": { "properties": { "user": { "type": "object", "properties": { "name": { "type": "string" }, "surname": { "type": "string" } } } }} | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/16933800', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2454513/']} | jdg_86440 |
Subsets and Splits
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves samples with 'mathoverflow.net' in the prompt, providing a basic subset for inspection but with limited analytical value.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves 10 samples where the prompt mentions Mathematica Stack Exchange, offering basic filtering to locate specific content.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves a limited number of rows where the prompt contains a specific URL, providing basic filtering that offers minimal insight into the broader dataset patterns.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves 10 samples from the dataset where the prompt contains 'dsp.stackexchange.com', offering a basic filtering of data points related to that specific domain.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves a sample of rows where the prompt contains 'cs.stackexchange.com', providing a basic filter without extensive insight.
Electronics Q&A Subset
Retrieves a limited number of samples that contain a specific URL, providing only raw data filtered by that URL.
StackExchange Stats Questions
Retrieves 100 entries containing 'stats.stackexchange.com' in the prompt, which is useful for finding specific content but lacks broader analytical value.
Math StackExchange Questions
Retrieves 100 records from the train dataset where the prompt contains 'math.stackexchange.com', providing a basic filtered overview of specific entries.
Physics SE Questions
Retrieves 100 samples containing the word 'physics.stackexchange.com' in the prompt, offering basic filtering without deep analysis.