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 | 591601 |
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 solutions of equation $$x^2+y^2+z^2+w^2=0,$$ in the $p$-adic integers? I think that for $p = 2$ it has only the trivial solution, but for $p$ odd there are nontrivial solutions.
Now provide the response and nothing else.
| If $\sum a_n$ converges, then $a_n \to 0$, therefore $\frac{1}{1+a_n} \to 1$ and $\sum \frac{1}{1+a_n}$ diverges. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/591601', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/35464/']} | jdg_79741 |
stackexchange | llm_judgeable_groundtruth_similarity | 1694595 |
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 timer in my JavaScript which needs to emulate clicking a link to go to another page once the time elapses. To do this I'm using jQuery's click() function. I have used $().trigger() and window.location also, and I can make it work as intended with all three. I've observed some weird behavior with click() and I'm trying to understand what happens and why. I'm using Firefox for everything I describe in this question, but I am also interested in what other browsers will do with this. If I have not used $('a').bind('click',fn) or $('a').click(fn) to set an event handler, then calling $('a').click() seems to do nothing at all. It does not call the browser's default handler for this event, as the browser does not load the new page. However, if I set an event handler first, then it works as expected, even if the event handler does nothing. $('a').click(function(){return true;}).click(); This loads the new page as if I had clicked the a myself. So my question is twofold: Is this weird behavior because I'm doing something wrong somewhere? and why does calling click() do nothing with the default behavior if I haven't created a handler of my own? As Hoffman determined when he tried to duplicate my results, the outcome I described above doesn't actually happen. I'm not sure what caused the events I observed yesterday, but I'm certain today that it was not what I described in the question. So the answer is that you can't "fake" clicks in the browser and that all jQuery does is call your event handler. You can still use window.location to change page, and that works fine for me.
Now provide the response and nothing else.
| Interesting, this is probably a "feature request" (ie bug) for jQuery. The jQuery click event only triggers the click action (called onClick event on the DOM) on the element if you bind a jQuery event to the element. You should go to jQuery mailing lists ( http://forum.jquery.com/ ) and report this. This might be the wanted behavior, but I don't think so. EDIT: I did some testing and what you said is wrong, even if you bind a function to an 'a' tag it still doesn't take you to the website specified by the href attribute. Try the following code: <html><head><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script> <script> $(document).ready(function() { /* Try to dis-comment this: $('#a').click(function () { alert('jQuery.click()'); return true; }); */ }); function button_onClick() { $('#a').click(); } function a_onClick() { alert('a_onClick'); } </script></head><body> <input type="button" onclick="button_onClick()"> <br> <a id='a' href='http://www.google.com' onClick="a_onClick()"> aaa </a></body></html> It never goes to google.com unless you directly click on the link (with or without the commented code). Also notice that even if you bind the click event to the link it still doesn't go purple once you click the button. It only goes purple if you click the link directly. I did some research and it seems that the .click is not suppose to work with 'a' tags because the browser does not suport "fake clicking" with javascript. I mean, you can't "click" an element with javascript. With 'a' tags you can trigger its onClick event but the link won't change colors (to the visited link color, the default is purple in most browsers). So it wouldn't make sense to make the $().click event work with 'a' tags since the act of going to the href attribute is not a part of the onClick event, but hardcoded in the browser. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/1694595', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5114/']} | jdg_79742 |
stackexchange | llm_judgeable_groundtruth_similarity | 29889098 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
When looking at the BuildConfig class generated by Android Studio and the Gradle plugin one can see that the BuildConfig.DEBUG field is initialized using the Boolean.parseBoolean(String) call instead of using one of the boolean literals true or false . When I add custom build properties using Gradle I would simply do it like this: android { buildTypes.debug.buildConfigField 'boolean', 'SOME_SETTING', 'true'} But looking at the generated BuildConfig tells me that Google has taken a different approach with the DEBUG flag: public final class BuildConfig { public static final boolean DEBUG = Boolean.parseBoolean("true"); // more fields here // Fields from build type: debug public static final boolean SOME_SETTING = true;} What is the benefit of using Boolean.parseBoolean(String) instead of literals?
Now provide the response and nothing else.
| Boolean literals inside the BuildConfig class are going to produce IDE warnings when using them in your code (at least within Android Studio). For example when using it in a boolean expression Android Studio will (mistakenly) recommend to simplify the boolean expression because the constant value is always the same (for current build variant that is). This warning is only because Android Studio does not know that the final value inside BuildConfig.SOME_SETTING may be different for other build variants. To keep the code clean and free of warnings you can tell Android Studio to ignore this specific warning by adding an IDE comment like this: But again this will add some noise to the code and reduce readability. By using the Boolean.parseBoolean(String) method to initialize your constant field, you actually trick Android Studio which will no longer be able to completely analyze your boolean expressions, thus not generating warnings any longer. This approach is very useful, as it keeps your code clean and readable, without turning off important code analysis and generation of warnings. Security & performance considerations As mentioned by Jiří Křivánek, the usage of parsed booleans does not only "trick" the static analysis performed by IDEs, but also by compilers, code minifiers, and obfuscators - making it harder for them to remove dead code from your application. This might leave code parts inside your application binaries, that would be stripped otherwise. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/29889098', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2134962/']} | jdg_79743 |
stackexchange | llm_judgeable_groundtruth_similarity | 539907 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I tried to transmit "S" using De0 nano FPGA board and UART over USB module . The problem is i am not receiving "s" constantly . I am using the software Called Hterm to see receiving data. When i remove the USB to UART module from the PC and reconnect the receiving value changes. After removing the Module and plug it again the value changes. And after this is received "S"
Now provide the response and nothing else.
| The problem is sending constant data stream without any pauses between symbols. The ASCII symbol 'S' has a value of 0x53, so it is sent over the wire as repeating pattern of 0110010101 which includes the start and stop bits. Because there is no pauses between transmissions, the receiving UART does not know which bits are the start and stop bits in the constant data stream, so it may synchronize to any wrong but valid-looking point in the stream. There are 4 combinations of valid symbols when sending out ASCII letter 'S' constantly. In addition to the 'S', they are the following: 0101011001 is one combination that also looks like perfectly valid symbol, that's 0x35, the ASCII symbol '5' you are seeing. 0101100101 is another one, that is 0x4D, the ASCII symbol 'M'. 0010101011 is another one, that is 0xAA, which is an unprintable ASCII character, the box you are seeing. This is why there should never be a constant symbol transmission, at least occasionally an idle space that is longer than one symbol should be sent to make the receiving UART to synchronize properly on the actual start bit. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/539907', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/272217/']} | jdg_79744 |
stackexchange | llm_judgeable_groundtruth_similarity | 1540523 |
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 need to find the following: $$\lim_{x\to\infty} f(x)= \lim_{x \to \infty}\left (\frac{x}{x+1} \right )^x$$ I know that this limit = $\frac{1}{e}$ from plugging it into a calculator, but I have to prove it without using the fact that: $$\lim_{x\to\infty} f(x)=\lim_{x \to \infty}\left (\frac{x}{x+k} \right )^x=\frac{1}{e^k}$$ I started by exponentiating: $$\lim_{x\to\infty} f(x)=\lim_{x \to \infty}e^{\ln \left (\frac{x}{x+1} \right )^x}$$ and from here I've dropped the exponent $x$ in front of the $\ln$, and from here I'm getting stuck. Should I separate the $\ln$ like this? $$\lim_{x\to\infty} f(x)=\lim_{x \to \infty}e^{x(\ln(x)-\ln(x+1))}$$ This doesn't seem to be leading me down the right path, but I'm not sure how else to do it. Is there a way to apply L'Hopital? If so, how?
Now provide the response and nothing else.
| Let's start with finding the limit of the reciprocal of the original expression:\begin{align}& \left(1 + \frac{1}{x}\right)^x \\\end{align}whose limit is the well-known $e$. Now you can conclude easily. For those who needed more details, let me put it more explictly:$$\left(\frac{x}{x + 1}\right)^x = \left(\frac{1}{1 + \frac{1}{x}}\right)^x = \frac{1}{\left(1 + \frac{1}{x}\right)^x}.$$Now use $$\lim_{x \to \infty}\frac{h(x)}{g(x)} = \frac{\lim\limits_{x \to \infty}h(x)}{\lim\limits_{x \to \infty} g(x)}$$when $\lim_{x \to \infty} g(x) \neq 0$. We conclude that$$\lim_{x \to \infty}\left(\frac{x}{x + 1}\right)^x = \frac{1}{\lim\limits_{x \to \infty} \left(1 + \frac{1}{x}\right)^x} = \frac{1}{e}.$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1540523', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/292147/']} | jdg_79745 |
stackexchange | llm_judgeable_groundtruth_similarity | 25083220 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
def is_unbound_method(func): passdef foo(): passclass MyClass(object): def bar(self): pass What can I put in the body of is_unbound_method so that is_unbound_method(foo) == Falseis_unbound_method(MyClass().bar) == Falseis_unbound_method(MyClass.bar) == True ??
Now provide the response and nothing else.
| An unbound method has __self__ set to None : def is_unbound_method(func): return getattr(func, '__self__', 'sentinel') is None Demo: >>> foo.__self__Traceback (most recent call last): File "<stdin>", line 1, in <module>AttributeError: 'function' object has no attribute '__self__'>>> is_unbound_method(foo)False>>> MyClass.bar.__self__>>> is_unbound_method(MyClass.bar)True>>> MyClass().bar.__self__<__main__.MyClass object at 0x106c64a50>>>> is_unbound_method(MyClass().bar)False The attribute is also available as .im_self , but __self__ is forward compatible. Note that in Python 3 unbound methods are gone; accessing MyClass.bar returns the function object. Thus the above function will always return False . See the Datamodel documentation , in the User-defined methods section: Special read-only attributes: im_self is the class instance object, im_func is the function object [...] Changed in version 2.6: For Python 3 forward-compatibility, im_func is also available as __func__ , and im_self as __self__ . [...] When a user-defined method object is created by retrieving a user-defined function object from a class, its im_self attribute is None and the method object is said to be unbound. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25083220', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/125415/']} | jdg_79746 |
stackexchange | llm_judgeable_groundtruth_similarity | 177424 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a Windows Server 2008 machine. 99% of the time, all I need to do to administer it is run command line commands such as hg fetch . I would like to move from Remote Desktop to just opening a (secure) command-line session. Some googling found this article which only lists third-party ssh servers for Windows. I want the most "legit" option. What do you recommend?
Now provide the response and nothing else.
| Install Powershell 2.0 In powershell on the server enter: set-executionpolicy remotesigned -force enable-psremoting -force Then from a remote machine (that has powershell enabled) initiate a remote connection: etsn -cred username -comp targetname If you are on the same domain and have proper authorization you can skip the '-cred username' part, but I've found if you're crossing domains with non-mutual trust then it is necessary to use credentials of the remote domain. Also if you want to just issue one command you can do something like... icm targetname {$host } The above should be enough to get you started down the magical world of powershell remoting. | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/177424', 'https://serverfault.com', 'https://serverfault.com/users/4478/']} | jdg_79747 |
stackexchange | llm_judgeable_groundtruth_similarity | 41466641 |
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 receiving a SAML request via HTTP-redirect binding the content of the SAML request look like this {"SigAlg"=>" http://www.w3.org/2000/09/xmldsig#rsa-sha1 ", "SAMLRequest"=>"lVLLaoQwFP0VyT5jEqPG4AiFoSDMtNApXXQzxDxaQRObRDqfX3XoolAKXd7DPQ/uuXUQ4zDxo3tzc3zSH7MOMWkPe3DpcixzVVVQl4RBqoiCncEYEmkoY7k00hCQvGgfemf3gOwQSNoQZt3aEIWNC4RwCRGGiD6jkmPMs2KHUPYKksPi0lsRN+Z7jFPgafqpvejtbtQpSK7jYAPfsu3B7C13IvSBWzHqwKPk57vTkS+WfPIuOukG0NSbub9R/yaJELRfzUGzrhmtFut15qdeeheciY926K2u05toUz8sIu0huXd+FPFv9RXpFTTbKp/WA4WobQT/jEYrykwhNaQ66yDNMwY7wijEtMCmysqqo6xOb8Ga+tbjWYe1jtYqfW0uCucoYwWCHS3F0kRGoajWTpAiiJRZJRmu01+Y3+CPt2i+AA=="} It also has a Signature value WkDaGzC6vPTlzh+EnFA5/8IMmV7LviyRh2DA5EHF0K0nl+xzBlKfNCYRnunpwoEvGhereGdI5xBpv+mc9IguiCaLZSZjDh6lIDdpvctCnmSNzORqzWQwQGeZ9vjgtCLjUn35VZLNs3WgEqbi2cL+ObrUDS2gV1XvBA3Q3RRhoDmi+XE89Ztnd1cNpR3XdA+EL2ENbMI2XAD9qSgMufUJY/3GBBpT7Vg1ODtPxBudq+sXrgPh/+WtUUitLkkfC8tdRTCS1EZPv+h27I5g/VNza23Xl8w2HdAuYP0F2FjREo8VV2aUtaOUd/jAF9+bfkGV93y1PzFttLxdBbFoxp6qBg== But I fail to understand how to verify this signature is correct. Section 3.4.4.1 on SAML binding https://docs.oasis-open.org/security/saml/v2.0/saml-bindings-2.0-os.pdf To construct the signature, a string consisting of the concatenation of the RelayState (if present),SigAlg, and SAMLRequest (or SAMLResponse) query string parameters (each one URLencoded)is constructed in one of the following ways (ordered as below):SAMLRequest=value&RelayState=value&SigAlg=valueSAMLResponse=value&RelayState=value&SigAlg=value I tried the approach but The signature I generated using the Private key does not match to the one I received from my SP. (posted above) Also, I'm not able to decrypt the signed message using the Private key (I'm assuming the Signature was created using the public that I federated it with.) <samlp:LogoutRequest ID="_36167d94-d868-4c04-aee3-8bbd4ed91317" Version="2.0" IssueInstant="2017-01-05T16:21:55.704Z" Destination="https://werain.me/" xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"><Issuer xmlns="urn:oasis:names:tc:SAML:2.0:assertion">urn:federation:MicrosoftOnline</Issuer><NameID Format="urn:oasis:names:tc:SAML:2.0:nameid-format:persistent" xmlns="urn:oasis:names:tc:SAML:2.0:assertion">4948f6ce-4e3b-4538-b284-1461f9379b48</NameID><samlp:SessionIndex>_eafbb730-b590-0134-a918-00d202739c81</samlp:SessionIndex></samlp:LogoutRequest> Any help here.
Now provide the response and nothing else.
| A SAML authentication message is a XML document with an embedded (enveloped) XMLDSig signature or a deflated encoding signature Enveloped XMLDSign signature <samlp:LogoutRequest> <...saml message...> <ds:Signature> <ds:SignedInfo /> <ds:SignatureValue /> <ds:KeyInfo /> </ds:Signature> </samlp:LogoutRequest> <ds:SignatureValue> contains the signature, <ds:SignedInfo> the signed data and a reference to the message and <ds:KeyInfo> usually contains the X509Certificate with the identity of the signer, or a reference to that certicate Deflated encoding in URL SAMLRequest=value&RelayState=value&SigAlg=value&Signature=value Where each value is url encoded SAMLRequest=urlencode(base64(<samlp:LogoutRequest> <...saml message...> </samlp:LogoutRequest>)) And the signature is done on a concatenation of query string algorithm using the algorithm SigAlg Signature = urlencode( base64 ( SigAlg ("SAMLRequest=value&RelayState=value&SigAlg=value"))) Digital signature of SAML messages SAML message is digitally signed (not encrypted) with the private key of the issuer (SP), and can be verified with the public key of the SP . A SAML response must be signed with the private key of the identity provider (IdP), and the SP can verify the message with the public key of the IdP. If you act as IdP and you want to verify a SAML request of the SP, you need: Verify the digital signature : Verify using the public key of the SP that the signature match with the signed message to ensure the identity of the signer and the message has not been altered Authorize the request : Verify that the identity of the signer can perform the requested operation. Usually you have to match the serial number or the subject of the certificate with a pre-existent list, or verify that the certificate has been issued by a trusted certificate authority Generate the SAML response : Generate a XML message with the SAML data and sign it with your private key to send to SP Most programming languages support XMLDsig signatures but in your case is used the deflated encodin g that is a specific characteristic of SAML binding, so if your SAML library does not support it, you have to verify the signature manually . These are more or less the steps to follow according to specification //get params from query string String samlrequest = getQueryParam("SAMLRequest");String relaystate = getQueryParam("RelayState");String sigalg = getQueryParam("SigAlg");String signature = getQueryParam("Signature");//The signaturebyte signature[] = URLDecoder.decode(Base64.getDecoder().decode(signature ), "UTF-8");//The signed data. build the following string checking if RelayState is null//SAMLRequest=samlrequest&RelayState=relaystate&SigAlg=sigalgbyte signedData[] = concat(samlrequest,relaystate,sigalg);//The signature algorithm could be "SHA1WithRSA" or "SHA1withDSA" depending on sigalg is http://www.w3.org/2000/09/xmldsig#rsa-sha1 or http://www.w3.org/2000/09/xmldsig#dsa-sha1 String signatureAlgorithm = extractSignatureAlgorithm(sigalg);//get the public key of the SP. It must be registered before this processPublicKey publicKey = ...//Verify the signatureSignature sig = Signature.getInstance(signatureAlgorithm);sig.initVerify(publicKey);sig.update(signedData); boolean verifies = sig.verify(signature); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41466641', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1438735/']} | jdg_79748 |
stackexchange | llm_judgeable_groundtruth_similarity | 6994114 |
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 "Effective STL" tip 16, it says that we should avoid to pass iterator to a function which accepts a pointer. Could anyone explain the detail for me please? void doSomething(const int* pInts, size_t numInts);vector<int> v;...doSomething(&v[0],v.size()) //correctdoSomething(v.begin(),v.size()) //incorrect
Now provide the response and nothing else.
| In some early implementations of the standard library iterators were implemented as pointers. Code that depended on that property stopped working when iterators became non-pointers. So, you should not pass an iterator where a pointer is expected, because if it compiles then it's just by happen-chance. An iterator is not necessarily a pointer. And if it is a pointer, then it may not necessarily be a pointer in some later version (of the library, compiler, whatever). | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6994114', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/885621/']} | jdg_79749 |
stackexchange | llm_judgeable_groundtruth_similarity | 37745051 |
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 2 divs side-by-side in a flexbox. The right hand one should always be the same width, and I want the left hand one to just grab the remaining space. But it won't unless I specifically set its width. So at the moment, it's set to 96% which looks OK until you really squash the screen - then the right hand div gets a bit starved of the space it needs. I guess I could leave it as it is but it feels wrong - like there has to be a way to say: the right one is always the same; you on the left - you get everything that's left .ar-course-nav { cursor: pointer; padding: 8px 12px 8px 12px; border-radius: 8px;}.ar-course-nav:hover { background-color: rgba(0, 0, 0, 0.1);} <br/><br/><div class="ar-course-nav" style="display:flex; justify-content:space-between;"> <div style="width:96%;"> <div style="overflow:hidden; white-space:nowrap; text-overflow:ellipsis;"> <strong title="Course Name Which is Really Quite Long And Does Go On a Bit But Then When You Think it's Stopped it Keeps on Going for even longer!"> Course Name Which is Really Quite Long And Does Go On a Bit But Then When You Think it's Stopped it Keeps on Going for even longer! </strong> </div> <div style="width:100%; display:flex; justify-content:space-between;"> <div style="color:#555555; margin-right:8px; overflow:hidden; white-space:nowrap; text-overflow:ellipsis;" title="A really really really really really really really really really really really long department name"> A really really really really really really really really really really really long department name </div> <div style="color:#555555; text-align:right; white-space:nowrap;"> Created: 21 September 2016 </div> </div> </div> <div style="margin-left:8px;"> <strong>></strong> </div></div>
Now provide the response and nothing else.
| Use the flex-grow property to make a flex item consume free space on the main axis . This property will expand the item as much as possible, adjusting the length to dynamic environments, such as screen re-sizing or the addition / removal of other items. A common example is flex-grow: 1 or, using the shorthand property, flex: 1 . Hence, instead of width: 96% on your div, use flex: 1 . You wrote: So at the moment, it's set to 96% which looks OK until you really squash the screen - then the right hand div gets a bit starved of the space it needs. The squashing of the fixed-width div is related to another flex property: flex-shrink By default, flex items are set to flex-shrink: 1 which enables them to shrink in order to prevent overflow of the container. To disable this feature use flex-shrink: 0 . For more details see The flex-shrink factor section in the answer here: What are the differences between flex-basis and width? Learn more about flex alignment along the main axis here: In CSS Flexbox, why are there no "justify-items" and "justify-self" properties? Learn more about flex alignment along the cross axis here: How does flex-wrap work with align-self, align-items and align-content? | {} | {'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/37745051', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5686593/']} | jdg_79750 |
stackexchange | llm_judgeable_groundtruth_similarity | 320936 |
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:
Let $X\sim\mathrm{Binomial}(n,p)$. We know that $\mathrm{E}[X]=np$ and $\mathrm{Var}[X]=np(1-p)$. Does this imply that the sample mean $\bar x$ and the sample variance $s^2$ are dependent of each other? Or does it just mean that the population variance can be written as a function of the population mean?
Now provide the response and nothing else.
| $\bar x$ and $s^2$ are random variables. We can work out their joint distribution. Let's try the simplest possible nontrivial case, that of a sample of size $2$ from a Binomial$(1,p)$ distribution. There are only four possibilities for that sample, which are hereby tabulated along with their probabilities (computed from the independence of the two sample elements): First value | Second value | Mean | Variance | Probability 0 | 0 | 0 | 0 | (1-p)^2 0 | 1 | 1/2 | 1/2 | (1-p)p 1 | 0 | 1/2 | 1/2 | p(1-p) 1 | 1 | 1 | 0 | p^2 The mean perfectly predicts the variance in this example. Thus, provided all probabilities are nonzero (that is, $p$ is neither $0$ nor $1$), the sample mean and sample variance are not independent. An interesting question is whether, if in a family of distributions the mean determines the variance, the sample mean and sample variance can be independent. The answer is yes: take any family of Normal distributions in which the variance depends on the mean such as the set of all Normal$(\mu, \mu^2)$ distributions. No matter which of these distributions governs the sample, the sample mean and sample variance will be independent, because that's the case for any Normal distribution. This analysis suggests that questions about the structure of a family of distributions (which concern $n$, $p$, $\mu$, and so forth) have no bearing on questions of independence of statistics of samples from any given element of the family. | {} | {'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/320936', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/168725/']} | jdg_79751 |
stackexchange | llm_judgeable_groundtruth_similarity | 15195717 |
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've been given to a Windows Mobile 6.1 Classic Device to work with for a project, but I was given a network adapter for it and not a USB cable. So I have to build and test across the network. So how do I get Visual Studio to connect to the device across the network? I have read the following articles to no avail: "How to: Connect to Windows CE Device Without ActiveSync" and also looked at: enter link description here But neither have helped me, I am not sure what to try next to try and get Visual Studio 08 to connect to this device remotely I can ping the device, but I can't connect to the device. I know the device is connected to the network because while it is in the cradle it can browse the internet. What am I missing to get this to work? If it can work in the first place... Edit : To make it clear, the issue I currently have is not to do with Debugging. It has to do with Visual merely connecting to the device. Edit 2 : If it helps I don't have a Windows Mobile 6.1 Classic Device in my list of Devices to connect to. I have; Windows CE Device Windows Mobile 6 Professional Device Windows Mobile 6 Standard Device
Now provide the response and nothing else.
| How to connect Visual Studio 2008 to SmartDevice using TCP/IP without ActiveSync/WMDC Remote Files You need the following files of your VS2008 Windows Mobile SDK installation: ClientShutdown.execmaccept.EXEConManClient2.exeeDbgTL.dllTcpConnectionA.dll change registry key HLKM\System\CoreConOverrideSecurity=DWORD:1 on device The files you need are located at (depends on Windows CE version on device): Windows CE 4.2, Windows CE .NET, Windows Mobile 2003, PocketPC 2003:C:\Program Files\Common Files\Microsoft Shared\CoreCon\1.0\target\wce400\armv4i For Visual Studio 2008 and a Windows CE 5 based SDK you can use ftp \hjgode.de\temp\rdb2008.exe tool (used in following example) or the original rdb2008.exe source. Check the IP of the device Start rdb2008.exe on the device **Press [Prepare] in rdb2008 will extract files and set reg entry Prepare VS2008 Ensure you use a matching Windows Mobile SDK. You may use Windows Mobile 6.5 Professional SDK also on a Windows Mobile 6.5 Classic device. Or you use Window Mobile 6 SDK with a Windows Mobile 6.5 Classic device. Just use a appropriate SDK for the device. Setup VS2008 remote device IP and Port Select Tools-Options-Device Tools-Devices Select a appropriate Platform here (show devices for platform)! But as said, it is sufficient to match the basic OS (Windows CE 5). After Selecting the right Platform select a device (no Emulator) and then click [Save As] Enter RemoteDebug as new name. Now select the new RemoteDebug saved entry in Devices... ... and click [Properties]: Now enter a directory for file deployment (here: "\Program Files").Ensure Transport is "TCP Connect Transport" and click [Properties] Ensure you use the fixed port 5655 and then enter the IP address of the remote device! Now close all these option dialogs using the [OK] buttons. Test the connection In VS2008 ensure the Platform and the device is active: Now click Tools in VS2008 menu and then on "Connect to device" Again check the Plaform and Device, do not yet click [Connect]: Now on device: Click [Start] in rdb2008: You see rdb2008 says listening Port 5655! Now click [Connect] in VS2008: Hopefully you got the above dialog and go on with another test. Click [Close]. In VS2008 select Debug-Attach to process: Select Transport=SmartDevice and click Califier:[Browse] and again select the used platform and device "RemoteDebug": If sucessfull, you will see a list of running processes on the device. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15195717', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/933887/']} | jdg_79752 |
stackexchange | llm_judgeable_groundtruth_similarity | 4140448 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
The familiar code: <servlet-mapping> <servlet-name>main</servlet-name> <url-pattern>/*</url-pattern></servlet-mapping><servlet-mapping> <servlet-name>main</servlet-name> <url-pattern>/</url-pattern></servlet-mapping> My understanding is that /* maps to http://host:port/context/* . How about / ? It sure doesn't map to http://host:port/context root only. In fact, it will accept http://host:port/context/hello , but reject http://host:port/context/hello.jsp . Can anyone explain how is http://host:port/context/hello mapped?
Now provide the response and nothing else.
| <url-pattern>/*</url-pattern> The /* on a servlet overrides all other servlets, including all servlets provided by the servletcontainer such as the default servlet and the JSP servlet. Whatever request you fire, it will end up in that servlet. This is thus a bad URL pattern for servlets. Usually, you'd like to use /* on a Filter only. It is able to let the request continue to any of the servlets listening on a more specific URL pattern by calling FilterChain#doFilter() . <url-pattern>/</url-pattern> The / doesn't override any other servlet. It only replaces the servletcontainer's built in default servlet for all requests which doesn't match any other registered servlet. This is normally only invoked on static resources (CSS/JS/image/etc) and directory listings. The servletcontainer's built in default servlet is also capable of dealing with HTTP cache requests, media (audio/video) streaming and file download resumes. Usually, you don't want to override the default servlet as you would otherwise have to take care of all its tasks, which is not exactly trivial (JSF utility library OmniFaces has an open source example ). This is thus also a bad URL pattern for servlets. As to why JSP pages doesn't hit this servlet, it's because the servletcontainer's built in JSP servlet will be invoked, which is already by default mapped on the more specific URL pattern *.jsp . <url-pattern></url-pattern> Then there's also the empty string URL pattern . This will be invoked when the context root is requested. This is different from the <welcome-file> approach that it isn't invoked when any subfolder is requested. This is most likely the URL pattern you're actually looking for in case you want a " home page servlet ". I only have to admit that I'd intuitively expect the empty string URL pattern and the slash URL pattern / be defined exactly the other way round, so I can understand that a lot of starters got confused on this. But it is what it is. Front Controller In case you actually intend to have a front controller servlet, then you'd best map it on a more specific URL pattern like *.html , *.do , /pages/* , /app/* , etc. You can hide away the front controller URL pattern and cover static resources on a common URL pattern like /resources/* , /static/* , etc with help of a servlet filter. See also How to prevent static resources from being handled by front controller servlet which is mapped on /* . Noted should be that Spring MVC has a built in static resource servlet, so that's why you could map its front controller on / if you configure a common URL pattern for static resources in Spring. See also How to handle static content in Spring MVC? | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/4140448', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/264140/']} | jdg_79753 |
stackexchange | llm_judgeable_groundtruth_similarity | 36775611 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
My Application class import com.example.haha.Haha;import com.example.hehe.Hehe;import com.example.logging.Logging;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.ApplicationContext;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.EnableAspectJAutoProxy;@SpringBootApplication@EnableAspectJAutoProxypublic class DemoApplication { public static void main(String[] args) throws InterruptedException { ApplicationContext ctx = SpringApplication.run(DemoApplication.class, args); for(String name:ctx.getBeanDefinitionNames()){ System.out.println(name); } Haha haha = (Haha)ctx.getBean("hh"); haha.haha1(); haha.haha2(); return; }} Haha.java package com.example.haha;import org.springframework.stereotype.Component;/** * Created by vamsi on 4/21/16. */@Component("hh")public class Haha { public Haha(){ } public void haha1() throws InterruptedException { System.out.println("In method haha1"); Thread.sleep(1000); } public void haha2() throws InterruptedException { System.out.println("In method haha2"); Thread.sleep(2000); }} My Aspect Class package com.example.logging;import org.apache.commons.logging.Log;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Pointcut;import org.springframework.context.annotation.Bean;import org.springframework.stereotype.Component;/** * Created by vamsi on 4/21/16. */@Aspect@Componentpublic class Logging { public Logging() { } @Pointcut("execution(public * *(..))") private void allPublicMethods(){} @Around("allPublicMethods()") public Object profile(ProceedingJoinPoint pjp) throws Throwable { long start = System.currentTimeMillis(); System.out.println(pjp.getSignature() +"begins"); Object output = pjp.proceed(); System.out.println(pjp.getSignature()+"completed."); long elapsedTime = System.currentTimeMillis() - start; System.out.println("Method execution time: " + elapsedTime + " milliseconds."); return output; }} pom.xml <?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>demo</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.3.3.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.7</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build></project> These are the files in my spring boot application. I want to log around all the public methods in my application using AOP. Bu when I run my application it gives the following error. org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.AutoConfigurationPackages': Initialization of bean failed; nested exception is org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class [class org.springframework.boot.autoconfigure.AutoConfigurationPackages$BasePackages]: Common causes of this problem include using a final class or a non-visible class; nested exception is java.lang.IllegalArgumentException: Cannot subclass final class org.springframework.boot.autoconfigure.AutoConfigurationPackages$BasePackages at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839) ~[spring-context-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538) ~[spring-context-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:766) [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE] at org.springframework.boot.SpringApplication.createAndRefreshContext(SpringApplication.java:361) [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:307) [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1191) [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1180) [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE] at com.example.DemoApplication.main(DemoApplication.java:18) [classes/:na]Caused by: org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class [class org.springframework.boot.autoconfigure.AutoConfigurationPackages$BasePackages]: Common causes of this problem include using a final class or a non-visible class; nested exception is java.lang.IllegalArgumentException: Cannot subclass final class org.springframework.boot.autoconfigure.AutoConfigurationPackages$BasePackages at org.springframework.aop.framework.CglibAopProxy.getProxy(CglibAopProxy.java:213) ~[spring-aop-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.aop.framework.ProxyFactory.getProxy(ProxyFactory.java:109) ~[spring-aop-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.createProxy(AbstractAutoProxyCreator.java:468) ~[spring-aop-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:349) ~[spring-aop-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:298) ~[spring-aop-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:422) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1583) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE] ... 14 common frames omittedCaused by: java.lang.IllegalArgumentException: Cannot subclass final class org.springframework.boot.autoconfigure.AutoConfigurationPackages$BasePackages at org.springframework.cglib.proxy.Enhancer.generateClass(Enhancer.java:457) ~[spring-core-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.cglib.transform.TransformingClassGenerator.generateClass(TransformingClassGenerator.java:33) ~[spring-core-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25) ~[spring-core-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.aop.framework.CglibAopProxy$ClassLoaderAwareUndeclaredThrowableStrategy.generate(CglibAopProxy.java:990) ~[spring-aop-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:231) ~[spring-core-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.cglib.proxy.Enhancer.createHelper(Enhancer.java:378) ~[spring-core-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.cglib.proxy.Enhancer.createClass(Enhancer.java:318) ~[spring-core-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.aop.framework.ObjenesisCglibAopProxy.createProxyClassAndInstance(ObjenesisCglibAopProxy.java:55) ~[spring-aop-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.aop.framework.CglibAopProxy.getProxy(CglibAopProxy.java:203) ~[spring-aop-4.2.5.RELEASE.jar:4.2.5.RELEASE] ... 21 common frames omitted
Now provide the response and nothing else.
| Your Pointcut is so generic: @Pointcut("execution(public * *(..))") That will advice all available public methods of every class on the classpath, every single of them! Unfortunately, Spring AOP can't make the required proxy for some present classes on the classpath (Since they're not implementing any interface and are final ), hence the error: Cannot subclass final class org.springframework.boot.autoconfigure.AutoConfigurationPackages$BasePackages If you restrict your pointcut to just advice your classes, you would be fine! | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36775611', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3858408/']} | jdg_79754 |
stackexchange | llm_judgeable_groundtruth_similarity | 16822956 |
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 WPF DataGrid <DataGrid AutoGenerateColumns="False" Name="dataGrid1" IsReadOnly="True" ><DataGrid.Columns> <DataGridTextColumn Header="Site" Binding="{Binding Site}" Width="150" /> <DataGridTextColumn Header="Subject" Binding="{Binding Subject}" Width="310" /></DataGrid.Columns><DataGrid.ContextMenu> <ContextMenu> <MenuItem Header="Delete" Click="Context_Delete"> <MenuItem.Icon> <Image Width="12" Height="12" Source="Images/Delete.png" /> </MenuItem.Icon> </MenuItem> </ContextMenu></DataGrid.ContextMenu></DataGrid> I have the click event handler as: private void Context_Delete(object sender, System.EventArgs e) { } How do I get the row on which the Context Menu was before the click? The sender object is System.Windows.Controls.MenuItem , not the DataGridRow . How do I get the DataGridRow where the Context Menu was clicked. (I set the DataGrid.ItemSource in the code behind file.)
Now provide the response and nothing else.
| So based on your example code, I presume you bind your DataGrid to an ObservableCollection of objects of which you bind the properties Site and Subject to the DataGridColumns. Essentially, all you need to do is figure out what the item bound to the clicked DataGridRow is and remove that from your ObservableCollection. Here is some example code to get you started: private void Context_Delete(object sender, RoutedEventArgs e){ //Get the clicked MenuItem var menuItem = (MenuItem)sender; //Get the ContextMenu to which the menuItem belongs var contextMenu = (ContextMenu)menuItem.Parent; //Find the placementTarget var item = (DataGrid)contextMenu.PlacementTarget; //Get the underlying item, that you cast to your object that is bound //to the DataGrid (and has subject and state as property) var toDeleteFromBindedList = (YourObject)item.SelectedCells[0].Item; //Remove the toDeleteFromBindedList object from your ObservableCollection yourObservableCollection.Remove(toDeleteFromBindedList);} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16822956', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1356847/']} | jdg_79755 |
stackexchange | llm_judgeable_groundtruth_similarity | 49677199 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've been working with ddev on my Drupal projects, and now want to use xdebug so I have step-debugging with PhpStorm (or really any IDE would be fine). But I can't seem to get it to stop on breakpoints. I tried to follow the instructions in ddev docs but that doesn't do get me going, and I don't know what to do next. I did: Set the 172.28.99.99 IP address as discussed there Enabled xdebug using config.yaml xdebug_enabled: true and ddev start (and checked with phpinfo to see that xdebug was enabled.) Put PHPStorm in "listen for debug connections" mode
Now provide the response and nothing else.
| Debugging xdebug in any setup can be a little trouble, but here are the steps to take: First, reread the docs . You may want to read the troubleshooting docs rather than this issue, since they're maintained more often. Make sure xdebug has been enabled; it's disabled by default for performance reasons. Most people use ddev xdebug on to enable it when they want it, and ddev xdebug off when they're done with it, but it can also be enabled in .ddev/config.yaml . Don't assume that some obscure piece of code is being executed and put a breakpoint there. Start by putting a breakpoint at the first executable line in your index.php. Oh-so-many times people think it should be stopping, but their code is not being executed. ddev ssh into the web container. Can you ping host.docker.internal (and get responses)? If you can't, you might have an over-aggressive firewall. In PHPStorm, disable the "listen for connections" button so it won't listen. Or just exit PHPStorm. ddev ssh : Can telnet host.docker.internal 9003 connect? If it does, you have something else running on port 9003, probably php-fpm. Use lsof -i :9003 -sTCP:LISTEN to find out what is there and stop it, or change the xdebug port and configure PHPStorm to use the new one . Don't continue until your telnet command does not connect. Now click the listen button on PHPStorm to start it listening for connections. ddev ssh and try the telnet host.docker.internal 9003 again. It should connect. If not, maybe PHPStorm is not listening, or not configured to listen on port 9003? Check to make sure that Xdebug is enabled. You can use php -i | grep grep Xdebug inside the container, or use any other technique you want that gives the output of phpinfo() , including Drupal's admin/reports/status/php. You should see with Xdebug v2.9.6, Copyright (c) 2002-2020 and php -i | grep "xdebug.remote_enable" should give you xdebug.remote_enable: On . Set a breakpoint in the first relevant line of the index.php of your project and then visit the site with a browser. It should stop there. A note from @heddn: If you want to have xdebug running only for fpm, phpenmod -s fpm xdebug for example, instead of running enable_xdebug . A note from @mfrieling: If you use a browser extension like XDebug Helper which sets an IDE key, that must be the same as on the server. Since DDEV 1.10.0 "there's a real user created for you inside the web and db containers, with your username and userid" which is also used as IDE key by default. The used IDE key must be the same on the server, the browser extension/cookie sent and PHPStorm. You can change the IDE key in DDEV by creating a file .ddev/php/xdebug.ini with the following two lines (replace PHPSTORM with the value you want use: [XDebug]xdebug.idekey = PHPSTORM Your followups are welcome here! | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49677199', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/215713/']} | jdg_79756 |
stackexchange | llm_judgeable_groundtruth_similarity | 64399 |
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 just read about PGP encryption scheme here , and started wondering what is the need to encrypt the file with a one time random key? In other words, how is this scheme more secure than simply sending the file which is directly encrypted using the public key? (Because the one time key is anyways sent along with the data)
Now provide the response and nothing else.
| This is called hybrid encryption . It is needed for the following reasons: Asymmetric encryption algorithms like RSA or ElGamal are very limited in the size of messages that they can process. If you use a 2048-bit RSA key, the maximum size of the data that you are going to encrypt is 245 bytes, no more. There is no currently known, clear, fully specified and heavily reviewed method by which a longer message could be somehow "split" into individual elements, each small enough to be RSA-encrypted, then reassembled. That is, it is easy to define a simple split/concatenate procedure, but it would not be safe. This area has not been thoroughly explored by cryptographers, so, in practice, that's a no-go. Even if we knew how to securely perform an only-RSA asymmetric encryption for bulk data, it would entail a substantial message size increase (not a fixed overhead, rather a multiplicative factor). Network bandwidth is often a primary concern (especially in embedded systems). We sometimes prefer to use key exchange algorithms, like Diffie-Hellman, for a variety of reasons (e.g., before 2000, RSA was patented, which was a powerful reason, from the US Federal government point of view, to mandate usage of DH instead of RSA). Such algorithms are not exactly encryption in that you end up with a shared secret, but you do not get to choose that secret value. A shared secret is enough to serve as key for a symmetric encryption algorithm, but you need a symmetric encryption algorithm. The most often quoted reason, and actually the least compelling, is performance. Asymmetric encryption algorithms can entail some non-negligible CPU cost. E.g., RSA decryption (not encryption, which is faster) with 2048-bit RSA key will proceed at a rate of a few hundred instances per second on a modern laptop (a few thousands if you use several cores). The reason that this reason is what is always said about hybrid encryption is that it is what crypto teachers have repeated for years, starting from a root piece of wisdom dating from the late 1970s. The point about RSA being very slow was perfectly true at that time. But remember that computers of that era were like that one . A basic smartphone from 2014 has a lot more punch, by a factor of more than 10000. Even the chip from a recent credit card outperforms a 1980 desktop computer by a very wide margin. This "piece of wisdom" is severely outdated. Right now, we may still encounter performance issues if we are too heavy-handed on public-key crypto, but certainly not as much as is usually feared. Hollywood has trained people to think of cryptography as something ponderous, expensive, and graphic; this is all a lie, as unrealistic as Mark Hamill's hairdo. Summary: we don't "directly encrypt" files with the public key because we do not know how to do it securely; even if we did, it could be expensive; and we want to keep the possibility of using algorithms and key types which don't actually support encryption, only key exchange. | {} | {'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/64399', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/53015/']} | jdg_79757 |
stackexchange | llm_judgeable_groundtruth_similarity | 9486835 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there a tool which takes a Java File what describes a REST service as a parameter and generates a wadl file out of that.
Now provide the response and nothing else.
| I had the same problem: was using RESTeasy and wanted to find a way to generate the WADL automatically. Did some research and came to the solution below. 1. Add this to your pom.xml : <build><plugins> <plugin> <groupId>com.sun.jersey.contribs</groupId> <artifactId>maven-wadl-plugin</artifactId> <version>1.17</version> <executions> <execution> <id>generate</id> <goals> <goal>generate</goal> </goals> <phase>${javadoc-phase}</phase> </execution> </executions> <configuration> <wadlFile>${project.build.outputDirectory}/application.wadl </wadlFile> <formatWadlFile>true</formatWadlFile> <baseUri>http://example.com:8080/rest</baseUri> <packagesResourceConfig> <param>com.example.rs.resource</param> </packagesResourceConfig> <wadlGenerators> <wadlGeneratorDescription> <className>com.sun.jersey.server.wadl.generators.WadlGeneratorApplicationDoc </className> <properties> <property> <name>applicationDocsFile</name> <value>${basedir}/src/main/doc/application-doc.xml</value> </property> </properties> </wadlGeneratorDescription> <wadlGeneratorDescription> <className>com.sun.jersey.server.wadl.generators.WadlGeneratorGrammarsSupport </className> <properties> <property> <name>grammarsFile</name> <value>${basedir}/src/main/doc/application-grammars.xml</value> </property> </properties> </wadlGeneratorDescription> </wadlGenerators> </configuration> </plugin></plugins></build> Pay attention to the buildUri and packagesResourceConfig elements. You have to change them to reflect your project's configuration. You may also want to change the plugin's version (I used 1.17). 2. Create a /doc folder and add some files. Create the src/main/doc/ folder and create the two files below. File: application-doc.xml Content: <?xml version="1.0" encoding="UTF-8"?><applicationDocs targetNamespace="http://wadl.dev.java.net/2009/02"> <doc xml:lang="en" title="A message in the WADL">This is added to the start of the generated application.wadl</doc></applicationDocs> File: application-grammars.xml Content: <?xml version="1.0" encoding="UTF-8" ?><grammars xmlns="http://wadl.dev.java.net/2009/02" /> 3. Run the maven command. Go to the project folder and run the following command: $ mvn compile com.sun.jersey.contribs:maven-wadl-plugin:generate The files \target\classes\application.wadl (the WADL itself) and \target\classes\xsd0.xsd (the schema of the resources - it's used by the application.wadl) should be generated. Edit and use them as you wish. PS.: Bear in mind that this is a very simple use of the maven-wadl-plugin. It can do a lot more. To know it better, please refer to the zip file mentioned in the other answer (by Pavel Bucek). | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9486835', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1025692/']} | jdg_79758 |
stackexchange | llm_judgeable_groundtruth_similarity | 761148 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Firstly, is there a way to use document.write() inside of JQuery's $(document).ready() method? If there is, please clue me in because that will resolve my issue. Otherwise, I have someone's code that I'm supposed to make work with mine. The catch is that I am not allowed to alter his code in any way. The part that doesn't work looks something like this: document.write('<script src=\"http://myurl.com/page.aspx?id=1\"></script>'); The script tag is referencing an aspx page that does a series of tests and then spits out something like so: document.write('<img src=\"/image/1.jpg\" alt=\"Second image for id 1\">') The scripts are just examples of what is actually going on. The problem here is that I've got a document.write() in the initial script and a document.write() in the script that get's appended to the first script and I've got to somehow make this work within JQuery's $(document).ready() function, without changing his code. I have no idea what to do. Help?
Now provide the response and nothing else.
| With the requirements given , no, you can't use document.write without really hosing up the document. If you're really bent on not changing the code, you can override the functionality of document.write() like so and tack on the result later: var phbRequirement = "";$(function() { document.write = function(evil) { phbRequirement += evil; } document.write("Haha, you can't change my code!"); $('body').append(phbRequirement);}); Make sure you overwrite the document.write function before it is used. You can do it at anytime. The other answers are boring, this is fun, but very pretty much doing it the wrong way for the sake of fulfilling the requirements given. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/761148', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/60799/']} | jdg_79759 |
stackexchange | llm_judgeable_groundtruth_similarity | 2895516 |
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 red, blue, and green circles have diameters 3, 4, and 5, respectively. What is the radius of the black circle tangent to all three of these circles? I just figured out the radius is exactly $\dfrac{72}{23}$ but I don't know how to do the solution.
Now provide the response and nothing else.
| Let's find tangent circle by applying inversion transformation, or equivalently working in complex domain and applying reciprocal transformation $w=1/\overline{z}$. Let (0,0), or the inversion centre, be the intersection of 3 circles. Other circle intersections are $(0,3)$, $(4,0)$ and $\frac{12}{25}\left(3,4\right)$. Inversion transformation transform a circle passing through centre into a line, and other circles into circles. Thus, given three circles are transformed into lines, intersecting at 3 points; while big (still unknown) tangent circle transforms into circle tangent on those three lines. Transformed intersection coordinates are: $ \begin{array}{lcr} (0,3) && \longrightarrow&& \left(0,\frac{1}{3}\right)\\ (4,0) && \longrightarrow && \left(\frac{1}{4},0\right)\\ \frac{12}{25}\left(3,4\right) && \longrightarrow && \left(\frac{1}{4},\frac{1}{3}\right)\end{array} $ There are 4 circles that are tangent on all 3 lines: 1 inscribed and 3 escribed circle. The correct one has (0,0) in its interior. Finding coordinates of the centre and radius (solving quadratic equation) gives following circle: $c=\left(-\frac{1}{6},-\frac{1}{4}\right)\quad r=\frac{1}{2}$ Transforming back escribed circle gives the required tangent circle. Take notice that, while points on a circle transform into a circle, a circle centre does not transform to a corresponding circle centre. Radius of transformed circle can be deduce by working on the line that connects origin and centre of the circle. Transforming 2 points of the circle that are collinear with circle centre and the origin gives. $2R= \left|\frac{1}{|c|-r}-\frac{1}{|c|+r}\right|\\ R= \frac{r}{\left||c|^2-r^2\right|}\\ R=\frac{72}{23}$ Here is the picture with requested tangent circle, as well as one other tangent circle corresponding to the inscribed circle of the reciprocal space. | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/2895516', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']} | jdg_79760 |
stackexchange | llm_judgeable_groundtruth_similarity | 17348586 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
the assembly code is mov eax, 0x3a14a5jmp eax GAS produces an opcode of 0xB8, 0xA5, 0x14, 0x3A, 0x00 0xFF, 0xE0 while NASM produces and opcode of 0x66, 0xB8, 0xA5, 0x14, 0x3A, 0x00 0x66, 0xFF, 0xE0 So you see NASM preappends a 0x66 before the code. Within my program (which I won't go into details about), the GAS opcode works correctly, and the NASM code causes a crash indicating that these two opcodes are not equal. Why does NASM preappend the 0x66 and how can I get rid of it? update: The bits 32 directive worked. Thanks for the quick reply, links, and explanations!
Now provide the response and nothing else.
| Yes, for Cassandra UPDATE is synonymous with INSERT , as explained in the CQL documentation where it says the following about UPDATE : Note that unlike in SQL, UPDATE does not check the prior existence of the row: the row is created if none existed before, and updated otherwise. Furthermore, there is no mean to know which of creation or update happened. In fact, the semantic of INSERT and UPDATE are identical. For the semantics to be different, Cassandra would need to do a read to know if the row already exists. Cassandra is write optimized, so you can always assume it doesn't do a read before write on any write operation. The only exception is counters (unless replicate_on_write = false ), in which case replication on increment involves a read. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/17348586', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2254852/']} | jdg_79761 |
stackexchange | llm_judgeable_groundtruth_similarity | 1716979 |
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 a simple question, but in everything I've read, I've never seen this spelled out specifically. If you do a query on a page, do you need to worry about SQL injection attacks? Or is it only a problem when you ask the user for input? Thanks!
Now provide the response and nothing else.
| You don't have to have user input to suffer a SQL injection attack. Let's say you have a product page that is called using a URL such as this: product.aspx?ID=123 And in your code you have a query constructed such as this: string sql = "SELECT * FROM Products WHERE ID = " + Request.Querystring["ID"]; Someone could call your page with this url: product.aspx?ID=123;DROP Table Students; And bam, you've just been had. In addition to ANYTHING that can be passed in via a user, querystring, post, cookie, browser variable, etc. I think it is just good practice to always use parameters, even if you have the literals in your code. For example: if(SomeCondition){ sql = "Select * from myTable where someCol = 'foo'";}else{ sql = "Select * from myTable where someCol = 'bar'";} this may be injection safe, but your RDBMS will cache them as two different queries.if you modiy it to this: sql = "Select * from myTable where someCol = @myParam";if(SomeCondition){ myCommand.Parameters.Add("@myParam").value = "foo";}else{ myCommand.Parameters.Add("@myParam").value = "bar";} You achieve the same result but the RDBMS will only cache it as one query, substituting the parameter at runtime. I use it as a rule of thumb to ALWAYS use parameterized queries, just to keep things consistent, not to mention a slight cache improvement. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1716979', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/80151/']} | jdg_79762 |
stackexchange | llm_judgeable_groundtruth_similarity | 6759463 |
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 list all users from the specific local group in the following format: "Domain\UserName". I can extract collection of GroupPrincipal objects for the group, but I don't know how to get users in required format. GroupPrincipal doesn't have property Domain. The following code outputs users without domain (e.g. "UserName"). using (var context = new PrincipalContext(ContextType.Machine, null)){ using (var group = GroupPrincipal.FindByIdentity(context, IdentityType.SamAccountName, @"My Local Group")) { if (group != null) { foreach (var p in group.GetMembers(false)) { Console.WriteLine(p.SamAccountName); } } }} Is it possible to get domain netbios name from the principal object? And if so, how to get it?
Now provide the response and nothing else.
| You can get the domain details from the principal's Context. e.g.: foreach (var p in group.GetMembers(false)) { Console.Write(p.SamAccountName); if (p.ContextType == ContextType.Domain) { Console.Write(" ({0})", p.Context.Name); } Console.WriteLine(); } If you just want to output account names in the "domain\user" format from a machine on the domain, you can translate the principal's SecurityIdentifier to an NTAccount. e.g.: foreach (var p in group.GetMembers(false)){ Console.WriteLine(p.Sid.Translate(typeof(NTAccount)).ToString());} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6759463', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/94803/']} | jdg_79763 |
stackexchange | llm_judgeable_groundtruth_similarity | 7898446 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
For example, I have 2 Maven projects. One is "project-parent". The other is "project-child". Obviously, "project-child" is the sub project of "project-parent". "project-parent" has a dependency of log4j. But I want to exclude it from the "project-child". Is there a way? You might say I should move log4j from "project-parent" to "project-child". That is totally correct. But the assumption is I CANNOT modify "project-parent"'s POM. Thanks in advance.
Now provide the response and nothing else.
| I think in Maven2 there is no way to achieve this, because this is what POM inheritance is for . However there is one trick that I can think of: Assume you have the right to upload artifact to your internal artifact repository. You may create an empty JAR, deploy it as log4j:log4j, with a obviously abnormal version (e.g. log4j:log4j:9999 ). Add such dependency in your project-child. Then it will override the dependency of parent to depends on a in-fact-empty JAR. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7898446', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/569472/']} | jdg_79764 |
stackexchange | llm_judgeable_groundtruth_similarity | 28896609 |
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 use case where I can get pointers of strings allocated either in memory or literals. Now the latter can't be freed so that's a problem if I pass the wrong one. Is there a way to know which one is allocated and which not? char *b = "dont free me!";if(!IS_LITERAL(b)) { free(b);} I imagine something like that. My example: Scenario 1: literal char *b = "dont free me!";scruct elem* my_element = mylib_create_element(b);// do smthint result = mylib_destroy_element(my_element); // free literal, very bad Scenario 2: in heap char *b = malloc(sizeof(char)*17); // examplestrncpy(b, "you can free me!",17);scruct elem* my_element = mylib_create_element(b);// do smthint result = mylib_destroy_element(my_element); // free heap, nice How the user calls mylib_create_element(b); is not under my control. If he frees before mylib_destroy_element it can crash. So it has got to be mylib_destroy_element that cleans up.
Now provide the response and nothing else.
| I've had a similar case recently. Here's what I did: If you're making an API that accepts a string pointer and then uses it to create an object ( mylib_create_element ), a good idea would be to copy the string to a separate heap buffer and then free it at your discretion. This way, the user is responsible for freeing the string he used in the call to your API, which makes sense. It's his string, after all. Note that this won't work if your API depends on the user changing the string after creating the object! | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/28896609', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2474098/']} | jdg_79765 |
stackexchange | llm_judgeable_groundtruth_similarity | 236212 |
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:
Two $n\times n$ matrices $A, B$ are said to be simultaneously diagonalizable if there is a nonsingular matrix $S$ such that both $S^{-1}AS$ and $S^{-1}BS$ are diagonal matrices. a) Show that simultaneously diagonalizable matrices commute: $AB = BA$ . b) Prove that the converse is valid, provided that one of the matrices has no multiple eigenvalues. Is every pair of commuting matrices simultaneously diagonalizable? My attempt: a) Let $$M=S^{-1}AS \qquad\text{and}\qquad P=S^{-1}BS.$$ It follows that $$A= S^{-1}MS \qquad\text{and}\qquad B=S^{-1}PS. \tag{Eq. 1}$$ Thus, \begin{align}A\,B &=S^{-1}\,M\,S\,S^{-1}\,P\,S &&\text{substitution of diagonal forms}\\A\,B &=S^{-1}\,M\,I\,P\,S &&\text{Identity element}\\&= S^{-1}\,M\,P\,S && \text{Multiplication by identity }\\&= S^{-1}\,P\,M\,S &&\text{$M$ and $P$ diagonal }\\&= S^{-1}\,P\,I\,M\,S &&\text{Multiplication by identity}\\&=S^{-1}\,P\, \left[SS^{-1}\right]\,M\, S&& \text{$S$ has inverse by premise}\\&=\left[S^{-1}\,P\, S\right] \left[S^{-1}\,M\, S\right]&& \text{associative properties of matrices}\\&=B\,A &&\text{Eq. 1}.\end{align} b) How can I do this?
Now provide the response and nothing else.
| This has undoubtedly been answered (likely multiple times) here before, so I post this at the risk of beating a dead (and decaying) horse. Let me first link you to this page, which contains two excellent answers (I particularly recommend Keith Conrad's expository paper linked in Pierre-Yves Gaillard's answer). However, let me provide a perhaps more elementary viewpoint since, from experience, many people beginning this topic are not quite comfortable with minimal polynomial based arguments yet. You seem to have covered part a quite adequately so let me focus on part b. I apologize in advance for the length, but I feel that this is a topic which requires thorough understanding. The main thing to remember about commuting matrices is the fact that commuting matrices respect each other's eigenspaces . What does this mean? To talk about that, we first have to introduce the topic of an invariant subspace . Consider a matrix mapping $A:\ V \rightarrow V$ for a vector space $V$. If there is some subspace $U$ of $V$ such that the restriction of $A$ to $U$ remains an operator in the sense that $A:\ U\rightarrow U$, then we say that $U$ is an invariant subspace of $A$. The term stable is also sometimes used. The significance of this is that $A(U) \subseteq U$, the image of $U$ is entirely contained within $U$. This way, it makes sense to talk about a restriction of the mapping to the smaller vector space $U$. This is desirable for several reasons, the main one being that linear mappings on smaller vector spaces are easier to analyze. We can look at the action of the mapping on each invariant subspace and then piece them together to get an overall picture. This is what diagonalization does; we break down the vector space into smaller invariant subspaces, the eigenspaces , and then piece together the facts to get a simpler picture of how the mapping works. Many of the simpler, canonical representations are dependent on this fact (for example, the Jordan canonical form looks at the invariant generalized eigenspaces ). Now, if we have two commuting, diagonalizable matrices, then each eigenspace of $B$ is not only invariant under $B$ itself, but also under $A$. This is what we mean by preserving each other's eigenspaces . To see this, let $\mathbf{v}$ be an eigenvector of $B$ under eigenvalue $\lambda$. Then$$B(A\mathbf{v}) = A(B\mathbf{v}) = \lambda A\mathbf{v}$$so that $A\mathbf{v}$ is again an eigenvector of $B$ under eigenvalue $\lambda$. In our new language, this means that the eigenspace $E_\lambda$ of $B$ is invariant under $A$. This means it makes sense to look at the restriction of $A$ to $E_\lambda$. Now consider the restriction of $A$ to $E_\lambda$. If all the eigenvalues of $B$ are simple (multiplicity one) then that means each eigenspace of $B$ is one dimensional. We have therefore restricted $A:\ E_\lambda \rightarrow E_\lambda$ to a mapping on a one-dimensional vector space. But this means that $A$ must take each vector of $E_\lambda$ to a scalar multiple of itself. You can check that this necessarily implies that $E_\lambda$ is also an eigenspace of $A$. Therefore, for any eigenbasis of $B$ that we take, the corresponding vectors also form an eigenbasis of $A$. This means that the two matrices are simultaneously diagonalizable; they share a common eigenbasis. The general case is a bit more involved in that the restrictions to the invariant subspaces are more complex (they're no longer one-dimensional), but the ideas are identical. P.S. Since you seem to be interested in physics, let me mention a crucial application of commuting operators. In quantum mechanics, you have quantities called observables , each of which is roughly speaking represented by a Hermitian matrix. Unlike in classical physics, different observables need not be simultaneously measurable (by measuring position for example, you cannot simultaneously measure momentum and vice versa) which is ultimately due to the fact that the position operator and the momentum operator do not commute (this is the underlying reasons behind the uncertainty principle ). They do not have a shared basis which can represent the states of a system. Commuting operators therefore form a key element of quantum physics in that they define quantities which are compatible , i.e. simultaneously defined. | {} | {'log_upvote_score': 9, 'links': ['https://math.stackexchange.com/questions/236212', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/40285/']} | jdg_79766 |
stackexchange | llm_judgeable_groundtruth_similarity | 91366 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
This is a theorem proved in Rudin. Theorem. Let $E_n, n=1,2,3,\ldots$ be a sequence of countable sets, and put $S=\bigcup_{n=1}^\infty E_n$. Then $S$ is countable. Proof. Let every set $E_n$ be arranged in a sequence $x_{nk}, k=1,2,3,\ldots$, and consider the infinite array $$\begin{array}{cccc}x_{11}&x_{12}&x_{13}&\cdots\\x_{21}&x_{22}&x_{23}&\cdots\\x_{31}&x_{32}&x_{33}&\cdots\\\vdots&\vdots&\vdots&\ddots\end{array}$$ in which elements of $E_n$ form the $n$th row. The array contains all elements of $S$. As indicated by the arrows in this picture — — these elements can be arranged in a sequence $$x_{11};x_{21},x_{12};x_{31},x_{22},x_{13};x_{41},x_{32},x_{23},x_{14};\ldots.\qquad(17)$$ If any two of the sets $E_n$ have elements in common, these will appear more than once in $(17)$. Hence there is a subset $T$ of the set of all positive integers such that $S\sim T$, which shows that $S$ is at most countable (Theorem 2.8). Since $E_1\subset S$ and $E_1$ is infinite, $S$ is infinite, and thus countable. I've a hard time visualizing/understanding the last part of the proof though[(17) onwards], will someone please give an intuitive explanation/description of the last paragraph to help me in understanding the proof?
Now provide the response and nothing else.
| The idea in the last paragraph is that in this sequence we many name the same element twice. This can happen if some $x$ is in two of the $E_k$ sets. Hence the author points out that the function that sends every natural number $n$ to the $n$th element of that sequence is not bijective. To make it bijective, we have to restrict its domain to some subset of the natural numbers (such that not two natural numbers are sent to the same element). Hence, $S$ is equinumerous with a subset of natural numbers. Now we know (and I assume this is theorem 2.8) that every subset of the natural numbers is either countably infinite or finite. Therefore up until now we have only shown that $S$ is either countably infinite or finite. But, we already know that it contains at least countably infinite elements, the elements of $E_1$. Hence it cannot be finite. This implies that it is countable. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/91366', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/16039/']} | jdg_79767 |
stackexchange | llm_judgeable_groundtruth_similarity | 600876 |
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:
No doubt this is a stupid question but I can't seem to find help anywhere online. I want to do a logistic regression with 2 independent variables. Ideally, I would like to see how each variable compares to the mean but for some reason, in R, I'm not able to do this. Whatever I try, I always get comparison with at least one of the explanatory variables. See the example and output below: set.seed(123)group1 <- rep(c("A", "B", "C"), times = 100)group2 <- rep(c("D", "E", "F"), each = 100)dat <- rbinom(300, 1, 0.5)model <- glm(dat ~ group1 + group2 + 0, family = binomial)summary(model)#Coefficients:# Estimate Std. Error z value Pr(>|z|)#group1A 0.14471 0.25837 0.560 0.575#group1B -0.17756 0.25991 -0.683 0.495#group1C -0.33858 0.26139 -1.295 0.195#group2E 0.12461 0.28455 0.438 0.661#group2F 0.04537 0.28466 0.159 0.873 If I did something similar with a linear regression, I would get an intercept which would be the mean of all the data, and then the other variables would show how that differs from the mean. However here, I am pretty sure that all the variables are showing me how they differ from the mean at group D. Surely it's not a matter of having to estimate too many variables. There are 300 data points. All I would like to know is the overall mean (log odds ratio) and how groups A-F differ from that mean. What am I missing? EDIT:I went with a workaround that is a bit subpar.In a loop, I construct an indicator variable that is 1 if it's the group (i.e. group D) that I'm interested in and 0 otherwise. Then I loop through the groups (about 100 for the problem I have) constructing a model each time with the indicator variable as an explanatory variable as well as the other variables I wanted to account for. It takes a little bit of time to load but it's not completely infeasible. Do let me know if there is another workaround where I could just put the raw data in to begin with and have everyone compared to the overall mean. A worked example would be nice.
Now provide the response and nothing else.
| Yes, there are. To name just one, which I've had good experiences with, you can minimize the Cramer-von Mises distance between the empirical distribution and the theoretical distribution with estimated parameters, possibly throwing out a specified percentage of the lowest and highest data points (or not; see below.) The C-vM distance is: $$\omega^2 = \int_{-\infty}^{\infty} [F_n(x) - F(x;\theta)]^2\,\mathrm{d}F(x;\theta)$$ Obviously, in the case of a discrete distribution, you would use the sum, and you would integrate / sum over a prespecified subset of the data, making the appropriate adjustments in the calculation of $F(x;\theta)$ . Some general links are below: The Consistency and Robustness of Modified Cramer-Von Mises and Kolmogorov-Cramer Estimators Robust Weighted Cramer-von Mises estimators of location... Robust estimation vis minimum distance methods Robust Estimation with Exponentially Tilted Hellinger Distance To see why this estimator is robust against small amounts of contamination (we will address the larger amounts of contamination case below), consider the function itself. The range of values of the square term is $[0,1]$ ; no matter how big an outlier in a sample of size $N$ we see, the influence of it on the squared term is limited by the $1/N$ change it can inflict on the empirical CDF. Likewise, as an outlier becomes more extreme, $\mathrm{d}F(x;\theta)$ goes to zero, further limiting its influence. There still is some influence, as the outlier reduces the empirical CDF of all the non-outlier data points by a factor of $(N-1)/N$ . To illustrate this, we construct an example. We generate 100 data points from a $\mathrm{Poisson(1)}$ distribution, and replace the $100^{th}$ with an increasing outlier. We calculate the C-vM estimate of the parameter $\theta$ , and plot how the estimate changes as the outlier increases: cvm.calc <- function(theta, x) { ub <- max(qpois(0.9999, theta)+1, length(x)) if (ub > length(x)) { x <- c(x, rep(1, ub-length(x))) } sum_over_range <- 0:(ub-1) sum((x-ppois(sum_over_range, theta))^2 * dpois(sum_over_range, theta))}x <- rpois(100, 1)estimate <- rep(0,51)for (outlier in 0:50) { x[100] <- outlier xtbl <- table(factor(x, 0:max(x))) x_edf <- cumsum(xtbl) / sum(xtbl) estimate[outlier+1] <- optimize(cvm.calc, interval=c(0.1,5), x=x_edf)$minimum}plot(estimate~I(0:50), type="b", pch=16, main="Sensitivity Curve - 1% Contaminated Poisson(1)", xlab="Outlier (1 % contamination)", ylab="C-vM Estimate")mean(x[1:99]) # The sample mean of the first 99 observations[1] 1.030303mean(x) # The sample mean with the 100th observation = 50[1] 1.52 with the result: A similar plot, this time with 10% of the data replaced by outliers, results in: with a sample mean in the outlier <- 50 case of 5.9. In the more general case, where we expect larger amounts of contamination, we can always use a truncated version of both the empirical distribution function and the theoretical distribution function, e.g., dropping the top $\alpha \%$ of the data and adjusting the theoretical distribution accordingly. An obvious question is: how efficient is it in the zero-outlier case? A simulation will help to answer that in the $\mathrm{Poisson(1)}$ case: cvm_estimate <- rep(0,10000)for (i in seq_along(cvm_estimate)) { x <- rpois(100, 1) xtbl <- table(factor(x, 0:max(x))) x_edf <- cumsum(xtbl) / sum(xtbl) cvm_estimate[i] <- optimize(cvm.calc, interval=c(0.1,5), x=x_edf)$minimum} mean((cvm_estimate - 1)^2)[1] 0.01102528 which is only slightly worse than the MSE of the sample mean $(0.01)$ . | {} | {'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/600876', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/186328/']} | jdg_79768 |
stackexchange | llm_judgeable_groundtruth_similarity | 20065780 |
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 having a discussion with a teammate about locking in .NET. He's a really bright guy with an extensive background in both lower-level and higher-level programming, but his experience with lower level programming far exceeds mine. Anyway, He argued that .NET locking should be avoided on critical systems expected to be under heavy-load if at all possible in order to avoid the admittedly small possibility of a "zombie thread" crashing a system. I routinely use locking and I didn't know what a "zombie thread" was, so I asked. The impression I got from his explanation is that a zombie thread is a thread that has terminated but somehow still holds onto some resources. An example he gave of how a zombie thread could break a system was a thread begins some procedure after locking on some object, and then is at some point terminated before the lock can be released. This situation has the potential to crash the system, because eventually, attempts to execute that method will result in the threads all waiting for access to an object that will never be returned, because the thread that is using the locked object is dead. I think I got the gist of this, but if I'm off base, please let me know. The concept made sense to me. I wasn't completely convinced that this was a real scenario that could happen in .NET. I've never previously heard of "zombies", but I do recognize that programmers who have worked in depth at lower levels tend to have a deeper understanding of computing fundamentals (like threading). I definitely do see the value in locking, however, and I have seen many world class programmers leverage locking. I also have limited ability to evaluate this for myself because I know that the lock(obj) statement is really just syntactic sugar for: bool lockWasTaken = false;var temp = obj;try { Monitor.Enter(temp, ref lockWasTaken); { body } }finally { if (lockWasTaken) Monitor.Exit(temp); } and because Monitor.Enter and Monitor.Exit are marked extern . It seems conceivable that .NET does some kind of processing that protects threads from exposure to system components that could have this kind of impact, but that is purely speculative and probably just based on the fact that I've never heard of "zombie threads" before. So, I'm hoping I can get some feedback on this here: Is there a clearer definition of a "zombie thread" than what I've explained here? Can zombie threads occur on .NET? (Why/Why not?) If applicable, How could I force the creation of a zombie thread in .NET? If applicable, How can I leverage locking without risking a zombie thread scenario in .NET? Update I asked this question a little over two years ago. Today this happened:
Now provide the response and nothing else.
| Is there a clearer definition of a "zombie thread" than what I've explained here? Seems like a pretty good explanation to me - a thread that has terminated (and can therefore no longer release any resources), but whose resources (e.g. handles) are still around and (potentially) causing problems. Can zombie threads occur on .NET? (Why/Why not?) If applicable, How could I force the creation of a zombie thread in .NET? They sure do, look, I made one! [DllImport("kernel32.dll")]private static extern void ExitThread(uint dwExitCode);static void Main(string[] args){ new Thread(Target).Start(); Console.ReadLine();}private static void Target(){ using (var file = File.Open("test.txt", FileMode.OpenOrCreate)) { ExitThread(0); }} This program starts a thread Target which opens a file and then immediately kills itself using ExitThread . The resulting zombie thread will never release the handle to the "test.txt" file and so the file will remain open until the program terminates (you can check with process explorer or similar). The handle to "test.txt" won't be released until GC.Collect is called - it turns out it is even more difficult than I thought to create a zombie thread that leaks handles) If applicable, How can I leverage locking without risking a zombie thread scenario in .NET? Don't do what I just did! As long as your code cleans up after itself correctly (use Safe Handles or equivalent classes if working with unmanaged resources), and as long as you don't go out of your way to kill threads in weird and wonderful ways (safest way is just to never kill threads - let them terminate themselves normally, or through exceptions if necessary), the only way that you are going to have something resembling a zombie thread is if something has gone very wrong (e.g. something goes wrong in the CLR). In fact its actually surprisingly difficult to create a zombie thread (I had to P/Invoke into a function that esentially tells you in the documentation not to call it outside of C). For example the following (awful) code actually doesn't create a zombie thread. static void Main(string[] args){ var thread = new Thread(Target); thread.Start(); // Ugh, never call Abort... thread.Abort(); Console.ReadLine();}private static void Target(){ // Ouch, open file which isn't closed... var file = File.Open("test.txt", FileMode.OpenOrCreate); while (true) { Thread.Sleep(1); } GC.KeepAlive(file);} Despite making some pretty awful mistakes, the handle to "test.txt" is still closed as soon as Abort is called (as part of the finalizer for file which under the covers uses SafeFileHandle to wrap its file handle) The locking example in C.Evenhuis answer is probably the easiest way to fail to release a resource (a lock in this case) when a thread is terminated in a non-weird way, but thats easily fixed by either using a lock statement instead, or putting the release in a finally block. See also Subtleties of C# ILcodegen for a very subtle case where an exception can prevent a lock frombeing released even when using the lock keyword (but only in .Net 3.5 and earlier) Locks and exceptions do notmix | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/20065780', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/344211/']} | jdg_79769 |
stackexchange | llm_judgeable_groundtruth_similarity | 100808 |
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 been reading information on making passwords secure, but what are the reasons an attacker would want to put effort into getting the original password? If an attacker does indeed have a copy of the database, then they have a copy of the database, and all of the information they would gain by logging into the account. Here are some of the reasons I can think of: The user may be using the password on a different site.Some of the users data may be encrypted.The attacker may want to access the account later.The attacker may want to modify the users data, and only had read access to the server's database.The attacker did not gain all information from the database. Would policies such as two-factor authentication, and picking a random password for a user make cracking a password worthless for an attacker that has already had access to the database?
Now provide the response and nothing else.
| TL;DR: The answer is no. A user cannot be stopped from reusing the given random password on other sites, so a text based password will always have value to an attacker. This is true for all sites with usernames, and passwords. Enforcing random passwords rarely works: it makes your users (customers ?) go away. Suggesting random passwords, and offering a generation tool, are good ideas, as long as they are not made compulsory. However, even if you succeed in enticing your users into using random-generated passwords for your site, you cannot prevent them from using the same passwords on another site. It can be expected that after having made the effort of remembering a random password, a substantial proportion of users will find it smart to reuse that effort, i.e. reuse the very same password elsewhere. This is a very general property: as long as a user "knows" his password (and he must certainly know it in order to type it), then he can reuse that password in other systems that are outside of your reach. You cannot do anything about it, except trying to explain to users why this is not a good idea. As for two-factor authentication: when it is there, it is for a reason, i.e. because one factor was not enough. If an attacker cracked a user password, then the user's two factors shrunk to one factor only. If one factor is not enough, then it is not enough . Or, said otherwise, if users authenticate with a password and a mobile phone, and cracking the password is not a problem, then why bother with passwords at all ? Just use the phone. | {} | {'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/100808', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/87324/']} | jdg_79770 |
stackexchange | llm_judgeable_groundtruth_similarity | 3969650 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
can anyone help me with the length of maximum characters that can be contain in a normal HTML text box....
Now provide the response and nothing else.
| As to the HTML side, when the maxlength attribute is not specified, then the maximum length of the input value is unlimited. However, if you're sending the request as GET instead of POST , then the limit will depend on the webbrowser and webserver used. The HTTP 1.1 specification even warns about this, here's an extract of chapter 3.2.1 : Note: Servers ought to be cautious about depending on URI lengths above 255 bytes, because some older client or proxy implementations might not properly support these lengths. As to the webbrowsers, the practical limit is in Firefox about 8KB, in Opera about 4KB and in IE and Safari about 2KB. So the total length of all inputs should not exceed this if you want a succesful processing. As to the webservers, most have a configureable limit of 8KB. When the limit is exceeded, then it will often just be truncated, but some webservers may send a HTTP 414 error . When you're sending the request as POST , then the limit depends on the server config. Often it's around 2GB. When it's exceeded, the server will often return a HTTP 500 error . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3969650', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/293709/']} | jdg_79771 |
stackexchange | llm_judgeable_groundtruth_similarity | 810753 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Prove that every odd prime number can be written as a difference of two squares. Prove also that this presentation is unique. Is such presentation possible if p is just an odd natural number? Can 2 be represented this way? Answers \3. Yes the presentation (i.e. odd numbers being written as differences of two squares) is possible for all odd natural number however the presentation may not be unique. For example, $57=11^2-8^2=29^2-28^2$. \4. 2 can't be written as a difference of two squares because 4-1=3 and 1-1=0 and the difference of squares grows to integers larger that 3. Can I get some help in proving questions 1 and 2?
Now provide the response and nothing else.
| $1$. Let $(x+y)(x-y) = p$ Since $p$ is prime, the smaller divisor has to be one, ie. $(x-y) = 1$, giving $2y+1 = p \implies y = \frac{p-1}{2}$ (you're guaranteed y is an integer because $p$ is an odd number). So the only possible solution set is $x = \frac{p+1}{2}, y = \frac{p-1}{2}$ $2$. Uniqueness already established via reasoning above. $3$. Possible, but it will be non-unique as $(x-y)$ can take on multiple values, e.g. $1$ or a single prime divisor of $p$ or a product of some (but not all) prime divisors of $p$. $4$. No, because again $(x-y)$ = 1 is forced. But now you get $x = \frac{3}{2}$ which is non-integral. So no integer solution sets exist. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/810753', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/62874/']} | jdg_79772 |
stackexchange | llm_judgeable_groundtruth_similarity | 4781478 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm working in a web application separated in blocks and I'm getting a CSV object from a work mate of mine which I must convert into XLS to be passed into an Excel Processor they built.This CSV object is delimited by the character ";". What I'd like to know is how I can convert the CSV object into XLS programatically.
Now provide the response and nothing else.
| It should be easy for you to convert the CSV object into an array of arrays of strings and then do like in the following example (you'll need to add a reference to Microsoft.Office.Interop.Excel): using Excel = Microsoft.Office.Interop.Excel;Excel.Application excel = new Excel.Application();Excel.Workbook workBook = excel.Workbooks.Add();Excel.Worksheet sheet = workBook.ActiveSheet;var CsvContent = new string[][]{ new string[] {"FirstName", "UserName", "PostCode", "City"}, new string[] {"John", "Smith", "4568", "London"}, new string[] {"Brian", "May", "9999", "Acapulco"}};for (int i = 0; i < CsvContent.Length; i++){ string[] CsvLine = CsvContent[i]; for (int j = 0; j < CsvLine.Length; j++) { sheet.Cells[i + 1, j + 1] = CsvLine[j]; }}workBook.SaveAs(@"C:\Temp\fromCsv.xls");workBook.Close(); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4781478', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/358406/']} | jdg_79773 |
stackexchange | llm_judgeable_groundtruth_similarity | 1521465 |
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 $N$ and $N'$ be two sets. Is it possible that $N \subseteq N \times N'$? I don't think so, but actually I am not able to get any absurd sentences supposing that is true. Let us suppose that $N \subseteq N \times N'$. Then, for any $x \in N$ there exist $n \in N$, $n' \in N'$, such that $x = (n,n')$. But then there exist $m \in N$, $m' \in N'$, such that $n=(m,m')$, $x=((m,m'),n)$ and so on. I see it is ugly, but I can't understand why it is absurd.
Now provide the response and nothing else.
| Suppose that $N\subseteq N\times N'$, and let $n_0\in N$; then there are $n_1\in N$ and $n_1'\in N'$ such that $n_0=\langle n_1,n_1'\rangle$. In general, given $n_k\in N$ we must have $n_{k+1}\in N$ and $n_{k+1}'\in N'$ such that $n_k=\langle n_{k+1},n_{k+1}'\rangle$, and in this way we can recursively define a sequence $\langle n_k:k\in\omega\rangle$ in $N$. Now $\langle x,y\rangle=\big\{\{x\},\{x,y\}\big\}$, so $x\in\{x\}\in\langle x,y\rangle$. Thus, $$\ldots\in n_3\in\{n_3\}\in n_2\in\{n_2\}\in n_1\in\{n_1\}\in n_0$$ is an infinite descending $\in$-chain, which violates the axiom of regularity . | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1521465', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']} | jdg_79774 |
stackexchange | llm_judgeable_groundtruth_similarity | 44688460 |
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 a to find patterns that are 6 digits and the first 3 digits are specific digits, but the remaining 3 digits will be any digit.For example, 6 digit strings starting with 123 followed by any 3 digits. var1="abc,123111,"var2="abcdefg,123222,"var3="xyzabc,987111,"if [[ $var1 == *",123ddd,"* ]] ; then echo "Pattern matched"; fi Where ddd are any digits. var1 and var2 would match the pattern but var 3 would not. I can't seem to get it just right.
Now provide the response and nothing else.
| Use a character class: [0-9] matches 0 , 9 , and every character between them in the character set, which - at least in Unicode (e.g. UTF-8) and subset character sets (e.g. US-ASCII, Latin-1) - are the digits 1 through 8 . So it matches any one of the 10 Latin digits. if [[ $var1 == *,123[0-9][0-9][0-9],* ]] ; then echo "Pattern matched"; fi Using =~ instead of == changes the pattern type from shell standard "glob" patterns to regular expressions ("regexes" for short). You can make an equivalent regex a little shorter: if [[ $var1 =~ ,123[0-9]{3}, ]] ; then echo "Pattern matched"; fi The first shortening comes from the fact that a regex only has to match any part of the string, not the whole thing. Therefore you don't need the equivalent of the leading and trailing * s that you find in the glob pattern. The second length reduction is due to the {n} syntax, which lets you specify an exact number of repetitions of the previous pattern instead of actually repeating the pattern itself in the regex. (You can also match any of a range of repetition counts by specifying a minimum and maximum, such as [0-9]{2,4} to match either two, three, or four digits in a row.) It's worth noting that you could also use a named character class to match digits. Depending on your locale, [[:digit:]] may be exactly equivalent to [0-9] , or it may include characters from other scripts with the Unicode "Number, Decimal Digit" property. if [[ $var1 =~ ,123[[:digit:]]{3}, ]] ; then echo "Pattern matched"; fi | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/44688460', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8197032/']} | jdg_79775 |
stackexchange | llm_judgeable_groundtruth_similarity | 3404055 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Can anyone help me? I have list of fields called 'allowed_fields' and I have object called 'individual'. allowed_fields is sub set of individual. Now I want to run loop like this for field in allowed_fields: obj.field = individual.field obj have same fields like individual. Do you have solution of my problem? I will thankful to you.
Now provide the response and nothing else.
| Application.Run(new CustomContext()); That's okay, but you don't store a reference to the CustomContext object you created. There's thus no way to call its ExitThread method. Tweak it like this: class Program { private static CustomContext appContext; [STAThread] public static void Main() { // Init code //... appContext = new CustomContext(); Application.Run(appContext); } public static void Quit() { appContext.ExitThread(); }} Now you can simply call Program.Quit() to stop the message loop. Check my answer in this thread for a better way to implement a single-instance app. The WindowsFormsApplicationBase class also offers the ShutdownStyle property, probably useful to you instead of ApplicationContext. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3404055', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/410564/']} | jdg_79776 |
stackexchange | llm_judgeable_groundtruth_similarity | 1035308 |
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:
Compute $$\lim_{x\to\infty}{3^x\over \sqrt {9^x - 4^x}}$$ Can one use end behavior to solve this? I.E. $$\lim_{x\to\infty}{\sqrt{3^{2x}\over (3^{2x} - 2^{2x})}}$$ and therefore divide $3^{2x}$ by $3^{2x}$ ? leaving us with an anwser of $1$ ?
Now provide the response and nothing else.
| HINT. Yes, note that:$${\sqrt{3^{2x}\over (3^{2x} - 2^{2x})}}={\sqrt{3^{2x}\over 3^{2x}\left(1 - \left(\frac{2}{3}\right)^{2x}\right)}}$$but$\left(\frac{2}{3}\right)^{2x}\rightarrow 0$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1035308', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/194608/']} | jdg_79777 |
stackexchange | llm_judgeable_groundtruth_similarity | 382567 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm using HP DL360p Generation 8. I need a pretty reliable server, so I'm using RAID 1 with a spare drive, and I also added an extra power supply. But should I install online spare memory? Or it's just wasting money?
Now provide the response and nothing else.
| It's not worth it. With ECC RAM and running HP management agents, it's pretty easy to detect bad memory. There are typically a few steps to intervene before you see a major problem that affects operation. Under standard support, RAM replacement is next-business-day, so there's no need to complicate your RAM arrangement by adding spare DIMMs. The worst HP ProLiant memory issue I had on a system eventually crashed the server after several ECC alerts that occurred over the course of a week. The errors came, the server rebooted through an ASR and the machine came back up with the bad DIMM disabled. This was an HP ProLiant DL580 G4 system and the error logs were as follows... 0004 Repaired 22:21 12/01/2008 22:21 12/01/2008 0001LOG: Corrected Memory Error threshold exceeded (Slot 1, Memory Module 1)0005 Repaired 20:41 12/06/2008 20:43 12/06/2008 0002LOG: POST Error: 201-Memory Error Single-bit error occured during memory initialization, Board 1, DIMM 1. Bank containing DIMM(s) has been disabled. Back in the day, I installed many HP ProLiant DL740 servers that featured a RAID5-style memory array. So a 16GB RAM server actually had 20GB installed in hot-swappable banks of 8 DIMMS. For the dozens of those servers that I deployed and ran for 5+ years, I only had one DIMM module fail. Figures... Edit: You're planning to use this in a high-frequency trading environment. You asked about latency with spare RAM in a server like this. Typically, for low-latency applications, I disable the memory pre-failure checks on my host systems. This is the recommendation from HP on page 7 of their Configuring the HP ProLiant Server BIOS for Low-Latency Applications white paper. It's a matter of monitoring and risk. I rarely have DIMMs fail. Do you care more about speed or resiliency? You won't get both at the hardware level... | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/382567', 'https://serverfault.com', 'https://serverfault.com/users/107579/']} | jdg_79778 |
stackexchange | llm_judgeable_groundtruth_similarity | 23203169 |
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 some reason I'm getting the error undefined method '%' for 1..100:Range when I run the following code: [1..100].each do |x| if x % 3 == 0 && x % 5 == 0 puts "CracklePop" elsif x % 3 == 0 puts "Crackle" elsif x % 5 == 0 puts "Pop" else puts x endend Any idea what's going on? Any help is much appreciated.
Now provide the response and nothing else.
| That's the wrong syntax for ranges. You've made an array with 1 element, and that element is itself the range 1..100 . What you've written is equivalent to [(1.100)] . You're iterating over the outer array one time, and setting x to (1..100) You want (1..100).each , which invokes each on the range, not on an array containing the range. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23203169', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2511012/']} | jdg_79779 |
stackexchange | llm_judgeable_groundtruth_similarity | 858750 |
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 know that Lyapunov equation: $A^TP + PA + Q = 0$ Algebraic Riccati equation: $A^TP + PA + Q + PBR^{-1}B^TP= 0$ It seems that the difference between the two lies in $B = 0$ (zero input) in Lyapunov Eqand both are infinite horizon in the case above. Is there any other engineering-sense difference (not mathematics) between the two Eqs? Thanks!
Now provide the response and nothing else.
| Lyapunov equation is used for the stability analysis of a relaxed system, I.e. no input signal. There exists a unique positive definite $P$ for any given positive definite $Q$ if and only if the system $\dot{x}=Ax$ is globally asymptotically stable. This means we can make $\dot{V}$ arbitrarily small where $V$ is the quadratic Lyapunov function $V(x)=x^T Px$. On the other hand, Riccati equation appears in LQR and LQE problems. The first one is used to find the optimal regulator that minimizes quadratic cost function. The second one is used to estimate the state variables from the output when there is measurement noise. First problem deals with input and second deals with output. This is why the extra term appears. These two problems are dual and convertible to each other. Together these problems makes LQG problem. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/858750', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/138119/']} | jdg_79780 |
stackexchange | llm_judgeable_groundtruth_similarity | 820349 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
I've got several web servers running Server 2008r2 SP2 Standard with SQL Server 2014. What is the best practice / easiest in-place upgrade path to get to Windows Server 2016? In testing, I'm only able to upgrade from 2008r2 to 2012 and then upgrade again from 2012 to 2016. We've got a decent amount of configuration done on these and quite a few websites running on them. With that in mind having to upgrade twice isn't ideal due to the downtime involved. Is there any way around this? (change license keys or some other solution?) Thanks! Update in 2020: We're finally pulling the plug and upgrading our remaining couple 2008R2 servers. For anyone wondering here's what we're (generally doing): If SQL Server is running, we're moving from SQL Server 2008R2 to SQLServer 2014 before upgrading Windows (so there's some overlap). I'malso upgrading to the latest 2014 SP3 + the latest CU4 (this websiteis great for that sort of thing: https://buildnumbers.wordpress.com/sqlserver/ ). You can then go from Server 2008R2 to 2012R2. We're then enabling and running disk cleanup. If necessary we're then doing another upgrade for SQL to SQL Server 2016 / SQL 2019. If necessary we're then doing another OS upgrade from Server 2012R2 directly to Server 2019 or if we're taking it slower on some other critical servers we're just upgrading to Server 2016 for the time being. After each upgrade step we're ensuring we have quality backups (for us VMware snapshots / DB backups) and also checking each piece of software is functioning on every server. Slow and steady wins the race. And that's enough quick work to get off of 2008R2 and avoid ESU licenses (if you can even purchase them - it's been basically impossible for us to get extended security update keys.)
Now provide the response and nothing else.
| If you must stay with the same hardware/machines, then a two-step upgrade is your only option: 2008 to 2012, then 2012 to 2016. But, if you have a virtual infrastructure or can use additional hardware, you can treat this as a migration rather than an upgrade. Build new SQL servers and new IIS hosts, and then migrate the applications rather than upgrade the OSes. | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/820349', 'https://serverfault.com', 'https://serverfault.com/users/390303/']} | jdg_79781 |
stackexchange | llm_judgeable_groundtruth_similarity | 883236 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am having trouble answering questions pertaining to immersions on smooth manifolds. For example: Given the unit sphere $S^2$ around the origin in $R^3$ and the map $f: S^2 \rightarrow R^3$ given by $f(x,y,z) =(yz,zx,xy), show f fails to be an immersion at 6 points. I am working on problems from a qualifying exam in topology and I am looking for a generic way to approach these types of problems. My ideas so far:I know that an immersion at a point x in $S^2$ means that the derivative map $df_x$ is injective from the tangent space at that point in $S^2$ to the tangent space of f(x) in $R^3$. 1) Use stereographic projection and then consider the composition with this map giving us a map from $R^2$ to $R^3$. This approach seems to be really ugly sometimes and if I replace $S^2$ with a hyperboloid or some other surface I may not have a map like stereographic projection. 2) Consider only hemispheres at a time and solve for one variable. In this case I would start by considering the top hemisphere and solve for z, getting $z = \sqrt{-x^2 -y^2 + 1}$ . Then the $df_x$ map would just be the Jacobian of f with the above relation plugged in for z. I can thus consider the rank of this map at different points to see if I have an immersion. This method again gets pretty ugly and I am not even sure if it is correct. 3) The method I prefer but seem to get the opposite answer with is to consider the sphere as a level curve at 1 of the function $F(x,y,z) = x^2 + y^2 + z^2$. Then to solve this problem I consider the 3x3 matrix for $df_x$. If it is rank 3 then f is an immersion as it will take the tangent space at any point on the sphere to a two dimensional subspace of $R^3$. If it is rank 2 then we need to show that the tangent space at a point is sent to a two dimensional space under $df_x$. One way I believe we can do this is to consider the normal vector (gradient of F) to this tangent plane and see what happens to it under $df_x$. IF the normal vector is in the kernel of $df_x$ then is it true that the tangent space is preserved? Trying this method I got the answer that the points $(\pm 1, 0,0), (0, \pm1,0), (0,0, \pm1)$ ARE points at which we have an immersion and every other point on the great circles (z=0, x=0,y=0) are NOT immersions. I know this is possible as an answer but seems to be the opposite of what the question asks. If anybody can give me any ideas on which method here works or any other generic method to do these problems I would be very appreciative. Thanks. Also this is my first question posted here so please let me know of any positing errors or anything I might have messed up.
Now provide the response and nothing else.
| We may rewrite your series in the following manner: \begin{align}&\sum_{n=0}^\infty\left(\frac{1}{6n+1}+\frac{-1}{6n+2}+\frac{-2}{6n+3}+\frac{-1}{6n+4}+\frac{1}{6n+5}+\frac{2}{6n+6}\right)\\&=\sum_{n=0}^\infty\left(\frac{1}{6n+1}+\frac{-1}{6n+2}+\frac{1}{6n+3}+\frac{-1}{6n+4}+\frac{1}{6n+5}+\frac{-1}{6n+6}\right)\\&\hspace{1cm}-\sum_{n=0}^\infty\left(\frac{3}{6n+3}-\frac{3}{6n+6}\right)\\\end{align}But these summations are both the alternating series $\sum_{n=0}^\infty \dfrac{(-1)^n}{n+1}$. Therefore they cancel and the summation is equal to zero. | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/883236', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/72002/']} | jdg_79782 |
stackexchange | llm_judgeable_groundtruth_similarity | 60447 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
It's probably a well known question, so it is just a reference question. Let $G$ be a finite group and let $C[G]$ be a group algebra. Then we can define a bracket on $C[G]$ by $[f,h]=f*h-h*f$. What does $C[G]$ look like as a Lie algebra? When is it solvable?
Now provide the response and nothing else.
| Assuming that your ground field $K$ has characteristic prime to the order of $G$. Then the group ring is a seminsimple algebra. Therefore, $C[G]=\bigoplus_{i=1}^{r} Mat_{n_i}(R_i)$ is a direct sum of matrix algebras, where $R_i$ is a finite-dimensional division ring over $K$. All this is very classical and nicely explained in Procesis book on Lie groups. Thus the Lie algebra is a sum of general linear Lie algebras over division rings. If $K$ is $\mathbb{C}$, then $R_i=\mathbb{C}$. So the Lie algebra is solvable iff all $n_i$ are $1$ (this happens iff $G$ is abelian). For $\mathbb{R}$, you also get the quaternions. For fields like $\mathbb{Q}$ or finite characteristic dividning the order of $G$, the story is going to be way more complicated and interesting. | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/60447', 'https://mathoverflow.net', 'https://mathoverflow.net/users/4246/']} | jdg_79783 |
stackexchange | llm_judgeable_groundtruth_similarity | 47112880 |
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 style half of an <hr> to be different from the other half, like this: As you can see, the left half of the <hr> is red and a bit thicker than the thin, grey side on the right. Possible to accomplish this with CSS? Thanks!
Now provide the response and nothing else.
| For the <hr> line you can use the css :before pseudo-element to make the differently-colored area (please change colors and sizes to match your design): hr { background-color: #555; border: none; display: block; height: 4px; overflow: visible; position: relative; width: 100%;}hr:before { background-color: #f90; content: ''; display: block; height: 8px; left: 0; position: absolute; top: -2px; width: 20%; z-index: 1;} <hr> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47112880', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3546086/']} | jdg_79784 |
stackexchange | llm_judgeable_groundtruth_similarity | 9862283 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
CSS has never supported constants or variables directly. Whenever I'm writing code like this: span.class1 { color: #377fb6;}div.class2 { border: solid 1px #377fb6; /* Repeated color */} I wonder why such a seemingly simple feature has never made it into the standard. What could be hard about implementing a scheme whereby we could avoid repetition, something like this: $theme_color1: #377fb6;span.class1 { color: $theme_color1;}div.class2 { border: solid 1px $theme_color1;} I know there are workarounds, like using a class for each color or generating CSS code from templates, but my question is: given that CSS is so rich and complex, why weren't CSS constants ever introduced?
Now provide the response and nothing else.
| Current status [update in Dec 2015] The W3C issued a draft about CSS variables just one month after this answer has been edited the last time. And this month has brought that draft up to a Candidate Recommendation . It will stay in review at least until June 2016. A test suite is available. So, all in all, CSS will have variables , also called "custom properties" : A custom property is any property whose name starts with two dashes (U+002D HYPHEN-MINUS), like --foo . The <custom-property-name> production corresponds to this: it’s defined as any valid identifier that starts with two dashes. Custom properties are solely for use by authors and users; CSS will never give them a meaning beyond what is presented here. Example 1 Custom properties define variables, referenced with the var() notation, which can be used for many purposes. For example, a page that consistently uses a small set of colors in its design can store the colors in custom properties and use them with variables: :root { --main-color: #06c; --accent-color: #006;}/* The rest of the CSS file */#foo h1 { color: var(--main-color);} The naming provides a mnemonic for the colors, prevents difficult-to-spot typos in the color codes, and if the theme colors are ever changed, focuses the change on one simple spot (the custom property value) rather than requiring many edits across all stylesheets in the webpage. Unlike other CSS properties, custom property names are case-sensitive. This feature is only implemented in Firefox and Chrome at the moment, and it will (probably) take quite some time until it's implemented in current browsers. Old answer from 2012 This is the original answer from March 2012. It pre-dates both the "official" W3C draft and the experimental browser implementations. Why aren't CSS variables in CSS 1 or 2? EDIT: This was already questioned to Håkon Wium Lie, the father of CSS ( Opera Watchblog (Wayback machine) ): Bernie Zimmermann: Håkon, why doesn't CSS support constants? Being able to assign an RGB value to a constant, for instance, could make stylesheet maintenance a lot more manageable. Was it just an oversight? Hakon: No, we thought about it. True, it would have saved some typing. However, there are also some downsides. First, the CSS syntax would have been more complex and more programming-like. Second, what would be the scope of the constant? The file? The document? Why? In the end we decided it wasn't worth it. So it's not in the standard because they thought it wasn't worth it . Workarounds Constants or variables as you have defined are merely placeholders. Since such a placeholder makes only sense if it's used on the same declaration it's useless as grouping already provides this mechanism: When several selectors share the same declarations, they may be grouped into a comma-separated list. CSS2:Grouping So instead of using a color in ten selectors, it's often better to collect common declarations and put them together. Instead of .header{ color: red;}.section:nth-of-type(2n) > .ridi.culous > .article:hover{ color: red;}.footer{ color: blue; border: 1px solid blue;} use /* Color definitions */.header,.section:nth-of-type(2n) > .ridi.culous > .article:hover{ color: red;}.footer{ color: blue;}/* border definitions */.footer{ border: 1px solid;} Also use inheritance whenever possible. Note that you can declare almost some kind of variable if you're using abstract/simple classes like .margin5em{ margin: 5em;}.corporateIdentityBackgroundColor{ background-color: #881200;}.corporateIdentityBackgroundImage{ background-image: url(we/are/awesome/corporation);}.backgroundCenter{ background-position: center center;}.backgroundNoRepeat{ background-repeat: no-repeat;} This will enable you to use <div class="corporateIdentityBackgroundImage backgroundCenter backgroundNoRepeat">Ridiculos long class names</div><div class="article"> <p class="margin5em">Yesterday I found a new hobby: Creating class names that are longer then most common words.</p></div> See also: http://icant.co.uk/articles/cssconstants/ | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9862283', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1155219/']} | jdg_79785 |
stackexchange | llm_judgeable_groundtruth_similarity | 3663704 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
It seems to use default color from Windows settings which is blue by default.Let's say I want to change it to red permanently. I'm using Winforms. Thanks in advance.
Now provide the response and nothing else.
| You must override the Drawitem event and set the DrawMode property to DrawMode.OwnerDrawFixed check this sample private void listBox1_DrawItem(object sender, DrawItemEventArgs e){ if (e.Index<0) return; //if the item state is selected them change the back color if ((e.State & DrawItemState.Selected) == DrawItemState.Selected) e = new DrawItemEventArgs(e.Graphics, e.Font, e.Bounds, e.Index, e.State ^ DrawItemState.Selected, e.ForeColor, Color.Yellow);//Choose the color // Draw the background of the ListBox control for each item. e.DrawBackground(); // Draw the current item text e.Graphics.DrawString(listBox1.Items[e.Index].ToString(),e.Font, Brushes.Black, e.Bounds, StringFormat.GenericDefault); // If the ListBox has focus, draw a focus rectangle around the selected item. e.DrawFocusRectangle();} | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3663704', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/346560/']} | jdg_79786 |
stackexchange | llm_judgeable_groundtruth_similarity | 41268702 |
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 Cloud storage system, AWS is highly demanded. Scan process need more faster. So how the scan process works and which one(Scan/Parallel Scan) is better in in which situation? How scan works in AWS DynamoDB? How parallel scan works in AWS DynamoDB? Scan vs Parallel Scan in AWS DyanmoDB? When Parallel Scan will be preferred? Is filter expression is applied before scan?
Now provide the response and nothing else.
| 1. How scan works in AWS DynamoDB? Ans: i) Scan operation returns one or more items. ii) By default, Scan operations proceed sequentially. iii) By default, Scan uses eventually consistent reads when accessing the data in a table. iv) If the total number of scanned items exceeds the maximum data set size limit of 1 MB, the scan stops and results are returned to the user as a LastEvaluatedKey value to continue the scan in a subsequent operation. v) A Scan operation performs eventually consistent reads by default, and it can return up to 1 MB (one page) of data. Therefore, a single Scan request can consume (1 MB page size / 4 KB item size) / 2 (eventually consistent reads) = 128 read operations. 2. How parallel scan works in AWS DynamoDB? Ans: i) For faster performance on a large table or secondary index, applications can request a parallel Scan operation. ii) You can run multiple worker threads or processes in parallel. Each worker will be able to scan a separate segment of a table concurently with the other workers. DynamoDB’s Scan function now accepts two additional parameters: TotalSegments denotes the number of workers that will access the table concurrently. Segment denotes the segment of table to be accessed by the calling worker. iii) The two parameters, when used together, limit the scan to a particular block of items in the table. You can also use the existing Limit parameter to control how much data is returned by an individual Scan request. 3. Scan vs Parallel Scan in AWS DyanmoDB? Ans: i) A Scan operation can only read one partition at a time. So parallel scan is needed for faster read on multiple partition at a time. ii) A sequential Scan might not always be able to fully utilize the provisioned read throughput capacity. So parallel scan is needed there. iii) Parallel Scans, reduce your costs by up to 4x for certain types of queries and scans. 4. When Parallel Scan will be preferred? Ans: A parallel scan can be the right choice if the following conditions are met: The table size is 20 GB or larger. The table's provisioned read throughput is not being fully utilized. Sequential Scan operations are too slow. 5. Is filter expression is applied before scan? Ans: No, A FilterExpression is applied after the items have already been read; the process of filtering does not consume any additional read capacity units. Resource Link: Scan Parallel Scan Example - Parallel Scan Using Java Amazon DynamoDB – Parallel Scans, 4x Cheaper Reads, Other Good News Avoid Sudden Bursts of Read Activity | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41268702', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2293534/']} | jdg_79787 |
stackexchange | llm_judgeable_groundtruth_similarity | 35967838 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Can i know why when i run this project it was out this error and the app on device was unfortunely,app has stopped.the error is . android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database package dijkstra.app.com.demodistancev8;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteException;import android.database.sqlite.SQLiteOpenHelper;import android.util.Log;import android.widget.Toast;//http://cariprogram.blogspot.compublic class SQLHelper extends SQLiteOpenHelper{private static final String DATABASE_NAME = "schoolnav.sqlite";private static final int DATABASE_VERSION = 1;private static String DB_PATH = "/data/data/com.app.dijkstra/databases/";private Context myContext;public SQLHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); // TODO Auto-generated constructor stub myContext=context;}public void createDataBase() throws IOException{ if(DataBaseisExist()){ //do nothing - database already exist Toast.makeText(myContext, "Database Sudah Ada", Toast.LENGTH_LONG).show(); } else{ //By calling this method and empty database will be created into the default system path //of your application so we are gonna be able to overwrite that database with our database. this.getReadableDatabase(); try { copyDataBase(); Toast.makeText(myContext, "Database Berhasil Diimport Dari Assets", Toast.LENGTH_LONG).show(); } catch (IOException e) { throw new Error("Error copying database"); } }}private boolean DataBaseisExist(){ SQLiteDatabase checkDB = null; try{ String myPath = DB_PATH + DATABASE_NAME; checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY); }catch(SQLiteException e){ //database does't exist yet. } if(checkDB != null){ checkDB.close(); } if(checkDB != null )return true ;else return false;}private void copyDataBase() throws IOException{ //Open your local db as the input stream InputStream myInput = myContext.getAssets().open(DATABASE_NAME); // Path to the just created empty db String outFileName = DB_PATH + DATABASE_NAME; //Open the empty db as the output stream OutputStream myOutput = new FileOutputStream(outFileName); //transfer bytes from the inputfile to the outputfile byte[] buffer = new byte[1024]; int length; while ((length = myInput.read(buffer))>0){ myOutput.write(buffer, 0, length); } //Close the streams myOutput.flush(); myOutput.close(); myInput.close();}@Overridepublic void onCreate(SQLiteDatabase db) {}@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub}}}<?xml version="1.0" encoding="utf-8"?> <permission android:name="dijkstra.app.com.demodistancev8.permission.MAPS_RECEIVE" android:protectionLevel="signature"></permission><uses-permission android:name="dijkstra.app.com.demodistancev8.permission.MAPS_RECEIVE"/><uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /><uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" /><uses-permission android:name="android.permission.READ_PHONE_STATE" /><uses-permission android:name="android.permission.SEND_SMS" /><!--The ACCESS_COARSE/FINE_LOCATION permissions are not required to use Google Maps Android API v2, but are recommended.--><uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /><application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="@string/google_maps_key" /> <activity android:name=".MapsActivity" android:label="@string/title_activity_maps" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity></application></manifest>
Now provide the response and nothing else.
| Boris the Spider has already outlined the most visible difference between ArrayBlockingQueue and LinkedBlockingQueue - the former is always bounded, while the latter can be unbounded. So in case you need an unbounded blocking queue, LinkedBlockingQueue or a LinkedTransferQueue used as a BlockingQueue are your best bets from the java.util.concurrent toolbox. But let's say you need a bounded blocking queue.In the end, you should choose an implementation based on extensive experimenting with a simulation of your real-world workload.Nevertheless, here are some notes that can help you with your choice or with interpreting the results from the experiment: ArrayBlockingQueue can be created with a configurable (on/off) scheduling fairness policy. This is great if you need fairness or want to avoid producer/consumer starvation, but it will cost you in throughput. ArrayBlockingQueue pre-allocates its backing array, so it doesn't allocate nodes during its usage, but it immediately takes what can be a considerable chunk of memory, which can be a problem if your memory is fragmented. ArrayBlockingQueue should have less variability in performance, because it has less moving parts overall, it uses a simpler and less-sophisticated single-lock algorithm, it does not create nodes during usage, and its cache behavior should be fairly consistent. LinkedBlockingQueue should have better throughput, because it uses separate locks for the head and the tail. LinkedBlockingQueue does not pre-allocate nodes, which means that its memory footprint will roughly match its size, but it also means that it will incur some work for allocation and freeing of nodes. LinkedBlockingQueue will probably have worse cache behavior, which may affect its own performance, but also the performance of other components due to false sharing. Depending on your use-case and how much do you care about performance, you may also want to look outside of java.util.concurrent and consider Disruptor (an exceptionally fast, but somewhat specialized bounded non-blocking ring buffer) or JCTools (a variety of bounded or unbounded queues with different guarantees depending on the number of producers and consumers). | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/35967838', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6044002/']} | jdg_79788 |
stackexchange | llm_judgeable_groundtruth_similarity | 233548 |
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 have a dataset of 140000 examples and 30 features for which I am training several classifiers for a binary classification (SVM, Logistic Regression, Random Forest etc) In many cases hyperparameter tuning on the whole dataset using either Grid or Random search is too costly time-wise. I started using the following technique Sub sample my dataset Use the obtained fraction to tune the hyperparameters on Use the obtained parameters to train a model using the whole dataset To evaluate each set of parameters on the second step I use sklearn 's GridSearchCV with cv=10.To evaluate the final model that I create in the third step I use sklearn 's cross_val_predict . In that sense I evaluate my models leaving a 10% percent of data out, I train on the rest and measure the predictive accuracy on the 10%, iteratively 10 times, then taking the average of the scores. What made me worry is that the prediction accuracy I get from training on my whole dataset, is really close to the evaluation I get when tuning the parameters for the best set of parameters (each tested set of parameters outputs a score obtained from averaging 10-fold-cross validation results). Most of the times the accuracy that cross_val_predict measured using all the training examples (whole dataset) is a little bit above what the evaluation of the best parameters returned. To illustrate this here is the evaluation of a set of parameters (on a smaller dataset than what I described above but the effect is the same) Best parameters set found on development set:{'kernel': 'rbf', 'C': 9, 'gamma': 0.1}Scores for all sets of parameters0.851 (+/-0.006) for {'kernel': 'rbf', 'C': 3, 'gamma': 0.5}0.852 (+/-0.006) for {'kernel': 'rbf', 'C': 3, 'gamma': 0.1}0.829 (+/-0.006) for {'kernel': 'rbf', 'C': 3, 'gamma': 0.001}0.853 (+/-0.006) for {'kernel': 'rbf', 'C': 9, 'gamma': 0.1}... And here are the averaged scores (from cross_val_predict ) I got from training on my whole dataset using the best parameters precision recall f1-score support 0 0.86 0.85 0.86 15417 1 0.86 0.87 0.87 16561avg / total 0.86 0.86 0.86 31978acc score: 0.863750078179roc au score: 0.863370490059[[13147 2270] [ 2087 14474]] As you can see training on the whole dataset improves the results. I have also validated that badly tuned model (e.g. using the default values or random values for C and gamma ) leads to much worse prediction accuracy. Overall I think that tuning the hyperparameters on a subset is not ideal but can potentially lead to relatively good results without having to wait too long. I for example before using that approach used optunity package for tuning the hyperparameter on the whole dataset. This procedure would take 3-5 days to complete and would produce results that either had really good precision or really good recall but not both, so although for each class either the precision or the recall was really high (higher than what any of my other classifiers had achieved) the f1 meassure was really low. In the contrary using the later approach leads to some hours of training and a better f1 meassure. My concerns are: Do I limit my classification accuracy? Do I avoid using all the prediction power that my dataset can offer by tuning only on a subset? If such a harm of performance is happening is it somehow limited by some factor?
Now provide the response and nothing else.
| In addition to Jim's (+1) answer: For some classifiers, the hyper-parameter values are dependent on the number of training examples, for instance for a linear SVM, the primal optimization problem is $\mathrm{min} \frac12\|w\|^2 + C\sum_{i=1}^\ell \xi_i$ subject to $y_i(x_i\cdot w _ b) \geq 1 - \xi_i, \quad \mathrm{and} \quad \xi_i \geq 0 \quad \forall i$ Note that the optimisation problem is basically a measure of the data mis-fit term (the summation over $\xi_i$) and a regularisation term, but the usual regrularisation parameter is placed with the data misfit term. Obviously the greater the number of training patterns we have, the larger the summation will be and the smaller $C$ ought to be to maintain the same balance with the magnitude of the weights. Some implementations of the SVM reparameterise as $\mathrm{min} \frac12\|w\|^2 + \frac{C}{\ell}\sum_{i=1}^\ell \xi_i$ in order to compensate, but some don't. So an additional point to consider is whether the optimal hyper-parameters depend on the number of training examples or not. I agree with Jim that overfitting the model selection criterion is likely to be more of an issue, but if you have enough data even in the subsample then this may not be a substantial issue. | {} | {'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/233548', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/107476/']} | jdg_79789 |
stackexchange | llm_judgeable_groundtruth_similarity | 14327327 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What is the idiomatic Haskell solution for dependency injection? E.g., suppose you have an interface frobby , and you needed to pass an instance conforming to frobby around (there might be multiple varieties of these instances, say, foo , and bar ). Typical operations would be: functions that take some value X and return some value Y . E.g., this might be a database accessor, taking a SQL query & a connector and returning a dataset. You might need to implement postgres, mysql, and a mock test system. functions that take some value Z and return a closure relating to Z , specialized to a given foo or bar style, chosen at runtime. One person solved the problem as follows: http://mikehadlow.blogspot.com/2011/05/dependency-injection-haskell-style.html But I don't know if that's the canonical way to manage this task.
Now provide the response and nothing else.
| I think the proper answer here is, and I will probably receive a few downvotes just for saying this: forget the term dependency injection . Just forget it. It's a trendy buzzword from the OO world, but nothing more. Let's solve the real problem. Keep in mind that you are solving a problem, and that problem is the particular programming task at hand. Don't make your problem "implementing dependency injection". We'll take the example of a logger, because that's a basic piece of functionality many programs will want to have, and there are lots of different types of loggers: One that logs to stderr, one that logs to a file, a database, and one that simply does nothing. To unify all them you want a type: type Logger m = String -> m () You could also choose a fancier type to save some keystrokes: class PrettyPrint a where pretty :: a -> Stringtype Logger m = forall a. (PrettyPrint a) => a -> m () Now let's define a few loggers using the latter variant: noLogger :: (Monad m) => Logger mnoLogger _ = return ()stderrLogger :: (MonadIO m) => Logger mstderrLogger x = liftIO . hPutStrLn stderr $ pretty xfileLogger :: (MonadIO m) => FilePath -> Logger mfileLogger logF x = liftIO . withFile logF AppendMode $ \h -> hPutStrLn h (pretty x)acidLogger :: (MonadIO m) => AcidState MyDB -> Logger macidLogger db x = update' db . AddLogLine $ pretty x You can see how this builds a graph of dependencies. The acidLogger depends on a database connection for the MyDB database layout. Passing arguments to functions is about the most natural way to express dependencies in a program. After all a function is just a value that depends on another value. That is also true for actions. If your action depends on a logger, then naturally it is a function of loggers: printFile :: (MonadIO m) => Logger m -> FilePath -> m ()printFile log fp = do log ("Printing file: " ++ fp) liftIO (readFile fp >>= putStr) log "Done printing." See how easy this is? At some point this makes you realize how much easier your life will be, when you just forget all the nonsense that OO has taught you. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/14327327', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/26227/']} | jdg_79790 |
stackexchange | llm_judgeable_groundtruth_similarity | 18686 |
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 you have an arbitrary triangle with vertices $A$, $B$, and $C$. This paper (section 4.2) says that you can generate a random point, $P$, uniformly from within triangle $ABC$ by the following convex combination of the vertices: $P = (1 - \sqrt{r_1}) A + (\sqrt{r_1} (1 - r_2)) B + (r_2 \sqrt{r_1}) C$ where $r_1, r_2 \sim U[0, 1]$. How do you prove that the sampled points are uniformly distributed within triangle $ABC$?
Now provide the response and nothing else.
| I would argue that if it is true for any triangle, it is true for all of them, as we can find an affine transformation between them. So I would pick my favorite triangle, which is $A=(0,0), B=(1,0), C=(0,1)$. Then the point is $(\sqrt{r_1}(1-r_2),r_2\sqrt{r_1})$ and we need to prove it is always within the triangle and evenly distributed. To be in the triangle we need $x,y\ge 0, x+y\le 1$, which is clear. Then show that the probability to be within an area $(0,x) \times (0,y)$ is $2xy$ by integration. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/18686', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/4841/']} | jdg_79791 |
stackexchange | llm_judgeable_groundtruth_similarity | 25145162 |
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 gradle build file that uses the java plugin. If I want to invoke build from the command line and avoiding running unit tests I can just do this: gradle build -x test However, we'll be calling gradle tasks from Eclipse. Do I need to build a special task for this kind of build? How would I go about doing it?
Now provide the response and nothing else.
| Under Eclipse > Menu bar "Windows" > Preferences > left hand side: Gradle> Arguments > Program Arguments > put -x test and Under Eclipse > Menu bar "Windows" > Preferences > left hand side: Gradle EnIDE> check box the box next to -x test (--exclude-task test) or use gradle assemble line. See if that helps. Make sure GRADLE_HOME is set / known to Eclipse. UPDATE: THIS will stop running test task from any project (as it's global).If you just want to run gradle clean build -x test or similar (once in a while and only on some project), then do something like this: In GRADLE_HOME/init.d folder, create a global common file called shenzi.gradle In this common file, add the following: allprojects{ apply plugin: 'java' apply plugin: 'groovy' // blah blah uncomment if you need. //apply plugin: 'pmd' //apply plugin: 'findbugs' //apply plugin: 'checkstyle' //apply plugin: 'jacoco' tasks.withType(Compile) { options.debug = true options.compilerArgs = ["-g"] } // .. // .. more code exists here for commented out lines as shown above, so ignore this in your version // .. task myAliasNoTestBuild() << { // see link below on how to create alias tasks }} OR try this solution: https://www.mail-archive.com/[email protected]/msg09173.html OR How to prevent gradle build from executing test task | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25145162', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/253575/']} | jdg_79792 |
stackexchange | llm_judgeable_groundtruth_similarity | 22990067 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How do I extract the epoch value to Long from instances of LocalDateTime or LocalDate ? I've tried the following, but it gives me other results: LocalDateTime time = LocalDateTime.parse("04.02.2014 19:51:01", DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss"));System.out.println(time.getLong(ChronoField.SECOND_OF_DAY)); // gives 71461System.out.println(time.getLong(ChronoField.EPOCH_DAY)); // gives 16105 What I want is simply the value 1391539861 for the local datetime "04.02.2014 19:51:01" .My timezone is Europe/Oslo UTC+1 with daylight saving time.
Now provide the response and nothing else.
| The classes LocalDate and LocalDateTime do not contain information about the timezone or time offset , and seconds since epoch would be ambigious without this information. However, the objects have several methods to convert them into date/time objects with timezones by passing a ZoneId instance. LocalDate LocalDate date = ...;ZoneId zoneId = ZoneId.systemDefault(); // or: ZoneId.of("Europe/Oslo");long epoch = date.atStartOfDay(zoneId).toEpochSecond(); LocalDateTime LocalDateTime time = ...;ZoneId zoneId = ZoneId.systemDefault(); // or: ZoneId.of("Europe/Oslo");long epoch = time.atZone(zoneId).toEpochSecond(); | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/22990067', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_79793 |
stackexchange | llm_judgeable_groundtruth_similarity | 9238890 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Here's my HTML: <a>View it in your browser</a><div id="html"> <h1>Doggies</h1> <p style="color:blue;">Kitties</p></div> How do I use JavaScript to make the href attribute of my link point to a base64 encoded webpage whose source is the innerHTML of div#html ? I basically want to do the same conversion done here (with the base64 checkbox checked) except for in JavaScript.
Now provide the response and nothing else.
| Characteristics of a data-URI A data-URI with MIME-type text/html has to be in one of these formats: data:text/html,<HTML HERE>data:text/html;charset=UTF-8,<HTML HERE> Base-64 encoding is not necessary. If your code contains non-ASCII characters, such as éé , charset=UTF-8 has to be added. The following characters have to be escaped: # - Firefox and Opera interpret this character as the marker of a hash (as in location.hash ). % - This character is used to escape characters. Escape this character to make sure that no side effects occur. Additionally, if you want to embed the code in an anchor tag, the following characters should also be escaped: " and/or ' - Quotes mark the value of the attribute. & - The ampersand is used to mark HTML entities. < and > do not have to be escaped inside a HTML attribute . However, if you're going to embed the link in the HTML, these should also be escaped ( %3C and %3E ) JavaScript implementation If you don't mind the size of the data-URI, the easiest method to do so is using encodeURIComponent : var html = document.getElementById("html").innerHTML;var dataURI = 'data:text/html,' + encodeURIComponent(html); If size matters, you'd better strip out all consecutive white-space (this can safely be done, unless the HTML contains a <pre> element/ style ). Then, only replace the significant characters: var html = document.getElementById("html").innerHTML;html = html.replace(/\s{2,}/g, '') // <-- Replace all consecutive spaces, 2+ .replace(/%/g, '%25') // <-- Escape % .replace(/&/g, '%26') // <-- Escape & .replace(/#/g, '%23') // <-- Escape # .replace(/"/g, '%22') // <-- Escape " .replace(/'/g, '%27'); // <-- Escape ' (to be 100% safe)var dataURI = 'data:text/html;charset=UTF-8,' + html; | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9238890', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/552067/']} | jdg_79794 |
stackexchange | llm_judgeable_groundtruth_similarity | 312778 |
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 $k > 1$ be an integer, and $A$ be a multiset initially containing all positive integers. We perform the following operation repeatedly: extract the $k$ smallest elements of $A$ and add their sum back to $A$ . Let $x_i$ be the element added on $i$ -th iteration of the process. The question is: is there a simple formula describing $x_i$ , or can they be computed faster than simulating the process? One can easily see that for $k = 2$ we have $x_i = 3i$ , but no simple pattern is evident for $k > 2$ . UPD: thought I would add some actual numbers and observations. Here's what happens for $k = 3$ (bold numbers are those not initially present in the set): $x_1 = 1 + 2 + 3 = \mathbf{6}$ $x_2 = 4 + 5 + 6 = \mathbf{15}$ $x_3 = \mathbf{6} + 7 + 8 = \mathbf{21}$ $x_4 = 9 + 10 + 11 = \mathbf{30}$ $x_5 = 12 + 13 + 14 = \mathbf{39}$ $x_6 = 15 + \mathbf{15} + 16 = \mathbf{46}$ The sequence continues with $54, 62, 69, 78, 87, 93, 102, 111, 118, 126, 135, \ldots$ One observation is that extra numbers are far apart from each other, enough so that no two extra numbers end up in the same batch, hence each batch is either a run of $k$ consecutive numbers, or a run of $k - 1$ numbers with one extra. If we look at consecutive differences $\Delta_i = x_{i + 1} - x_i$ , we get a sequence $9, 6, 9, 9, 7, 8, 8, 7, 9, 9, 6, 9, 9, 7, 8, 9, 6, \ldots$ It looks like it can be split into triples with sum $24$ (implying $x_{3i + 1} = 6 + 24i$ for whatever reason?). Further update: a similar pattern seems to persist for any $k$ : empirically $x_{ki + 1} = k(k + 1) / 2 + i(k^3 - k)$ for any integer $i \geq 0$ . Looking further down the sequence, there's a hint of periodicity which never seems to amount to much. (Since this answer was becoming cluttered I've removed the huge table of differences, but one can probably find them in the edit history.) UPD: Bullet51 discovered what seems to be a complete solution for the case $k = 3$ . Understanding how and why it works may be the key to cracking the general case as well. UPD: Following in Bullet51's steps I decided to try my hand at constructing some finite state machines for larger $k$ (see their answer below for the legend). This resulted in pictures I feel painfully obliged to share. $k = 4$ : $k = 5$ : $k = 6$ : $k = 7$ : I've verified all of these FSMs for the first $10^7$ differences in each case. Hopefully someone can make sense of what's going on here.
Now provide the response and nothing else.
| It seems that the sequence $Δ_i$ can be computed by a finite state machine for $k = 3$ : Instructions: In order to compute $Δ_i$ , let $S_n$ be the nth rightmost digit of the ternary expansion of $i$ . Start from the vertex labelled $Start$ . If there is a transition labelled $S_n$ , make the transition. Otherwise, terminate at the current vertex, and $Δ_i$ is the label of the vertex. Example: Compute $Δ_{24}$ . As $24=(220)_3$ , make the transitions $0$ , $2$ , $2$ and terminate at a vertex labelled $9$ . So $Δ_{24}=9$ . | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/312778', 'https://mathoverflow.net', 'https://mathoverflow.net/users/106512/']} | jdg_79795 |
stackexchange | llm_judgeable_groundtruth_similarity | 535448 |
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:
From school and/or university we know that there is Coulomb's law that allows us to calculate the amount of force between two electrically charged particles. However, I have never found any information on the origin of this force. Is there any explanation as to why this force exists? Is it really fundamental (i. e. it is not the result of any other forces like Archimedes force or the friction force for example)? Is there any evidence here? Does it propagate at light speed or another speed and why?
Now provide the response and nothing else.
| In school, we simplify slightly. We talk about science as if it tells us the truth about the universe in what philosophers would call an " ontological " sense. In reality, science is all about making models that explain things and predict things. We make our models, then turn up the heat, and see if they hold or if new behaviors occur. Often we find that behaviors we saw before were just special cases of a more generalized pattern. If a pattern survives us turning up the heat on it as far as we can go without giving way to new and more complex patterns, we call these patterns "fundamental laws." And they get to keep this terminology until we prove otherwise. As the most famous example, Newtonian physics was "the laws of kinematics" for several hundred years. His laws were "fundamental" until the 20th century finally gave us enough capability to peer into the very-very-fast, and discover things that did not obey Newton's laws. The behaviors that they obeyed were named Specific Relativity and General relativity. Newton's laws were a special case of this when objects were slow (and by slow, I mean things below a few million miles per hour... the bar is pretty high). So, in that sense, we currently consider the forces of electromagnetism to be "fundamental." They appear at the core of our theories, unmolested. Well, almost. If you get into quantum mechanics, you find that photons are the "force carrier" of the electromagnetic world. When you get down to really small scales, these photons are seen as the way electromagnetic forces are transmitted (and, to answer one of your questions, they are why it is said that the effects of electromagnetism propagate at the speed of light). But we still call it electromagnetism. It just looks a little different. Dig further, and you find string theory. String theory is an open collection of theories which are still not yet proven, but are an effort to simplify things so that they can all be explained via one mechanism. String theorists would based electromagnetism in the way strings vibrate, so we might argue that string theorists do not consider electromagnetism to be "fundamental." Of course, its a standing question as to whether any of their theories will ever be proven out (currently they all require particle accelerators with vastly more energy than we have today). So we call electromagnetism "fundamental." Its generally a good choice of word. unless you get into the nether regions of physics, it will indeed be a fundamental force. But its good to understand what is meant when we say these things. And for fun, you'll note that I talked about the laws of electromagnetism, not just Columb's law. There are actually four fundamental equations governing electricity and magnetism known as Maxwell's equations. Columb's law can be derived from them if you assume point charges generate spherically symmetric fields. And, if you have fun digging into relativity later, you will see that the effects of magnetism can be explained by starting with electricity and accounting for relativistic effects. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/535448', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/256170/']} | jdg_79796 |
stackexchange | llm_judgeable_groundtruth_similarity | 20166232 |
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 next navigation block in html template <nav class="navigation"> <ul class="nav"> <li><a href="#">Item 1</a></li> <li><a href="#">Item 2</a></li> <li><a href="#">Item 3</a></li> <li><a href="#">Item 4</a></li> <li><a href="#">Item 5</a></li> <li><a href="#">Item 6</a></li> </ul></nav> with css .navigation { padding: 0 0 19px; }.nav { font: 20px/22px "futura_demi_c", Arial, Helvetica, sans-serif; text-align: justify; text-align-last: justify; list-style-type: none; padding: 0; margin: 0;}.nav:after { content: ""; display: inline-block; width: 100%; overflow: hidden;}.nav li { display: inline-block;}.nav a { color: #020202;} Items have to be aligned justify in navigation block and occupy all entire width. And they are, if I use the code above. But if i remove new lines after each 'li' all items move to the right without spaces between them <nav class="navigation"> <ul class="nav"> <li><a href="#">Item 1</a></li><li><a href="#">Item 2</a></li><li><a href="#">Item 3</a></li><li><a href="#">Item 4</a></li><li><a href="#">Item 5</a></li><li><a href="#">Item 6</a></li> </ul></nav> Is it normal behaviour or my css is wrong?Behaviour is the same for all browsers.Jsfiddle examples: correct - http://jsfiddle.net/x9zfP/1 wrong - http://jsfiddle.net/AMK8z/1/ Tnx!
Now provide the response and nothing else.
| It's not about CDI.EntityManager's life cycle depends on its type, which can be: container-managed transactional, container-managed extended, application-managed. The first two are only available in a full-blown application server. So if you're going to stick with a servlet container you're narrowed to the 3rd option. You will have to explicitly open and close EMs in your application.It's straightforward: create an application-wide instance of EntityManagerFactory, inject it to all your beans. When you need an EM just create it, use and then immediately close without waiting for your bean's context to end. Because in this configuration an open EntityManager will retain a connection and with long-lived beans you'll run out of connections. You can find an easy and comprehensive explanation in the Obtaining a JPA Database Connection section of the ObjectDB manual. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/20166232', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3025588/']} | jdg_79797 |
stackexchange | llm_judgeable_groundtruth_similarity | 73931 |
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:
What is the correct way to redirect the output of multiple commands as input for another command? e.g. $ command < (command2 | grep pattern)
Now provide the response and nothing else.
| (This refers to bash in case of doubt) The output of one command or one pipeline can be made the input of another command by creating a (or extending the existing) pipeline: command1 | command2command1 | command2 | command3 Several commands (including pipelines) can be combined with a subshell or a list (group command). This combination becomes the first part of the pipeline then: (command1; command2 | command3; command4) | command5{command1; command2 | command3; command4;} | command5 # note the ; before } Another possibility is a "here string" (or even a "here document"): command2 <<< $(command1)command2 <<EOTFirst input line$(command1)Last input lineEOT Other cases Command substitution is used when the output shall be part of a command line i.e. if one command shall see the output of another as its own parameter: echo $(date) echo sees the output of date as its parameter; as if it had been typed in the command line. Process substitution makes the output of another process appearing as the content of a (non-seekable) file given as parameter on the command line. grep bar <(echo $'foo\nbar\nbaz') looks to grep like echo $'foo\nbar\nbaz' > /path/to/filegrep bar /path/to/file | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/73931', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/38006/']} | jdg_79798 |
stackexchange | llm_judgeable_groundtruth_similarity | 50089903 |
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 Pandas Dataframe that has date values stored in 2 columns in the below format: Column 1: 04-APR-2018 11:04:29Column 2: 2018040415203 How could I convert this to a time stamp. Datatype of both these column is Object.
Now provide the response and nothing else.
| For the first format you can simply pass to_datetime, for the latter you need to explicitly describe the date format ( see the table of available directives in the python docs ): In [21]: dfOut[21]: col1 col20 04-APR-2018 11:04:29 2018040415203In [22]: pd.to_datetime(df.col1)Out[22]:0 2018-04-04 11:04:29Name: col1, dtype: datetime64[ns]In [23]: pd.to_datetime(df.col2, format="%Y%m%d%H%M%S")Out[23]:0 2018-04-04 15:20:03Name: col2, dtype: datetime64[ns] | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/50089903', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9282755/']} | jdg_79799 |
stackexchange | llm_judgeable_groundtruth_similarity | 9573395 |
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 some help with an app. I need to make a random number generator for integers between zero and fifteen, which will then, depending on which number is created, push to a view with the corresponding number. This is how I want it to work Push a button --> random number generator gives a number between 0 and 15 --> view pushes to another view that has been assigned the number that the random number generator gave. Can anybody help me with the code?Thanks
Now provide the response and nothing else.
| arc4random() is the standard Objective-C random number generator function. It'll give you a number between zero and... well, more than fifteen! You can generate a number between 0 and 15 (so, 0, 1, 2, ... 15) with the following code: NSInteger randomNumber = arc4random() % 16; Then you can do a switch or a series of if / else statements to push a different view controller: UIViewController *viewController = nil;switch (randomNumber){ case 0: viewController = [[MyViewController alloc] initWithNibName:@"MyViewController" bundle:nil]; break; // etc ...}[self.navigationController pushViewController:viewController animated:YES]; Or rather, upon rereading the question, it would look like the following: UIViewController *viewController = [[MyViewController alloc] initWithNibName:@"MyViewController" viewController.number = randomNumber; And you'd have an NSInteger property on the MyViewController subclass. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/9573395', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/643996/']} | jdg_79800 |
stackexchange | llm_judgeable_groundtruth_similarity | 6634093 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Just that is the question: is possible to do a ROLLBACK in a MySQL trigger? If answer is yes, then, please, explain how.
Now provide the response and nothing else.
| I've found out that this functionnality exists since MySQL 5.5 and does not work in earlier releases. The trigger does no rollback or commit.To initiate any rollback, you have to raise an exception. Thus your insert/update/delete command will abort.The rollback or commit action has to be raised around your SQL command. To raise your exception, in your XXX's trigger (eg.) : create trigger Trigger_XXX_BeforeInsert before insert on XXXfor each row begin if [Test] then SIGNAL sqlstate '45001' set message_text = "No way ! You cannot do this !"; end if ;end ; | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6634093', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/299897/']} | jdg_79801 |
stackexchange | llm_judgeable_groundtruth_similarity | 616880 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to solve:$$8n^2=64 n\log(n)$$ I factored out $8n$ and was left with $$n = 8 \log n$$ but I do not know how to proceed from here, I checked the solution on Wolfram Alpha, and they were able to simplify it down to: which is approximately: how where they able to get to this point ?
Now provide the response and nothing else.
| Your equation does not have a closed form in terms of standard functions you come across in school, but it does have a solution in terms of the Lambert W-function $W(z)$. The defining equation for $W(z)$ is$$z=W(z)e^{W(z)}$$We want to rearrange your equation into something similar so we get$$\begin{align*}n&=8\log n \\\longrightarrow\hspace{10mm}\frac n8&=\log n \\\longrightarrow\hspace{7mm} e^{\frac n8}&=n \\\longrightarrow\hspace{12mm} 1&=ne^{-\frac n8} \\\longrightarrow\hspace{5mm} -\frac18&=-\frac n8e^{-\frac n8} \\\end{align*}$$Now$$Y=Xe^X\iff X=W(Y)$$Thus we get$$\begin{align*}-\frac n8&=W\left(-\frac18\right)\\n&=-8W\left(-\frac18\right)\end{align*}$$To get decimal approximations, you can numerically evaluate $W$ for its different branches and you get the solutions wolfram alpha gave you. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/616880', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/114651/']} | jdg_79802 |
stackexchange | llm_judgeable_groundtruth_similarity | 23086 |
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 need to follow several steps to safe our Web Project from DoS attack. Is there any guideline / steps? EDIT : We have our own server where we are running several e-Commerce websites. Our server's OS is CentOS.
Now provide the response and nothing else.
| To avoid downtime during DDoS running single server, you can make sure that your operating system remains stable during DDoS, so when the attack is gone, it continues to work. This can be accomplished the following way: Setup IPTABLES with rate limit Add Varnish proxy and configure it to deny attacks, it's stable and very resilient and has some modules to support it. Enable syncookies Use latest Linux kernel This is very difficult thing to do and not straight forward, that's why the answer is a bit vague, and hardly you will get anything else. In essence, you should make sure that flood is not reaching your application level causing server to choke, but instead dropping connections. See this on Server Fault: https://serverfault.com/questions/417969/how-to-tune-linux-kernel-to-withstand-ddos-haproxy | {} | {'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/23086', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/12757/']} | jdg_79803 |
stackexchange | llm_judgeable_groundtruth_similarity | 2399874 |
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 implement this scenario using Unity and i can't figure out how this could be done: the same web application (ASP.NET MVC) should be made accessible to more than one client (multi-tenant). The URL of the web site will differentiate the client (this i know how to get). So getting the URL one could set the (let's call it) IConnectionStringProvider parameter (which will be afterward injected into IRepository and so on).Through which mechanism (using Unity) do i set the IConnectionStringProvider parameter at run time? I have done this in the past using Windsor & IHandlerSelector (see this ) but it's my first attempt using Unity. Any help is deeply appreciated!Thanks in advance
Now provide the response and nothing else.
| Yes, you can do this reasonably easily. For each received data point, append it to an array of values to display. As these data points come in, call -reloadData on the Core Plot graph (or just the particular plot) to redraw the graph, passing in the array you just added a value to in response to the -numbersForPlot:field:recordIndexRange: delegate method. If you need to adjust the plot range to track your data points (for a moving ticker), recalculate the new CPPlotRange for the X axis and set the plot space's xRange property to that. Use the CPTestApp-iPhone , AAPLot , or StockPlot examples as templates for how to set up the line chart overall, and modify from that starting point. I do something similar to this on the Mac in a scientific application: (source: sunsetlakesoftware.com ) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2399874', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/225180/']} | jdg_79804 |
stackexchange | llm_judgeable_groundtruth_similarity | 82096 |
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:
This is in the context of two random variables. A frequent assumption (e.g. of the error term in ANOVA) is of independent and identically distributed random variables. There is a question on this site asking how the assumption can be checked in a given dataset. Is it an assumption or a fact?
Now provide the response and nothing else.
| In practice being independent and identically distributed is an assumption; it may sometimes be a good approximation, but it's next to impossible to demonstrate that it actually holds. Generally, the best you can do is show that it doesn't fail too badly. This is what diagnostics, and to some extent hypothesis tests attempt to do. For example, if someone looks at an ACF of residuals (for data observed in sequence) to see if there's any obvious serial correlation (which would mean that independence didn't hold) ... but having small sample correlations doesn't imply independence. [If you're trying to assess assumptions for some statistical procedure -- or especially if you're trying to choose between possible procedures -- it's generally best to avoid hypothesis tests for that purpose. Hypothesis tests don't answer the question you really need an answer to for such a purpose, and using the data to choose in that manner will impact the properties of whichever later procedure you choose. If you must test something like that, avoid testing the data you're running the main test on.] | {} | {'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/82096', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/-1/']} | jdg_79805 |
stackexchange | llm_judgeable_groundtruth_similarity | 4342326 |
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 swipe images in windows phone 7.Where do I begin from?
Now provide the response and nothing else.
| You can use the GestureService in the Silverlight Control Toolkit for Windows Phone 7 . In your UI element, add the following piece of code (after you have referenced the toolkit's DLL in your WP7 project) - <toolkit:GestureService.GestureListener> <toolkit:GestureListener Flick="OnFlick"/></toolkit:GestureService.GestureListener> Implement the handler OnFlick in the code-behind file, like so - private void OnFlick(object sender, FlickGestureEventArgs e){ var vm = DataContext as SelectedCatalogViewModel; if (vm != null) { // User flicked towards left if (e.HorizontalVelocity < 0) { // Load the next image LoadNextPage(null); } // User flicked towards right if (e.HorizontalVelocity > 0) { // Load the previous image LoadPreviousPage(); } }} Hope this helps,indyfromoz | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4342326', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/505407/']} | jdg_79806 |
stackexchange | llm_judgeable_groundtruth_similarity | 5331293 |
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 conducting some experiments in Java, my project supervisor reminded me to seed each iteration of the experiment with a different number. He also mentioned that I should use prime numbers for the seed values. This got me thinking — why primes? Why not any other number as the seed? Also, why must the prime number be sufficiently big? Any ideas? I would've asked him this myself, but its 4am here right now, everyone's asleep, I just remembered this question and I'm burning to know the answer (I'm sure you know the feeling). It would be nice if you could provide some references, I'm very interested in the math/concept behind all this! EDIT: I'm using java.util.Random. FURTHER EDIT: My professor comes from a C background, but I'm using Java. Don't know if that helps. It appears that using primes is his idiosyncrasy, but I think we've unearthed some interesting answers about generating random numbers. Thanks to everyone for the effort!
Now provide the response and nothing else.
| Well one blink at the implementation would show you that he CAN'T have any reason for that claim at all. Why? Because that's how the set seed function looks like: synchronized public void setSeed(long seed) { seed = (seed ^ multiplier) & mask; this.seed.set(seed); haveNextNextGaussian = false;} And that's exactly what's called from the constructor. So even if you give it a prime, it won't use it anyhow, so if at all you'd have to use a seed s where (s^ multiplier) & mask results in a prime ;) Java uses a usual linear congruency method, i.e.: x_n+1 = (a * x_n + c) mod m with 2 <= a < m; 0 <= c < m. Since you want to get a maximal periode, c and m have to be relatively prime and a few other quite obscure limitations, plus a few tips how to get a practically useful version. Knuth obviously covers that in detail in part2 ;) But anyhow, the seed doesn't influence the qualities of the generator at all. Even if the implementation would be using a Lehmer generator, it would obviously make sure that N is prime (otherwise the algorithm is practically useless; and not uniformly distributed if all random values would have to be coprime to a non prime N I wager) which makes the point moot | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5331293', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/495545/']} | jdg_79807 |
stackexchange | llm_judgeable_groundtruth_similarity | 1589429 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
It's very basic but I'm having trouble to find a way to prove this inequality $\log(x)<x$ when $x>1$ ( $\log(x)$ is the natural logarithm) I can think about the two graphs but I can't find another way to prove it, and, besides that, I don't understand why should it not hold if $x<1$ Can anyone help me? Thanks in advance.
Now provide the response and nothing else.
| You may just differentiate$$f(x):=\log x-x, \quad x\geq1,$$ giving$$f'(x)=\frac1x-1=\frac{1-x}x<0 \quad \text{for}\quad x>1$$ since$$f(1)=-1<0$$ and $f$ is strictly decreasing, then$$f(x)<0, \quad x>1,$$ that is $$\log x -x <0, \quad x>1.$$ | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/1589429', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/287613/']} | jdg_79808 |
stackexchange | llm_judgeable_groundtruth_similarity | 29642 |
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:
Background I'm in charge of auditing a medium-scale web application. I have audited web applications several times before, but I've always written a short PDF quickly explaining what I encountered and usually I'm the one who's gonna be fixing those vulnerabilities so I never cared for the actual content of the report. In my current job things are done in a more organized fashion. First I have to write the report, then the project manager will review it, then he'll decide whether I'll be the one to fix the issues or someone else. Question What should such report contain? I'm looking for a general outline of how it should be organized. Update : Because I couldn't find anything here on Security.SE about audit reports, I decided to make this question a bit broader and include any kind of security audit rather than just web applications. I think it'll be useful to more people in this case.
Now provide the response and nothing else.
| There's a couple of ways that I've seen this done, each has it's pros and cons. As noted by @RoryAlsop below a common point for both approaches is that the executive summary should, as much as possible, be written for a business audience (assuming that it's a test you're doing for a 3rd party or the report will be passed to management). Reporting by finding. Here you list the findings, usually ranked by severity (e.g. CVSS score or some other scale like severity/likelihood). You then list out the technical details of the finding and potential mitigations if you have that information. This kind of report gets to the point quite quickly and plays well with tool output. Reporting by methodology. Assuming here that you're following a defined testing methodology, the report is structured along the lines of the methodology and includes a section for each area of the review. The sections detail what testing was done and the outcome (e.g. either a finding or the fact that there was no finding in this section). The advantage here is that you're showing your workings and that someone reading the report can get a good idea that you've actually tested something and it was ok rather than you just having missed it out. The downside is that it tends to be a longer report and harder to automate. One other gotcha is that you need to make sure that the testers don't just follow the methodology and they actually engage brain to look for other things. In terms of format for the findings, I usually include the following Title (descriptive gets used in the table and linked to the detail) Description - technical description of what the issue is and importantly under what circumstances it is likely to cause a security issue (e.g. for Cross-Site Scripting one of the potential issues is use to grab session tokens which could allow an attacker to get unauthorised access to the application) Recommendations - How the issue should be resolved, where possible include specific details on vendor guidance to fix it (e.g. things like removing web server versions from headers have specific instructions for Apache/IIS etc) References - Any links to additional information that's relevant to the finding (e.g. links to the relevant OWASP page for Web app. issues) Severity. As I mentioned above this could be CVSS or something more general like High/Medium/Low based on impact and likelihood. Other classification as needed by the client. For instance some client might need things lined up against a standard or policy or something like OWASP Top 10. One other point to make is that if your do a lot of tests it's well worth having a database of previous findings to avoid having to look up references repeatedly and to make sure that severities are consistent. | {} | {'log_upvote_score': 6, 'links': ['https://security.stackexchange.com/questions/29642', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/16228/']} | jdg_79809 |
stackexchange | llm_judgeable_groundtruth_similarity | 21226980 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it possible to direct this output from cURL into a file? % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed100 1354 100 1354 0 0 17358 0 --:--:-- --:--:-- --:--:-- 17358100 67081 100 67081 0 0 68171 0 --:--:-- --:--:-- --:--:-- 4031k I cannot find anything in --help that would indicate you can. -o just done the response from what I can tell. I am just wanting to know if the request succeded and how long it took.
Now provide the response and nothing else.
| This output is sent to stderr. So, to get it all you need is redirect stream 2 (stderr) to a file as curl -o responseFile.html http://www.somewhere.com 2> informationFile.txt But, as your capture shows, times are not always included. The better option to know if the request succeded and how long it took is to ask curl to output some internal variables. This is done with the -w switch. So, your command should look as curl -o responseFile.html http://www.somewhere.com -w "%{response_code};%{time_total}" > dataFile.txt 2> informationFile.txt That way, the response will go to responseFile.html (or whatever you need), the progress information (stderr or stream 2) will go to informationFile.txt and the required request response code and time information will go to dataFile.txt | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21226980', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1727487/']} | jdg_79810 |
stackexchange | llm_judgeable_groundtruth_similarity | 301362 |
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:
How does one begin to design an abstract class for the larger application that can interface with several types of databases, such as MySQL, SQLLite, MSSQL etc? What is the design pattern called and where exactly does it start? Let's say you need to write a class that has the following methods: public class Database { public DatabaseType databaseType; public Database (DatabaseType databaseType){ this.databaseType = databaseType; } public void SaveToDatabase(){ // Save some data to the db } public void ReadFromDatabase(){ // Read some data from db }}//Applicationpublic class Foo { public Database db = new Database (DatabaseType.MySQL); public void SaveData(){ db.SaveToDatabase(); }} The only thing I can think of is an if statement in every single Database method: public void SaveToDatabase(){ if(databaseType == DatabaseType.MySQL){ } else if(databaseType == DatabaseType.SQLLite){ }}
Now provide the response and nothing else.
| What you want is multiple implementations for the interface that your application uses. like so: public interface IDatabase{ void SaveToDatabase(); void ReadFromDatabase();}public class MySQLDatabase : IDatabase{ public MySQLDatabase () { //init stuff } public void SaveToDatabase(){ //MySql implementation } public void ReadFromDatabase(){ //MySql implementation }}public class SQLLiteDatabase : IDatabase{ public SQLLiteDatabase () { //init stuff } public void SaveToDatabase(){ //SQLLite implementation } public void ReadFromDatabase(){ //SQLLite implementation }}//Applicationpublic class Foo { public IDatabase db = GetDatabase(); public void SaveData(){ db.SaveToDatabase(); } private IDatabase GetDatabase() { if(/*some way to tell if should use MySql*/) return new MySQLDatabase(); else if(/*some way to tell if should use MySql*/) return new SQLLiteDatabase(); throw new Exception("You forgot to configure the database!"); }} As far as a better way of setting up the correct IDatabase implementation at run time in your application, you should look into things like " Factory Method ", and " Dependancy Injection ". | {} | {'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/301362', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/155613/']} | jdg_79811 |
stackexchange | llm_judgeable_groundtruth_similarity | 40104838 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
This is driving me crazy for several months now and I'm still not able to achieve it. My managed libraries are extracted from the Nuget package but not the natives ones. We have a bunch of managed and native libraries provided by another company.We have both x86 and x64 version of them. In order to use them in an ASP.NET Core project I have to create an Nuget Package. My architecture is: an ASP.NET Core class library that I changed to target full .NET Framework only. This project references my Nuget Package an ASP.NET Core website also targeting full .NET Framework and referencing the class library Of course, at the end, I need my native libraries being extracted to the proper runtime folder of the Website (eg: \bin\Debug\net461\win7-x64 ). For the moment my solution was: to put the native libs inside the build folder create a targets file that copies them to the $(OutputPath) (which is even not the runtime folder) add some MsBuild commands to the xproj of my website to get the targets file in my $(USERPROFILE)\.nuget\packages\ folder and execute it copy by hand the native DLLs now extracted in bin folder to the runtime one I've tried to copy them directly to the runtime folder using some configuration in project.json (I honestly don't remember all the things I've tried for this part) but this was always failing. Also even though I specified SkipUnchangedFiles="true" in my targets file, this is just ignored and my DLLs are copied to my bin folder during each build. This is an heavy process just to achieve a DLLs extracting, now I really want to get rid of all that MsBuild and get a much simpler solution. I know with newer versions of Nuget, it's now capable of extracting them natively without any help of adding custom MsBuild commands. As written here , C# projects don't even need a targets file Next, C++ and JavaScript projects that might consume your NuGet package need a .targets file to identify the necessary assembly and winmd files. (C# and Visual Basic projects do this automatically.) I kept a tab opened in my browser for several month ( original link ) and realize this resource has been recently removed from Nuget website. It was explaining how to use the runtimes folder to automatically extract natives DLLs. However I've never been able to get a successful result as it was explained. Now this page has been deleted and replaced by this one with so few explanations and not talking about this runtimes folder at all. My guess is that I should use runtimes folder for native DLLs and the lib one for managed but I'm not 100% sure of that. (also should I use the build folder?) I've tried several things (I can't recall number of attempts, as I said several months of headache...) like this architecture (I don't understand here what's the point of having build/native and also natives folders under runtimes ) I also tried to use the .NET framework version structure as described here for my managed libraries. This seems to be also part of the solution The architecture is ignored by the compiler when creating an assembly reference. It's a load time concept. The loader will prefer an architecture specific reference if it exists. One trick you can use to produce an AnyCPU assembly is to use corflags to remove the architecture from your x86 assembly. EG: corflags /32BITREQ- MySDK.dll. Corflags is part of the .NET SDK and can be found in VS's developer command prompt. That's what I did, converting both x86 and x64 DLLs to AnyCPU (don't know if it does something for x64 DLLs but I didn't get errors) and then tried several different architectures in my Nuget package but still not working. The default runtime without any entry in project.json is win7-x64 , so I decided to explicitly specify it just in case "runtimes": { "win7-x64": {}}, So this is the Runtime Identifier I'm using for all my attempts in my Nuget package. However I don't care about the windows version. I would actually prefer having win-x86 or win-x64 but it seems to be an invalid value according to this page Windows RIDs Windows 7 / Windows Server 2008 R2 win7-x64 win7-x86 Windows 8 / Windows Server 2012 win8-x64 win8-x86 win8-arm Windows 8.1 / Windows Server 2012 R2 win81-x64 win81-x86 win81-arm Windows 10 / Windows Server 2016 win10-x64 win10-x86 win10-arm win10-arm64 However this Github source is describing more RID so which source is right? As you can see, there is so many mysteries here, mostly because of the lack of documentation or even contradictions between different docs. If at least I could have a working example, then I could perform my tests to answer other questions like trying generic win-x64 RID or see if I can include once my managed libs whatever the .NET Framework version. Please pay attention to my special context: I have an ASP.NET Core project targeting the full .NET Framework Thanks for your answers, I'm desperate to get this simple thing working.
Now provide the response and nothing else.
| I will try to explain all the pain and solutions I've been through as detailed as possible. In my example I use simple text files AAA86.txt , AAA64.txt and AAAany.txt instead of native DLLs to simply demonstrate the extraction process. First thing you need to know: If you try to mix the native NuGet's architecture with a lib folder containing some managed libraries, IT WILL NOT WORK In that case your managed DLLs will be copied to your project's output directory but NOT your native ones. Thanks to Jon Skeet who pointed me in the good direction, advising me to take a look at the Grpc.Core package . The trick is to create a targets file that will handle the DLL extraction. Your targets file should contain something like this <?xml version="1.0" encoding="utf-8"?><Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ItemGroup Condition=" '$(Platform)' == 'x64' "> <Content Include="$(MSBuildThisFileDirectory)..\runtimes\win-x64\native\AAA64.txt"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <Link>AAA64.txt</Link> </Content> </ItemGroup> <ItemGroup Condition=" '$(Platform)' == 'x86' OR '$(Platform)' == 'AnyCPU' "> <Content Include="$(MSBuildThisFileDirectory)..\runtimes\win-x86\native\AAA86.txt"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <Link>AAA86.txt</Link> </Content> </ItemGroup></Project> Also make sure your .targets file is named the same as your AssemblyName. So if the name of your assembly is DemoPackage , your targets file should be named DemoPackage.targets . Otherwise, the .targets file might not be applied when referencing the package in another project. Now few other things you need to know: 1) Visual Studio doesn't care at all about the settings you choose, it will always use a dummy RID. (In my case I always end up with a win7-x64 folder even though I'm on Windows 10...) 2) The platform setting in your project.json is also totally useless { "buildOptions": { "platform": "x64" }} 3) In the runtimes settings if you set only win and/or win-x64 "runtimes": { "win": {}, "win-x64": {}} Visual Studio will instead use win7-x64 . But if you add win10-x64 while you are on a Windows 10 machine then this will be used 4) If you compile your application with a generic RID like this dotnet build -c debug -r win Then your targets file will receive the architecture of your machine (x64 in my case) instead of AnyCPU as I was expecting 5) With only native libraries without any managed ones, the extraction will work without a target file if you follow the architecture runtimes/RID/native 6) With only native libraries in my package, the chosen RID will always be win-x64 building with Visual Studio as I told you the runtime folder always created is win7-x64 , no matter the configuration I select. If I only had one single win RID in my package then it would successfully be picked. EDIT: As a last useful note, when working on such tasks, you might find it convenient to print out the current directory from which your .targets file is being executed like this <Target Name="TestMessage" AfterTargets="Build" > <Message Text="***********************************************************" Importance="high"/> <Message Text="$(MSBuildThisFileDirectory)" Importance="high"/> <Message Text="***********************************************************" Importance="high"/></Target> Your directory will be printed out in the Build output in Visual Studio | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/40104838', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1203116/']} | jdg_79812 |
stackexchange | llm_judgeable_groundtruth_similarity | 76013 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
For any URL with a plus sign (+) in the base URL (not the querystring), IIS7 and IIS7.5 (Windows Server 2008 and 2008 R2) do not appear to forward the URL to the default handler on an ASP.NET application. I started noticing the issue with a custom HTTP handler on *.html but I have the same issue with *.aspx . IIS6 (Server 2003) has no problem with these same URLs. To replicate the issue, in an ASP.NET site, I created a set of ASPX files that did a simple Response.Write with various names: test_something.aspx test_some+thing.aspx test_some thing.aspx The third file was a test to see if IIS7[.5] was treating plus symbols as spaces (as it would in the querystring); this does not appear to be the case. With all of these files in place, hitting http://somehost/test_some+thing.aspx or http://somehost/test_some%2bthing.aspx will work fine in IIS6 but 404 in IIS7/IIS7.5 before getting to any ASP.NET handler. Is there some configuration in IIS7/7.5 that I am missing to get it to "see" a plus sign in the URL without missing the final extension used to determine an HTTP handler?
Now provide the response and nothing else.
| After searching for more combinations of IIS and plus, it appears that IIS7[.5] is set up to reject URLs with a plus sign by default out of some fear of the use of that character; that symbol is still allowed in the querystring, though. The solution is to alter the requestFiltering attribute default on <system><webServer><security><requestFiltering> to allow doubly-encoded characters with a command line call (ultimately modifying your ASP.NET web.config): %windir%\system32\inetsrv\appcmd set config "Default Web Site" -section:system.webServer/security/requestFiltering -allowDoubleEscaping:true This may be a bit more dangerous than one prefers to be with their web site, but there didn't appear to be a way to be more specific than a blanket allow. The warnings were regarding the mismatching that could occur between using a plus in a URL and its typical translation as a space. It looks like the only other alternative is to stop using plus characters in your URLs at all. | {} | {'log_upvote_score': 6, 'links': ['https://serverfault.com/questions/76013', 'https://serverfault.com', 'https://serverfault.com/users/751/']} | jdg_79813 |
stackexchange | llm_judgeable_groundtruth_similarity | 391023 |
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 make NameValueCollection accessible to LINQ query operator such as where, join, groupby? I tried the below: private NameValueCollection RequestFields(){ NameValueCollection nvc = new NameValueCollection() { {"emailOption: blah Blah", "true"}, {"emailOption: blah Blah2", "false"}, {"nothing", "false"}, {"nothinger", "true"} }; return nvc;}public void GetSelectedEmail(){ NameValueCollection nvc = RequestFields(); IQueryable queryable = nvc.AsQueryable();} But I got an ArgumentException telling me that the source is not IEnumerable<> .
Now provide the response and nothing else.
| You need to "lift" the non-generic IEnumerable to an IEnumerable<string> . It has been suggested that you use OfType but that is a filtering method. What you're doing is the equivalent of a cast, for which there is the Cast operator: var fields = RequestFields().Cast<string>(); As Frans pointed out, this only provides access to the keys. You would still need to index into the collection for the values. Here is an extension method to extract KeyValuePair s from the NameValueCollection : public static IEnumerable<KeyValuePair<string, string>> ToPairs(this NameValueCollection collection){ if(collection == null) { throw new ArgumentNullException("collection"); } return collection.Cast<string>().Select(key => new KeyValuePair<string, string>(key, collection[key]));} Edit: In response to @Ruben Bartelink's request, here is how to access the full set of values for each key using ToLookup : public static ILookup<string, string> ToLookup(this NameValueCollection collection){ if(collection == null) { throw new ArgumentNullException("collection"); } var pairs = from key in collection.Cast<String>() from value in collection.GetValues(key) select new { key, value }; return pairs.ToLookup(pair => pair.key, pair => pair.value);} Alternatively, using C# 7.0 tuples: public static IEnumerable<(String name, String value)> ToTuples(this NameValueCollection collection){ if(collection == null) { throw new ArgumentNullException("collection"); } return from key in collection.Cast<string>() from value in collection.GetValues(key) select (key, value);} | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/391023', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3834/']} | jdg_79814 |
stackexchange | llm_judgeable_groundtruth_similarity | 880512 |
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 handling the dblclick event on a span in my web app. A side-effect is that the double click selects text on the page. How can I prevent this selection from happening?
Now provide the response and nothing else.
| function clearSelection() { if(document.selection && document.selection.empty) { document.selection.empty(); } else if(window.getSelection) { var sel = window.getSelection(); sel.removeAllRanges(); }} You can also apply these styles to the span for all non-IE browsers and IE10: span.no_selection { user-select: none; /* standard syntax */ -webkit-user-select: none; /* webkit (safari, chrome) browsers */ -moz-user-select: none; /* mozilla browsers */ -khtml-user-select: none; /* webkit (konqueror) browsers */ -ms-user-select: none; /* IE10+ */} | {} | {'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/880512', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3351/']} | jdg_79815 |
stackexchange | llm_judgeable_groundtruth_similarity | 3972945 |
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 two layouts files in my app. Also I have Activity extends ListActivity. Every item of this activity looks consider item.xml layout file. I am trying to get context menu when make long presss on item, but I don't see it. In my activity I trying to registerForContextMenu(getListView()) and override two methods @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle bundle = this.getIntent().getExtras(); registerForContextMenu(getListView()); new PopulateAdapterTask().execute(ACTION_SELECT); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.context_menu, menu); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterView.AdapterContextMenuInfo info; try { info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); } catch (ClassCastException e) { return false; } long id = getListAdapter().getItemId(info.position); Log.d(TAG, "id = " + id); return true; } Main.xml <?xml version="1.0" encoding="utf-8"?><TabHost xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/tabhost" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="5dp"> <TabWidget android:id="@android:id/tabs" android:layout_width="fill_parent" android:layout_height="wrap_content"/> <FrameLayout android:id="@android:id/tabcontent" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="5dp"> <ListView android:id="@+id/list" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </FrameLayout> </LinearLayout></TabHost> Item.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" > <ImageView android:id="@+id/icon" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/info" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="10dp" android:textSize="15sp" android:singleLine="true" android:ellipsize="marquee" android:scrollHorizontally = "true" android:maxWidth="200dp" /> <LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="right" > <ImageButton android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="fill_parent" android:background="@null" android:paddingRight="10dp" android:paddingLeft="10dp" /> </LinearLayout></LinearLayout> All this doesn't work. Maybe the reason is in LinearLayout? I also find similar topic Android: Context menu doesn't show up for ListView with members defined by LinearLayout? but I have more complicated list item. How to get context menu in my case? Also in my activity I have inner class extends ArrayAdapter. In this class in getView method I can set OnCreateContextMenuListener on every View, after that context menu is appears, but I don't know how to handle items clicks. If I am trying to do this in method onContextItemSelected, item.getMenuInfo() object always is null and i can't to get some information from it. private class ChannelAdapter extends ArrayAdapter<Channel> { private List<Channel> channels; public ChannelAdapter(Context context, int textViewResourceId, List<Channel> objects) { super(context, textViewResourceId, objects); this.channels = objects; } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; if (v == null) { LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = vi.inflate(R.layout.station_item, null); } v.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() { public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.context_menu, menu); } }); Thanks. Hope for your help.
Now provide the response and nothing else.
| I got solution, my friend helped me! Hope this information will helpful to someone.This is complete class code with ArrayAdapter and complex list layout and context menu. public class ComplexListActivity extends ListActivity { /** * Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setListAdapter(new ComplexObjectAdapter(this, R.layout.item, getComplexObjects())); registerForContextMenu(getListView()); } private List getComplexObjects() { List<ComplexObject> list = new ArrayList<ComplexObject>(); list.add(new ComplexObject("1", "1", getResources().getDrawable(R.drawable.icon))); list.add(new ComplexObject("2", "2", getResources().getDrawable(R.drawable.icon))); list.add(new ComplexObject("3", "3", getResources().getDrawable(R.drawable.icon))); list.add(new ComplexObject("4", "4", getResources().getDrawable(R.drawable.icon))); list.add(new ComplexObject("5", "5", getResources().getDrawable(R.drawable.icon))); list.add(new ComplexObject("6", "6", getResources().getDrawable(R.drawable.icon))); list.add(new ComplexObject("7", "7", getResources().getDrawable(R.drawable.icon))); list.add(new ComplexObject("8", "8", getResources().getDrawable(R.drawable.icon))); list.add(new ComplexObject("9", "9", getResources().getDrawable(R.drawable.icon))); return list; } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.context_menu, menu); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterView.AdapterContextMenuInfo info; try { info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); } catch (ClassCastException e) { Log.e("", "bad menuInfo", e); return false; } long id = getListAdapter().getItemId(info.position); Log.d("", "id = " + id); Toast.makeText(this, "id = " + id, Toast.LENGTH_SHORT).show(); return true; } private class ComplexObjectAdapter extends ArrayAdapter<ComplexObject> implements View.OnCreateContextMenuListener { private List<ComplexObject> objects; public ComplexObjectAdapter(Context context, int textViewResourceId, List<ComplexObject> objects) { super(context, textViewResourceId, objects); this.objects = objects; } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; if (v == null) { LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = vi.inflate(R.layout.item, null); } final ComplexObject o = objects.get(position); if (o != null) { TextView textlInfo = (TextView) v.findViewById(R.id.info); textlInfo.setText(o.getName()); ImageView channelIcon = (ImageView) v.findViewById(R.id.icon); channelIcon.setAdjustViewBounds(true); channelIcon.setMaxHeight(30); channelIcon.setMaxWidth(30); channelIcon.setImageDrawable(o.getLogo()); ImageButton button = (ImageButton) v.findViewById(R.id.button); button.setImageResource(R.drawable.icon); v.setOnCreateContextMenuListener(this); } return v; } public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo) { // empty implementation } }} let me know if someone will find better approach. Thanks! | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3972945', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/423868/']} | jdg_79816 |
stackexchange | llm_judgeable_groundtruth_similarity | 48931966 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Have a Sharepoint list with 5 columns i.e Asset Class, Start Date/TIme, End Date/Time, Patching status, comments. I have column validation on Start Date/TIme and End Date/Time. My problem is if the data needs to be amended i need to allow them to save as is if they are amending details on the Asset Class, Patching status or the comments columnns i.e as long as they are not changing the column information on Start Date/TIme or End Date/Time.
Now provide the response and nothing else.
| You will need to set an explicit constraint to make tableView.height 4x bigger than your view size. They don't have intrinsic content size, so the stackView does not "know" how to properly fill the space. Also, set the distribution mode to .fill , because .fillProportionally uses intrinsic content size to determine proper distribution (excerpt from docs ): case fillProportionally A layout where the stack view resizes its arranged views so that they fill the available space along the stack view’s axis. Views are resized proportionally based on their intrinsic content size along the stack view’s axis. Using constraints we are setting the size explicitly, not using intrinsic content size - thus .fillProportionally does not work. I assume in that case the stackView uses values returned by view.intrinsicContentSize directly. However, constraints will not change view.intrinsicContentSize . If you would be doing it in code, you could do it with this: tableView.heightAnchor.constraint(equalTo: myView.heightAnchor, multiplier: 4).isActive = true In storyboards, control drag from tableView to the myView and select Equal Heights : Then select the created constraint and set the appropriate multiplier: | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/48931966', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9396957/']} | jdg_79817 |
stackexchange | llm_judgeable_groundtruth_similarity | 46915495 |
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 supposed to normalize an array. I've read about normalization and come across a formula: I wrote the following function for it: def normalize_list(list): max_value = max(list) min_value = min(list) for i in range(0, len(list)): list[i] = (list[i] - min_value) / (max_value - min_value) That is supposed to normalize an array of elements. Then I have come across this: https://stackoverflow.com/a/21031303/6209399 Which says you can normalize an array by simply doing this: def normalize_list_numpy(list): normalized_list = list / np.linalg.norm(list) return normalized_list If I normalize this test array test_array = [1, 2, 3, 4, 5, 6, 7, 8, 9] with my own function and with the numpy method, I get these answers: My own function: [0.0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1.0]The numpy way: [0.059234887775909233, 0.11846977555181847, 0.17770466332772769, 0.23693955110363693, 0.29617443887954614, 0.35540932665545538, 0.41464421443136462, 0.47387910220727386, 0.5331139899831830 Why do the functions give different answers? Is there others way to normalize an array of data? What does numpy.linalg.norm(list) do? What do I get wrong?
Now provide the response and nothing else.
| There are different types of normalization. You are using min-max normalization. The min-max normalization from scikit learn is as follows. import numpy as npfrom sklearn.preprocessing import minmax_scale# your functiondef normalize_list(list_normal): max_value = max(list_normal) min_value = min(list_normal) for i in range(len(list_normal)): list_normal[i] = (list_normal[i] - min_value) / (max_value - min_value) return list_normal#Scikit learn version def normalize_list_numpy(list_numpy): normalized_list = minmax_scale(list_numpy) return normalized_listtest_array = [1, 2, 3, 4, 5, 6, 7, 8, 9]test_array_numpy = np.array(test_array)print(normalize_list(test_array))print(normalize_list_numpy(test_array_numpy)) Output: [0.0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1.0] [0.0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1.0] MinMaxscaler uses exactly your formula for normalization/scaling: http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.minmax_scale.html @OuuGiii: NOTE: It is not a good idea to use Python built-in function names as varibale names. list() is a Python builtin function so its use as a variable should be avoided. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46915495', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6209399/']} | jdg_79818 |
stackexchange | llm_judgeable_groundtruth_similarity | 241684 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm curious to know if this assumption is correct, Consider $A_{n \times n}$ is invertible, so $AA^{-1} = A^{-1}A = I$, Now, what I wonder is if we have lets say $(I + AB)_{n\times n}$ (an arbitrary matrix), So is it possible to diminish $A$ and $A^{-1}$ in this situation: $A(I+AB)A^{-1} \rightarrow (I+AB)$ I think it's possible due to the fact that $AA^{-1} = I $, Because it's the same as saying $4 \times X \times {1 \over 4}$ is the same as $X$ Is this the same for $_{n \times n}$ matrices? if so how can it be proven?
Now provide the response and nothing else.
| Matrix multiplication is not commutative in general. Hence, in general$$A(I + AB)A^{-1} \neq I + AB$$If $A$ and $B$ commute i.e. if we have $AB = BA$, then $$A(I + AB)A^{-1} = A(I + BA)A^{-1} = \underbrace{A \cdot A^{-1}}_I + A \cdot B \underbrace{A \cdot A^{-1}}_I = I + AB$$Hence, if $A$ and $B$ commute then it is true that $$A(I + AB)A^{-1} = I + AB$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/241684', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/49890/']} | jdg_79819 |
stackexchange | llm_judgeable_groundtruth_similarity | 6374576 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What is the difference between "TOP" and "SAMPLE" in TeraData SQL? Are they the same?
Now provide the response and nothing else.
| From TOP vs SAMPLE : TOP 10 means "first 10 rows in sorted order". If you don't have an ORDER BY, then by extension it will be interpreted as asking for "ANY 10 rows" in any order. The optimizer is free to select the cheapest plan it can find and stop processing as soon as it has found enough rows to return. If this query is the only thing running on your system, TOP may appear to always give you exactly the same answer, but that behavior is NOT guaranteed. SAMPLE, as you have observed, does extra processing to try to randomize the result set yet maintain the same approximate distribution. At a very simple level, for example, it could pick a random point at which to start scanning the table and a number of rows to skip between rows that are returned. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6374576', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/591300/']} | jdg_79820 |
stackexchange | llm_judgeable_groundtruth_similarity | 4257386 |
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:
Question: Suppose you know $G:=\gcd$ (greatest common divisor) and $L:=\text{lcm}$ (least common multiple) of $n$ positive integers; how many solution sets exist? In the case of $n = 2$ , one finds that for the $k$ distinct primes dividing $L/G$ , there are a total of $2^{k-1}$ unique solutions. I am happy to write out a proof of the $n = 2$ case if desirable, but my question here concerns the more general version. The $n=3$ case already proved thorny in my explorations, so I would be happy to see smaller cases worked out even if responders are unsure about the full generalization. Alternatively: If there is already an existing reference to this problem and its solution, then a pointer to such information would be most welcome, too!
Now provide the response and nothing else.
| If you are interested in counting tuples $(a_1,a_2,\dots,a_n)$ such that $\gcd(a_1,\dots,a_n) = G$ and $\operatorname{lcm}(a_1,\dots,a_n) = L$ then we can do it as follows. If $L/G = \prod\limits_{i=1}^s p_i^{x_i}$ then each $a_i$ must be of the form $G \prod\limits_{j=1}^s p_i^{y_{i,j}}$ with $0 \leq y_{i,j} \leq x_i$ . Hence for each prime $p_i$ we require that the function from $\{1,\dots, n\}$ to $\mathbb N$ that sends $j$ to $y_{i,j}$ be a function that hits $0$ and $x_i$ . The number of such functions is easy by inclusion-exclusion for $x_i \geq 1$ , it is $(x_i+1)^n - 2(x_i)^n + (x_i-1)^n$ . It follows the total number of tuples is $\prod\limits_{i=1}^s ( (x_i+1)^n - 2x_i^n + (x_i-1)^n)$ . | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4257386', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/37122/']} | jdg_79821 |
stackexchange | llm_judgeable_groundtruth_similarity | 1078926 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a little question: which other representation of factorial $n!$ without using the factorial? Is there any definition of factorial as a series? or any other way? Thanks in advanced.
Now provide the response and nothing else.
| It depends on what you mean by "without using the factorial". The typical definition is usually$$n!=\prod_{k=1}^n k$$meaning multiply all the natural numbers less than or equal to $n$ together. It can also be defined recursively (or as a sequence) where $f_0=1$ and $f_n=n\cdot f_{n-1}$. Others have mentioned the Gamma function, which is a generalized factorial defined by an integral. It can also be represented as an $n$th derivative, where$$n!=\frac{d^n}{dx^n}x^n$$which reduces to a natural number for natural $n$ due to the power rule. I don't know of any definition of a factorial as a series , however, it is a part of some useful ones. For example, $$\sum_{x=0}^{\infty}\frac{1}{x!}=e$$You could define factorial some other ways, like for $n\ge1$, you could say $n!=n!!(n-1)!!$, but that just makes things more complicated without really giving any benefit. I'm not sure why you need or want another definition of factorial, but there should be something here to help you. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1078926', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/188829/']} | jdg_79822 |
stackexchange | llm_judgeable_groundtruth_similarity | 8190 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Is there an notion of elliptic curve over the field with one element? As I learned from a previous question , there are several different versions of what the field with one element and what schemes over it should be (see for example this article by Javier López Peña and Oliver Lorscheid). What I want to know is whether there a good notion of elliptic curve over $F_{un}$? What about modular forms?
Now provide the response and nothing else.
| In a strict sense, elliptic curves over the rationals (say) are not defined over $F_1$ since their reduction modulo $p$ varies with $p$, e.g. they have places of bad reduction. However, CM elliptic curves have some of the properties that one would associate with objects defined over $F_1$. For example, their L-function looks a bit like the twist of a constant elliptic curve over a function field, except that the role played by the character is actually played by a Hecke character. So, in a sense, a CM elliptic curve is the twist of a curve over $F_1$ by a Hecke character, although I have never tried to fully formalize this notion. Another way to view this is perhaps through J. Borger's viewpoint in which a variety over $F_1$ is a variety in which all Frobeniuses lift. That sort of happens for CM elliptic curves. | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/8190', 'https://mathoverflow.net', 'https://mathoverflow.net/users/184/']} | jdg_79823 |
stackexchange | llm_judgeable_groundtruth_similarity | 30466 |
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 need to authenticate against another programs user credentials to allow access to a second tie-in system. I am having trouble figuring out what hashing algorithm is being used by the first program in order to create a connection to it. I have the following hashes from throwing around test passwords. HASH | PLAIN TEXTF3d2427323a202034686f736973616 | passwordF2c2737616d6f7270686f736973616 | abc I do know that the passwords are not case sensative, which likely means that the first program is converting the plain text to all upper or all lower case. Can anyone identify these hashes?
Now provide the response and nothing else.
| This is not one of the standard cryptographic hash functions . There is also some sort of encoding which includes things other than the hash, because both strings end with the same sequence '686f736973616'. In fact it looks to partially be the direct encoding of ASCII strings, possibly truncated. Ignoring the leading 'F' and the final '6' (are you sure the values are not truncated when you display them ?), your examples map to =$'2: 4hosisa and ,'7amorphosisa respectively, which look suspiciously non-random to me. Looking at it more closely, I notice that this so-called "hash" is just a byte-wise XOR. Namely, it seems to go thus: Convert the password to lowercase. Pad the password to 14 characters by appending spaces. XOR the encoding of the password with the encoding of: metamorphosisa XOR each resulting byte with 0x20 (the ASCII encoding of a space). Convert the result into hexadecimal. Put a 'F' at the beginning and a '6' at the end. I.e. not a hash at all, rather one of the weakest forms of homemade encryption. | {} | {'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/30466', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/20520/']} | jdg_79824 |
stackexchange | llm_judgeable_groundtruth_similarity | 24038939 |
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 just playing around with JavaScript and got stuck with a simple program. I declared an array in JavaScript like var a = [0, 1, 2]; Then as there is no fixed size for an array in JavaScript and we can add more to the array, I added another integer to array. a[3] = 3; And as expected If I try to access a[4] I am definitely going to get it as undefined . Now, if I take an array var a = [0,1,2]; And add another element a[4] = 4; I have intentionally not defined a[3] , and this also gives me a[3] as undefined . Here is a fiddle where this can be observed: http://jsfiddle.net/ZUrvM/ Now, if I try the same thing in Java, int[] a = new int[4];a[0] = 0;a[1] = 1;a[3] = 3; Then I end up with a[2] = 0; You can see this on ideone: https://ideone.com/WKn6Rf The reason for this in Java I found is that the four variables are defined while declaring the array and we can only assign values to the declared size of array.But in JavaScript when I declare an array of size 3 and then add 5th element why does it not consider the 4th element to be null or 0 if we have increased the array size beyond 4? Why do I see this strange behavior in JavaScript, but not in other languages?
Now provide the response and nothing else.
| Why is this strange behavior in JavaScript? Because arrays are only objects. If you access a nonexisting property, you get back undefined . You simply didn't assign an element at index 3 , so there is nothing. Auto-growing the array by assigning higher indices does not change this behaviour. It will affect the .length property, yes, but the intermediate indices will stay nonexistent. This is known as a sparse array . Why is this strange behaviour in Java / C / C++? Because arrays are chunks of allocated memory, and when allocating an array of size 4, all its elements take their values from that memory location. To avoid indeterminate values, in some languages/occasions the fields get default-initialised, typically with 0 . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24038939', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3556874/']} | jdg_79825 |
stackexchange | llm_judgeable_groundtruth_similarity | 1237 |
Below is a question asked on the forum softwarerecs.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm looking for a password manager which is available as Android App and Linux Desktop application alike. I know there's e.g. KeePassDroid (see: Password manager for Linux with just working in-browser autotype ), but that does not fit my requirements, as it has a "fixed layout" when it comes to its "password form". What I need: must be available as native Android app and native Linux Desktop application specific forms for different "password" types, such as credit cards, login information, etc. folder-like organization (or at least categories somehow) secure storage (i.e. good encryption) data file location should be configurable (requirement for the next item) Sync between Desktop and Mobile must be possible by simply synchronizing the database file Android app must not require network access (sync will be done separately) Preferred options (not mandatory) nice GUI icon-sets to select icons from for folders and "leafs" is contained in Ubuntu repositories (PPA is fine, a .deb would do, no problems if it comes as .jar or ready-to-go .tar.gz however, or source if not too many dependencies (I feel fit enough to configure && make && check-install ;) I'm currently running Ubuntu 12.04, but plan switching to Debian with my next install – which won't be too soon, however) Candidates tried, but failed: KeePassDroid / KeePassDroidX : While offering clients for multiple platforms, the format is fixed for "web logins" (name, url, login, password, comment), which is unsuitable for e.g. credit or debit cards. Pocket : while offering an Android app and Java desktop, and seemingly even different "forms" suitable for credit cards, logins, and more, the Android app requires the Internet permission, and it wants to sync via Dropbox. Also I couldn't get the desktop app working (it required an existing database, which was of course not there to start with), using the same database on both ends involves permanent renaming of the file (both ends are fixed to different file names), plus the Desktop has trouble with mixed-case directory names on case sensitive file-systems.
Now provide the response and nothing else.
| The easy thing about your criteria is that you don't actually need a matched set. As long as the data file is completely inter-operable, any combination of unrelated apps will work. TL;DR KeepassX 2 + Keepass2Android use the same data format and are the only pair I know of to meet all your criteria, even though there are a couple "gotchas". Data format As far as password-manager data formats that are interchangeable go, there is basically one 800 pound gorilla in the room. The data format originally conceived for KeePass is both well established and widely supported. The cryptography used has also been extensively peer reviewed so it is arguably safer than many smaller players or commercial solutions that use proprietary formats. The trick is going to be that you need to use version 2 of the data format (kdbx). Your criteria includes several items including the need for custom data fields that were not possible in the version 1 database format (kdb) which restricted entries to a pre-defined set of fields that made is suitable for a rigid "login credentials manager" roll but not a "private data manager" role that you are looking for. History The original KeePass software was written for Windows. and the 1.x series only worked on that platform (although it worked under WINE so some of us got Linux mileage out of it before there were alternatives. The 2.x series is basically a rewrite with many advancements that includes a port that will run under Mono for Linux, OSX and BSD support. I would actually recommend not using the original client software and using some of the alternatives instead. The pair I use seem to match all your criteria perfectly with one caveat. The keepass database format allows arbitrary key/value pairs to be stored with each entry. While theoretically this could be used with a smart interface that intelligently adapted to different entry types (e.g. website login, credit card data, passport, etc), to my knowledge no clients yet do this. What you can do is use the arbitrary fields to organize your own data. That caveat aside, I tried a LOT of alternatives when I was picking my own solution and was unable to find a better pair. If something else is out there that meets your criteria better I would like to hear about it too as our needs seem similar. This is the best setup I could arrange. Linux Client Recommendation The KeePassX project has been around quite some time. It was originally conceived as a parallel to the Windows project and indeed called KeePass/Linux. After the original project got a port of it's own, the name KeePassX was adapted and the code has in fact been ported to also run on Windows and OSX. As you can see from the commit log it is actively developed, but unfortunately the project has always suffered from very long release cycles and a hesitancy to call anything stable that hasn't stood up to years of testing. For your purposes you will need to use the 2.x series . If your distro still has the 0.4.x series the data format won't be interchangeable with the Android app in this recommendation. Since anything you would be putting in such a system is obviously important and irrecoverable if you were to corrupt it, you should definitely have a fail safe backup system it place. I like to keep my database it a private git repository so there is a versioned history of it spread across many of my machines as well as some special backup provisions. You said you are going to be syncing and managing the database file yourself. This is fine, just do your homework and do it right. It is NOT the client software's fault if a corrupted copy of the DB gets synced across all your devices and clobbers your backups! The latest KeepassX 2 release tag as of this writing edit is 2.0.3, but check the project news and source code tags for new ones. That source can be downloaded , compiled and installed from the announcement page or you can download an up to the minute zip from the project's Github mirror Android Client Recommendation You mentioned you had tried KeePassDroid , which was an attempt to port the KeePass 1 software to Android. I found the interface to be clunky and (when I last tried it) it did not support custom fields. There is support for kdbx format files (marked beta) but not all the features are exploited. Instead I use use Keepass2Android and find the interface to be better than any of the other KeePass compatible clients available. There is an offline version that is stripped of all connectivity options if you prefer to do the sync yourself, so that criteria is met. Custom fields are also supported and the interface even makes this relatively simple. The download is a little heavy weighing in at an unwieldy 13 MB, but in practice the front end is clean and fast and has been updated regularly to keep pace with the latest Android UI guidelines. The backend is heavy because is it wraps up other widely used code for the actual encryption but this does mean you can be pretty sure that the cryptography is being done right than some one-off design. Bonus Let's say you are on a Linux box (or almost any other desktop platform) and need into your password database but can't be bothered to install a program from source or fiddle with custom package repositories. There is an open source JavaScript client with read-only support for KeePass (kdbx only) files called BrowsePass ( Chrome extension here ). | {} | {'log_upvote_score': 6, 'links': ['https://softwarerecs.stackexchange.com/questions/1237', 'https://softwarerecs.stackexchange.com', 'https://softwarerecs.stackexchange.com/users/185/']} | jdg_79826 |
stackexchange | llm_judgeable_groundtruth_similarity | 215350 |
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:
How do I let mathematica compute a tensor contraction like $\delta_{ab}\delta_{bc}$ with an output $\delta_{ac}$ efficiently? I tried TensorContract and TensorReduce but they were not helpful. Thanks for your help!
Now provide the response and nothing else.
| A straightforward way to implement Kronecker Delta is as follows: SetAttributes[\[Delta], Orderless];\[Delta][a_, b_] f_[c___, b_, d__] ^:= f[c, a, d] /; ! NumericQ[b];\[Delta][a_, a_] := dim /; ! NumericQ[a];\[Delta][a_, b_] := Boole[a == b] /; NumericQ[a] && NumericQ[b];Format[\[Delta][a_, b_]] := Subscript[\[Delta], a, b]; where dim is the dimension of the vector space. We see that it satisfies required conditions: In[1]:= {\[Delta][a, b] \[Delta][b, d], \[Delta][a, b] f[b, c], \[Delta][a, b] == \[Delta][b, a], \[Delta][1, 2], \[Delta][1, 1], \[Delta][a, a]}Out[1]:= {Subscript[\[Delta], a, d], f[a, c], True, 0, 1,dim} In other words, for the input $\left\{\delta _{a,b} \delta _{b,d},\delta _{a,b} f(b,c),\delta _{a,b}=\delta _{b,a},\delta _{1,2},\delta _{1,1},\delta _{a,a}\right\}$ we get the expected output: $\left\{\delta _{a,d},f(a,c),\text{True},0,1,dim\right\}$ | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/215350', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/34749/']} | jdg_79827 |
stackexchange | llm_judgeable_groundtruth_similarity | 2659290 |
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 method: public bool IsValid{ get { return (GetRuleViolations().Count() == 0); }}public IEnumerable<RuleViolation> GetRuleViolations(){ //code here} Why is it that when I do .Count() above it is underlined in red? I got the following error: Error 1 'System.Collections.Generic.IEnumerable' does not contain a definition for 'Count' and no extension method 'Count' accepting a first argument of type 'System.Collections.Generic.IEnumerable' could be found (are you missing a using directive or an assembly reference?) c:\users\a\documents\visual studio 2010\Projects\NerdDinner\NerdDinner\Models\Dinner.cs 15 47 NerdDinner
Now provide the response and nothing else.
| You add: using System.Linq; at the top of your source and make sure you've got a reference to the System.Core assembly. Count() is an extension method provided by the System.Linq.Enumerable static class for LINQ to Objects, and System.Linq.Queryable for LINQ to SQL and other out-of-process providers. EDIT: In fact, using Count() here is relatively inefficient (at least in LINQ to Objects). All you want to know is whether there are any elements or not, right? In that case, Any() is a better fit: public bool IsValid{ get { return !GetRuleViolations().Any(); }} | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/2659290', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/95265/']} | jdg_79828 |
stackexchange | llm_judgeable_groundtruth_similarity | 224767 |
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:
In special relativity one may show that a plane wave solution of Maxwell's equations (in a vacuum), of the form $A^a=C^a\mathrm{e}^{\mathrm{i}\psi}$ has the following properties: The normal $k:=\mathrm{d}\psi$ to the surfaces of constant $\psi$ is a null vector and the integral curves of $k$ are null geodesics. Here $A$ is the electromagnetic vector potential, $C$ is a constant vector and $\psi$ is some function. This analysis is possible because of the relatively simple form of the Maxwell equations in flat space, $\partial^a\partial_a A^b=0$ (Lorenz gauge assumed). However, in curved spacetime, we have an extra term involving the Ricci tensor that is irrelevant for SR:$$\nabla^a\nabla_aA^b=R^b{}_aA^a,$$where $\nabla$ is the Levi-Civita connection of our spacetime $(\mathcal{M},g)$ and $R_{ab}$ its Ricci curvature. The textbook treatment is to now look at solutions of the form $A^a=C^a\mathrm{e}^{\mathrm{i}\psi}$ where the covariant derivatives of $C$ are "small." In order to obtain the condition for $\mathrm{d}\psi$ to be null and autoparallel ($\nabla_a\psi\nabla^a\psi=0$), one must ignore the term $\nabla_b\nabla^b C^a$ as well as the Ricci tensor term. The missing details may be found in [1], sections 4.2 and 4.3. This approximation is called the geometric optics approximation. Ref. [2] gives the following characteristic lengths for ray optics (section 2.8): The wavelength $\lambda$. The typical length $L$ over which the amplitude, polarization and wavelength of the wave vary significantly. A typical "radius of curvature," which can be taken to be $$R:=\lvert\text{typical component of the Riemann tensor in a typical local inertial system}\rvert^{-1/2}$$ The region of validity for geometric optics is then $\lambda\ll L$ and $\lambda \ll R$. Question: Since one must ignore terms in the preceding analysis, do light rays not actually follow null geodesics in GR? Is $\mathrm{d}\psi$ even null? Furthermore, how do wave-like solutions of Maxwell's equations behave over length-scales greater than those given in [2] (i.e., over length scales where the curvature of $\mathcal{M}$ can vary greatly and rapidly). In particular, to what extent do they travel along null geodesics? Please note: The argument that massless particles travel along null geodesics in flat space so the same must be true (by the Equivalence Principle) in curved space is not an answer to this question. I'm asking about wave-like solutions to the Maxwell equations. Light, classically, is just a wave solution of the vacuum Maxwell equations. Any answer should include (or reference) a rigorous analysis of Maxwell's equations. This is not a question that can be answered well by stating a few equations everyone knows and nitpicking at the words in the OP. (Apparently one member of the site did not have this impression, so I'm making it more clear.) References: [1] Wald, R.M. General Relativity. Chicago University Press, 1984. [2] Straumann, N. General Relativity. Springer, 2013.
Now provide the response and nothing else.
| For clarity I think is best to start with Minkowski spacetime. The equation we are trying to solve to understand the radiation of a point particle is:$$\square A^{b}=j^{b}$$ with the gauge $\nabla_{a}A^{a}=0$ and $j^{b}$ is the current density. The potential\begin{eqnarray} A^{b}(t,x)&=&\int G^{b}_{a}(t,x,t'x')j^{a}(t',x')dx'^{3}dt\\&=&\int\delta_{a}^{b}\delta(t−t′−|x − x′|)∕|x − x′|j^{a}(t',x')dx'^{3}dt'\end{eqnarray} where $G^{b}_{a}$ is the Green function with support in the past light cone. In fact, the potential $A^{b}(t,x)$ only depends in the single event $(t',x')$ in the past which is the intersection between the null cone from $(t,x)$ and the world line of the particle. Now in curved spacetime the generalization \begin{eqnarray}A^{b}(t,x)&=&\int G^{b}_{a}(t,x;t'x')j^{a}(t,x)dV\\&=&\int\delta_{a}^{b}\delta(\gamma(t,x,t'x'))∕\Gamma(x − x ′)|j^{a}(t',x')\sqrt(g)dx'^{3}dt'\end{eqnarray} where $\gamma$ is the null geodesic between the two points $(t,x),(t',x')$ and $\Gamma$ is the distance with respect the induced metric of a suitable spacelike surface that contains $x,x'$ does not work. In general curved spacetimes the retarded Green function would depend on the whole causal past cone and not only the past light cone. This dependence comes from the interaction with the curvature and is related with the extra terms that you point out that vanish for Minkowski. Therefore the potential is not only defined by the information that travel along the null geodesics but depends on the whole past of the particle. Nevertheless, singularities of the field travel along null geodesics globally. This is the content of the propagation of singularity theorems for linear hyperbolic systems and is related with the geometric optics limit. As you required rigorous analysis I will point you to some papers with appropriate calculations: Section 1.4 of http://relativity.livingreviews.org/open?pubNo=lrr-2011-7&page=articlese1.html http://arxiv.org/abs/1108.1825 http://arxiv.org/abs/gr-qc/0008047 Also notice that my answer is just about electromagnetism in curved spacetime. To talk about General Relativity we would need to solve also for the Einstein's Equations. The point particle will affect the metric as self force corrections to the background metric. These type of corrections are treated in depth in the first reference. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/224767', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/59215/']} | jdg_79829 |
stackexchange | llm_judgeable_groundtruth_similarity | 10132706 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Here is the problem and what I currently have, I just don't understand how it is wrong... getByte - Extract byte n from word x Bytes numbered from 0 (LSB) to 3 (MSB) Examples: getByte(0x12345678,1) = 0x56 Legal ops: ! ~ & ^ | + << >> Max ops: 6 Rating: 2 int getByte(int x, int n) { return ((x << (24 - 8 * n)) >> (8 * n));}
Now provide the response and nothing else.
| Your shifting doesn't make any sense - first, you shift left by (24 - 8n) bits, then you shift back right by 8n bits. Why? Also, it's wrong. If n is 0, you shift x left by 24 bits and return that value. Try pen and paper to see that this is entirely wrong. The correct approach would be to do: int getByte(int x, int n) { return (x >> 8*n) & 0xFF;} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10132706', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1330319/']} | jdg_79830 |
stackexchange | llm_judgeable_groundtruth_similarity | 19573074 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
We are currently loading 2 different versions of jQuery on our page, 1.4.2 and 1.10.1. The $ and window.jQuery objects are currently pointing to 1.4.2. We are using noConflict() with version 1.10.1 to set it to $jq1: var $jq1 = jQuery.noConflict(true); Is there any way to get Bootstrap 3.0 plugins to automatically use $jq1 instead of $ or window.jQuery?
Now provide the response and nothing else.
| If you load the bootstrap JS straight after loading jQuery version 1.10.1 and then put jQuery into no conflict mode, it should work. e.g.: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script><!-- Load any Bootsrap JS files before calling jQuery.noConflict() --><script src="bootstrap.js"></script><script>// Put jQuery 1.10.2 into noConflict mode.var $jq1 = jQuery.noConflict(true);</script><!-- This can be before or after the above --><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> jQuery.noConflict(true) will reassign both $ and jQuery to their previous values so it doesn't matter if version 1.4.2 is loaded first or not. It does mean your users will be downloading jQuery twice though and you will need to remember if to use $jq1 or $ when doing anything with jQuery. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19573074', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2916998/']} | jdg_79831 |
stackexchange | llm_judgeable_groundtruth_similarity | 5176 |
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 two Linux distributions (OpenSuSE, Ubuntu) installed on two different partitions. Each time I start my machine, GRUB loads up, allowing me to select one of the two distributions. I don't want the GRUB to show up, so I limit timeout to zero in /boot/grub/menu.lst, which will most probably make my machine load OpenSuSE each time I start my PC because it's the first option in the menu.lst. Is it possible that the second time I restart my PC, Ubuntu gets loaded automatically? The third time I restart again, OpenSuSE may get booted while fourth time I restart, Ubuntu may load up and so on? In other words, how can I make my machine to boot the next OS in menu.lst, the next time it is restarted?
Now provide the response and nothing else.
| Put something in the startup scripts to rewrite menu.lst . So have Ubuntu write a version of menu.lst that loads OpenSuSE, and have OpenSuSE write a version that loads Ubuntu. A relatively safe way to do this would be to have 3 files, menu.lst , menu.lst.ubuntu and menu.lst.SuSE and have the scripts do: cp menu.lst.ubuntu menu.lst on SuSE and: cp menu.lst.SuSE menu.lst on Ubuntu. | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/5176', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/4381/']} | jdg_79832 |
stackexchange | llm_judgeable_groundtruth_similarity | 9031891 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
My Problem is the following:Say you have three different tables (Products, Bills and Returns) | ProductId | Name |=====================| 1 | Car || BillId | ProductId | Amount |=================================| 1 | 1 | 100$ || 2 | 1 | 200$ || ReturnId | ProductId | Amount |===================================| 1 | 1 | 50$ | How would a SINGLE Query look like to get the following output: | Product-ID | Name | Type | Amount |=====================================| 1 | Car | Bill | 100$ || 1 | Car | Bill | 200$ || 1 | Car | Ret | 50$ | I was trying with all sorts of Joins, and somehow I can't get my head around this.What am I doing wrong?The closest solution I have found till now was something like this: SELECT p.*, (CASE WHEN b.Amount IS NOT NULL THEN 'Bill' ELSE 'Ret' END) AS Type, COALESCE(b.Amount, r.Amount) AS AmountFROM Products pLEFT JOIN Bills b ON b.ProductId = p.ProductIdLEFT JOIN Returns r ON r.ProductId = p.ProductId One thing is very important to me: The real scenario-query is MUCH bigger, and I don't want to copy/paste the whole logic of there query as if it would be the case when using a Union.
Now provide the response and nothing else.
| The below would work as needed, SELECT Products.*, [Type], AmountFROM Products INNER JOIN ( SELECT ProductID, 'Bill' [Type], Amount FROM Bills UNION ALL SELECT ProductID, 'Ret' [Type], Amount FROM Returns ) transactions ON transactions.ProductID = Products.ProductID | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9031891', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/772667/']} | jdg_79833 |
stackexchange | llm_judgeable_groundtruth_similarity | 382822 |
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 declared a private variable vector<SomeClass> theVector; someplace inside my SomeClass class. Why can't I say: delete theVector inside my SomeClass destructor? The compiler error says: type `class Vector<SomeClass>' argument given to `delete', expected pointer What expected pointer?
Now provide the response and nothing else.
| If new and delete go hand in hand. To delete something you need to create it via new (which gives you a pointer). You can then delete the pointer. The way you are declaring the vector it is being created on the stack (not the heap) and will be deallocated when it goes out of scope. int main(){ vector<SomeClass> theVector; vector<SomeClass>* ptrVctor = new vector<SomeClass>(); delete ptrVctor; // ptrVctor must be deleted manually // theVector destroyed automatically here} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/382822', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/45963/']} | jdg_79834 |
stackexchange | llm_judgeable_groundtruth_similarity | 22011106 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
TableViewApplication[1458:70b] CUICatalog: Invalid asset name supplied: (null), or invalid scale factor: 2.000000 Getting this warning while working with TableViewController. How to rectify this error and which block is affected?
Now provide the response and nothing else.
| This one appears when someone is trying to put nil in [UIImage imageNamed:] Add symbolic breakpoint for [UIImage imageNamed:] Add $arg3 == nil condition on Simulator, $r0 == nil condition on 32-bit iPhone, or $x2 == nil on 64-bit iPhone. Run your application and see where debugger will stop. P.S. Keep in mind this also happens if image name is empty string. You can check this by adding [(NSString*)$x2 length] == 0 to the condition. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/22011106', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3336176/']} | jdg_79835 |
stackexchange | llm_judgeable_groundtruth_similarity | 2265137 |
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 seeking a tutorial on how to cache images loaded from a url into cells of a uitableview. I found an example here http://www.ericd.net/2009/05/iphone-caching-images-in-memory.html#top But the code is incomplete. I'm an objective c novice so I found it very difficult to fill in the missing pieces.
Now provide the response and nothing else.
| Here is a simple ImageCache implementation using NSCache. ImageCache is a singelton. ImageCache.h #import <Foundation/Foundation.h> @interface ImageCache : NSObject @property (nonatomic, retain) NSCache *imgCache; #pragma mark - Methods + (ImageCache*)sharedImageCache; //- (void) AddImage:(NSString *)imageURL: (UIImage *)image; - (void) AddImage:(NSString *)imageURL withImage:(UIImage *)image; - (UIImage*) GetImage:(NSString *)imageURL; - (BOOL) DoesExist:(NSString *)imageURL; @end ImageCache.m #import "ImageCache.h" @implementation ImageCache @synthesize imgCache; #pragma mark - Methods static ImageCache* sharedImageCache = nil; +(ImageCache*)sharedImageCache { @synchronized([ImageCache class]) { if (!sharedImageCache) sharedImageCache= [[self alloc] init]; return sharedImageCache; } return nil; } +(id)alloc { @synchronized([ImageCache class]) { NSAssert(sharedImageCache == nil, @"Attempted to allocate a second instance of a singleton."); sharedImageCache = [super alloc]; return sharedImageCache; } return nil; } -(id)init { self = [super init]; if (self != nil) { imgCache = [[NSCache alloc] init]; } return self; } // - (void) AddImage:(NSString *)imageURL: (UIImage *)image- (void) AddImage:(NSString *)imageURL withImage:(UIImage *)image { [imgCache setObject:image forKey:imageURL]; } - (NSString*) GetImage:(NSString *)imageURL { return [imgCache objectForKey:imageURL]; } - (BOOL) DoesExist:(NSString *)imageURL { if ([imgCache objectForKey:imageURL] == nil) { return false; } return true; } @end Example UIImage *image; // 1. Check the image cache to see if the image already exists. If so, then use it. If not, then download it. if ([[ImageCache sharedImageCache] DoesExist:imgUrl] == true) { image = [[ImageCache sharedImageCache] GetImage:imgUrl]; } else { NSData *imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: imgUrl]]; image = [[UIImage alloc] initWithData:imageData]; // Add the image to the cache //[[ImageCache sharedImageCache] AddImage:imgUrl :image]; [[ImageCache sharedImageCache] AddImage:imgUrl withImage:image]; } | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2265137', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/264273/']} | jdg_79836 |
stackexchange | llm_judgeable_groundtruth_similarity | 145179 |
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 $a^n \equiv b \pmod m$ and $b^n \equiv c \pmod m$, is it true that $(a^n)^n \equiv c \pmod m$? From testing cases it seems to be true, but I'm unsure of how to prove this.
Now provide the response and nothing else.
| Yes; because $a\equiv b\pmod{m}$ and $c\equiv d\pmod{m}$ implies $ac\equiv bd\pmod{m}$. Therefore, $x\equiv y\pmod{m}$ implies $x^n\equiv y^n\pmod{m}$ for all positive integers $n$. Thus, $a^n\equiv b\pmod{m}$ implies that $(a^n)^n \equiv b^n \equiv c\pmod{m}$, and since congruence is transitive, $(a^n)^n\equiv c\pmod{m}$. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/145179', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/31401/']} | jdg_79837 |
stackexchange | llm_judgeable_groundtruth_similarity | 505641 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am just starting to learn design patterns and I have two questions related to the Decorator... I was wondering why the decorator pattern suggests that the decorator implement all public methods of the component of which it decorates? Can't the decorator class just be used to provide the additional behaviors, and then the concrete component (which is passed into it) just be used to call everything else? And secondly, what if the concrete component you want to decorate doesn't have a base class which the abstract decorator can also derive from? Thanks in advance!
Now provide the response and nothing else.
| I think you have have misunderstood Decorator. You're thinking of a simple case of extending a concrete class with additional functionality. In this case, yes in most OO languages the derived class can simply allow its superclass to handle any unimplemented methods. class Base { function foo() { return "foo"; } function bar() { return "bar"; }}// Not what we think of as a Decorator,// really just a subclass.class Decorator extends Base { // foo() inherits behavior from parent Base class function bar() { return parent::bar() . "!"; // add something }} A Decorator class does not extend the base class of its "decorated" class. It is a different type, which has a member object of the decorated class. Thus it must implement the same interface, if only to call the respective method of the decorated object. class Decorator { // extends nothing protected $base; function __construct(Base $base) { $this->base = $base; } function foo() { return $base->foo(); } function bar() { return $base->foo() . "!"; // add something }} It might be worthwhile to define an interface (if your language supports such a thing) for both the decorated class and the Decorator class. That way you can check at compile time that the Decorator implements the same interface. interface IBase { function foo(); function bar();}class Base implements IBase { . . .}class Decorator implements IBase { . . .} Re: @Yossi Dahan's comment: I see the ambiguity in the wikipedia article, but if you read carefully it does say that the component being decorated is a field in the decorator object, and that the component is passed as an argument to the decorator constructor. This is different from inheritance. Though the wikipedia article does say the decorator inherits from the component, you should think of this as implementing an interface, as I showed in the PHP example above. The decorator still has to proxy for the component object, which it wouldn't if it had inherited. This allows the decorator to decorate an object of any class that implements that interface. Here are some excerpts from "Design Patterns: Elements of Reusable Object-Oriented Software" by Gamma, Helm, Johnson, and Vlissides: Decorator Intent Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality. Motivation ... A decorator conforms to the interface of the component it decorates so that its presence is transparent to the component's clients. Participants Decorator maintains a reference to a Component object and defines an interface that conforms to Component's interface. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/505641', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61742/']} | jdg_79838 |
stackexchange | llm_judgeable_groundtruth_similarity | 3548857 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How can a javascript file know where it is located? For example: <script type="text/javascript" src="http://mysite.com/scripts/howdy.js"></script> How can the code in howdy.js know about http://mysite.com/scripts/howdy.js ? Edit: Clarification. I cannot rely on searching the DOM for my script tag because I need to know about it before the DOM may be ready.
Now provide the response and nothing else.
| In the moment in which the current script is being executed, will be the last script element in the DOM, therefore you can get it by: var scripts = document.getElementsByTagName('script'), currentScriptSrc = scripts[scripts.length-1].src; Check this example that loads this script . Edit: Taking in consideration the @kangax's comment, about the async and defer attributes, the only safe way IMO, previously knowing the file name, would be to inspect the script elements on the page, examining its src attribute, some libraries like Scriptaculous.us use this technique, for example: var scripts = document.getElementsByTagName('script'), len = scripts.length, re = /howdy\.js$/, src, howdyScriptSrc;while (len--) { src = scripts[len].src; if (src && src.match(re)) { howdyScriptSrc = src; break; }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3548857', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/235179/']} | jdg_79839 |
stackexchange | llm_judgeable_groundtruth_similarity | 4084431 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to use criteria to make the following query. I have an Entity with EmbeddedId defined: @Entity @Table(name="TB_INTERFASES") public class Interfase implements Serializable { @EmbeddedId private InterfaseId id; } @Embeddable public class InterfaseId implements Serializable { @Column(name="CLASE") private String clase; } And the criteria query that i am trying to do is: CriteriaBuilder criteriaBuilder = this.entityManager.getCriteriaBuilder(); CriteriaQuery<Interfase> criteriaQuery = criteriaBuilder.createQuery(Interfase.class); Root<Interfase> entity = criteriaQuery.from(Interfase.class); criteriaQuery.where( criteriaBuilder.equal(entity.get("clase"), "Clase"), ); But this is throwing an IllegalArgumentException: java.lang.IllegalArgumentException: Not an managed type: class InterfaseId i've tried with this queries too: Root<Interfase> entity = criteriaQuery.from(Interfase.class); criteriaQuery.where( criteriaBuilder.equal(entity.get("id").get("clase"), "Clase"), ); and this one too... Root<Interfase> entity = criteriaQuery.from(Interfase.class); criteriaQuery.where( criteriaBuilder.equal(entity.get("id.clase", "Clase"), ); with no luck.So my question is how can i make a query with criteria when my classes are using Embedded and EmbeddedId annotations? Thanks!.Mauro.
Now provide the response and nothing else.
| You need to use path navigation to access the attribute(s) of the Embeddable . Here is an example from the JPA 2.0 specification (using the static metamodel): 6.5.5 Path Navigation ... In the following example, ContactInfo is an embeddable class consisting of an address and set of phones. Phone is an entity. CriteriaQuery<Vendor> q = cb.createQuery(Vendor.class);Root<Employee> emp = q.from(Employee.class);Join<ContactInfo, Phone> phone = emp.join(Employee_.contactInfo).join(ContactInfo_.phones);q.where(cb.equal(emp.get(Employee_.contactInfo) .get(ContactInfo_.address) .get(Address_.zipcode), "95054")) .select(phone.get(Phone_.vendor)); The following Java Persistence query language query is equivalent: SELECT p.vendorFROM Employee e JOIN e.contactInfo.phones pWHERE e.contactInfo.address.zipcode = '95054' So in your case, I think you'll need something like this: criteriaBuilder.equal(entity.get("id").get("clase"), "Referencia 111") References JPA 2.0 Specification Section 6.5.5 "Path Navigation" Update: I've tested the provided entities with Hibernate EntityManager 3.5.6 and the following query: CriteriaBuilder builder = em.getCriteriaBuilder();CriteriaQuery<Interfase> criteria = builder.createQuery(Interfase.class);Root<Interfase> interfaseRoot = criteria.from(Interfase.class);criteria.select(interfaseRoot);criteria.where(builder.equal(interfaseRoot.get("id").get("clase"), "Referencia 111"));List<Interfase> interfases = em.createQuery(criteria).getResultList(); runs fine and generates the following SQL: 17:20:26.893 [main] DEBUG org.hibernate.SQL - select interfase0_.CLASE as CLASE31_ from TB_INTERFASES interfase0_ where interfase0_.CLASE=?17:20:26.895 [main] TRACE org.hibernate.type.StringType - binding 'Referencia 111' to parameter: 1 Works as expected. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4084431', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/495551/']} | jdg_79840 |
Subsets and Splits