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
|
79087
|
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:
Someone told me that this circuit has "poor gate drive capability": simulate this circuit – Schematic created using CircuitLab What exactly does that mean? I tested it with an LED as a load for M1, and the microcontroller is able to turn it on and off just fine. Under what circumstances is poor drive capability a problem? How do I improve it?
Now provide the response and nothing else.
|
The answer is at the end, but, just in case you are not familiar with the concept of MOS capacitor, I'll do a quick review. MOS Capacitor: The Gate of MOSFET transistor is essentially a capacitor. When you apply any voltage to this capacitor, it responds by accumulating an electrical charge: The charge accumulated on the Gate electrode is useless, but the charge under the electrode forms a conductive channel which allows for a current to flow between Source and Drain terminals: The transistor switches ON when the charge stored in this capacitor becomes appreciable. The Gate voltage at which this happens is called the Threshold Voltage (essentially it is the Gate-to-Body voltage which is relevant here, but let us assume that the Body is defined as zero potential). As you may know, charging a capacitor through resistor takes time (there is always some resistance present, even if the schematic does not contain resistors). This time depends on both capacitor's and resistor's value: Combining all the above statements together we get: Transistor's Gate is a capacitor which should be charged through a resistor in order for transistor to "switch ON" The higher the input capacitance of the Gate, the longer it takes to switch the transistor ON The higher the resistance between the voltage source and the Gate, the longer it takes to switch the transistor ON The higher the externally applied voltage, the shorter it takes to switch the transistor ON. The answer: When people say "poor gate drive capability" they mean that the turn ON and turn OFF times of the transistor in given configuration are too long. "Too long compared to what?" you might ask, and this is the most important question to ask. The required turn ON/OFF times depend on many aspects, which I don't want to get into. Just as an example, think of driving the transistor with a periodic square wave having 50% duty cycle and period of 10ms. You want the transistor to be ON during the high phase and OFF during the low phase of the signal. Now, if the turn ON time of the transistor in a given configuration will be 10ms, it is clear that 5ms of high phase signal will not be enough to turn it on at all. The given configuration has "poor gate drive capability". When you used the transistor to switch on the LED, you did not employ high switching frequencies, right? In this case, the switching time of the transistor wasn't of major importance - you just wanted to see that it does switches on/off eventually. Summary: "Gate drive capability" can't be good or bad in general, but it either good enough for your application or not. Depends on switching times you want to achieve. In order to reduce the switching times you may do the following: Reduce the resistance to the Gate Increase the voltage/current rating of the driving circuitry There is nothing you can do about Gate's capacitance - it is a built in property of the transistor. Hope this helps
|
{}
|
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/79087', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/17608/']}
|
jdg_375741
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18584525
|
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 web application that listens for Server Sent Events. While I was working and testing with multiple windows open, things were not working and I banged my head for several times looking in the wrong direction: eventually, I realized that the problem was concurrent connections. However I was testing a very limited number and even if I am running the test on Apache (I know, I should use node). I then, switched browser and noticed something really interesting: apparently Chrome limits Server Sent Events connections to 4-5, while Opera doesn't. Firefox, on the other hand, after 4-5 simultaneous connections, refuses to load any other page. What is the reason behind this? Does the limit only apply to SSE connections from the same source, or would it be the same if I were to test open them from a different domain? Is there any chance that I am misusing SSE and this is actually blocking the browsers, or this is a known behaviour? Is there any way around it?
Now provide the response and nothing else.
|
The way this works in all browsers are that each domain gets a limited amount of connections and the limits are global for your whole application. That means if you have one connection open for realtime communication you have one less for loading images, CSS and other pages. On top of that you don't get new connections for new tabs or windows, all of them needs to share the same amount of connections. This is very frustrating but there are good reasons for limiting the connections. A few years back, this limit was 2 in all browsers (based on the rules in ( http://www.ietf.org/rfc/rfc2616.txt ) HTTP1.1 spec) but now most browsers use 4-10 connections in general. Mobile browsers on the other hand still needs to limit the amount of connections for battery saving purposes. These tricks are available: Use more host names. By assigning ex. www1.example.com , www2.example.com you get new connections for each host name. This trick works in all browsers. Don't forget to change the cookie domain to include the whole domain ( example.com , not www.example.com ) Use web sockets. Web sockets are not limited by these restrictions and more importantly they are not competing with the rest of your websites content. Reuse the same connection when you open new tabs/windows. If you have gathered all realtime communication logic to an object call Hub you can recall that object on all opened windows like this: window.hub = window.opener ? window.opener.hub || new Hub() 4. or use flash - not quite the best advice these days but it might still be an option if websockets aren't an option.5. Remember to add a few seconds of time between each SSE request to let queued requests to be cleared before starting a new one. Also add a little more waiting time for each second the user is inactive, that way you can concentrate your server resources on those users that are active. Also add a random number of delay to avoid the Thundering Herd Problem Another thing to remember when using a multithreaded and blocking language such as Java or C# you risk using resources in your long polling request that are needed for the rest of your application. For example in C# each request locks the Session object which means that the whole application is unresponsive during the time a SSE request is active. NodeJs is great for these things for many reasons as you have already figured out and if you were using NodeJS you would have used socket.io or engine.io that takes care of all these problems for you by using websockets, flashsockets and XHR-polling and also because it is non blocking and single threaded which means it will consume very little resources on the server when it is waiting for things to send. A C# application consumes one thread per waiting request which takes at least 2MB of memory just for the thread.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/18584525', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/313115/']}
|
jdg_375742
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
335332
|
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I just don't understand why use matrix transpose, instead of matrix inverse, to calculate delta of weight in gradient descent, like described in http://cs231n.github.io/optimization-2/#mat . # forward passW = np.random.randn(5, 10)X = np.random.randn(10, 3)D = W.dot(X)# now suppose we had the gradient on D from above in the circuitdD = np.random.randn(*D.shape) # same shape as DdW = dD.dot(X.T) #.T gives the transpose of the matrixdX = W.T.dot(dD) This is my understanding to calculate weight delta: $$D = WX\\WXX^-1 = DX^-1\\W = DX^-1$$ Could anyone please tell me what wrong with my understanding?
Now provide the response and nothing else.
|
Consider what matrix multiplication is, and observe the pattern of indices carefully: $$D_{ij} = \sum_{k}W_{ik} X_{kj}$$ $$\frac{\partial D_{ij}}{\partial W_{ik}} = X_{kj}$$ For a previously described loss function $L$ , by the chain rule, $$\frac{\partial L}{\partial W_{ik}} = \sum_j \frac{\partial L}{\partial D_{ij}} \frac{\partial D_{ij}}{\partial W_{ik}} = \sum_j \frac{\partial L}{\partial D_{ij}} X_{kj} = \sum_j \frac{\partial L}{\partial D_{ij}} X_{jk}^T$$ Note $\partial D_{i'j}/\partial W_{ik} = 0$ for $i'\ne i$ , so our chain rule sum is over the given $i$ ranging over $j$ . Since we used $X^T$ , the inner index $j$ matches up for convenient matrix multiplication notation, $$\frac{\partial L}{\partial W} = \frac{\partial L}{\partial D} X^T$$ This matrix of partial derivatives $\partial L / \partial W$ can also be implemented as the outer product of vectors : $(\partial L / \partial D) \otimes X$ . If you really understand the chain rule and are careful with your indexing, then you should be able to reason through every step of the gradient calculation.We need to be careful which matrix calculus layout convention we use: here "denominator layout" is used where $\partial L / \partial W$ has the same shape as $W$ and $\partial L / \partial D$ is a column vector.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/335332', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/165057/']}
|
jdg_375743
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7823
|
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to read this chemical formula but I'm a bit confused. I'm hoping that someone could help break this down for me to explain what the various parts mean. Someone purchased epigallocatechin in a purchase request and I found that it's synonymous with the following. (−)- cis -2-(3,4,5-Trihydroxyphenyl)-3,4-dihydro-1(2 H )-benzopyran-3,5,7-triol I believe that the minus up front refers to the way that the polarity changes as light passes through the molecule. What does the 3,4,5 refer to and the 2?
Now provide the response and nothing else.
|
Klaus's answer has all the right explanations but I always find these things hard to follow without pictures, so here are some to clarify. Note that in the pictures below we don't explicitly draw carbons or the hydrogens attached to them (we just mentally add enough hydrogens to make the number of bonds to each carbon equal 4). First what is benzopyran? The two numbers on the first structure tell us where the oxygen appears in the pyran ring and where the saturated carbon (with an extra hydrogen) appears. Both could be in different places. The second picture showns the numbering convention for each atom in the ring so we can keep track of where anything else is attached. The third picture shows what happens if we notionally add extra hydrogens on carbons 3 and 4 to give a fully saturated ring. Now we add an OH (hydroxy) in certain positions: The picture on the right shows how we number the parts of trihydroxy phenyl when it is attached to something else (it will be stuck on the 2-carbon on the benzopyran in the final compound). Finally we have the epigallocatechin: The "cis" indicates that the two hydrogens (mentally fill them in in positions 2 and 3) are on the same side of the benzopyran (the opposite side to the two wedge-like bonds on the OH and phenyl groups). I hope that all makes some sort of sense. Note that none of the above bears any relation to how the molecules are made: this is all notional deconstruction for the purpose of explaining how the molecule is named.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/7823', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/4171/']}
|
jdg_375744
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
30109030
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Why does str(list) returns how we see list on the console? How does str(list) work? (any reference to the CPython code for str(list) )? >>> x = ['abc', 'def', 'ghi']>>> str(x)"['abc', 'def', 'ghi']" To get the original list back from the str(list) I have to: >>> from ast import literal_eval>>> x = ['abc', 'def', 'ghi']>>> str(x)"['abc', 'def', 'ghi']">>> list(str(x))['[', "'", 'a', 'b', 'c', "'", ',', ' ', "'", 'd', 'e', 'f', "'", ',', ' ', "'", 'g', 'h', 'i', "'", ']']>>> literal_eval(str(x))['abc', 'def', 'ghi'] Why doesn't list(str(list)) turns the str(list) back to the original list? Or I could use: >>> eval(str(x))['abc', 'def', 'ghi'] Is literal_eval the same as eval ? Is eval safe to use? How many times can I do the following? Does the code break if it keep on doing str(list(str(list)))) ? E.g. >>> x = 'abc'>>> list(x)['a', 'b', 'c']>>> str(list(x))"['a', 'b', 'c']">>> list(str(list(x)))['[', "'", 'a', "'", ',', ' ', "'", 'b', "'", ',', ' ', "'", 'c', "'", ']']>>> str(list(str(list(x))))'[\'[\', "\'", \'a\', "\'", \',\', \' \', "\'", \'b\', "\'", \',\', \' \', "\'", \'c\', "\'", \']\']'>>> list(str(list(str(list(x)))))['[', "'", '[', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", 'a', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", ',', "'", ',', ' ', "'", ' ', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", 'b', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", ',', "'", ',', ' ', "'", ' ', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", 'c', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", ']', "'", ']']>>> str(list(str(list(str(list(x))))))'[\'[\', "\'", \'[\', "\'", \',\', \' \', \'"\', "\'", \'"\', \',\', \' \', "\'", \'a\', "\'", \',\', \' \', \'"\', "\'", \'"\', \',\', \' \', "\'", \',\', "\'", \',\', \' \', "\'", \' \', "\'", \',\', \' \', \'"\', "\'", \'"\', \',\', \' \', "\'", \'b\', "\'", \',\', \' \', \'"\', "\'", \'"\', \',\', \' \', "\'", \',\', "\'", \',\', \' \', "\'", \' \', "\'", \',\', \' \', \'"\', "\'", \'"\', \',\', \' \', "\'", \'c\', "\'", \',\', \' \', \'"\', "\'", \'"\', \',\', \' \', "\'", \']\', "\'", \']\']'>>> list(str(list(str(list(str(list(x)))))))['[', "'", '[', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", '[', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", ',', "'", ',', ' ', "'", ' ', "'", ',', ' ', "'", '"', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", '"', "'", ',', ' ', "'", ',', "'", ',', ' ', "'", ' ', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", 'a', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", ',', "'", ',', ' ', "'", ' ', "'", ',', ' ', "'", '"', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", '"', "'", ',', ' ', "'", ',', "'", ',', ' ', "'", ' ', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", ',', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", ',', "'", ',', ' ', "'", ' ', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", ' ', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", ',', "'", ',', ' ', "'", ' ', "'", ',', ' ', "'", '"', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", '"', "'", ',', ' ', "'", ',', "'", ',', ' ', "'", ' ', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", 'b', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", ',', "'", ',', ' ', "'", ' ', "'", ',', ' ', "'", '"', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", '"', "'", ',', ' ', "'", ',', "'", ',', ' ', "'", ' ', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", ',', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", ',', "'", ',', ' ', "'", ' ', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", ' ', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", ',', "'", ',', ' ', "'", ' ', "'", ',', ' ', "'", '"', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", '"', "'", ',', ' ', "'", ',', "'", ',', ' ', "'", ' ', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", 'c', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", ',', "'", ',', ' ', "'", ' ', "'", ',', ' ', "'", '"', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", '"', "'", ',', ' ', "'", ',', "'", ',', ' ', "'", ' ', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", ']', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", ']', "'", ']']
Now provide the response and nothing else.
|
Well you have a total of 4 questions, let us go one by one. 1. Why does str(list) returns how we see list on the console? How does str(list) work? What is str() and __str__() ? The str() callable is to return a printable form of the object only! From the docs str(object) does not always attempt to return a string that is acceptable to eval() ; its goal is to return a printable string. The __str__() function in a class is called whenever you call str() on an object. Again from the documentation object.__str__(self) Called by the str() built-in function and by the print statement to compute the “informal” string representation of an object. What is the list callable? The list() callable is to create a list from an iterable passed as an argument. Again from the docs Return a list whose items are the same and in the same order as iterable‘s items Thus, str(list) gives you a printable form and list(str(list)) will iterate over the string. That is list(str(list)) will give you a list of the individual characters of the printable form of the argument passed. A small walk-through between the nested calls, Given list, l = ['a','b'] (Apologies for taking a smaller example than that in your question) . When you call str(l) , it returns a printable form of the list l , that is "['a','b']" . Now you can see clearly that "['a','b']" is a string and is indeed an iterable . Now when you call list on this i.e. list("['a','b']") you get a weird list like ['[', "'", 'a', "'", ',', "'", 'b', "'", ']'] . Why does this happen? This happens because the string iterates over its characters, you can test this by using a dummy string, >>> 'dummy''dummy'>>> list('dummy')['d', 'u', 'm', 'm', 'y'] Thus when you call the list on a string you get a list of character. Note that again here, when you call str() on list('dummy') , you will not get back your original string 'dummy' , so again you will have to use join ! Thus recalling the same function will NOT get you back your original object! So, Calling str() over a list calls the builtin __str__() method of the list? The answer is NO! What happens internally when you call str() on a list? Whenever you call str() on an list object, the steps followed are Call the repr() of each of the list element. Add a fancy [ at the front and another ] at the end of the list. Join all of them with a comma. As you can see from the source code of the list object in cpython on github . Going through the source code of cpython in hg.python , which is more clear, you can see the following three comments. (Thanks to Ashwini for the link on that particular code ) /* Do repr() on each element. Note that this may mutate the list, so must refetch the list size on each iteration. */ line (382)/* Add "[]" decorations to the first and last items. */ line (398)/* Paste them all together with ", " between. */ line (418) These correspond to the points I mentioned above. Now what is repr() ? repr() prints the string representation of all the objects. Again from the documentation Return a string containing a printable representation of an object. and also note this sentence! For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval() , otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. And now your second question here, 2. Why doesn't list(str(list)) turns the str(list) back to the original list? Internally, str(list) actually creates the repr() representation of the list object. So to get back the list after calling str on the list, you actually need to do eval on it and not a list call. Workarounds But we all know that eval is evil , so what is/are the workaround(s)? 1. Using literal_eval The first work-around would be to use ast.literal_eval . That brings us to your 3rd question, 3. Is literal_eval() the same as eval() ? Is eval() safe to use? ast.literal_eval() is safe unlike the eval() function. The docs themselves mention that it is safe -- Safely evaluate an expression node or a string containing a Python literal or container display 2. Using string functions and builtins Another workaround can be done using str.split() >>> x = ['abc', 'def', 'ghi']>>> a = str(x)>>> a[2:-2].split("', '")['abc', 'def', 'ghi'] This is just a simple way to do that for a list of strings. For a list of integers you will need map . >>> x = [1,2,3]>>> a =str(x)>>> list(map(int,a[1:-1].split(', '))) # No need for list call in Py2[1, 2, 3] Thus unlike literal_eval these are simple hacks given that you know the elements of the list. If they are heterogeneous in nature like [1, "a", True] then you will have to loop through the split list and discover the element type and then convert it and append the converted element to a final list. Another place where this fails is when the string itself contains quote characters. As mentioned by nneonneo in a comment The str.split solution is very fragile and will break if the input contains e.g. strings that contain ", " , or tuples, or other lists, ... It is much better to use ast.literal_eval because that will deal with all the subtleties of the syntax. And for your final question, 4. Does the code break if you do str(list(str(list)))) again and again? Not really. The output will grow longer and longer as each time you are creating a list of a str and then again getting the printable version of it. The limitation is your physical machine's limitation only. (which will be soon reached as each step the string length is multiplied by 5.)
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/30109030', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/610569/']}
|
jdg_375745
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18909206
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
HttpServlet is an abstract class with all implemented methods. Why it is abstract? The most common answer I got is, to restrict the instantiation of HttpServlet . But there are other ways of doing it, like a private constructor will restrict the instantiation. I can understand that they are following Template Method design pattern. If some methods are abstract, user will end up implementing all of them, even if he does not need them for his business logic. But if HttpServlet was not abstract, an user can still extend it and override the require methods. At least by the dictionary meaning of the word 'abstract', its does not make any sense to me to have a abstract class with all implemented method. Yes a combination of abstract and concrete methods are ok to have. But if you are making a class abstract why not make those methods abstract which the sub class has to override? or may be do not declare it as abstract at all? Like doGet() or doPost() is this case.
Now provide the response and nothing else.
|
To have any useful behaviour, it is expected that you will have to override the methods. HttpServlet does not have useful functionality on its own. Making its constructors private would limit the ability for subclasses to be created. The design of HttpServlet was probably not ideal -- as on many pages, forms especially, GET and POST logic should proceed at least partly along a common path. The design idea of HttpServlet however was to offer doGet() , doPost() etc implementations answering a 'not supported' error depending on HTTP version. These stubs would be useful to inherit if you needed to return such an answer. In summary, the API/ interface is complete -- but the functionality is definitively not. Thus it is declared as abstract .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18909206', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2790522/']}
|
jdg_375746
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
417701
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Let $p > 2$ be a prime and $q = p^r$ for some $r \in \mathbb{Z}^+$ . I will assume that all roots of unity lie in $\mathbb{C}_p^{\times}$ . Let $\zeta$ a primitive $p$ -th root of unity. Let $Tr : \mathbb{F}_q \to \mathbb{F}_p$ be the trace. Also, denote $\pi$ to be the maximal prime in $\mathbb{Z}_p[\zeta]$ such that $\pi^{p-1} = -p$ . For a multiplicative character $\psi: \mathbb{F}_q \to \mathbb{C}_p^{\times}$ ( $\psi(0) = 0$ ), the Gauss sum for $\psi$ is defined to be \begin{align*}G(\psi) = \sum_{c \in \mathbb{F}_q} \psi(c) \zeta^{Tr_{\mathbb{F}_q/\mathbb{F}_p}(c)}\end{align*} I feel that the following should be true: If $\psi$ is order 2 and $r =1$ then $G(\psi) = \pi^{(p-1)/2}$ or $-i\pi^{(p-1)/2}$ , where $i \in \mathbb{C}_p$ is a solution to $X^2 + 1 = 0$ . My thought is that $\pi^{(p-1)/2}$ is playing the role of $i\sqrt{p}$ in the traditional value for the Gauss sum (where we view everything taking place in $\mathbb{C}$ ). Is this correct? Or is there something more subtle going on that I'm missing?
Now provide the response and nothing else.
|
That $G(\psi,\zeta)^2 = \psi(-1)p$ is pure algebra, so it holds in $\mathbf C$ or $\mathbf C_p$ or any other field not of characteristic $2$ that contains a nontrivial $p$ th root of unity. You could write down a $p$ -adic formula for your quadratic Gauss sum using the Gross–Koblitz formula. First let's normalize the link between your nontrivial $p$ th root of unity and your choice of $\pi$ such that $\pi^{p-1} = -p$ . To each $\pi$ there is a unique nontrivial $p$ th root of unity $\zeta$ such that $\zeta \equiv 1 + \pi \bmod \pi^2$ , where the congruence means $\lvert\zeta - (1 + \pi)\rvert_p \leq \lvert\pi\rvert_p^2$ , or equivalently $\lvert\zeta - (1 + \pi)\rvert_p < \lvert\pi\rvert_p$ since $\mathbf Q_p(\pi) = \mathbf Q_p(\zeta)$ . Write the $\zeta$ fitting that congruence mod $\pi^2$ as $\zeta_{\pi}$ . Every character of $\mathbf F_q^\times$ with values in $\mathbf C_p$ is a power of the Teichmüller character $\omega_q$ (interpret $\mathbf F_q$ as $\mathbf Z_p[\zeta_{q-1}]/(p)$ ). For the Gross–Koblitz formula it is convenient to write characters of $\mathbf F_q^\times$ as powers of $\omega_q^{-1}$ , say as $\omega_q^{-k}$ for $0 \leq k < q-1$ . The quadratic character $\psi$ of $\mathbf F_q^\times$ is $\omega_q^{(q-1)/2} = \omega_q^{-(q-1)/2}$ , so $k = (q-1)/2$ .Let the base $p$ expansion of $k$ be $d_0 + d_1p + \cdots + d_{f-1}p^{f-1}$ . When $k = (q-1)/2 = (p^f-1)/2$ , all of its base $p$ digits are $(p-1)/2$ , so the sum of the base $p$ digits is $f(p-1)/2$ . The Gross–Koblitz formula for the quadratic character $\psi$ says $$-G(\psi,\zeta_\pi) = \pi^{f(p-1)/2}\Gamma_p\left(\frac{(p-1)/2}{q-1}\right)^f, $$ where $\Gamma_p$ is Morita's $p$ -adic Gamma-function. Note the minus sign on the left side: normalizing Gauss sums with an overall minus sign is reasonable for various purposes, like here and in the Hasse–Davenport relation. On the right side of the formula above, $\pi^{f(p-1)/2}$ is a square root of $\pi^{f(p-1)} = (-p)^f = (-1)^fq$ . $\newcommand\sgn{\genfrac(){}{}}$ In the special case $q = p$ (so $f = 1$ ), you're working with the classical quadratic Gauss sum for $\mathbf F_p$ and the Legendre symbol. In this case $$-G\left(\sgn\cdot p,\zeta_\pi\right) = \pi^{(p-1)/2}\Gamma_p\left(\frac{1}{2}\right),$$ where $\pi^{(p-1)/2}$ is a square root of $\pi^{p-1} = -p$ . For $p > 2$ it is known that $\Gamma_p(1/2)^2 = -\sgn{-1}p$ , so if you square the right side above then you get $\pi^{p-1}\Gamma_p(1/2)^2 = -p(-\sgn{-1}p) = \sgn{-1}p p$ , which is the formula for the square of the mod $p$ quadratic Gauss sum that I mentioned at the start of this answer (when $q = p$ ).
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/417701', 'https://mathoverflow.net', 'https://mathoverflow.net/users/171396/']}
|
jdg_375747
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
343640
|
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:
My question: Was it inappropriate to flag for mod? https://stackoverflow.com/questions/42173089/css-is-not-applying-on-the-ajax-response I hammer closed as duplicate User updated question and tags and asked to reopen the now improved question. I clicked reopen but was only allowed to vote due to the changed tags To expedite the reopen, I flagged for moderator to reopen Nothing happened so I suggested user to delete and write another question with the now improved text. He complied. I am now reviewing and am told my flag was declined.
Now provide the response and nothing else.
|
"Double-dipping" the process by flagging and close-voting doesn't have any benefit as far as I know. Both lead to the question being queued up for review, so using either one should suffice. Close-voting is obviously better, as flags ( other than "Spam" or "Rude/Abusive" ) cannot trigger something like automated deletion, as far as I know atleast. Regarding the flagged questions: I would say that your flags were warranted, and should not have been declined. At most, if the moderator handling your flags felt very strong about it, they should've been disputed, but I can see no reason why one would choose to decline them. As I've stated in my comment already, I don't think that edits made by the original poster apply. Going by that understanding those questions are simply unsalvageable. We cannot know what the OP is asking for, atleast it question 1 and 3, and thus flagging those questions is warranted in my opinion. That being said, I think the current flag reasons should be flagged as well. In my opinion most of them are confusing, and really don't do any good. As of now, I'd say that simply flagging a post without giving a reason would be more efficient. The best option, in my opinion, would be new flag reasons. Clear borders, and clear instructions. Short, clear reasoning, the user quickly checks "Does it fit?", and the moderator quickly checks "Does it fit?", and the process is done. That'd be much easier than applying those hella obfuscated reasons, especially considering that every single one , no matter if user, moderator or SE employee, seems to have a slightly different interpretation of the flag reasons. Apparently though that has no priority, as most of the feature requests regarding flags didn't receive any attention (not even status-declined ).
|
{}
|
{'log_upvote_score': 5, 'links': ['https://meta.stackoverflow.com/questions/343640', 'https://meta.stackoverflow.com', 'https://meta.stackoverflow.com/users/295783/']}
|
jdg_375748
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3736370
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
After using WebResponse to export excel then clicking a Link gives Page expired error. Any suggestions ? Thanks.
Now provide the response and nothing else.
|
I was able to get to the contents of an Activity with this call: ViewGroup view = (ViewGroup)getWindow().getDecorView(); You should probably check that getDecorView returns an instanceof ViewGroup for all cases, but with a LinearLayout in the Activity the code above runs fine. To get to the LinearLayout you could then just: LinearLayout content = (LinearLayout)view.getChildAt(0); And if you have a function like this: void logContentView(View parent, String indent) { Log.i("test", indent + parent.getClass().getName()); if (parent instanceof ViewGroup) { ViewGroup group = (ViewGroup)parent; for (int i = 0; i < group.getChildCount(); i++) logContentView(group.getChildAt(i), indent + " "); }} You could iterate through all views and log their class names with the following call inside your Activity: logContentView(getWindow().getDecorView(), "");
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3736370', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/174005/']}
|
jdg_375749
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5101560
|
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 alert view having 2 buttons "OK" and "Cancel" and a textfield.Now i want to disable "OK" button until user enter some text in textfield.How can i do this?thanks in advance
Now provide the response and nothing else.
|
UPDATE 2: For Swift 5.1 <#your alert controller#>.addTextField {(tf) in //... set your tf characteristics i.e .keyboardType here NotificationCenter.default.addObserver(forName: UITextField.textDidChangeNotification, object: tf, queue: OperationQueue.main) { _ in //enable or disable the selected action depending on whether the textField text is empty <#your alert controller#>.actions[0].isEnabled = !tf.text!.isEmpty } } posting this to update the response since ios 5 : - (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView{ UITextField *textField = [alertView textFieldAtIndex:0]; if ([textField.text length] == 0) { return NO; } return YES;} UPDATE :iOS 8 Since Apple have deprecated the UIAlertView in favour of the UIAlertController. There is no longer a delegate call to alertViewShouldEnableFirstOtherButton: So instead you would set the buttons enabled property via the UITextFieldTextDidChangeNotification Add a textView to the alert with (void)addTextFieldWithConfigurationHandler:(void (^)(UITextField *textField))configurationHandler [<#your alert#> addTextFieldWithConfigurationHandler:^(UITextField *textField) {textField.delegate = self;textField.tag = 0; //set a tag to 0 though better to use a #define}]; Then implement the delegate method (void)textFieldDidBeginEditing:(UITextField *)textField - (void)textFieldDidBeginEditing:(UITextField *)textField{//in here we want to listen for the "UITextFieldTextDidChangeNotification"[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldHasText:) name:UITextFieldTextDidChangeNotification object:textField];} When the text in textField changes it will invoke a call to "textFieldHasText:" and pass along a NSNotification* -(void)textFieldHasText:(NSNotification*)notification{//inside the notification is the object property which is the textField//we cast the object to a UITextField*if([[(UITextField*)notification.object text] length] == 0){//The UIAlertController has actions which are its buttons.//You can get all the actions "buttons" from the `actions` array//we have just one so its at index 0[<#your alert#>.actions[0] setEnabled:NO];}else{[<#your alert#>.actions[0] setEnabled:YES];}} Don't forget to remove your observer when done
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5101560', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/520031/']}
|
jdg_375750
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3362926
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I've been thinking about the following category $\mathbb{G}$ . Objects of $\mathbb{G}$ are groups and a morphism from $G$ to $H$ is a set $X$ equipped with commuting left, right actions of $G, H$ ; equivalently, a left action of $G \oplus H^{op}$ on $X$ . The identity morphism on $G$ is $G$ itself, with the actions just given by left and right multiplication. If $X \in \mathbb{G}(G,H)$ and $Y \in \mathbb{G}(H,K)$ , the composition $X\circ Y$ is the cartesian product $X \times Y$ , modulo the relation $(x\cdot h, y) \sim (x,h\cdot y)$ . This admits a well-defined $G \oplus K^{op}$ action. Is this a standard category to consider? It is similar to the category of rings, with bimodules as morphisms. I am interested in whether this category has a coproduct, and if it is different from the coproduct in the standard category of groups (free product).
Now provide the response and nothing else.
|
This category does not have coproducts. The simplest example is that it has no initial object: an initial object would be a group $G$ such that for any group $H$ there is exactly one $(G,H)$ -bimodule (up to isomorphism), but this is impossible since there is always a proper class of different $(G,H)$ -bimodules. (Here by $(G,H)$ -bimodule of course I mean set with commuting left $G$ -action and right $H$ -action.) Or, consider a coproduct of two copies of the trivial group. That would be a group $G$ together with two right $G$ -modules $A$ and $B$ such that for any group $H$ with two right $H$ -modules $C$ and $D$ , there is a unique $(G,H)$ -bimodule $X$ such that $A\circ X\cong C$ and $B\circ X\cong D$ . But, since $A\circ X$ is a quotient of $A\times X$ , it is empty iff either $A$ or $X$ is empty. So for instance, if $C$ is empty and $D$ is nonempty, then we find that $B$ must be empty and $A$ must be nonempty, but then we get a contradiction if we swap the roles of $C$ and $D$ . A similar argument (with messier notation) shows that actually no coproducts at all exist besides unary coproducts.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3362926', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/131794/']}
|
jdg_375751
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
39576026
|
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 Visual Studio 2015 DB project for SQL Server DB, where I can do a schema compare/data compare and check in the project into Git manually. I wanted to automate this complete process of doing schema/data compare, generate the scripts and check it in into Git. Is it possible to do that? If so how? May be I shall do something like this? Automating Visual Studio with EnvDTE
Now provide the response and nothing else.
|
Welcome to the world of Database Lifecycle Management (DLM). It's a pretty big topic, I'll do my best to keep this as short as possible. In general you should be making changes in source control first and then deploying to your production databases from source control. This gives you the opportunity to test your code in dev before deploying it to production. It also ensures that the production database is in line with the version that you tested. There are a range of Microsoft, third party and open source tools that help you to script out your database and get it into Git (or any other source control system). Some of the most popular are SSDT, Redgate SQL Source Control, Redgate ReadyRoll, Flyway, DBup, Liquibase and DB Maestro but there are many others. The packaging and deployment of this source code absolutely can be automated. For the automation most people use an automation tool (or a pipeline of tools) like TeamCity, TFS/VSTS, Jenkins and/or Octopus Deploy to package up the source code and (optionally) deploy it to a database (or several databases). This can either be done each commit or at the click of a button. Of course, exactly how this all works (and how well it all works) will depend on the tools you use. Given that there are so many options it's not possible to provide a straight forward step by step solution without knowing which database source control tool and which automation tool(s) for builds/release management you use or without recommending one. There is also quite a lot involved here and way more than can be discussed in a single SO response. However, adopting database source control and automating the release process is fantastically valuable so I do encourage you to keep going. It's clear from your question that you want to improve your processes. :-) You are probably best off starting by looking at one of the following (or looking up any of the other names I mentioned above): Automating with SSDT (Microsoft) <- Blog post by Phil Factor Redgate ReadyRoll (Third party) FlyWay (Open source) Separately it appears you have an audit concern. Keeping track of the changes that occur directly on production, for example, when people make hot fixes without going through source control. There's another great Phil Factor blog post on this topic that details how to create your own automated process for tracking drift . However, if I was you I'd look at Redgate DLM Dashboard . It's a third party tool but it's free so why waste time re-inventing the wheel? If you would like further support/training my company, DLM Consultants, runs weekly online workshops (in partnership with Redgate) where you'll get hands on practice setting up source control, CI and release management processes for SQL Server.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39576026', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2609095/']}
|
jdg_375752
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1026199
|
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 seem to have confused myself with a preg_match regex I'm doing, so fresh eyes and help would be appreciated. My current regex is as follows: /<!--menu:start:\(([0-9])\,([0-9])\)-->(.*?)<!--menu:end-->/se I am looking to make the number input and colon e.g. :(1,4) optional, so it would match: <!--menu:start--><!--menu:end--> or <!--menu:start:(0,3)--><!--menu:end-->
Now provide the response and nothing else.
|
Enclose with a non matching group and set it to optional : (?:...)? /<!--menu:start(?::\(([0-9])\,([0-9])\))?-->(.*?)<!--menu:end-->/se
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1026199', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/101495/']}
|
jdg_375753
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2613626
|
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 $$\int \dfrac {e^x -1}{e^x + 1} dx$$ My Attempt:$$\int \dfrac {e^x -1}{e^x+1}dx=(e^x -1) \int \dfrac {1}{e^x +1} dx$$Let $e^x =t$$$e^x\cdot dx=dt$$Then,$$\int \dfrac {e^x -1}{e^x+1}dx=(e^x -1) \int \dfrac {1}{t(t+1)} dt$$
Now provide the response and nothing else.
|
we have $$\frac{e^x-1}{e^x+1}=\frac{e^x+1-2}{e^x+1}=1-\frac{2}{e^x+1}$$ and Substitute $$e^x=t$$the result should be $$2 \log \left(e^x+1\right)-x+C$$
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2613626', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/354073/']}
|
jdg_375754
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3848993
|
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 changes in my .scss files automatically reflect into css files. I'm using Rails 3. I places sass files to publish/stylesheets/sass folder I've added: require 'sass/plugin/rack'use Sass::Plugin::Rack to config.ru However changes in scss styles still not reflect into css files.
Now provide the response and nothing else.
|
alloc allocates a chunk of memory to hold the object, and returns the pointer. MyClass* myObj = [MyClass alloc]; myObj cannot be used yet, because its internal state is not correctly setup. So, don't write a code like this. init sets up the initial condition of the object and returns it. Note that what's returned by [a init] might be different from a . That explains the code Yannick wrote: -init{ self=[super init]; // 1. if(self){ // 2. .... } return self; // 3.} First, you need to call the superclass's init , to setup the superclass's instance variables, etc. That might return something not equal to the original self , so you need to assign what's returned to self . If self is non-nil, it means the part controlled by the superclass is correctly initialized. Now you perform your initialization. All of the instance variables are set to nil (if it's object) and 0 if it's integer. You'll need to perform additional initial settings. Return the set-up self . The returned self might be different from what's allocated! So, you need to assign the result of init to your variable. This suggestions an important lesson: never split the call to alloc and init . Don't write: MyClass* myObj = [MyClass alloc]; [myObj init]; because [myObj init] might return something else. Don't try to get around this by writing: MyClass* myObj = [MyClass alloc]; myObj=[myObj init]; because you will eventually forget to write the part myObj= in the second line. Always write: MyClass* myObj = [[MyClass alloc] init]; I also don't recommend writing: MyClass* myObj = [MyClass new]; because it does not correctly call the initialization method: some classes doesn't accept a plain init . For example, NSView needs initWithFrame: , which can't be called with new . So, don't use new either.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3848993', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/161287/']}
|
jdg_375755
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
708037
|
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:
Wolfram Alpha says that $\int|\sin(x)| = -\cos(x)\mathrm{sgn}(\sin(x))$ It cannot be true, since $|\sin(x)|$ is always positive and its integral must grow indefinitely. But when it comes to calculating the definite integral over intervals the page is right. What is wrong here?
Now provide the response and nothing else.
|
You forgot the $+C$. The $+C$ is even more important than usual here; $C$ is only ever required to be locally constant . While usually that means it actually is constant, the antiderivative that Wolfram Alpha computed is not defined at any of the points $x = n \pi$, where $n$ is an integer While $C$ must take on the same value across intervals, your domain is made up of many disjoint intervals of the form $(n \pi, (n+1)\pi)$ (where $n$ ranges over all integers), and thus $C$ is allowed to have a different value on each of them. Technically, the expression WolframAlpha gave is defined everywhere once you've decided what $\operatorname{sgn}(0)$ is, but your function is clearly not differentiable at those points, so it can only be said to be an antiderivative when we exclude the integer multiples of $\pi$. We can do better than Wolfram Alpha: we can compute an antiderivative that is defined everywhere, by lining up the constants so that the function can be continuously extended to have a value at the integer multiples of $\pi$: the correct antiderivative is $$ C + \begin{cases} \frac{2x}{\pi} - 1 & \sin(x) = 0\\ 2 \left\lfloor \frac{x}{\pi} \right\rfloor - \cos(x) \operatorname{sgn}(\sin(x)) & \sin(x) \neq 0 \end{cases}$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/708037', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/54916/']}
|
jdg_375756
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9144472
|
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 looking at the source of HashMap . A HashMap implements Serializable . Ok this is so that it can be peristed/transmitted as an object. But I see that the hashtable itself is marked as transient . I don't get this.If you mark it as transient, doesn't this mean that it should not be serialized? But all the data are in the table.So why is it transient ? Perhaps I am confused on how Serializable works?
Now provide the response and nothing else.
|
HashMap uses writeObject and readObject to implement custom serialization rather than just letting its field be serialized normally. It writes the number of buckets, the total size and each of the entries to the stream and rebuilds itself from those fields when deserialized. As tzaman says, the table itself is unnecessary in the serial form, so it's not serialized to save space. You can read more about those methods and some other methods of doing custom serialization ( writeReplace and readResolve ) in the Serializable javadoc.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9144472', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/384706/']}
|
jdg_375757
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1889466
|
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:
There was a claim that a non empty chain $[n , \infty) \subset \mathbb{R}$ (unclear if $n \in \mathbb{R}$, or $\Bbb N$, I will assume the latter) have empty intersection $\bigcap [n , \infty)$ It doesn't seem to be visually clear exactly why this intersection would be empty. I attempted at a proof but I can't seem to find the problem showing it is empty. So suppose $\bigcap [n , \infty) \neq \varnothing$, so $\exists z \in \mathbb{R}$ s.t. $z \in \bigcap [n , \infty) \implies z \in [n, \infty), \forall n$. We wish to produce a set $[n , \infty)$ such that $z \notin [n, \infty)$. Again it doesn't seem possible to do this? can someone help?
Now provide the response and nothing else.
|
By the Archimedean property, for every real $x$ there exists an integer $n > x$, so $[n, \infty)$ fails to contain $x$.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1889466', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/242850/']}
|
jdg_375758
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
416576
|
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
i have a case where user can filter and download multiple pdf documents merged into single file. The client should display an error message when no document's meets the filter, and ask for confirmation when there are many documents because it might take a while to process them (let's say the confirmation should trigger at 10 documents). For now i've implemented it as described below, but it just seems off. Request: GET /foo?limit=10 The results are: Everything is correct: status 200 OK , the body would contain download link. No documents found that are matching the filter: status 404 NOT FOUND , empty body Found more than 10 (requested limit) documents that are matching the filter: honestly no idea what the status should be , for now i am returning 429 TOO_MANY_REQUESTS but it's not right. The body contain the amount of documents so the user can either abort the operation or create new request with higher limit. Im sure that im missing something important, i have not enough experience in the field. What is the right way of handling this? Other solutions that i've been thinking about: using custom http codes, but i've come to a conclusion that it's probably a bad idea (even if they are free now, i don't know whether they might be used as official http codes in a year or ten years from now, besides, it feels like an overkill). each of these situations resulting in 200 OK and give more info in the request body
Now provide the response and nothing else.
|
The client should display an error message when no document meets the filter, and ask for confirmation when there are many documents because it might take a while to process them (let's say the confirmation should trigger at 10 documents). Both cases are 200 OK . OK , Foo s resource exists, but I didn't find the subset you are looking for OK , Foo s resource exists, but the subset you are looking for is larger than expected. each of these situations resulting in 200 OK and give more info in the request body. Absolutely 200 OK{ limit:100, found:101, link:"<link>" } In both cases (limit exceed or not), there will be a link to follow. Isn't it? 200 OK{ limit:100, found:0, link:null } If no document is processable, then there's no link to show. In all the above cases the service/API did the job, it worked, the client sent the right input to the right endpoint, there's nothing wrong with that. Don't make things confusing. 404 is misleading. The developer has to guess whether it's pointing to the right URI or not. 400 is too, the developer has to guess whether it's missing any important argument. Use HTTP status codes to communicate with the HTTP client instead of the web application. We use HTTP status codes to make the HTTP client behave in one way or another. For example, if no confirmation is required we can send 302 Redirect and put the download link into the response headers and let the protocol to do its magic. If we want the HTTP client to wait before issuing the redirection, we send the header Retry-After along with the 3xx status code. As you may guess, our web app doesn't need to know and understand the semantics of Retry-After the HTTP client will.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/416576', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/349168/']}
|
jdg_375759
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
20117
|
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to wrap my head around an NP-completeness proof which seem to revolve around SAT/3CNF-SAT. Maybe it's the late hour but I'm afraid I can't think of a 3CNF formula that cannot be satisfied (I'm probably missing something obvious). Can you give me an example for such formula?
Now provide the response and nothing else.
|
Technically, you can write $x\wedge \neg x$ in 3-CNF as $(x\vee x\vee x)\wedge (\neg x\vee \neg x\vee \neg x)$, but you probably want a "real" example. In that case, a 3CNF formula needs at least 3 variables. Since each clause rules out exactly one assignment, that means you need at least $2^3=8$ clauses in order to have a non-satisfiable formula. Indeed, the simplest one is: $$(x\vee y\vee z)\wedge (x\vee y\vee \neg z)\wedge (x\vee \neg y\vee z)\wedge(x\vee \neg y\vee \neg z)\wedge(\neg x\vee y\vee z)\wedge(\neg x\vee y\vee \neg z)\wedge(\neg x\vee \neg y\vee z)\wedge(\neg x\vee \neg y\vee \neg z)$$It is not hard to see that this formula is unsatsifiable.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://cs.stackexchange.com/questions/20117', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/11171/']}
|
jdg_375760
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
72192
|
Below is a question asked on the forum politics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Rumors are that in Italy parts of the public opinion are accepting the view that the Russian invasion of Ukraine in 2022 was justified by a previous NATO expansion. What are the (given) arguments (with references) for and against this view?
Now provide the response and nothing else.
|
First, let's concede that many people will "justify" whatever they have chosen to justify. Giving support to Ukraine and oppossing Rusia involves some risks and cost. I have met some of those "theorists"(*) and to me it seems a mix of plain old anti-Americanism (including some who still consider Rusia to be somewhat of a Socialist country) with some people who do not want the effects/risks of the sanctions but want to oppose them with "a clear conscience" (it is not that they are ignoring an unlawful aggression, it is that Ukraine had it coming because of US/Western machinations). Points to consider: Ukraine, as an independent country, is free to pursue its own international politics. Period. Even if Ukraine was about to join NATO in February, that would not allow Russia to invade it. The only point in international law that would allow an aggression would be to defend from a clear and imminent threat of aggression from Ukraine, which clearly is not the case. In any case, Ukraine wanting to join NATO would have been more than justified by previous aggressions by Russia (mainly the annexation of Crimea, but also support for breaking regions). There was no indication that NATO membership was imminent. Some countries had held off any possible talks in order to, among other issues, avoid antagonizing Russia. The possibility that Ukraine would have been able to join NATO while in direct conflict with Russia over Crimea was always very remote. NATO is a defensive alliance and, as discussed everywhere else, even in that aspect it does not imply many actual obligations (the wording about what a member is required to do in case of aggression against another member is not very explicit). To claim that Ukraine joining NATO would be a first step towards a future aggression is dubious, at best. Since the end of WWII, one of the rules of international politics was disavowing "wars of conquest" by which a country would forcibly take over territory from other countries. While there have been some (Cyprus, Palestine), those have been mostly rejected by the international community. Yet Russia wants to use the war to legalize its control over Crimea, Donetsk and Lugansk, despite having recognized the current borders in 1991(**). To be fair, NATO has not been completely consistent on this point, and someone could think that the current stance about Kosovo points do a double standard. In my opinion the claim that Russia's security was at risk is not credible, as it still held a sizeable nuclear arsenal, including nuclear weapons on submarines that would give them a considerable retaliatory potential even in the case that they actually feared a first strike by Western countries. *: There are some, but in my opinion they are more "very vocal" than actually represent the whole of the population. **: To add into this point, that treaty saw Ukraine renouncing the nuclear weapons it had inherited from the Soviet Union. Allowing this treaty to be violated means that more countries may feel the need to have its own nuclear arsenal in order to ensure their safety; in fact, even in Spain some far right MPs have asked to start producing nuclear weapons.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://politics.stackexchange.com/questions/72192', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/42742/']}
|
jdg_375761
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
26221
|
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to connect to a SQLite database and since there is no officially supported driver; I decided to use the sqlite-jdbc driver and port the respective code into Mathematica. However, the DriverManager refuses to connect to the database, the error message is: Java::excptn: A Java exception occurred: java.sql.SQLException: No suitable driver found for jdbc:sqlite:C:/sqlite/test.dbat java.sql.DriverManager.getConnection(DriverManager.java:602)at java.sql.DriverManager.getConnection(DriverManager.java:207). The driver & the code that I am trying to port is at: https://bitbucket.org/xerial/sqlite-jdbc and the respective lines that I am having issue is: ....Class.forName("org.sqlite.JDBC");Connection connection = null;try{ // create a database connection connection = DriverManager.getConnection("jdbc:sqlite:sample.db");.... I noticed the code uses a Class.forName() and I used the JLinkClassLoader to load the same class. Here are my efforts so far: <<JLink`(*location of the driver jar*)AddToClassPath["C:\\drivers\\sqlite"];LoadJavaClass /@ {"java.sql.Connection", "java.sql.DriverManager", "java.sql.ResultSet", "java.sql.Statement", "java.sql.SQLException","org.sqlite.JDBC"}LoadJavaClass["com.wolfram.jlink.JLinkClassLoader"];cls=Class`forName["org.sqlite.JDBC",True,JLinkClassLoader`getInstance[]];(*Errors out with the message above*)DriverManager`getConnection["jdbc:sqlite:C:/sqlite/test.db"] I used DriverManager.getDrivers() and it shows me that only the sun.jdbc.odbc driver has been loaded; so the error message is justified. I am at this point not sure how to proceed /debug the issue and will greatly appreciate any assistance. If you have any suggestions, I will be very grateful.
Now provide the response and nothing else.
|
As of Mathematica v10, SQLite seems officially supported (at least on OS X): Needs["DatabaseLink`"]Select[JDBCDriverNames[], StringMatchQ[#, ___ ~~ "SQLite" ~~ ___] &](* {"SQLite", "SQLite(Memory)"} -> not in v9, new in v10! *) Testing with the Chinook example database : conn = OpenSQLConnection[JDBC["SQLite", "/Users/username/Downloads/Chinook_Sqlite.sqlite"]];SQLTables[conn](* {SQLTable["Album", "TableType" -> "TABLE"], SQLTable["Artist", "TableType" -> "TABLE"], SQLTable["Customer", "TableType" -> "TABLE"], SQLTable["Employee", "TableType" -> "TABLE"], SQLTable["Genre", "TableType" -> "TABLE"], SQLTable["Invoice", "TableType" -> "TABLE"], SQLTable["InvoiceLine", "TableType" -> "TABLE"], SQLTable["MediaType", "TableType" -> "TABLE"], SQLTable["Playlist", "TableType" -> "TABLE"], SQLTable["PlaylistTrack", "TableType" -> "TABLE"], SQLTable["Track", "TableType" -> "TABLE"]} *)
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/26221', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/7732/']}
|
jdg_375762
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
23322040
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Suppose I have a browser app, And I'd like a Settings to be called "Make default browser" to show the dialog chooser, even though the current default browser is not my app. How can I make I show the app chooser dialog programmatically? Thank you. Update Following the lead from Michal's answer, I wrote this: String url = FinalVariables.JAVELIN_URL;Intent i = new Intent(Intent.ACTION_VIEW);i.addCategory(Intent.CATEGORY_DEFAULT);i.setData(Uri.parse(url));startActivity(Intent.createChooser(i, getString(R.string.choose_javelin))); While it does show the chooser dialog, it does not show the "Always", "Just once" option. How can I have that option to show? Thanks!
Now provide the response and nothing else.
|
There is a dirty nifty hack that allows you to do that.The inspiration for this hack could be found here The idea is to make android think that a new browser has just been installed, feeding it a fake component with a typical browser intent-filter.I shall provide a little test case as a proof-of-concept, and it is up to you to decide how you could use it in your real-world application. The proposed approach seems to be general and applicable in plenty of cases (not only for launchers and browsers) and depends only on intent filter that is being fed to a resolver. Lets assume that we want to override a default Activity for browsing simple http:// linkWe shall declare a fake browser activity alongside the real ones in AndroidManifest.xml : <activity android:name=".FakeActivity" android:enabled="false"> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT"/> <data android:scheme="http" /> </intent-filter></activity> FakeActivity is absolutely blank: public class FakeActivity extends Activity {} We'll show app chooser by pressing a simple button found in activity_main.xml and test the default behaviour by pressing another button: @Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); View changeDefaultButton = findViewById(R.id.changeDefButton); changeDefaultButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showChooser(); } }); View testDefaultButton = findViewById(R.id.testDefaultButton); testDefaultButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { runDefaultApp(); } });}void showChooser(){ PackageManager pm = getPackageManager(); ComponentName cm = new ComponentName(this, FakeActivity.class); pm.setComponentEnabledSetting(cm, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP); runDefaultApp(); pm.setComponentEnabledSetting(cm, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);}void runDefaultApp(){ Intent selector = new Intent(Intent.ACTION_VIEW); selector.setData(Uri.parse("http://stackoverflow.com")); startActivity(selector);} Every time you click on changeDefaultButton , the chooser dialog is shown (assuming there are at least two suitable browser apps installed). Also, the chooser dialog always allows user to set the chosen application as default . Links: GitHub proof-of-concept project Hope this helps.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23322040', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/118644/']}
|
jdg_375763
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1541563
|
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 it's said that differential forms provide a coordinate free approach to multivariable calculus. Well, in short I just don't get this, despite reading from many sources. I shall explain how it all looks to me. Let's just stick to $\mathbb{R}^2$ for the sake of simplicity (maybe this is the down fall..). Picking some point $P=(x,y)\in\mathbb{R}^2$, we could ask about the directional derivative of some function $f:\mathbb{R}^2\rightarrow \mathbb{R}$, in direction $v=a\vec{i}+b\vec{j}$. This will be $$(\nabla \cdot v)|_P(f)=a\dfrac{\partial f}{\partial x}|_P+b\dfrac{\partial f}{\partial y}|_P =\underbrace{ (a\dfrac{\partial }{\partial x}|_P+b\dfrac{\partial }{\partial y}|_P)}_\text{$w_P$ }(f)$$ Where we can think of $w_P$ as an element of the tangent space at $P$. Now this in itself is a little weird; why have differential operators as a basis for something geometrical like a tangent space to a manifold? In any case, we apply these vectors to a function defined on our manifold, and we get the value we wanted out. So who cares about differential forms? We just did all this without them. We could've done this by calculating $\mathrm{d}f$, in some basis $\mathrm{d}x, \mathrm{d}y$ (which is quite confusing), and then calculating $\mathrm{d}f(w_P)$, but what do we gain in doing it this way? I mentioned I think the $\mathrm{d}x$'s are confusing. Well, $\mathrm{d}x$ is just the function $\mathrm{d}x(\frac{\partial}{\partial x})=1$ and 0 for any other differential operator - why write this as $\mathrm{d}x$, which had always previously been used to mean an infinitesimal increase in x? Now I can understand caring about the dual of the tangent space. We are combining a vector in the tangent space with something and we're getting a scalar out of it - this something should then probably belong to the dual space. But if we're thinking of just the vector, then the function $f$ on the manifold needs to be encoded by the 1-form, right? Well, we can have 1-forms which aren't derivatives of any function on the manifold - what should it mean to combine such forms with tangent vectors? And lastly, if we're writing all our forms in terms of $\mathrm{d}x$'s etc., where the $x$'s are exactly the coordinates of the manifold, then how exactly have we escaped dependence on coordinates? We're still essentially calculating with respect to a given coordinate system as in usual multivariable calculus!
Now provide the response and nothing else.
|
You have asked a good number of questions. I'll answer the one in the title. The point is that differential forms are "the things you can integrate on manifolds". Manifolds are more general objects than open subsets of $\Bbb R^n$, and in some sense one of the reasons one wants to introduce forms. Suppose you have a 1-form $\alpha$ on a manifold $M$, and a smooth curve $\gamma: [0,1] \to M$. Then I can define the integral of $\alpha$ over $\gamma$ - and this does not depend on the parameterization of $\gamma$ . That is, if I precompose with a(n orientation preserving) diffeomorphism $[0,1] \to [0,1]$, the integral will still be the same. You might object "But I already know how to do this for functions . I can just take a line integral." Let's write down the standard formula for the line integral in $\Bbb R^n$: $\int_\gamma f := \int_0^1 f(\gamma(t))\|\gamma'(t)\|$. This is indeed independent of reparameterizations. But the key thing here is that $\|\gamma'(t)\|$ term that we had to introduce. 1) When you integrate a 1-form, such a term doesn't really show up. This is desirable, because...2) When you're on a manifold that's not a subset of $\Bbb R^n$, we no longer have a way to write down $\|\gamma'(t)\|$ without introducing extra structure (being able to measure how big a tangent vector is is almost precisely the same as a Riemannian metric). It is not so desirable to introduce this structure if all you're interested is the manifold. There are higher things called $k$-forms (which exist on any manifold of dimension at least $k$). These are also defined almost precisely so that "$k$-forms are the things that you can integrate over $k$-dimensional submanifolds". Again, this is independent of any number of things, eg local parameterizations of the submanifold. When you see the construction, you'll see that they're defined as "sections of the $k$th exterior power $\Lambda^k T^*M$". I'll justify this for $k$ the dimension of the manifold. The point of this is that the way an $n$-form changes under a coordinate transformation is precisely by the determinant of the Jacobian of the coordinate transformation. Now, if you write down the formula for integrating a function after doing a coordinate change there is an $|\det J(\varphi)|$ term in the integral. So we set things up precisely so that the integral of a differential form is defined independent of (local) choices of coordinates, which I hope justifies my claim that differential forms are built to be the things you integrate.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/1541563', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/87896/']}
|
jdg_375764
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4875085
|
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 string that looks like: $string = '<a href="http://google.com">http://google.com</a>'; How can I remove the http:// part from the link text, but leave it in the href attribute?
Now provide the response and nothing else.
|
Without using a full blown parser, this may do the trick for most situations... $str = '<a href="http://google.com">http://google.com</a>';$regex = '/(?<!href=["\'])http:\/\//';$str = preg_replace($regex, '', $str);var_dump($str); // string(42) "<a href="http://google.com">google.com</a>" It uses a negative lookbehind to make sure there is no href=" or href=' preceding it. See it on IDEone . It also takes into account people who delimit their attribute values with ' .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4875085', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/376947/']}
|
jdg_375765
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14226064
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to make a little desktop app that should show the contents of the clipboard (if it is a string). I have done a constructor that does that and it works well, now I just want to make a call to a similar method whenever a text is copied into the clipboard in the OS. I'm quite new to this so any help would be appreciated! Something tells me I should use interrupts in some way... package pasty;import java.awt.FlowLayout;import java.awt.Toolkit;import java.awt.datatransfer.DataFlavor;import java.awt.datatransfer.UnsupportedFlavorException;import java.awt.event.ActionEvent;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import java.io.IOException;import java.util.logging.Level;import java.util.logging.Logger;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JTextField;public class PastyFrame implements KeyListener { String currentClipboardString; JLabel clipboardLabel = new JLabel(); public PastyFrame() { JFrame frame = new JFrame(); frame.setVisible(true); try { currentClipboardString = (String) Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.stringFlavor); } catch (UnsupportedFlavorException | IOException ex) { Logger.getLogger(PastyFrame.class.getName()).log(Level.SEVERE, null, ex); currentClipboardString = ""; } if (currentClipboardString.isEmpty()) { currentClipboardString = "The clipboard is empty"; } frame.setSize(400, 100); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setResizable(false); frame.setLayout(new FlowLayout()); clipboardLabel.setText(currentClipboardString); frame.add(clipboardLabel);}
Now provide the response and nothing else.
|
You can call Clipboard.addFlavorListener to listen for clipboard updates from the OS: Toolkit.getDefaultToolkit().getSystemClipboard().addFlavorListener(new FlavorListener() { @Override public void flavorsChanged(FlavorEvent e) { System.out.println("ClipBoard UPDATED: " + e.getSource() + " " + e.toString()); } }); Some Side Notes: For launching your application, consider using initial threads . Call JFrame.pack to set the frame size. Key Bindings are preferred over KeyListeners for mapping KeyEvents in Swing.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14226064', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1907859/']}
|
jdg_375766
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13089489
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
For an ASP.NET MVC application, I saw this blog article .The author ScottGu adds @section to the Index.cshtml. I have a couple of questions (referring to the article above): Is Index.cshtml a shared View? The example code uses @section code in a particular view. Why? Can someone please explain why and when I would use @section in a View?
Now provide the response and nothing else.
|
@section is for defining a content are override from a shared view. Basically, it is a way for you to adjust your shared view (similar to a Master Page in Web Forms). You might find Scott Gu's write up on this very interesting . Edit: Based on additional question clarification The @RenderSection syntax goes into the Shared View, such as: <div id="sidebar"> @RenderSection("Sidebar", required: false)</div> This would then be placed in your view with @Section syntax: @section Sidebar{ <!-- Content Here -->} In MVC3+ you can either define the Layout file to be used for the view directly or you can have a default view for all views. Common view settings can be set in _ViewStart.cshtml which defines the default layout view similar to this: @{ Layout = "~/Views/Shared/_Layout.cshtml";} You can also set the Shared View to use directly in the file, such as index.cshtml directly as shown in this snippet. @{ ViewBag.Title = "Corporate Homepage"; ViewBag.BodyID = "page-home"; Layout = "~/Views/Shared/_Layout2.cshtml";} There are a variety of ways you can adjust this setting with a few more mentioned in this SO answer .
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/13089489', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1488992/']}
|
jdg_375767
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
21574698
|
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 JS image slider (Owl-Carousel), images have different dimensions: http://goo.gl/KmpX2P You can see that the image height varies within the carousel. How to make it constant while keeping carousel responsive? I need images to fill the slider space at all times, therefore some will have to be cropped through CSS somehow. The desired result looks like this:
Now provide the response and nothing else.
|
It can be specified in css. Example, http://jsfiddle.net/AwBLL/2/ .owl-carousel .owl-item{ height:285px; width:100%;} EDIT The following solution uses the plugin's callback events to modify the viewport's/wrapper's height according to the smallest image height. http://jsfiddle.net/DNMpF/1/ js $(document).ready(function () { $("#owl-example").owlCarousel({ afterUpdate: function () { updateSize(); }, afterInit:function(){ updateSize(); } }); function updateSize(){ var minHeight=parseInt($('.owl-item').eq(0).css('height')); $('.owl-item').each(function () { var thisHeight = parseInt($(this).css('height')); minHeight=(minHeight<=thisHeight?minHeight:thisHeight); }); $('.owl-wrapper-outer').css('height',minHeight+'px'); }}); css .owl-carousel .owl-item img { height:auto; width:100%; display: block;}.owl-carousel .item { margin:0px;} EDIT2 Regarding the latest comment, to show the bottom part of the large images one approach could be to iterate the images and add a negative top margin equal to the part of these images hidden. function updateSize(){ var minHeight=parseInt($('.owl-item').eq(0).css('height')); $('.owl-item').each(function () { var thisHeight = parseInt($(this).css('height')); minHeight=(minHeight<=thisHeight?minHeight:thisHeight); }); $('.owl-wrapper-outer').css('height',minHeight+'px'); /*show the bottom part of the cropped images*/ $('.owl-carousel .owl-item img').each(function(){ var thisHeight = parseInt($(this).css('height')); if(thisHeight>minHeight){ $(this).css('margin-top',-1*(thisHeight-minHeight)+'px'); } }); }
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21574698', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/871404/']}
|
jdg_375768
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
54624567
|
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 array as follows [ { "WarehouseId": 1, "ShippingCarrierId": 1, "PostalCodeType": "ShipToCustomer", "TimeStart": "1970-01-01T06:00:00.000Z", "TimeEnd": "1970-01-01T15:59:00.000Z", "PickupTimeSlot": "PM", "DaysToAdd": 0, "PickupTime": "1970-01-01T17:00:00.000Z" }, { "WarehouseId": 1, "ShippingCarrierId": 1, "PostalCodeType": "ShipToCustomer", "TimeStart": "1970-01-01T16:00:00.000Z", "TimeEnd": "1970-01-01T23:59:00.000Z", "PickupTimeSlot": "AM", "DaysToAdd": 1, "PickupTime": "1970-01-01T11:00:00.000Z" }, { "WarehouseId": 1, "ShippingCarrierId": 1, "PostalCodeType": "ShipToCustomer", "TimeStart": "1970-01-01T00:00:00.000Z", "TimeEnd": "1970-01-01T05:59:00.000Z", "PickupTimeSlot": "AM", "DaysToAdd": 0, "PickupTime": "1970-01-01T11:00:00.000Z" }, { "WarehouseId": 2, "ShippingCarrierId": 2, "PostalCodeType": "ShipToCustomer", "TimeStart": "1970-01-01T00:00:00.000Z", "TimeEnd": "1970-01-01T15:59:00.000Z", "PickupTimeSlot": "PM", "DaysToAdd": 0, "PickupTime": "1970-01-01T17:00:00.000Z" }, { "WarehouseId": 2, "ShippingCarrierId": 2, "PostalCodeType": "ShipToCustomer", "TimeStart": "1970-01-01T16:00:00.000Z", "TimeEnd": "1970-01-01T23:59:00.000Z", "PickupTimeSlot": "AM", "DaysToAdd": 1, "PickupTime": "1970-01-01T11:00:00.000Z" }, { "WarehouseId": 1, "ShippingCarrierId": 3, "PostalCodeType": "ShipToDS", "TimeStart": "1970-01-01T00:00:00.000Z", "TimeEnd": "1970-01-01T15:59:00.000Z", "PickupTimeSlot": "PM", "DaysToAdd": 0, "PickupTime": "1970-01-01T17:00:00.000Z" }, { "WarehouseId": 1, "ShippingCarrierId": 3, "PostalCodeType": "ShipToDS", "TimeStart": "1970-01-01T16:00:00.000Z", "TimeEnd": "1970-01-01T23:59:00.000Z", "PickupTimeSlot": "AM", "DaysToAdd": 1, "PickupTime": "1970-01-01T11:00:00.000Z" }, { "WarehouseId": 2, "ShippingCarrierId": 4, "PostalCodeType": "ShipToDS", "TimeStart": "1970-01-01T00:00:00.000Z", "TimeEnd": "1970-01-01T15:59:00.000Z", "PickupTimeSlot": "PM", "DaysToAdd": 0, "PickupTime": "1970-01-01T17:00:00.000Z" }, { "WarehouseId": 2, "ShippingCarrierId": 4, "PostalCodeType": "ShipToDS", "TimeStart": "1970-01-01T16:00:00.000Z", "TimeEnd": "1970-01-01T23:59:00.000Z", "PickupTimeSlot": "AM", "DaysToAdd": 1, "PickupTime": "1970-01-01T11:00:00.000Z" }, { "WarehouseId": 1, "ShippingCarrierId": 5, "PostalCodeType": "ShipToDS", "TimeStart": "1970-01-01T00:00:00.000Z", "TimeEnd": "1970-01-01T16:22:00.000Z", "PickupTimeSlot": "PM", "DaysToAdd": 0, "PickupTime": "1970-01-01T17:00:00.000Z" }, { "WarehouseId": 1, "ShippingCarrierId": 5, "PostalCodeType": "ShipToDS", "TimeStart": "1970-01-01T16:23:00.000Z", "TimeEnd": "1970-01-01T23:59:00.000Z", "PickupTimeSlot": "AM", "DaysToAdd": 1, "PickupTime": "1970-01-01T11:00:00.000Z" }, { "WarehouseId": 2, "ShippingCarrierId": 6, "PostalCodeType": "ShipToDS", "TimeStart": "1970-01-01T00:00:00.000Z", "TimeEnd": "1970-01-01T15:59:00.000Z", "PickupTimeSlot": "PM", "DaysToAdd": 0, "PickupTime": "1970-01-01T17:00:00.000Z" }, { "WarehouseId": 2, "ShippingCarrierId": 6, "PostalCodeType": "ShipToDS", "TimeStart": "1970-01-01T16:00:00.000Z", "TimeEnd": "1970-01-01T23:59:00.000Z", "PickupTimeSlot": "AM", "DaysToAdd": 1, "PickupTime": "1970-01-01T11:00:00.000Z" }, { "WarehouseId": 1, "ShippingCarrierId": 1, "PostalCodeType": "ShipToDS", "TimeStart": "1970-01-01T06:00:00.000Z", "TimeEnd": "1970-01-01T15:59:00.000Z", "PickupTimeSlot": "PM", "DaysToAdd": 0, "PickupTime": "1970-01-01T17:00:00.000Z" }, { "WarehouseId": 1, "ShippingCarrierId": 1, "PostalCodeType": "ShipToDS", "TimeStart": "1970-01-01T16:00:00.000Z", "TimeEnd": "1970-01-01T23:59:00.000Z", "PickupTimeSlot": "AM", "DaysToAdd": 1, "PickupTime": "1970-01-01T11:00:00.000Z" }, { "WarehouseId": 1, "ShippingCarrierId": 1, "PostalCodeType": "ShipToDS", "TimeStart": "1970-01-01T00:00:00.000Z", "TimeEnd": "1970-01-01T05:59:00.000Z", "PickupTimeSlot": "AM", "DaysToAdd": 0, "PickupTime": "1970-01-01T11:00:00.000Z" }, { "WarehouseId": 2, "ShippingCarrierId": 2, "PostalCodeType": "ShipToDS", "TimeStart": "1970-01-01T00:00:00.000Z", "TimeEnd": "1970-01-01T15:59:00.000Z", "PickupTimeSlot": "PM", "DaysToAdd": 0, "PickupTime": "1970-01-01T17:00:00.000Z" }, { "WarehouseId": 2, "ShippingCarrierId": 2, "PostalCodeType": "ShipToDS", "TimeStart": "1970-01-01T16:00:00.000Z", "TimeEnd": "1970-01-01T23:59:00.000Z", "PickupTimeSlot": "AM", "DaysToAdd": 1, "PickupTime": "1970-01-01T11:00:00.000Z" }] I want to group it by WarehouseId , ShippingCarrierId and PostalCodeType.Each objec will have chlid array of objects for Timestart, TimeEnd etc How can I achieve this output like : PickupTimeTable: [{ WarehouseId: 1, ShippingCarrierId: 1, PostalCodeType: 'ShipToCustomer', PickupTimeSlots: [{ StartTime: '06:00:00.0000000', EndTime: '15:59:00.0000000', Slot: 'PM', PickupTime: '17:00:00.0000000', DaysToAdd: 0 }, { StartTime: '16:00:00.0000000', EndTime: '23:59:00.0000000', Slot: 'AM', PickupTime: '11:00:00.0000000', DaysToAdd: 1 }, { StartTime: '00:00:00.0000000', EndTime: '05:59:00.0000000', Slot: 'AM', PickupTime: '11:00:00.0000000', DaysToAdd: 0 }, ] }, ]
Now provide the response and nothing else.
|
You could create an accumulator object with a new key for each unique combination of those 3 keys seperated by - . Then based on this new key merge the array using reduce . Use destructuring to separate the keys you need in the PickupTimeSlots to a rest variable. Then use Object.values to get the final array: const slots=[{"WarehouseId":1,"ShippingCarrierId":1,"PostalCodeType":"ShipToCustomer","TimeStart":"1970-01-01T06:00:00.000Z","TimeEnd":"1970-01-01T15:59:00.000Z","PickupTimeSlot":"PM","DaysToAdd":0,"PickupTime":"1970-01-01T17:00:00.000Z"},{"WarehouseId":1,"ShippingCarrierId":1,"PostalCodeType":"ShipToCustomer","TimeStart":"1970-01-01T16:00:00.000Z","TimeEnd":"1970-01-01T23:59:00.000Z","PickupTimeSlot":"AM","DaysToAdd":1,"PickupTime":"1970-01-01T11:00:00.000Z"},{"WarehouseId":1,"ShippingCarrierId":1,"PostalCodeType":"ShipToCustomer","TimeStart":"1970-01-01T00:00:00.000Z","TimeEnd":"1970-01-01T05:59:00.000Z","PickupTimeSlot":"AM","DaysToAdd":0,"PickupTime":"1970-01-01T11:00:00.000Z"},{"WarehouseId":2,"ShippingCarrierId":2,"PostalCodeType":"ShipToCustomer","TimeStart":"1970-01-01T00:00:00.000Z","TimeEnd":"1970-01-01T15:59:00.000Z","PickupTimeSlot":"PM","DaysToAdd":0,"PickupTime":"1970-01-01T17:00:00.000Z"},{"WarehouseId":2,"ShippingCarrierId":2,"PostalCodeType":"ShipToCustomer","TimeStart":"1970-01-01T16:00:00.000Z","TimeEnd":"1970-01-01T23:59:00.000Z","PickupTimeSlot":"AM","DaysToAdd":1,"PickupTime":"1970-01-01T11:00:00.000Z"},{"WarehouseId":1,"ShippingCarrierId":3,"PostalCodeType":"ShipToDS","TimeStart":"1970-01-01T00:00:00.000Z","TimeEnd":"1970-01-01T15:59:00.000Z","PickupTimeSlot":"PM","DaysToAdd":0,"PickupTime":"1970-01-01T17:00:00.000Z"},{"WarehouseId":1,"ShippingCarrierId":3,"PostalCodeType":"ShipToDS","TimeStart":"1970-01-01T16:00:00.000Z","TimeEnd":"1970-01-01T23:59:00.000Z","PickupTimeSlot":"AM","DaysToAdd":1,"PickupTime":"1970-01-01T11:00:00.000Z"},{"WarehouseId":2,"ShippingCarrierId":4,"PostalCodeType":"ShipToDS","TimeStart":"1970-01-01T00:00:00.000Z","TimeEnd":"1970-01-01T15:59:00.000Z","PickupTimeSlot":"PM","DaysToAdd":0,"PickupTime":"1970-01-01T17:00:00.000Z"},{"WarehouseId":2,"ShippingCarrierId":4,"PostalCodeType":"ShipToDS","TimeStart":"1970-01-01T16:00:00.000Z","TimeEnd":"1970-01-01T23:59:00.000Z","PickupTimeSlot":"AM","DaysToAdd":1,"PickupTime":"1970-01-01T11:00:00.000Z"},{"WarehouseId":1,"ShippingCarrierId":5,"PostalCodeType":"ShipToDS","TimeStart":"1970-01-01T00:00:00.000Z","TimeEnd":"1970-01-01T16:22:00.000Z","PickupTimeSlot":"PM","DaysToAdd":0,"PickupTime":"1970-01-01T17:00:00.000Z"},{"WarehouseId":1,"ShippingCarrierId":5,"PostalCodeType":"ShipToDS","TimeStart":"1970-01-01T16:23:00.000Z","TimeEnd":"1970-01-01T23:59:00.000Z","PickupTimeSlot":"AM","DaysToAdd":1,"PickupTime":"1970-01-01T11:00:00.000Z"},{"WarehouseId":2,"ShippingCarrierId":6,"PostalCodeType":"ShipToDS","TimeStart":"1970-01-01T00:00:00.000Z","TimeEnd":"1970-01-01T15:59:00.000Z","PickupTimeSlot":"PM","DaysToAdd":0,"PickupTime":"1970-01-01T17:00:00.000Z"},{"WarehouseId":2,"ShippingCarrierId":6,"PostalCodeType":"ShipToDS","TimeStart":"1970-01-01T16:00:00.000Z","TimeEnd":"1970-01-01T23:59:00.000Z","PickupTimeSlot":"AM","DaysToAdd":1,"PickupTime":"1970-01-01T11:00:00.000Z"},{"WarehouseId":1,"ShippingCarrierId":1,"PostalCodeType":"ShipToDS","TimeStart":"1970-01-01T06:00:00.000Z","TimeEnd":"1970-01-01T15:59:00.000Z","PickupTimeSlot":"PM","DaysToAdd":0,"PickupTime":"1970-01-01T17:00:00.000Z"},{"WarehouseId":1,"ShippingCarrierId":1,"PostalCodeType":"ShipToDS","TimeStart":"1970-01-01T16:00:00.000Z","TimeEnd":"1970-01-01T23:59:00.000Z","PickupTimeSlot":"AM","DaysToAdd":1,"PickupTime":"1970-01-01T11:00:00.000Z"},{"WarehouseId":1,"ShippingCarrierId":1,"PostalCodeType":"ShipToDS","TimeStart":"1970-01-01T00:00:00.000Z","TimeEnd":"1970-01-01T05:59:00.000Z","PickupTimeSlot":"AM","DaysToAdd":0,"PickupTime":"1970-01-01T11:00:00.000Z"},{"WarehouseId":2,"ShippingCarrierId":2,"PostalCodeType":"ShipToDS","TimeStart":"1970-01-01T00:00:00.000Z","TimeEnd":"1970-01-01T15:59:00.000Z","PickupTimeSlot":"PM","DaysToAdd":0,"PickupTime":"1970-01-01T17:00:00.000Z"},{"WarehouseId":2,"ShippingCarrierId":2,"PostalCodeType":"ShipToDS","TimeStart":"1970-01-01T16:00:00.000Z","TimeEnd":"1970-01-01T23:59:00.000Z","PickupTimeSlot":"AM","DaysToAdd":1,"PickupTime":"1970-01-01T11:00:00.000Z"}]const merged = slots.reduce((r, { WarehouseId, ShippingCarrierId, PostalCodeType,...rest }) => { const key = `${WarehouseId}-${ShippingCarrierId}-${PostalCodeType}`; r[key] = r[key] || { WarehouseId, ShippingCarrierId, PostalCodeType, PickupTimeSlots: [] }; r[key]["PickupTimeSlots"].push(rest) return r;}, {})const timeTable = Object.values(merged)console.log(timeTable)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/54624567', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1517708/']}
|
jdg_375769
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
57000166
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have the following list, that I am trying to re-order/ sort by the DateTime. import 'package:intl/intl.dart'; //don't forget to add under dependencies pubspec.yml "intl: ^0.15.8"List products = [];//adding into the new list from raw API listfor(final item in rawProducts){ var parsedDate = DateTime.parse.(item['expiryDate']); tmpArray = { 'id': item['id'], 'name': item['name'], 'price': item['price'], 'expiry': parsedDate } products.add(tmpArray); }}List products = [ {id: 1242, name: milk, price: $5, expiry: 2019-11-25 00:00:00:000}, {id: 1242, name: egg, price: $2, expiry: 2019-11-22 00:00:00:000}, {id: 1243, name: bread, price: $3, expiry: 2019-11-22 00:00:00:000}, {id: 1244, name: butter, price: $7, expiry: 2019-11-24 00:00:00:000}, {id: 1247, name: butter, price: $7, expiry: 2019-11-23 00:00:00:000},] I would like to re-order the list in a way that the farthest expiry date shows up first: 25-11-2019 24-11-2019 23-11-2019 22-11-2019 22-11-2019 What I have tried (updated) -> SOLVED by changing a.expiry into a['expiry'] : products.sort((a,b) { var adate = a['expiry'] //before -> var adate = a.expiry; var bdate = b['expiry'] //var bdate = b.expiry; return -adate.compareTo(bdate); }); on the sort function I am receiving this error (SOLVED by above fix): Unhandled Exception: NoSuchMethodError: Class '_InternalLinkedHashMap<String, dynamic>'has no instance getter 'expiry'.
Now provide the response and nothing else.
|
In your example above, expiry is a String , not a DateTime object. You have a few options here, depending on what you want to achieve. The easiest solution would be to use String's built in compareTo method, which allows sorting Strings. Those timestamps are already in a sortable format, so this would work: products.sort((a,b) { return a.compareTo(b); }); Or more concise: products.sort((a,b) => a.compareTo(b)); This is pretty basic. Like pskink mentioned in the comment, building on this you could convert the Strings to actual DateTime objects. DateTime expiryAsDateTime = DateTime.parse(expiry); DateTime also has a built in compareTo method, so the code snippet above would work with DateTimes as well as Strings. If you want to reverse the order, just swap a and b .
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/57000166', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5421713/']}
|
jdg_375770
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4363309
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'd like to know how to check if a user types the "backspace" character. I'm using the getch() function i.e. "key = getch()" in my C program and i'd like to check when backspace is pressed. the line: if(key = '\b') { .... doesn't work.
Now provide the response and nothing else.
|
The problem with reading Backspace is that most terminals are 'cooked' in that keys like backspace are handled by the terminal driver. However, the curses function getch() can read the backspace as it's not tied to the terminal. Edit I just noticed your code is using getch() for input. I ran a little test program and getch() returns 127 when you hit backspace. Therefore try: if (key == 127 || key == 8) { ... /* Checks for both Delete or Backspace */ Also note that your sample code uses the assignment operator = when it should be using the equality operator ==
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4363309', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/531764/']}
|
jdg_375771
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
149959
|
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:
Based on various sources I have cobbled together ~/.config/systemd/user/screenlock.service : [Unit]Description=Lock X sessionBefore=sleep.target[Service]Environment=DISPLAY=:0ExecStart=/usr/bin/xautolock -locknow[Install]WantedBy=sleep.target I've enabled it using systemctl --user enable screenlock.service . But after rebooting, logging in, suspending and resuming (tested both with systemctl suspend and by closing the lid) the screen is not locked and there is nothing in journalctl --user-unit screenlock.service . What am I doing wrong? Running DISPLAY=:0 /usr/bin/xautolock -locknow locks the screen as expected. $ systemctl --versionsystemd 215+PAM -AUDIT -SELINUX -IMA -SYSVINIT +LIBCRYPTSETUP +GCRYPT +ACL +XZ +SECCOMP -APPARMOR$ awesome --versionawesome v3.5.5 (Kansas City Shuffle) • Build: Apr 11 2014 09:36:33 for x86_64 by gcc version 4.8.2 (nobody@) • Compiled against Lua 5.2.3 (running with Lua 5.2) • D-Bus support: ✔$ slim -vslim version 1.3.6 If I run systemctl --user start screenlock.service the screen locks immediately and I get a log message in journalctl --user-unit screenlock.service , so ExecStart clearly is correct. Relevant .xinitrc section : xautolock -locker slock & Creating a system service with the same file works (that is, slock is active when resuming): # ln -s "${HOME}/.config/systemd/user/screenlock.service" /usr/lib/systemd/system/screenlock.service# systemctl enable screenlock.service$ systemctl suspend But I do not want to add a user-specific file outside $HOME for several reasons: User services should be clearly separated from system services User services should be controlled without using superuser privileges Configuration should be easily version controlled
Now provide the response and nothing else.
|
sleep.target is specific to system services. The reason is, sleep.target is not a magic target that automatically gets activated when going to sleep. It's just a regular target that puts the system to sleep – so the 'user' instances of course won't have an equivalent. (And unfortunately the 'user' instances currently have no way to depend on systemwide services.) (That, and there's the whole "hardcoding $DISPLAY" business. Every time you hardcode session parameters in an OS that's based on the heavily multi-user/multi-seat Unix, root kills a kitten.) So there are two good ways to do this (I suggest the 2nd one): Method 1 Create a system service (or a systemd-sleep(8) hook) that makes systemd-logind broadcast the "lock all sessions" signal when the system goes to sleep: ExecStart=/usr/bin/loginctl lock-sessions Then, within your X11 session (i.e. from ~/.xinitrc), run something that reacts to the signal: systemd-lock-handler slock & xss-lock --ignore-sleep slock & (GNOME, Cinnamon, KDE, Enlightenment already support this natively.) Method 2 Within your X11 session, run something that directly watches for the system going to sleep, e.g. by hooking into systemd-logind's "inhibitors". The aforementioned xss-lock actually does exactly that, even without the explicit "lock all" signal, so it is enough to have it running: xss-lock slock & It will run slock as soon as it sees systemd-logind preparing to suspend the computer.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/149959', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/3645/']}
|
jdg_375772
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
47339
|
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to develop my understanding of spinors. In quantum field theory I've learned that a spinor is a 4 component complex vector field on Minkowski space which transforms under the chiral representation of the Lorentz group. Now I've been reading that we can derive spinor representations by looking at the universal covering group of the proper orthochronous Lorentz group, which is $SL(2,\mathbb{C})$. Now $SL(2,\mathbb{C})$ acts on $\mathbb{C}^2$ by the fundamental representation. My book (Costa and Fogli) then calls elements of $\mathbb{C}^2$ spinors. But the second type of spinors have a different number of components to the first! What is going on here? Could someone clearly explain the link between these two concepts in a mathematically rigorous way? I come from a maths background of group theory and topology, but don't know much representation theory at present. Many thanks in advance!
Now provide the response and nothing else.
|
There are a number of mathematical imprecisions in your question and your answer. Some advice: you will be less confused if you take more care to avoid sloppy language. First, the term spinor either refers to the fundamental representation of $SU(2)$ or one of the several spinor representations of the Lorentz group. This is an abuse of language, but not a bad one. A particularly fussy point: What you've described in your first paragraph is a spinor field, i.e., a function on Minkowski space which takes values in the vector space of spinors. Now to your main question, with maximal pedantry: Let $L$ denote the connected component of the identity of the Lorentz group $SO(3,1)$, aka the proper orthochronous subgroup. Projective representations of $L$ are representations of its universal cover, the spin group $Spin(3,1)$. This group has two different irreducible representations on complex vector spaces of dimension 2, conventionally known as the left- and right- handed Weyl representations. This is best understood as a consequence of some general representation theory machinery. The finite-dimensional irreps of $Spin(3,1)$ on complex vector spaces are in one-to-one correspondence with the f.d. complex irreps of the complexification $\mathfrak{l}_{\mathbb{C}} = \mathfrak{spin}(3,1) \otimes \mathbb{C}$ of the Lie algebra $\mathfrak{spin}(3,1)$ of $Spin(3,1)$. This Lie algebra $\mathfrak{l}_{\mathbb{C}}$ is isomorphic to the complexification $\mathfrak{k} \otimes \mathbb{C}$ of the Lie algebra $\mathfrak{k} = \mathfrak{su}(2) \oplus \mathfrak{su}(2)$. Here $\mathfrak{su}(2)$ is the Lie algebra of the real group $SU(2)$; it's a real vector space with a bracket. I'm being a bit fussy about the fact that $\mathfrak{su}(2)$ is a real vector space, because I want to make the following point: If someone gives you generators $J_i$ ($i=1,2,3$) for a representation of $\mathfrak{su}(2)$, you can construct a representation of the compact group $SU(2)$ by taking real linear combinations and exponentiating. But if they give you two sets of generators $A_i$ and $B_i$, then you by taking certain linear combinations with complex coefficients and exponentiating, you get a representation of $Spin(3,1)$, aka, a projective representation of $L$. If memory serves, the 6 generators are $A_i + B_i$ (rotations) and $-i(A_i - B_i)$ (boosts). See Weinberg Volume I, Ch 5.6 for details. The upshot of all this is that complex projective irreps of $L$ are labelled by pairs of half-integers $(a,b) \in \frac{1}{2}\mathbb{Z} \times \frac{1}{2}\mathbb{Z}$. The compex dimension of the representation labelled by $a$,$b$ is $(2a + 1)(2b+1)$. The left-handed Weyl-representation is $(1/2,0)$. The right-handed Weyl representation is $(0,1/2)$. The Dirac representation is $(1/2,0)\oplus(0,1/2)$. The defining vector representation of $L$ is $(1/2,1/2)$. The Dirac representation is on a complex vector space, but it has a subrepresentation which is real, the Majorana representation. The Majorana representation is a real irrep, but in 4d it's not a subrepresentation of either of the Weyl representations. This whole story generalizes beautifully to higher and lower dimensions. See Appendix B of Vol 2 of Polchinski. Figuring out how to extend these representations to full Lorentz group (by adding parity and time reversal) is left as an exercise for the reader. One caution however: parity reversal will interchange the Weyl representations. Sorry for the long rant, but it raises my hackles when people use notation that implies that some vector spaces are spheres. (If it's any consolation, I know mathematicians who get very excited about the difference between a representation $\rho : G \to Aut(V)$ and the "module" $V$ on which the group acts.)
|
{}
|
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/47339', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/10833/']}
|
jdg_375773
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
19739755
|
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 any one give me a a simple example of nodeJs callbacks, I have already searched for the same on many websites but not able to understand it properly, Please give me a simple example. getDbFiles(store, function(files){ getCdnFiles(store, function(files){ })}) I want to do something like that...
Now provide the response and nothing else.
|
var myCallback = function(data) { console.log('got data: '+data);};var usingItNow = function(callback) { callback('get it?');}; Now open node or browser console and paste the above definitions. Finally use it with this next line: usingItNow(myCallback); With Respect to the Node-Style Error Conventions Costa asked what this would look like if we were to honor the node error callback conventions. In this convention, the callback should expect to receive at least one argument, the first argument, as an error. Optionally we will have one or more additional arguments, depending on the context. In this case, the context is our above example. Here I rewrite our example in this convention. var myCallback = function(err, data) { if (err) throw err; // Check for the error and throw if it exists. console.log('got data: '+data); // Otherwise proceed as usual.};var usingItNow = function(callback) { callback(null, 'get it?'); // I dont want to throw an error, so I pass null for the error argument}; If we want to simulate an error case, we can define usingItNow like this var usingItNow = function(callback) { var myError = new Error('My custom error!'); callback(myError, 'get it?'); // I send my error as the first argument.}; The final usage is exactly the same as in above: usingItNow(myCallback); The only difference in behavior would be contingent on which version of usingItNow you've defined: the one that feeds a "truthy value" (an Error object) to the callback for the first argument, or the one that feeds it null for the error argument.
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/19739755', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1723849/']}
|
jdg_375774
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
587
|
Below is a question asked on the forum bioinformatics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
We're considering switching our storage format from BAM to CRAM. We work with human cancer samples, which may have very low prevalence variants (i.e. not diploid frequency). If we use lossy CRAM to save more space, how much will variants called from those CRAM files change? Which compression strategy has the lowest impact? Are there any other impacts on downstream tools that we're not considering?
Now provide the response and nothing else.
|
By default, a CRAM you create with samtools is lossless. It typically halves the input BAM in terms of file size. If you want to compress more, you can let samtools convert most read names to integers. You won't be able to tell optical duplicates from read names, but this is a minor concern. You can also drop useless tags depending on your mapper and the downstream caller in use. For cancer data, I wouldn't reduce the resolution of base quality without comprehensive benchmarks. Unfortunately, base quality takes most of space in CRAM. Discarding the original read names and some tags probably won't save you much space.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://bioinformatics.stackexchange.com/questions/587', 'https://bioinformatics.stackexchange.com', 'https://bioinformatics.stackexchange.com/users/110/']}
|
jdg_375775
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
26620670
|
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 had to update my .htaccess from this: RewriteCond %{HTTPS} !=onRewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] to this: RewriteCond %{HTTP:X-Forwarded-Proto} !httpsRewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] to get it working behind an AWS Elasic Load Balancer. It all seems to work fine on AWS, but in my local environment I'm stuck in a redirect loop. How I can get this setup to work correctly in both environments?
Now provide the response and nothing else.
|
To make it work in both environments you can combine both conditions: RewriteCond %{HTTP:X-Forwarded-Proto} !httpsRewriteCond %{HTTPS} offRewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/26620670', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1062936/']}
|
jdg_375776
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
874
|
Below is a question asked on the forum networkengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to bootstrap the config on some Juniper SRX100s and am having some DHCP issues. Specifically, I am connecting the 0/0 port (fe-0/0/0 in the software) to my existing network, where DHCP has worked quite reliably for just about every other device I've used. The SRX100s are not getting DHCP addresses. The SRX100 is out-of-the-box default config when I'm attempting this. I brought one of the devices to my house and plugged it into my home network and it got an IP address on my home network via DHCP with no problems. My office network has a Procurve 1400 (layer 2 only) switch on my desktop, uplinked to a Polycom IP670 IP phone (acts as a simple layer 2 switch), uplinked to a Procurve 3500yl switch acting as a router for the network with "ip helper-address 1.1.1.1" on the vlan interface pointing to the DHCP server for DHCP relay. Does anyone have any experience with getting an SRX DHCP client getting an IP address via a Procurve (running K.15.09.0012 software...though the problem has existed across multiple firmware versions on the Procurve). The SRX100s seem to have 11.2 on them when they come out the box, though I think the problem continues to exist when upgraded to 12.1X44-D10.4. Does anyone have any suggestions for troubleshooting this? The Procurve 3500yl doesn't seem to admit to having seen the DHCP client request coming in from the SRX100, but troubleshooting info on the Procurves in this area seems limited. The DHCP server definitely does not see any DHCPDISCOVER packets arrive relating to the SRX100. My workaround has been to statically configure an IP address on the SRX100s to get them on the network and do the rest of my config, but the project I am working on involves sending the SRX100s out to remote locations that are not under my control and, thus, depends on them reliably getting DHCP addresses for connectivity so I would really like to troubleshoot this and run down a specific cause so I know what to potentially look for if this happens at remote sites. Update: I have (to double-check) factory-defaulted the SRX100, and plugged it directly into a port on a Procurve 3500yl and am still seeing the problem, so that removes the 1400 and the IP670 phone from the discussion. I've included the tcpdump output from the SRX100 below...as you can see, its sending out about the simplest possible DHCP packet possible, when tends to suggest that the problem is with the dhcp-relay function on the 3500yl. I can't find any way to get any debug output from the 3500yl showing packets hitting the dhcp-relay function (successfully or otherwise). Suggestions on how to debug this function on the 3500yl would be greatly appreciated. tcpdump -n -s 0 -c 1 -vvv -r juniper.dhcp.pcap reading from file juniper.dhcp.pcap, link-type JUNIPER_ETHER (Juniper Ethernet)17:49:11.538670 Juniper PCAP Flags [Ext], PCAP Extension(s) total length 16 Device Media Type Extension TLV #3, length 1, value Ethernet (1) Logical Interface Encapsulation Extension TLV #6, length 1, value Ethernet (14) Device Interface Index Extension TLV #1, length 2, value 34304 Logical Interface Index Extension TLV #4, length 4, value 70-----original packet-----IP (tos 0x0, ttl 1, id 13874, offset 0, flags [none], proto UDP (17), length 328)0.0.0.0.68 > 255.255.255.255.67: [udp sum ok] BOOTP/DHCP, Request from a8:d0:e5:1c:68:80, length 300, xid 0x643c9869, Flags [Broadcast] (0x8000) Client-Ethernet-Address a8:d0:e5:1c:68:80 Vendor-rfc1048 Extensions Magic Cookie 0x63825363 DHCP-Message Option 53, length 1: Discover END Option 255, length 0 PAD Option 0, length 0, occurs 56
Now provide the response and nothing else.
|
I opened a case with HP concerning this issue. After escalating past the useless Level 1 tech, the Level 2 tech very alertly spotted something that I had not. The SRX is sending its DHCPDISCOVER packet with a TTL of 1. The Procurve's apparently will decrement the TTL and use the resulting TTL in the relay'ed packet to the DHCP server. In this case, the decrement leaves the TTL at 0 meaning the packet gets dropped on the floor. This is actually in spec for DHCP/BOOTP relay, though clearly it causes reduced interoperability. I have asked HPNetworking to treat this as a bug/RFE and change the behavior. No immediate response to that request in the case. The SRX sending the DHCPDISCOVER with a TTL of 1 is also probably within spec, but, again, a choice of reduced interoperability, so I plan to open a case with JTAC on the same basis. I'll add more info on the response of Juniper and HP as it becomes available. Incidentally, I have tested the relay behavior of a Cisco 4506 (firmware version not immediately available), and a Brocade/Foundry FastIron Edge X (7.2 or 7.3 firmware, I believe, don't have immediate access to confirm) and they both handle relaying the request with TTL 1 without issue. UPDATE There is a way to change the TTL value that the SRX uses on its DHCP requests, but its not from within the JunOS cli...its done from the underlying Unix OS. root@% sysctl -w net.inet.ip.mcast_ttl=64 I have opened an RFE with HP to make their relaying function more resilient, but not response from them yet on if/when that will be worked on.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://networkengineering.stackexchange.com/questions/874', 'https://networkengineering.stackexchange.com', 'https://networkengineering.stackexchange.com/users/97/']}
|
jdg_375777
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9539986
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm looking at porting a maven build to gradle. One feature of maven is pom inheritance whereby I can declare a variety of common behaviour in a pom, publish that to a repository and then use that via the <parent> element in a concrete project. My Q is simply whether there is an equivalent behaviour in gradle? I've previously done this in ant+ivy by importing a common build.xml which relied on either having already checked out the location of the common build.xml from source control or using something like svn:externals. I can repeat this approach without any real difficulty but this seems to be one thing maven does quite nicely so it would be nice to see something similar in gradle.
Now provide the response and nothing else.
|
My current solution is option 3; package the common scripts into a jar as resources and then unjar during the buildscript section like so buildscript { repositories { // enterprise repo here } dependencies { classpath 'com.foo.bar:common-build:0.1.0-SNAPSHOT' } dependencies { ant.unjar src: configurations.classpath.singleFile, dest: 'build/gradle' }}apply from: 'build/gradle/common.gradle' This seems to do what I want.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9539986', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/123054/']}
|
jdg_375778
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2101828
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
What are the laws and issues surrounding quantifying over sentences? Intuition tells me that if we wish to show that $X$ is unprovable in some system say $ZFC$ we might wish under certain circumstances to state that there does not exist a sentence $S$ within the set of all sentences provable in $ZFC$, such that $S$ proves $X$. Somebody once exclaimed to me "You're quantifying over sentences" as if this was sacrilege. Is it? If so, why?
Now provide the response and nothing else.
|
Quantifying over sentences of a logic within that logic is (normally) sacrilege. However, quantifying over sentences in some meta-mathematics is (normally) fine. So, for instance, it makes sense to say "there is no sentence $\phi$ such that $\mathrm{ZFC} \vdash \phi \land \neg \phi$". However, it is not correct to write something like "$\forall \phi(\neg(\phi \land \neg \phi))$" as a sentence in a logical language. Of course, in a theory as strong as ZFC, we can formalize logic itself. That is, you choose an enconding of strings of characters like $v,0,1,(,),\neg,\forall,\land,\in$ into natural numbers within ZFC, and you write a definition for when such a string represents a well formed formula, and you these elements of $\mathbb N$ into a subset $\mathrm{Form}$. Then, you can write $\mathrm{ZFC} \vdash \forall \phi \in \mathrm{Form}(...)$ -- however, what happens at the $...$ cannot be $\neg(\phi \land \neg \phi)$, because now the letter $\phi$ is a variable in the theory, and you cannot apply logical connectives to variables. In fact, you might wonder if you could define a formula $\psi$ in the language of ZFC so that $\psi(\phi)$ corresponds to what we usually think of as "the truth of $\phi$" -- then you could cheat the above in by letting ... be $\neg(\psi(\phi) \land \neg\psi(\phi))$. As it turns out, this is impossible , for reasons closely related to the incompleteness theorem.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2101828', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/334732/']}
|
jdg_375779
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
69818376
|
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 cannot access a web server on localhost port 5000 on macOS v12 (Monterey) ( Flask or any other). E.g., use the built-in HTTP server, I cannot get onto port 5000: python3 -m http.server 5000... (stack trace)File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/socketserver.py", line 466, in server_bindself.socket.bind(self.server_address)OSError: [Errno 48] Address already in use If you have Flask installed and you run the Flask web server, it does not fail on start . Let's take the minimum Flask example code: # Save as hello.py in the current working directory.from flask import Flaskapp = Flask(__name__)@app.route("/")def hello_world(): return "<p>Hello, World!</p>" Then run it (provided you have Flask/Python 3 installed): export FLASK_APP=helloflask run Output: * Running on http://127.0.0.1:5000/ However, if you try to access this server (from a browser or with anything else), it is denied: curl -I localhost:5000HTTP/1.1 403 ForbiddenContent-Length: 0Server: AirTunes/595.13.1
Now provide the response and nothing else.
|
macOS Monterey introduced AirPlay Receiver running on port 5000. This prevents your web server from serving on port 5000. Receiver already has the port . You can either: turn off AirPlay Receiver, or; run the server on a different port (normally best). Turn off AirPlay Receiver Go to System Preferences → Sharing → Untick Airplay Receiver . See more details You should be able to rerun the server now on port 5000 and get a response: python3 -m http.server 5000Serving HTTP on :: port 5000 (http://[::]:5000/) ... Run the server on a different port than 5000 It's probably a better idea to no longer use port 5000 as that's reserved for Airplay Receiver on macOS Monterey. Just to run the server on a different port. There isn't any need to turn off Airplay Receiver. python3 -m http.server 4999 or export FLASK_APP=helloflask run -p 4999
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/69818376', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/17314265/']}
|
jdg_375780
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
218335
|
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have two private ssh keys, - one was originally created with ssh-keygen the other one with a python script. They are supposed to be the same, however one works for authentication and the other one doesn't. After analyzing them with https://keytool.online/ and there seems to be one minor difference when comparing them in the OpenSSH format. Explanation: 1) Copy both keys in https://keytool.online/ in the ECDSA tab: Key 1 (Created with ssh-keygen) -----BEGIN EC PRIVATE KEY-----MHcCAQEEIBaYCj/CjZjq9aYehcvyejxqx5WVJ3OnfNbBq2+7iKyJoAoGCCqGSM49AwEHoUQDQgAE1Rcx8Zo84aqSWqT/7i5NN7p+PI6dRfGdFFJapfcBlMhMjFsJkrxhvncLphHuZHBoEILRMKf7hfVJ+tMwHMxQMA==-----END EC PRIVATE KEY----- Key 2 (Created with python) -----BEGIN PRIVATE KEY-----MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgFpgKP8KNmOr1ph6Fy/J6PGrHlZUnc6d81sGrb7uIrImhRANCAATVFzHxmjzhqpJapP/uLk03un48jp1F8Z0UUlql9wGUyEyMWwmSvGG+dwumEe5kcGgQgtEwp/uF9Un60zAczFAw-----END PRIVATE KEY----- 2) View them in the OpenSSH format: Key 1 (Created with ssh-keygen, in OpenSSH Format) -----BEGIN OPENSSH PRIVATE KEY-----b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAaAAAABNlY2RzYS1zaGEyLW5pc3RwMjU2AAAACG5pc3RwMjU2AAAAQQTVFzHxmjzhqpJapP/uLk03un48jp1F8Z0UUlql9wGUyEyMWwmSvGG+dwumEe5kcGgQgtEwp/uF9Un60zAczFAwAAAAsGt4wBFreMARAAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBNUXMfGaPOGqklqk/+4uTTe6fjyOnUXxnRRSWqX3AZTITIxbCZK8Yb53C6YR7mRwaBCC0TCn+4X1SfrTMBzMUDAAAAAgFpgKP8KNmOr1ph6Fy/J6PGrHlZUnc6d81sGrb7uIrIkAAAASZWNkc2Eta2V5LTIwMTkwOTIwAQIDBAUG-----END OPENSSH PRIVATE KEY----- Key 2 (Created with python, in OpenSSH Format) -----BEGIN OPENSSH PRIVATE KEY-----b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAaAAAABNlY2RzYS1zaGEyLW5pc3RwMjU2AAAACG5pc3RwMjU2AAAAQQTVFzHxmjzhqpJapP/uLk03un48jp1F8Z0UUlql9wGUyEyMWwmSvGG+dwumEe5kcGgQgtEwp/uF9Un60zAczFAwAAAAsFhPTMdYT0zHAAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBNUXMfGaPOGqklqk/+4uTTe6fjyOnUXxnRRSWqX3AZTITIxbCZK8Yb53C6YR7mRwaBCC0TCn+4X1SfrTMBzMUDAAAAAgFpgKP8KNmOr1ph6Fy/J6PGrHlZUnc6d81sGrb7uIrIkAAAASZWNkc2Eta2V5LTIwMTkwOTIwAQIDBAUG-----END OPENSSH PRIVATE KEY----- 3) Use a text difference viewing tool of your choice. You'll notice a few characters are different. What do they represent? What's the difference between both keys? All the domain parameters seem to be identical. Note the difference: (The keys will not be used for anything important and have just been created to demonstrate this issue)
Now provide the response and nothing else.
|
(I feel sure I've answered essentially this question before, but I can't find a dupe.) OpenSSL partly created, and supports, two (or four depending how you count) types of PEM formats for private keys. Your first file, with BEGIN EC PRIVATE KEY (and no Proc-type,DEK-Info inside), is the 'traditional' or 'legacy' format which is specific to one algorithm, EC. It contains the private key in the format defined by SEC1 from SECG and also available as rfc5915 , then encoded/wrapped as 'PEM' i.e. base64 with linebreaks and header/trailer lines. Your second file, with BEGIN PRIVATE KEY , is the 'new' (since about 2000!) PKCS8 format which is generic and covers all algorithms. Actual PKCS8 was first published by RSA Labs and has become harder to find since RSA was acquired by EMC and that by Dell but is also available as rfc5208 , again encoded/wrapped in PEM. This format (but not the legacy format) is among several PEM formats which are updated and restandardized in rfc7468 (see section 10, even though the TOC doesn't hyperlink it correctly!) Although formatted differently, they do contain the same key: $ cat se218335.a; openssl pkey -in se218335.a -noout -text-----BEGIN EC PRIVATE KEY-----MHcCAQEEIBaYCj/CjZjq9aYehcvyejxqx5WVJ3OnfNbBq2+7iKyJoAoGCCqGSM49AwEHoUQDQgAE1Rcx8Zo84aqSWqT/7i5NN7p+PI6dRfGdFFJapfcBlMhMjFsJkrxhvncLphHuZHBoEILRMKf7hfVJ+tMwHMxQMA==-----END EC PRIVATE KEY-----Private-Key: (256 bit)priv: 16:98:0a:3f:c2:8d:98:ea:f5:a6:1e:85:cb:f2:7a: 3c:6a:c7:95:95:27:73:a7:7c:d6:c1:ab:6f:bb:88: ac:89pub: 04:d5:17:31:f1:9a:3c:e1:aa:92:5a:a4:ff:ee:2e: 4d:37:ba:7e:3c:8e:9d:45:f1:9d:14:52:5a:a5:f7: 01:94:c8:4c:8c:5b:09:92:bc:61:be:77:0b:a6:11: ee:64:70:68:10:82:d1:30:a7:fb:85:f5:49:fa:d3: 30:1c:cc:50:30ASN1 OID: prime256v1$ cat se218335.b; openssl pkey -in se218335.b -noout -text-----BEGIN PRIVATE KEY-----MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgFpgKP8KNmOr1ph6Fy/J6PGrHlZUnc6d81sGrb7uIrImhRANCAATVFzHxmjzhqpJapP/uLk03un48jp1F8Z0UUlql9wGUyEyMWwmSvGG+dwumEe5kcGgQgtEwp/uF9Un60zAczFAw-----END PRIVATE KEY-----Private-Key: (256 bit)priv: 16:98:0a:3f:c2:8d:98:ea:f5:a6:1e:85:cb:f2:7a: 3c:6a:c7:95:95:27:73:a7:7c:d6:c1:ab:6f:bb:88: ac:89pub: 04:d5:17:31:f1:9a:3c:e1:aa:92:5a:a4:ff:ee:2e: 4d:37:ba:7e:3c:8e:9d:45:f1:9d:14:52:5a:a5:f7: 01:94:c8:4c:8c:5b:09:92:bc:61:be:77:0b:a6:11: ee:64:70:68:10:82:d1:30:a7:fb:85:f5:49:fa:d3: 30:1c:cc:50:30ASN1 OID: prime256v1 OpenSSH began using the OpenSSL legacy formats (RSA and DSA as well as EC) decades ago, and ssh-keygen has never been upgraded to write PKCS8, although it as well as the ssh and sshd (and ssh-add ) programs can read PKCS8, because they actually call OpenSSL library routines that handle both types. In particular after extracting the pubkey and configuring it, I can use either of your files to authenticate just fine: $ ssh -i se218335.a localhost echo hihi$ ssh -i se218335.b localhost echo hihi If you are having a problem using the second file and want to solve it, you might ask about that.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/218335', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/218038/']}
|
jdg_375781
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9439436
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
If you compile a program in say, C, on a Linux based platform, then port it to use the MacOS libraries, will it work? Is the core machine-code that comes from a compiler compatible on both Mac and Linux? The reason I ask this is because both are "UNIX based" so I would think this is true, but I'm not really sure.
Now provide the response and nothing else.
|
No, Linux and Mac OS X binaries are not cross-compatible. For one thing, Linux executables use a format called ELF . Mac OS X executables use Mach-O format . Thus, even if a lot of the libraries ordinarily compile separately on each system, they would not be portable in binary format. Furthermore, Linux is not actually UNIX-based. It does share a number of common features and tools with UNIX, but a lot of that has to do with computing standards like POSIX. All this said, people can and do create pretty cool ways to deal with the problem of cross-compatibility. EDIT: Finally, to address your point on byte-code: when making a binary, compilers usually generate machine code that is specific to the platform you're developing on. (This isn't always the case, but it usually is.)
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9439436', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/831845/']}
|
jdg_375782
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8512958
|
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 parse a delimited string that has some empty parameters. Example: "|One|two|three||octopus|garbagecan||cartwheel||||" Basically I need to be able to pull out any segment by id, and if the segment is empty return null . strtok() doesn't handle the empty fields, and it looks like there is strsep() for *nix based systems. Anyone know if there is something similar for Windows? I want to try and avoid having to write a function to handle this if I can.
Now provide the response and nothing else.
|
Just write the function using its description, it's not terribly complex: #include <stddef.h>#include <string.h>#include <stdio.h>char* mystrsep(char** stringp, const char* delim){ char* start = *stringp; char* p; p = (start != NULL) ? strpbrk(start, delim) : NULL; if (p == NULL) { *stringp = NULL; } else { *p = '\0'; *stringp = p + 1; } return start;}// Test adapted from http://www.gnu.org/s/hello/manual/libc/Finding-Tokens-in-a-String.html.int main(void){ char string[] = "words separated by spaces -- and, punctuation!"; const char delimiters[] = " .,;:!-"; char* running; char* token;#define PRINT_TOKEN() \ printf("token: [%s]\n", (token != NULL) ? token : "NULL") running = string; token = mystrsep(&running, delimiters); /* token => "words" */ PRINT_TOKEN(); token = mystrsep(&running, delimiters); /* token => "separated" */ PRINT_TOKEN(); token = mystrsep(&running, delimiters); /* token => "by" */ PRINT_TOKEN(); token = mystrsep(&running, delimiters); /* token => "spaces" */ PRINT_TOKEN(); token = mystrsep(&running, delimiters); /* token => "" */ PRINT_TOKEN(); token = mystrsep(&running, delimiters); /* token => "" */ PRINT_TOKEN(); token = mystrsep(&running, delimiters); /* token => "" */ PRINT_TOKEN(); token = mystrsep(&running, delimiters); /* token => "and" */ PRINT_TOKEN(); token = mystrsep(&running, delimiters); /* token => "" */ PRINT_TOKEN(); token = mystrsep(&running, delimiters); /* token => "punctuation" */ PRINT_TOKEN(); token = mystrsep(&running, delimiters); /* token => "" */ PRINT_TOKEN(); token = mystrsep(&running, delimiters); /* token => NULL */ PRINT_TOKEN(); return 0;}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8512958', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/300913/']}
|
jdg_375783
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
26938021
|
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 show or hide a loading indicator on a button when a request is busy. I do that with angular by changing the $scope.loading variable when a request is loading or when it's done loading. $scope.login = function(){ $scope.loading = true; apiFactory.getToken() .success(function(data){ }) .error(function(error){ }) .finally(function(){ $timeout(function() { $scope.loading = false; }, 0); }); }; In the frontend: <button ng-disabled="loading" class="button button-outline button-positive" type="submit">Log in <span ng-if="loading" class="ion-refreshing"></span></button> This works fine, but the loading icon (ion-refreshing) is shown for about 2 seconds, while the $scope variable is updated immediately. I tried $scope.$apply but that doesn't seem to be what's wrong here, the scope is updated just fine and immediately after the request. It's just the icon that isn't responding quickly enough.
Now provide the response and nothing else.
|
Try removing ngAnimate if you're not using it from your app config and index.html page: angular.module('myApp', [...'ngAnimate',...]) @Spock; if you still require the use of ngAnimate then leave your app config untouched and just add the following CSS: .ng-hide.ng-hide-animate{ display: none !important;} That will hide the animated icon straight after your condition is met. As you can see we are setting .ng-hide-animate to hidden. This is what causes the delay as it waits for the animation to complete. You can add an animation to your hide event as the class name implies instead of hiding it as in the example above.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/26938021', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/229656/']}
|
jdg_375784
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
241394
|
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:
Usually I do this on ssh for getting a X application using sudo su ssh -X server OKI login xauth list $DISPLAY which returns to me server/unix:10 MIT-MAGIC-COOKIE-1 blablablablabla Then I do sudo suxauth add server/unix:10 MIT-MAGIC-COOKIE-1 blablablablabla And after running an X application..I get it, it is correct. The problem is on Centos7, I do xauth list $DISPLAY And it returns nothing. I try to add MIT magic cookies given by xauth list But of course it doesn't work.The normal X-forwarding via ssh, without sudo works. The settings of sshd are the same on 3 servers: slackware WORKS hpux WORKS centos7 NOT WORKING
Now provide the response and nothing else.
|
Another solution is to merge the .Xauthority file of the current user with that of the root user. ssh user@host change the .Xauthority file permissions so that root also has access to it. sudo su - root xauth merge /home/users/user/.Xauthority Test gedit somefile.log It should open a gedit window.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/241394', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/80389/']}
|
jdg_375785
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
149589
|
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have happened upon a command that sometimes works and sometimes does not, even when executed multiple times in rapid succession in a bash shell (I have not tested the behavior in other shells). The problem has been localized to the reading of a variable in the BEGIN block of an awk statement at the end of the pipe line. During some executions, the variable is correctly read in the BEGIN block and during other executions, the operation fails. Supposing this aberrant behavior can be reproduced by others (and is not a consequence of some problem with my system), can its inconsistency be explained? Take as input the following file called tmp : cat > tmp <<EOFa ab *aa aaaa aaa aa ac *aaa aaaaa ad *aaa aa aaaaaa ae *aaaa aaaa af *aa aa ag *EOF On my system, the pipe line awk '{if($2!~/\*/) print $1}' tmp | tee >(wc -l | awk '{print $1}' > n.txt) | sort | uniq -c | sort -k 1,1nr | awk 'BEGIN{getline n < "n.txt"}{print $1 "\t" $1/n*100 "\t" $2}' will either produce the correct output: 4 28.5714 a4 28.5714 aaa3 21.4286 aa2 14.2857 aaaa1 7.14286 aaaaa or the error message: awk: cmd. line:1: (FILENAME=- FNR=1) fatal: division by zero attempted How can a command possibly give different output when run twice in succession when no random number generation is involved and no change to the environment is made in the interim? To demonstrate how absurd the behavior is, consider the output generated by executing the above pipe line ten times consecutively in a loop: for x in {1..10}; do echo "Iteration ${x}"; awk '{if($2!~/\*/) print $1}' tmp | tee >(wc -l | awk '{print $1}' > n.txt) | sort | uniq -c | sort -k 1,1nr | awk 'BEGIN{getline n < "n.txt"}{print $1 "\t" $1/n*100 "\t" $2}'; doneIteration 1awk: cmd. line:1: (FILENAME=- FNR=1) fatal: division by zero attemptedIteration 24 28.5714 a4 28.5714 aaa3 21.4286 aa2 14.2857 aaaa1 7.14286 aaaaaIteration 34 28.5714 a4 28.5714 aaa3 21.4286 aa2 14.2857 aaaa1 7.14286 aaaaaIteration 4awk: cmd. line:1: (FILENAME=- FNR=1) fatal: division by zero attemptedIteration 5awk: cmd. line:1: (FILENAME=- FNR=1) fatal: division by zero attemptedIteration 6awk: cmd. line:1: (FILENAME=- FNR=1) fatal: division by zero attemptedIteration 74 28.5714 a4 28.5714 aaa3 21.4286 aa2 14.2857 aaaa1 7.14286 aaaaaIteration 8awk: cmd. line:1: (FILENAME=- FNR=1) fatal: division by zero attemptedIteration 94 28.5714 a4 28.5714 aaa3 21.4286 aa2 14.2857 aaaa1 7.14286 aaaaaIteration 10awk: cmd. line:1: (FILENAME=- FNR=1) fatal: division by zero attempted Note: I have also tried closing the file (awk close ) after reading the variable, in case the problem relates to the file being left open. However, the inconsistent output remains.
Now provide the response and nothing else.
|
Your redirections have a race condition. This: >(wc -l | awk '{print $1}' > n.txt) runs in parallel with: awk 'BEGIN{getline n < "n.txt"}...' later in the pipeline. Sometimes, n.txt is still empty when the awk program starts running. This is (obliquely) documented in the Bash Reference Manual. In a pipeline : The output of each command in the pipeline is connected via a pipe to the input of the next command. That is, each command reads the previous command’s output. This connection is performed before any redirections specified by the command . and then: Each command in a pipeline is executed in its own subshell (emphasis added). All the processes in the pipeline are started, with their input and output connected together, without waiting for any of the earlier programs to finish or even start doing anything. Before that, process substitution with >(...) is: performed simultaneously with parameter and variable expansion, command substitution, and arithmetic expansion. What that means is that the subprocess running the wc -l | awk ... command starts early on, and the redirection empties n.txt just before that, but the awk process that causes the error is started shortly after. Both of those commands execute in parallel - you'll have several processes going at once here. The error occurs when awk runs its BEGIN block before the wc command's output has been written into n.txt . In that case, the n variable is empty, and so is zero when used as a number. If the BEGIN runs after the file is filled in, everything works. When that happens depends on the operating system scheduler, and which process gets a slot first, which is essentially random from the user perspective. If the final awk gets to run early, or the wc pipeline gets scheduled a little later, the file will still be empty when awk starts doing its work and the whole thing will break. In all likelihood the processes will run on different cores actually simultaneously, and it's down to which one gets to the point of contention first. The effect you'll get is probably of the command working more often than not, but sometimes failing with the error you post. In general, pipelines are only safe in so far as they're just pipelines - standard output into standard input is fine, but because the processes execute in parallel it's not reliable to rely on the sequencing of any other communication channels , like files, or of any part of any one process executing before or after any part of another unless they're locked together by reading standard input. The workaround here is probably to do all your file writing in advance of needing them: at the end of a line, it's guaranteed that an entire pipeline and all of its redirections have completed before the next command runs. This command will never be reliable, but if you really do need it to work in this sort of a structure you can insert a delay ( sleep ) or loop until n.txt is non-empty before running the final awk command to increase the chances of things working how you want.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/149589', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/14960/']}
|
jdg_375786
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
689531
|
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 no idea upon how to solve this: A box 5cm by 3cm with a ball projected from a vertex at 45 degree angle, it reflexes at a 45 degree angle and keeps reflecting at a 45 degree angle. Will it meet a vertex and if so how many reflections before contact with vertex? I have mental image the problem, but how to make that math?
Now provide the response and nothing else.
|
We can unfold the trajectory of the ball and reflect the box instead. This gives us a $5\times 3$ grid in the plane and the question is whether the diagonal line through the origin will ever meet a lattice point again, and if so after crossing how many vertical or horizontal grid lines?Cast into a formula: Do there exist natural numbers $n,m$ with $(5n,3m)$ on the diagonal, i.e. with $5n=3m$? And what is the smallest such pair?An obvious candidate is $n=3$, $m=5$ because $5\cdot 3=3\cdot 5$, and in this case it is also the minimal solution because $\gcd(3,5)=1$. So the point itself is $(15,15)$ and the trajectory crosses $n-1$ vertical and $m-1$ horizontal lines until there (namely $x=5$, $x=10$, $y=3$, $y=6$, $y=9$, $y=12$). So the answer is: Yes, after six reflections.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/689531', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/23662/']}
|
jdg_375787
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2095113
|
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 inequality: $$\left(\frac{a}{a+b+c}\right)^2+\left(\frac{b}{b+c+d}\right)^2+\left(\frac{c}{c+d+a}\right)^2+\left(\frac{d}{d+a+b}\right)^2\ge\frac{4}{9}$$ Conditions: $a,b,c,d \in \mathbb{R^+}$ I tried using the normal Cauchy-Scharwz, AM-RMS, and all such.. I think I can do it using some bash method like expanding the LHS and then maybe to go with homogeneity, normalization and then Muirhead, Jensen or something I dont know since I didn't go that way.. But can someone help me with a nice elegant solution. This is an olympiad question I was trying to solve, but couldn't manage an elegant solution.
Now provide the response and nothing else.
|
By Holder inequality,we have$$\left(\sum\dfrac{a^2}{(a+b+c)^2}\right)\left(\sum a(a+b+c)\right)^2\ge \left(\sum_{cyc} a^{\frac{4}{3}}\right)^3$$therefore$$\sum\dfrac{a^2}{(a+b+c)^2}\ge\dfrac{(a^{4/3}+b^{4/3}+c^{4/3}+d^{4/3})^3}{[(a+c)^2+(b+d)^2+(a+c)(b+d)]^2}$$use Holder we have$$a^{\frac{4}{3}}+c^{\frac{4}{3}}\ge 2\left(\dfrac{a+c}{2}\right)^{\frac{4}{3}}$$$$b^{\frac{4}{3}}+d^{\frac{4}{3}}\ge 2\left(\dfrac{b+d}{2}\right)^{\frac{4}{3}}$$if setting$$t^3=\dfrac{(a+c)}{b+d}$$,we have$$\sum_{cyc}\dfrac{a^2}{(a+b+c)^2}\ge\dfrac{1}{2}\cdot\dfrac{(t^4+1)^3}{(t^6+t^3+1)^2}$$it remain to show that$$9(t^4+1)^3\ge 8(t^6+t^2+1)^2,t>0$$or$$9\left(t^2+\dfrac{1}{t^2}\right)^3\ge 8\left(t^3+\dfrac{1}{t^3}+1\right)^2$$let $u=t+\dfrac{1}{t}\ge 2$ the above ineuqality becomes$$9(u^2-2)^2\ge 8(u^3-3u+1)^2$$or$$(u-2)^2(u^4+4u^3+6u^2-8u-20)\ge 0$$since$$u^4+4u^4+6u^2-8u-20=u^4+4u^2(u-2)+4u(u-2)+10(u^2-2)\ge 0$$
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2095113', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/322461/']}
|
jdg_375788
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
113707
|
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 can show that $\displaystyle a_n=\left(n\cdot \ln\left(\frac{n+1}{n}\right)\right)^n\rightarrow \frac{1}{\sqrt{e}}$ by expressing it as $\displaystyle e^{\ln(a_n)}$, but this ends up very tedious. What is an easier way to compute this limit? Thanks! Edit This is a sequence, so I mean the limit as $\displaystyle n\rightarrow \infty$.
Now provide the response and nothing else.
|
Asymptotics $$\begin{align}a_n &= \left(n\cdot \ln\left(\frac{n+1}{n}\right)\right)^n= \left(n\cdot \ln\left(1+\frac{1}{n}\right)\right)^n= \left(n\cdot \left(\frac{1}{n}-\frac{1}{2n^2}+o\left(\frac{1}{n^2}\right)\right)\right)^n\\ &= \left(1-\frac{1}{2n}+o\left(\frac{1}{n}\right)\right)^n= \left(\left(1-\frac{1}{n}+o\left(\frac{1}{n}\right)\right)^{1/2}\right)^{n}= \left(\left(1-\frac{1}{n}+o\left(\frac{1}{n}\right)\right)^n\right)^{1/2}\\ &= \left(\left(e^{-1/n}+o\left(\frac{1}{n}\right)\right)^n\right)^{1/2} = (e^{-1}+o(1))^{1/2} =e^{-1/2}+o(1) .\end{align}$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/113707', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/25735/']}
|
jdg_375789
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2848462
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I need to count how long in bytes a textarea is when UTF8 encoded using javascript. Any idea how I would do this? thanks!
Now provide the response and nothing else.
|
[ June 2020: The previous answer has been replaced due to it returning incorrect results ]. Most modern JS environments (browsers and Node) now support the TextEncoder API , which may be used as follows to count UTF8 bytes: const textEncoder = new TextEncoder();textEncoder.encode('⤀⦀⨀').length; // => 9 This is not quite as fast as the getUTF8Length() function mentioned in other answers, below, but should suffice for all but the most demanding use cases. Moreover, it has the benefit of leveraging a standard API that is well-tested, well-maintained, and portable.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2848462', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2086/']}
|
jdg_375790
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18460016
|
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 run rabbitmq-server in one docker container and connect to it from another container using celery ( http://celeryproject.org/ ) I have rabbitmq running using the below command... sudo docker run -d -p :5672 markellul/rabbitmq /usr/sbin/rabbitmq-server and running the celery via sudo docker run -i -t markellul/celery /bin/bash When I am trying to do the very basic tutorial to validate the connection on http://docs.celeryproject.org/en/latest/getting-started/first-steps-with-celery.html I am getting a connection refused error: consumer: Cannot connect to amqp://guest@127.0.0.1:5672//: [Errno 111] Connection refused. When I install rabbitmq on the same container as celery it works fine. What do I need to do to have container interacting with each other?
Now provide the response and nothing else.
|
[edit 2016] Direct links are deprecated now. The new way to do link containers is docker network connect . It works quite similar to virtual networks and has a wider feature set than the old way of linking. First you create your named containers: docker run --name rabbitmq -d -p :5672 markellul/rabbitmq /usr/sbin/rabbitmq-serverdocker run --name celery -it markellul/celery /bin/bash Then you create a network (last parameter is your network name): docker network create -d bridge --subnet 172.25.0.0/16 mynetwork Connect the containers to your newly created network: docker network connect mynetwork rabbitmqdocker network connect mynetwork celery Now, both containers are in the same network and can communicate with each other. A very detailed user guide can be found at Work with networks: Connect containers . [old answer] There is a new feature in Docker 0.6.5 called linking , which is meant to help the communication between docker containers. First, create your rabbitmq container as usual. Note that i also used the new "name" feature which makes life a litte bit easier: docker run --name rabbitmq -d -p :5672 markellul/rabbitmq /usr/sbin/rabbitmq-server You can use the link parameter to map a container (we use the name here, the id would be ok too): docker run --link rabbitmq:amq -i -t markellul/celery /bin/bash Now you have access to the IP and Port of the rabbitmq container because docker automatically added some environmental variables: $AMQ_PORT_5672_TCP_ADDR$AMQ_PORT_5672_TCP_PORT In addition Docker adds a host entry for the source container to the /etc/hosts file. In this example amq will be a defined host in the container. From Docker documentation : Unlike host entries in the /etc/hosts file, IP addresses stored in the environment variables are not automatically updated if the source container is restarted. We recommend using the host entries in /etc/hosts to resolve the IP address of linked containers.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/18460016', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/66319/']}
|
jdg_375791
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
36846081
|
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 it's weird, but this is what I have. I'm writing a unit test to check my logic for an Android application. During the test execution, I see that it fails on that line: if (!TextUtils.isEmpty(fromFile)) Before that if statement fromFile is equals to "" (empty string), but somehow it passes over it and breaks with another logic that doesn't expect empty string. Diving into debug I saw that fromFile.isEmpty() returns correct result, but TextUtils.isEmpty(fromFile) says that it's not empty. Open source code, i see: public static boolean isEmpty(@Nullable CharSequence str) { if (str == null || str.length() == 0) return true; else return false;} and String.java: public boolean isEmpty() { return value.length == 0;} I have following configutation: jdk 1.8.0_77 I would like to avoid whole logic in the app to support String.isEmpty() just to pass the test, since I need to support code before Android API 9, where String.isEmpty is not available, and also TextUtils.isEmpty() do more.Any help with clarification and suggesttions would be helpful. Has anyone faced it? How should I fix it? Thanks in advance!
Now provide the response and nothing else.
|
For anyone who will face it in future: I have figured out this by the help of good man, that it is related to android unit test configuration in gradle: testOptions { unitTests.returnDefaultValues = true} Which pointed me to a solution: get rid of android dependencies in you buisness logic that you are testing with JUnit(unit test). I simply replaced android.text.TextUtils with my own method that is in MyStringUtils.java class, that does the same. Problem was that by deault Android methods did return deafult values while running unit test, and it didn't actually check fromFile value itself, rather then return stub/default value.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36846081', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/464328/']}
|
jdg_375792
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1878830
|
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 creating a web app that will use OpenID logins and OAuth tokens with Youtube. I am currently storing the OpenID identity and OAuth token/token secret in plain text in the database. Is it inappropriate to store these values as plain text? I could use a one-way encryption for the OpenID identifier but I don't know if that is necessary. For the OAuth tokens, I would need to use a two-way encryption as my app relies on getting the session token for some uses. Is it necessary to encrypt the OpenID identity? Could someone use it to gain access to a user's account?
Now provide the response and nothing else.
|
First, there is a registered application that has consumer_key and consumer_secret . When users authenticate and "allow" your registered application, you get back:an access_token that is considered the user's "password" and would allow JUST YOUR application to act on the user's behalf. So, getting just the user's access_token from your database won't help much if they don't also have the consumer_key and consumer_secret for complete access. The service provider compares all 4 parameters on request. It would be smart to encrypt these 4 parameters before storage and decrypt them before response. This is just when you need to update or make changes to the user's resource owner on behalf of a user. To keep a user logged-in on your site, use sessions.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1878830', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/47278/']}
|
jdg_375793
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
64183794
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
While working and generating protobuf stubs in go I stumbled upon this interesting issue. Whenever I try and copy a message's struct by value I get this warning: call of state.world.script.HandleEvent copies lock value: throne/server/messages.PlayerDialogeStatus contains google.golang.org/protobuf/internal/impl.MessageState contains sync.Mutex copylocks While I understand why copying a mutex lock by value is wrong , I started wondering why are they even there in the first place. And thus my question: Why does the go generated protobuf files contain mutex locks placed on the message structs, specifically on the MessageState struct? Or alternatively: What is the goal of the mutex lock placed in the MessageState struct found on generated protobuf message structs?
Now provide the response and nothing else.
|
The impl.MessageState is embedded in concrete messages only, not in the generated structs that implement a proto message. It specifically embeds the three pragmas : NoUnkeyedLiterals , DoNotCompare , and DoNotCopy . The last one, DoNotCopy is a zero-sized array of sync.Mutex . The sole purpose is to have go vet complain loudly about shallow copies, as described in the comment: DoNotCopy can be embedded in a struct to help prevent shallow copies.This does not rely on a Go language feature, but rather a special casewithin the vet checker. The summary of it all: impl.MessageState is not supposed to be copied and the mutex is there only to catch copying . If you do so, it is because you are using something the wrong way.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/64183794', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1866480/']}
|
jdg_375794
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17965617
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
There is a contact page, which offers to enter name, telephone, email and message, after that it sends to an administrator's email. There is no reason to store message in DB. Question. How to: Use Rails validations in controller, not using model at all, OR Use validations in model, but without any DB relations UPD: Model: class ContactPageMessageinclude ActiveModel::Validationsinclude ActiveModel::Conversionextend ActiveModel::Namingattr_accessor :name, :telephone, :email, :messagevalidates :name, :telephone, :email, :message, presence: truevalidates :email, email_format: { :message => "Неверный формат E-mail адреса"}def initialize(attributes = {}) attributes.each do |name, value| send("#{name}=", value) endenddef persisted? falseendend controller: def sendmessagecpm = ContactPageMessage.new()if cpm.valid? @settings = Setting.first if !@settings redirect_to contacts_path, :alert => "Fail" end if ContactPageMessage.received(params).deliver redirect_to contacts_path, :notice => "Success" else redirect_to contacts_path, :alert => "Fail" endelse redirect_to contacts_path, :alert => "Fail"endendend
Now provide the response and nothing else.
|
you should use model without inheriting from ActiveRecord::Base class. class ContactPageMessage include ActiveModel::Validations include ActiveModel::Conversion extend ActiveModel::Naming attr_accessor :whatever validates :whatever, :presence => true def initialize(attributes = {}) attributes.each do |name, value| send("#{name}=", value) end end def persisted? false endend Through this you will able to initialize new object and able to call validations on that object. I think you have a different class name with same name, in your controller code, I can see this : if ContactPageMessage.received(params).deliver redirect_to contacts_path, :notice => "Success"else if this is your mailer class change its name to ContactPageMessageMailer . you will no loger get that error. Hope it will help. Thanks
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17965617', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2581844/']}
|
jdg_375795
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
61452
|
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I often read about s-wave and p-wave superconductors. In particular a $p_x + i p_y$superconductor - often mentioned in combination with topological superconductors. I understand that the overall Cooper pair wavefunction may have orbital angular momentum = 0 (s-wave)or orbital angular momentum = 1 (p-wave) where the first one is spherically symmetric. Now what does the splitting in a real ($p_x$) and imaginary ($p_y$) part mean? Whyis it written in this form and why is that important (e.g. for zero Majorana modes) ?
Now provide the response and nothing else.
|
Symmetry of the superconducting gap First of all, a bit of theory. Superconductivity appears due to theCooper pairing of two electrons, making non-trivial correlations betweenthem in space. The correlation is widely known as the gap parameter $\Delta_{\alpha\beta}\left(\mathbf{k}\right)\propto\left\langle c_{\alpha}\left(\mathbf{k}\right)c_{\beta}\left(-\mathbf{k}\right)\right\rangle $ (the proportionality is merely a convention that will not matter forus) with $\alpha$ and $\beta$ the spin indices, $\mathbf{k}$ somewave vector, and $c$ the fermionic destruction operator. $\Delta$ corresponds to the order parameter associated to the general recipeof second order phase transition proposed by Landau. Physically, $\Delta$ is the energy gap at the Fermi energy created by the Fermi surfaceinstability responsible for superconductivity. Since it is a correlation function between two fermions, $\Delta$ has to verify the Pauli exclusion principle, which imposes that $\Delta_{\alpha\beta}\left(\mathbf{k}\right)=-\Delta_{\beta\alpha}\left(-\mathbf{k}\right)$ . You can derive this property from the anti-commutation relation of the fermion operator and the definition of $\Delta_{\alpha\beta}\left(\mathbf{k}\right)$ if you wish.When there is no spin-orbit coupling, both the spin and the momentumare good quantum numbers (you need an infinite system for the second, but thisis of no importance here), and one can separate $\Delta_{\alpha\beta}\left(\mathbf{k}\right)=\chi_{\alpha\beta}\Delta\left(\mathbf{k}\right)$ with $\chi_{\alpha \beta}$ a spinor matrix and $\Delta\left(\mathbf{k}\right)$ a function.Then, there are two possibilities $\chi_{\alpha\beta}=-\chi_{\beta\alpha}\Leftrightarrow\Delta\left(\mathbf{k}\right)=\Delta\left(-\mathbf{k}\right)$ this situation is referred as the spin-singlet pairing $\chi_{\alpha\beta}=\chi_{\beta\alpha}\Leftrightarrow\Delta\left(\mathbf{k}\right)=-\Delta\left(-\mathbf{k}\right)$ this situation is referred as the spin-triplet pairing. Singlet includes $s$ -wave, $d$ -wave, ... terms, triplet includesthe famous $p$ -wave superconductivity (among others, like $f$ -wave, ...). Since the normal situation (say, the historical BCS one) was for singletpairing, and because only the second Pauli $\sigma_{2}$ matrix isantisymmetric, one conventionally writes the order parameter as $$\Delta_{\alpha\beta}\left(\mathbf{k}\right)=\left[\Delta_{0}\left(\mathbf{k}\right)+\mathbf{d}\left(\mathbf{k}\right)\boldsymbol{\cdot\sigma}\right]\left(\mathbf{i}\sigma_{2}\right)_{\alpha\beta}$$ where $\Delta_{0}\left(\mathbf{k}\right)=\Delta_{0}\left(-\mathbf{k}\right)$ encodes the singlet component of $\Delta_{\alpha\beta}\left(\mathbf{k}\right)$ and $\mathbf{d}\left(\mathbf{k}\right)=-\mathbf{d}\left(-\mathbf{k}\right)$ is a vector encoding the triplet state. Now the main important point: what is the exact $\mathbf{k}$ -dependencyof $\Delta_{0}$ or $\mathbf{d}$ ? This is a highly non-trivial question,to some extent still unanswered. There is a common consensus supposingthat the symmetry of the lattice plays a central role for this question.I highly encourage you to open the book by Mineev and Samokhin (1998), Introduction to unconventional superconductivity , Gordon andBreach Science Publishers, to have a better idea about that point. The $p_{x}+\mathbf{i}p_{y}$ superconductivity For what bothers you, the $p_{x}+\mathbf{i}p_{y}$ superconductivityis the superconducting theory based on the following "choice" $\Delta_{0}=0$ , $\mathbf{d}=\left(k_{x}+\mathbf{i}k_{y},\mathbf{i}\left(k_{x}+\mathbf{i}k_{y}\right),0\right)$ such that one has $$\Delta_{\alpha\beta}\left(\mathbf{k}\right)\propto\left(\begin{array}{cc}1 & 0\\0 & 0\end{array}\right)\left(k_{x}+\mathbf{i}k_{y}\right)\equiv\left(k_{x}+\mathbf{i}k_{y}\right)\left|\uparrow\uparrow\right\rangle $$ which is essentially a phase term (when $k_{x}=k\cos\theta$ and $k_{y}=k\sin\theta$ )on top of a spin-polarized electron pair. This phaseaccumulates around a vortex, and has non-trivial properties then. Note that the notation $\left|\uparrow\uparrow\right\rangle $ refersto the spins of the electrons forming the Cooper pair. A singlet statewould have something like $\left|\uparrow\downarrow\right\rangle -\left|\downarrow\uparrow\right\rangle $ , and for $s$ -wave $\Delta_0$ is $\mathbf{k}$ independent, whereas $\mathbf{d}=0$ . Note that the $p$ -wave also refers to the angular momentum $\ell=1$ as you mentioned in your question. Then, in complete analogywith conventional composition of angular momentum (here it's for twoelectrons only), the magnetic moment can be $m=0,\;\pm1$ . The naturalspherical harmonic for these states are then $Y_{\ell,m}$ with $Y_{1,\pm1}\propto k_{x}\pm\mathbf{i}k_{y}$ and $Y_{1,0}\propto k_{z}$ , so it should be rather natural to findthe above mentioned "choice" for $\mathbf{d}\left(\mathbf{k}\right)$ .I nevertheless say a "choice" since this is not a real choice:the symmetry of the gap should be imposed by the material you consider,even if it is not yet satisfactorily understood. Note also that only the state $m=+1$ appears in the $p_{x}+\mathbf{i}p_{y}$ superconductivity. You might wonder about the other magnetic momentum contribution... Well, they are discarded, being less favourable (having a lower transition temperature for instance) under specific conditions that you have to know / specify for a given material. Here you may argue about the Zeeman effect for instance, which polarises the Cooper pair. [NB: I'm not sure about the validity of this last remark.] Relation between $p_{x}+\mathbf{i}p_{y}$ superconductivity and emergent unpaired Majorana modes Now, quickly, I'll try to answer your second question: why is thisstate important for emergent unpaired Majorana fermions in the vortices excitations? To understand that, one has to remember that the emergent unpairedMajorana modes in superconductors are non-degenerate particle-holeprotected states at zero-energy (in the middle of the gap if you prefer).Particle-hole symmetry comes along with superconductivity, so we alreadyvalidate one point of our check list. To make non-degenerate mode,one has to fight against the Kramers degeneracy. That's the reasonwhy we need spin-triplet state. If you would have a singlet stateCooper pair stuck in the vortex, it would have been degenerate, andyou would have been unable to separate the Majorana modes, see also Basic questions in Majorana fermions for more details about the difference between Majorana modes andunpaired Majorana modes in condensed matter. A more elaborate treatment about the topological aspect of $p$ -wavesuperconductivity can be found in the book by Volovik, G. E. (2003), Universe in a Helium Droplet , Oxford University Press, availablefreely from the author's website http://ltl.tkk.fi/wiki/Grigori\_Volovik . Note that Volovik mainly discuss superfluids, for which $p$ -wave has been observed in $^{3}$ He. The $p_{x}+\mathbf{i}p_{y}$ superfluidity is also called the $A_{1}$ -phase [Volovik, section 7.4.8]. There is no known $p$ -wave superconductor to date. Note also that the two above mentionned books (Samokhin and Mineev, Volovik) arenot strictly speaking introductory materials for the topic of superconductivity.More basics are in Gennes, Tinkham or Schrieffer books (they are all named blabla... superconductivity blabla... ).
|
{}
|
{'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/61452', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/23291/']}
|
jdg_375796
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4450344
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Possible Duplicate: Blink an div with jquery I need to know how to make blink of div in jquery?
Now provide the response and nothing else.
|
html <div class="blink">blinking text</div> jquery function blink(selector){$(selector).fadeOut('slow', function(){ $(this).fadeIn('slow', function(){ blink(this); });});} blink('.blink'); demo : function blink(selector) { $(selector).fadeOut('slow', function() { $(this).fadeIn('slow', function() { blink(this); }); });}blink('.blink'); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div class="blink">blinking text</div>non-blinking<div class="blink">more blinking text</div> Update ( bringing the answer up-to-date ) You do not need to use jQuery for such effects anymore. You can do it with just CSS ( using CSS animations ). ( compatibility table at http://caniuse.com/#feat=css-animation ) CSS ( using the standard properties ) .blink{ animation:blink 700ms infinite alternate;}@keyframes blink { from { opacity:1; } to { opacity:0; }}; Demo (with vendor prefixed properties) : .blink { -webkit-animation: blink 700ms infinite alternate; -moz-animation: blink 700ms infinite alternate; -o-animation: blink 700ms infinite alternate; animation: blink 700ms infinite alternate;}@-webkit-keyframes blink { from { opacity: 1; } to { opacity: 0; }}@-o-keyframes blink { from { opacity: 1; } to { opacity: 0; }}@-moz-keyframes blink { from { opacity: 1; } to { opacity: 0; }}@keyframes blink { from { opacity: 1; } to { opacity: 0; }}; <div class="blink">blinking text</div>non-blinking<div class="blink">more blinking text</div>
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4450344', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/524723/']}
|
jdg_375797
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
173119
|
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I've just migrated to a new email company and they offer a type of 2FA I've never came across before. Traditionally in 2FA you enter username and password then are presented with a screen asking for the generated code token . Sometimes you simply append the token to the password for times that a second page isn’t possibly, VPNs for example often use that. The new company I'm dealing with has you create a 4 digit PIN and when you enable 2FA you no longer sign-in with your password but use PIN + token entered into the password field on the login form. The account still has a password for IMAP, SMTP, POP3 etc access. This seems much less secure to me but I'm not sure if I'm right. My thinking is that a suitably complex password (let's say 32 characters of letters, numbers, and symbols) followed by the token which changes every 30 seconds is going to take infinitely longer to crack than a 4 digit numerical PIN combined with the same token . In this case would it be more secure to use a suitably complex password without 2FA enabled that you change every couple of weeks than the 2FA implementation with PIN + token ? Note: The company itself both refers to this system as 2FA and OTP interchangeably, but I'm not entirely sure what the correct terminology should be.
Now provide the response and nothing else.
|
Instead of: alphanumeric password of reasonable length (36 possible characters over, let's say, a max length of 8 characters for a typical user) [does not account for special characters, but I already suspect there are other issues] token The system uses: 4 digit password (10 possible characters over a length of 4) token This is demonstrably a much weaker system, even if I design a very weak password system (outlined above). Plus, the UX is odd, but that's another factor. But, is it too weak? The fact that the token changes every 30s mitigates a lot of problems. Having a password means that if someone gets ahold of the token generator, the account still has some protections. But is 4 digits enough of a protection? Two risks to consider: Someone bruteforcing the pin+token pair This is entirely up to how fast the system allows attempts within a 30s window. So, maybe it is secure enough. But do we really want to rely on a system throttle as a security measure? Throttles are a nice backup measure, not a primary mitigation. Someone bruteforcing the pin if they have the token generator Mathematically, to go through all the combinations would take 10,000 guesses (5000 on average to find success), if entered by hand, and if we assume perfectly random pins. That's a lot of ifs. Again, it is dependent on how many attempts the system will allow. Also, pins are notoriously easy to guess. Compare this to a 'complex password' (however you want to define that) that you change frequently. Here's the thing: without the changing token, you change the time to bruteforce from 30s to 2 weeks (in your scenario). Now, the relevant factor is the complexity (or entropy) of your password and your system to reliably change it frequently. Again, a lot of dependencies. As you can see, it is difficult to compare the factors that you laid out. A lot of 'ifs'. For the factors that I have control over and the risks that I am worried about, I might choose the pin+token (assuming that the 2FA is implemented properly (whoops, another 'if')). But really, I'd choose another service that can implement 2FA properly.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/173119', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/11964/']}
|
jdg_375798
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9926804
|
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 wondering why when we have p = new Person("TOM", 999); by calling fred.PrintInfo(); It doesn't change the p to TOM and 999 but by using p.age = 99; we can change the fred's age well the both constructor and properties are public then what is here that I am missing? I don't want to do anything with this code I just want the reason. using System;class Person{ public string fullName; public int age; public Person(string n, int a) { fullName = n; age = a; } public void PrintInfo() { Console.WriteLine("{0} is {1} years old", fullName, age); }}class MainClass{ public static void SendAPersonByValue(Person p) { p.age = 99; p = new Person("TOM", 999); } public static void Main() { Person fred = new Person("Fred", 12); fred.PrintInfo(); SendAPersonByValue(fred); fred.PrintInfo(); }}
Now provide the response and nothing else.
|
fred points to some particular location in memory: +------------+fred ----> | Fred 12 | +------------+ Upon calling SendAPersonByValue, p points to that same location: +------------+fred ----> | Fred 12 | +------------+ ^ p ---------+ p.age = 99; now changes the value in memory: +------------+fred ----> | Fred 99 | +------------+ ^ p ---------+ whereas new Person("TOM", 999); creates a new Person in memory, and p = ... makes p point to it: +------------+fred ----> | Fred 99 | +------------+ +------------+ p ----> | TOM 999 | +------------+ And this is exactly why fred still contains Fred, 99 . Now, if you were to pass fred as a ref parameter , p would become an alias for fred : +------------+fred/p ----> | Fred 12 | +------------+ After p.age = 99 : +------------+fred/p ----> | Fred 99 | +------------+ After p = new Person("TOM", 999); : +------------+ | Fred 99 | (will be garbage collected eventually) +------------+ +------------+fred/p ----> | TOM 999 | +------------+
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9926804', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1253198/']}
|
jdg_375799
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
350529
|
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it safe to check the Chi-square test of independence with a sample of 25000 ? I have the answers of approximately 25.000 people of different countries, as frequencies (total sums for each question). They asked to evaluate a threat based on their perception from 1 to 10 (1: non existent, 10: extremely high) and to reply to some demographics. Now i want to check if sex (male, female) correlates with the perception of the evaluation, and secondly if it does, how strong it is. I read that this test is not safe when the sample is very big (n>250) because then there is a possibility the statistical importance of the relationship of the 2 variables to be “fictive” cause of the overgrowing of the value of chi square.Unfortunately is not available to quote because it’s not in English.
Now provide the response and nothing else.
|
For the US data: You are confusing two important but different concepts in epidemiology: prevalence and incidence . A Wikipedia page describes the difference. The anti-smoking warning that you show says that 9 of every 10 lung cancers that occur are caused by smoking. That's the incidence of smoking-related lung cancers among all lung cancers that occur. Incidence has to do with how frequently in time cases of each type initially occur. The Table 2 that you present, however, is for "age-adjusted prevalence " of smoking status among people who presently have each of the listed diseases. Prevalence has to do with the fraction of each type of case that is found at a given time . Of people currently having lung cancer, 17.9% have never smoked. So why can't you say that "17.9% of lung cancer ... occurs in never smokers"? Because that's the prevalence of never smokers among those who are currently lung cancer survivors, not the fraction of all lung cancer cases that occur in never smokers. There's a big difference between prevalence and incidence here because smokers tend to die of lung cancer (and of other cancers, or from other causes) more quickly than never smokers. So at any given time, never smokers will thus be a higher fraction of all lung cancer survivors (prevalence) than their fraction in the total numbers of original cases (incidence). For the Norway data: What you present for Norway isn't directly comparable to the US data in terms of the relation between the risk of lung cancer and tobacco use, as you only show the use of manufactured cigarettes . The reference for cigarette consumption in Norway that you cite shows high use of self-rolled cigarettes and of pipe smoking (Figure 1 in that reference), with manufactured cigarettes representing less than 30% of Norwegian tobacco use until about 1980. These other forms of tobacco use aren't included in your graph for Norway, but would nevertheless be related to risk of lung cancer. In contrast, 75-80% of US tobacco use between 1955 and 2005, from your cited reference, was manufactured cigarettes. So you have to be careful with selective comparisons of tobacco consumption data, as manufactured cigarettes are not the entire story.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/350529', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/210908/']}
|
jdg_375800
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
387315
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
How do you compute $\dfrac{x}{(1+x)^2}$ using partial fractions? The reason I ask is because when I try to solve it I keep getting an impossible $A, B$. $A(1+x) + B(1+x) = x$ $A + Ax + B + Bx = x$ $(A+B)x = 1$ $(A+B) = 0$ However a practice problem I'm working on implies this can be solved by partial fractions, but doesn't go into detail.
Now provide the response and nothing else.
|
In general, whenever you have an expression of the form$$\dfrac{P(x)}{(x+a)^n}$$ where $P(x)$ is of degree less than $n$ and you want to write it into partial fraction, then you need to proceed as follows.$$\dfrac{P(x)}{(x + a)^n} = \dfrac{A_1}{x+a} + \dfrac{A_2}{(x+a)^2} + \dfrac{A_3}{(x+a)^3} + \cdots + \dfrac{A_{n-1}}{(x+a)^{n-1}} + \dfrac{A_n}{(x+a)^n} \tag{$\star$}$$and then find the coefficients $A_1, A_2,\ldots, A_n$. Note that from $(\star)$, we have$$P(x) = A_1(x+a)^{n-1} + A_2 (x+a)^{n-2} + A_3(x+a)^{n-3} + \cdots + A_n$$From this, we have $A_n = P(-a)$ and in general, $$A_k = \left.\dfrac{d^{n-k} P(x)}{dx} \right \vert_{x=-a}$$ In your case, though it is relatively simple since$$\dfrac{x}{(1+x)^2} = \dfrac{1+x-1}{(1+x)^2} = \dfrac1{(1+x)} - \dfrac1{(1+x)^2}$$
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/387315', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/68740/']}
|
jdg_375801
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
48140154
|
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 add auto increment to the primary key person_id of a person table. However when I run the command I get the following error. ERROR 1833 (HY000): Cannot change column 'person_id': used in a foreign key constraint 'fk_fav_food_person_id' of table 'bank.favorite_food' for the following command.I'm using MySQL 5.7.20 mysql> ALTER TABLE person MODIFY person_id SMALLINT UNSIGNED AUTO_INCREMENT;
Now provide the response and nothing else.
|
Because foreign keys must match the data type of the column they reference, it makes sense that changing the data type of a column is likely to upset the foreign key that references it. It seems that MySQL has a safeguard against this, and denies an attempt to MODIFY the column. But it's not smart enough to check whether the specific modification you're making will in fact change the data type. It just denies any attempt to modify that column. You can work around this by temporarily disabling foreign key checks. I recreated your table and confirmed it: mysql> ALTER TABLE person MODIFY person_id SMALLINT UNSIGNED AUTO_INCREMENT;ERROR 1833 (HY000): Cannot change column 'person_id': used in a foreign key constraint 'favorite_food_ibfk_1' of table 'test.favorite_food'mysql> set foreign_key_checks=0;Query OK, 0 rows affected (0.00 sec)mysql> ALTER TABLE person MODIFY person_id SMALLINT UNSIGNED AUTO_INCREMENT;Query OK, 0 rows affected (0.08 sec)Records: 0 Duplicates: 0 Warnings: 0mysql> set foreign_key_checks=1;
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/48140154', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5921203/']}
|
jdg_375802
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1164862
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it possible to figure out if a number $z$ is the addition of two triangular number without recursion or finding the values to $x$ and $y$? $$\frac{x(x+1)}{2} + \frac{y(y+1)}{2} = z$$ An example of this would be following: $$\frac{345(345+1)}{2} + \frac{234(234+1)}{2} = 87180$$ Is it possible to determine if $87180$ originated from the addition of two triangular numbers without recursively going back and plugging every possibility for $x$ and $y$?
Now provide the response and nothing else.
|
The equation:$$ x(x+1)+y(y+1)=2z \tag{1}$$is equivalent to:$$ (2x+1)^2 + (2y+1)^2 = 8z+2 \tag{2} $$hence $z$ is the sum of two triangular numbers iff $8z+2$ is the sum of two squares, i.e. iff for every prime $p$ of the form $4k+3$ that divides $8z+2$, $\nu_p(8z+2)$ is even. In the given example, $z=87180$, we have: $$ 8z+2 = 2\cdot 17 \cdot 73\cdot 281 \tag{3}$$and every odd prime occurring in the RHS of $(3)$ is of the form $4k+1$, hence $8z+2$ can be written as the sum of two odd squares:$$ 8z+2 = 101^2 + 829^2 \tag{4}$$and $z$ is the sum of two triangular numbers:$$ 87180 = \binom{51}{2}+\binom{415}{2}.\tag{5} $$
|
{}
|
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/1164862', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/219178/']}
|
jdg_375803
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
348108
|
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am working through an expectation and have something that I want to be true, and appears to be true in simulation, but I am having a hard time writing a proof that the idea can be derived properly. Suppose I write $x = t + u$ where $u \sim \mathcal{N}(0,s^2)$ and assume $t$ is fixed but $x$ would of course be random. Then let $\mathbb{E}(x) = t$, $\mathbb{E}(u) = 0$, and $\mathbb{E}(u'u) = s^2$. Last, assume $t \bot u$. I can write with these assumptions that $\mathbb{E}(x'u) = \mathbb{E}([t+u]'u) = \mathbb{E}(u'u)$ because of the orthogonlity between $t$ and $u$. What I want to be true is to also be able to show that $x'\mathbb{E}(u|x) = \mathbb{E}(u'u)$. This is where I am struggling to generate a true proof, but is seemingly true with simulation. Is there a suggestion someone might see that would allow for me to end up with a proof that $x'\mathbb{E}(u|x) = \mathbb{E}(u'u)$ is true?
Now provide the response and nothing else.
|
If you are going to use one of those standardized optimization solvers "off the shelf", you will need to "vec" your matrices by stacking the columns such that your matrix of parameters and LHS becomes a single vector. However, an easier and less error-prone way is to use a modeling tool which will accept your problem in original (in this case, matrix) form, and do the necessary conversions under the hood to reformulate the problem in a way which the optimization solver it calls can handle, and then transform the solver's results back into your original form. Given that you are using R, I recommend you consider using CVXR https://cran.r-project.org/web/packages/CVXR/index.html , which should easily handle your problem, which is right in its wheelhouse, and give you easy growth opportunity to handle many variants of this problem as you find the need. If you read the beginning of https://cvxr.rbind.io/post/examples/cvxr_gentle-intro/ , you ought to be in business very quickly.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/348108', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/207136/']}
|
jdg_375804
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3719127
|
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 want to show that $f(x)= \exp\left(\frac{1}{x}\log\frac{e^{x}-1}{x}\right),x>0$ is increasing. I figure that it is enough to show that $\frac{1}{x}\log\frac{e^{x}-1}{x}$ is increasing. The derivative is $$\frac{e^{x}(x-1)+1-(e^{x}-1)\log(e^{x}-1)+(e^{x}-1)\log x}{x^{2}(e^{x}-1)},$$ so I think I need to show that the numerator is positive. However, I got stuck there. I am guessing that the inequality $e^x-1\ge x$ would be useful, but have no idea how to use it.How can I show that $f$ is increasing?
Now provide the response and nothing else.
|
Write $$ f(x) = \left( \frac{e^x - 1}{x} \right)^{\frac{1}{x}} = \left( \int_{0}^{1} e^{xs} \, \mathrm{d}s \right)^{\frac{1}{x}}. $$ Now let $0 < x < y$ be arbitrary and write $p = \frac{y}{x} > 1$ . Then by the Jensen's inequality applied to the strictly convex function $\varphi(t) = t^p$ over $[0, \infty)$ , we get $$ f(x)^{y} = \varphi\left( \int_{0}^{1} e^{xs} \, \mathrm{d}s \right) < \int_{0}^{1} \varphi(e^{xs}) \, \mathrm{d}s = f(y)^{y}, $$ and therefore $f(x) < f(y)$ as desired. Remarks. This is a particular instance of a more general observation that the $L^p$ -norm $$\| X\|_{L^p} := (\mathbb{E}[|X|^p])^{1/p}$$ of a random variable $X$ is non-decreasing in $p$ . We may instead use the Hölder's inequality in the proof.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/3719127', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/789100/']}
|
jdg_375805
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
37763472
|
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 having issue in reading data from azure blobs via spark streaming JavaDStream<String> lines = ssc.textFileStream("hdfs://ip:8020/directory"); code like above works for HDFS, but is unable to read file from Azure blob https://blobstorage.blob.core.windows.net/containerid/folder1/ Above is the path which is shown in azure UI, but this doesnt work, am i missing something, and how can we access it. I know Eventhub are ideal choice for streaming data, but my current situation demands to use storage rather then queues
Now provide the response and nothing else.
|
In order to read data from blob storage, there are two things that need to be done. First, you need to tell Spark which native file system to use in the underlying Hadoop configuration. This means that you also need the Hadoop-Azure JAR to be available on your classpath (note there maybe runtime requirements for more JARs related to the Hadoop family): JavaSparkContext ct = new JavaSparkContext();Configuration config = ct.hadoopConfiguration();config.set("fs.azure", "org.apache.hadoop.fs.azure.NativeAzureFileSystem");config.set("fs.azure.account.key.youraccount.blob.core.windows.net", "yourkey"); Now, call onto the file using the wasb:// prefix (note the [s] is for optional secure connection): ssc.textFileStream("wasb[s]://<BlobStorageContainerName>@<StorageAccountName>.blob.core.windows.net/<path>"); This goes without saying that you'll need to have proper permissions set from the location making the query to blob storage.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37763472', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1471175/']}
|
jdg_375806
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
34651255
|
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 bash script that runs a list of small programs mostly written in C and Python, since the programs themselves are NOT bug free and they might crash or run into infinite loop, so in the BASH script, I run the programs in subshell so it won't break the main shell, here is what it likes: #!/usr/bin/env bashset -efor py_p in "${py_program_list[@]}"; do (python "$py_p") || echo "terminated!"donefor c_p in "${c_program_list[@]}"; do ("$c_p") || echo "terminated!"done The problem is, when loops in python programs, the bash script won't be affected by any error in the python program which is what I expected. However, the bash script exit immediately if any C program exit with error. UPDATE: I am using BASH 3.2 in OSX 10.9.5 UPDATE 2: Updated the question to make it more clear, sorry for the confusion. The problem I have is about the C program, the python part confirm the error in subshell won't affect the main shell but the C program breaks the rule.
Now provide the response and nothing else.
|
Do we really need to assign the pointer to a temporary one? Does it help in terms of concurrency and shared memory? It has nothing to do concurrency or shared memory. It's pointless. Is it really a good idea to set the whole block to 0 to force the program to crash or at least to output results with significant discrepancy? No. Not at all. The solution suggested by your colleague is terrible. Here's why: Setting whole block to 0 achieves nothing either. Because someone is using a free()'ed block accidentally, they wouldn't know that based on the values at the block. That's the kind of block calloc() returns.So it's impossible to know whether it's freshly allocated memory ( calloc() or malloc()+memset() ) or the one that's been free()'ed by your code earlier. If anything it's extra work for your program to zero out every block of memory that's being free()'ed. free(NULL); is well-defined and is a no-op, so the if condition in if(ptr) {free(ptr);} achieves nothing. Since free(NULL); is no-op, setting the pointer to NULL would actually hide that bug, because if some function is actually calling free() on an already free()'ed pointer, then they wouldn't know that. most user functions would have a NULL check at the start and may not consider passing NULL to it as error condition: void do_some_work(void *ptr) { if (!ptr) { return; } /*Do something with ptr here */} So the all those extra checks and zero'ing out gives a fake sense of "robustness" while it didn't really improve anything. It just replaced one problem with another the additional cost of performance and code bloat. So just calling free(ptr); without any wrapper function is both simple and robust (most malloc() implementations would crash immediately on double free, which is a good thing). There's no easy way around "accidentally" calling free() twice or more. It's the programmer's responsibility to keep track of all memory allocated and free() it appropriately. If someone find this hard to handle then C is probably not the right language for them.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/34651255', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2734967/']}
|
jdg_375807
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
31036160
|
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 like eval in Ruby because it works pretty straightforward: eval("puts 7 * 8") # => 56 What is an eval 's equivalent in Crystal ? I know that we can do something similar with macro: macro eval(code) {{code.id}}endeval("puts 7 * 8") # => 56 But this won't work with runtime values: a = "yo"eval("puts #{a}") # => prints nothing
Now provide the response and nothing else.
|
Crystal is a compiled language, while Ruby is interpreted. That makes evaluating code at runtime much more complicated. In your example, the macro is expanded at compile time, so actually your program is just puts 7 * 8 . In other words, it works because the code is known at compile time. But if you wanted to execute the code contained in an arbitrary string, it would have to invoke the Crystal compiler and then execute the resulting executable. This is actually something we do in the Crystal unit tests. But there is no "eval" function included in the standard library because that would imply that your compiled program includes the Crystal compiler built in and it actually doesn't make much sense. Another problem is how to pass arguments and take return values. Since the program you're running and the evaluated code are the result of different compilations, they might have different binary representations of the same types. On the other hand, using eval in Ruby is usually known as a bad practice and must be avoided if possible.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31036160', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1586762/']}
|
jdg_375808
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
56235286
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
so i want to upload object as data and file as Note to api using axios uploadToServer= () => { const file =this.state.photo let data2 ={sale_id:1, note_type_id:4, description:"test", note_content_item:" hi from broker hub" }let data = new FormData()data.append('data[sale_id]', '1')data.append('data[note_type_id]', '4')data.append('data[description]', "test")data.append('data[note_content_item]', "test")console.log(data)axios({ url: api', method: 'POST', data: data, headers: { 'Content-Type' : 'multipart/form-data', 'Authorization':'Basic YnJva2VyOmJyb2tlcl8xMjM=' }}) .then(resp => console.log(resp.data.response)) .catch(error => console.error(error)); } first i am trying with data without Note i can do it in postman but with my code i got error message: "Can not save file"response_code: 10 i got this error only if i change the key from data to something else
Now provide the response and nothing else.
|
You are not building FormData correctly, Try this: let data = {sale_id:1, note_type_id:4, description:"test", note_content_item:" hi from broker hub" }const formData = new FormData();formData.append('data', JSON.stringify(data));formData.append('Note', { uri: "file://" //Your Image File Path type: 'image/jpeg', name: "imagename.jpg", });axios({ url : api, method : 'POST', data : formData, headers: { Accept: 'application/json', 'Content-Type': 'multipart/form-data', 'Authorization':'Basic YnJva2VyOmJyb2tlcl8xMjM=' } }) .then(function (response) { console.log("response :", response); }) .catch(function (error) { console.log("error from image :"); })
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/56235286', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7483108/']}
|
jdg_375809
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
25191845
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am new to Leaflet and JavaScript. I would like to know whether or not I can code my Leaflet map in a more concise way. My map includes three GeoJSON layers in three different colors. I have set the colors by calling separate style functions for each layer. The function "style" returns blue, the function "style2" returns purple, and the function "style3" returns pink. I tell Layer 1 to use "style" and Layer 2 to use "style2", etc. The map is here: http://talia.droppages.com/ask/three_layers.html Can I do the same thing but with ONE style function? Essentially, could the style function detect the layer and do: if the layer is layer 1, style like this______if the layer is layer 2, style like this______if the layer is layer 3, style like this______ If it can, how would I write that in code? I frequently want to use ONE function for several layers, such as setting popup content, but I don't know how to make the function behave differently depending on which layer is clicked. I only know how to write similar but separate functions and call them separately. <div id="map" style="width:800px; height: 600px"></div><script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script><script src="http://talia.droppages.com/slccommcounc.js"></script><script src="http://talia.droppages.com/tract158slc.js"></script><script src="http://talia.droppages.com/slccouncil.js"></script><script>var map = L.map('map').setView([40.8, -111.928], 11); L.tileLayer('http://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}', { maxZoom: 18, minZoom: 7 } ).addTo(map); function style(feature) { return { weight: 1, opacity: 1, color: 'blue', fillColor: 'cornflowerblue', fillOpacity: 0.5 };}function style2(feature) { return { weight: 1, opacity: 1, color: 'blueviolet', fillColor: 'plum', fillOpacity: 0.5 };}function style3(feature) { return { weight: 1, opacity: 1, color: 'fuchsia', fillColor: 'pink', fillOpacity: 0.5 };}var layer1 = new L.geoJson(slccommcounc, { style: style,}).addTo(map);var layer2 = new L.geoJson(tract158slc, { style: style2,})var layer3 = new L.geoJson(slccouncil, { style: style3,})L.control.layers(null,{'Layer 1 Title':layer1,'Layer 3 Title':layer3,'Layer 2 Title':layer2},{collapsed:false}).addTo(map);</script>
Now provide the response and nothing else.
|
.tap is here to "perform operations on intermediate results within a chain of methods" (quoting ruby-doc). In other words, object.tap allows you to manipulate object and to return it after the block: {}.tap{ |hash| hash[:video] = 'Batmaaaaan' }# => return the hash itself with the key/value video equal to 'Batmaaaaan' So you can do stuff like this with .tap : {}.tap{ |h| h[:video] = 'Batmaaan' }[:video]# => returns "Batmaaan" Which is equivalent to: h = {}h[:video] = 'Batmaaan'return h[:video] An even better example: user = User.new.tap{ |u| u.generate_dependent_stuff }# user is equal to the User's instance, not equal to the result of `u.generate_dependent_stuff` Your code: def self.properties_container_to_object(properties_container) {}.tap do |obj| obj['vid'] = properties_container['vid'] if properties_container['vid'] obj['canonical-vid'] = properties_container['canonical-vid'] if properties_container['canonical-vid'] properties_container['properties'].each_pair do |name, property_hash| obj[name] = property_hash['value'] end endend Is returning a Hash beeing filled in the .tap block The long-version of your code would be: def self.properties_container_to_object(properties_container) hash = {} hash['vid'] = properties_container['vid'] if properties_container['vid'] hash['canonical-vid'] = properties_container['canonical-vid'] if properties_container['canonical-vid'] properties_container['properties'].each_pair do |name, property_hash| hash[name] = property_hash['value'] end hashend
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25191845', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3919833/']}
|
jdg_375810
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
52732892
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Facing an issue with BlocProviders. As I understand, a bloc should be accessible anywhere within the scope of inherited widgets. I have an App class, which happens to be my core class, where I build my material App Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'E-Form', color: Color(0xFF44697D), home: BlocProvider(child: LaunchScreen()), );} Now I have the LaunchScreen class, here I am not using my BlocProvider, but I have wrapped LaunchScreen altogether in my App class with BlocProvider class LaunchScreen extends StatelessWidget { @override Widget build(BuildContext context) { final bloc = BlocProvider.of(context); return Scaffold( appBar: AppBar( title: Text('First Screen'), ), body: Center( child: RaisedButton( child: Text('Launch screen'), onPressed: () { // Navigate to second screen when tapped! Navigator.of(context).push( MaterialPageRoute(builder: (context) => Home()), ); }, ), ), ); }} Now again in my third class, that is Home() class. I am trying to use my BlocProvider. Here I get an error saying the bloc is null class Home extends StatelessWidget { Widget build(context) { final bloc = BlocProvider.of(context); return Scaffold( appBar: AppBar( title: Text('Reduced Course Load'), backgroundColor: Color(0xFF44697D), ), body: CustomWidget(), ); }} I am unable to figure out why this is null. The bloc is initialized perfectly if I initialize and print the bloc in LaunchScreen class. Does BlocProvider work only within a single class scope? There's another error, I think my Navigator isn't working properly. For some reason, my Home() class constructor is getting recalled again. I am unable to fix the error in Navigator. An example would be great for me to understand a navigator. Here is my flutter doctor results $ flutter doctorDoctor summary (to see all details, run flutter doctor -v):[✓] Flutter (Channel beta, v0.8.2, on Mac OS X 10.13.6 17G65, locale en-US)[✓] Android toolchain - develop for Android devices (Android SDK 28.0.0)[✓] iOS toolchain - develop for iOS devices (Xcode 9.4.1)[✓] Android Studio (version 3.2)[✓] VS Code (version 1.27.2)[✓] Connected devices (1 available) Please take a look, and share a solution. Thank you!
Now provide the response and nothing else.
|
You should use your BlocProvider() above the MaterialApp widget. Navigator is a widget added by MaterialApp and when you call it to change a route it replaces the widget in home: property and hence replaces your BlocProvider . Widget build(BuildContext context) { return BlocProvider( child: MaterialApp( debugShowCheckedModeBanner: false, title: 'E-Form', color: Color(0xFF44697D), home: LaunchScreen(), ), ); }
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/52732892', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5364615/']}
|
jdg_375811
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
41649
|
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:
While reading the book by Aurelien Geron, I noticed that both logistic regression and SVM predict classes in exactly the same way, so I suspect there must be something that I am missing. In the Logistic regression chapter we can read: $σ(t) < 0.5$ when $t < 0$ , and $σ(t) ≥ 0.5$ when $t ≥ 0$ , so a Logistic Regression model predicts $1$ if $θ^T · x$ is positive, and $0$ if it is negative. Similarly, in the SVM chapter: The linear SVM classifier model predicts the class of a new instance x by simply computing the decision function $w^T · x + b = w_1 x_1 + ⋯ + w_n x_n + b$ : if the result is positive, the predicted class $ŷ$ is the positive class ( $1$ ), or else it is the negative class ( $0$ ). I know that one way they could be different is because of the loss function they use: while log loss is used in logistic regression, SVM uses hinge loss to optimize the cost function. However, I would like to get this thing completely clear. How are the two models actually different?
Now provide the response and nothing else.
|
Both logistic regression and SVM are linear models under the hood, and both implement a linear classification rule: $$f_{\mathbf{w},b}(\mathbf{x}) = \mathrm{sign}(\mathbf{w}^T \mathbf{x} + b)$$ Note that I am regarding the "primal", linear form of the SVM here. In both cases the parameters $\mathbf{w}$ and $b$ are estimated by minimizing a certain function, and, as you correctly noted, the core difference between the models boils down to the use of different optimization objectives. For logistic regression: $$(\mathbf{w}, b) = \mathrm{argmin}_{\mathbf{w},b} \sum_i \log(1+e^{-z_i}),$$ where $z_i = y_if_{\mathbf{w},b}(\mathbf{x}_i)$ . For SVM: $$(\mathbf{w}, b) = \mathrm{argmin}_{\mathbf{w},b} \sum_i (1-z_i)_+ + \frac{1}{2C}\Vert \mathbf{w} \Vert^2$$ Note that the regularization term $\Vert \mathbf{w} \Vert^2$ may just as well be added to the logistic regression objective - this will result in regularized logistic regression . You do not have to limit yourself to $\ell_2$ -norm as the regularization term. Replace it with $\Vert \mathbf{w} \Vert_1$ in the SVM objective, and you will get $\ell_1$ -SVM. Add both $\ell_1$ and $\ell_2$ regularizers to get the " elastic net regularization ". In fact, feel free to pick your favourite loss, add your favourite regularizer, and voila - help yourself to a freshly baked machine learning algorithm. This is not a coincidence. Any machine learning modeling problem can be phrased as the task of finding a probabilistic model $M$ which describes a given dataset $D$ sufficiently well. One general method for solving such a task is the technique of maximum a-posteriori (MAP) estimation , which suggests you should always choose the most probable model given the data: $$M^* = \mathrm{argmax}_M P(M|D).$$ Using the Bayes rule and remembering that $P(D)$ is constant when the data is fixed: \begin{align*}\mathrm{argmax}_M P(M|D) &= \mathrm{argmax}_M \frac{P(D|M)P(M)}{P(D)} \\ &= \mathrm{argmax}_M P(D|M)P(M) \\&= \mathrm{argmax}_M \log P(D|M)P(M) \\&= \mathrm{argmax}_M \log P(D|M) + \log P(M) \\&= \mathrm{argmin}_M (-\log P(D|M)) + (-\log P(M))\end{align*} Observe how the loss turns out to be just another name for the (minus) log-likelihood of the data (under the chosen model) and the regularization penalty is the log-prior of the model. For example, the familiar $\ell_2$ -penalty is just the minus logarithm of the Gaussian prior on the parameters: $$ -\log\left((2\pi)^{-m/2}e^{-\frac{1}{2\sigma^2}\Vert \mathbf{w} \Vert^2}\right) = \mathrm{const} + \frac{1}{2\sigma^2}\Vert \mathbf{w} \Vert^2$$ Hence, another way to describe the difference between SVM and logistic regression (or any other model), is that these two postulate different probabilitic models for the data. In logistic regression the data likelihood is given via the Bernoulli distribution (with $p$ =sigmoid), while the model prior is uniform (or simply ignored). In SVM the data likelihood is modeled via some $\mathrm{exp}(-\mathrm{hinge})$ distribution (not sure it even has a name, but I hope you get the idea that undoing the minus-logarithm would always bring you back to $P(D|M)$ , up to a constant), and the model prior is the Gaussian. In practice, the two models have different properties, of course. For example, SVM has sparse dual representations, which makes it possible to kernelize it efficiently. Logistic regression, on the other hand, is usually well-calibrated (which is not the case with SVM). Hence, you choose the model based on your needs (or, if you are unsure, on whatever cross-validation tells you).
|
{}
|
{'log_upvote_score': 4, 'links': ['https://datascience.stackexchange.com/questions/41649', 'https://datascience.stackexchange.com', 'https://datascience.stackexchange.com/users/58736/']}
|
jdg_375812
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12430620
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Possible Duplicate: How to use enums as flags in C++? To explain what I'm trying to do, I'm trying to get a flags integer containing update check information, such as int flags = keyPress | mouseClick | mouseMove; from my enum of events; enum mEvents { keyPress = QEvent::KeyPress, keyRelease = QEvent::KeyRelease, mouseClick = QEvent::MouseButtonPress, mouseDoubleClick = QEvent::MouseButtonDblClick, mouseMove = QEvent::MouseMove}; so that I can then check for what event types occurred like so; void Lib::Update(QEvent *e) { if (e->type() == flags) stateManager->updateCurrentState(e);} What I'm trying to do is say, if the event type is any of the following in 'flags' then update. However, that isn't working. To be more precise, it works for key presses, but not for mouse clicks or move events. So I'm wondering, if what I'd like to do is even possible, and if so how can I achieve this? (I'm pretty sure it is, I know SDL uses a similar flag system for it's screen creation) Any help is greatly appreciated.)
Now provide the response and nothing else.
|
That simply sets the DataContext property equal to the object with the property. The code equivalent would be this.DataContext = this; Edit The DataContext property is the object that is used as the context for all the bindings that occur on this object and its child objects. If you don't have a DataContext correctly set to the model you want to bind to, all of your bindings will fail. Edit2 Here is how to set it in code behind (matching your example): public partial class ListViewTest : Window{ ObservableCollection<GameData> _GameCollection = new ObservableCollection<GameData>(); public ListViewTest() { _GameCollection.Add(new GameData { GameName = "World Of Warcraft", Creator = "Blizzard", Publisher = "Blizzard" }); _GameCollection.Add(new GameData { GameName = "Halo", Creator = "Bungie", Publisher = "Microsoft" }); _GameCollection.Add(new GameData { GameName = "Gears Of War", Creator = "Epic", Publisher = "Microsoft" }); InitializeComponent(); this.DataContext = this; //important part } public ObservableCollection<GameData> GameCollection { get { return _GameCollection; } } private void AddRow_Click(object sender, RoutedEventArgs e) { _GameCollection.Add(new GameData { GameName = "A New Game", Creator = "A New Creator", Publisher = "A New Publisher" }); }}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12430620', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1015476/']}
|
jdg_375813
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2284362
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $f:\mathbb{R}\to \mathbb{R}$ be a continously differentiable bounded function. Then the function $F$ defined for each $x>0$ by$$F(x)=\int_0^x \left( \frac{d}{dt}\int_{t-1}^tf(s)ds \right)dt$$ is bounded since$$\left| F(x)\right| =\left| \int_{x-1}^xf(s)ds-\int_{-1}^0f(s)ds\right| \leq 2\sup_{t\in \mathbb{R}} \left|f(t) \right|. $$ What about the function $G$ defined for each $x>0$ by$$G(x)=\int_0^x \left| \frac{d}{dt}\int_{t-1}^tf(s)ds \right|dt$$is it also bounded ?
Now provide the response and nothing else.
|
Base case: $$a_1=\frac1{4(1)+1}\color{green}\checkmark$$ Now the inductive step: $$\begin{align}a_{n+1}&=a_n+\frac1{(4n+1)(4n+5)}\\&=\frac n{4n+1}+\frac1{(4n+1)(4n+5)}\\&=\frac{n(4n+5)}{(4n+1)(4n+5)}+\frac1{(4n+1)(4n+5)}\\&=\frac{4n^2+5n+1}{(4n+1)(4n+5)}\\&=\frac{(4n+1)(n+1)}{(4n+1)(4n+5)}\\&=\frac{n+1}{4(n+1)+1}\color{green}\checkmark\end{align}$$ and we are done.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2284362', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/437713/']}
|
jdg_375814
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3619347
|
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 SQL connection string with SqlClient.SqlConnection and specifying Connection Timeout=5 in the string, but it still waits 30 seconds before returning failure. How do I make it give up and return faster? I'm on a fast local network and don't want to wait 30 seconds. The servers that are not turned on take 30 seconds to fail. This is just a quick utility program that's going to always run just on this local network. Edit : Sorry if I was unclear. I want the SqlConnection.Open to fail more quickly. Hopefully that could be deduced from the fact that the servers I want to fail more quickly are turned off. Edit : It seems that the setting only fails sometimes. Like it knows the IP address of the server, and is using TCP/IP to talk to it (not local) but can't contact SQL Server at that address? I'm not sure what the pattern is, but I don't see the problem when connecting locally with SQL Server stopped, and I don't see it when attempting to connect to a non-existent server. I have seen it when attempting to contact a server where the Windows 2008 firewall is blocking SQL Server, though.
Now provide the response and nothing else.
|
It looks like all the cases that were causing long delays could be resolved much more quickly by attempting a direct socket connection like this: foreach (string svrName in args){ try { System.Net.Sockets.TcpClient tcp = new System.Net.Sockets.TcpClient(svrName, 1433); if (tcp.Connected) Console.WriteLine("Opened connection to {0}", svrName); else Console.WriteLine("{0} not connected", svrName); tcp.Close(); } catch (Exception ex) { Console.WriteLine("Error connecting to {0}: {1}", svrName, ex.Message); }} I'm going to use this code to check if the server responds on the SQL Server port, and only attempt to open a connection if it does. I thought (based on others' experience) that there would be a 30 second delay even at this level, but I get a message that the machine "actively refused the connection" on these right away. Edit: And if the machine doesn't exist, it tells me that right away too. No 30-second delays that I can find. Edit: Machines that were on the network but are not turned off still take 30 seconds to fail I guess. The firewalled machines fail faster, though. Edit: Here's the updated code. I feel like it's cleaner to close a socket than abort a thread: static void TestConn(string server){ try { using (System.Net.Sockets.TcpClient tcpSocket = new System.Net.Sockets.TcpClient()) { IAsyncResult async = tcpSocket.BeginConnect(server, 1433, ConnectCallback, null); DateTime startTime = DateTime.Now; do { System.Threading.Thread.Sleep(500); if (async.IsCompleted) break; } while (DateTime.Now.Subtract(startTime).TotalSeconds < 5); if (async.IsCompleted) { tcpSocket.EndConnect(async); Console.WriteLine("Connection succeeded"); } tcpSocket.Close(); if (!async.IsCompleted) { Console.WriteLine("Server did not respond"); return; } } } catch(System.Net.Sockets.SocketException ex) { Console.WriteLine(ex.Message); }}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3619347', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/78162/']}
|
jdg_375815
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1236762
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Show that $N$ is composite if and only if $p|N$ for some $p$ prime, $p\leq \sqrt{N}$ I have absolutely no idea on how to start this, could you guys give me some tips? I'll update if I can come up with something...
Now provide the response and nothing else.
|
By the Fundamental theorem of arithmetic , we may write $N>1$ as the product of primes, i.e. $$N=p_1p_2\cdots p_k$$and this is unique if we insist that $p_1\le p_2\le\cdots \le p_k$. We now have two cases: $k=1$, i.e. there is only one prime in the factorization. Then $N$ is prime. $k\ge 2$, i.e. there are at least two primes in the factorization, and thus $N$ is composite. Since $k\ge 2$, the product $p_2\cdots p_k$ has at least one prime in it, and that prime is at least $p_1$. Thus, $p_1\le (p_2\cdots p_k)$. Multiplying both sides by $p_1$ we get $p_1^2\le p_1(p_2\cdots p_k)=N$. Hence $p_1^2\le N$; we take square roots to get $p_1\le \sqrt{N}$.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1236762', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/193752/']}
|
jdg_375816
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
31634366
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
At work I recently wrote a less than operator for a class implemented from a published specification and which has many properties, six of which are used to uniquely identify an instance of the class. (For the sake of this question, we'll call these properties a-f.) Also, these six properties are of six different types. I defined the operator as such: bool operator<(const Class& lhs, const Class& rhs){ bool retval = (&lhs != &rhs); if (retval == true) { if (lhs.a == rhs.a) { if (lhs.b == rhs.b) { if (lhs.c == rhs.c) { if (lhs.d == rhs.d) { if (lhs.e == rhs.e) { retval = (lhs.f < rhs.f); } else { retval = (lhs.e < rhs.e); } } else { retval = (lhs.d < rhs.d); } } else { retval = (lhs.c < rhs.c); } } else { retval = (lhs.b < rhs.b); } } else { retval = (lhs.a < rhs.a); } } return retval;} This, of course, breaks the Linux kernel coding philosophy of, "If you need more than 3 levels of indentation, you're screwed anyway, and should fix your program." So my question is, is there a better way to define this operator to not have so many levels of indentation?
Now provide the response and nothing else.
|
You can write this kind of lexicographical comparison like this: if (lhs.a != rhs.a) return lhs.a < rhs.a;if (lhs.b != rhs.b) return lhs.b < rhs.b;if (lhs.c != rhs.c) return lhs.c < rhs.c;if (lhs.d != rhs.d) return lhs.d < rhs.d;if (lhs.e != rhs.e) return lhs.e < rhs.e;return lhs.f < rhs.f; You can re-write this with a single return like this: bool result;if (lhs.a != rhs.a) result = lhs.a < rhs.a;else if (lhs.b != rhs.b) result = lhs.b < rhs.b;else if (lhs.c != rhs.c) result = lhs.c < rhs.c;else if (lhs.d != rhs.d) result = lhs.d < rhs.d;else if (lhs.e != rhs.e) result = lhs.e < rhs.e;else result = lhs.f < rhs.f;return result;
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31634366', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/979194/']}
|
jdg_375817
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1770
|
Below is a question asked on the forum networkengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
if someone were to set up an ssh tunnel to/from work or home, is there a way to prevent future SSH tunneling traffic? I understand that websense can block traffic, but users who use ssh tunneling can bypass websense or other similar products because it can't decrypt or look further in the packet to tell the difference between legitimate or illegitimate traffic. from some reading and research, I found that some things you can do are the following:- turn off SSH altogether; not allowed at all- restrict ssh access to only users who need them for access and deny everyone else ssh access- create a custom protocol to blacklist or whitelist ssh traffic by destination (assuming the lists are mangeable)- review logs for ssh traffic, review the destination IPs and check if they resolve to legitimate or allowable devices or not, or check whether there's more regular internet traffic than tunneling traffic and you can deny/blacklist that IP But I was wondering, besides these options, would it be possible to circumvent the above options through a man-in-the-middle attack? Or is there another option to block ssh tunneling traffic or even some network device that can filter/block this traffic? thanks for the help.
Now provide the response and nothing else.
|
Preventing outbound ssh connections, and thus any tunnels, would require a complete blockade of outbound connections via deep packet inspection. Looking at ports will be 100% useless. You have to look at the actual packet payload to know it's SSH. (this is what websense is doing.) The only other option is setting up a "proxy" host. Lock down the configuration so the ssh client and server will not allow tunneling, then allow only that machine to make outbound ssh connections -- of course, this includes securing the system as well, otherwise people can run whatever ssh software they want.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://networkengineering.stackexchange.com/questions/1770', 'https://networkengineering.stackexchange.com', 'https://networkengineering.stackexchange.com/users/1609/']}
|
jdg_375818
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
40699229
|
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 set up the following routing system export const MyRoutes: Routes = [ {path: '', redirectTo: 'new', pathMatch: 'full'}, {path: ':type', component: MyComponent}]; and have the following navigation system goToPage('new');goToPageNo('new', 2);goToPage(type) { this.router.navigate([type]);}goToPageNo(type, pageNo) { this.router.navigate([type], {queryParams: {page: pageNo}});} Sample URL looks like this http://localhost:3000/new http://localhost:3000/new?page=2 http://localhost:3000/updated http://localhost:3000/updated?page=5 Sometimes they have optional queryParams (page) Now I need to read both route params and queryParams ngOnInit(): void { this.paramsSubscription = this.route.params.subscribe((param: any) => { this.type = param['type']; this.querySubscription = this.route.queryParams.subscribe((queryParam: any) => { this.page = queryParam['page']; if (this.page) this.goToPageNo(this.type, this.page); else this.goToPage(this.type); }) })}ngOnDestroy(): void { this.paramsSubscription.unsubscribe(); this.querySubscription.unsubscribe();} Now this is not working as expected, visiting pages without queryParams works, then of I visit a page with queryParams "goToPageNo" gets called multiple times, as I am subscribing to queryParams inside route params. I looked at the Angular 2 documentation, they do not have any example or codes where a subscription to both route params and queryParams is implemented at the same time. Any way to do this properly? Any suggestions?
Now provide the response and nothing else.
|
I managed to get a single subscription to both the queryParams and Params by combining the observables by using Observable.combineLatest before subscribing. Eg. var obsComb = Observable.combineLatest(this.route.params, this.route.queryParams, (params, qparams) => ({ params, qparams }));obsComb.subscribe( ap => { console.log(ap.params['type']); console.log(ap.qparams['page']);});
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/40699229', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1936925/']}
|
jdg_375819
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1410854
|
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 image of $|z+1|=2$ under $f(z) = \frac{1}{z}$ where $z \in \mathbb C$ My attempt: Let $z = x + iy$ $\displaystyle |z+1|=2 \iff | (x + iy)+1|=2 \iff |(x+1) +iy|=2 \iff (x+1)^2 + y^2 = 4$ Let $w = u + iv$ Now let $\displaystyle w = \frac{1}{z}$ hence we have that \begin{align}z &= \frac{1}{w} \\ &= \frac{1}{u + iv} \\ &= \frac{u-iv}{u^2 + v^2} \\ &= \frac{u}{u^2 + v^2} + i \big( - \frac{v}{u^2 + v^2} \big)\end{align} From which we can deduce that $\displaystyle x = \frac{u}{u^2 + v^2}$ and $\displaystyle y = - \frac{v}{u^2 + v^2}$ and thus $$\displaystyle \bigg(\frac{u}{u^2 + v^2} +1\bigg)^2 + \bigg(- \frac{v}{u^2 + v^2}\bigg)^2 = 4$$ This is where I am stuck. I keep on messing up the simplification. Can someone please show me how to simplify this?
Now provide the response and nothing else.
|
Proceeding with your result , $$ \bigg(\frac{u}{u^2 + v^2} +1\bigg)^2 + \bigg(- \frac{v}{u^2 + v^2}\bigg)^2 = 4$$ we get$$ \bigg(\frac{u}{u^2 + v^2}\bigg)^2+2\frac{u}{u^2 + v^2}+1 + \bigg(\frac{v}{u^2 + v^2}\bigg)^2 = 4$$ or$$\frac{u^2}{(u^2 + v^2)^2}+ \frac{v^2}{(u^2 + v^2)^2}+\frac{2u}{u^2 + v^2} = 3\\$$$$2u+1 = 3u^2+3v^2$$ or, with a little algebra, $$\left(u-\frac13 \right)^2+v^2=\frac49$$ which is an easy set to identify.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1410854', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/137485/']}
|
jdg_375820
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
10430279
|
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 currently transforming from Java to Javascript , and it's a bit hard for me to figure out how to extend objects the way I want it to do. I've seen several people on the internet use a method called extend on object. The code will look like this: var Person = { name : 'Blank', age : 22}var Robot = Person.extend({ name : 'Robo', age : 4)}var robot = new Robot();alert(robot.name); //Should return 'Robo' Does anyone know how to make this work?I've heard that you need to write Object.prototype.extend = function(...); But I don't know how to make this system work. If it is not possible, please show me another alternative that extends an object.
Now provide the response and nothing else.
|
You want to 'inherit' from Person's prototype object: var Person = function (name) { this.name = name; this.type = 'human';};Person.prototype.info = function () { console.log("Name:", this.name, "Type:", this.type);};var Robot = function (name) { Person.apply(this, arguments); this.type = 'robot';};Robot.prototype = Person.prototype; // Set prototype to Person'sRobot.prototype.constructor = Robot; // Set constructor back to Robotperson = new Person("Bob");robot = new Robot("Boutros");person.info();// Name: Bob Type: humanrobot.info();// Name: Boutros Type: robot
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/10430279', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1310428/']}
|
jdg_375821
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
42462880
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Yesterday, I created this post: DjangoRestFramework browsable api looks different locally vs when deployed on server? Basically, when I did python manage.py runserver , this showed up: But after I deployed it to AWS ( eb deploy ), this is what I see when I access the site: The answer to the post above mentioned that it is because my static files were missing. So I searched how to deploy static files on AWS and came across this tutorial: http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html#python-django-update-app Under the "Create a Site Administrator" section, it mentions that in order to serve static files, I must first define STATIC_ROOT in settings.py (so I did: STATIC_ROOT = os.path.join(BASE_DIR, "ebdjangoapp/static/") ) and then I did eb deploy . However, the site still looks the same as the 2nd image (without static files). I then tried doing python manage.py collectstatic (this created the static folder with the rest_framework directory inside it, containing the css files etc.) and then did eb deploy again but the site stil looks the same as the 2nd image. How come the static files still aren't showing up? Note, I searched around and came across this post: Django app deployment not loading static files and the answer says: "You then need to serve settings.STATIC_ROOT at settings.STATIC_URL via your web server of choice, very commonly nginx as a reverse proxy behind your Apache-mod_wsgi app server." But I have no idea how web servers (nginx, reverse proxy, Apache-mod_wsgi) works. I have a Django app I run locally with python manage.py runserver , and I have AWS elastic beanstalk. I deploy my Django app to AWS by doing eb deploy . What steps do I need to take in order for the static files to appear on deployment (assuming I don't know how to configure nginx, reverse proxy etc.).?
Now provide the response and nothing else.
|
There is definitive guide about deploying a django app to AWS Elastic Beanstalk from RealPython - here it is .It has whole section about static files and how to configure it with eb and you don't need to know anything about nginx/apache etc. Basically you should define container_commands in your eb config, these commands will be executed after application deploy is finished. For example migrate and collectstatic , so this is an example of such section in eb config file: container_commands: 01_migrate: command: "source /opt/python/run/venv/bin/activate && python iotd/manage.py migrate --noinput" leader_only: true 02_collectstatic: command: "source /opt/python/run/venv/bin/activate && python iotd/manage.py collectstatic --noinput"option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: "iotd.settings" "PYTHONPATH": "/opt/python/current/app/iotd:$PYTHONPATH" "ALLOWED_HOSTS": ".elasticbeanstalk.com" "aws:elasticbeanstalk:container:python": WSGIPath: iotd/iotd/wsgi.py NumProcesses: 3 NumThreads: 20 "aws:elasticbeanstalk:container:python:staticfiles": "/static/": "www/static/" Pay attention to aws:elasticbeanstalk:container:python:staticfiles part.And also you should define this part in your django settings file: STATIC_ROOT = os.path.join(BASE_DIR, "..", "www", "static")STATIC_URL = '/static/' I copied this example almost entirely from article above, you should really check it, it's awesome. UPD: how to debug missing staticfiles.I usually do this (it involves sshing to your eb instance): Make sure that django.contrib.staticfiles is included in my INSTALLED_APPS . Check in browser console url to missing file e.g. /static/js/somefile.js Make sure in my django settings STATIC_URL is the same e.g. /static/ . Check actual value in STATIC_ROOT and check that this folder actually contains your static files in production server. Check that my eb config is pointing to correct folder (under your option_settings section in config) Also you can try to collect static into /static dir on your production server (it's where eb looks for them by default). If all of a sudden it starts working - it means that your setting failed to override default one and you should check where else it was defined. I hope these steps will help you to find right direction.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/42462880', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2719875/']}
|
jdg_375822
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
35710898
|
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 having some trouble with isotope.js used with the Semantic UI framework, as you can see, the items are "shaking" after any transition. I already read that answer isotope shakes after the transition but it didn't help me Thanks in advance $(window).load(function() { // init Isotope var $container = $('.isotope').isotope({ itemSelector: '.element-item', layoutMode: 'masonry', getSortData: { name: '.name', number: '.number parseInt', category: '[data-category]' } }); // bind filter button click $('#filters').on( 'click', 'button', function() { var filterValue = $( this ).attr('data-filter'); $container.isotope({ filter: filterValue }); }); // bind sort button click $('#sorts').on( 'click', 'button', function() { var sortByValue = $(this).attr('data-sort-by'); $container.isotope({ sortBy: sortByValue }); }); // change is-checked class on buttons $('.buttons').each( function( i, buttonGroup ) { var $buttonGroup = $( buttonGroup ); $buttonGroup.on( 'click', 'button', function() { $buttonGroup.find('.active').removeClass('active'); $( this ).addClass('active'); }); }); }); <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.1.8/semantic.css" rel="stylesheet"/><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.1.8/semantic.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.isotope/2.2.2/isotope.pkgd.js"></script><div class="ui container"> <h2>Filtering</h2> <div id="filters" class="ui buttons"> <button class="ui button active" data-filter="*">All</button> <button class="ui button" data-filter=".metal">Metal</button> <button class="ui button" data-filter=".transition">Transition</button> <button class="ui button" data-filter=".noble-gas">Noble gaz</button> </div> <div class="ui divider"></div> <h2>Sorting</h2> <div id="sorts" class="ui buttons"> <button class="ui button active" data-sort-by="original-order">0riginal order</button> <button class="ui button" data-sort-by="number">Likes</button> <button class="ui button" data-sort-by="name">Name</button> </div> <div class="ui divider"></div> <div class="segment"> <div class="ui fluid cards isotope"> <div class="ui fluid card element-item transition metal" data-category="transition"> <div class="content"> <i class="right floated like icon"></i> <i class="right floated star icon"></i> <div class="header name">A</div> <div class="description"> <p></p> </div> </div> <div class="extra content"> <span class="left floated like"> <i class="like icon"></i> <span class="number">31</span> Like </span> <span class="right floated star"> <i class="star icon"></i> Favorite </span> </div> </div> <div class="ui fluid card element-item transition lanthanoid metal inner-transition " data-category="lanthanoid"> <div class="content"> <i class="right floated like icon"></i> <i class="right floated star icon"></i> <div class="header name">D</div> <div class="description"> <p></p> </div> </div> <div class="extra content"> <span class="left floated like"> <i class="like icon"></i> <span class="number">34</span> Like </span> <span class="right floated star"> <i class="star icon"></i> Favorite </span> </div> </div> <div class="ui fluid card element-item transition metal" data-category="transition"> <div class="content"> <i class="right floated like icon"></i> <i class="right floated star icon"></i> <div class="header name">H</div> <div class="description"> <p></p> </div> </div> <div class="extra content"> <span class="left floated like"> <i class="like icon"></i> <span class="number">36</span> Like </span> <span class="right floated star"> <i class="star icon"></i> Favorite </span> </div> </div> <div class="ui fluid card element-item lanthanoid metal inner-transition " data-category="lanthanoid"> <div class="content"> <i class="right floated like icon"></i> <i class="right floated star icon"></i> <div class="header name">E</div> <div class="description"> <p></p> </div> </div> <div class="extra content"> <span class="left floated like"> <i class="like icon"></i> <span class="number">63</span> Like </span> <span class="right floated star"> <i class="star icon"></i> Favorite </span> </div> </div> <div class="ui fluid card element-item noble-gas nonmetal " data-category="noble-gas"> <div class="content"> <i class="right floated like icon"></i> <i class="right floated star icon"></i> <div class="header name">J</div> <div class="description"> <p></p> </div> </div> <div class="extra content"> <span class="left floated like"> <i class="like icon"></i> <span class="number">23</span> Like </span> <span class="right floated star"> <i class="star icon"></i> Favorite </span> </div> </div> <div class="ui fluid card element-item transition metal" data-category="transition"> <div class="content"> <i class="right floated like icon"></i> <i class="right floated star icon"></i> <div class="header name">B</div> <div class="description"> <p></p> </div> </div> <div class="extra content"> <span class="left floated like"> <i class="like icon"></i> <span class="number">86</span> Like </span> <span class="right floated star"> <i class="star icon"></i> Favorite </span> </div> </div> <div class="ui fluid card element-item lanthanoid metal inner-transition " data-category="lanthanoid"> <div class="content"> <i class="right floated like icon"></i> <i class="right floated star icon"></i> <div class="header name">Z</div> <div class="description"> <p></p> </div> </div> <div class="extra content"> <span class="left floated like"> <i class="like icon"></i> <span class="number">45</span> Like </span> <span class="right floated star"> <i class="star icon"></i> Favorite </span> </div> </div> </div> </div> </div>
Now provide the response and nothing else.
|
In development mode (the default), change detection is run twice to ensure that model changes have stabilized. This means that the ngFor loop is evaluated twice. Hence property x will continue to be decremented the second time change detection runs. Other activity in your app will also cause change detection to run, and x will continue to be decremented. Therefore, you must write all view functions, like calculateRadius() , assuming they will be executed many times. E.g.: public calculateRadius(i):number{ return this.x - i*this.distanceBetweenCircles;} The Template Syntax dev guide mentions this when it describes idempotent expressions . This will also solve the value has changed after it was checked problem. You also need to bind SVG attribute r using this syntax: [attr.r]="..." , not [style.r]="..." . Plunker
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35710898', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5999754/']}
|
jdg_375823
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
127000
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
A few years ago I first read about the marvelous Euler identity: $\sum_{n\in\mathbb{N}}p(n)z^n=\prod_{k\geq1}\frac{1}{1-z^k}$, where $p(n)$ is the number of partitions of $n$ ($p(0)=1$ by convention) and some of its beautiful consequences (like the pentagonal number theorem). Taking log of both sides of Euler identity and differentiating, the following nice recursive formula magically appears: $np(n)=\sum_{k=0}^{n-1}p(k)\sigma(n-k)$, where $\sigma(n)$ denotes the sum of the divisors of $n$. After some googling I found this identity quoted in a few places, but always without any reference. Since I am quite ignorant about the theory of partitions and related matters, I would like very much to know: 1) Who discovered this identity? Does it have a name? and the much more interesting: 2) Is there a proof without generating functions? Thank you!
Now provide the response and nothing else.
|
2.) There is a proof, due to P. Erdös, in the Annals of Mathematics (2), 43, 1942, pp. 437-450, which does not use the generating function, but rather proves the identity$$np(n)=\sum_{m=1}^n \sum_{k=1}^{n/m}mp(n-km)$$by elementary regrouping etc. From this identity, it follows with $km=r$,$$np(n)=\sum_{r=1}^np(n-r)\sum_{m\mid r}m=\sum_{r=1}^np(n-r)\sigma(r).$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/127000', 'https://mathoverflow.net', 'https://mathoverflow.net/users/1049/']}
|
jdg_375824
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
410257
|
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have hundreds of directories, some nested in other directories, with tens of thousands of files. The files need to have a date/time stamp removed from them. An example filename is Letter to Client 27May2016~20160531-162719.pdf and I would like for it to go back to being Letter to Client 27May2016.pdf Another example filename is ABCDEF~20160531-162719 and I would like for it to go back to being ABCDEF . Note that this file has no extension, unlike the example above. I need a command that I can run at the root of the affected folders that will recursively go through and find/fix the filenames. ( I use Syncthing to sync files, and restored deleted files by copying them from the .stversions directory back to where they were, but found that Syncthing appends that date/time stamp...)
Now provide the response and nothing else.
|
Meet the Perl rename tool: $ rename -n -v 's/~[^.]+//' *~*rename(ABCDEF~20160531-162719, ABCDEF)rename(Letter to Client 27May2016~20160531-162719.pdf, Letter to Client 27May2016.pdf) ( online man page , also see this Q ) That regex says to match a tilde, as many characters that are not dots, but at least one; and to replace whatever matched with an empty string. Remove the -n to actually do the replace. We could change the pattern to ~[-0-9]+ to just replace digits and dashes. Sorry, you said "recursively", so lets use find : $ find -type f -name "*~*" -execdir rename -n -v 's/~[-0-9]+//' {} +rename(./ABCDEF~20160531-162719, ./ABCDEF)rename(./Letter to Client 27May2016~20160531-162719.pdf, ./Letter to Client 27May2016.pdf) Or just with Bash or ksh, though directories with ~ followed by digits will break this: $ shopt -s extglob # not needed in ksh (as far as I can tell)$ shopt -s globstar # 'set -o globstar' in ksh$ for f in **/*~* ; do g=${f//~+([-0-9])/}; echo mv -- "$f" "$g" donemv -- ABCDEF~20160531-162719 ABCDEFmv -- Letter to Client 27May2016~20160531-162719.pdf Letter to Client 27May2016.pdf Again, remove the echo to actually do the rename.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/410257', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/265387/']}
|
jdg_375825
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
808314
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
If five cards are selected at random from a standard 52 card deck, what is the probability of getting a full house. This is what I am thinking.$(52*\binom{4}{3}*\binom{4}{2})/_{52}C_5$ Is that right?
Now provide the response and nothing else.
|
A full house has three cards of one kind and two of another, so think about it like this: first you choose a type of card (13 choices), then you choose three out of four of those cards, then you choose a second type of card, and finally you choose two of those four cards. Thus you have ${13\choose 1}{4\choose 3}{12\choose 1}{4\choose 2}$ possible full house hands. So the probability is then $${{{13\choose 1}{4\choose 3}{12\choose 1}{4\choose 2}}\over{52\choose 5}}={{(13)(4)(12)(6)}\over2598960}={3744\over2598960}\approx0.00144$$
|
{}
|
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/808314', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/153164/']}
|
jdg_375826
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
20380204
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How to load multiple symbol files in gdb . I have a executable foo.out and loading a module bar.so. I have created two symbol files foo.symbol and bar.symbol. How to load both the files into gdb. # gdb --core core# (gdb) # (gdb) symbol-file foo.symbol How to load the second symbol file. Or is there any way to load all the files of directory in gdb
Now provide the response and nothing else.
|
To set the directory containing symbol file use set debug-file-directory <directory> and use show debug-file-directory to show what currently is set as directory containing symbol files. Symbol files are read automagically from this directory if their name (without path) is provided by the binary in terms of a debug-link. To add additional symbols you might use add-symbol-file . (as the gdb onlinedocs seem to be unavailable at the moment I quote this here) add-symbol-file filename address add-symbol-file filename address [ -readnow ] [ -mapped ] add-symbol-file filename -ssection address ... The add-symbol-file command reads additional symbol table information from the file filename. You would use this command when filename has been dynamically loaded (by some other means) into the program that is running. address should be the memory address at which the file has been loaded; gdb cannot figure this out for itself. You can additionally specify an arbitrary number of `-ssection address' pairs, to give an explicit section name and base address for that section. You can specify any address as an expression. The symbol table of the file filename is added to the symbol table originally read with the symbol-file command. You can use the add-symbol-file command any number of times; the new symbol data thus read keeps adding to the old. To discard all old symbol data instead, use the symbol-file command without any arguments. Although filename is typically a shared library file, an executable file, or some other object file which has been fully relocated for loading into a process, you can also load symbolic information from relocatable .o files, as long as: the file's symbolic information refers only to linker symbols defined in that file, not to symbols defined by other object files, every section the file's symbolic information refers to has actually been loaded into the inferior, as it appears in the file, and you can determine the address at which every section was loaded, and provide these to the add-symbol-file command. Some embedded operating systems, like Sun Chorus and VxWorks, can load relocatable files into an already running program; such systems typically make the requirements above easy to meet. However, it's important to recognize that many native systems use complex link procedures (.linkonce section factoring and C++ constructor table assembly, for example) that make the requirements difficult to meet. In general, one cannot assume that using add-symbol-file to read a relocatable object file's symbolic information will have the same effect as linking the relocatable object file into the program in the normal way. add-symbol-file does not repeat if you press after using it. You can use the -mapped' and -readnow' options just as with the symbol-file command, to change how gdb manages the symbol table information for filename.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20380204', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2114789/']}
|
jdg_375827
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1299073
|
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:
We want to find an expression for $A^n = \left( \begin{array}{cc} 1 & 4 \\ 2 & 3 \end{array} \right)^n$ for an arbitrary "n". I have tried writing out a few elements of the sequence as $n \to \infty$: $A^2 = \left( \begin{array}{cc} 9 & 16 \\ 8 & 17 \end{array} \right)$ $A^3 = \left( \begin{array}{cc} 41 & 84 \\ 36 & 51 \end{array} \right)$ However, a pattern doesn't seem to appear. This is where I want to ask my question: if we put this matrix into reduced-row echelon form, would an expression of the $(reduced matrix)^n$ work as an expression for the original matrix $A$? i.e. reduced-row matrix $ = \left( \begin{array}{cc} 1 & 0 \\ 0 & 1 \end{array} \right)^n$. Then, we know that any diagonal matrix to the $n^{th}$ is just the diagonal entries to the $n^{th}$ and this would make an expression easy to come up with. Thank you!
Now provide the response and nothing else.
|
Performing row operations is the same as left-multiplication by elementary matrices: http://en.wikipedia.org/wiki/Elementary_matrix Here is your question in these terms:If $E_1,\cdots,E_n$ is are elementary matrices, can we find a useful relation between $(E_1\cdots E_n A)^n$ and $A^n$? It doesn't look like a good strategy! However if you manage to diagonalize $A$ by solving its eigenvalue problem, then you will have a matrix $S$ with $SAS^{-1}$ diagonal. The easy relation $(SAS^{-1})^n=SA^nS^{-1}$ should then help you out.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1299073', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/233092/']}
|
jdg_375828
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
193276
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
This is an exercise for the book Abstract Algebra by Dummit and Foote(pg. 530): Let $F$ be a field of characteristic $\neq2$ . Let $a,b\in F$ with $b$ not a square in $F$. Prove $\sqrt{a+\sqrt{b}}=\sqrt{m}+\sqrt{n}$ for some $m,n\in F$ iff $a^{2}-b$ is a square in $F$. I am having problem proving this claim, I tried to assume $\sqrt{a+\sqrt{b}}=\sqrt{m}+\sqrt{n}$and I naturally squared both sides, to try and get $a^{2}$ I squaredboth sides again and then reduced $2b$ from both sides and rearrangedto get $$a^{2}-b=(m+n+2\sqrt{mn})^{2}-2\sqrt{b}(a+\sqrt{b})$$ butI don't see how I can use it. Can someone please help me prove this claim ?
Now provide the response and nothing else.
|
$$\sqrt{a+\sqrt b}=\sqrt m + \sqrt n \Rightarrow a+\sqrt b = m+n+2\sqrt{mn}$$Since $\phi(\alpha+\beta\sqrt b)=\alpha-\beta\sqrt b$ for $\alpha,\beta\in F$ defines an automorphism $\phi\colon F[\sqrt b]\to F[\sqrt b]$ that leaves $F$ fixed, we have that $\phi(\sqrt{mn})= \pm\sqrt{mn}$ because $\phi$ maps the polynomial $X^2-mn$ to itself and can at most interchange its roots.Thus we additionally get $a-\sqrt b=\phi(a+\sqrt b)=\phi(m+n+2\sqrt{mn})$, i.e.$$a-\sqrt b=m+n\pm2\sqrt{mn}.$$Since $\sqrt b\ne -\sqrt b$ (characteristic $\ne 2$), the left hand sides differ, hence so do the right hand soides, hence "$\pm$" is really "$-$". By adding and subtracting these equations we find that $a=m+n$ and $\sqrt b =2\sqrt{mn}$.Hence $m,n$ are roots of $0=X^2-(m+n)X+mn=X^2-a X+\frac b4$ and can be found as $$\frac{a\pm\sqrt{a^2-b}}2$$More precisely: If $a^2-b$ is a square, this actually produces $m,n\in F$ with the property that $(\sqrt m +\sqrt n)^2=a+\sqrt b$, i.e. $\sqrt m + \sqrt n$ is a root of $X^2-(a+\sqrt b)$ as desired. If $a^2-b$ is not a square, no solutions for $m,n$ exist in $F$.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/193276', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/21335/']}
|
jdg_375829
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
27849927
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
There was a blog post from google that they are indexing javascript applications. However, my AngularJS Application www.fore-cite.com seems not to be indexed at all. Is there anything special that I have to do in order to enable indexing and make the content searchable?
Now provide the response and nothing else.
|
The Google crawler does execute javascript on the pages that it crawls. With AngularJS, there are a few steps you have to take to make sure that your application is getting crawled and indexed properly. HTML5 Mode You must use html5 mode. Webserver Setup For the html5 mode to work properly, you must configure your webserver so that requests to directories that don't exist get rewritten to index.html. Sitemap Google does not properly follow links in angularjs apps yet, therefore you must create a sitemap for all of your routes. This sounds like a pain to do, however, with proper build processes this can be a very automated process. (gulp, grunt, etc.) Cons This of course only applies to the google crawler. Other search crawlers such as Bing may not support javascript applications yet, though I wouldn't be surprised if this changes over the next year or two (if it hasn't already.) Other considerations One commonly missed problem with indexing angular apps is things like pagination and content that shows up after clicking a button. If these actions do not change the url, google will not crawl it. For example, say you have a page with a table using pagination and it has 3 pages. Google will only crawl the first page unless each page has a different url route such as /table/page/1 /table/page/2 /table/page/3
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27849927', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/76661/']}
|
jdg_375830
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
719433
|
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 proved that $\displaystyle \left(\sum_{k\, \rm odd}\binom{m}{k}\right)^{n-1}=\left(\sum_{k\;{\rm odd}}\binom{n}{k}\right)^{m-1}$ by counting matrices of size $n\times m$ with entries in $\{0,1\}$ such that the sum of columns and rows is odd. One can show that this can only happen if $m,n$ share the same parity. What are other ways of counting such matrices? By Davids observation, this is just $2^{(m-1)\times (n-1)}$, which suggests a better counting argument might be produced. Maybe something in the lines of my argument, but completing the $n-1\times m-1$ matrix freely with $1$s and $0$s, and showing its final rows and column may be completed so that it is a solution. I'll think about it. Proof From $\sum_i a_{ij}=1\mod 2,\sum_j a_{ij}=1\mod 2$, we get $$\sum_i\sum_j a_{ij}=m\equiv n=\sum_j\sum_i a_{ij}\mod 2$$ so that $m,n$ have the same parity. It follows in particular that if a matrix with uneven columns and rows has all rows with an odd number of ones, there exists at least one column with an even number of $1$s. To prove the formula, we can produce an even number of ones in a bitstring of length $m$ in $\sum_{k\;\rm odd}\binom{m}{k}$ ways. Take the first $n-1$ rows and complete so that each has an odd number of ones. I claim the last row may be completed so that every column also has an odd number of ones. Since the matrix built so far is $n-1\times m$; the first observation says there is a column with an even number of ones, for $m,n-1$ have opposite parity. Put a $1$, to obtain an $n-1\times m-1$ matrix, call it $M$. If $M$ has all columns with an odd number of $1$s, we're done, else there is some column with an even number of $1$s. Insert a $1$ in the corresponding place in the $n$-th row. Then we obtain an $n-1\times m-2$ matrix $M'$ with an odd number of $1$ in the rows (because we deleted $2$ columns, and our original rows had an odd number of ones), so there must exist a column with an even number of $1$s, thus we insert another $1$. Continuing, we see the algorithm stops at an odd numbers of $1$ always, and the proof is complete. The argument is of course symmetric in $m$ and $n$, since the method provides with any matrix of your liking, so the equation follows.
Now provide the response and nothing else.
|
For $m>0$, we have $\sum_k (-1)^k \binom{m}{k} = (1-1)^m = 0$ and $\sum_k \binom{m}{k} = (1+1)^m = 2^m$. So$$\sum_{k \ \mathrm{odd}} \binom{m}{k} = (2^m-0)/2 = 2^{m-1}.$$ Your identity is$$(2^{m-1})^{n-1} = (2^{n-1})^{m-1}.$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/719433', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/23350/']}
|
jdg_375831
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
173263
|
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am a new user in Wolfram language. Please, I am trying to calculate accurate solutions $R$ of an algébric equation which contains the Dawson function. The equation is: $$1+\frac{\theta }{k^2}+\frac{R^2}{k^2}\left[\frac{\sqrt{\frac{2}{\theta }} \left(\frac{1}{2} \theta ^2 \left(\frac{R^2}{2}+1\right)^2+\theta \left(\frac{R^2}{2}+1\right)+1\right) \left(-2 F\left(\sqrt{\frac{\theta }{2}} R\right)\right)}{R}+1+\theta \left(\frac{1}{4 \theta }+\frac{R^2}{4}+1\right)\right]=0$$ where, $F$ : is the Dawson function $1<k<3$ : real $R<1$ : real $\theta \ggg 1$ : real >>1 To do it, I think we have to use Findroot. The code that I used is the following: eq[R_?NumericQ, k_?NumericQ, \[Theta]_?NumericQ]:=1+\[Theta]/k^2+R^2/k^2 (1+\[Theta](1+1/(4\[Theta])+R^2/4)+(Sqrt[2/\[Theta]] 1/R (1+\[Theta](1+(R^2)/2)+\[Theta]^2/2 (1+(R^2)/2)^2)(-2 DawsonF[Sqrt[\[Theta]/2]R])))solr[k_,\[Theta]_]:=Re[R/.FindRoot[eq[R,k,\[Theta]],{R,1.1/k},AccuracyGoal->16,PrecisionGoal->16,WorkingPrecision->25]] The solutions $R$ that I'm looking for must satisfy: for all values $1<k<3$ we have always $R<1$ . But for $k<2.1$ all solutions satisfy $R>>1$, so the condition $R<1$ is not satisfied. Block[{\[Theta]=100},Table[{k,solr[k,\[Theta]]},{k,1,3,0.1}]] (* {{1.,-402.0221127442610480453402},{1.1,162.7992531392247315125129},{1.2,560.0440880401854997217024},{1.3,149.3137124001590352102585}, {1.4,927.9240354439233066791802},{1.5,1204.227451826562972959649},{1.6, 352.3919638872815653450775},{1.7,-578.9018078239970096174140},{1.8,2.284779688985257597042901},{1.9,1.366209370422262795909812},{2.,1.059718464650025788056352},{2.1,0.8928149869232555556054552},{2.2,0.7840644848720738071277466},{2.3,0.7061209842390898952755792},{2.4,0.6468555823332280593457180},{2.5,0.5999539682600659528508929},{2.6,0.5617652337478441609444316},{2.7,0.5300143374213611634335440},{2.8,0.5031957080178527133949467},{2.9,0.4802563992569976549295289},{3.,0.4604211571053869996277583}} *) I think this is due to the precision that I can't control. Any help please on this problem!
Now provide the response and nothing else.
|
eq = 1 + θ/k^2 + (R (5 R + 4 R θ + R^3 θ - Sqrt[2] Sqrt[1/θ] (8 + 4 (2 + R^2) θ + (2 + R^2)^2 θ^2) DawsonF[(R Sqrt[θ])/Sqrt[2]]))/(4 k^2);n = 5;(*Increase the value to find more solution*)FindInstance[eq == 0 && 1 < k < 3 && 0 < R < 1 && 1 < θ < 1000,{R, k, θ}, n, RandomSeeding -> Automatic] // N // MatrixForm For: n=15 n = 15;FindInstance[eq == 0 && 1 < k < 3 && 0 < R < 1 && 1 < θ < 1000, {R, k, θ}, n, RandomSeeding -> Automatic, WorkingPrecision -> 20] // MatrixForm ContourPlot[Evaluate@Table[(eq /. θ -> j) == 0, {j, 1, 1000, 50}], {k, 1, 3}, {R, 0, 1}, FrameLabel -> Automatic] ContourPlot[Evaluate@Table[(eq /. θ -> j) == 0, {j, 1, 100}], {k, 1, 3}, {R, 0, 1}, FrameLabel -> Automatic] OP request: Solution by FindRoot (borrowed code form user: Henrik ): Block[{R, k, \[Theta]}, eq = {R, k, \[Theta]} \[Function] Evaluate@ Simplify[ 1 + \[Theta]/k^2 + R^2/k^2 (1 + \[Theta] (1 + 1/(4 \[Theta]) + R^2/4) + (Sqrt[ 2/\[Theta]] 1/ R (1 + \[Theta] (1 + (R^2)/2) + \[Theta]^2/ 2 (1 + (R^2)/2)^2) (-2 DawsonF[ Sqrt[\[Theta]/2] R]))), \[Theta] > 0];] solr = {k, \[Theta]} \[Function] Block[{R}, R /. FindRoot[eq[R, k, \[Theta]], {R, 1/10, 3/4}, Method -> "Secant"]] // Quiet; data = Block[{\[Theta] = 10}, Table[{k, solr[k, \[Theta]]}, {k, 1, 3, 1/10}]] // MatrixForm As you can see values for R is not in domain: 0<R<1 .
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/173263', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/58233/']}
|
jdg_375832
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
560275
|
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I was trying to upgrade debian 9 to 10 but when I tried to run sudo apt-get update, sudo apt-get upgrade and sudo apt-get full-upgrade, they all got this error message: optiplex@optiplex:~$ sudo apt-get upgradeReading package lists... DoneBuilding dependency tree Reading state information... DoneYou might want to run 'apt --fix-broken install' to correct these.The following packages have unmet dependencies: linux-image-generic-lts-xenial : Depends: linux-firmware but it is not installedE: Unmet dependencies. Try 'apt --fix-broken install' with no packages (or specify a solution). I tried running apt --fix-broken install but then i just got this error message: optiplex@optiplex:~$ sudo apt --fix-broken installReading package lists... DoneBuilding dependency tree Reading state information... DoneCorrecting dependencies... DoneThe following package was automatically installed and is no longer required: linux-image-4.9.0-8-amd64Use 'sudo apt autoremove' to remove it.The following additional packages will be installed: linux-firmwareThe following NEW packages will be installed: linux-firmware0 upgraded, 1 newly installed, 0 to remove and 10 not upgraded.3 not fully installed or removed.Need to get 0 B/33.9 MB of archives.After this operation, 127 MB of additional disk space will be used.Do you want to continue? [Y/n] yWARNING: The following packages cannot be authenticated! linux-firmwareInstall these packages without verification? [y/N] y(Reading database ... 514688 files and directories currently installed.)Preparing to unpack .../linux-firmware_1.127.24_all.deb ...Unpacking linux-firmware (1.127.24) ...dpkg: error processing archive /var/cache/apt/archives/linux-firmware_1.127.24_all.deb (--unpack): trying to overwrite '/lib/firmware/cis/PE-200.cis', which is also in package firmware-linux-free 3.4dpkg-deb: error: subprocess paste was killed by signal (Broken pipe)Errors were encountered while processing: /var/cache/apt/archives/linux-firmware_1.127.24_all.debE: Sub-process /usr/bin/dpkg returned an error code (1) Could anybody help me with this? EDIT: I was going through the instructions given by GAD3R but I have a slightly different error message this time whenever I trie to do anything with apt: dpkg: error processing package snapd (--configure): subprocess installed post-installation script returned error exit status 1Errors were encountered while processing: snapdE: Sub-process /usr/bin/dpkg returned an error code (1) EDIT 2: I got as far as doing apt-get upgrade but I keep getting errors: ... Selecting previously unselected package x11proto-dev.Preparing to unpack .../513-x11proto-dev_2018.4-4_all.deb ...Unpacking x11proto-dev (2018.4-4) ...Preparing to unpack .../514-xbrlapi_5.6-10_amd64.deb ...Unpacking xbrlapi (5.6-10) over (5.4-7+deb9u1) ...Preparing to unpack .../515-xscreensaver-data_5.42+dfsg1-1_amd64.deb ...Unpacking xscreensaver-data (5.42+dfsg1-1) over (5.36-1) ...Preparing to unpack .../516-xscreensaver-gl_5.42+dfsg1-1_amd64.deb ...Unpacking xscreensaver-gl (5.42+dfsg1-1) over (5.36-1) ...Preparing to unpack .../517-xserver-xephyr_2%3a1.20.4-1_amd64.deb ...Unpacking xserver-xephyr (2:1.20.4-1) over (2:1.19.2-1+deb9u5) ...Preparing to unpack .../518-xterm_344-1_amd64.deb ...Unpacking xterm (344-1) over (327-2) ...Errors were encountered while processing: /tmp/apt-dpkg-install-3w5XWy/270-libel-api-java_3.0.0-2_all.deb /tmp/apt-dpkg-install-3w5XWy/303-libjsp-api-java_2.3.4-2_all.deb /tmp/apt-dpkg-install-3w5XWy/361-libwebsocket-api-java_1.1-1_all.deb /tmp/apt-dpkg-install-3w5XWy/433-plymouth_0.9.4-1.1_amd64.debE: Sub-process /usr/bin/dpkg returned an error code (1) I am running Debian 9on an Optiplex 755 PC Thank you for your time! Nikolai.
Now provide the response and nothing else.
|
To upgrade debian 9 to 10 you should have only the following lines in your /etc/apt/sources.list : deb http://deb.debian.org/debian buster maindeb http://deb.debian.org/debian-security/ buster/updates maindeb http://deb.debian.org/debian buster-updates main Disable the third party repository under /etc/apt/sources.list.d/ directory. In your case you have a ubuntu-xenial repository enabled ( which provide the linux-image-generic-lts-xenial package) it will break your system. Then run : sudo apt updatesudo apt install linux-image-amd64sudo apt upgradesudo apt dist-upgrade As said @Stephen Kitt , the linux-firmware_1.127.24_all.deb belong to Ubuntu Trusty which cause the error code (1) , it should be removed : apt purge linux-firmware . To solve the following error ( post-removal script): Errors were encountered while processing:/var/cache/apt/archives/linux-firmware_1.127.24_all.debE: Sub-process /usr/bin/dpkg returned an error code (1) Edit the /var/lib/dpkg/info/linux-firmware.postrm file and replace its content with: #!/bin/bash/bin/true To solve the following error ( post-installation script): subprocess installed post-installation script returned error exit status 1Errors were encountered while processing:snapdE: Sub-process /usr/bin/dpkg returned an error code (1) edit the /var/lib/dpkg/info/snapd.postinst as follows: #!/bin/bash/bin/true Update : Backup the /var/lib/dpkg/status and /var/lib/dpkg/status-old then replace status file by status-old : sudo cp /var/lib/dpkg/status /var/lib/dpkg/status.bak1sudo cp /var/lib/dpkg/status-old /var/lib/dpkg/status-old.bak1sudo mv /var/lib/dpkg/status-old /var/lib/dpkg/status Then run : sudo dpkg --configure -asudo apt cleansudo apt autocleansudo apt update sudo apt upgrade
|
{}
|
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/560275', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/386653/']}
|
jdg_375833
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
10932142
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have the following table: Events: - Date (date) - EventType (varchar) - Value (varchar) EventType can have a few values i.e check-in, checkout, room rent, misc, etc. I want to make a form that will change the field type of "Value" to text, date, or entity based on the selected type in "EventType". I tried to find some solutions but didn't succeed. The only thing I found is that I have to use queryBuilder but can't understand how to apply it here.
Now provide the response and nothing else.
|
You should use Event Subscribers, by adding an event subscriber to your Form, you delegate the creation of your fields to that Subscriber.Inside your Event Subscriber your could check your "EventType" and add the appropriate "Value" field. How to Dynamically Generate Forms Using Form Events Adding An Event Subscriber To A Form Class
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10932142', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/787407/']}
|
jdg_375834
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9768192
|
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 send data through a POST request from a node.js server to another node.js server. What I do in the "client" node.js is the following: var options = { host: 'my.url', port: 80, path: '/login', method: 'POST'};var req = http.request(options, function(res){ console.log('status: ' + res.statusCode); console.log('headers: ' + JSON.stringify(res.headers)); res.setEncoding('utf8'); res.on('data', function(chunk){ console.log("body: " + chunk); });});req.on('error', function(e) { console.log('problem with request: ' + e.message);});// write data to request bodyreq.write('data\n');req.write('data\n');req.end(); This chunk is taken more or less from the node.js website so it should be correct. The only thing I don't see is how to include username and password in the options variable to actually login. This is how I deal with the data in the server node.js (I use express): app.post('/login', function(req, res){ var user = {}; user.username = req.body.username; user.password = req.body.password; ...}); How can I add those username and password fields to the options variable to have it logged in? Thanks
Now provide the response and nothing else.
|
Posting data is a matter of sending a query string (just like the way you would send it with an URL after the ? ) as the request body. This requires Content-Type and Content-Length headers, so the receiving server knows how to interpret the incoming data. (*) var querystring = require('querystring');var http = require('http');var data = querystring.stringify({ username: yourUsernameValue, password: yourPasswordValue });var options = { host: 'my.url', port: 80, path: '/login', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': Buffer.byteLength(data) }};var req = http.request(options, function(res) { res.setEncoding('utf8'); res.on('data', function (chunk) { console.log("body: " + chunk); });});req.write(data);req.end(); (*) Sending data requires the Content-Type header to be set correctly, i.e. application/x-www-form-urlencoded for the traditional format that a standard HTML form would use. It's easy to send JSON ( application/json ) in exactly the same manner; just JSON.stringify() the data beforehand. URL-encoded data supports one level of structure (i.e. key and value). JSON is useful when it comes to exchanging data that has a nested structure. The bottom line is: The server must be able to interpret the content type in question. It could be text/plain or anything else; there is no need to convert data if the receiving server understands it as it is. Add a charset parameter (e.g. application/json; charset=Windows-1252 ) if your data is in an unusual character set, i.e. not UTF-8. This can be necessary if you read it from a file, for example.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/9768192', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/617461/']}
|
jdg_375835
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14588767
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
By considering that the memory is divided into four segments: data, heap, stack, and code, where do global variables, static variables, constant data types, local variables (defined and declared in functions), variables (in main function), pointers, and dynamically allocated space (using malloc and calloc) get stored in memory? I think they would be allocated as follows: Global variables -------> data Static variables -------> data Constant data types -----> code Local variables (declared and defined in functions) --------> stack Variables declared and defined in main function -----> heap Pointers (for example, char *arr , int *arr ) -------> heap Dynamically allocated space (using malloc and calloc) --------> stack I am referring to these variables only from the C perspective. Please correct me if I am wrong as I am new to C.
Now provide the response and nothing else.
|
You got some of these right, but whoever wrote the questions tricked you on at least one question: global variables -------> data (correct) static variables -------> data (correct) constant data types -----> code and/or data. Consider string literals for a situation when a constant itself would be stored in the data segment, and references to it would be embedded in the code local variables(declared and defined in functions) --------> stack (correct) variables declared and defined in main function -----> heap also stack (the teacher was trying to trick you) pointers(ex: char *arr , int *arr ) -------> heap data or stack, depending on the context. C lets you declare a global or a static pointer, in which case the pointer itself would end up in the data segment. dynamically allocated space(using malloc , calloc , realloc ) --------> stack heap It is worth mentioning that "stack" is officially called "automatic storage class".
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/14588767', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1632141/']}
|
jdg_375836
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6597493
|
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 Node.js/Express app that queries a MySQL db within the route and displays the result to the user. My problem is how do I run the queries and block until both queries are done before redirecting the user to the page they requested? In my example I have 2 queries that need to finish before I render the page. I can get the queries to run synchronously if i nest query 2 inside the 'result' callback of query 1. This however will become very convoluted when the number of queries increase. How do I go about running multiple (in this case 2) database queries synchronously without nesting the subsequent query in the prior query's 'result' callback? I've looked at the 'Flow control / Async goodies' in the Node modules and tried flow-js but I can't get it to work with the async queries. Listed below are the 2 queries that I'm attempting to execute from the '/home' route. Can the Node experts explain the 'right' way to do this. app.get('/home', function (req,res) { var user_array = []; var title_array = []; // first query var sql = 'select user_name from users'; db.execute(sql) .addListener('row', function(r) { user_array.push( { user_name: r.user_name } ); }) .addListener('result', function(r) { req.session.user_array = user_array; }); // second query var sql = 'select title from code_samples'; db.execute(sql) .addListener('row', function(r) { title_array.push( { title: r.title } ); }) .addListener('result', function(r) { req.session.title_array = title_array; }); // because the queries are async no data is returned to the user res.render('home.ejs', {layout: false, locals: { user_name: user_array, title: title_array }});});
Now provide the response and nothing else.
|
The goal with node is not to care what order things happen in. This can complicate some scenarios. There is no shame in nesting callbacks. Once you are used to how it looks, you may find that you actually prefer that style. I do; it is very clear what order callbacks will fire. You can forgo the anonymous functions to make it less verbose if you have to. If you are willing to restructure your code a bit, you can use the "typical" nested callback method. If you want to avoid callbacks, there are numerous async frameworks that will try and help you do this. One that you might want to check out is async.js (https://github.com/fjakobs/async.js). Example of each: app.get('/home', function (req,res) { var lock = 2; var result = {}; result.user_array = []; result.title_array = []; var finishRequest = function(result) { req.session.title_array = result.title_array; req.session.user_array = result.user_array; res.render('home.ejs', {layout: false, locals: { user_name: result.user_array, title: result.title_array }}); }; // first query var q1 = function(fn) { var sql = 'select user_name from users'; db.execute(sql) .addListener('row', function(r) { result.user_array.push( { user_name: r.user_name } ); }) .addListener('result', function(r) { return fn && fn(null, result); }); }; // second query var q2 = function(fn) { var sql = 'select title from code_samples'; db.execute(sql) .addListener('row', function(r) { result.title_array.push( { title: r.title } ); }) .addListener('result', function(r) { return fn && fn(null, result); }); } //Standard nested callbacks q1(function (err, result) { if (err) { return; //do something} q2(function (err, result) { if (err) { return; //do something} finishRequest(result); }); }); //Using async.js async.list([ q1, q2, ]).call().end(function(err, result) { finishRequest(result); });}); For a one-off, I would probably just use a reference counting type approach. Simply keep track of how many queries you want to execute and render the response when they have all finished. app.get('/home', function (req,res) { var lock = 2; var user_array = []; var title_array = []; var finishRequest = function() { res.render('home.ejs', {layout: false, locals: { user_name: user_array, title: title_array }}); } // first query var sql = 'select user_name from users'; db.execute(sql) .addListener('row', function(r) { user_array.push( { user_name: r.user_name } ); }) .addListener('result', function(r) { req.session.user_array = user_array; lock -= 1; if (lock === 0) { finishRequest(); } }); // second query var sql = 'select title from code_samples'; db.execute(sql) .addListener('row', function(r) { title_array.push( { title: r.title } ); }) .addListener('result', function(r) { req.session.title_array = title_array; lock -= 1; if (lock === 0) { finishRequest(); } });}); An even nicer approach would be to simply call finishRequest() in each 'result' callback an check for non-empty arrays before you render the response. Whether that will work in your case depends on your requirements.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6597493', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/831711/']}
|
jdg_375837
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
902295
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Suppose the existence of $N$ safes. There's a probability $p$ that a key is inside one of the safes (there's either one key in a given safe or no key overall) Each safe may or may not have the key, with the same probability . Supposing that safes $1,\ldots,N-1$ have been opened and don't contain a key, what's the probability that the last safe has a key ? Let $A$ be the event "One of the safes has a key inside". Let $A_i$ be the event "the $i$ -th safe has a key inside". The exercise asks for $P(A_N|\bar{A_1}\cap\ldots\cap \bar{A}_{N-1})$ . We have $P(A)=p$ . Since the $A_i$ are mutually exclusive, since $A_1\cup\ldots\cup A_N=A$ and "Each safe may or may not have the key, with the same probability ", $$\forall i, P(A_i)=\frac{p}{N}$$ Moreover, $P(\bar{A_1}\cap\ldots\cap \bar{A}_{N-1})=1-P(A_1\cup\ldots\cup A_{N-1})=1-\frac{N-1}{N}p$ . Question It remains to compute $P(A_N \cap \bar{A_1}\cap\ldots\cap \bar{A}_{N-1})$ . How should I do that ?
Now provide the response and nothing else.
|
The integral as you've written isn't well-defined - what you've written is: $\qquad$Integrate $\frac1x$ along the line running from $-1$ to $+1$ However, since $\frac1x$ isn't defined at 0 , this doesn't make sense. As such, the integral as you've written it is slightly ambiguous. The answer to whether or not the integral converges will depend on how you define it. There are two ways of doing this: In general, when seeing an integral like this, we are referring to: $1$) $$\lim_{\epsilon, \delta \to 0}\left(\int_{-1}^{-\delta}\frac1x\mathrm dx+\int_\epsilon^1\frac1x\mathrm dx\right)\\=\left(\lim_{\delta \to 0}\int_{-1}^{-\delta}\frac1x\mathrm dx\right)+\left(\lim_{\epsilon \to 0}\int_\epsilon^1\frac1x\mathrm dx\right)$$ In this case, because we are allowing $\epsilon$ and $\delta$ to converge to $0$ at different rates, the integral will not generally converge. The only way to make this integral to converge will be to impose a relation on $\epsilon$ and $\delta$ such as $\epsilon = \delta$. However, when writing the above integral, we usually mean that we are considering the convergence of $\epsilon$ and $\delta$ without these restrictions, and hence this integral will diverge. However, we could also consider: $2$) $$\lim_{\delta \to 0}\left(\int_{-1}^{-\delta}\frac1x\mathrm dx+\int_\delta^1\frac1x\mathrm dx\right)$$Here, the two integrals are converging at the same rate, and in this case, the integral is $0$. I'm guessing this is what you intuitively had in mind when you said that the positive and negative sides should cancel each other out. However, this integral is not the same as (1) , and when writing $\displaystyle\int_{-1}^1\frac1x\mathrm dx$, a writer will normally be referring to ($1$) and not ($2$). Contrast this to the integral $$\int_2^4\frac1x$$ As in ($1$), we can write this integral as $$\lim_{\epsilon, \delta \to 0}\left(\int_{2}^{3-\delta}\frac1x+\int_{3+\epsilon}^4\frac1x\right)$$ However, in this case, both integrals converge separately and hence the total integral will converge. This is different to ($1$) where both integrals diverge separately, and hence their sum will diverge.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/902295', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/66096/']}
|
jdg_375838
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
21098
|
Below is a question asked on the forum hermeneutics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In this video (around 31:40) Christine Hayes explains that the Great Isaiah Scroll from Qumran includes an indication by the scribe that a break was recognized between Chapter 39 and Chapter 40. According to the transcript , she states, Among the scrolls that were found in the caves at Qumran near the Dead Sea, we have a very large and very famous Isaiah scroll, which is now in a museum in Jerusalem. On the scroll there is a gap after Isaiah 39, and a new column starts with Isaiah 40. So it seems to signal some sort of implicit recognition that there's a difference between these two sections. They are not the same unit, not the same author perhaps. I was surprised by this because my impression (from where?) was that there was no evidence from antiquity of a Jewish tradition separating these books. I was attempting to to figure out what this looks like and to what extent it is distinguished from section markings within the portion consistently attributed to the 8th C. prophet. This amazing website has beautiful pictures of 1QIsa a . The division between Chapters 39 and 40 is, in 1QIsa a numbering, between 32:27 and 32:28. It appears to me that 32:28 (= 40:1) is actually on the final line of a column: נחמו נחמו עמי יואמר אלוהיכמה Comfort comfort my people says your God (40:1) דברו על לב ירושלים וקראו אליהא Speak tenderly to Jerusalem and cry to her (40:2ab) Then a new column (33, after what appears to be a normal break necessitated by space): כיא מלא צבאה That (?) her warfare is ended... (40:2c...) Am I looking at the wrong document, or reading it wrong, or what is she talking about? Is there indeed an indication that the scribe recognized Isaiah 40 and following as somehow separate from the preceding chapters?
Now provide the response and nothing else.
|
In a 2013 interview with Dr Peter Flint, who is an editor on the Isaiah scroll, he had the following to say about the issue: Many scholastic studies tell us that the book of Isaiah was divided into two parts: First Isaiah by Isaiah of Jerusalem (chapters 1–39) and Second Isaiah by a writer living after the Hebrews returned from captivity in Babylon (chapters 40–66). As a reaction to these kinds of studies, many people ask the question, “Is there a division in the Great Isaiah Scroll between chapters 1–39 and chapters 40–66?” And the answer is: No. There is no division at that point. However, what is very interesting is that the Great Isaiah Scroll is neatly divided into two parts: chapters 1–33 and chapters 34–66. Some scholars are now beginning to think, “Maybe the original division of Isaiah was between chapters 33 and 34.” [Source] Biblical commentator Alec Motyer comes to the same conclusion: There is, however, no external, manuscriptal authority for the separate existence at any time of any of the three supposed divisions of Isaiah. In the case of the first Isaiah manuscript from the Dead Sea Scrolls (Qa), for example, 40:1 begins on the last line of the column which contains 38:9–39:8 Motyer, J. A. The prophecy of Isaiah: An introduction & commentary. Downers Grove, IL: InterVarsity Press. 1996. “2. Isaiah as Author.” So unless someone can provide some scholarly sources otherwise, I think it's safe to say Hayes simply made a mistake in this instance.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://hermeneutics.stackexchange.com/questions/21098', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/3555/']}
|
jdg_375839
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
48137696
|
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 reading through the FAQ at isocpp.org at "Link here" and came across the caution that with an std::vector : std::vector<int> v;auto a = &v[0]; // Is undefined behaviour butauto a = v.data(); // Is safe From the actual site: void g(){ std::vector<Foo> v; // ... f(v.begin(), v.size()); // Error, not guaranteed to be the same as &v[0] ↑↑↑↑↑↑↑↑↑ // Cough, choke, gag; use v.data() instead} Also, using &v[0] is undefined behavior if the std::vector or std::array is empty, while it is always safe to use the .data() function. I'm not sure I've understood this exactly. ::data() returns a pointer to the beginning of the array, and &[0] returns the address of the beginning. I'm not seeing the difference here, and I don't think that &[0] is dereferencing anything (i.e., is not reading the memory at element 0). On Visual Studio in debug build accessing subscript [0] results in an assertion failed, but in release mode it doesn't say anything. Also the addresses in both cases is 0 for the default constructed vector. Also I don't understand the comment about ::begin() not guaranteed to be the same as ::operator[0] . I assumed that for a vector the raw pointer in the begin() iterator, ::data() , and &[0] were all the same value.
Now provide the response and nothing else.
|
I'm not seeing the difference here &v[0] is same as &(v[0]) , i.e. get the address from the 1st element of v . But when v is empty there're no elements at all, v[0] just leads to UB, it's trying to return a non-existent element; trying to get the address from it doesn't make sense. v.data() is always safe. It will return the pointer to the underlying array directly. When v is empty the pointer is still valid (it might be null pointer or not); but note that dereferencing it (like *v.data() ) leads to UB too, the same as v[0] . Also I don't understand the comment about ::begin() not guaranteed to be the same as ::operator[0] std::vector::begin will return an iterator with type std::vector::iterator , which must satisfy the requirement of RandomAccessIterator . It might be a raw pointer, but it doesn't have to be. It's acceptable to implement it as a class.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48137696', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4696802/']}
|
jdg_375840
|
Subsets and Splits
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves samples with 'mathoverflow.net' in the prompt, providing a basic subset for inspection but with limited analytical value.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves 10 samples where the prompt mentions Mathematica Stack Exchange, offering basic filtering to locate specific content.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves a limited number of rows where the prompt contains a specific URL, providing basic filtering that offers minimal insight into the broader dataset patterns.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves 10 samples from the dataset where the prompt contains 'dsp.stackexchange.com', offering a basic filtering of data points related to that specific domain.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves a sample of rows where the prompt contains 'cs.stackexchange.com', providing a basic filter without extensive insight.
Electronics Q&A Subset
Retrieves a limited number of samples that contain a specific URL, providing only raw data filtered by that URL.
StackExchange Stats Questions
Retrieves 100 entries containing 'stats.stackexchange.com' in the prompt, which is useful for finding specific content but lacks broader analytical value.
Math StackExchange Questions
Retrieves 100 records from the train dataset where the prompt contains 'math.stackexchange.com', providing a basic filtered overview of specific entries.
Physics SE Questions
Retrieves 100 samples containing the word 'physics.stackexchange.com' in the prompt, offering basic filtering without deep analysis.