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
36762686
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an array of dictionary, in which i need to search and return matching Dict let foo = [ ["selectedSegment":0, "severity":3, "dataDictKey": "critical"], ["selectedSegment":1, "severity":2, "dataDictKey": "major"], ["selectedSegment":2, "severity":1, "dataDictKey": "minor"],] In foo , how can i find for severity:2 and get matching Dict ? Now provide the response and nothing else.
Use the filter function let foo = [ ["selectedSegment":0, "severity":3, "dataDictKey": "critical"], ["selectedSegment":1, "severity":2, "dataDictKey": "major"], ["selectedSegment":2, "severity":1, "dataDictKey": "minor"],]let filteredArray = foo.filter{$0["severity"]! == 2}print(filteredArray.first ?? "Item not found") or indexOf if let filteredArrayIndex = foo.indexOf({$0["severity"]! == 2}) { print(foo[filteredArrayIndex])} else { print("Item not found")} or NSPredicate let predicate = NSPredicate(format: "severity == 2")let filteredArray = (foo as NSArray).filteredArrayUsingPredicate(predicate)print(filteredArray.first ?? "Item not found") Swift 3 Update: indexOf( has been renamed to index(where: filteredArrayUsingPredicate(predicate) has been renamed to filtered(using: predicate)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36762686', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1616074/']}
jdg_381841
stackexchange
llm_judgeable_groundtruth_similarity
31711837
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 learning Scala from Scala for the Impatient and Chapter 01 exercise has a problem What do the take, drop, takeRight, and dropRight string functions do? What advantage or disadvantage do they have over using substring? The only advantage I see that drop (and flavors) will not throw IndexOutOfBoundsException For example: scala> "Hello World!" dropRight 100res26: String = ""scala> "Hello World!" substring 100java.lang.StringIndexOutOfBoundsException: String index out of range: -88 at java.lang.String.substring(String.java:1919) ... 33 elided What else? Memory efficient? Now provide the response and nothing else.
The main benefit is that it allows you to treat a String as a sequential collection of characters, much like any other Seq or List instance. In fact, these methods (and other important transformational functions like map, flatMap and filter) are not implemented in String itself (which is, in fact, simply the Java String class, not a native-Scala class), but in the StringOps class (which extends StringLike -> ... -> SeqLike), and an implicit conversion ensures that a String is converted into a StringOps whenever you need access to these methods. This means you can pass a String to a list-manipulation function and the function will receive a StringOps instance, work on it like any other SeqLike entity without needing to know it is actually a String, and hand back the results of the manipulation, which StringOps is designed to present back to you as a String. If you know an entity is a String in a given piece of code, feel free to use the String-specific methods, but the availability of this implicit conversion means that you can also take advantage of a String's "character sequence"-like nature to treat it like any other list in situations where that may be convenient.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/31711837', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/379235/']}
jdg_381842
stackexchange
llm_judgeable_groundtruth_similarity
10525548
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 what my current code looks like: HTML: <a class="button" href="#">Read More</a> CSS: .button {background:url('../images/btn_bg.jpg') repeat scroll 0% 0%;font: 12px Helvetica, Arial, sans-serif;color: #FFF;text-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);text-transform: uppercase;text-align: center;text-decoration: none;cursor: pointer;border: none;min-width: 87px;min-height: 29px;float: right;margin-top: 14px;padding-top: 4.25px;transition: all 0.5s ease 0s;-webkit-transition: all 0.5s ease 0s;-moz-transition: all 0.5s ease 0s;-o-transition: all 0.5s ease 0s;}.button:hover {background: url('../images/btn_over.jpg') repeat scroll 0% 0%;} Result : Firstly, the column that this is all wrapped in has a margin-bottom: 14px . This creates the spacing from the column and the two horizontal lines below it. This is so if the user wanted to take the button out all together, the text inside the column would still meet 14px shy from the two lines below. As you can see the text for the .button is aligned to the middle by using the css padding property and text-align: center .There is a margin-top: 14px on the button which gives the same spacing above the button as under it. However, what I am finding is that by using the padding element for the text inside the button, it affects the distance around it (in this case, the space below the button which is meant to be 14px, is now bigger than what it should be). Question: Is there a way to vertically align the text within the .button without using the padding property as I have tried vertical-align, position, float and a few others but to no success without changing the space above or below the box...what is the best way to go about this and if possible, an alternative way to just using an image instead? Any help would be greatly appreciated. http://jsfiddle.net/9xpfY/ Now provide the response and nothing else.
There are two ways you can do this, however without javascript both of these methods require absolute heights although the second option works relative to the padding you have set. The first, an obvious choice is the use of line height. This works by setting the height of the line of text to a value, and because text is already natively vertically aligned to the center of the line-height you get the effect you are looking for. adding the line line-height : 27px; to .button { will give you your desired result. jsfiddle The second way is to wrap the text inside the element in a span tag and set the bottom property to bottom: -6.75px; Your button element would look like this <a class="button" href="#"><span id="buttontext">Read More</span></a> and you would add this line to your css: #buttontext {position: relative; bottom: -6.75px;} jsfiddle REFERENCES line-height bottom
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10525548', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1356483/']}
jdg_381843
stackexchange
llm_judgeable_groundtruth_similarity
34992
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Is it true that a single application can not allocate more than 2 GiBs even if the system has GiBs more free memory when using a 32-bit x86 PAE Linux kernel? Is this limit loosened by 64-bit x86 Linux kernels? Now provide the response and nothing else.
A 32-bit process has a 32-bit address space, by definition: “32-bit” means that memory addresses in the process are 32 bits wide, and if you have 2 32 distinct addresses you can address at most 2 32 bytes (4GB). A 32-bit Linux kernel can only execute 32-bit processes. Depending on the kernel compilation options, each process can only allocate 1GB, 2GB or 3GB of memory (the rest is reserved for the kernel when it's processing system calls). This is an amount of virtual memory, unrelated to any breakdown between RAM, swap, and mmapped files. A 64-bit kernel can run 64-bit processes as well as 32-bit processes. A 64-bit process can address up to 2 64 bytes (16EB) in principle. On the x86_64 architecture , partly due to the design of x86_64 MMU s, there is currently a limitation to 128TB of address space per process.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/34992', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/2119/']}
jdg_381844
stackexchange
llm_judgeable_groundtruth_similarity
342954
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: A bit of a neophyte haskell question, but I came across this example in Haskell's tutorial examples . For "find the last element of a list" there are some obvious versions, like last' [x] = xlast' (_:xs) = last' xs But I can't make sense of an alternate version presented: myLast' = foldr1 (const id) So, in trying to make sense of what the application of the id function is doing, I tried in ghci: const id 1 2 -> gives 2 This binds like this: (const id) 1 2 -> gives 2 And not like this: const (id 1) 2 -> gives 1 But I'm not making sense of this. (const id) should translate to something like `(\x y->x) (\x->x)` Shouldn't this return a function that simply returns the id of its first element? Or, how is the function order making (const id) behave differently than const? Now provide the response and nothing else.
The definition of const is const x = \_ -> x Hence, (const id) is a function which takes one argument and always returns id and const id 1 2 = (\_ -> id) 1 2 = id 2 = 2 The definition of foldr1 is foldr1 f [x] = xfoldr1 f (x:xs) = f x (foldr1 f xs) If we have myLast' = foldr1 (const id) then myLast' [x] = foldr1 (const id) [x] {- definition of foldr1 -} = x and myLast' (x:xs) = foldr1 (const id) (x:xs) {- definition of foldr1 -} = (const id) x (foldr1 (const id) xs) {- definition of const -} = (\_ -> id) x (foldr1 (const id) xs) {- function application -} = id (foldr1 (const id) xs) {- definition of id -} = foldr1 (const id) xs {- definition of myLast' -} = myLast' xs which agrees with the definition of last' .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/342954', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/19479/']}
jdg_381845
stackexchange
llm_judgeable_groundtruth_similarity
40624930
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 an open source project (Open Scene Graph). I found that all the header file names are in File format, which I found to be File With No Extension as mentioned in some website. I would like to know why those developer used this extension, rather than the traditional .h file extension. Now provide the response and nothing else.
It seems you are talking about this repository of C++ code. It looks like the authors of that code decided to follow the patterns of the C++ standard library. In standard C++, library headers are not supposed to have the .h extension. So the following is correct: #include <iostream> With most implementations writing <iostream.h> would also work, but the version without an extension is actually correct. The C++ standard library was able to drop extensions in C++98 due to the introduction of namespaces, and introduction of the std namespace for the standard library. The C++ standard neither requires nor forbids an extension for other headers, so it's entirely up to the authors of some software what file extension to use, if any. The most common choices are to use .h or .hpp , the latter being intended to distinguish C++ headers from C headers. A quick look at the OpenSceneGraph code shows that they've followed the C++ standard library pattern in their includes. There are no extensions, and everything is in the osg namespace, analogous to the std namespace of the standard library. So using the OpenSceneGraph libraries is very similar to using the C++ standard library. #include <osg/Camera> // Provides osg::Camera It's the same pattern as: #include <string> //Provides std::string So I think it's safe to say that authors of the OSG wanted to follow the same pattern as in the C++ Standard Library. My personal opinion is that it's better to have a file extension, even if only to be able to search for header files.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40624930', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7165526/']}
jdg_381846
stackexchange
llm_judgeable_groundtruth_similarity
44820
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: Does every locally compact second countable space have a non-trivial automorphism? The motivation for this question comes from something I'm thinking about in logic. Now provide the response and nothing else.
After a bit of looking around I found an even nicer answer: The answer is no, even for compact metric spaces. More precisely, in H. Cook, Continua which admit only the identity mapping onto non-degenerate subcontinua , Fund. Math. 60 (1967) , 241–249 there is the following Theorem 3 on page 248 (it should probably be Theorem 13, never seen such a typo...). If $n$ is a positive integer, there exists a compact metric continuum $H_n$, with an atomic mapping onto a simple closed curve, such that there exist $n$, and only $n$, mappings of $H_n$ onto $H_n$, each of them is a homeomorphism, and there exists no mapping of $H_n$ onto a proper nondegenerate subcontinuum. While I only understand roughly half of the words used here, I am sure that this means in particular: $\# \operatorname{Aut}(H_n) = n$. Put $n = 1$ and we have what we want (I'm cheating a bit because that case is the most difficult one, and is settled in in the "slightly technical" Theorem 6 already which I didn't want to reproduce here for that reason). Added: The paper by the same H. Cook, Upper semi-continuous continuum-valued mappings onto circle like continua , Fund. Math. 60 (1967) , 233–239 is also of relevance for understanding the theorem quoted here. As explained by Henno Brandsma in his answer, J. de Groot's paper Groups represented by homeomorphism groups I , Math. Annalen 138 (1959), 80–102, and its predecessor J. de Groot and R. J. Wille, Rigid continua and topological group-pictures , Arch. Math. 9 (1958), 441–446 started these investigations. Added Later: Here's a freely accessible link to Brian M. Scott's paper On the existence of totally inhomogeneous spaces , Proc. Amer. Math. Soc. 51 (1975), 489–493 mentioned in a comment and in Henno's answer.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/44820', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/12008/']}
jdg_381847
stackexchange
llm_judgeable_groundtruth_similarity
1036703
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I created a site using ning, when i open the site in IE, I get an error "dojo is undefined". The page display is totally haywire. But the site works perfectly in other browsers (i have tried in safari only). I am looking for some workaround / fix on the server side, since i do not expect users to change their IE parameters Thanks Now provide the response and nothing else.
You haven't shown your class declaration - my guess is that your class doesn't extend Servlet or HttpServlet . If it does , then check how many different servlet.jar files you have in your deployment - it could be that it's being loaded by two different classloaders.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1036703', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/128015/']}
jdg_381848
stackexchange
llm_judgeable_groundtruth_similarity
17530408
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Got a question about printing Integers with thousands/millions separator. I got a Textfile where i got Country, City,Total Population. I have to read in the File, and sort by country. If country is eual, i have to sort descending by population. Textfile is like: Australia........Sydney.........10.123.456 Brazil...........Sao Paulo.......7.123.345 I read all 3 into a seperated string. Then i erase all "." in the population string. Then i use atoi() to cast the population string to an integer. Now i can sort by population if country is equal. This sort works correctly. So far so good. But i need to get thousand/millions seperator into the printing of the population. If i use string,with the "." for population, sorting dont work correctly.Its sorted like: x........x......1.123456 x........x......10.123.456 x........x......2.123.232 It have to look like: Australia........Sydney.........10.123.456 Australia........Brisbane.......8.123.456 Is there a way to manipulate the printing by adding separator the the int again? Many Thanks in advance Now provide the response and nothing else.
imbue() the output stream with a locale that has the desired separator. For example: #include <iostream>#include <locale>int main(){ // imbue the output stream with a locale. int i = 45749785; std::cout << i << "\n"; std::cout.imbue(std::locale("")); std::cout << i << "\n";} Output on my machine (and online demo ): 4574978545,749,785 As commented, and answered, by James Kanze imbue the input stream also to read the separated int values without manually modifying the input. See Stroustrop's Appendix D: Locales for a detailed overview of locales.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17530408', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2546565/']}
jdg_381849
stackexchange
llm_judgeable_groundtruth_similarity
2625291
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: So I know this is probably a really obvious question, but I'm a bit unclear on this. Why is $\sin(x^3)$ odd? Is it because you can substitute $u = x^3$ and then $\sin(x^3)=\sin(u)$ Then you can say $\sin(-u) = -\sin(u)$? The part about this that seems weird to me is that I don't understand why rules for $\sin(x)$ should work for $\sin(f(x))$. If someone can please explain to me what is going on that would be really helpful. Thanks. Now provide the response and nothing else.
Pure definition: A function $f$ is odd if $f(-x) = - f(x)$ for all $x$. So $\sin((-x)^3) = \sin(-x^3) = - \sin (x^3)$. So it is odd. ....... One thing to note, is that if $f$ is odd, and $g$ is also odd then $f\circ g$ is odd because: $f(g(-x) = f(-g(x)) = -f(g(x))$. And $x^3$ is odd because $(-x)^3 = (-1*x)^3 = (-1)^3x^3 = (-1)*x^3 = -x^3$ An $\sin x$ is odd because .... well, it's a basic trigonometric identity that $\sin (-x) = -\sin (x)$. Just draw a picture. The $y$ value of a point of a circle at an angle will be the negative of the $y$ value of the angle in the opposite direction. ===== Is it because you can substitute $u=x^3$ and then $sin(x^3)=sin(u)$ Then you can say $sin(−u)=−sin(u)$? Only if you can also say that $-u = (-x)^3$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2625291', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/258116/']}
jdg_381850
stackexchange
llm_judgeable_groundtruth_similarity
19390136
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 Project I'm writing a Java command line interface to a C library of internal networking and network testing tools using the Java Native Interface. The C code (which I didn't write) is complex and low level, often manipulates memory at the bit level, and uses raw sockets exclusively. The application is multi-threaded from the C side (pthreads running in the background) as well as the Java side (ScheduledThreadPoolExecutors running threads that call native code). That said, the C library should be mostly stable. The Java and JNI interface code, as it turns out, is causing problems. The Problem(s) The application crashes with a segmentation fault upon entry into a native C function. This only happens when the program is in a specific state (i.e. successfully running a specific native function causes the next call to another specific native function to segfault). Additionally, the application crashes with a similar-looking segfault when the quit command is issued, but again, only after successfully running that same specific native function. I'm an inexperienced C developer and an experienced Java developer -- I'm used to crashes giving me a specific reason and a specific line number. All I have to work from in this case is the hs_err_pid*.log output and the core dump. I've included what I could at the end of this question. My Work So Far Naturally, I wanted to find the specific line of code where the crash happened. I placed a System.out.println() right before the native call on the Java side and a printf() as the first line of the native function where the program crashes being sure to use fflush(stdout) directly after. The System.out call ran and the printf call didn't. This tells me that the segfault happened upon entry into the function -- something I've never seen before. I triple checked the parameters to the function, to ensure that they wouldn't act up. However, I only pass one parameter (of type jint ). The other two ( JNIEnv *env, jobject j_object ) are JNI constructs and out of my control. I commented out every single line in the function, leaving only a return 0; at the end. The segfault still happened. This leads me to believe that the problem is not in this function. I ran the command in different orders (effectively running the native functions different orders). The segfaults only happen when one specific native function is run before the crashing function call. This specific function appears to behave properly when it is run. I printed the value of the env pointer and the value of &j_object near the end of this other function, to ensure that I didn't somehow corrupt them. I don't know if I corrupted them, but both have non-zero values upon exiting the function. Edit 1: Typically, the same function is run in many threads (not usually concurrently, but it should be thread safe). I ran the function from the main thread without any other threads active to ensure that multithreading on the Java side wasn't causing the issue. It wasn't, and I got the same segfault. All of this perplexes me. Why is does it still segfault if I comment out the whole function, except for the return statement? If the problem is in this other function, why doesn't it fail there? If it's a problem where the first function messes up the memory and the second function illegally accesses the corrupt memory, why doesn't if fail on the line with the illegal access, rather than on entry to the function? If you see an internet article where someone explains a problem similar to mine, please comment it. There are so many segfault articles, and none seem to contain this specific problem. Ditto for SO questions. The problem may also be that I'm not experienced enough to apply an abstract solution to this problem. My Question What can cause a Java native function (in C) to segfault upon entry like this? What specific things can I look for that will help me squash this bug? How can I write code in the future that will help me avoid this problem? Helpful Info For the record, I can't actually post the code. If you think a description of the code would be helpful, comment and I'll edit it in. Error Message ## A fatal error has been detected by the Java Runtime Environment:## SIGSEGV (0xb) at pc=0x00002aaaaaf6d9c3, pid=2185, tid=1086892352## JRE version: 6.0_21-b06# Java VM: Java HotSpot(TM) 64-Bit Server VM (17.0-b16 mixed mode linux-amd64 )# Problematic frame:# j path.to.my.Object.native_function_name(I)I+0## An error report file with more information is saved as:# /path/to/hs_err_pid2185.log## If you would like to submit a bug report, please visit:# http://java.sun.com/webapps/bugreport/crash.jsp# The crash happened outside the Java Virtual Machine in native code.# See problematic frame for where to report the bug.# The Important Bits of the hs_err_pid*.log File --------------- T H R E A D ---------------Current thread (0x000000004fd13800): JavaThread "pool-1-thread-1" [_thread_in_native, id=2198, stack(0x0000000040b8a000,0x0000000040c8b000)]siginfo:si_signo=SIGSEGV: si_errno=0, si_code=128 (), si_addr=0x0000000000000000Registers:RAX=0x34372e302e3095e1, RBX=0x00002aaaae39dcd0, RCX=0x0000000000000000, RDX=0x0000000000000000RSP=0x0000000040c89870, RBP=0x0000000040c898c0, RSI=0x0000000040c898e8, RDI=0x000000004fd139c8R8 =0x000000004fb631f0, R9 =0x000000004faf5d30, R10=0x00002aaaaaf6d999, R11=0x00002b1243b39580R12=0x00002aaaae3706d0, R13=0x00002aaaae39dcd0, R14=0x0000000040c898e8, R15=0x000000004fd13800RIP=0x00002aaaaaf6d9c3, EFL=0x0000000000010202, CSGSFS=0x0000000000000033, ERR=0x0000000000000000 TRAPNO=0x000000000000000dStack: [0x0000000040b8a000,0x0000000040c8b000], sp=0x0000000040c89870, free space=3fe0000000000000018kNative frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)j path.to.my.Object.native_function_name(I)I+0j path.to.my.Object$CustomThread.fire()V+18j path.to.my.CustomThreadSuperClass.run()V+1j java.util.concurrent.Executors$RunnableAdapter.call()Ljava/lang/Object;+4j java.util.concurrent.FutureTask$Sync.innerRun()V+30j java.util.concurrent.FutureTask.run()V+4j java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(Ljava/util/concurrent/ScheduledThreadPoolExecutor$ScheduledFutureTask;)V+1j java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run()V+15j java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Ljava/lang/Runnable;)V+59j java.util.concurrent.ThreadPoolExecutor$Worker.run()V+28j java.lang.Thread.run()V+11v ~StubRoutines::call_stubV [libjvm.so+0x3e756d]V [libjvm.so+0x5f6f59]V [libjvm.so+0x3e6e39]V [libjvm.so+0x3e6eeb]V [libjvm.so+0x476387]V [libjvm.so+0x6ee452]V [libjvm.so+0x5f80df]Java frames: (J=compiled Java code, j=interpreted, Vv=VM code)j path.to.my.Object.native_function_name(I)I+0j path.to.my.Object$CustomThread.fire()V+18j path.to.my.CustomThreadSuperClass.run()V+1j java.util.concurrent.Executors$RunnableAdapter.call()Ljava/lang/Object;+4j java.util.concurrent.FutureTask$Sync.innerRun()V+30j java.util.concurrent.FutureTask.run()V+4j java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(Ljava/util/concurrent/ScheduledThreadPoolExecutor$ScheduledFutureTask;)V+1j java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run()V+15j java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Ljava/lang/Runnable;)V+59j java.util.concurrent.ThreadPoolExecutor$Worker.run()V+28j java.lang.Thread.run()V+11v ~StubRoutines::call_stub--------------- P R O C E S S ---------------Java Threads: ( => current thread ) 0x000000004fabc800 JavaThread "pool-1-thread-6" [_thread_new, id=2203, stack(0x0000000000000000,0x0000000000000000)] 0x000000004fbcb000 JavaThread "pool-1-thread-5" [_thread_blocked, id=2202, stack(0x0000000042c13000,0x0000000042d14000)] 0x000000004fbc9800 JavaThread "pool-1-thread-4" [_thread_blocked, id=2201, stack(0x0000000042b12000,0x0000000042c13000)] 0x000000004fbc7800 JavaThread "pool-1-thread-3" [_thread_blocked, id=2200, stack(0x0000000042a11000,0x0000000042b12000)] 0x000000004fc54800 JavaThread "pool-1-thread-2" [_thread_blocked, id=2199, stack(0x0000000042910000,0x0000000042a11000)]=>0x000000004fd13800 JavaThread "pool-1-thread-1" [_thread_in_native, id=2198, stack(0x0000000040b8a000,0x0000000040c8b000)] 0x000000004fb04800 JavaThread "Low Memory Detector" daemon [_thread_blocked, id=2194, stack(0x0000000041d0d000,0x0000000041e0e000)] 0x000000004fb02000 JavaThread "CompilerThread1" daemon [_thread_blocked, id=2193, stack(0x0000000041c0c000,0x0000000041d0d000)] 0x000000004fafc800 JavaThread "CompilerThread0" daemon [_thread_blocked, id=2192, stack(0x0000000040572000,0x0000000040673000)] 0x000000004fafa800 JavaThread "Signal Dispatcher" daemon [_thread_blocked, id=2191, stack(0x0000000040471000,0x0000000040572000)] 0x000000004fad6000 JavaThread "Finalizer" daemon [_thread_blocked, id=2190, stack(0x0000000041119000,0x000000004121a000)] 0x000000004fad4000 JavaThread "Reference Handler" daemon [_thread_blocked, id=2189, stack(0x0000000041018000,0x0000000041119000)] 0x000000004fa51000 JavaThread "main" [_thread_in_vm, id=2186, stack(0x00000000418cc000,0x00000000419cd000)]Other Threads: 0x000000004facf800 VMThread [stack: 0x0000000040f17000,0x0000000041018000] [id=2188] 0x000000004fb0f000 WatcherThread [stack: 0x0000000041e0e000,0x0000000041f0f000] [id=2195]VM state:not at safepoint (normal execution)VM Mutex/Monitor currently owned by a thread: NoneHeap PSYoungGen total 305856K, used 31465K [0x00002aaadded0000, 0x00002aaaf3420000, 0x00002aaaf3420000) eden space 262208K, 12% used [0x00002aaadded0000,0x00002aaadfd8a6a8,0x00002aaaedee0000) from space 43648K, 0% used [0x00002aaaf0980000,0x00002aaaf0980000,0x00002aaaf3420000) to space 43648K, 0% used [0x00002aaaedee0000,0x00002aaaedee0000,0x00002aaaf0980000) PSOldGen total 699072K, used 0K [0x00002aaab3420000, 0x00002aaadded0000, 0x00002aaadded0000) object space 699072K, 0% used [0x00002aaab3420000,0x00002aaab3420000,0x00002aaadded0000) PSPermGen total 21248K, used 3741K [0x00002aaaae020000, 0x00002aaaaf4e0000, 0x00002aaab3420000) object space 21248K, 17% used [0x00002aaaae020000,0x00002aaaae3c77c0,0x00002aaaaf4e0000)VM Arguments:jvm_args: -Xms1024m -Xmx1024m -XX:+UseParallelGC--------------- S Y S T E M ---------------OS:Red Hat Enterprise Linux Client release 5.5 (Tikanga)uname:Linux 2.6.18-194.8.1.el5 #1 SMP Wed Jun 23 10:52:51 EDT 2010 x86_64libc:glibc 2.5 NPTL 2.5rlimit: STACK 10240k, CORE 102400k, NPROC 10000, NOFILE 1024, AS infinityload average:0.21 0.08 0.05CPU:total 1 (1 cores per cpu, 1 threads per core) family 6 model 26 stepping 4, cmov, cx8, fxsr, mmx, sse, sse2, sse3, ssse3, sse4.1, sse4.2, popcntMemory: 4k page, physical 3913532k(1537020k free), swap 1494004k(1494004k free)vm_info: Java HotSpot(TM) 64-Bit Server VM (17.0-b16) for linux-amd64 JRE (1.6.0_21-b06), built on Jun 22 2010 01:10:00 by "java_re" with gcc 3.2.2 (SuSE Linux)time: Tue Oct 15 15:08:13 2013elapsed time: 13 seconds Valgrind Output I don't really know how to use Valgrind properly. This is what came up when running valgrind app arg1 ==2184== ==2184== HEAP SUMMARY:==2184== in use at exit: 16,914 bytes in 444 blocks==2184== total heap usage: 673 allocs, 229 frees, 32,931 bytes allocated==2184== ==2184== LEAK SUMMARY:==2184== definitely lost: 0 bytes in 0 blocks==2184== indirectly lost: 0 bytes in 0 blocks==2184== possibly lost: 0 bytes in 0 blocks==2184== still reachable: 16,914 bytes in 444 blocks==2184== suppressed: 0 bytes in 0 blocks==2184== Rerun with --leak-check=full to see details of leaked memory==2184== ==2184== For counts of detected and suppressed errors, rerun with: -v==2184== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 7 from 7) Edit 2: GDB Output and Backtrace I ran it through with GDB. I made sure that the C library was compiled with the -g flag. $ gdb `which java`GNU gdb (GDB) Red Hat Enterprise Linux (7.0.1-23.el5)Copyright (C) 2009 Free Software Foundation, Inc.License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>This is free software: you are free to change and redistribute it.There is NO WARRANTY, to the extent permitted by law. Type "show copying"and "show warranty" for details.This GDB was configured as "x86_64-redhat-linux-gnu".For bug reporting instructions, please see:<http://www.gnu.org/software/gdb/bugs/>...Reading symbols from /usr/bin/java...(no debugging symbols found)...done.(gdb) run -jar /opt/scts/scts.jar test.configStarting program: /usr/bin/java -jar /opt/scts/scts.jar test.config[Thread debugging using libthread_db enabled]Executing new program: /usr/lib/jvm/java-1.6.0-sun-1.6.0.21.x86_64/jre/bin/java[Thread debugging using libthread_db enabled][New Thread 0x4022c940 (LWP 3241)][New Thread 0x4032d940 (LWP 3242)][New Thread 0x4042e940 (LWP 3243)][New Thread 0x4052f940 (LWP 3244)][New Thread 0x40630940 (LWP 3245)][New Thread 0x40731940 (LWP 3246)][New Thread 0x40832940 (LWP 3247)][New Thread 0x40933940 (LWP 3248)][New Thread 0x40a34940 (LWP 3249)] ... my program does some work, and starts a background thread ... [New Thread 0x41435940 (LWP 3250)] ... I type the command that seems to cause the segfault on the next command; the new threads are expected ... [New Thread 0x41536940 (LWP 3252)][New Thread 0x41637940 (LWP 3253)][New Thread 0x41738940 (LWP 3254)][New Thread 0x41839940 (LWP 3255)][New Thread 0x4193a940 (LWP 3256)] ... I type the command that actually triggers the segfault. The new thread is expected, since the function is run in its own thread. If it did not segfault, it would have created the same number of thread as the previous command ... [New Thread 0x41a3b940 (LWP 3257)]Program received signal SIGSEGV, Segmentation fault.[Switching to Thread 0x41839940 (LWP 3255)]0x00002aaaabcaec45 in ?? () ... I furiously read through the gdb help, then run the backtrace ... (gdb) bt#0 0x00002aaaabcaec45 in ?? ()#1 0x00002aaaf3ad7800 in ?? ()#2 0x00002aaaf3ad81e8 in ?? ()#3 0x0000000041838600 in ?? ()#4 0x00002aaaeacddcd0 in ?? ()#5 0x0000000041838668 in ?? ()#6 0x00002aaaeace23f0 in ?? ()#7 0x0000000000000000 in ?? () ... Shouldn't that have symbols if I compiled with -g ? I did, according to the lines from the output of make : gcc -g -Wall -fPIC -c -I ...gcc -g -shared -W1,soname, ... Now provide the response and nothing else.
Looks like I've solved the issue, which I'll outline here for the benefit of others. What Happened The cause of the segmentation fault was that I used sprintf() to assign a value to a char * pointer which had not been assigned a value. Here is the bad code: char* ip_to_string(uint32_t ip){ unsigned char bytes[4]; bytes[0] = ip & 0xFF; bytes[1] = (ip >> 8) & 0xFF; bytes[2] = (ip >> 16) & 0xFF; bytes[3] = (ip >> 24) & 0xFF; char *ip_string; sprintf(ip_string, "%d.%d.%d.%d", bytes[0], bytes[1], bytes[2], bytes[3]); return ip_string;} The pointer ip_string does not have a value here, which means it points to nothing. Except, that's not entirely true. What it points to is undefined . It could point anywhere. So in assigning a value to it with sprintf() , I inadvertently overwrote a random bit of memory. I believe that the reason for the odd behaviour (though I never confirmed this) was that the undefined pointer was pointing to somewhere on the stack. This caused the computer to be confused when certain functions were called. One way to fix this is to allocate memory and then point the pointer to that memory, which can be accomplished with malloc() . That solution would look similar to this: char* ip_to_string(uint32_t ip){ unsigned char bytes[4]; bytes[0] = ip & 0xFF; bytes[1] = (ip >> 8) & 0xFF; bytes[2] = (ip >> 16) & 0xFF; bytes[3] = (ip >> 24) & 0xFF; char *ip_string = malloc(16); sprintf(ip_string, "%d.%d.%d.%d", bytes[0], bytes[1], bytes[2], bytes[3]); return ip_string;} The problem with this is that every malloc() needs to be matched by a call to free() , or you have a memory leak. If I call free(ip_string) inside this function the returned pointer will be useless, and if I don't then I have to rely on the code that's calling this function to release the memory, which is pretty dangerous. As far as I can tell, the "right" solution to this is to pass an already allocated pointer to the function, such that it is the function's responsibility to fill pointed to memory. That way, calls to malloc() and free() can be made in the block of code. Much safer. Here's the new function: char* ip_to_string(uint32_t ip, char *ip_string){ unsigned char bytes[4]; bytes[0] = ip & 0xFF; bytes[1] = (ip >> 8) & 0xFF; bytes[2] = (ip >> 16) & 0xFF; bytes[3] = (ip >> 24) & 0xFF; sprintf(ip_string, "%d.%d.%d.%d", bytes[0], bytes[1], bytes[2], bytes[3]); return ip_string;} Answers to the Questions What can cause a Java native function (in C) to segfault upon entry like this? If you assign a value to a pointer that hasn't been allocated memory, you may accidentally overwrite memory on the stack. This may not cause an immediate failure, but will probably cause problems when you call other functions later. What specific things can I look for that will help me squash this bug? Look for a segmentation fault like any other. Things like assigning a value to unallocated memory or dereferencing a null pointer. I'm not an expert on this, but I'm willing to bet that there are many web resources for this. How can I write code in the future that will help me avoid this problem? Be careful with pointers, especially when you are responsible for creating them. If you see a line of code that looks like this: type *variable; ... then look for a line that looks like ... variable = ...; ... and make sure that this line comes before writing to the pointed to memory.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19390136', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/625053/']}
jdg_381851
stackexchange
llm_judgeable_groundtruth_similarity
21407962
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 think, it's a different issue than this( remote rejected master -> master (pre-receive hook declined) ), and many people are facing the same issue, So I am posting a new here. My friend added me on bitbucket.org as an admin, so that I can help on his project. So, I wanted to start by taking a pull of the latest code on my local. Steps I followed: Goto empty folder git init git remote -v (this gives nothing) git remote add origin <path to git repo> git remote add master <path to git repo> git remote -v (this show both with fetch and push in brackets) git fetch origin master git pull origin master (I have latest code now, all files and folders) touch test (lets test a "test" commit) git status git add . git commit -m "testing, first commit" git push origin master error: Counting objects: 4, done.Delta compression using up to 2 threads.Compressing objects: 100% (2/2), done.Writing objects: 100% (3/3), 274 bytes | 0 bytes/s, done.Total 3 (delta 1), reused 0 (delta 0)remote: permission denied to update branch masterTo '<repo path>' ! [remote rejected] master -> master (pre-receive hook declined)error: failed to push some refs to '<repo path>' Now provide the response and nothing else.
It looks like the branch management (one of the admin settings) in bitbucket has been configured to only allow certain people to push directly to master. Try creating a branch - git checkout -b test , create your test commit and push git push origin test:test . You can always cleanly delete this branch once you have completed the test. The other option (probably best agreeing with whoever set this up) is you go to bitbucket and head to admin, branch management and remove master be too limited. cf - https://confluence.atlassian.com/display/BITBUCKET/Branch+management
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/21407962', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2462759/']}
jdg_381852
stackexchange
llm_judgeable_groundtruth_similarity
3479464
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 following process: we place $n$ points labelled $1...n$ uniformly at random on the interval $[0,1]$ . At each time step, two points $i, j$ are selected uniformly at random and $i$ updates its position to be a point chosen uniformly at random in the interval between the positions of $i$ and $j$ (so the interval $[p(i),p(j)]$ if $p(i) < p(j)$ or $[p(j),p(i)]$ otherwise, where $p(x)$ denotes the position of the point labelled $x$ ). What is the expected time until all points are within distance $\varepsilon$ of each other for some fixed $\varepsilon > 0$ ? What is the expected time until all points are either to the left or right of $\frac{1}{2}$ ? Asymptotic bounds are also very interesting to me. Now provide the response and nothing else.
Update: I'll prove that the expected time in question 1 (for fixed $\varepsilon$ ) is $\Theta(n \log n)$ , and that the expected time in question 2 is $\geq \Omega(n \log n)$ ; at the moment I don't have a good upper bound for question 2. Upper bound: Define $S = \sum_{1 \leq a, b \leq n} (p(a) - p(b))^2$ , and let $S_t$ be the value of $S$ at time $t$ . Now, at a fixed time $t$ , let $p$ denote the positions at time $t$ , and $p'$ denote the positions at time $t+1$ . Then $p'$ is determined from $p$ by independently picking $(i, j)$ uniformly from $\{1, \dots, n\}^2$ and $\lambda \sim \mathrm{Unif}[0, 1]$ , and setting $p'(a) = p(a)$ for all $a \neq i$ , and $p'(i) = \lambda p(i) + (1-\lambda) p(j)$ . Then we have \begin{align*}S_t - S_{t+1} &= 2 \sum_{a \neq i} \left((p(i) - p(a))^2 - (p'(i) - p(a))^2\right) \\&= 2(1-\lambda^2)(p(i) - p(j))^2 + 2 \sum_{a \neq i, j} \left((p(i) - p(a))^2 - (p'(i) - p(a))^2\right) \\&= 2(1-\lambda^2)(p(i) - p(j))^2 + 2 \sum_{a \neq i, j} (p(i) - p'(i))(p(i) + p'(i) - 2p(a)) \\&= 2\left(1-\lambda^2 + (n-2)\lambda(1-\lambda)\right)(p(i) - p(j))^2 \\&\qquad+ 2 (1-\lambda) \sum_{a \neq i, j} (p(i) - p(j))(p(i) + p(j) - 2p(a)) \end{align*} There is a slight technicality here in that it appears we have assumed $i \neq j$ , but in fact these expressions are still equal in the case $i = j$ : the LHS is $0$ since then $S_{t+1} = S_t$ , and the RHS is $0$ since $p(i) = p(j)$ . Now, upon taking expectations conditional on $S_t$ , the second term vanishes because it's antisymmetric in $i, j$ (i.e. it is negated when we swap $i, j$ ), so we have \begin{align*}S_t - \mathbb{E}[S_{t+1} | S_t] &= \mathbb{E}\bigg[ 2\left(1-\lambda^2 + (n-2)\lambda(1-\lambda)\right)(p(i) - p(j))^2 \,\bigg|\, S_t \bigg] \\&= 2\,\mathbb{E}\big[1-\lambda^2 + (n-2)\lambda(1-\lambda)\,\big|\, S_t\big] \mathbb{E}[(p(i) - p(j))^2 \,|\, S_t] \\&= 2\left(\frac{n+2}{6}\right)\left(\frac{S_t}{n^2}\right)\end{align*} (where the second equality follows by independence),hence $$\mathbb{E}[S_{t+1}|S_t] = \left(1 - \frac{n+2}{3n^2}\right)S_t$$ which means, in particular, that $\mathbb{E}[S_{t+1}] = \left(1 - \frac{n+2}{3n^2}\right)\mathbb{E}[S_t]$ . We can now use this to get an upper bound for question 1. Note we have $\mathbb{E}[S_0] \leq n^2$ and $\mathbb{E}[S_{t+1}] \leq e^{-1/3n} \mathbb{E}[S_t]$ , so $\mathbb{E}[S_t] \leq n^2 e^{-t/3n}$ , and thus the probability that there are two points which are at least $\varepsilon$ apart at time $t$ is at most $(n^2 / \varepsilon^2) e^{-t/3n}$ (by Markov's inequality, since if this holds we must have $S_t \geq \varepsilon^2$ ). Letting $T_1$ be the time at which all points are within distance $\varepsilon$ of each other, this means $\mathbb{P}[T_1 > t] \leq (n^2 / \varepsilon^2) e^{-t/3n}$ , hence $$\mathbb{E}[T_1] = \sum_{t=0}^\infty \mathbb{P}[T_1 > t] \leq \sum_{t=0}^\infty \min \{(n^2 / \varepsilon^2) e^{-t/3n}, 1\},$$ which we can approximate as $$6n \log(n / \varepsilon) + \int_{6n\log(n/\varepsilon)}^\infty (n^2 / \varepsilon^2) e^{-t/3n} \,dt = 6n\log(n / \varepsilon) + 3n.$$ Therefore $\mathbb{E}[T_1] \leq O(n \log(n/\varepsilon))$ . Lower bounds: I should have thought of this before -- we can actually get some basic coupon-collector-type lower bounds for both questions. I'm not really optimizing for good constants below. Lemma: Suppose we have two disjoint sets $A, B \subset \{1, \dots, n\}$ with $|A|, |B| \geq k$ . At each time step we choose a uniformly random element of $\{1, \dots, n\}$ . Then the expected time until either all elements of $A$ have been chosen at least once or all elements of $B$ have been chosen at least once is at least $(n/2) \log k$ . Proof : This is essentially the same as the proof for the coupon collector's problem found here . Let $a_1, \dots, a_k$ be distinct elements of $A$ , and $b_1, \dots, b_k$ distinct elements of $B$ , and say that the pair $(a_i, b_i)$ is hit if one of $a_i, b_i$ is chosen. Note that our condition -- that all elements of $A$ are chosen or all elements of $B$ are chosen -- is satisfied only if all pairs $(a_1, b_1), \dots, (a_k, b_k)$ are hit. Let $t_r$ be the time until the $r$ -th pair is hit after $r-1$ pairs are hit. After $r-1$ pairs are hit, the probability of hitting a new pair is $\frac{2(k-r+1)}{n}$ , hence $t_r$ has geometric distribution with expectation $\frac{n}{2(k-r+1)}$ , and the expected time until all pairs are hit is thus at least $$\sum_{r=1}^k \mathbb{E}[t_r] = \frac{n}{2} \sum_{r=1}^k \frac{1}{k-r+1} = \frac{n}{2} \sum_{r=1}^k \frac{1}{r} \geq \frac{n}{2} \log k.$$ Note that for question 1, at time $T_1$ all points lie in some interval $I$ of length $\leq \varepsilon$ , so all points initially outside of $I$ have moved, i.e. all points initially outside of $I$ have been chosen as the $i$ -value at some time-step. Defining $I^- = [0, (1+\varepsilon)/2]$ and $I^+ = [(1-\varepsilon)/2, 1]$ , this interval necessarily satisfies either $I \subset I^-$ or $I \subset I^+$ . Letting $A$ be the set of points outside of $I^-$ at $t = 0$ , and $B$ be the set of points outside of $I^+$ at $t = 0$ , this means that at time $T_1$ , either every element of $A$ has been chosen as $i$ or every element of $B$ has been chosen as $i$ . The complement of each of $I^-$ and $I^+$ is an interval of length $\frac{1 - \varepsilon}{2}$ , hence since the points are i.i.d. uniform on $[0, 1]$ at $t = 0$ , we have $|A|, |B| \geq \frac{1 - \varepsilon}{3} n$ with probability $1 - o(1)$ . Conditioning on the arrangement of points at $t = 0$ , by the Lemma the conditional expectation has $\mathbb{E}[T_1 \mid p|_{t = 0}] \geq \frac{1}{2} n \log (\frac{1-\varepsilon}{3}n)$ when $|A|, |B| \geq \frac{1 - \varepsilon}{3} n$ , hence the unconditional expectation has $\mathbb{E}[T_1] \geq \frac{1}{2} (1 - o(1)) n \log(\frac{1-\varepsilon}{3}n) = \Omega(n \log n)$ . Similarly, for question 2, let $A$ be the set of points in $[0, 1/2)$ at $t = 0$ , and $B$ be the set of points in $(1/2, 1]$ at $t = 0$ . Then at time $T_2$ (when all points lie on one side of $1/2$ ), either all points in $A$ have moved, or all points in $B$ have moved. Since with probability $1 - o(1)$ we have $|A|, |B| \geq n/3$ , the same argument as above gives $\mathbb{E}[T_2] \geq \frac{1}{2} (1 - o(1)) n \log(n/3) = \Omega(n \log n)$ . Computational results: I don't have an upper bound for question 2 right now, but I ran some simulations of the process $50$ times for each of $n = 10, 11, \dots, 250$ . The estimates for $\mathbb{E}[T_2]/n$ are plotted below. Based on this, $\mathbb{E}[T_2]/n$ appears to be linear in $\log n$ , suggesting the possibility of a matching upper bound for $\mathbb{E}[T_2]$ . Least squares gives a best-fit line of $\mathbb{E}[T_2]/n \approx 5.75 \log n - 7.19$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3479464', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/15902/']}
jdg_381853
stackexchange
llm_judgeable_groundtruth_similarity
47405
Below is a question asked on the forum datascience.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am replicating, in Keras, the work of a paper where I know the values of epoch and batch_size . Since the dataset is quite large, I am using fit_generator . I would like to know what to set in steps_per_epoch given epoch value and batch_size . Is there a standard way? Now provide the response and nothing else.
As mentioned in Keras' webpage about fit_generator() : steps_per_epoch : Integer. Total number of steps (batches of samples)to yield from generator before declaring one epoch finished andstarting the next epoch. It should typically be equal to ceil(num_samples / batch_size) . Optional for Sequence: if unspecified,will use the len(generator) as a number of steps. You can set it equal to num_samples // batch_size , which is a typical choice. However, steps_per_epoch give you the chance to "trick" the generator when updating the learning rate using ReduceLROnPlateau() callback , because this callback checks the drop of the loss once each epoch has finished. If the loss has stagnated for a patience number of consecutive epochs, the callback decreases the learning rate to "slow-cook" the network. If your dataset is huge, as it is usually the case when you need to use generators, you would probably like to decay the learning rate within a single epoch (since it includes a big number of data). This can be achieved by setting steps_per_epoch to a value that is less than num_samples // batch_size without affecting the overall number of training epochs of your model. Imagine this case as using mini-epochs within your normal epochs to change the learning rate because your loss has stagnated. I have found it very useful in my applications .
{}
{'log_upvote_score': 5, 'links': ['https://datascience.stackexchange.com/questions/47405', 'https://datascience.stackexchange.com', 'https://datascience.stackexchange.com/users/65133/']}
jdg_381854
stackexchange
llm_judgeable_groundtruth_similarity
40102686
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 package.json I'm pointing local package my-custom-i18n by its relative path: package.json "dependencies": { "core-js": "^2.4.1", "my-custom-i18n": "./../MyProject.Shared/myproject-i18n", "rxjs": "5.0.0-beta.12", ...} npm install installs packages correctly, but yarn has problem with it and simply cannot find this package: yarn output $ yarnyarn install v0.15.1info No lockfile found.[1/4] Resolving packages...error Couldn't find package "myproject-i18n" on the "npm" registry.info Visit http://yarnpkg.com/en/docs/cli/install for documentation about this command. I see that it looks it on the npm registry, where this package doesn't live. Question Is there any change to use yarn with local packages?By local packages I mean packages pointed by relative path as my-custom-i18n . Now provide the response and nothing else.
For yarn version < 2.x Yarn requires prefix file: for local packages. For relative path: yarn add file:./../your-project For absolute path yarn add file:/dev/your-project For your example, dependency in package.json would be declared as follows: "my-custom-i18n": "file:./../MyProject.Shared/myproject-i18n", This works both for Yarn and NPM as well. It is incompatibility with NPM client, Yarn team is aware and declared to support this behavior - reference on GitHub issue . Update: Since v0.21.0 release, file: prefix is not needed.See pull-request with fix and changelog .
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/40102686', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2029818/']}
jdg_381855
stackexchange
llm_judgeable_groundtruth_similarity
14307996
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 someone tell me when are literal classes needed in C++ ? I am getting a little confused from constexpr constructors, constexpr members, and I can't see what the point is. I'd like to see some practical use of it. Also I'd want to know if a set member function needs to be constexpr , i.e.: constexpr void set_num(int a) { num = a; } Now provide the response and nothing else.
In C++03 this object has dynamic initialization struct Data { int i; int j;};Data init_data(); // calculate somethingconst Data data = init_data(); i.e. when the program starts, before main runs, the function will be called and the object gets initialized. In C++11 the object can have constant initialization , a form of static initialization , meaning that its value is set at compile-time and it's initialized before the program begins. This is useful to avoid the static initialization order fiasco among other things. To ensure the type gets constant initialization it must be initialized by a constant expression, so must have a constexpr constructor and any functions called in the full expression must be constexpr functions. The type Data is trivial so its implicitly-declared constructors are constexpr constructors, so to make the global data undergo constant initialization we just need to make init_data() be a constexpr function: struct Data { int i; int j;};constexpr Data init_data(); // calculate somethingconstexpr Data data = init_data(); The advantage of a literal type is that such types can be used in other constant expressions i.e. in contexts that require compile-time constants. So now that we have our data object as a compile-time constant, we can use it in other constant expressions e.g. to initialize other compile-time constants: const int i = ::data.i; And we can use the Data type for a static data member with an in-class initializer: struct MoreData { static constexpr Data zerozero = Data{}; // OK, Data is a literal type}; If Data wasn't a literal type we would have to write: struct MoreData { static const Data zerozero;};// in moredata.ccconst Data MoreData::zerozero = Data{}; And then code which only sees the header doesn't know the value of MoreData::zerozero and can't use it in compile-time optimisations. So the advantage of the "literal type" rules is that they allow you to define new class types that can be used in constant expressions. In C++03 only very few types, such as integers, could be used in constant expressions, e.g. integer literals such as 1 or 0x23 or compile-time constants of integer type. In C++11 you can write you own types which can have moderately complicated logic in their constructors (anything that can be expressed in a constexpr function) but can still be used as a compile-time constant. Also I'd want to know if a set member function needs to be constexpr, i.e. A constexpr member function is a special case of a const member function, so it can't modify (non -mutable ) members of the type. A setter function, which modifies the object, can't be const. To be a literal type a class must follow some rules including having at least one constexpr constructor. That doesn't mean all objects of that type must be constexpr constants, it just means that objects of that type can be constexpr constants if they are declared as such and are initialized using one of the class' constexpr constructors. To use the Data example again, most objects in your program would not be constants: Data d = { 0, 1 };d.i = d.i + 5; So if you added a setter, a function which modifies the object, then it would only make sense to use it on non-const objects of that type, and like any other functions which modifies the type it should not be
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14307996', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1973164/']}
jdg_381856
stackexchange
llm_judgeable_groundtruth_similarity
25785575
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 json stored as text in one of my database row. the json data is as following [{"id":67272,"name":"EE_Quick_Changes_J_UTP.xlsx"},{"id":67273,"name":"16167.txt"},{"id":67274,"name":"EE_12_09_2013_Bcum_Searchall.png"}] to parse this i want to use postgresql method json_populate_recordset() when I post a command like select json_populate_recordset(null::json,'[{"id":67272,"name":"EE_Quick_Changes_J_UTP.xlsx"},{"id":67273,"name":"16167.txt"},{"id":67274,"name":"EE_12_09_2013_Bcum_Searchall.png"}]') from anoop; it gives me following errorfirst argument of json_populate_recordset must be a row type note : in the from clause "anoop" is the table name. can anyone suggest me how to use the json_populate_recordset method to extract data from this json string. I got method's reference from http://www.postgresql.org/docs/9.3/static/functions-json.html Now provide the response and nothing else.
The first argument passed to pgsql function json_populate_recordset should be a row type. If you want to use the json array to populate the existing table anoop you can simply pass the table anoop as the row type like this: insert into anoopselect * from json_populate_recordset(null::anoop, '[{"id":67272,"name":"EE_Quick_Changes_J_UTP.xlsx"}, {"id":67273,"name":"16167.txt"}, {"id":67274,"name":"EE_12_09_2013_Bcum_Searchall.png"}]'); Here the null is the default value to insert into table columns not set in the json passed. If you don't have an existing table, you need to create a row type to hold your json data (ie. column names and their types) and pass it as the first parameter, like this anoop_type : create TYPE anoop_type AS (id int, name varchar(100));select * from json_populate_recordset(null :: anoop_type, '[...]') --same as above
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/25785575', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3578771/']}
jdg_381857
stackexchange
llm_judgeable_groundtruth_similarity
3234514
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a hint that we need to use an identity that $\sin^4x+\cos^4x=1-\frac{1}{2}\sin^22x$ in order to find the value of $\sin {^4 \frac{\pi}{16}} +\sin {^4 \frac{3\pi}{16}} +\sin {^4 \frac{5\pi}{16}} +\sin {^4 \frac{7\pi}{16}} $ . I tried and error for different values of $x$ but I still could not eliminate the $\cos$ -term Now provide the response and nothing else.
We have $$\sin\frac{\pi}{16}=\cos(\frac{\pi}{2}-\frac{\pi}{16})=\cos\frac{7\pi}{16} $$ and $$\sin\frac{3\pi}{16}=\cos(\frac{\pi}{2}-\frac{3\pi}{16})=\cos\frac{5\pi}{16}. $$ Thus $$A=\sin^4\frac{\pi}{16}+\sin^4\frac{3\pi}{16}+\sin^4\frac{5\pi}{16}+\sin^4\frac{7\pi}{16} $$ $$=\sin^4\frac{\pi}{16}+\sin^4\frac{3\pi}{16}+\cos^4\frac{3\pi}{16}+\cos^4\frac{\pi}{16}. $$ Using the hint, we get: $$A=1-\frac{1}{2}\sin^2\frac{2\pi}{16}+1-\frac{1}{2} \sin^2\frac{6\pi}{16}$$ $$=2-\frac{1}{2}(\sin^2\frac{\pi}{8}+\sin^2\frac{3\pi}{8})$$ $$=2-\frac{1}{2}(\sin^2\frac{\pi}{8}+\cos^2\frac{\pi}{8})=2-\frac{1}{2}=\frac{3}{2}. $$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3234514', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/592397/']}
jdg_381858
stackexchange
llm_judgeable_groundtruth_similarity
17063
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: everyone. I am afraid that my question is too trivial. But here it is. The Klein four group is the first counterexample to the the statement: "If all proper subgroups of a group are cyclic, then the group is cyclic." I am looking for other examples, if any. Are there? Thanks in advance. Now provide the response and nothing else.
The example of the Klein group, $\mathbb{Z}_2 \times \mathbb{Z}_2$, generalizes naturally to $\mathbb{Z}_p \times \mathbb{Z}_p$ for any prime $p$. Other finite examples include any nonabelian group of order $pq$, where $p$ and $q$ are primes (such a group exists whenever $p-1$ is divisible by $q$). But there are even infinite examples. For all sufficiently large primes $p$, there exist infinite groups all of whose proper nontrivial subgroups are cyclic of order $p$. These are the Tarski monsters .
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/17063', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/5595/']}
jdg_381859
stackexchange
llm_judgeable_groundtruth_similarity
14907987
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm getting the following warning: Access to foreach variable in closure. May have different behaviour when compiled with different versions of compiler. This is what it looks like in my editor: I know how fix this warning, but I want know why would I get this warning? Is this about the "CLR" version? Is it related to "IL"? Now provide the response and nothing else.
There are two parts to this warning. The first is... Access to foreach variable in closure ...which is not invalid per se but it is counter-intuitive at first glance. It's also very hard to do right. (So much so that the article I link to below describes this as "harmful".) Take your query, noting that the code you've excerpted is basically an expanded form of what the C# compiler (before C# 5) generates for foreach 1 : I [don't] understand why [the following is] not valid: string s; while (enumerator.MoveNext()) { s = enumerator.Current; ... Well, it is valid syntactically. And if all you're doing in your loop is using the value of s then everything is good. But closing over s will lead to counter-intuitive behaviour. Take a look at the following code: var countingActions = new List<Action>();var numbers = from n in Enumerable.Range(1, 5) select n.ToString(CultureInfo.InvariantCulture);using (var enumerator = numbers.GetEnumerator()){ string s; while (enumerator.MoveNext()) { s = enumerator.Current; Console.WriteLine("Creating an action where s == {0}", s); Action action = () => Console.WriteLine("s == {0}", s); countingActions.Add(action); }} If you run this code, you'll get the following console output: Creating an action where s == 1Creating an action where s == 2Creating an action where s == 3Creating an action where s == 4Creating an action where s == 5 This is what you expect. To see something you probably don't expect, run the following code immediately after the above code: foreach (var action in countingActions) action(); You'll get the following console output: s == 5s == 5s == 5s == 5s == 5 Why? Because we created five functions that all do the exact same thing: print the value of s (which we've closed over). In reality, they're the same function ("Print s ", "Print s ", "Print s "...). At the point at which we go to use them, they do exactly what we ask: print the value of s . If you look at the last known value of s , you'll see that it's 5 . So we get s == 5 printed five times to the console. Which is exactly what we asked for, but probably not what we want. The second part of the warning... May have different behaviour when compiled with different versions of compiler. ...is what it is. Starting with C# 5, the compiler generates different code that "prevents" this from happening via foreach . Thus the following code will produce different results under different versions of the compiler: foreach (var n in numbers){ Action action = () => Console.WriteLine("n == {0}", n); countingActions.Add(action);} Consequently, it will also produce the R# warning :) My first code snippet, above, will exhibit the same behaviour in all versions of the compiler, since I'm not using foreach (rather, I've expanded it out the way pre-C# 5 compilers do). Is this for CLR version? I'm not quite sure what you're asking here. Eric Lippert's post says the change happens "in C# 5". So presumably you have to target .NET 4.5 or later with a C# 5 or later compiler to get the new behaviour, and everything before that gets the old behaviour. But to be clear, it's a function of the compiler and not the .NET Framework version. Is there relevance with IL? Different code produces different IL so in that sense there's consequences for the IL generated. 1 foreach is a much more common construct than the code you've posted in your comment. The issue typically arises through use of foreach , not through manual enumeration. That's why the changes to foreach in C# 5 help prevent this issue, but not completely.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/14907987', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_381860
stackexchange
llm_judgeable_groundtruth_similarity
8271853
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 android ActionBar may split into a top and bottom bars if activity's parameter " uiOptions " is set to " splitActionBarWhenNarrow ", note this parameter is only valid in ICS. Honeycomb has introduced a new approach to multi-select list items using action bar. When a item is under press & hold the list becomes into a multi-selection mode and the actionbar bar may be used to accomplish some actions. The actionbar setup is inherited from the list activity, i.e., if the activity has a split action bar the multi-selection will have too, and if the activity has only the top bar, so, the multi-selection will be compliant with that. The question is, is it possible to have only a top action bar in the activity and when the list turns into multi-selection mode programmatically split the actionbar? Thanks! Now provide the response and nothing else.
No, you cannot switch between split and non-split action bars on the fly. The setter counterpart to android:uiOptions is on Window , not Activity . Window#setUiOptions is the method and the flag to use is ActivityInfo#UIOPTION_SPLIT_ACTION_BAR_WHEN_NARROW . However this isn't going to do what you want. Split action bar when narrow must be specified as the window is first configured before the window decor is initialized. In other words, once the window has been displayed (or even once you've called setContentView ) it's too late to change it. This was a conscious decision by the Android UX team. Action modes (including selection modes) are meant to mirror the configuration of the action bar on the current activity. This gives the user a single place to look for currently valid actions within the same activity.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8271853', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/465870/']}
jdg_381861
stackexchange
llm_judgeable_groundtruth_similarity
266216
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: From Wikipedia : The vector space of (equivalence classes of) measurable functions on $(S, Σ, μ)$ is denoted $L^0(S, Σ, μ)$. This doesn't seem connected to the definition of $L^p(S, Σ, μ), \forall p \in (0, \infty)$ as being the set of measurable functions $f$ such that $\int_S |f|^p d\mu <\infty$. So I wonder if I miss any connection, and why use the notation $L^0$ if there is no connection? Thanks and regards! Now provide the response and nothing else.
Note that when we restrict ourselves to the probability measures, then this terminology makes sense: $L^p$ is the space of those (equivalence classes of) measurable functions $f$ satisfying $$\int |f|^p<\infty.$$Therefore $L^0$ should be the space of those (equivalence classes of) measurable functions $f$ satisfying $$\int |f|^0=\int 1=1<\infty,$$that is the space of all (equivalence classes of) measurable functions $f$. And it is indeed the case.
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/266216', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/1281/']}
jdg_381862
stackexchange
llm_judgeable_groundtruth_similarity
206556
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Each line in a comma-separated file has 5 fields. a,b,c,d,ef,g,c,i,j,k,c,m,no,p,c,r,st,u,c,w,x,y,z,aa,bb How can I extract the lines which have c in the 3rd field and their 5th field is NOT empty? The result would be: a,b,c,d,ej,k,c,m,no,p,c,r,s Now provide the response and nothing else.
Possible solution with awk : awk -F',' '$3 == "c" && $5' file Depending on actual data this may not work as desired as mentioned in comments (thanks Janis for pointing this: it will miss f,g,c,i,0 e.g 5th field is 0) so you can do following: awk -F',' '$3 == "c" && $5 != ""' file And as this is the accepted answer I am adding not so obvious forcing 5th field to string (as in cuonglm(+1) solution): awk -F',' '$3 == "c" && $5""' file
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/206556', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/117446/']}
jdg_381863
stackexchange
llm_judgeable_groundtruth_similarity
12028568
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 increase the width of the column of excel sheet. as the i am writing trough code is long.and I need to drag the column manually to see the full text. I did this – HSSFRow dataRow = sampleDataSheet.createRow(0);HSSFCellStyle cellStyle = setHeaderStyle(sampleWorkbook);cellStyle.setWrapText(true);***sampleDataSheet.autoSizeColumn(1000000);*** But its not changing anything.. Now provide the response and nothing else.
This should work. However, sampleDataSheet.autoSizeColumn(1000000); auto-expands column 1000000. If you want to auto-expand column 0(the first column), use: sampleDataSheet.autoSizeColumn(0); To auto-expand column 0 to 9(the first 10 columns): for (int i=0; i<10; i++){ sampleDataSheet.autoSizeColumn(i);} Also, you should create all your rows and fill them with content first, before you call autoSizeColumn(so the column gets the width of the value with the broadest width). (If you want to set the column width to a fixed value, use HSSFSheet.setColumnWidth(int,int) instead.)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12028568', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/760754/']}
jdg_381864
stackexchange
llm_judgeable_groundtruth_similarity
4409502
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How do you use Paramiko to transfer complete directories?I'm trying to use: sftp.put("/Folder1","/Folder2") which is giving me this error - Error : [Errno 21] Is a directory Now provide the response and nothing else.
You'll need to do this just like you would locally with python (if you weren't using shutils). Combine os.walk() , with sftp.mkdir() and sftp.put() . You may also want to check each file and directory with os.path.islink() depending on whether you want to resolve symlinks or not.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4409502', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/170005/']}
jdg_381865
stackexchange
llm_judgeable_groundtruth_similarity
241795
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 disassembled a LED lamp and it's circuit. My intention is to rebuild that circuit within EveryCircuit app, to understand how it is working. On this circuit I found two elements that are rising questions to me. A) I couldn't find a reference for “CY40(0|D)474JE“ To me it looks like a capacitor but it have no idea about the numbers to use? B) I also found a so-called varistor. I understand that as a variable resistor? But the data sheet that I found did not specify any ohms. The lamp was driven by 230V AC. The lamp's circuit did drive 30 LEDs in series. From my measures I saw 300V DC coming out of the circuit and going to the LEDs. Thanks Now provide the response and nothing else.
471KD07 This is a variable resistor but not like potentiometer. In potentiometer , resistance variation is linear . But for varistor , it's resistivity changes is non linear, it mainly works like diode , specially zener diode and mainly use to protect the device. It has a threshold voltage below which, varistor's resistance remain so high as it is non conducting. When voltage crossed the threshold voltage, it became conducting. For your better understanding , you can go to wiki . So what you are looking here is not resistance value but voltage and you may need to replace varistor with zener diode in EveryCircuit app as it do not have varistor (as far as I know).For this varistor maximum allowable voltage is 470V CY400 474JE this is CY400 model capacitor with value 470nF. This link will teach you how to read capacitor code information .and JE most probably manufacturer's name. Some write it at the end of the code or model name.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/241795', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/108682/']}
jdg_381866
stackexchange
llm_judgeable_groundtruth_similarity
41087206
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: A feature added on Dec, 7, 2016, announced on GitHub blog, introduced the option to add reviewers to a Pull Request You can now request a review explicitly from collaborators, making it easier to specify who you'd like to review your pull request. You can also see a list of people who you are awaiting review from in the pull request page sidebar, as well as the status of reviews from those who have already left them. However, explicit setting a reviewer for a PR was already done by assigning people ( assignees option). With both options now available, what's the role of each option since they both share the same end goal? Now provide the response and nothing else.
EDIT: After discussing with several OSS maintainers, reviewers is defined as what the word supposed to be: to review (someone's code) and "assignee" has a looser definiton explained below. For "reviewer" : someone you want to review the code. Not necessarily the person responsible for that area or responsible for merging the commit. Can be someone who worked on that chunk of code before, as GitHub auto-suggests. For "assignee" : up to the project's team/maintainer what it means and there's no strict definition. It can be the PR opener, or someone responsible for that area (who is going to accept the PR after the review is done or just close it). It's not up to GitHub to define what it is leaving it open for project maintainers what fits best for their project. Previous answer: Ok I'll go ahead and answer my own question. For PR of users with write-access: the Assignee would be the same person who opened the PR, and reviewer would replace the old assignee function (reviewing code), being this one someone of assignee choice. For PR of users without write-access (outside contributors): Someone with write-access would assign herself (or other write-priviledge member), to review the PR (Reviewer). Assignee is blank. For unfinished PR from outside contributors : the write-access member would take the unfinished work and assign for her. She will be responsible for finishing the task, being the Assignee . Since the main reason of PRs is reviewing changes, she would select some other people to review the changes.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/41087206', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4902448/']}
jdg_381867
stackexchange
llm_judgeable_groundtruth_similarity
51956000
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: On occasion, circumstances require us to do the following: from keras.preprocessing.text import Tokenizertokenizer = Tokenizer(num_words=my_max) Then, invariably, we chant this mantra: tokenizer.fit_on_texts(text) sequences = tokenizer.texts_to_sequences(text) While I (more or less) understand what the total effect is, I can't figure out what each one does separately, regardless of how much research I do (including, obviously, the documentation). I don't think I've ever seen one without the other. So what does each do? Are there any circumstances where you would use either one without the other? If not, why aren't they simply combined into something like: sequences = tokenizer.fit_on_texts_to_sequences(text) Apologies if I'm missing something obvious, but I'm pretty new at this. Now provide the response and nothing else.
From the source code : fit_on_texts Updates internal vocabulary based on a list of texts. This method creates the vocabulary index based on word frequency. So if you give it something like, "The cat sat on the mat." It will create a dictionary s.t. word_index["the"] = 1; word_index["cat"] = 2 it is word -> index dictionary so every word gets a unique integer value. 0 is reserved for padding. So lower integer means more frequent word (often the first few are stop words because they appear a lot). texts_to_sequences Transforms each text in texts to a sequence of integers. So it basically takes each word in the text and replaces it with its corresponding integer value from the word_index dictionary. Nothing more, nothing less, certainly no magic involved. Why don't combine them? Because you almost always fit once and convert to sequences many times . You will fit on your training corpus once and use that exact same word_index dictionary at train / eval / testing / prediction time to convert actual text into sequences to feed them to the network. So it makes sense to keep those methods separate.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/51956000', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9448090/']}
jdg_381868
stackexchange
llm_judgeable_groundtruth_similarity
56617900
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Android Studio suddenly stops working. Studio asks me to upgrade my build . gradle version to 3.4.1. I already did it but it is still giving the issue; ERROR: Gradle DSL method not found: 'testImplementation()' ... buildscript { repositories { jcenter() google() } dependencies { classpath 'com.android.tools.build:gradle:3.4.1' }} ... ERROR: Gradle DSL method not found: 'testImplementation()'Possible causes:The project 'android' may be using a version of the Android Gradle plug-in that does not contain the method (e.g. 'testCompile' was added in 1.1.0).Upgrade plugin to version 3.4.1 and sync projectThe project 'android' may be using a version of Gradle that does not contain the method.Open Gradle wrapper fileThe build file may be missing a Gradle plugin.Apply Gradle plugin Now provide the response and nothing else.
There are good pointers in the comments, but let me dig a little deeper: Explanation of $i++ : $i++ uses ++ , the increment operator , to increment the value of variable $i by 1 , as may be familiar from languages such as C# and C/C++. As expected, a complemementary decrement operator, -- , exists too). Since the ++ is positioned after the variable ( postfix form), incrementing happens after the variable's value has been used in a statement; placing it before the variable - ++$i ( prefix form) would perform incrementing first ; if an increment / decrement operation in used in isolation, that distinction is irrelevant. $i is assumed to contain an instance of a numeric type, otherwise an error occurs; if variable $i has not been initialized, its value is effectively $null , which PowerShell coerces to an [int] -typed 0 . Thus, $i++ evaluates to 0 in the context of its statement and is incremented to 1 afterwards. An increment / decrement expression such as $i++ is treated like an assignment - you can think of it as $i = $i + 1 - and assignments in PowerShell produce no output (they do not return anything; they only update the variable's value). Explanation of (...) around $i++ : By enclosing an assignment in parentheses ( (...) ) you turn it into an expression , which means that the value of the assignment is passed through , so that it can participate in a larger expression; e.g.: $i = 0 ... no output - just assigns value 0 to variable $i . ($i = 1) ... outputs 1 : due to (...) , the assigned value is also output. (++$i) ... pre-increment: increments the value of $i to 2 and outputs that value. ($i++) ... post-decrement: outputs 2 , the current value, then increments the value to 3 . Explanation of $(...) around ($i++) : $(...) , the subexpression operator , is needed for embedding the output from one or even multiple statements in contexts where statements aren't directly supported. Notably, you can use it to embed command output in an expandable string ( "..." ), i.e., to perform string interpolation . Note that $(...) is only needed for embedding expressions (e.g., something enclosed in (...) , property access ( $foo.bar ), indexing, ( $foo[0] ) and method calls ( $foo.Baz() )) and commands (e.g., Get-Date ), not for mere variable references such as in "Honey, I'm $HOME" . See this answer for more information about expandable strings in PowerShell. While there is no strict need for an expandable string in your simple example - just ($i++) would produce output that looks the same [1] - the $(...) is useful for making the value of ($i++) part of a larger string; e.g., "Iteration #$(($i++))" to print "Iteration #0" , "Iteration #1" , ... [1] ($i++) is a number , whereas "$(($i++)" is a string , where the to-string conversion of the number happened as part of the string interpolation.While that typically results in the same console output, it can actually differ for non-integral numbers such as 1.2 , because direct output applies culture -sensitive stringification, whereas string interpolation is culture- invariant . Thus, with a culture in effect that uses , as the decimal mark -e.g, fr-FR , 1.2 prints - culture-appropriately - as 1,2 to the console, whereas "$(1.2)" always prints as 1.2
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/56617900', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11049724/']}
jdg_381869
stackexchange
llm_judgeable_groundtruth_similarity
430848
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 have a t1.micro instance with the public DNS that looks similar to the following: ec2-184-72-67-202.compute-1.amazonaws.com (some numbers have been changed) On this instance, I am running the following Django app: $ sudo python manage.py runserver --settings=vlists.settings.devValidating models...0 errors foundDjango version 1.4.1, using settings 'vlists.settings.dev'Development server is running at http://127.0.0.1:8000/ I have opened the port 8000 through the AWS console : When I navigate to the the following URL in Chrome, I get the message: Oops! Google Chrome could not connect to : http://ec2-184-72-67-202.compute-1.amazonaws.com:8000 What am I doing wrong? Netstat: netstat -lan | grep 8000tcp 0 0 127.0.0.1:8000 0.0.0.0:* LISTEN Now provide the response and nothing else.
>Development server is running at http://127.0.0.1:8000/ Sounds like the server is set to respond only on the localhost. Check your Django config, and make sure it's set to respond on all interfaces. Update: netstat -lan | grep 8000tcp 0 0 127.0.0.1:8000 0.0.0.0:* LISTEN Yep, definitely an issue with your bindings. 127.0.0.1 should instead be your Public IP or 0.0.0.0 for all interfaces.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/430848', 'https://serverfault.com', 'https://serverfault.com/users/52183/']}
jdg_381870
stackexchange
llm_judgeable_groundtruth_similarity
45736656
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 just getting started with dash. Taking the example from here . I want to convert the dash app below import dashfrom dash.dependencies import Input, Outputimport dash_core_components as dccimport dash_html_components as htmlapp = dash.Dash()app.layout = html.Div([ dcc.Input(id='my-id', value='initial value', type="text"), html.Div(id='my-div')])@app.callback( Output(component_id='my-div', component_property='children'), [Input(component_id='my-id', component_property='value')])def update_output_div(input_value): return 'You\'ve entered "{}"'.format(input_value)if __name__ == '__main__': app.run_server() To update when the user presses a button not when the value of the input field changes. How do I accomplish this? Now provide the response and nothing else.
This is a similar question to this post . There is a click event available for a button in the latest dash_html_components , but it doesn't appear to be fully documented yet. The creator, chriddyp, has stated that the Event object may not be future-proof, but that State should be. Using State like: @app.callback( Output('output', 'children'), [Input('button-2', 'n_clicks')], state=[State('input-1', 'value'), State('input-2', 'value'), State('slider-1', 'value')]) you can use values as inputs, without initiating the callback if they change. The callback only fires if the Input('button', 'n_clicks') updates. So for your example, I've added a button and fed the State object your existing html.Input's value: import dashfrom dash.dependencies import Input, Output, Stateimport dash_core_components as dccimport dash_html_components as htmlapp = dash.Dash()app.layout = html.Div([ dcc.Input(id='my-id', value='initial value', type="text"), html.Button('Click Me', id='button'), html.Div(id='my-div')])@app.callback( Output(component_id='my-div', component_property='children'), [Input('button', 'n_clicks')], state=[State(component_id='my-id', component_property='value')])def update_output_div(n_clicks, input_value): return 'You\'ve entered "{}" and clicked {} times'.format(input_value, n_clicks)if __name__ == '__main__': app.run_server()
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45736656', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2075745/']}
jdg_381871
stackexchange
llm_judgeable_groundtruth_similarity
719915
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Find the center of the symmetry group $S_n$. Attempt: By definition, the center is $Z(S_n) = \{ a \in S_n : ag = ga \forall\ g \in S_n\}$. Then we know the identity $e$ is in $S_n$ since there is always the trivial permutation. Suppose $a$ is in $S_n$, but not equal to identity. Now we can imagine the permutation as bijective function that maps from $\{1,2,\dotsc,n\}$ to $\{1,2,\dotsc,n\}$. So suppose $p$ is a permutation map. Then $p$ maps from a location $i$ to a location $j$. Take $p(i) = j$ where $i\neq j$. Let $k$ be in $\{1,2,\dotsc,n\}$, where $k$, $i$ and $j$ are all different elements. The cycle $r = (jk)$, then we will see if this commutes. $rp(i) = rj$ Can someone please help me, I am stuck? Thank you. Now provide the response and nothing else.
If $n=2$; $S_2$ is cyclic of order $2$, so it is abelian and $Z(S_2)=S_2$. Suppose $n>2$. If $\sigma \in S_n$ is not the identity, then it moves at least one letter $i$, say $\sigma(i)=k$ and since $i\neq k$, it also moves $k$, say $\sigma(k)=j$. Can you produce a permutation (a simple one, don't think too hard) that doesn't commute with $\sigma$? Spoiler For example, say $\sigma(i)=k$ and $\sigma(k)=i$; (so $i=j$), and $\sigma$ is of the form $\sigma=(ij)\tau$, with $\tau(ij)=\tau(ji)$. Note that $\tau$ fixes $i,j$, and cannot map something to $i$ or $j$. Then consider $(i\ell)$, a transposition. Then $\sigma(i\ell)$ doesn't map $i$ to $j$: if $\tau$ moves $\ell$, it moves $i$ to something different from $j$; and if $\tau$ doesn't move $\ell$, $i\to\ell$ -- but $(i\ell)\sigma$ maps $i\to j$, so $(i\ell)\sigma\neq \sigma(i\ell)$. It remains you see what happens when $i\neq j$; but it shouldn't be too hard either.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/719915', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/136811/']}
jdg_381872
stackexchange
llm_judgeable_groundtruth_similarity
94486
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: The usual Fubini's theorem(see the Wikipedia article for example) assumes completeness or $\sigma$-finiteness on measures. However, I think I came up with a proof of the Fubini's theorem without those assumptions. Am I mistaken? I restate the theorem to avoid confusion: If a function is integrable on a product measure space, its integral can be calculated by iterated integrals. The idea of my proof is to use a fact that if a function is integrable on a product measure space, the function must be zero outside a $\sigma$-finite subset of the product measure space. Now provide the response and nothing else.
You do not need $\sigma$-finiteness of the measure in Fubini theorem, although it is an hypothesis that can be assumed with no loss of generality, in that the support of an integrable function is, of course, $\sigma$-finite. On the opposite, Tonelli theorem deals with non-negative measurable functions, whose support may well be non-$\sigma$-finite (as in the quoted example) and $\sigma$-finiteness is really needed. As to the hypothesis of completeness of the factor measures spaces $(X,\mathcal A,\mu)$ and $(Y,\mathcal B, \nu)$, it is not necessary, in either theorems (but, again, it could be assumed w.l.o.g., since the two measures can be completed). Notice however that some care is needed in stating the theorem if you consider a function on the product space which is measurable with respect to the $\mu\otimes\nu$ -completion of the product $\sigma$-algebra $\mathcal {A}\otimes\mathcal B$, more generally than just "measurable wrto the product $\sigma$-algebra". This generalization occurs quite naturally dealing with a Lebesgue measurable function on ${\bf R}^n\times{\bf R}^m$ (because the completion of the product measures is the Lebesgue measure on the product space). The result of taking this more general hypothesis is that you have to stuff the statement of the theorem with a sequel of " a.e. ", which wouldn't be necessary in the case $f\in \mathcal{L}^1 (X\times Y, \mathcal {A}\otimes\mathcal B, \mu\otimes\nu)\, .$
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/94486', 'https://mathoverflow.net', 'https://mathoverflow.net/users/37646/']}
jdg_381873
stackexchange
llm_judgeable_groundtruth_similarity
33746357
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 wondering if I can add an operation to a stream, based off of some sort of condition set outside of the stream. For example, I want to add a limit operation to the stream if my limit variable is not equal to -1 . My code currently looks like this, but I have yet to see other examples of streams being used this way, where a Stream object is reassigned to the result of an intermediate operation applied on itself: // Do some stream stuffstream = stream.filter(e -> e.getTimestamp() < max);// Limit the streamif (limit != -1) { stream = stream.limit(limit);}// Collect stream to liststream.collect(Collectors.toList()); As stated in this stackoverflow post , the filter isn't actually applied until a terminal operation is called. Since I'm reassigning the value of stream before a terminal operation is called, is the above code still a proper way to use Java 8 streams? Now provide the response and nothing else.
There is no semantic difference between a chained series of invocations and a series of invocations storing the intermediate return values. Thus, the following code fragments are equivalent: a = object.foo();b = a.bar();c = b.baz(); and c = object.foo().bar().baz(); In either case, each method is invoked on the result of the previous invocation. But in the latter case, the intermediate results are not stored but lost on the next invocation. In the case of the stream API, the intermediate results must not be used after you have called the next method on it, thus chaining is the natural way of using stream as it intrinsically ensures that you don’t invoke more than one method on a returned reference. Still, it is not wrong to store the reference to a stream as long as you obey the contract of not using a returned reference more than once. By using it they way as in your question, i.e. overwriting the variable with the result of the next invocation, you also ensure that you don’t invoke more than one method on a returned reference, thus, it’s a correct usage. Of course, this only works with intermediate results of the same type, so when you are using map or flatMap , getting a stream of a different reference type, you can’t overwrite the local variable. Then you have to be careful to not use the old local variable again, but, as said, as long as you are not using it after the next invocation, there is nothing wrong with the intermediate storage. Sometimes, you have to store it, e.g. try(Stream<String> stream = Files.lines(Paths.get("myFile.txt"))) { stream.filter(s -> !s.isEmpty()).forEach(System.out::println);} Note that the code is equivalent to the following alternatives: try(Stream<String> stream = Files.lines(Paths.get("myFile.txt")).filter(s->!s.isEmpty())) { stream.forEach(System.out::println);} and try(Stream<String> srcStream = Files.lines(Paths.get("myFile.txt"))) { Stream<String> tmp = srcStream.filter(s -> !s.isEmpty()); // must not be use variable srcStream here: tmp.forEach(System.out::println);} They are equivalent because forEach is always invoked on the result of filter which is always invoked on the result of Files.lines and it doesn’t matter on which result the final close() operation is invoked as closing affects the entire stream pipeline. To put it in one sentence, the way you use it, is correct. I even prefer to do it that way, as not chaining a limit operation when you don’t want to apply a limit is the cleanest way of expression your intent. It’s also worth noting that the suggested alternatives may work in a lot of cases, but they are not semantically equivalent: .limit(condition? aLimit: Long.MAX_VALUE) assumes that the maximum number of elements, you can ever encounter, is Long.MAX_VALUE but streams can have more elements than that, they even might be infinite. .limit(condition? aLimit: list.size()) when the stream source is list , is breaking the lazy evaluation of a stream. In principle, a mutable stream source might legally get arbitrarily changed up to the point when the terminal action is commenced. The result will reflect all modifications made up to this point. When you add an intermediate operation incorporating list.size() , i.e. the actual size of the list at this point, subsequent modifications applied to the collection between this point and the terminal operation may turn this value to have a different meaning than the intended “actually no limit” semantic. Compare with “Non Interference” section of the API documentation : For well-behaved stream sources, the source can be modified before the terminal operation commences and those modifications will be reflected in the covered elements. For example, consider the following code: List<String> l = new ArrayList(Arrays.asList("one", "two"));Stream<String> sl = l.stream();l.add("three");String s = sl.collect(joining(" ")); First a list is created consisting of two strings: "one"; and "two". Then a stream is created from that list. Next the list is modified by adding a third string: "three". Finally the elements of the stream are collected and joined together. Since the list was modified before the terminal collect operation commenced the result will be a string of "one two three". Of course, this is a rare corner case as normally, a programmer will formulate an entire stream pipeline without modifying the source collection in between. Still, the different semantic remains and it might turn into a very hard to find bug when you once enter such a corner case. Further, since they are not equivalent, the stream API will never recognize these values as “actually no limit”. Even specifying Long.MAX_VALUE implies that the stream implementation has to track the number of processed elements to ensure that the limit has been obeyed. Thus, not adding a limit operation can have a significant performance advantage over adding a limit with a number that the programmer expects to never be exceeded.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33746357', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/513233/']}
jdg_381874
stackexchange
llm_judgeable_groundtruth_similarity
58861457
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I was trying to make a pipe in typescript that would split a PascalCase string, but it would be nice if this would also split on digits as well. I would also like it to split on consecutive capital letters. I have this pipe, which works great, except it only works in Chrome and not Firefox, evidently only Chrome supports look backs. How can accomplish this without look backs? transform(value: string): string { let extracted = ''; if (!value) { return extracted; } const regExSplit = value .split(new RegExp('(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|(?<=[0-9])(?=[A-Z][a-z])|(?<=[a-zA-Z])(?=[0-9])')); for (let i = 0; i < regExSplit.length; i++) { if (i !== regExSplit.length - 1) { extracted += `${regExSplit[i]} `; } else { extracted += regExSplit[i]; } } return extracted; } So for example a string ANet15Amount should be transformed into A Net 15 Amount . This regex above also would split a camelCase string, but that's not necessary to consider. Now provide the response and nothing else.
How about matching by a more basic pattern like this and joining with space. let str = `ANet15Amount`;let camel = str.match(/[A-Z]+(?![a-z])|[A-Z]?[a-z]+|\d+/g).join(' ');console.log(camel); First I thought of simply [A-Z][a-z]*|\d+ but this would break eg ABCDefg123 into A B C Defg 123 which would be different working to your current function, that transforms to ABC Defg 123 . There is still a little difference. Yours transforms A1B2 to A 1B 2 and this one to A 1 B 2 where I think this one would be more accurate, wouldn't it.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/58861457', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6471259/']}
jdg_381875
stackexchange
llm_judgeable_groundtruth_similarity
3891331
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How can rows with non-ASCII characters be returned using SQL Server? If you can show how to do it for one column would be great. I am doing something like this now, but it is not working select *from Staging.APARMRE1 as arwhere ar.Line like '%[^!-~ ]%' For extra credit, if it can span all varchar columns in a table, that would be outstanding! In this solution, it would be nice to return three columns: The identity field for that record. (This will allow the whole record to be reviewed with another query.) The column name The text with the invalid character Id | FieldName | InvalidText |----+-----------+-------------------+ 25 | LastName | Solís | 56 | FirstName | François |100 | Address1 | 123 Ümlaut street | Invalid characters would be any outside the range of SPACE (32 10 ) through ~ (127 10 ) Now provide the response and nothing else.
Here is a solution for the single column search using PATINDEX. It also displays the StartPosition, InvalidCharacter and ASCII code. select line, patindex('%[^ !-~]%' COLLATE Latin1_General_BIN,Line) as [Position], substring(line,patindex('%[^ !-~]%' COLLATE Latin1_General_BIN,Line),1) as [InvalidCharacter], ascii(substring(line,patindex('%[^ !-~]%' COLLATE Latin1_General_BIN,Line),1)) as [ASCIICode]from staging.APARMRE1where patindex('%[^ !-~]%' COLLATE Latin1_General_BIN,Line) >0
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3891331', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4964/']}
jdg_381876
stackexchange
llm_judgeable_groundtruth_similarity
1436779
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The point p = (1,1,1,1) ∈ R^4 (real numbers) to the line L(a) with a = (1,2,3,4) in particular. I tried it as follows: The distance d(p,L(a)) is the orthogonal projection of p onto L(a). So the dot product equals zero. Out of this follows L(a) = c * a , with c = (c_1, c_2, c_3, c_4) and c_1, c_2, c_3, c_4 elements in the real numbersThen dot product of c*a,p = 0, so 1c_1 + 2c_2 + 3c_3 + 4c_4 = 0 and I'm getting stuck here and to be honest I feel like I'm going about this all wrong... I hope someone can give me a hint or a push in the right direction. Thank you kindly for your time. Edit: I think I found the solution:I'm looking for a vector v_2 that is the orthogonal projection of p onto L(a)take c = dotprod(a,p)/dotprod(a,a) = 10/30 = 1/3 v_1 = c*a = 1/3 * (1,2,3,4) v_2 = v - v_1 = (1,1,1,1) - 1/3* (1,2,3,4) = (-2/3, -1/3, 0, 1/3) The displacement of v_2 = |v_2| = 1/5 sqrt((-2/3)^2 + (-1/3)^2 + (0)^2 + (1/3)^2) and v_2 = d(p,L(a)) am I close? Now provide the response and nothing else.
Yes, and more is true: given any positive rational number $n$, there exists a finite set $M\subset\Bbb N$ such that $\sum_{k\in M} \frac1k = n$. Perhaps the most straightforward proof is this: since the harmonic series diverges, there exists a unique $m\in\Bbb N$ such that$$\sum_{k=1}^m \frac1k \le n < \sum_{k=1}^{m+1} \frac1k.$$(If $n$ is small then $m$ might equal $0$.)Write $r=n-\sum_{k=1}^m \frac1k$, which is a rational number less than $\frac1{m+1}$. Then use the greedy algorithm to write $r$ as an Egyptian fraction $\sum_{k\in M_r} \frac1k$. By size considerations, every element of $M_r$ exceeds $m$, and so $M=\{1,\dots,m\} \cup M_r$ has the property that $\sum_{k\in M} \frac1k = n$. Similar constructions can yield representations of $n$ with particular constraints; for example, one can choose any $j\in\Bbb N$ and force all the elements of $M$ to exceed $j$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1436779', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/271069/']}
jdg_381877
stackexchange
llm_judgeable_groundtruth_similarity
3395236
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 Django with an sqlite backend, and write performance is a problem. I may graduate to a "proper" db at some stage, but for the moment I'm stuck with sqlite. I think that my write performance problems are probably related to the fact that I'm creating a large number of rows, and presumably each time I save() one it's locking, unlocking and syncing the DB on disk. How can I aggregate a large number of save() calls into a single database operation? Now provide the response and nothing else.
EDITED: commit_on_success is deprecated and was removed in Django 1.8. Use transaction.atomic instead. See Fraser Harris's answer . Actually this is easier to do than you think. You can use transactions in Django. These batch database operations (specifically save, insert and delete) into one operation. I've found the easiest one to use is commit_on_success . Essentially you wrap your database save operations into a function and then use the commit_on_success decorator. from django.db.transaction import commit_on_success@commit_on_successdef lot_of_saves(queryset): for item in queryset: modify_item(item) item.save() This will have a huge speed increase. You'll also get the benefit of having roll-backs if any of the items fail. If you have millions of save operations then you may have to commit them in blocks using the commit_manually and transaction.commit() but I've rarely needed that. Hope that helps, Will
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3395236', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/99876/']}
jdg_381878
stackexchange
llm_judgeable_groundtruth_similarity
16436575
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 LinearLayout that contains a lot of sub LinearLayouts which contain TextViews . I want to get a screenshot from the parent LinearLayout to get a full view of my "Receipt". So I tried to do that: View v = findViewById(R.id.llReceipt);v.setDrawingCacheEnabled(true);Bitmap b = v.getDrawingCache(); the problem is the Bitmap b get a null value. Is there any solution to solve it? Now provide the response and nothing else.
You can turn a selector and value into a predicate using Expression.Equal : static IQueryable<TSource> Search<TSource, TValue>( this IQueryable<TSource> source, Expression<Func<TSource,TValue>> selector, TValue value){ var predicate = Expression.Lambda<Func<TSource,bool>>( Expression.Equal( selector.Body, Expression.Constant(value, typeof(TValue)) ), selector.Parameters); return source.Where(predicate);} Then you just need to do something like: var result = database.SomeEntities.Search(x => x.SomeProp, "value"); If you want to do it from the database , then that depends on what the database is ; for example, with LINQ-to-SQL you could add an additional method: static IQueryable<TSource> Search<TSource, TValue>( this System.Data.Linq.DataContext database, Expression<Func<TSource, TValue>> selector, TValue value) where TSource : class{ IQueryable<TSource> source = database.GetTable<TSource>(); return Search(source, selector, value);} and use: var result = database.Search<SomeEntity, string>(x => x.SomeProp, "value"); frankly I think it is clearer to use the database.SomeEntities version, though.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16436575', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2064262/']}
jdg_381879
stackexchange
llm_judgeable_groundtruth_similarity
24016592
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 didn't explicitly add timers to a runloop and it works just fine. The other day when I read some article about NSRunLoop and it said it's better to add a NSTimer instance into a runloop instance to execute. I just wonder will it do any harm if I don't do so? Now provide the response and nothing else.
NSTimer instances always need to be scheduled on a run loop to operate properly. If you're doing it from the main thread, you can just use scheduleTimerWithTimeInterval and it will automatically added to the main run loop for you and no manual call to NSRunLoop method addTimer is needed. But you can create timer and add it yourself, if you want. The scheduleTimerWithTimeInterval is a convenience method that just does that for you. If you are creating a timer from a background thread that doesn't have its own run loop (and by default, when you use background dispatch queues or operation queues, the thread on which that is running will not have its own run loop), you then have to manually add the timer to a run loop. Typically, people will just add the timer to the main run loop. Alternatively, if you really want a timer to run on a background thread, rather than creating a run loop for that thread and adding the timer to that new run loop, you can use GCD dispatch timers, which don't require a run loop to run. See https://stackoverflow.com/a/19996367/1271826 for a Objective-C example. See https://stackoverflow.com/a/25952724/1271826 for Swift example. So, unless creating timers in background thread, just use scheduledTimerWithTimeInterval , and you don't have to worry about manually adding it to a run loop.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24016592', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2968168/']}
jdg_381880
stackexchange
llm_judgeable_groundtruth_similarity
961816
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Assuming that I want to write the following HQL query: FROM Cat c WHERE c.id IN (1,2,3) what is the proper way of writing this as a parametrized query, e.g. FROM Cat c WHERE c.id IN (?) Now provide the response and nothing else.
I am unsure how to do this with positional parameter, but if you can use named parameters instead of positional, then named parameter can be placed inside brackets and setParameterList method from Query interface can be used to bind the list of values to this parameter. ...Query query = session.createQuery("FROM Cat c WHERE c.id IN (:ids)");query.setParameterList("ids", listOfIds);...
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/961816', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/112671/']}
jdg_381881
stackexchange
llm_judgeable_groundtruth_similarity
3797991
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Recently I attended an interview where they asked me to write a C program to concatenate two strings without using strcat() , strlen() and strcmp() and that function should not exceed two (2) lines. I know how to concatenate two strings without using strcat() . But my method has nearly 15 lines. I dont know how to write it in two lines. Now provide the response and nothing else.
I expect they wanted something like this: void mystrcat(char * dest, const char * src){ //advance dest until we find the terminating null while (*dest) ++dest; //copy src to dest including terminating null, until we hit the end of src //Edit: originally this: //for (; *dest = *src, *src; ++dest, ++src); //...which is the same as this for (; *dest = *src; ++dest, ++src);} It doesn't return the end of the concatenated string like the real strcat , but that doesn't seem to be required. I don't necessarily know if this sort of thing is a good interview question - it shows that you can code tersely, and that you know what strcat does, but that's about it. Edit: as aib writes, the statement while (*dest++ = *src++); ...is perhaps a more conventional way of writing the second loop (instead of using for ).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3797991', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/273396/']}
jdg_381882
stackexchange
llm_judgeable_groundtruth_similarity
13670948
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Just starting to play with breeze.js because of the obvious gains in coding time, i.e. managing to access model data from the server direct within Javascript (I am a newbie here, so obviously bare with!). In the past I have used the stock ajax calls to get/post data to the server, and I have used a few different client tools in the past to provide some help in querying local data, such as jLinq . My question is this. Isn't it dangerous to have essentially full model query access in Javascript? I must be missing something because it looks like a really well thought through tool. In the past I have at least controlled what can be sent to the client via the backend query process, and again using something like jLinq etc I could filter the data etc. I can also understand the trade-off perhaps with gaining the direct query/none-duplicating local model problem, so just if anyone could provide some insight to this? Thanks! EDIT Obviously I am not the only one, however I am guessing there is a reasonable response - maybe limiting the data being requested using DTO methods or something? The other question posted is here Now provide the response and nothing else.
It can be dangerous to expose the full business model. It can be dangerous to allow unrestrained querying of even that part of the model that you want to expose to the client. This is true whether you offer an easy-to-query API or one that is difficult to query. That's why our teams are careful about how we construct our services. You should only expose types that your client app needs. If you want to limit access to authorized instances of a type, you can write carefully prescribed non-queryable service methods. Breeze can call them just fine. You don't have to use the Breeze query facilities for every request. You'll still benefit from the caching, related-entity-navigation, change-tracking, validation, save-bundling, cache-querying, offline support. Repeat: your service methods don't have to return IQueryable. Even when they do return IQueryable, you can easily write the service method to constrain the query results to just those entities the user is authorized to see. Fortunately, you can blend the two approaches in the same service or in collaborating services. Breeze gives you choices. It's up to you to exercise those choices wisely. Go out there and design your services to fit your requirements.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13670948', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/218297/']}
jdg_381883
stackexchange
llm_judgeable_groundtruth_similarity
14339046
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 that I have a nested one to many -type hierarchy database as follows: One Region has many Countries ; each Country has many Cities ; a City must belong to one and only one country. Abstracting this information into a RDBMS is a trivial exercise, but (to my mind) the most sensible REST endpoint to return a list of countries for a given region id would be something like the following: HTTP GET http://localhost/Region/3/Countries By default, the .NET Web API's routing would be, at best, http://localhost/Countries/Region/3 or http://localhost/Region/Countries/3 . Is there a sensible naming-convention I should follow, or is the routing customisable enough to allow URIs to take any shape I like? Now provide the response and nothing else.
The routing should be customizable enough to get the URLs you're looking for. Assuming you want URLs in the form 'http://localhost/Region/3/Countries', you could register this custom route: config.Routes.MapHttpRoute("MyRoute", "Region/{regionId}/Countries", new { controller = "Region", action = "GetCountries" }); This would dispatch requests to the 'GetCountries' action on the 'RegionController' class. You can have a regionId parameter on the action that gets model bound automatically for you from the URI. You may want to look online for the attribute routing package for WebAPI since it may be more appropriate in your case.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14339046', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1700634/']}
jdg_381884
stackexchange
llm_judgeable_groundtruth_similarity
485158
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Evaluate $\lim_{x\to 49} \frac{x-49}{\sqrt{x}-7}$ I'm guessing the answer is 7 but again that is only a guess. I don't know how to solve this type of problem. Please help. Now provide the response and nothing else.
$$\lim_{x \to 49} \frac {x - 49}{\sqrt x - 7} = \lim_{x \to 49} \frac {(\sqrt x + 7)(\sqrt x - 7)}{\sqrt x - 7} = \lim_{x \to 49} (\sqrt x + 7) = 14$$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/485158', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/92256/']}
jdg_381885
stackexchange
llm_judgeable_groundtruth_similarity
39617895
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 country dropdown <select name="country" class="form-control"/> <option>Select a Country</option> <?php foreach($country_list as $country) :?> <option value="<?php echo $account_result->Country;?>" <?php if($country->id==$account_result->Country) {echo 'selected="selected"';};?>> <?php echo $country->name; ?></option> <?php endforeach; ?></select> but while updating I am getting only selected value id it's not changing. Now provide the response and nothing else.
Yes, don't add "()" if there is no param button.addTarget(self, action:#selector(handleRegister), for: .touchUpInside). and if you want to get the sender button.addTarget(self, action:#selector(handleRegister(_:)), for: .touchUpInside). func handleRegister(sender: UIButton){ //...} Edit: button.addTarget(self, action:#selector(handleRegister(_:)), for: .touchUpInside) no longer works, you need to replace _ in the selector with a variable name you used in the function header, in this case it would be sender , so the working code becomes: button.addTarget(self, action:#selector(handleRegister(sender:)), for: .touchUpInside)
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/39617895', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6858567/']}
jdg_381886
stackexchange
llm_judgeable_groundtruth_similarity
57833208
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 updated my OS version to android 10 last night, and since then the startActivity function inside the broadcast receiver is doing nothing. This is how I try to start the activity based on the answer of CommonsWare: Intent i = new Intent(context, AlarmNotificationActivity.class);i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { // This is at least android 10... Log.d("Debug", "This is android 10"); // Start the alert via full-screen intent. PendingIntent startAlarmPendingIntent = PendingIntent.getBroadcast(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT); String CHANNEL_ID = "my_channel_02"; NotificationChannel channel = new NotificationChannel(CHANNEL_ID, context.getString(R.string.notification_channel_name_second), NotificationManager.IMPORTANCE_HIGH); NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.createNotificationChannel(channel); NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID) .setContentTitle("Um, hi!") .setAutoCancel(true) .setPriority(NotificationCompat.PRIORITY_HIGH) .setFullScreenIntent(startAlarmPendingIntent, true); Log.d("Debug", "Try to load screen"); notificationManager.notify(0, builder.build()); } The log shows that I am getting to the notify command but nothing happens. I am asking for USE_FULL_SCREEN_INTENT permission on the manifest so I should be able to use full-screen intents.My app is useless now because of that issue. Does anyone know how to solve it? Now provide the response and nothing else.
Android 10's restriction on background activity starts was announced about six months ago. You can read more about it in the documentation . Use a high-priority notification, with an associated full-screen Intent , instead. See the documentation . This sample app demonstrates this, by using WorkManager to trigger a background event needing to alert the user. There, I use a high-priority notification instead of starting the activity directly: val pi = PendingIntent.getActivity( appContext, 0, Intent(appContext, MainActivity::class.java), PendingIntent.FLAG_UPDATE_CURRENT)val builder = NotificationCompat.Builder(appContext, CHANNEL_WHATEVER) .setSmallIcon(R.drawable.ic_notification) .setContentTitle("Um, hi!") .setAutoCancel(true) .setPriority(NotificationCompat.PRIORITY_HIGH) .setFullScreenIntent(pi, true)val mgr = appContext.getSystemService(NotificationManager::class.java)if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && mgr.getNotificationChannel(CHANNEL_WHATEVER) == null) { mgr.createNotificationChannel( NotificationChannel( CHANNEL_WHATEVER, "Whatever", NotificationManager.IMPORTANCE_HIGH ) )}mgr.notify(NOTIF_ID, builder.build())
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/57833208', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9818547/']}
jdg_381887
stackexchange
llm_judgeable_groundtruth_similarity
133750
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: This question is inspired by a recent talk by Matt Kahle on random geometric complexes. Some simple notation: let $\mathcal{B} \subset \mathbb{R}^d$ be the unit ball in $d$-dimensional Euclidean space with the usual norm $\|\cdot\|$ and let $\mathcal{B}^k$ denote the $k$-fold product of this ball with itself for any positive integer $k$. For each $n \in \mathbb{N}$, define $K_n \subset \mathcal{B}^n$ as follows: $$ K_n = \lbrace(p_1,\ldots,p_n) \in \mathcal{B}^n \text{ so that } \|p_i - p_j\| < 1 \text{ for all } 1 \leq i,j \leq n\rbrace.$$ Thus, $K_n$ consists of those $n$-tuples of points in the unit ball whose diameter is bounded above by $1$. I would like to know what fraction of $\mathcal{B}^n$ lies in $K_n$ asymptotically as $n$ increases. More precisely, let $\mu$ be the usual $d$-dimensional Lebesgue measure, and define $$\chi(n) = \frac{\mu(K_n)}{\mu(\mathcal{B})^n}.$$ How does $\chi(n)$ behave for fixed dimension $d$ as $n \to \infty$? While an answer to this specific question would be great, I would be much more interested in some insight regarding how one should tackle such problems. The Calculus approach of setting up some integral fails horribly -- at least, I should confess that I tried $n = 2 = d$ and got hopelessly stuck with what appears to be an elliptic integral of the murderous kind -- so I expect that there is no closed formula for $\chi(n)$. But surely someone has worked out asymptotic envelopes for such a basic quantity! Now provide the response and nothing else.
I am certainly not the best person to answer this question, as I do not have much insight to share regarding how to approach this kind of problems. My only (fairly obvious) suggestion is to estimate the relevant quantities in any way possible. In this process, it can be very helpful to reduce the calculations to lower dimensions, and the Fubini theorem will be our friend here.$\newcommand{\norm}[1]{\lVert #1 \rVert}$$\newcommand{\abs}[1]{\lvert #1 \rvert}$$\newcommand{\suchthat}{\ : \ }$$\newcommand{\set}[1]{\left\lbrace #1 \right\rbrace}$$\newcommand{\NN}{\mathbb{N}}$$\newcommand{\RR}{\mathbb{R}}$$\newcommand{\ball}[2][0]{{B_{#2}(#1)}}$$\newcommand{\unitball}{\ball{1}}$$\newcommand{\dd}{\:\mathrm{d}}$$\newcommand{\label}[1]{\rlap{\qquad\qquad \text{#1}}}$ For this problem, my single intuition is that when one of the points $p_i$ drifts away from the centre of the unit ball, then every other point $p_j$ for $j\neq i$ cannot access a certain portion of the unit ball which sits close to $-p_i \: /\norm{p_i}$. By adding sufficiently many points, this should make the ratio $\chi(n)$ go to zero as $n$ goes to infinity. I will try to make this intuition precise in the remainder of this answer. Notation and preliminaries Fix the dimension $d$ of the ambient Euclidean space. Let $\norm{\cdot}$ denote the Euclidean norm on $\RR^d$, and $\ball[x]{r} = \set{ p\in\RR^d \suchthat \norm{p - x} \lt r }$ the open ball in $\RR^d$ with radius $r$ and centre $x$. Further, let $\mu$ be the Lebesgue measure on $\RR^d$, and $\mu_n = \mu^{\times n}$ the product measure on $\bigl(\RR^d \bigr)^{\times n}$ (i.e. Lebesgue measure on $\RR^{d n}$). As in the statement of the question, $K_n$ will denote the following subset of $\unitball^{\times n}$:$$ K_n = \set{ (p_1, \ldots, p_n) \in \unitball^{\times n} \suchthat \forall_{i,j} \ \norm{p_i - p_j} \lt 1 } $$We shall prove that$$ \chi(n) = \frac{\mu_n(K_n)}{\mu_n \bigl( \unitball^{\times n} \bigr)} = \frac{\mu_n(K_n)}{\mu\bigl(\unitball\bigr)^n} $$converges to $0$ as $n\to\infty$. In fact, I will give (fairly coarse) upper and lower bounds for $\chi(n)$. Nevertheless, I am sure one can give much stricter bounds for $\chi(n)$ and perhaps even describe its asymptotic behaviour. Upper bound for $\chi(n)$ Fix a positive integer $n$. Define$$ X_n = \set{ (p_1, \ldots, p_n)\in K_n \suchthat \forall_i \ \norm{p_i} \lt 1/2 } $$(the choice of the number $1/2$ here is mostly arbitrary) and $Y_n = K_n\setminus X_n$ to be the complement of $X_n$ in $K_n$. The set $X_n$ is contained in $\ball{1/2}^{\times n}$ and thus$$ \mu_n(X_n) \leq \mu_n\bigl(\ball{1/2}^{\times n}\bigr) = \mu\bigl(\ball{1/2}\bigr)^n $$Now define for each $i\in\set{1, \ldots, n}$ the set$$ Z_{n,i} = \set{ (p_1, \ldots, p_n)\in K_n \suchthat \norm{p_i} \geq 1/2 } $$It is easy to check that$$ Y_n = \bigcup_{i=1}^n Z_{n,i} $$Moreover, by permuting the first and $i$-th points (which gives a measure preserving self-bijection of $K_n$), we see that $\mu_n(Z_{n,i}) = \mu_n(Z_{n,1})$ for all $i\in\set{1, \ldots, n}$. It follows that$$ \mu_n(Y_n) \leq n \cdot \mu_n(Z_{n,1}) $$and therefore$$ \mu_n(K_n) = \mu_n(X_n) + \mu_n(Y_n) \leq \mu\bigl(\ball{1/2}\bigr)^n + n\cdot \mu_n(Z_{n,1}) \label{(A)} $$ Now we perform a crude estimation of the volume of $Z_{n,1}$. The Fubini theorem entails$$ \mu_n(Z_{n,1}) = \int_{\unitball\setminus\ball{1/2}} \mu_{n-1}(P_x) \dd \mu(x) $$where $P_x \subset K_{n-1}$ is the following cross-section of $Z_{n,1}$, for each $x\in\unitball\setminus\ball{1/2}$:$$ P_x = \set{ (p_1, \ldots, p_{n-1}) \in \bigl(\RR^d \bigr)^{\times (n-1)} \suchthat (x, p_1, \ldots, p_{n-1}) \in K_n } $$ Lemma: For each $x\in\unitball\setminus\ball{1/2}$, the inequality $\mu_{n-1}(P_x) \leq \mu\bigl(\unitball\cap\ball[1/2,0,\ldots,0]{1}\bigr)^{n-1}$ holds. I will present a proof of the lemma at the end of this answer. We now apply the estimate in the lemma to the preceding integral expression for $\mu_n(Z_{n,1})$ to obtain:$$ \mu(Z_{n,1}) \leq \mu\bigl( \unitball \bigr) \cdot \mu\bigl( \unitball\cap\ball[1/2,0,\ldots,0]{1} \bigr)^{n-1} $$Putting this together with estimate (A):$$ \mu_n(K_n) \leq \mu\bigl(\ball{1/2}\bigr)^n + n\cdot \mu\bigl( \unitball \bigr) \cdot \mu\bigl(\unitball\cap\ball[1/2,0,\ldots,0]{1}\bigr)^{n-1} $$and further using the fact that $\ball{1/2} \subset \unitball\cap\ball[1/2,0,\ldots,0]{1}$, we simplify$$ \mu_n(K_n) \leq (n+1) \cdot \mu\bigl( \unitball \bigr) \cdot \mu\bigl(\unitball\cap\ball[1/2,0,\ldots,0]{1}\bigr)^{n-1} $$Consequently, we obtain an upper bound for $\chi(n)$: $$ \chi(n) \leq (n+1) \left( \frac{\mu\bigl(\unitball\cap\ball[1/2,0,\ldots,0]{1}\bigr)}{\mu\bigl(\unitball\bigr)} \right)^{n-1} = (n+1) \rho^{n-1} $$ where $0 \lt \rho \lt 1$. Note that $\rho$ depends only on $d$. In particular, $\chi(n)$ converges to zero as $n\to\infty$. Lower bound for $\chi(n)$ It is very easy to give a crude lower bound for $\chi(n)$. Simply observe that $X_n \subset K_n$, and that $X_n = \ball{1/2}^{\times n}$ (here we do require the choice of $1/2$ in the definition of $X_n$). Therefore,$$ \mu_n(K_n) \geq \mu_n(X_n) = \mu\bigl(\ball{1/2}\bigr)^n $$and so $$ \chi(n) \geq \left( \frac{\mu\bigl(\ball{1/2}\bigr)}{\mu\bigl(\ball{1}\bigr)} \right)^n = 2^{-dn} $$ Proof of the lemma We make use of the rotational symmetry of $Z_{n,1}$. Choose a rotation on $\RR^d$ which takes the point $x$ to the point $(\norm{x},0,\ldots,0)$ on the first axis. Applying that rotation componentwise gives a measure preserving bijection between $P_x$ and $P_{(\norm{x},0,\ldots,0)}$, and we see that$$ \mu_{n-1}(P_x) = \mu_{n-1}\bigl( P_{(\norm{x},0,\ldots,0)} \bigr) \label{(1)} $$ On the other hand, it is straightforward to check that$$ P_x = \set{ (p_1, \ldots, p_{n-1}) \in K_{n-1} \suchthat \forall_i \ \norm{p_i - x} \lt 1 } $$and it follows that$$ P_x \subset \bigl(\unitball\cap\ball[x]{1}\bigr)^{\times (n-1)} \label{(2)} $$ Claim : For $0\leq s\leq t$, the following inclusion holds:$$ \unitball\cap\ball[t,0,\ldots,0]{1} \subset \unitball\cap\ball[s,0,\ldots,0]{1} \label{(3)} $$ Proof of claim: For $a\in\RR$, we have $\abs{a-s} \leq \max\set{ \abs{a-t}, \abs{a} }$: either $a \lt s$ which implies $\abs{a-s} \leq \abs{a-t}$, or $a\geq s$ which implies $\abs{a-s}\leq \abs{a}$. Thus, for any $y\in\RR^d$ we have $\abs{y_1-s} \leq \max\set{ \abs{y_1-t}, \abs{y_1} }$ which by a simple calculation implies $\norm{y-(s,0,\ldots,0)} \leq \max\set{ \norm{y-(t,0,\ldots,0)}, \norm{y} }$. End of proof. The inclusions (2) and (3) prove$$ P_{(t,0,\ldots,0)} \subset \bigl(\unitball\cap\ball[t,0,\ldots,0]{1}\bigr)^{\times (n-1)} \subset \bigl(\unitball\cap\ball[1/2,0,\ldots,0]{1}\bigr)^{\times (n-1)} $$for $1/2 \leq t \lt 1$. Using (1), we conclude that for each $x\in\unitball\setminus\ball{1/2}$$$ \mu_{n-1}(P_x) = \mu_{n-1}\bigl( P_{(\norm{x},0,\ldots,0)} \bigr) \leq \mu_{n-1}\Bigl(\bigl(\unitball\cap\ball[1/2,0,\ldots,0]{1}\bigr)^{\times (n-1)}\Bigr) $$and so $\mu_{n-1}(P_x) \leq \mu\bigl(\unitball\cap\ball[1/2,0,\ldots,0]{1}\bigr)^{n-1}$ as desired.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/133750', 'https://mathoverflow.net', 'https://mathoverflow.net/users/18263/']}
jdg_381888
stackexchange
llm_judgeable_groundtruth_similarity
12347412
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 very new to xslt, and found it can be easy or complex.I want to make clear some concepts. What is preceding-sibling and what is ancestor, after searching from google, I found ancestor explanation. and the chart from their website makes easier to understand. But I still don't understand preceding-sibling <product> <inventory> <drink> <lemonade> <price>$2.50</price> <amount>20</amount> </lemonade> <pop> <price>$1.50</price> <amount>10</amount> </pop> </drink> <service> <address /> <phone /> <delivery> City </delivery> </service> <snack> <chips> <price>$4.50</price> <amount>60</amount> </chips> </snack> <hotfood></hotfood> <totalprice> $15</totleprice> </inventory></product> so how do I read this preceding-sibling::pop/ancestor::inventory/totalprice ancestor::inventory/totalprice = product\inventory\totalpricepreceding-sibling::pop - I dont understand this onethen how to read all together? Many thanks Now provide the response and nothing else.
The preceding-sibling:: axis The preceding-sibling:: axis is an axis of navigation that includes all the preceding sibling elements to the focus element. By "sibling" we mean a different element which has the same parent to the reference item. By "preceding" we mean a node that occurs before the reference one. The order of the preceding-sibling axis is the reverse document order. Take a look at this document: <fruit> <banana> <lady-finger-banana/> </banana> <apple/> <pear/> <kiwi/></fruit> If the focus node is pear, then the sequence preceding-sibling::* is ... apple banana Note: fruit, pear, lady-finger-banana and kiwi are not in the sequence. So the following is true: preceding-sibling::*[ 1] is the apple preceding-sibling::*[ 2] is the banana count( preceding-sibling::*) is 2 preceding-sibling::apple[ 1] is also the apple preceding-sibling::banana[ 1] is the banana preceding-sibling::*[ 3] is absent or the empty sequence preceding-sibling::pop/ancestor::inventory/totalprice Example We have to alter your sample document a little bit to usefully study this example <product> <inventory> <drink> <lemonade> <price>$2.50</price> <amount>20</amount> </lemonade> <pop> <price>$1.50</price> <amount>10</amount> </pop> <focus-item /> </drink> <totalprice>$15</totalprice> </inventory></product> Let us say the focus is on the element focus-item.To evaluate the expression preceding-sibling::pop/ancestor::inventory/totalprice follow these steps: preceding-sibling::pop selects all the preceding pop elements to focus-item. This evaluates to a sequence of one node. For each item in the left hand sequence (just one pop element it so happens), set this item as a temporary focus item, and evaluate the expression of the right of the / operator which is ... ancestor::inventory There is only one such node, which is the ancestral inventory node. Thus the first / operator evaluates to a sequence of one inventory node. Now we evaluate the effect of the second / and its right-hand operand expression total price. For each item in the left hand sequence (just one inventory node so it happens), set this as a temporary focus item and evaluate totalprice . totalprice is short for child::totalprice . There is only one total price element on the child axis of the temporary focus node, so the final result is a sequence of one node, which is the total price node. Understanding by Diagrams Here is a diagram for preceding-sibling:: . In it the reference node is Charlie and the node on the preceding-sibling:: axis is in green. It is the only such node.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/12347412', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1166137/']}
jdg_381889
stackexchange
llm_judgeable_groundtruth_similarity
825034
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: Aside from one type of disk bottlenecking the other, are there any other problems with mixing SSD models in RAID? My problem is, I need to upgrade the storage in a server with 4x Samsung 845DC EVO 960GB in RAID10. These drives are not available anymore, so my options are to either use some newer comparable SSD's or to replace the array altogether. Now provide the response and nothing else.
The single biggest thing that crosses my mind isn't SSD-specific: that the biggest danger with RAID is that all the devices in any given RAID are often purchased from the same manufacturer, at the same time, and therefore tend to get to the far end of the bathtub curve and start dying at about the same time. In that sense, buying from different vendors is not only not a bad idea, but best practice. You don't say whether you're doing hardware or software RAID. If it's hardware, you have the issue of whether the new models are supported by the controller, both from a hardware support contract standpoint and an " it's too new for me to talk to / my programmer told me not to talk to you " standpoint. Either of those would be a reason not to do it. There is also the issue of capacity: if you're adding devices that are smaller than your existing ones, even if by only a few sectors, this will not go well. Check the absolute raw capacity to ensure it's greater than or equal to the devices you're already using. But assuming you can get past those issues, I think it's generally a good idea to do what you're planning.
{}
{'log_upvote_score': 7, 'links': ['https://serverfault.com/questions/825034', 'https://serverfault.com', 'https://serverfault.com/users/257295/']}
jdg_381890
stackexchange
llm_judgeable_groundtruth_similarity
43256459
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I found a number of similar questions (e.g. this , that or this ), but none of them helped me solve my problem. I have a *.so file (from the core of gnss-sdr ) that, as indicated by: $nm libgnss_system_parameters_dyn.so | c++filt |grep Gps_Eph contains the symbol Gps_Ephemeris::Gps_Ephemeris() , which is supposed to be a constructor. I've written some minimal code: #include <iostream>#include <core/system_parameters/gps_ephemeris.h>int main(int argc,const char* argv[]){ Gps_Ephemeris ge; return 0; } which I compile with: g++ main.cpp -std=c++0x -I some_include_path -L some_lib_path -l gnss_system_parameters_dyn` The linker then complains: /tmp/ccHCvldG.o: In function `main':main.cpp:(.text+0x33): undefined reference to `Gps_Ephemeris::Gps_Ephemeris()'collect2: error: ld returned 1 exit status I also tried cmake , but the line it generated was similar to that (it just added -rdynamic before linking), and it still generated the exact same linker error. Note that both the library and my minimal code are being compiled with the same compiler (g++-5), with the exact same flags and the same c++0x standard. Addressing the answer by Maxim Egorushkin, the line: nm --demangle --defined-only --extern-only libgnss_system_parameters.so |grep Gps_Eph doesn't output anything. However, the symbol is defined in the static library ( i.e. the *.a library): 00000000000006b0 T Gps_Ephemeris::Gps_Ephemeris()00000000000006b0 T Gps_Ephemeris::Gps_Ephemeris() Knowing that both are generated by cmake , in the following way: add_library(lib_name SHARED ${sources_etc}) #for the *.soadd_library(lib_name_2 ${sources_etc}) #for the *.a there should be no difference in symbols contained/defined in those libraries, right? I didn't notice anything in cmake 's documentation on add_library . Am I missing something obvious? Now provide the response and nothing else.
The pedantically correct way to check that a .so exports a symbol is nm --demangle --dynamic --defined-only --extern-only <lib.so> | grep <symbol> . Without --defined-only your command also shows undefined symbols. Without --extern-only it also shows symbols with internal linkage which are unavailable for linking. It looks like you need to link another library because Gps_Ephemeris::Gps_Ephermeris() is not resolved by linking libgnss_system_parameters_dyn.so . A good way to start is that library's documentation and examples.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/43256459', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1866656/']}
jdg_381891
stackexchange
llm_judgeable_groundtruth_similarity
4605132
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm confused about a use of Zorn's lemma that seems to give a contradiction. Suppose $m$ is the Lebesgue measure on $[0,1]$ . Let $\mathcal{A}$ be the set of measurable subsets of $[0,1]$ with measure $1$ partially ordered by inclusion. If $A_0 \supset A_1 \supset \cdots $ is a decreasing sequence in $\mathcal{A}$ then $A:=\cap_k A_k\in \mathcal{A}$ since $m(A) = \lim_{k\rightarrow \infty} m(A_k) = 1$ . So $A$ bounds the sequence below and by Zorn's lemma $\mathcal{A}$ has a minimal element $A'$ . But since points have measure $0$ , $A'$ cannot be minimal since any point can be removed from $A'$ while maintaining a measure of $1$ . Now provide the response and nothing else.
In order to apply Zorn's Lemma, you would have to consider any ordered set $I$ and an indexed collection of sets $\{A_i \mid i \in I\}$ such that $A_i \supset A_j$ whenever $i<j$ , and each $A_i$ has measure $1$ . You would then have have to prove that this collection of sets has a lower bound of measure $1$ . By restricting your attention only to the ordered set of natural numbers $I = \mathbb N$ , you have not yet verified the hypotheses of Zorn's Lemma.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4605132', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/477553/']}
jdg_381892
stackexchange
llm_judgeable_groundtruth_similarity
251800
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: It is known that if a Banach space is reflexive and separable, its unit ball is weakly metrizable. My question is about the generalization of this property : 1) Is it true that for all reflexive separable locally convex space, bounded sets are weakly metrizable? 2) If that's true, is there a way to explicitly construct a distance for the weak-topology on any bounded set? Now provide the response and nothing else.
No. Let $I$ be an index set with the cardinality of the continuum. Endow $X=\mathbb R^I$ with the product topology. According to (a particular case of) the Hewitt-Marczewski-Pondiczery theorem (which is 2.3.15 in Engelking's General Topology ) $X$ is separable. Moreover, it is semi-reflexive (by Tychonov) and barrelled (because barrelledness is stable w.r.t. products, proposition 4.2.5 in Barrelled Locally Convex Spaces of Bonet and Perez Carreras). Therefore, $X$ is reflexive. The set $B=[-1,1]^I$ is bounded. Assume that it is weakly metrizable (by the way, $X$ carries its weak topology). Then it has a countable basis of $0$-neighbourhoods and since every $0$-neighbourhood in $X$ contains one of the form $\lbrace x\in X: |\varphi_i(x)|<\varepsilon, i=1,\ldots,n \rbrace$ for some $n\in \mathbb N$, $\varphi_1,\ldots,\varphi_n \in X'$, and $\varepsilon>0$, we find a sequence of $\phi_n\in X'$ such that$$B\cap \bigcap_{n\in\mathbb N} \text{kern}(\phi_n) = \lbrace 0 \rbrace.$$But each $\phi_n$ only depends on finitely many coordinates, i.e., it is of the form $\phi_n((x_i)_{i\in I})= \sum_{i\in E_n} a_{n,i} x_i$ for some finite $E_n \subseteq I$, and it is enough to consider $j\in I\setminus \bigcup_{n\in\mathbb N} E_n$ and $b=(\delta_{i,j})_{i\in I} \in B$ to get a contradiction.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/251800', 'https://mathoverflow.net', 'https://mathoverflow.net/users/99246/']}
jdg_381893
stackexchange
llm_judgeable_groundtruth_similarity
5669454
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is it possible to iterate over a list of functions in MATLAB? I'm trying to test different radial basis functions and this seems like the best way to do it. Now provide the response and nothing else.
You can make a cell array of function handles and iterate over that. For example: vec = 1:5; % A sample vector of valuesfcnList = {@max, @min, @mean}; % Functions to apply to the vectornFcns = numel(fcnList); % Number of functions to evaluateresult = zeros(1, nFcns); % Variable to store the resultsfor iFcn = 1:nFcns result(iFcn) = fcnList{iFcn}(vec); % Get the handle and evaluate itend
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5669454', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/619962/']}
jdg_381894
stackexchange
llm_judgeable_groundtruth_similarity
1479222
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 compact group. I learned the version of the Peter-Weyl theorem which says: the matrix coefficients of $G$ are dense in $L^2(G)$ . Call this Peter-Weyl I. Apparently there is another version which states: For any $g \in G$ there exists a finite dimensional unitary representation $(\pi,V)$ such that $\pi(g) \neq I$ (identity) . Call this Peter-Weyl II. Can one prove Peter-Weyl II using Peter-Weyl I? A short slick proof is what I'm looking for, of course. Now provide the response and nothing else.
Let $H\subseteq G$ be the intersection of the kernels of all the finite-dimensional unitary representations of $G$; we wish to show $H=\{1\}$. Let $q:G\to G/H$ be the quotient map. For any integrable function $f:G/H\to\mathbb{C}$, $f\circ q$ is integrable and we have $\int_G f\circ q=\int_{G/H} f$, where both integrals are with respect to the Haar measures (this can be proven for $f$ continuous by uniqueness of the Haar measure on $G/H$, and then extends to all of $L^1(G/H)$ since continuous functions are dense). In particular, composition with $q$ defines an isometry $q^*:L^2(G/H)\to L^2(G)$. Furthermore, every matrix coefficient of $G$ is in the image of $q^*$, because if $f$ is a matrix coefficient, then $f(g)=f(hg)$ for all $h\in H$, $g\in G$ by definition of $H$. Let us now assume Peter-Weyl I. The image of $q^*$ is a closed subspace containing every matrix coefficient, so it must be all of $L^2(G)$. But if $H$ is nontrivial, there is a continuous function $f$ on $G$ which is not constant on $H$, and it is easy to see that such a function cannot be in the image of $q^*$. Thus $H$ must be trivial, proving Peter-Weyl II.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1479222', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/49330/']}
jdg_381895
stackexchange
llm_judgeable_groundtruth_similarity
18387490
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have the max-height of an element as 65vh. I need to convert it to pixels in my JavaScript to see whether an image can fit there or if I need to shrink/crop it. (am doing win8 App development). Will this work? 100 vh = screen.height therefore 65vh in pixels is screen.height *0.65 Now provide the response and nothing else.
Not necessarily screen.height * 0.65 , but viewport.height * 0.65 . Even though a Windows 8 app will always have the same height, regardless of the snapped state, this is an important difference in browser-based applications. In JavaScript: document.documentElement.clientHeight * 0.65; If you're using jQuery, you can do: $(window).height() * 0.65;
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18387490', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/298798/']}
jdg_381896
stackexchange
llm_judgeable_groundtruth_similarity
69991
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: Hi I have an issue with bounced mail it does not happen all the time but at the same time is very frequent. Most of the time if I send an email to an address that does not exist then i get a bounce back into failues@domain however there seem to be instances when I get this error below Sep 30 13:38:53 postfix/smtp[62566]: DB8E6D6F9EA: to=, relay=none, delay=0, delays=0/0/0/0, dsn=5.4.6, status=bounced (mail for domain loops back to myself) I seem to get this when I get an immediate bounce i.e the server im trying to connect to immediately blocks the email because it nows that the address does not exist. If the email goes out and is returned later this seems to work fine. Does anyone have any ideas why I would get this "mail for domain loops back to myself" error message. Obviously it is me trying to send the email back to myself as my server received a block when trying to send a mail then it tries to send the mail back to the ReplyTo header which in this case is itself but shouldn't it be able to handle this? ........ NOTE: ive had to remove any '.com' from this post as I can only post 1 url Thanks for the 2 answers already however we are still having the same issue.so below I'm trying to provide some more detailed information. Both the examples below try to send to a non-existent address. RealTSP bounce from another postfix instance works. Yahoo's bounce doesn't work.We are expecting a "non-delivery notification" to be delivered to , because the Return-Path in both cases isan equivalent VERP address. Note if we don't use VERP, ie "Return-Path: " then yahoo works also. Log entries realtsp.....working!====================Oct 6 16:46:08 milford postfix/smtpd[58480]: 5027DD6E971: client=takapuna.realtsp[89.187.108.20], sasl_method=LOGIN, sasl_username=*****Oct 6 16:46:08 milford postfix/cleanup[58482]: 5027DD6E971: message-id=Oct 6 16:46:08 milford postfix/qmgr[57929]: 5027DD6E971: from=, size=9468, nrcpt=1 (queue active)Oct 6 16:46:08 milford postfix/smtp[57936]: 5027DD6E971: to=, relay=milford.realtsp[89.187.108.21]:25, delay=0.64, delays=0.63/0/0/0.01, dsn=5.1.1, status\=bounced (host milford.realtsp[89.187.108.21] said: 550 5.1.1 : Recipient address rejected: User unknown in virtual mailbox table (in reply to RCPT TO comm\and))Oct 6 16:46:08 milford postfix/bounce[58483]: 5027DD6E971: sender non-delivery notification: EA68FD6EAB7Oct 6 16:46:08 milford postfix/qmgr[57929]: 5027DD6E971: removedOct 6 16:46:08 milford postfix/cleanup[58482]: EA68FD6EAB7: message-id=Oct 6 16:46:08 milford postfix/qmgr[57929]: EA68FD6EAB7: from=, size=11600, nrcpt=1 (queue active)Oct 6 16:46:09 milford postfix/lmtp[58484]: EA68FD6EAB7: to=, relay=smtp.news.t1ps[/var/imap/socket/lmtp], delay=0.76, delays=0/0.0\1/0/0.75, dsn=2.1.5, status=sent (250 2.1.5 Ok)Oct 6 16:46:09 milford postfix/qmgr[57929]: EA68FD6EAB7: removedyahoo...not working!========================Oct 6 16:42:01 milford postfix/smtpd[57732]: 33EBBD6EE87: client=takapuna.realtsp[89.187.108.20], sasl_method=LOGIN, sasl_username=****Oct 6 16:42:01 milford postfix/cleanup[57735]: 33EBBD6EE87: message-id=Oct 6 16:42:01 milford postfix/qmgr[57598]: 33EBBD6EE87: from=, size=9480, nrcpt=1 (queue active)Oct 6 16:42:10 milford postfix/smtp[57636]: 33EBBD6EE87: to=, relay=e.mx.mail.yahoo[206.190.53.191]:25, delay=9.4, delays=0.02/0/6.5/2.9, dsn=5.0.0, s\tatus=bounced (host e.mx.mail.yahoo[206.190.53.191] said: 554 delivery error: dd This user doesn't have a yahoo account (nkaderibigbe@yahoo) [0] - mta164.mail.re2.yaho\o (in reply to end of DATA command))Oct 6 16:42:10 milford postfix/bounce[57756]: 33EBBD6EE87: sender non-delivery notification: A083ED6EA01Oct 6 16:42:10 milford postfix/qmgr[57598]: 33EBBD6EE87: removedOct 6 16:42:10 milford postfix/cleanup[57735]: A083ED6EA01: message-id=Oct 6 16:42:10 milford postfix/qmgr[57598]: A083ED6EA01: from=, size=11696, nrcpt=1 (queue active)Oct 6 16:42:10 milford postfix/smtp[57631]: A083ED6EA01: to=, relay=none, delay=0.01, delays=0.01/0/0/0, dsn=5.4.6, status=bounced \(mail for news.t1ps loops back to myself)Oct 6 16:42:10 milford postfix/qmgr[57598]: A083ED6EA01: removed main.cf soft_bounce = noqueue_directory = /var/spool/postfix_rshcommand_directory = /usr/local/sbindaemon_directory = /usr/local/libexec/postfixdata_directory = /var/db/postfix_rshmail_owner = postfixmyhostname = smtp.news.t1psinet_interfaces = 89.187.108.81local_recipient_maps = $virtual_mailbox_mapsunknown_local_recipient_reject_code = 550mynetworks_style = hostrelay_domains = $mydestinationrecipient_delimiter = +mailbox_transport = lmtp:unix:/var/imap/socket/lmtpheader_checks = regexp:/usr/local/etc/postfix_rsh/header_checksdebug_peer_level = 10debug_peer_list = yahoodebugger_command = PATH=/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin ddd $daemon_directory/$process_name $process_id & sleep 5sendmail_path = /usr/local/sbin/sendmailnewaliases_path = /usr/local/bin/newaliasesmailq_path = /usr/local/bin/mailqsetgid_group = maildrophtml_directory = nomanpage_directory = /usr/local/mansample_directory = /usr/local/etc/postfix_rshreadme_directory = nomasquerade_domains = $mydomainmessage_size_limit = 51200000virtual_transport = lmtp:unix:/var/imap/socket/lmtpvirtual_mailbox_domains = news.t1ps, domain2, domain3.co.uk, domain4virtual_alias_maps = hash:/usr/local/etc/postfix_rsh/virtualvirtual_mailbox_maps = hash:/usr/local/etc/postfix_rsh/virtual_mailbox_mapstransport_maps = regexp:/usr/local/etc/postfix_rsh/transportbroken_sasl_auth_clients = nosmtp_bind_address = 89.187.108.81smtpd_sasl_auth_enable = yessmtpd_sender_restrictions = permit_sasl_authenticated, permit_mynetworks, reject_unauth_destinationsmtpd_recipient_restrictions = permit_sasl_authenticated, permit_mynetworks, reject_unauth_destinationsmtpd_helo_restrictions = reject_invalid_hostnamesmtpd_require_helo = yesslow_destination_concurrency_limit = 15slow_destination_recipient_limit = 5syslog_facility = local1 /usr/local/etc/postfix_rsh/virtual_mailbox_maps [email protected] dummy master.cf pickup fifo n - n 60 1 pickupcleanup unix n - n - 0 cleanupqmgr fifo n - n 300 1 qmgrtlsmgr unix - - n 1000? 1 tlsmgrrewrite unix - - n - - trivial-rewritebounce unix - - n - 0 bouncedefer unix - - n - 0 bouncetrace unix - - n - 0 bounceverify unix - - n - 1 verifyflush unix n - n 1000? 0 flushproxymap unix - - n - - proxymapsmtp unix - - n - 500 smtpslow unix - - n - 100 smtp -o smtp_connect_timeout=5relay unix - - n - 100 smtp -o fallback_relay=showq unix n - n - - showqerror unix - - n - - errorretry unix - - n - - errordiscard unix - - n - - discardlocal unix - n n - - localvirtual unix - n n - - virtuallmtp unix - - n - - lmtpanvil unix - - n - 1 anvilscache unix - - n - 1 scache26 inet n - n - - smtpd -o content_filter=smtp inet n - n - - smtpd -o content_filter=spamchk:dummyspamchk unix - n n - 10 pipe flags=Rq user=spamd argv=/usr/local/bin/spamchk_rsh -f ${sender} -- ${recipient}proxywrite unix - - n - 1 proxymap Now provide the response and nothing else.
This happens when domain.com has an MX record (or, in the absence of an MX, an A record) that points to your Postfix server, but your Postfix server is not configured to accept mail for that domain. It's commonly seen in two situations: You've acquired a new domain that you want to use for email, but you just forgot to add it to Postfix. There are a couple ways to do it. In my case, I'm using the virtual table to map addresses to real local users, so I list my domains in the virtual_alias_domains directive in main.cf. The domain has its MX record set to a host that resolves to 127.0.0.1. Some malware will use this trick so they can set their return address to a valid domain, which most anti-spam measures will check for. However, the MX effectively prevents any delivery to that address, so the sender doesn't have to deal with replies or bounces.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/69991', 'https://serverfault.com', 'https://serverfault.com/users/13492/']}
jdg_381897
stackexchange
llm_judgeable_groundtruth_similarity
17684201
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am a beginner of JavaScript and want to display an array of objects in HTML. The format of the data is like this: [ {"key":"apple","value":1.90}, {"key":"berry","value":1.7}, {"key":"banana","value":1.5}, {"key":"cherry","value":1.2}] I want to use a list with three columns (id, name, relevance) to display them. And the id can increase from 1 automatically. Could anyone tell me how to write a javascript code to display it? Please give me some materials or examples to learn. Now provide the response and nothing else.
Explanation What you want is to fill a table (or another DOMElement) in HTML, with your JavaScript, which is executed dynamically once the page is loaded and your JSON object is received. You want to loop through the object. The best way to do so would be with a for loop, and making sure our looping variable remains valid for the length of our object (all its attributes). The best way to get the length of a JSON object is through myJSONObject.length : You select the keys of myJSONObject and return their count. You can access the values stored in your JSON Object the following way, in your for loop (assuming the looping variable defined is named i ): myJSONObject[i].theAttributeIWantToGet Price formatting breakdown Now, those prices need to have a proper format, don't they? So we'll check if any of the value attribute has less than 2 characters after the . within them. If they do, we add another decimal 0 . We also add a $ before writing the formatted value. Here is a breakdown of how it works: obj[i].value.toString().substring(startIndex, length) We want to check the length after the . sign, so our startIndex will be the position of this dot within our string. obj[i].value.toString().substring(obj[i].value.toString().indexOf('.'),length) We now need to set the length. We want to find the length of all what's after the dot, so we'll take the length of the whole string just to be safe. Final result: obj[i].value.toString().substring(obj[i].value.toString().indexOf('.'), obj[i].value.toString().length) < 2 This will return true or false. If it's true: There's less than 2 digits after the dot ! We add the if statement and the last zero: if (obj[i].value.toString().substring(obj[i].value.toString().indexOf('.'), obj[i].value.toString().length) < 2) obj[i].value += "0"; Also: Why I use innerHTML instead of appendChild() . Solution JSFiddle HTML <table> <tbody id="tbody"></tbody></table> JSON [{ "key": "apple", "value": 1.90}, { "key": "berry", "value": 1.7}, { "key": "banana", "value": 1.5}, { "key": "cherry", "value": 1.2}] JavaScript Note: The JSON object will be named obj in this instance. var tbody = document.getElementById('tbody');for (var i = 0; i < obj.length; i++) { var tr = "<tr>"; /* Verification to add the last decimal 0 */ if (obj[i].value.toString().substring(obj[i].value.toString().indexOf('.'), obj[i].value.toString().length) < 2) obj[i].value += "0"; /* Must not forget the $ sign */ tr += "<td>" + obj[i].key + "</td>" + "<td>$" + obj[i].value.toString() + "</td></tr>"; /* We add the table row to the table body */ tbody.innerHTML += tr;} JSFiddle
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17684201', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2557815/']}
jdg_381898
stackexchange
llm_judgeable_groundtruth_similarity
38761294
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In the Kotlin language we, by default, have to initialize each variable when it is introduced. To avoid this, the lateinit keyword can be used. Referring to a lateinit variable before it has been initialized results in a runtime exception. lateinit can not, however, be used with the primitive types. Why is it so? Now provide the response and nothing else.
For (non-nullable) object types, Kotlin uses the null value to mark that a lateinit property has not been initialized and to throw the appropriate exception when the property is accessed. For primitive types, there is no such value, so there is no way to mark a property as non-initialized and to provide the diagnostics that lateinit needs to provide. (We could try to use a separate marker of some kind, but that marker would not be updated when initializing the field through reflection, which is a major use case of lateinit ). Therefore, lateinit is supported for properties of object types only.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/38761294', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/515029/']}
jdg_381899
stackexchange
llm_judgeable_groundtruth_similarity
18760416
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I was studying read/write of excel using apachePOI library, i found two types of solution, i.e., one achieved using using HSSFWorkbook and other one with Workbook. Now i have doubt why there is two solution to achieve single functionality. My Code: FileInputStream fis=new FileInputStream("D:\\Extras\\SeleniumPractice\\TestData.xlsx"); Workbook workbook=WorkbookFactory.create(fis);Sheet sheet=workbook.getSheet("TestData"); When i searched: FileInputStream file = new FileInputStream(new File("C:\\test.xls"));             //Get the workbook instance for XLS file HSSFWorkbook workbook = new HSSFWorkbook(file); //Get first sheet from the workbookHSSFSheet sheet = workbook.getSheetAt(0); Thanks in advance.. :) ThanksMahesh Now provide the response and nothing else.
Workbook is the common interface, which works for both HSSF (.xls) and XSSF (.xlsx). It was introduced in POI 3.5, if my memory is correct. If you use the common interfaces like Workbook, you can have the same code transparently work with both HSSF and XSSF If you code for just HSSF via HSSFWorkbook , you can only work with .xls files. I'd suggest you go for the common ones wherever possible Your loading code should be something like: Workbook wb = WorkbookFactory.create(new File("test.xls")); Sheet s = wb.getSheetAt(0); .... That will auto-detect the type of the file, and give you back a working object for either .xls or .xlsx based on what it finds
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18760416', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2485634/']}
jdg_381900
stackexchange
llm_judgeable_groundtruth_similarity
14707360
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Ok, I think I need to repost my question that was originally: Javascript Regex group multiple with a full example. I have: var text = ""+ "<html> " + " <head> " + " </head> " + " <body> " + " <g:alert content='alert'/> " + " <g:alert content='poop'/> " + " </body> " + "</html>"; var regex = /<([a-zA-Z]*?):([a-zA-Z]*?)\s([\s\S]*?)>/m; var match = regex.exec( text ); console.log(match) Output from console.log is: The problem is that I am only getting the result for the first ... not the other... what can I do to be able to capture and walk over all stuff that matched? Now provide the response and nothing else.
exec returns only ONE result at a time and sets the pointer to the end of that match. Therefore, if you want to get ALL matches use a while loop: while ((match = regex.exec( text )) != null){ console.log(match);} To get all matches at one shot, use text.match(regex) , in which the regex has g (global flag) specified. The g flag will make match find all matches to the regex in the string and return all the matches in an array. [edit]and that's why my example HAD a g flag set![/eoe] var text = ""+ "<html> " + " <head> " + " </head> " + " <body> " + " <g:alert content='alert'/> " + " <g:alert content='poop'/> " + " </body> " + "</html>";// Note the g flagvar regex = /<([a-zA-Z]*?):([a-zA-Z]*?)\s([\s\S]*?)>/gm;var match = text.match( regex );console.log(match); SIMPLE TEST: <button onclick="myFunction()">Try it</button><script>function myFunction(){var text = ""+ "<html> " + " <head> " + " </head> " + " <body> " + " <g:alert content='alert'/> " + " <g:alert content='poop'/> " + " </body> " + "</html>";// Note the g flagvar regex = /<([a-zA-Z]*?):([a-zA-Z]*?)\s([\s\S]*?)>/gi;var n = text.match( regex );alert(n);}</script> working perfectly...
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14707360', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/961018/']}
jdg_381901
stackexchange
llm_judgeable_groundtruth_similarity
4790652
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's the difference between enum i = 2;enum s = "Hello"; and immutable i = 2;immutable s = "Hello"; in D 2.0? Now provide the response and nothing else.
An enum is a user-defined type, not a variable. enum e = 2; is ashort-hand for something like this enum : int { e = 2 } (i.e. an anonymousenum with one member e ), see the documentation .By definition, all members of an anonymous enum are placed into the current scope. So, e is a type member placed into the current scope, where it behaveslike a literal . immutable i = 2; on the other hand actually creates a variable i of type int. This difference has a couple of consequences: enum e will have no memory location and no address (is no lvalue), sinceneither a type nor its members have an address. I.e. you cannot do something like auto ptr = &e; (just like you cannot do auto ptr = &2; ). immutable i on the other hand is a normal variable (just immutable). As discussed by Jonathan ,immutable variables can be initialized at compile time or at run-time,whereas a type (with all its members defining the type) must be known at compile time. The compiler can simply replace all appearances of e with 2 . For i itusually has to create a memory location (although an optimizing compilermight be able to avoid this sometimes). For this reason, the workload duringcompilation for an enum might be expected to be somewhat lower, and thebinary somewhat smaller. There is a surprising difference for arrays. For enum uint[2] E = [0, 1]; and immutable uint[2] I = [0, 1]; the access to the enum , e.g. E[0] , canbe orders of magnitude slower than for the immutable array, e.g. I[0] ,especially as the arrays E and I get bigger. This is so because for an immutable array, it is just a normal array lookup to, say, a globalvariable. For the enum however it looks like the array gets created everytime before it gets used, e.g. inside a function for a global enum (don'task me, why, but the compiler really seems to simply replace the appearancewith the value in this case, too). I have never tried but would guess thatthe same applies to enum strings and other non-trivial types. To sum up: when I use compile-time constants, I usually take enum unlessthose constants are arrays or I need a memory location for some other reason.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4790652', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/541686/']}
jdg_381902
stackexchange
llm_judgeable_groundtruth_similarity
47064090
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: One of my Rails migrations uses a uuid as the primary key. The Postgres extension gen_random_uuid() should solve this issue, but I continue to get the error after installing the relevant extension ( uuid-ossp ). Now provide the response and nothing else.
The issue was that the uuid-ossp extension was being blown away with the database each time I dropped the db as part of a reset and migration (e.g. rake db:drop db:create db:migrate ). The fix is to create a migration that's run before all other migrations which enables the relevant extension(s). Like so ( db/migrate/0_enable_extensions.rb ): class EnableExtensions < ActiveRecord::Migration[5.1] def change enable_extension 'uuid-ossp' enable_extension 'pgcrypto' endend
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/47064090', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3006381/']}
jdg_381903
stackexchange
llm_judgeable_groundtruth_similarity
32007871
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to use C# 6 in my project (null propagation, other features). I've installed VS 2015 on my PC and it works brilliantly and builds test code like var user = new SingleUserModel(); //all model fields are nullvar test = user.User?.Avatar?["blah"]; But when I push my project to the repo and CI starts to build it, build fails because of unsupported ? . I've installed VS2015 on CI server too but looke like it doesn't use it.What can I do? CI - CruiseControl .NETBuilds with C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe Now provide the response and nothing else.
Make sure you call: C:\Program Files (x86)\MSBuild\14.0\Bin\MsBuild.exe That's the version of MsBuild that ships with Visual Studio 2015 and calls the C# compiler that understands this. You can get this version of MsBuild on your system by installing any edition of Visual Studio 2015 or by installing the stand-alone Microsoft Build Tools 2015 . Adding a reference to the following NuGet package will also force use of the new compiler: Install-Package Microsoft.Net.Compilers Please note Install-Package will pick the latest available version which may not be the one you are looking for. Before you install, please check the release notes and dependencies to resolve the underlying issue with the version being dealt with, which in this case, was more specific to VS 2015. So for Visual Studio 2015: Install-Package Microsoft.Net.Compilers -Version 1.0.0
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/32007871', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1177168/']}
jdg_381904
stackexchange
llm_judgeable_groundtruth_similarity
2463768
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: So earlier today I came across Elchanan Mossel's Dice Paradox , and I am having some trouble understanding the solution. The question is as follows: You throw a fair six-sided die until you get 6. What is the expected number of throws (including the throw giving 6) conditioned on the event that all throws gave even numbers? Quoted from Jimmy Jin in "Elchanan Mossel’s dice problem" In the paper it goes on to state why a common wrong answer is $3$. Then afterwards explains that this problem has the same answer to, "What is the expected number of times you can roll only $2$’s or $4$’s untilyou roll any other number?" I don't understand why this is the case. If the original problem is asking for specifically a $6$, shouldn't that limit many of the possible sequences? I also attempted to solve the problem using another method, but got an answer different from both $3$ and the correct answer of $1.5$. I saw that possible sequences could have been something like: $$\{6\}$$$$\{2,6\}, \{4,6\}$$$$\{2,2,6\}, \{2,4,6\}, \{4,2,6\}, \{4,4,6\}$$$$\vdots$$ To which I set up the following summation and solved using Wolfram Alpha : $$\text{Expected Value} =\sum_{n=1}^\infty n\left( {\frac{1}{6}} \right)^n 2^{n-1} = 0.375$$Obviously this is different and probably incorrect, but I can't figure out where the error in the thought process is. Any help on understanding this would be greatly appreciated. A blog post discussing the problem can be found here. Now provide the response and nothing else.
When you roll a die until $6$ appears, you can represent the sample space as all possible finite sequences from the set $\{1, 2, 3, 4, 5, 6\}$ ending in $6$, with probability of any sequence of length $k$ being $(1/6)^k$. The original question is asking for $(1)$ the expected length of a sequence conditional on all throws being even. You've correctly enumerated all sequences from $\{2,4,6\}$ that end in $6$, and calculated the sum$$\sum_{n=1}^\infty n\left( {\frac{1}{6}} \right)^n 2^{n-1} = 0.375$$properly, but you forgot to divide this by the probability of the event you are conditioning on, which is$$\sum_{n=1}^\infty\left(\frac16\right)^n2^{n-1}=1/4.$$So your approach does yield the correct answer, namely $4\times 0.375=1.5$. The act of conditioning on all throws being even is tantamount to restricting the sample space to all possible finite sequences from the set $\{2, 4, 6\}$ that end in $6$, and rescaling the probability function (by a factor $4$) so that this new sample space has total mass $1$. As for the Jin paper, he claims that the original question $(1)$ is equivalent to $(2)$ the expected number of times you can roll only $2$'s or $4$'s until you roll a $6$. I disagree with $(2)$; it is incorrect to compute an unconditional expectation, as he just explained in his previous paragraph. He still needs an expectation conditional on some event, and I would argue the original question $(1)$ is equivalent to computing $(2')$ the expected number of times you can roll only $2$'s or $4$'s until you roll any other number, given that the other number is $6$. The reason is that conditioning on the event "the other number is $6$" results in the same restricted sample space as before. In fact his subsequent argument that it suffices to compute the unconditional expectation $(3)$ the expected number of times you can roll only $2$'s or $4$'s until you roll any other number. (i.e., that $(2') = (3)$, which is what he actually proves) is relevant only if we intend $(2')$ instead of $(2)$. EDIT: Here's a Python simulation of the experiment, based on code provided by @thecoder: import randomtimes = 0 #number of times a successful (all-even) sequence was rolledrolls = 0 #total of all number of rolls it took to get a 6, on successful sequencescurr = 0alleven = Truefor x in range(0, 100000): num = random.randint(1,6) if num % 2 != 0: alleven = False else: if num == 6: if alleven: times += 1 rolls += curr + 1 curr = 0 alleven = True else: curr += 1print(rolls * 1.0 / times)#1.51506456241
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2463768', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/323744/']}
jdg_381905
stackexchange
llm_judgeable_groundtruth_similarity
26732952
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 convert my app to use the v21 AppCompat library, so I started to use Toolbar instead of ActionBar. In all my regular activities (which extend ActionBarActivity) everything is fine. but in my SettingsActivity which extends PreferenceActivity, and therefore I can't use the setSupportActionBar(actionbar) call I need to use a "standalone" toolbar. The toolbar shows up, but I can't figure out how could I add the "home / up" button to the toolbar. SettingsActivity.java: public class SettingsActivity extends PreferenceActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); Toolbar actionbar = (Toolbar) findViewById(R.id.actionbar); if (null != actionbar) { // In every other activity that extends ActionBarActivity I simply use: // setSupportActionBar(actionbar); // final ActionBar supportActionBar = getSupportActionBar(); // supportActionBar.setDisplayHomeAsUpEnabled(true); // but in PreferenceActivity you need to add a standalone toolbar: actionbar.setTitle(R.string.title_activity_settings); actionbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SettingsActivity.this.finish(); } }); // Inflate a menu to be displayed in the toolbar actionbar.inflateMenu(R.menu.settings); } }} layout/activity_settings.xml: <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" tools:context=".SettingsActivity" tools:menu="settings" tools:actionBarNavMode="standard" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <include layout="@layout/actionbar" android:layout_width="match_parent" android:layout_height="wrap_content"/> <ListView android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@android:id/list" /></LinearLayout> layout/actionbar.xml: <?xml version="1.0" encoding="utf-8"?><android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/actionbar" android:layout_height="wrap_content" android:layout_width="match_parent" android:minHeight="?attr/actionBarSize" android:background="?attr/colorPrimaryDark" app:theme="@style/AppTheme" /> menu/settings.xml: <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" tools:context="com.fletech.android.redalert.SettingsActivity" ></menu> I tried to add actionBarStyle and displayOptions to my theme as explained in Show up/back button on android nested PreferenceScreen? , but in other places people said that actionBarStyle won't be used when I use Toolbar, and they seem to be right. values/themes.xml: <?xml version="1.0" encoding="utf-8"?><resources> <style name="AppTheme" parent="AppTheme.Base"/> <style name="AppTheme.Base" parent="Theme.AppCompat"> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimary</item> <item name="android:windowNoTitle">true</item> <item name="windowActionBar">false</item> <item name="windowActionModeOverlay">true</item> <!-- Set AppCompat’s actionBarStyle --> <item name="actionBarStyle">@style/MyActionBar</item> </style> <style name="MyActionBar" parent="Widget.AppCompat.ActionBar"> <item name="displayOptions">showHome|homeAsUp|showTitle</item> </style><resources> Now provide the response and nothing else.
@Pedro Oliveira's solution worked. I could even find the drawable that the AppCompat library uses (and therefore is already included in the apk). What more it's also mirrored, so it works both for ltr, rtl locales: actionbar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha); and this is it alltogether, with the correction from @VictorYakunin public class SettingsActivity extends PreferenceActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); Toolbar actionbar = (Toolbar) findViewById(R.id.actionbar); if (null != actionbar) { actionbar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha); actionbar.setTitle(R.string.title_activity_settings); actionbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { NavUtils.navigateUpFromSameTask(SettingsActivity.this); } }); // Inflate a menu to be displayed in the toolbar actionbar.inflateMenu(R.menu.settings); } }}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/26732952', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/661589/']}
jdg_381906
stackexchange
llm_judgeable_groundtruth_similarity
13843772
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: GCC version 4.6 The Problem: To find a way to feed in parameters to the executable, say a.out , from the command line - more specifically feed in an array of double precision numbers. Attempt: Using the READ(*,*) command, which is older in the standard:Program test.f - PROGRAM MAIN REAL(8) :: A,B READ(*,*) A,B PRINT*, A+B, COMMAND_ARGUMENT_COUNT()END PROGRAM MAIN The execution - $ gfortran test.f$ ./a.out 3.D0 1.D0 This did not work. On a bit of soul-searching, found that $./a.out3.d0,1.d0 4.0000000000000000 0 does work, but the second line is an input prompt, and the objective of getting this done in one-line is not achieved. Also the COMMAND_ARGUMENT_COUNT() shows that the numbers fed into the input prompt don't really count as 'command line arguments', unlike PERL. Now provide the response and nothing else.
If you want to get the arguments fed to your program on the command line, use the (since Fortran 2003) standard intrinsic subroutine GET_COMMAND_ARGUMENT . Something like this might work PROGRAM MAIN REAL(8) :: A,B integer :: num_args, ix character(len=12), dimension(:), allocatable :: args num_args = command_argument_count() allocate(args(num_args)) ! I've omitted checking the return status of the allocation do ix = 1, num_args call get_command_argument(ix,args(ix)) ! now parse the argument as you wish end do PRINT*, A+B, COMMAND_ARGUMENT_COUNT()END PROGRAM MAIN Note: The second argument to the subroutine get_command_argument is a character variable which you'll have to parse to turn into a real (or whatever). Note also that I've allowed only 12 characters in each element of the args array, you may want to fiddle around with that. As you've already figured out read isn't used for reading command line arguments in Fortran programs. Since you want to read an array of real numbers, you might be better off using the approach you've already figured out, that is reading them from the terminal after the program has started, it's up to you.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13843772', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1472196/']}
jdg_381907
stackexchange
llm_judgeable_groundtruth_similarity
41623
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 that true that all the prime numbers are of the form $6m \pm 1$ ? If so, can you please provide an example? Thanks in advance. Now provide the response and nothing else.
This is true of all prime numbers except for $2$ and $3$. The reason is that numbers with remainders $0$, $2$ and $4$ modulo $6$ are divisible by $2$, and numbers with remainders $0$ and $3$ modulo $6$ are divisible by $3$, so other than $2$ and $3$ themselves, all prime numbers must have remainder $1$ or $5$ modulo $6$.
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/41623', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/11406/']}
jdg_381908
stackexchange
llm_judgeable_groundtruth_similarity
3235685
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 stumbled across something "interesting" and I cant put my finger why the behaviour isn't coherent. Check this code. char buf[100];sprint(buf,"%s",bla); Simple, right. It's easy to understand what is going on when bla is a NULL pointer. This should always segfault right!? In one machine the executable segfaults, on another (my development machine), it's just business as usual. My devel PC is running Windows7 and I'm compiling with gcc/MingW . The computer where this is crashing is XP and it does have Visual studio 6 installed. Why doesn't this crash on my PC? Now provide the response and nothing else.
ISO C99: 7.19.6.3 The printf function Synopsis #include <stdio.h> int printf(const char * restrict format, ...); The printf function is equivalent to fprintf with the argument stdout interposed before the arguments to printf. 7.19.6.1 The fprintf function 7.19.6.1.9 If a conversion specification is invalid, the behavior is **undefined**. If any argument isnot the correct type for the corresponding conversion specification, the behavior is **undefined**. So your code invokes Undefined Behavior [ (ISO C99 3.4.3)behavior, upon use of a nonportable or erroneous program construct or of erroneous data,for which this International Standard imposes **no requirements** ] This should always segfault right!? Not necessarily, Undefined Behavior means anything can happen.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3235685', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/147941/']}
jdg_381909
stackexchange
llm_judgeable_groundtruth_similarity
1598092
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: While solving a quantum mechanics problem using perturbation theory I encountered the following sum$$S_{0,1}=\sum_{m=1}^\infty\frac{y_{1,m}y_{0,1}}{[y_{1,m}-y_{0,1}]^3},$$where $y_{n,k}=\left(\text{BesselJZero[n,k]}\right)^2$ is square of the $k$-th zero of Bessel function $J_n$ of the first kind. Numerical calculation using Mathematica showed that $S_{0,1}\approx 0.1250000$. Although I couldn't verify this with higher precision I found some other cases where analogous sums are close to rational numbers. Specifically, after some experimentation I found that the sums$$S_{n,k}=\sum_{m=1}^\infty\frac{y_{n+1,m}y_{n,k}}{[y_{n+1,m}-y_{n,k}]^3}$$are independent of $k$ and have rational values for integer $n$, and made the following conjecture $\bf{Conjecture:}\ $ for $k=1,2,3,...$ and arbitrary $n\geq 0$ $$\sum_{m=1}^\infty\frac{y_{n+1,m}y_{n,k}}{[y_{n+1,m}-y_{n,k}]^3}\overset{?}=\frac{n+1}{8},\\ \text{where}\ y_{n,k}=\left(\text{BesselJZero[n,k]}\right)^2. $$ How one can prove it? It seems this conjecture is correct also for negative values of $n$. For example for $n=-\frac{1}{2}$ one has $y_{\frac{1}{2},m}=\pi^2 m^2$, $y_{-\frac{1}{2},k}=\pi^2 \left(k-\frac{1}{2}\right)^2$ and the conjecture becomes (see Claude Leibovici's answer for more details)$$\sum_{m=1}^\infty\frac{m^2\left(k-\frac{1}{2}\right)^2}{\left(m^2-\left(k-\frac{1}{2}\right)^2\right)^3}=\frac{\pi^2}{16}.$$ Now provide the response and nothing else.
There is a rather neat proof of this. First, note that there is already an analogue for this: DLMF §10.21 says that a Rayleighfunction $\sigma_n(\nu)$ is defined as a similar power series$$ \sigma_n(\nu) = \sum_{m\geq1} y_{\nu, m}^{-n}. $$It links to http://arxiv.org/abs/math/9910128v1 among others as an example of howto evaluate such things. In your case, call $\zeta_m = y_{\nu,m}$ and $z=y_{\nu-1,k}$ ($\nu$ is $n$ shifted by $1$), so that afterexpanding in partial fractions your sum is$$ \sum_{m\geq1} \frac{\zeta_m z}{(\zeta_m-z)^3} = \sum_{m\geq1}\frac{z^2}{(\zeta_m-z)^3} + \frac{z}{(\zeta_m-z)^2}. $$ Introduce the function$$ y_\nu(z) = z^{-\nu/2}J_\nu(z^{1/2}). $$By DLMF 10.6.5 its derivativesatisfies the two relations$$\begin{aligned} y'_\nu(z) &= (2z)^{-1} y_{\nu-1}(z) - \nu z^{-1} y_\nu(z) \\&=-\tfrac12 y_{\nu+1}(z).\end{aligned} $$ It also has the infinite productexpansion $$ y_\nu(z) = \frac{1}{2^\nu\nu!}\prod_{k\geq1}(1 - z/\zeta_k). $$Therefore, each partial sum of $(\zeta_k-z)^{-s}$, $s\geq1$ can be evaluated interms of derivatives of $y_\nu$:$$ \sum_{k\geq1}(\zeta_k-z)^{-s} = \frac{-1}{(s-1)!}\frac{d^s}{dz^s}\logy_\nu(z). $$When evaluating this logarithmic derivative, the derivative $y'_\nu$can be expressed in terms of $y_{\nu-1}$, going down in $\nu$, but the derivative$y'_{\nu-1}$ can be expressed in terms of $y_\nu$ using the otherrelation that goes up in the index $\nu$. So even higher-order derivatives contain only $y_\nu$ and $y_{\nu-1}$. I calculated your sum using this procedure with a CAS as:$$ -\tfrac12z^2(\log y)''' -z(\log y)''= \tfrac18\nu + z^{-1} P\big(y_{\nu-1}(z)/y_\nu(z)\big), $$where $P$ is the polynomial$$ P(q) = -\tfrac18 q^3 + (\tfrac38\nu-\tfrac18) q^2 + (-\tfrac14\nu^2+ \tfrac14\nu - \tfrac18)q. $$ When $z$ is chosen to be any root of $y_{\nu-1}$,$z=\mathsf{BesselJZero}[\nu-1, k]\hat{}2$, $P(q)=0$, your sum is equalto$$ \frac{\nu}{8}, $$which is $(n+1)/8$ in your notation. It is possible to derive a number of such closed forms for sums ofthis type. For example, by differentiating $\log y$ differently(going $\nu\to\nu+1\to\nu$), one would get$$ \sum_{m\geq1}\frac{y_{\nu,m}y_{\nu+1,k}}{(y_{\nu,m}-y_{\nu+1,k})^3} =-\frac{\nu}{8}. $$ Some other examples, for which the r.h.s. is independent of $z$ ($\zeta_m=y_{\nu,m}, z=y_{\nu-1,l}$, $l$ arbitrary):$$ \begin{gathered}\sum_{k\geq1} \frac{\zeta_k}{(\zeta_k-z)^2} = \frac14,\\\sum_{k\geq1} \frac{z^2}{(\zeta_k-z)^4} - \frac{1}{(\zeta_k-z)^2} + \frac1{24}\frac{5-\nu}{\zeta_k-z} = \frac{1}{48}, \\\sum_{k\geq1} \frac{\zeta_k}{(\zeta_k-z)^4} + \frac1{96}\frac{z-\zeta_k-8+4\nu}{(\zeta_k-z)^2} = 0. \end{gathered} $$or with $z=y_{\nu+1,l}$, $l$ arbitrary:$$ \begin{gathered}\sum_{k\geq1} \frac{z^2}{(\zeta_k-z)^3} = -\tfrac18\nu-\tfrac14,\end{gathered} $$and they get messier with higher degrees.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1598092', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_381910
stackexchange
llm_judgeable_groundtruth_similarity
2544389
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 company took some old php application over. Due to our preference to ASP.net and to the lack of any documentation from the previous developer, we do not want to spend much resources on developing in PHP.For implementing new features, we will create an Asp.net application that has the same look to the user. We want to develop a kind of 'coexisting' web application. Therefore we must share sessions between an PHP and an Asp.net webapplication project, because there is a usermanagement involved with an existing MySQL database. (e.g. link 'A' directs to the PHP website, and link 'B' directs to the asp.net application) How can we share the session between and PHP and an asp.net application? And does anyone have a hint for this 'coexisting' thing, that might be useful in development? Edit : IIS 6 would be our targeted server, altough IIS 7.5 would also be an option Now provide the response and nothing else.
I want to tell you, how I ended up doing it. Both applications access a MySQL database and access a "session" table, which consists of a Guid, the ID of the user, and a confirmationString (I guess I encoded the IDUser in it, somehow) and a date. Sessions are only started by the PHP application (due to the fact, that the PHP application is still the main application). A new session will result in a new entry in the log table. Every link in the PHP application, that links to the ASP.Net application contains GET-Parameters, containing the Guid etc. The ASP.net application checks for the GET-Parameters and sets the IDUser in the ASP.Net Session, if the GET-Parameters point to an existing session. The links pointing back to the PHP application use the same technique. (There are also other things to consider, like timeouts or logouts, but that can be handled as well) All in all, I'd say that my approach is useful and none of the customers complained since the deployment (over 1 year ago)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2544389', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/225808/']}
jdg_381911
stackexchange
llm_judgeable_groundtruth_similarity
42581847
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 customize password reset email in Laravel. I have to override this function: namespace Illuminate\Auth\Passwords;use Illuminate\Auth\Notifications\ResetPassword as ResetPasswordNotification;use Illuminate\Http\Request;trait CanResetPassword{ /** * Get the e-mail address where password reset links are sent. * * @return string */ public function getEmailForPasswordReset() { return $this->email; } /** * Send the password reset notification. * * @param string $token * @return void */public function sendPasswordResetNotification($token){ $this->notify(new ResetPasswordNotification($token));} This is my attempt: public function sendPasswordResetNotification($token, Requests $request){Mail::to($request->email)->send(new newpassword($token));} I get this error: Declaration of Illuminate\Foundation\Auth\User::sendPasswordResetNotification($token, Illuminate\Http\Request $request) must be compatible with Illuminate\Contracts\Auth\CanResetPassword::sendPasswordResetNotification($token) Now provide the response and nothing else.
If you read the error, it's telling you your class is not compatible with CanResetPassword . If you look at that.... interface CanResetPassword{ /** * Get the e-mail address where password reset links are sent. * * @return string */ public function getEmailForPasswordReset(); /** * Send the password reset notification. * * @param string $token * @return void */ public function sendPasswordResetNotification($token);} You can see the function sendPasswordResetNotification should only take one parameter, $token . So you need to remove Request $request as a parameter from the method's signature. In order to get the request, you will want to use the function request() inside the sendPasswordResetNotification method. public function sendPasswordResetNotification($token){ Mail::to(request()->email)->send(new newpassword($token));}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42581847', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4485955/']}
jdg_381912
stackexchange
llm_judgeable_groundtruth_similarity
47462114
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I just installed tensorflow for gpu and am using keras for my CNN. During training my GPU is only used about 5%, but 5 out of 6gb of the vram is being used during the training. Sometimes it glitches, prints 0.000000e+00 in the console and the gpu goes to 100% but then after a few seconds the training slows back down to 5%. My GPU is the Zotac gtx 1060 mini and I am using a Ryzen 5 1600x. Epoch 1/25 121/3860 [..............................] - ETA: 31:42 - loss: 3.0575 - acc: 0.0877 - val_loss: 0.0000e+00 - val_acc: 0.0000e+00Epoch 2/25 121/3860 [..............................] - ETA: 29:48 - loss: 3.0005 - acc: 0.0994 - val_loss: 0.0000e+00 - val_acc: 0.0000e+00Epoch 3/25 36/3860 [..............................] - ETA: 24:47 - loss: 2.9863 - acc: 0.1024 Now provide the response and nothing else.
Usually, we want the bottleneck to be on the GPU (hence 100% utilization). If that's not happening, some other part of your code is taking a long time during each batch processing. It's hard to say what is it (specialy because you didn't add any code), but there's a few things you can try: 1. input data Make sure the input data for your network is always available. Reading images from disk takes a long time, so use multiple workers and the multiprocessing interface: model.fit(..., use_multiprocessing=True, workers=8) 2. Force the model into the GPU This is hardly the problem, because /gpu:0 is the default device, but it's worth to make sure you are executing the model in the intended device: with tf.device('/gpu:0'): x = Input(...) y = Conv2D(..) model = Model(x, y) 2. Check the model's size If your batch size is large and allowed soft placement, parts of your network (which didn't fit in the GPU's memory) might be placed at the CPU. This considerably slows down the process. If soft placement is on, try to disable and check if a memory error is thrown: # make sure soft-placement is offtf_config = tf.ConfigProto(allow_soft_placement=False)tf_config.gpu_options.allow_growth = Trues = tf.Session(config=tf_config)K.set_session(s)with tf.device(...): ...model.fit(...) If that's the case, try to reduce the batch size until it fits and give you good GPU usage. Then turn soft placement on again.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47462114', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6252787/']}
jdg_381913
stackexchange
llm_judgeable_groundtruth_similarity
37305230
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've been through dozens of potential solutions to this problem but cannot find anything that works. Basically, PHP files are not executing on my NginX + PHP_fpm + Ubuntu 14 server. I have all the packages, and they are running. I've cleared browser cache etc., but nothing has worked yet. I appreciate all the help! As of right now, if I try accessing the PHP file, the GET will return it as an HTML file but will not execute the script. Here is my nginx.conf file: worker_processes 1;worker_rlimit_nofile 8192;events { worker_connections 3000;}error_log /var/log/nginx/error.log warn;pid /var/run/nginx.pid;http { include /etc/nginx/mime.types; #default_type application/octet-stream; default_type text/html; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; #tcp_nopush on; keepalive_timeout 65; #gzip on; include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*;} Here is my /sites-available/default file: ### You should look at the following URL's in order to grasp a solid understanding# of Nginx configuration files in order to fully unleash the power of Nginx.# http://wiki.nginx.org/Pitfalls# http://wiki.nginx.org/QuickStart# http://wiki.nginx.org/Configuration## Generally, you will want to move this file somewhere, and start with a clean# file but keep this around for reference. Or just disable in sites-enabled.## Please see /usr/share/doc/nginx-doc/examples/ for more detailed examples.### Default server configuration#server { listen 80 default_server; listen [::]:80 default_server ipv6only=on; # SSL configuration # # listen 443 ssl default_server; # listen [::]:443 ssl default_server; # # Note: You should disable gzip for SSL traffic. # See: https://bugs.debian.org/773332 # # Read up on ssl_ciphers to ensure a secure configuration. # See: https://bugs.debian.org/765782 # # Self signed certs generated by the ssl-cert package # Don't use them in a production server! # # include snippets/snakeoil.conf; root /usr/share/nginx/html; # Add index.php to the list if you are using PHP index index.php index.html index.htm index.nginx-debian.html; server_name localhost; location / { # First attempt to serve request as file, then # as directory, then fall back to displaying a 404. try_files $uri $uri/ =404; } error_page 404 /404.html; error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 # location ~ \.php$ { try_files $uri =404; include snippets/fastcgi-php.conf; # With php5-cgi alone: #fastcgi_pass 127.0.0.1:9000; # With php5-fpm: #fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass unix:/var/run/php5-fpm.sock; #fastcgi_index index.php; include fastcgi_params; } # deny access to .htaccess files, if Apache's document root # concurs with nginx's one # #location ~ /\.ht { # deny all; #}}# Virtual Host configuration for example.com## You can move that to a different file under sites-available/ and symlink that# to sites-enabled/ to enable it.##server {# listen 80;# listen [::]:80;## server_name example.com;## root /var/www/example.com;# index index.html;## location / {# try_files $uri $uri/ =404;# }#} Here is my server conf file: server { listen 8000 default_server; listen [::]:8000 default_server ipv6only=on; root /var/www/html; #index index.php index.html index.htm; #location / { #index index.php index.html index.htm; #}} As you can see, I've been playing around with these files. But to no avail. Now provide the response and nothing else.
Ok, so based on our comments back and forth you need to add this section to your nginx config for the server config listening on :8000. That regex tells nginx that whenever it gets a request for a URL with a file ending in .php to send that to the fastcgi process. Otherwise it's going to default to returning the raw file that matches in /var/www/html. Hope that helps. # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000#location ~ \.php$ { try_files $uri =404; include snippets/fastcgi-php.conf; # With php5-cgi alone: #fastcgi_pass 127.0.0.1:9000; # With php5-fpm: #fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass unix:/var/run/php5-fpm.sock; #fastcgi_index index.php; include fastcgi_params;}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37305230', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6351968/']}
jdg_381914
stackexchange
llm_judgeable_groundtruth_similarity
54519626
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In the docs here - https://docs.python.org/3/library/json.html it says of object_pairs_hook : object_pairs_hook is an optional function that will be called with the result of any object literal decoded with an ordered list of pairs. The return value of object_pairs_hook will be used instead of the dict. This feature can be used to implement custom decoders. If object_hook is also defined, the object_pairs_hook takes priority. There is one rather impressive example of it in this answer . I don't understand what a "hook" is or how this feature works. The docs don't really explain it very clearly. I would like to write one now (otherwise it will be a mess of string methods on the string I am parsing) Does anyone know of a tutorial on this feature or understand it well enough to explain in detail how it works? They seem to assume in the docs that you know what is going on in the black box of json.loads() Now provide the response and nothing else.
It allows you to customize what objects your JSON will parse into. For this specific argument ( object_pairs_hook ) it's for pair (read key/value pairs of a mapping object). For instance if this string appears in your JSON: {"var1": "val1", "var2": "val2"} It will call the function pointed to with the following argument: [('var1', 'val1'), ('var2', 'val2')] Whatever the function returns is what will be used in the resulting parsed structure where the above string was. A trivial example is object_pairs_hook=collections.OrderedDict which ensures your keys to be ordered the same way as they were they occurred in the incoming string. The generic idea of a hook is to allow you to register a function that is called (back) as needed for a given task. In this specific case it allows you to customize decoding of (different types of objects in the) incoming JSON string.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/54519626', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4288043/']}
jdg_381915
stackexchange
llm_judgeable_groundtruth_similarity
624528
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: Running nginx 1.0.15 on CentOS 6.5 . I have three upstream servers and everything works fine, however when I simulate an outage, and take one of the upstream servers down, I notice considerable lag in response times (additional 5-7 seconds). The second I bring the downed server back online, the lag disappears. Also, another weird thing I noticed, if I simply stop the httpd service on the simulated outage server, the response times are normal, the lag only occurs if the server is completely down. Here is my conf: upstream prod_example_com { server app-a-1:51000; server app-a-2:51000; server app-a-3:51000;}server { # link: http://wiki.nginx.org/MailCoreModule#server_name server_name example.com www.example.com *.example.com; #----- # Upstream logic #----- set $upstream_type prod_example_com; #----- include include.d/common.conf; # Configure logging access_log /var/log/nginx/example/access/access.log access; error_log /var/log/nginx/example/error.log error; location / { # link: http://wiki.nginx.org/HttpProxyModule#proxy_pass proxy_pass http://$upstream_type$request_uri; # link: http://wiki.nginx.org/HttpProxyModule#proxy_set_header proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ { # link: http://wiki.nginx.org/HttpProxyModule#proxy_pass proxy_pass http://$upstream_type$request_uri; # link: http://wiki.nginx.org/HttpProxyModule#proxy_set_header proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_hide_header expires; proxy_hide_header Cache-Control # Even tho this reads like the older syntax, it is handled internally by nginx to set max age to now + 1 year expires max; # Allow intermediary caches the ability to cache the asset add_header Cache-Control "public"; }} I have tried the suggestions on similar posts like this . And apparently my version of nginx is too old to support health_checks as outlined in the nginx docs . I've also tried to explicitly set the max_fails=2 and fail_timeout=120 on the app-a-3 upstream definition, but none of these seem to avoid the additional 5-7 seconds lag for every request if app-a-3 is offline. -- Update -- Per request, here is the output for a single request when app-a-3 is completely down. The only thing I could see out of the ordinary is the 3 second lag between initial event and subsequent event. -- Update #2 -- Looks like a few years ago Nginx decided to create Nginx Plus, which adds active health checks, but for a yearly support contract. Based on some articles I've read, Nginx got sick of making companies millions, and getting nothing in return. As mentioned in the comments we are bootstrapping and don't have the $$ to throw at a $1,350 contract. I did find this repo which provides the functionality. Wondering if anyone has any experience with it? Stable? Performant? Worst case scenario I will just have to bit the bullet and pay the extra $20 / month for a Linode "Node Balancer" which I am pretty sure is based off of Nginx Plus. The only problem is there is no control over the config other than a few generic options, so no way to support multiple vhost files via one balancer, and all the nodes have to be in the same datacenter. -- Update #3 -- Here are some siege results . It seems the second node is misconfigured, as it is only able to handle about 75% of the requests the first and third nodes are handling. Also I thought it odd, that when I took the second node offline, the performance was as bad as if I took the third (better performing) node offline. Logic would dictate that if I removed the weak link (second node), that I would get better performance because the remaining two nodes perform better than the weak link, individually. In short: node 1, 2, 3 + my nginx = 2037 requestsnode 1, 2 + my nginx = 733 requestsnode 1, 3 + my nginx = 639 requests (huh? these two perform better individually so together should be somewhere around ~1500 requests, based on 2000 requests when all nodes are up)node 1, 3 + Linode Load Balancer = 790 requestsnode 1, 2, 3 + Linode Load Balancer = 1,988 requests Now provide the response and nothing else.
If nginx sends a request to a closed port on a server with a functional IP stack, it'll get an immediate negative acknowledgement. If there's no server there to respond (or if you drop the incoming packet at a firewall) then you'll have to wait for the connection to time out. Most load balancers have a polling mechanism and/or heartbeat for preemptively checking for a down server. You might want to look into those options. Polling isn't usually run against a web server more than once or twice a minute, but a heartbeat check for server down situations might be every second or so. Nginx is not the most sophisticated of load balancers. If you're getting into this sort of issue you might want to look at other options. EDIT: Something like this maybe? http://www.howtoforge.com/setting-up-a-high-availability-load-balancer-with-haproxy-heartbeat-on-debian-lenny . For a smallish installation, there's no need for separate servers, just put it on the web server boxes. That gives load balancing, but not caching. There are also HA solutions that control squid or varnish in response to a heartbeat.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/624528', 'https://serverfault.com', 'https://serverfault.com/users/87836/']}
jdg_381916
stackexchange
llm_judgeable_groundtruth_similarity
58266688
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 start RMQ inside docker container, with precreated queue qwer . Prior to this, I was using simple docker-compose.yml file: rabbit: image: rabbitmq:management-alpine environment: RABBITMQ_DEFAULT_USER: guest RABBITMQ_DEFAULT_PASS: guest And it worked fine, except that it has no queues pre-created at start.Now I've switched to custom image, with following Dockerfile : FROM rabbitmq:management-alpineADD rabbitmq.conf /etc/rabbitmq/ADD definitions.json /etc/rabbitmq/RUN chown rabbitmq:rabbitmq /etc/rabbitmq/rabbitmq.conf /etc/rabbitmq/definitions.json where rabbitmq.conf is v3.7+ sysctl-styled config, with line: management.load_definitions = /etc/rabbitmq/definitions.json and definitions.json contains attempt to create queue: { "vhosts":[ {"name":"/"} ], "queues":[ {"name":"qwer","vhost":"/","durable":true,"auto_delete":false,"arguments":{}} ]} Now it started to refuse login: Error on AMQP connection <0.660.0> (172.18.0.6:48916 -> 172.18.0.10:5672, state: starting):PLAIN login refused: user 'guest' - invalid credentials I thought that the task is somewhat simple, but configuration process of rabbit itself is most complex task, and documentation is somewhat unclear. I was unable to figure out how should it work, even after 4 days of trials and googling.. Could you help me, how to write configuration file, in order to create a queue and preserve ability to connect and talk to it? Now provide the response and nothing else.
You are almost there actually. RabbitMQ has a rule that the "guest" user can only connect from localhost. Since you are running it on a docker, I'm assuming you are trying to access it from outside by exposing port "15672" by doing: docker run <rabbitmq-docker-img> -p 15672:15672 So to get around this, what you have to do is create a user with admin privileges. Firstly, change this: rabbit: image: rabbitmq:management-alpine environment: RABBITMQ_DEFAULT_USER: user RABBITMQ_DEFAULT_PASS: password You can use ath, I used user/password as your user/password. In your Dockerfile, you can add: EXPOSE 15672 If you don't want to expose each time you run. Lastly, make amends to your definitions.json file as follows: { "users": [ { "name": "user", "password_hash": "password", "hashing_algorithm": "rabbit_password_hashing_sha256", "tags": "administrator" } ], "vhosts":[ {"name":"/"} ], "queues":[ {"name":"qwer","vhost":"/","durable":true,"auto_delete":false,"arguments":{}} ]} Let me know how it goes! Check out this link Use this Dockerfile: FROM rabbitmq# Define environment variables.ENV RABBITMQ_USER userENV RABBITMQ_PASSWORD passwordADD init.sh /init.shEXPOSE 15672# Define default commandCMD ["/init.sh"] And use this init.sh: #!/bin/sh# Create Rabbitmq user( sleep 5 ; \rabbitmqctl add_user $RABBITMQ_USER $RABBITMQ_PASSWORD 2>/dev/null ; \rabbitmqctl set_user_tags $RABBITMQ_USER administrator ; \rabbitmqctl set_permissions -p / $RABBITMQ_USER ".*" ".*" ".*" ; \echo "*** User '$RABBITMQ_USER' with password '$RABBITMQ_PASSWORD' completed. ***" ; \echo "*** Log in the WebUI at port 15672 (example: http:/localhost:15672) ***") &# $@ is used to pass arguments to the rabbitmq-server command.# For example if you use it like this: docker run -d rabbitmq arg1 arg2,# it will be as you run in the container rabbitmq-server arg1 arg2rabbitmq-server $@
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/58266688', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1976993/']}
jdg_381917
stackexchange
llm_judgeable_groundtruth_similarity
40735185
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 document as below: { "_index": "abc_local", "_type": "users", "_id": "1", "_version": 5, "found": true, "_source": { "firstname": "simer", "lastname": "kaur", "gender": "1", "Address": "Punjab House Fed. Housing Society, Amritsar, Punjab, India", "email": "[email protected]", "occupation": "Php Developer", "work": "Development", "fav_hunting_land": 2, "zipcode": "", "marital_status": "1", "phone": "1234567899", "school": "sdfergdfh", "species": [{ "id": 1 }, { "id": 2 }, { "id": 3 }, { "id": 4 }, { "id": 5 }, { "id": 6 }], "activities": [{ "id": 1 }], "fav_weapon": 6, "weapons": [{ "id": 1 }, { "id": 2 }, { "id": 3 }, { "id": 6 }], "properties": [{ "id": 4 }] }} and I need to match user on basis of weapons and I am trying something like: $params = [ 'index' => Constants::INDEX, 'type' => Constants::DOC_TYPE_USERS, 'body' => [ "query"=> [ "bool"=> [ "must"=> [ "match"=> [ "weapons.id"=>$params['weapons'] ]], "should"=> [ [ "match"=> [ "firstname"=> $params['search_text'] ]], [ "match"=> [ "lastname"=> $params['search_text'] ]] ] ] ] ] ]; as I am using elastic in PHP. Here $params['weapons'] is: array (size=2) 0 => string '1' (length=1) 1 => string '2' (length=1) I get an error: illegal_state_exception: Can't get text on a START_ARRAY at 1:36 Any suggestions/help would be appreciated that how I can match array. I took reference from nested datatypes Update#1 :parameters I am sending to my function: {"from":0,"size":null,"city":null,"state":"0","weapons":["1","2"],"activities":[],"species":[],"properties":[],"search_text":"lastname"} update#2 :Body of my query in json format: { "index": "abc_local", "type": "users", "body": { "query": { "bool": { "must": { "match": { "weapons.id": ["1", "2"] } }, "should": [{ "match": { "firstname": "simer" } }, { "match": { "lastname": "simer" } }] } } }} Now provide the response and nothing else.
You can simply replace the first match query by a terms one as match doesn't work with arrays of values. $params = [ 'index' => Constants::INDEX, 'type' => Constants::DOC_TYPE_USERS, 'body' => [ "query"=> [ "bool"=> [ "must"=> [ "terms"=> [ "weapons.id"=>$params['weapons'] ]], ^ | change this "should"=> [ [ "match"=> [ "firstname"=> $params['search_text'] ]], [ "match"=> [ "lastname"=> $params['search_text'] ]] ] ] ] ] ];
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40735185', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3032338/']}
jdg_381918
stackexchange
llm_judgeable_groundtruth_similarity
16055527
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 iCarousel in my iPad application, i would like to know if there is way to change the view of the center item dynamically whenever selected. In short i would like to achieve something like this I managed to set the first index (item - 0) to red, but i could not figure out a way to do the following: When 1 is selected i wish to change the image of 0 to plain white and 1 to red. Something for 2 as well. Any Help or Advise would be appreciated. Thanks Now provide the response and nothing else.
If you want to select item and then change the colour then just simply use: - (void)carousel:(iCarousel *)carousel didSelectItemAtIndex:(NSInteger)index{//change the view of current index} If you want current item colour is red without select, then you need to do more things: - (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view{//Here you need to check current index if (index == self.carousel.currentItemIndex) { //change the view }} And also you need to use this method to check index changed or not: - (void)carouselCurrentItemIndexDidChange:(iCarousel *)carousel{//you need to reload carousel for update view of current index[self.carousel reloadData];}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16055527', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/867094/']}
jdg_381919
stackexchange
llm_judgeable_groundtruth_similarity
855525
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: Prove that $$\underset{n\rightarrow \infty }{\lim} \ \int_{\epsilon }^{\pi} \frac{\sin(nx)}{nx}dx=0\ ;\ \epsilon>0$$ then use the result to deduce: $$\underset{n\rightarrow \infty }{\lim} \ \int_{0 }^{\pi} \frac{\sin(nx)}{nx}dx=0$$ My Attempt: Since $\frac{\sin(nx)}{nx} \leq \frac{1}{n \epsilon} \forall x \in [\epsilon, \pi]$ (of course if we choose $\epsilon$ small enough), it converges uniformly to 0. Solving first part is trivial, however when it comes to the second one: $$\underset{n\rightarrow \infty }{\lim} \ \int_{0 }^{\pi} \frac{\sin(nx)}{nx}dx=\underset{n\rightarrow \infty }{\lim} \ \int_{0 }^{\epsilon} \frac{\sin(nx)}{nx}dx+\underset{n\rightarrow \infty }{\lim} \ \int_{\epsilon }^{\pi} \frac{\sin(nx)}{nx}dx$$I am stuck with the improper integral $\underset{n\rightarrow \infty }{\lim} \ \int_{0 }^{\epsilon} \frac{\sin(nx)}{nx}dx$. It's obvious that it's equal to 0 but I am facing difficulties in showing that. Help would be appreciated. Now provide the response and nothing else.
Since $$\left\lvert \frac{\sin (nx)}{nx}\right\rvert\leqslant 1,$$ you have $$\left\lvert \int_0^\epsilon \frac{\sin (nx)}{nx}\,dx\right\rvert \leqslant \epsilon,$$ and therefore $$\limsup_{n\to\infty} \left\lvert \int_0^\pi \frac{\sin (nx)}{nx}\,dx\right\rvert \leqslant \epsilon.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/855525', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/87286/']}
jdg_381920
stackexchange
llm_judgeable_groundtruth_similarity
3943823
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 simple stored procedure which queries a sys.tables table. CREATE PROCEDURE dbo.test @dbname NVARCHAR(255), @col NVARCHAR(255)AS SET NOCOUNT ON SET XACT_ABORT ON USE @dbname SELECT TOP 100 * FROM sys.tables WHERE name = @colGO This does not seem to work cause I should put GO after USE @dbname but this terminates the creation of this procedure? How can I put this database selction into this procedure so that a user can give a database name as a parameter for this proc? Now provide the response and nothing else.
EDIT My answer assumes some things which make this approach effectively useless. Unfortunately, SO will not let me delete the answer. I recommend @MartinSmith's answer (below in this thread). I think there's still some useful information here, BUT it doesn't actually solve the original problem. Godspeed. Original Response There are at least two ways to do this: Use a case/switch statement (or ,in my example, a naive if..else block) to compare the parameter against a list of databases, and execute a using statement based on that. This has the advantage of limiting the databases that the proc can access to a known set, rather than allowing access anything and everything that the user account has rights to. declare @dbname nvarchar(255); set @dbname = 'db1'; if @dbname = 'db1' use db1; else if @dbname = 'db2' use db2; Dynamic SQL. I HATE dynamic SQL. It's a huge security hole and almost never necessary. (to put this in perspective: In 17 years of professional development, I have never had to deploy a production system which used dynamic SQL). If you decide to go this route, limit the code that is dynamically called/created to a using statement, and a call to another stored proc do do the actual work. You can't just dynamically execute the using statement by itself due to scope rules. declare @sql nvarchar(255); set @sql = 'using '+@dbname+'; exec mydatabase..do_work_proc;'; of course, in your example, you could just do set @sql='select * from '+@dbname+'.sys.tables'; the .<schema_name>. resolution operator allows you to query objects in a different database without using a use statement. There are some very, very rare circumstances in which it may be desirable to allow a sproc to use an arbitrary database. In my opinion, the only acceptable use is a code generator, or some sort of database analysis tool which cannot know the required information ahead of time. Update Turns out you can't use in a stored procedure, leaving dynamic SQL as the only obvious method. Still, I'd consider using select top 100 * from db_name.dbo.table_name rather than a use .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3943823', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/477087/']}
jdg_381921
stackexchange
llm_judgeable_groundtruth_similarity
49856794
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 fancy way to disable cookies untill the user accepts them? Following Problem: I have a webshop which uses quite a lot cookies and in order to be GDPR conform we need to "disable" cookies untill the user has accepted them. I do not want to rewrite the whole shop system and therefore I am searching for a generic solution. My aproach is: unset all set-cookie headers sent by our server (via nginx or php) But there are still some problems: how can I prevent external sites from setting cookies without completely removing them (bing, google, fb, ..) how can I prevent javascript from setting cookies without modifying all javascript sources (is it possible to override the browser functions so you can't set cookies via JS) Now provide the response and nothing else.
If GDPR compliance is your concern, just removing cookies won't be enough. You need to disable any tracking scripts collecting personally identifiable information (PII). I recommend moving all tracking scripts to Google Tag Manger, and using the methods outlined by Simo Ahava. Guide 1 and Guide 2 . His methods don't work great for tracking tags that aren't Google, but with a custom trigger you can stop anything. That being said, if you do just want to remove cookies, this should do it. function deleteCookies() { var theCookies = document.cookie.split(';'); for (var i = 0 ; i < theCookies.length; i++) { document.cookie = theCookies[i].split('=')[0] + '=; path=/; expires=Thu, 01 Jan 1970 00:00:01 GMT;'; }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49856794', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3742743/']}
jdg_381922
stackexchange
llm_judgeable_groundtruth_similarity
56275080
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 HTML snippet which looks like this: <pre>Traceback (most recent call last): File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 69, in execute_job_and_create_log output = self._execute_job_and_create_log() File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 127, in _execute_job_and_create_log return self.execute_job_and_create_log__ftp() File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 133, in execute_job_and_create_log__ftp return self._execute_job_and_create_log__ftp() File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 140, in _execute_job_and_create_log__ftp port=self.job_group.remote.port, session_factory=SessionOnPort) as host: File "/home/foobar_cok_p/lib/python2.7/site-packages/ftputil/host.py", line 72, in __init__ self._session = self._make_session() File "/home/foobar_cok_p/lib/python2.7/site-packages/ftputil/host.py", line 135, in _make_session session = factory(*args, **kwargs) File "/home/foobar_cok_p/lib/python2.7/site-packages/ftputil/error.py", line 151, in __exit__ raise FTPOSError(*exc_value.args, original_exception=exc_value)FTPOSError: [Errno 110] TimeoutDebugging info: ftputil 3.4, Python 2.7.13 (linux2)</pre> Since most users do not care for the details, I would like to hide the traceback and only show the first few characters. The remaining text should only be visible if you expand the text. This should be visible as hyperlink: "Traceback ...." How to do this with? (I can't modify the html, a JavaScript/jquery/CSS solution is needed) Now provide the response and nothing else.
Here is a pure CSS solution. It's a bit clumsy, but jquery not required pre { width: 10em; height: 1em; overflow: hidden; white-space: pre; text-overflow: ellipsis; background-color: lightgreen; border-radius: 8px; border: 2px solid #6c6; transition: width 1s ease;}pre:hover { width: 100%; height: auto; overflow: auto; text-overflow: clip;} <pre>Traceback (most recent call last): File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 69, in execute_job_and_create_log output = self._execute_job_and_create_log() File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 127, in _execute_job_and_create_log return self.execute_job_and_create_log__ftp() File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 133, in execute_job_and_create_log__ftp return self._execute_job_and_create_log__ftp() File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 140, in _execute_job_and_create_log__ftp port=self.job_group.remote.port, session_factory=SessionOnPort) as host: File "/home/foobar_cok_p/lib/python2.7/site-packages/ftputil/host.py", line 72, in __init__ self._session = self._make_session() File "/home/foobar_cok_p/lib/python2.7/site-packages/ftputil/host.py", line 135, in _make_session session = factory(*args, **kwargs) File "/home/foobar_cok_p/lib/python2.7/site-packages/ftputil/error.py", line 151, in __exit__ raise FTPOSError(*exc_value.args, original_exception=exc_value)FTPOSError: [Errno 110] TimeoutDebugging info: ftputil 3.4, Python 2.7.13 (linux2)</pre>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/56275080', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/633961/']}
jdg_381923
stackexchange
llm_judgeable_groundtruth_similarity
7833173
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 required to use/learn R for a new lecture at uni and I’m currently struggling a bit with its syntax. I want to plot (via curve ) a simple function, but I can’t seem to get it working with an inline lambda-like function. I’ve tried the following: > curve( function(x) x^2 )Error in curve(function(x) x^2) : 'expr' did not evaluate to an object of length 'n' When I however store the function in a variable first, it works: > quad <- function(x) x^2> curve( quad ) Is such an inline use not allowed in R? Is there any other way to make this work without defining an extra function? Thanks! Now provide the response and nothing else.
You have to look at the source of curve to appreciate what is happening (just type curve at the prompt and press enter). There you can find how the expression passed is parsed. The only way a function is discovered as being just that, is when only its name is passed along (see the is.name part). If that is not the case, the expression is called for every x . In your case: for every x , the result is a function, which is not a happy thought for plotting... So in short: no you cannot do what you tried, but as @ROLO indicated, you can immediately pass the function body, which will be parsed as an expression (and should contain x ). If this holds multiple statements, just enclose them in curly braces.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7833173', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/216074/']}
jdg_381924
stackexchange
llm_judgeable_groundtruth_similarity
2180320
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The number of terms in a polynomial expansion can be found here But what about in number of terms for polynomial expansion in Galois Field (or characteristic of 2, where addition is addition mod 2 or Xor) Now provide the response and nothing else.
$$h = h\circ\operatorname{id}_X = h\circ (f\circ g) = (h\circ f)\circ g = \operatorname{id}_X\circ g = g$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2180320', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/424168/']}
jdg_381925
stackexchange
llm_judgeable_groundtruth_similarity
14006707
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 data type data Time = Time {hour :: Int, minute :: Int } for which i have defined the instance of Show as being instance Show Time where show (Time hour minute) = (if hour > 10 then (show hour) else ("0" ++ show hour)) ++ ":" ++ (if minute > 10 then (show minute) else ("0" ++ show minute)) which prints out times in a format of 07:09 . Now, there should be symmetry between Show and Read , so after reading (but not truly (i think) understanding) this and this , and reading the documentation , i have come up with the following code: instance Read Time where readsPrec _ input = let hourPart = takeWhile (/= ':') minutePart = tail . dropWhile (/= ':') in (\str -> [(newTime (read (hourPart str) :: Int) (read (minutePart str) :: Int), "")]) input This works, but the "" part makes it seem wrong. So my question ends up being: Can anyone explain to me the correct way to implement Read to parse "07:09" into newTime 7 9 and/or show me? Now provide the response and nothing else.
I'll use isDigit and keep your definition of Time. import Data.Char (isDigit)data Time = Time {hour :: Int, minute :: Int } You used but didn't define newTime , so I wrote one myself so my code compiles! newTime :: Int -> Int -> TimenewTime h m | between 0 23 h && between 0 59 m = Time h m | otherwise = error "newTime: hours must be in range 0-23 and minutes 0-59" where between low high val = low <= val && val <= high Firstly, your show instance is a little wrong because show $ Time 10 10 gives "010:010" instance Show Time where show (Time hour minute) = (if hour > 9 -- oops then (show hour) else ("0" ++ show hour)) ++ ":" ++ (if minute > 9 -- oops then (show minute) else ("0" ++ show minute)) Let's have a look at readsPrec : *Main> :i readsPrecclass Read a where readsPrec :: Int -> ReadS a ... -- Defined in GHC.Read*Main> :i ReadStype ReadS a = String -> [(a, String)] -- Defined in Text.ParserCombinators.ReadP That's a parser - it should return the unmatched remaining string instead of just "" , so you're right that the "" is wrong: *Main> read "03:22" :: Time03:22*Main> read "[23:34,23:12,03:22]" :: [Time]*** Exception: Prelude.read: no parse It can't parse it because you threw away the ,23:12,03:22] in the first read. Let's refactor that a bit to eat the input as we go along: instance Read Time where readsPrec _ input = let (hours,rest1) = span isDigit input hour = read hours :: Int (c:rest2) = rest1 (mins,rest3) = splitAt 2 rest2 minute = read mins :: Int in if c==':' && all isDigit mins && length mins == 2 then -- it looks valid [(newTime hour minute,rest3)] else [] -- don't give any parse if it was invalid Gives for example Main> read "[23:34,23:12,03:22]" :: [Time][23:34,23:12,03:22]*Main> read "34:76" :: Time*** Exception: Prelude.read: no parse It does, however, allow "3:45" and interprets it as "03:45". I'm not sure that's a good idea, so perhaps we could add another test length hours == 2 . I'm going off all this split and span stuff if we're doing it this way, so maybe I'd prefer: instance Read Time where readsPrec _ (h1:h2:':':m1:m2:therest) = let hour = read [h1,h2] :: Int -- lazily doesn't get evaluated unless valid minute = read [m1,m2] :: Int in if all isDigit [h1,h2,m1,m2] then -- it looks valid [(newTime hour minute,therest)] else [] -- don't give any parse if it was invalid readsPrec _ _ = [] -- don't give any parse if it was invalid Which actually seems cleaner and simpler to me. This time it doesn't allow "3:45" : *Main> read "3:40" :: Time*** Exception: Prelude.read: no parse*Main> read "03:40" :: Time03:40*Main> read "[03:40,02:10]" :: [Time][03:40,02:10]
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14006707', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1038219/']}
jdg_381926
stackexchange
llm_judgeable_groundtruth_similarity
39521060
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: First, please note that I ask this question out of curiosity, and I'm aware that using variable names like @@ is probably not a good idea. When using doubles quotes (or qq operator), scalars and arrays are interpolated : $v = 5;say "$v"; # prints: 5$@ = 6;say "$@"; # prints: 6@a = (1,2);say "@a"; # prints: 1 2 Yet, with array names of the form @ + special char like @@ , @! , @, , @% , @; etc, the array isn't interpolated : @; = (1,2);say "@;"; # prints nothingsay @; ; # prints: 1 2 So here is my question : does anyone knows why such arrays aren't interpolated? Is it documented anywhere? I couldn't find any information or documentation about that. There are too many articles/posts on google (or SO) about the basics of interpolation, so maybe the answer was just hidden in one of them, or at the 10th page of results.. If you wonder why I could need variable names like those : The -n (and -p for that matter) flag adds a semicolon ; at the end of the code (I'm not sure it works on every version of perl though). So I can make this program perl -nE 'push@a,1;say"@a"}{say@a' shorter by doing instead perl -nE 'push@;,1;say"@;"}{say@' , because that last ; convert say@ to say@; . Well, actually I can't do that because @; isn't interpolated in double quotes. It won't be useful every day of course, but in some golfing challenges, why not! It can be useful to obfuscate some code. (whether obfuscation is useful or not is another debate!) Now provide the response and nothing else.
Unfortunately I can't tell you why, but this restriction comes from code in toke.c that goes back to perl 5.000 (1994!). My best guess is that it's because Perl doesn't use any built-in array punctuation variables (except for @- and @+ , added in 5.6 (2000)). The code in S_scan_const only interprets @ as the start of an array if the following character is a word character (e.g. @x , @_ , @1 ), or a : (e.g. @::foo ), or a ' (e.g. @'foo (this is the old syntax for :: )), or a { (e.g. @{foo} ), or a $ (e.g. @$foo ), or a + or - (the arrays @+ and @- ), but not in regexes. As you can see, the only punctuation arrays that are supported are @- and @+ , and even then not inside a regex. Initially no punctuation arrays were supported; @- and @+ were special-cased in 2000. (The exception in regex patterns was added to make /[\c@-\c_]/ work; it used to interpolate @- first.) There is a workaround: Because @{ is treated as the start of an array variable, the syntax "@{;}" works (but that doesn't help your golf code because it makes the code longer).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39521060', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4990392/']}
jdg_381927
stackexchange
llm_judgeable_groundtruth_similarity
42853392
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 some way how to monitor free disk space from the Azure Portal? I know that there are all kinds of diagnostics for I/O, memory, network, CPU, .NET, SQL, ASP.NET, IIS, etc. But is there some way to see how much free space there's on a disk attached to the VM? All I found was this third-party solution: http://cloudmonix.com/blog/how-to-monitor-free-disk-space-on-azure-vms/ But there should be some way how to see a basic metric like disk space without needing third-party SW, right? Now provide the response and nothing else.
Update 2019 This is possible today. To monitor free disk space per drive with Azure Monitor do the following: Enable Guest Operating System OS Metrics for the VM . In the Azure Portal select the Virtual Machine. Click Diagnostics Settings (under Monitoring). Click the Performance counters tab. Click the Custom button. In the textbox add the custom metric for the drive you would like. e.g. \LogicalDisk(C:)\% Free Space . Click Add and set the Unit to Percent . Source: Azure Support. To view the logs from the Azure Guest Monitor for Linux: // Virtual Machine free disk space// Show the latest report of free disk space, per instanceInsightsMetrics| where Name == "FreeSpacePercentage"| summarize arg_max(TimeGenerated, *) by Tags// arg_max over TimeGenerated returns the latest record| project TimeGenerated, Computer, Val, Tags This results in the following alert query (you need AggregatedValue and bin(TimeGenerated, <some time>) in the query): InsightsMetrics| where Name == "FreeSpacePercentage"| summarize AggregatedValue=arg_min(Val, *) by bin(TimeGenerated, 5min), Tags To view the same for any generic diagnostics endpoint (thanks @gabe): After turning this on, i was able to view the free disk space with a log query: // Virtual Machine free disk space // Show the latest report of free disk space, per instance Perf | where ObjectName == "LogicalDisk" or // the object name used in Windows records ObjectName == "Logical Disk" // the object name used in Linux records | where CounterName == "Free Megabytes" | summarize arg_max(TimeGenerated, *) by InstanceName // arg_max over TimeGenerated returns the latest record | project TimeGenerated, InstanceName, CounterValue
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42853392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/108374/']}
jdg_381928
stackexchange
llm_judgeable_groundtruth_similarity
8640376
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: $data = array( 'validation' => '1', 'username' => 'peter'), 'password' => 'bigpass' ); I have a JSON array like this.On the receiving end I want to strip out username and then sent it on in JSON format again - eg: only containing validation and passwd. Is there a way to strip out a JSON element without decoding it?Or do I have to decode it and convert it into an array, then remove the required element and then re-encode it again? thx Now provide the response and nothing else.
Here is what you wrote: # from here code executes in main process and all child processes# every process makes all these importsfrom multiprocessing import Process, Manager# every process creates own 'manager' and 'd'manager = Manager() # BTW, Manager is also child process, and # in its initialization it creates new Manager, and new Manager# creates new and new and new# Did you checked how many python processes were in your system? - a lot!d = manager.dict()def f(): # 'd' - is that 'd', that is defined in globals in this, current process d[1].append(4) print dif __name__ == '__main__':# from here code executes ONLY in main process d[1] = [] p = Process(target=f) p.start() p.join() Here is what you should have written: from multiprocessing import Process, Managerdef f(d): d[1] = d[1] + [4] print dif __name__ == '__main__': manager = Manager() # create only 1 mgr d = manager.dict() # create only 1 dict d[1] = [] p = Process(target=f,args=(d,)) # say to 'f', in which 'd' it should append p.start() p.join()
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8640376', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/880413/']}
jdg_381929
stackexchange
llm_judgeable_groundtruth_similarity
39333639
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I know how to modify and create code snippets and I know how to modify shortcut keys, but how does one bring those 2 together? Now provide the response and nothing else.
Note that the line below will open a list of snippets defined for the language you are currently using (and you don't want that) "args": { "snippet": "'$TM_SELECTED_TEXT'" } Whereas with the below line the snippet given as argument will be executed right away "args": { "name": "your_snippets_name" } Here's how I defined a snippet for HTML where I wanted to select a text and when pressing CTRL + B the text to become enclosed in <strong></strong> tags: "make_strong": { "prefix": "strong", "body": [ "<strong>$TM_SELECTED_TEXT${1:}</strong>" ], "description": "Encloses selected text in <strong></strong> tags"} Note the ${1:} above - what this does is that it places the cursor there. This enables you to press CTRL + B at cursor and then have the cursor placed inside the <strong></strong> tags. When selecting a string and pressing CTRL + B , the string will enclosed in <strong> tags and the cursor will be placed before the closing </strong> tag. Pressing TAB at this point, will put your cursor after the closing </strong> tag. And added in my keybindings.json the following: { "key": "ctrl+b", "command": "editor.action.insertSnippet", "args": { "name": "make_strong" }} UPDATE JUNE 2nd, 2021 Since this is getting lots of views, I am posting some of the snippets I use, maybe it will be useful to someone { "key": "ctrl+alt+u", "command": "editor.action.transformToUppercase"},{ "key": "ctrl+alt+l", "command": "editor.action.transformToLowercase"},{ "key": "ctrl+b", "command": "editor.action.insertSnippet", "args": { "name": "insert_strong" }},{ "key": "ctrl+i", "command": "editor.action.insertSnippet", "args": { "name": "insert_italic" }},{ "key": "ctrl+u", "command": "editor.action.insertSnippet", "args": { "name": "insert_underline" }},{ "key": "ctrl+alt+p", "command": "editor.action.insertSnippet", "args": { "name": "insert_paragraph" }},{ "key": "ctrl+shift+space", "command": "editor.action.insertSnippet", "args": { "name": "insert_nbsp" }},{ "key": "ctrl+enter", "command": "editor.action.insertSnippet", "args": { "name": "insert_br" }},
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39333639', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1864190/']}
jdg_381930
stackexchange
llm_judgeable_groundtruth_similarity
25649097
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 test a function in a module. This function ( I will refer to it as function_a ) calls a different function ( function_b ) within the same file. So this module looks like this: //the module filemodule.exports.function_a = function (){ //does stuff function_b()};module.exports.function_b = function_b = function () { //more stuff} I need to test function_a with a specific result from function_b. I would like to override function_b from my test file, then call function_a from my test file, resulting in function_a calling this override function instead of function_b. Just a note, I have tried and succeeded in overriding functions from separate modules, like this question, but that is not what I am interested in. I have tried the code below, and as far as I know, doesn't work. It does illustrates what I am going for, though. //test filethat_module = require("that module")that_module.function_b = function () { ...override ... }that_module.function_a() //now uses the override function Is there a correct way to do this? Now provide the response and nothing else.
From outside a module's code, you can only modify that module's exports object. You can't "reach into" the module and change the value of function_b within the module code. However, you can (and did, in your final example) change the value of exports.function_b . If you change function_a to call exports.function_b instead of function_b , your external change to the module will happen as expected.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25649097', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1541105/']}
jdg_381931
stackexchange
llm_judgeable_groundtruth_similarity
39264003
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: HTML CODE <tbody> <tr> <td>0</td> <td>204093D-P12</td> <td>80443</td> <td>Name</td> <td><span class="label label-success">Updated</span></td> <td><button class="btn btn-xs btn-flat" data-toggle="modal" data-id="204093D-P132" data-target="#myModal" type="button" title="Add" onClick="ShowModal()"><i class="fa fa-plus" aria-hidden="true"></i></button> | <button class="btn btn-xs btn-flat" data-toggle="modal" data-id="204093D-P132" data-target="#myModal_edit" type="button" title="Edit" onClick="ShowEdit()"><i class="fa fa-pencil-square-o" aria-hidden="true" ></i></button>| <button class="btn btn-xs btn-flat" data-toggle="modal" data-id="204093D-P132" data-target="#myModal_details" type="button" title="Details" onClick="ShowDetails()"><i class="fa fa-list-ul" aria-hidden="true"></i></button></td> </tr><tr> <td>1</td> <td>216619D-P18</td> <td>16009</td> <td>Name</td> <td><span class="label label-success">Updated</span></td> <td><button class="btn btn-xs btn-flat" data-toggle="modal" data-id="216619D-P918" data-target="#myModal" type="button" title="Add" onClick="ShowModal()"><i class="fa fa-plus" aria-hidden="true"></i></button> | <button class="btn btn-xs btn-flat" data-toggle="modal" data-id="216619D-P918" data-target="#myModal_edit" type="button" title="Edit" onClick="ShowEdit()"><i class="fa fa-pencil-square-o" aria-hidden="true" ></i></button>| <button class="btn btn-xs btn-flat" data-toggle="modal" data-id="216619D-P918" data-target="#myModal_details" type="button" title="Details" onClick="ShowDetails()"><i class="fa fa-list-ul" aria-hidden="true"></i></button></td> </tr><tr> <td>2</td> <td>21663P0012</td> <td>13116</td> <td>Name</td> <td><span class="label label-success">Updated</span></td> <td><button class="btn btn-xs btn-flat" data-toggle="modal" data-id="216693P0012" data-target="#myModal" type="button" title="Add" onClick="ShowModal()"><i class="fa fa-plus" aria-hidden="true"></i></button> | <button class="btn btn-xs btn-flat" data-toggle="modal" data-id="216693P0012" data-target="#myModal_edit" type="button" title="Edit" onClick="ShowEdit()"><i class="fa fa-pencil-square-o" aria-hidden="true" ></i></button>| <button class="btn btn-xs btn-flat" data-toggle="modal" data-id="216693P0012" data-target="#myModal_details" type="button" title="Details" onClick="ShowDetails()"><i class="fa fa-list-ul" aria-hidden="true"></i></button></td> </tr><tr> <td>3</td> <td>217496D-P078</td> <td>16032</td> <td>Name</td> <td><span class="label label-success">Updated</span></td> <td><button class="btn btn-xs btn-flat" data-toggle="modal" data-id="217496D-P078" data-target="#myModal" type="button" title="Add" onClick="ShowModal()"><i class="fa fa-plus" aria-hidden="true"></i></button> | <button class="btn btn-xs btn-flat" data-toggle="modal" data-id="217496D-P078" data-target="#myModal_edit" type="button" title="Edit" onClick="ShowEdit()"><i class="fa fa-pencil-square-o" aria-hidden="true" ></i></button>| <button class="btn btn-xs btn-flat" data-toggle="modal" data-id="217496D-P078" data-target="#myModal_details" type="button" title="Details" onClick="ShowDetails()"><i class="fa fa-list-ul" aria-hidden="true"></i></button></td> </tr></tbody> And i have to tried to get data-id attribute value from using Jquery in following way function ShowModal(){ alert($(this).attr("data-id"));} but return undefined how to get data-id value from jquery? and i have an another doubt data-id value can hold numeric value or string value? Now provide the response and nothing else.
You need to pass the current element context in inline click handler like <button onClick="ShowModal(this)" data-id="217496D-P078"></button> Then use the passed element reference to get the data-id . You can also use HTMLElement.dataset property like elem.dataset.id function ShowModal(elem){ var dataId = $(elem).data("id"); alert(dataId);} Additionally, I would recommend you use jquery to bind event handler's instead of ugly inline click handler.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39264003', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6070497/']}
jdg_381932
stackexchange
llm_judgeable_groundtruth_similarity
26967509
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 python 3.3.3. I am doing the tutorial from tutorialspoint.com. I am unable to understand what this error is. Here is my code: fo = open("foo.txt", "w")print ("Name of the file: ", fo.name)# Assuming file has following 5 lines# This is 1st line# This is 2nd line# This is 3rd line# This is 4th line# This is 5th lineseq = ["This is 6th line\n", "This is 7th line"]# Write sequence of lines at the end of the file.fo.seek(0, 2)line = fo.writelines( seq )# Now read complete file from beginning.fo.seek(0,0)for index in range(7): # line = fo.next() print ("Line No %d - %s" % (index, line)+"\n")# Close opend filefo.close() Error: Name of the file: foo.txtTraceback (most recent call last): File "C:/Users/DELL/Desktop/python/s/fyp/filewrite.py", line 19, in <module> line = fo.next()AttributeError: '_io.TextIOWrapper' object has no attribute 'next' Now provide the response and nothing else.
There's two reasons you're running into issues here. The first is that you've created fo in write-only mode. You need a file object that can read and write. You can also use the with keyword to automatically destruct a file object after you're done with it, rather than having to worry about closing it manually: # the plus sign means "and write also"with open("foo.txt", "r+") as fo: # do write operations here # do read operations here The second is that (like the error you've pasted very strongly suggests) the file object fo , a text file object, doesn't have a next method. You're using an tutorial written for Python 2.x, but you're using Python 3.x. This isn't going to go well for you. (I believe next was/maybe is valid in Python 2.x, but it is not in 3.x.) Rather, what's most analogous to next in Python 3.x is readline , like so: for index in range(7): line = fo.readline() print("Line No %d - %s % (index, line) + "\n") Note that this will only work if the file has at least 7 lines. Otherwise, you'll encounter an exception. A safer, and simpler way of iterating through a text file is with a for loop: index = 0for line in file: print("Line No %d - %s % (index, line) + "\n") index += 1 Or, if you wanted to get a little more pythonic, you could use the enumerate function: for index, line in enumerate(file): print("Line No %d - %s % (index, line) + "\n")
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/26967509', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_381933
stackexchange
llm_judgeable_groundtruth_similarity
933993
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What is a use case for using a dynamic proxy? How do they relate to bytecode generation and reflection? Any recommended reading? Now provide the response and nothing else.
I highly recommend this resource . First of all, you must understand what the proxy pattern use case. Remember that the main intent of a proxy is to control access tothe target object, rather than to enhance the functionality of thetarget object. The access control includes synchronization, authentication, remote access (RPC), lazy instantiation (Hibernate, Mybatis), AOP (transaction). In contrast with static proxy, the dynamic proxy generates bytecode which requires Java reflection at runtime. With the dynamic approach you don't need to create the proxy class, which can lead to more convenience.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/933993', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/59561/']}
jdg_381934
stackexchange
llm_judgeable_groundtruth_similarity
2426794
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 $q : X \to Y$ be a quotient map, $X$ is a locally connected space. Show that $Y$ is also locally connected. I will be thankful if some one could present a proof of this theorem, because I couldn't find one. Thank you very much. Now provide the response and nothing else.
I'll use the following characterisation of local connectedness: A space $X$ is locally connected iff for every open set $O$ of $X$, all connected components of $O$ are open in $X$. This is a fact that is routinely taught about local connectedness and proofs can be found on this site. Let's show that if $f: X \to Y$ is onto and quotient, and $X$ is locally connected, then $Y$ is locally connected. Let $O$ be an open neighbourhood of a point $y \in Y$, and let $C_y$be the component of $y$ in $O$. We want to show that $C_y$ is open, and sowe need to show that $C= f^{-1}[C_y]$ is open: because $f$ is quotient we can thenconclude that $C_y$ is open. So let $x$ be any point in $C$. Then $f(x) \in C_y \subseteq O$, hence $x \in f^{-1}[O]$, which is open by continuity of $f$. So (using local connectedness of $X$) this $x$ has a connected neighbourhood$U_x$ such that $U_x \subseteq f^{-1}[O]$. The set $f[U_x]$ is then also connected (as a continuous image of a connected set)and intersects $C_y$ in $f(x)$. So $C_y \cup f[U_x]$ is connected (and contains $y$) and is a subset of $O$, and as $C_y$ is a component of $O$ (so maximally connected inside $O$), and so $C_y \cup f[U_x] = C_y$ which implies that $f[U_x] \subseteq C_y$. But recapping, the last equation just says that $U_x \subseteq f^{-1}[C_y] = C$ and so $x$ is an interior point of $C$. So all points of $C$ are interior points and so $C$ is open.So, as we saw, $f$ being quotient then tells us $C_y$ is open, and by the characterisation, $Y$ is locally connected.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2426794', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/459484/']}
jdg_381935
stackexchange
llm_judgeable_groundtruth_similarity
38008354
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 form where its fields need to be reset after successful submission. The entire flow happens through ajax and php . Here is the code: HTML <form role="form" class="contact-form" id="contact-fm" method="post"> <div class="form-group"> <div class="controls"> <input type="text" placeholder="Name" class="requiredField" name="name" required> </div> </div> <div class="form-group"> <div class="controls"> <input type="email" class="email" class="requiredField" placeholder="Email" name="email" required> </div> </div> <div class="form-group"> <div class="controls"> <input type="text" class="requiredField" placeholder="Subject" name="subject" required> </div> </div> <div class="form-group"> <div class="controls"> <textarea rows="7" placeholder="Message" name="message" class="requiredField" required></textarea> </div> </div> <button type="submit" id="submit" class="btn-system btn-large">Send</button> <div id="success" style="color:#34495e;"></div> </form> AJAX $(function() { $("input,textarea").jqBootstrapValidation({ preventSubmit: true, submitError: function($form, event, errors) { // additional error messages or events }, submitSuccess: function($form, event) { event.preventDefault(); // prevent default submit behaviour // get values from FORM var name = $("input#name").val(); var email = $("input#email").val(); var sub = $("input#subject").val(); var message = $("textarea#message").val(); $.ajax({ url: "php/send.php", type: "POST", data: { name: name, email: email, sub: subject, message: message }, cache: false, }) document.getElementById('contact-fm').reset(); }, });}); PHP <?php $name = $_POST['name']; $email = $_POST['email']; $message = $_POST['message']; $subject = $_POST['subject']; $to = '[email protected]'; if (filter_var($email, FILTER_VALIDATE_EMAIL)) { // this line checks that we have a valid email address $mailSubject = "Contact request from " .$name; $txt = "name : ".$name.".\n\nSubject : ".$subject.".\n\nMail id : ".$email."\n\nMessage : ".$message; $headers = "From: ".$email ; mail($to,$mailSubject,$txt,$headers); $data = array(); $data['status'] = 'success'; //echo json_encode($data); echo "<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js'></script>"; echo "<p id='text'>Your email was sent! One of our team members would contact you shortly!</p>"; // success message echo "<script type='text/javascript'>"; echo "$(function(){"; echo "$('#text').fadeOut(5000);"; echo "});"; echo "</script>"; } else{ echo "<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js'></script>"; echo "<p id='textOne'>Mail was not sent, make sure that all fields are filled in!</p>"; // success message echo "<script type='text/javascript'>"; echo "$(function(){"; echo "$('#textOne').fadeOut(5000);"; echo "});"; echo "</script>"; }?> When I use document.getElementById('contact-fm').reset(); , form doesn't get reset. How can I make it reset? Now provide the response and nothing else.
TL;DR For this question there are two kinds of Observables - finite value and infinite value. http Observables produce finite (1) values and something like a DOM event listener Observable produces infinite values. If you manually call subscribe (not using async pipe), then unsubscribe from infinite Observables. Don't worry about finite ones, RxJs will take care of them. Sources: I tracked down an answer from Rob Wormald in Angular's Gitter here . He states (I reorganized for clarity and emphasis is mine): if its a single-value-sequence (like an http request)the manual cleanup is unnecessary (assuming you subscribe in the controller manually) i should say "if its a sequence that completes " (of which single value sequences, a la http, are one) if its an infinite sequence , you should unsubscribe which the async pipe does for you Also he mentions in this YouTube video on Observables that "they clean up after themselves..." in the context of Observables that complete (like Promises, which always complete because they are always producing one value and ending - we never worried about unsubscribing from Promises to make sure they clean up XHR event listeners, right?) Also in the Rangle guide to Angular 2 it reads In most cases we will not need to explicitly call the unsubscribe method unless we want to cancel early or our Observable has a longer lifespan than our subscription. The default behavior of Observable operators is to dispose of the subscription as soon as .complete() or .error() messages are published. Keep in mind that RxJS was designed to be used in a "fire and forget" fashion most of the time. When does the phrase "our Observable has a longer lifespan than our subscription" apply? It applies when a subscription is created inside a component which is destroyed before (or not 'long' before) the Observable completes. I read this as meaning if we subscribe to an http request or an Observable that emits 10 values and our component is destroyed before that http request returns or the 10 values have been emitted, we are still OK! When the request does return or the 10th value is finally emitted the Observable will complete and all resources will be cleaned up. If we look at this example from the same Rangle guide we can see that the subscription to route.params does require an unsubscribe() because we don't know when those params will stop changing (emitting new values). The component could be destroyed by navigating away in which case the route params will likely still be changing (they could technically change until the app ends) and the resources allocated in subscription would still be allocated because there hasn't been a completion . In this video from NgEurope Rob Wormald also says you do not need to unsubscribe from Router Observables. He also mentions the http service and ActivatedRoute.params in this video from November 2016. The Angular tutorial, the Routing chapter now states the following: The Router manages the observables it provides and localizes the subscriptions. The subscriptions are cleaned up when the component is destroyed, protecting against memory leaks, so we don't need to unsubscribe from the route params Observable . Here's a discussion on the GitHub Issues for the Angular docs regarding Router Observables where Ward Bell mentions that clarification for all of this is in the works. I spoke with Ward Bell about this question at NGConf (I even showed him this answer which he said was correct) but he told me the docs team for Angular had a solution to this question that is unpublished (though they are working on getting it approved). He also told me I could update my SO answer with the forthcoming official recommendation. The solution we should all use going forward is to add a private ngUnsubscribe = new Subject<void>(); field to all components that have .subscribe() calls to Observables within their class code. We then call this.ngUnsubscribe.next(); this.ngUnsubscribe.complete(); in our ngOnDestroy() methods. The secret sauce (as noted already by @metamaker ) is to call takeUntil(this.ngUnsubscribe) before each of our .subscribe() calls which will guarantee all subscriptions will be cleaned up when the component is destroyed. Example: import { Component, OnDestroy, OnInit } from '@angular/core';// RxJs 6.x+ import pathsimport { filter, startWith, takeUntil } from 'rxjs/operators';import { Subject } from 'rxjs';import { BookService } from '../books.service';@Component({ selector: 'app-books', templateUrl: './books.component.html'})export class BooksComponent implements OnDestroy, OnInit { private ngUnsubscribe = new Subject<void>(); constructor(private booksService: BookService) { } ngOnInit() { this.booksService.getBooks() .pipe( startWith([]), filter(books => books.length > 0), takeUntil(this.ngUnsubscribe) ) .subscribe(books => console.log(books)); this.booksService.getArchivedBooks() .pipe(takeUntil(this.ngUnsubscribe)) .subscribe(archivedBooks => console.log(archivedBooks)); } ngOnDestroy() { this.ngUnsubscribe.next(); this.ngUnsubscribe.complete(); }} Note: It's important to add the takeUntil operator as the last one to prevent leaks with intermediate Observables in the operator chain. More recently, in an episode of Adventures in Angular Ben Lesh and Ward Bell discuss the issues around how/when to unsubscribe in a component. The discussion starts at about 1:05:30. Ward mentions "right now there's an awful takeUntil dance that takes a lot of machinery" and Shai Reznik mentions "Angular handles some of the subscriptions like http and routing" . In response Ben mentions that there are discussions right now to allow Observables to hook into the Angular component lifecycle events and Ward suggests an Observable of lifecycle events that a component could subscribe to as a way of knowing when to complete Observables maintained as component internal state. That said, we mostly need solutions now so here are some other resources. A recommendation for the takeUntil() pattern from RxJs core team member Nicholas Jamieson and a TSLint rule to help enforce it: https://ncjamieson.com/avoiding-takeuntil-leaks/ Lightweight npm package that exposes an Observable operator that takes a component instance ( this ) as a parameter and automatically unsubscribes during ngOnDestroy : https://github.com/NetanelBasal/ngx-take-until-destroy Another variation of the above with slightly better ergonomics if you are not doing AOT builds (but we should all be doing AOT now): https://github.com/smnbbrv/ngx-rx-collector Custom directive *ngSubscribe that works like async pipe but creates an embedded view in your template so you can refer to the 'unwrapped' value throughout your template: https://netbasal.com/diy-subscription-handling-directive-in-angular-c8f6e762697f I mention in a comment to Nicholas' blog that over-use of takeUntil() could be a sign that your component is trying to do too much and that separating your existing components into Feature and Presentational components should be considered. You can then | async the Observable from the Feature component into an Input of the Presentational component, which means no subscriptions are necessary anywhere. Read more about this approach here .
{}
{'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/38008354', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4185813/']}
jdg_381936
stackexchange
llm_judgeable_groundtruth_similarity
2225503
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I was writing an instructive example for a colleague to show him why testing floats for equality is often a bad idea. The example I went with was adding .1 ten times, and comparing against 1.0 (the one I was shown in my introductory numerical class). I was surprised to find that the two results were equal ( code + output ). float @float = 0.0f;for(int @int = 0; @int < 10; @int += 1){ @float += 0.1f;}Console.WriteLine(@float == 1.0f); Some investigation showed that this result could not be relied upon (much like float equality). The one I found most surprising was that adding code after the other code could change the result of the calculation ( code + output ). Note that this example has exactly the same code and IL, with one more line of C# appended. float @float = 0.0f;for(int @int = 0; @int < 10; @int += 1){ @float += 0.1f;}Console.WriteLine(@float == 1.0f);Console.WriteLine(@float.ToString("G9")); I know I'm not supposed to use equality on floats and thus shouldn't care too much about this, but I found it to be quite surprising, as have about everyone I've shown this to. Doing stuff after you've performed a calculation changes the value of the preceding calculation? I don't think that's the model of computation people usually have in their minds. I'm not totally stumped, it seems safe to assume that there's some kind of optimization occurring in the "equal" case that changes the result of the calculation (building in debug mode prevents the "equal" case). Apparently, the optimization is abandoned when the CLR finds that it will later need to box the float. I've searched a bit but couldn't find a reason for this behavior. Can anyone clue me in? Now provide the response and nothing else.
This is a side effect of the way the JIT optimizer works. It does more work if there is less code to generate. The loop in your original snippet gets compiled to this: @float += 0.1f;0000000f fld dword ptr ds:[0025156Ch] ; push(intermediate), st0 = 0.100000015 faddp st(1),st ; st0 = st0 + st1 for (int @int = 0; @int < 10; @int += 1) {00000017 inc eax 00000018 cmp eax,0Ah 0000001b jl 0000000F When you add the extra Console.WriteLine() statement, it compiles it to this: @float += 0.1f;00000011 fld dword ptr ds:[00961594h] ; st0 = 0.100000017 fadd dword ptr [ebp-8] ; st0 = st0 + @float0000001a fstp dword ptr [ebp-8] ; @float = st0 for (int @int = 0; @int < 10; @int += 1) {0000001d inc eax 0000001e cmp eax,0Ah 00000021 jl 00000011 Note the difference at address 15 vs address 17+1a, the first loop keeps the intermediate result in the FPU. The second loop stores it back to the @float local variable. While it stays inside the FPU, the result is calculated with full precision. Storing it back however truncates the intermediate result back to a float, losing lots of bits of precision in the process. While unpleasant, I don't believe this is a bug. The x64 JIT compiler behaves differently yet. You can make your case at connect.microsoft.com
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2225503', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/187296/']}
jdg_381937
stackexchange
llm_judgeable_groundtruth_similarity
298004
Below is a question asked on the forum meta.stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Before dismissing this as a "spurious interpretation" , please consider that these license restrictions are the same ones that protect our names and technical content from being used on sites that promote white supremacy (fancy some KKK pictures slotted between answers, anyone? Or maybe used to indicate "accepted answer" or used for upvote and downvote buttons or user flair?), flag burning, protests at military funerals, or whatever offends you, if having five black-robed officials assume for themselves the roles of executive, legislature, and judiciary doesn't 1 . Ok, I get that Stack Exchange is a private company, and stackoverflow.com is your property, and you can use it to spread your message. In an extreme case, you could (temporarily I would hope) replace the entire site with a page celebrating the new "rights" of founder Joel. The community would surely be unhappy with losing access to this great resource, but it would be within your rights. What's problematic, however, is using Subscriber Content and Subscriber profiles to promote your cause. You and I and every other subscriber have entered into a legal agreement which grants you certain rights to use content. That agreement uses the following language to incorporate a license by reference, which we commonly know as "CC BY-SA 3.0": You agree that all Subscriber Content that You contribute to the Network is perpetually and irrevocably licensed to Stack Exchange under the Creative Commons Attribution Share Alike license. That license has multiple provisions which protect the author of content by ensuring that they receive credit for their work while protecting their personal brand against abuse. Here's the wording (emphasis mine): Restrictions. The license granted in Section 3 above is expressly made subject to and limited by the following restrictions: c. If You Distribute, or Publicly Perform the Work or any Adaptations or Collections , You must, unless a request has been made pursuant to Section 4(a), keep intact all copyright notices for the Work and provide, reasonable to the medium or means You are utilizing: (i) the name of the Original Author (or pseudonym, if applicable) if supplied, and/or if the Original Author and/or Licensor designate another party or parties (e.g., a sponsor institute, publishing entity, journal) for attribution ("Attribution Parties") in Licensor's copyright notice, terms of service or by other reasonable means, the name of such party or parties; (ii) the title of the Work if supplied; (iii) to the extent reasonably practicable, the URI, if any, that Licensor specifies to be associated with the Work, unless such URI does not refer to the copyright notice or licensing information for the Work; and (iv) , consistent with Ssection 3(b), in the case of an Adaptation, a credit identifying the use of the Work in the Adaptation (e.g., "French translation of the Work by Original Author," or "Screenplay based on original Work by Original Author"). The credit required by this Section 4(c) may be implemented in any reasonable manner; provided, however, that in the case of a Adaptation or Collection, at a minimum such credit will appear, if a credit for all contributing authors of the Adaptation or Collection appears, then as part of these credits and in a manner at least as prominent as the credits for the other contributing authors. For the avoidance of doubt, You may only use the credit required by this Section for the purpose of attribution in the manner set out above and, by exercising Your rights under this License, You may not implicitly or explicitly assert or imply any connection with, sponsorship or endorsement by the Original Author, Licensor and/or Attribution Parties, as appropriate, of You or Your use of the Work, without the separate, express prior written permission of the Original Author, Licensor and/or Attribution Parties. d. Except as otherwise agreed in writing by the Licensor or as may be otherwise permitted by applicable law, if You Reproduce, Distribute or Publicly Perform the Work either by itself or as part of any Adaptations or Collections, You must not distort, mutilate, modify or take other derogatory action in relation to the Work which would be prejudicial to the Original Author's honor or reputation. Licensor agrees that in those jurisdictions (e.g. Japan), in which any exercise of the right granted in Section 3(b) of this License (the right to make Adaptations) would be deemed to be a distortion, mutilation, modification or other derogatory action prejudicial to the Original Author's honor and reputation, the Licensor will waive or not assert, as appropriate, this Section, to the fullest extent permitted by the applicable national law, to enable You to reasonably exercise Your right under Section 3(b) of this License (right to make Adaptations) but not otherwise. These sections clearly apply to Collections, and therefore to stackoverflow.com. It is indisputable that placing the logo and mouseover text on user profile pages creates a "connection with" the user. It is also indisputable that written permission has not been obtained from every registered user to create such a connection between their content 2 and the cause which Stack Exchange, Inc. has chosen to publicize/celebrate this weekend. It is disputable (and probably will be disputed endlessly) whether the presence of the logo and mouseover text on the profile imply "sponsorship or endorsement", but we can probably agree that it is possible that a reasonable person might perceive it as so doing. Similarly for whether the usage of the logo on Q&A pages where Subscriber Content appears implies a connection. Most viewers probably agree that including the rainbow logo and mouseover text on Q&A pages "distort" and "modify" the message of the technical content; fewer will consider it to "mutilate" or be a "derogatory action" but these too are not unreasonable. I'm pointing this out on Meta at this time, rather than via the legal contact form, because I have hope that this matter can be amicably resolved. In my estimation, Stack Exchange has simply been a little careless about their responsibilities concerning messages which do not represent the views of contributors, and will quickly cure the violation, without need for closing accounts, takedown notices, or stronger legal actions. My suggestion is that the rainbow logo be immediately removed from user profile pages (all tabs), and that a disclaimer be added to the logo on other pages, in such a fashion that it appears in mouseover text and also when the page is printed, stating that the message represents the viewpoint of Stack Exchange, Inc., but may not reflect the views of individual users. Whether or not you are OK with having your personal brand used to spread this message, you should be very concerned about the fact that the requirement of a written opt-in was bypassed. Alternately, Stack Exchange could take more effective steps to clearly separate their speech from association with subscribers and Subscriber Content. 1 I realize that most people have chosen a side on this issue without considering the balance of power between the three branches of the USA's government, and it's OK if you have. But please realize that this ruling is controversial for many reasons and that throwing out words like "discrimination" or "bigot" do not adequately address those reasons. I personally find that this quote sums up concerns about judicial overreach nicely: "A government big enough to give you everything you want is a government big enough to take from you everything you have." (Gerald Ford) 2 Even if I upload a different avatar image and use a pseudonym, as suggested by Bill Woodger , it will still be my content. Whether the image is a photo of myself or a geometric figure of my creation makes no difference to the verbiage of the CC BY-SA license, although it might be material to other contracts and laws concerning likenesses of individuals. For what it's worth, here is the specific way in which Stack Overflow's action threatens to harm my reputation (previously mentioned here and here ): I consistently support (across the Internet and in real life) an originalist view of Constitutional interpretation. Therefore associating my work with a celebration of a ruling based on dynamic interpretation, paints me as insincere or a hypocrite. Now provide the response and nothing else.
Normally, I try to focus on what's fair, appropriate, etc. to everyone, but this question is really about legal questions, so I'll try to focus on that. Even though I'm not a lawyer, so you should get your own if you really need legal advice. :) The short version: Legally speaking, the CC-SA license does not give contributors any veto power over our name, logo, catchphrases, tee shirt designs, or font choice. The clauses you're quoting don't do what you're suggesting. Here's the first: You may not implicitly or explicitly assert or imply any connection with, sponsorship or endorsement by the Original Author... This means that we can't do things that say, "Ben Endorses...". It would likely cover actions such as us saying "Ben endorses Stack Overflow," or being sneaky bastards, and taking some quote from your post saying, "originalist view of Constitutional interpretation? I love it!" ... and then just excerpting the "I love it! - Ben" and using it in an ad for Stack Overflow, which would imply you endorsed us . But your argument is dependent on the assumption that that just by having anything in our header (a name, logo, and tooltip, say) we've done something to imply you endorse all those things, whatever they happen to say, even when you didn't have an issue with them. Before, it would mean you endorsed us, our name, the font we used, orange, etc. That's... pretty certainly not right, since it literally would mean any website with a header can't use CC-SA without constantly violating it. As to the second clause you cited: You must not distort, mutilate, modify or take other derogatory action in relation to the Work which would be prejudicial to the Original Author's honor or reputation Others in the comments touched on the what's wrong there - it's about mutilating the work . It doesn't assign control over other parts of the site, page, etc. If an edit does things that can be demonstrated convincingly to a judge to harm your reputation, you've got a strong legal case. If we start running taglines on the top of the page saying, "Stack Overflow - the website that kills puppies!" you don't have much of a legal case. Couple more minor legal clarifications: "Reasonable person" has different meanings in different fields of law, but none that I know of allow for the possibility that a reasonable person might think something. They're all related to what a reasonable person is likely to think. As in, "Is it likely that the average reasonable person will think Ben approves of our logo colors, politics, or hairstyle, assuming we depict them all in our wesite header?" CC-SA does not in any case grant one the right to remove their work. It's always been the option to anonymize in certain circumstances. (To be fair, you didn't suggest otherwise in your post, but I saw it touched on in other answers or comments.) One note, in case it helps: We have no position on whether this use of judicial power was constitutionally... anything. Our support was entirely for the result, and it's possible that some day, over a beer, you'd easily convince me that despite my support for the outcome, that the court was the wrong place for it to happen. I'm honestly embarrassed that I lack the background to have an opinion on that. Oh, and one last thing: Ben has taken a legal position (which I disagreed with) and expressed a constitutional opinion (which I've no opinion of). Let's steer clear of making assumptions about his feelings toward any group; his post does not necessarily imply any disrespect for anyone.
{}
{'log_upvote_score': 7, 'links': ['https://meta.stackoverflow.com/questions/298004', 'https://meta.stackoverflow.com', 'https://meta.stackoverflow.com/users/103167/']}
jdg_381938
stackexchange
llm_judgeable_groundtruth_similarity
68074495
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 attended an interview recently and the interviewer asked me number the occurrences of 'A', 'B', 'C' and so on. To put in table and columns - there is a table tab with column as col. The values in col is 'A', 'B', 'C' etc. create table tab226 (col varchar2(3) );insert into tab226 VALUES ('A');insert into tab226 VALUES ('B');insert into tab226 VALUES ('C');insert into tab226 VALUES ('B');insert into tab226 VALUES ('A');insert into tab226 VALUES ('C');insert into tab226 VALUES ('C');insert into tab226 VALUES ('A');insert into tab226 VALUES ('B'); The expected output is : Interviewer told me I can use SQL or PLSQL to achieve it. I thought about it for almost 10 mins but couldn't come up with a plan let alone the solution. Does anyone know if this can be achieved in Oracle SQL or PLSQL? Now provide the response and nothing else.
For arbitrary unsigned integers, x and n , evaluating the modulo expression x % n involves (conceptually, at least), three operations: division, multiplication and subtraction: quotient = x / n;product = quotient * n;modulus = x - product; However, when n is a power of 2 ( n = 2 p ), the modulo can be determined much more rapidly, simply by masking out all but the lower p bits. On most CPUs, addition, subtraction and bit-masking are very 'cheap' (rapid) operations, multiplication is more 'expensive' and division is very expensive – but note that most optimizing compilers will convert division by a compile-time constant into a multiplication (by a different constant) and a bit-shift ( vide infra ). Thus, if we can convert our modulo 255 into a modulo 256, without too much overhead, we can likely speed up the process. We can do just this by noting that x % n is equivalent to (x + x / n) % (n + 1) † . Thus, our conceptual operations are now: division, addition and masking. In the specific case of masking the lower 8 bits, x86/x64-based CPUs (and others?) will likely be able to perform a further optimization, as they can access 8-bit versions of (most) registers. Here's what the clang-cl compiler generates for a naïve modulo 255 function (argument passed in ecx and returned in eax ): unsigned Naive255(unsigned x){ return x % 255;} mov edx, ecx mov eax, 2155905153 ; imul rax, rdx ; Replacing the IDIV with IMUL and SHR shr rax, 39 ; mov edx, eax shl edx, 8 sub eax, edx add eax, ecx And here's the (clearly faster) code generated using the 'trick' described above: unsigned Trick255(unsigned x){ return (x + x / 255) & 0xFF;} mov eax, ecx mov edx, 2155905153 imul rdx, rax shr rdx, 39 add edx, ecx movzx eax, dl ; Faster than an explicit AND mask? Testing this code on a Windows-10 (64-bit) platform (Intel® Core™ i7-8550U CPU) shows that it significantly (but not hugely) out-performs the other algorithms presented in the question. † The answer given by David Eisenstat explains how/why this equivalence is valid.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/68074495', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9839560/']}
jdg_381939
stackexchange
llm_judgeable_groundtruth_similarity
1708835
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm using the SocketServer module for a TCP server.I'm experiencing some issue here with the recv() function, because the incoming packets always have a different size, so if I specify recv(1024) (I tried with a bigger value, and smaller), it gets stuck after 2 or 3 requests because the packet length will be smaller (I think), and then the server gets stuck until a timeout. class Test(SocketServer.BaseRequestHandler):def handle(self): print "From:", self.client_address while True: data = self.request.recv(1024) if not data: break if data[4] == "\x20": self.request.sendall("hello") if data[4] == "\x21": self.request.sendall("bye") else: print "unknow packet" self.request.close() print "Disconnected", self.client_addresslaunch = SocketServer.ThreadingTCPServer(('', int(sys.argv[1])),Test)launch.allow_reuse_address= True;launch.serve_forever() If the client sends multiples requests over the same source port, but the server gets stuck, any help would be very appreciated, thank ! Now provide the response and nothing else.
The answer by Larry Hastings has some great general advice about sockets, but there are a couple of mistakes as it pertains to how the recv(bufsize) method works in the Python socket module. So, to clarify, since this may be confusing to others looking to this for help: The bufsize param for the recv(bufsize) method is not optional. You'll get an error if you call recv() (without the param). The bufferlen in recv(bufsize) is a maximum size. The recv will happily return fewer bytes if there are fewer available. See the documentation for details. Now, if you're receiving data from a client and want to know when you've received all of the data, you're probably going to have to add it to your protocol -- as Larry suggests. See this recipe for strategies for determining end of message. As that recipe points out, for some protocols, the client will simply disconnect when it's done sending data. In those cases, your while True loop should work fine. If the client does not disconnect, you'll need to figure out some way to signal your content length, delimit your messages, or implement a timeout. I'd be happy to try to help further if you could post your exact client code and a description of your test protocol.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1708835', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/207864/']}
jdg_381940