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
35199808
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Given the following piece of code: (map Integer/parseInt ["1" "2" "3" "4"]) Why do I get the following exception unless I wrap Integer/parseInt in an anonymous function and call it manually ( #(Integer/parseInt %) )? clojure.lang.Compiler$CompilerException: java.lang.RuntimeException: Unable to find static field: parseInt in class java.lang.Integer Now provide the response and nothing else.
the documentation on java interop says the following: The preferred idiomatic forms for accessing field or method members are given above. The instance member form works for both fields and methods. The instanceField form is preferred for fields and required if both a field and a 0-argument method of the same name exist. They all expand into calls to the dot operator (described below) at macroexpansion time. The expansions are as follows: ... (Classname/staticMethod args*) ==> (. Classname staticMethod args*) Classname/staticField ==> (. Classname staticField) so you should remember, that Class/fieldName is just a sugar for getting a static field , neither static method call , nor reference to the static method (java method is not a clojure function really), so there is no static field parseInt in Integer class , while (Class/fieldName arg) calls a static method , they are two totally different operations, using the similar sugary syntax. so when you do (map #(Integer/parseInt %) ["1" "2" "3" "4"]) it expands to (map #(. Integer parseInt %) ["1" "2" "3" "4"]) (you can easily see it yourself with macroexpansion), and (map Integer/parseInt ["1" "2" "3"]) expands to (map (. Integer parseInt) ["1" "2" "3"]) It fails when it is trying to get a field (which you think is getting a reference to a method).
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/35199808', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2345852/']}
jdg_373941
stackexchange
llm_judgeable_groundtruth_similarity
8758305
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I created plist with big base of different animals in it (keys) and added this plist in my project.Type of every animal is NSDictionary. In every dictionary there are 5 more keys - characteristics of these animals (). I would like to go through every animal and if I match a certain characteristics of this animal, I put this animal in another array. So, I tried to make a code: NSArray *newArray = [[NSArray alloc]initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"animals" ofType:@"plist"]]; for (int i = 0;[newArray objectAtIndex:i];i++) { if ([[newArray objectAtIndex:i]objectForKey:@"minAge"] == [NSNumber numberWithInt:3]) { [array addObject:[[newArray objectAtIndex:i]objectForKey:@"name"]]; }} So objectAtIndex:i is an animal and minAge is one of it's characteristics. But my code does not work.I do it for the first time, so what I have done wrong ? Thanks! UPDATE:Thank you, your plist works normally ! But I still cant understand why doesn't work mine plist: Anyway, thank you so much ! I didn't eat and sleep while I was solving this problem :)You helped me a lot ! Now provide the response and nothing else.
NSArray The Return value will be nil if the file can’t be opened or if the contents of the file can’t be parsed into an array. I suspect the issue is you need to put the contents in a NSDictionary rather than a NSArray NSDictionary *theDict = [NSDictionary dictionaryWithContentsOfFile:plistFile]; Edit.Further to my answer NSMutableArray *mutableArray =[[NSMutableArray alloc] initWithObjects:nil];NSDictionary *mainDictionary = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"animals" ofType:@"plist"]]; //--get parent dictionary/Array named animals which holds the animals dictionary items NSDictionary *parentDictionary = [mainDictionary objectForKey:@"animals"]; //---enumerate through the dictionary objects inside the parentDictionary NSEnumerator *enumerator = [parentDictionary objectEnumerator]; id value; while ((value = [enumerator nextObject])) { if ([[value valueForKey:@"minAge"] isEqualToNumber:[NSNumber numberWithInt:3]]) { [mutableArray addObject:[value valueForKey:@"name"]]; } } If the animal dictionaries are not inside of a parent dictionary or Array, use something like this NSMutableArray *mutableArray =[[NSMutableArray alloc] initWithObjects:nil]; NSDictionary *mainDictionary = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"animals" ofType:@"plist"]]; //---enumerate through the dictionary objects NSEnumerator *enumerator = [mainDictionary objectEnumerator]; id value; while ((value = [enumerator nextObject])) { if ([[value valueForKey:@"minAge"] isEqualToNumber:[NSNumber numberWithInt:3]]) { [mutableArray addObject:[value valueForKey:@"name"]]; } } Edit. 1. Try it with this plist. Make sure you use a plain text editor to paste it into and save as a plist file Edit.2 .I have now updated my plist to match yours. Although the other one worked. I felt it would make more sense that we are using the same. <?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict> <key>Whale</key> <dict> <key>name</key> <string>Whale</string> <key>isMale</key> <true/> <key>color</key> <string>blue</string> <key>maxAge</key> <integer>8</integer> <key>minAge</key> <integer>3</integer> </dict> <key>Dolphin</key> <dict> <key>maxAge</key> <integer>20</integer> <key>name</key> <string>Dolphin</string> <key>isMale</key> <false/> <key>color</key> <string>blue</string> <key>minAge</key> <integer>15</integer> </dict></dict></plist> Also, here is another example showing how to compare the boolean and number together NSMutableArray *theAnimalMatched =[[NSMutableArray alloc] initWithObjects:nil]; NSDictionary *mainDictionary = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"data1" ofType:@"plist"]]; //---enumerate through the dictionary objects inside the rootDictionary NSEnumerator *enumerator = [mainDictionary objectEnumerator]; id returnValue; while ((returnValue = [enumerator nextObject])) { if ( [[returnValue valueForKey:@"isMale" ] boolValue] && [[returnValue valueForKey:@"minAge"] isEqualToNumber:[NSNumber numberWithInt:3]] && [[returnValue valueForKey:@"color"] isEqualToString:@"blue"] ) { [theAnimalMatched addObject:[returnValue valueForKey:@"name"]]; }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8758305', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1107728/']}
jdg_373942
stackexchange
llm_judgeable_groundtruth_similarity
1337598
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have seen some proofs on the Internet, which make use of the transformation map. However, I couldn't understand the methods since what I learned about the transformation map is so superficial. Can you use a simple way to explain it? And for now, just restrict the similar matrices to square matrices. Now provide the response and nothing else.
Theorem. Similar matrices have the same rank. Proof . Part (1): We will show that $\text{rank}(AB)=\text{rank}(B)$ if $A$ is invertible. Take some $u \in \text{ker}(B)$ . Then, $Bu=0$ , so $(AB)u=A(Bu)=A0 = 0$ . Thus, $u\in \text{ker}(AB)$ , so $\text{ker}(B) \subseteq \text{ker}(AB)$ . Conversely, for some $u \in \text{ker}(AB)$ , $(AB)u=0$ , so $A(Bu)=0$ . Thus $Bu=A^{-1}0=0$ , so $U \in \text{ker}(B)$ . Therefore, $\text{ker}(AB)= \text{ker}(B)$ , implies $\text{null}(AB)=\text{null}(B)$ , implies $\text{rank}(AB)=\text{rank}(B)$ , provided that $A$ is nonsingular. Part (2): Show that: $\text{rank}(AB)=\text{rank}(A)$ , if $B$ is invertible. $$\text{rank}(AB) = \text{rank}((AB)^{t})=\text{rank}(B^{t}A^{t})=\text{rank}(A^{t})=\text{rank}(A),$$ since $B^{t}$ is nonsingular. Thus, similar matrices have the same rank. We have $\text{rank}(XB)=\text{rank}(B)$ and $\text{rank}(AX)=\text{rank}(A)$ and $X^{-1}AX=B$ implies $AX=XB$ . Therefore, $\text{rank}(A)=\text{rank}(B)$ .
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1337598', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/236145/']}
jdg_373943
stackexchange
llm_judgeable_groundtruth_similarity
393607
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: We consider a matrix $$M_{\mu} = \begin{pmatrix} 1 & \mu & 1 & 0 \\ -\mu & 1 & 0 & 1 \\ -1 & 0 & 0 & 0 \\ 0 &-1 & 0 & 0 \end{pmatrix}$$ One easily checks that $\operatorname{det}(M_{\mu})=1$ . I however noticed something peculiar: Consider a sequence of real numbers $\mu_i$ then the four eigenvalues $\lambda_1,..,\lambda_4$ of $$ A=\prod_{i=1}^n M_{\mu_i}$$ have the property that they can be chosen to satisfy $\lambda_1 = \overline{\lambda_2}$ and $\lambda_3 = 1/\lambda_1$ and consequently by the determinant $\lambda_4 = 1/\lambda_2.$ I tried to explicitly study the product and see if I can see some structure explaining all this, but so far only with limited luck. Question: Show that the eigenvalues of $A$ for every $n$ and $\mu_i \in \mathbb R$ satisfy $$\lambda_1 = \overline{\lambda_2 } = 1/\lambda_3 = 1/\overline{\lambda_4}.$$ Update: What we know so far is that $\lambda_1 = \frac{1}{\lambda_3}$ and $\lambda_2 = \frac{1}{\lambda_4}$ and if any of the eigenvalues is non-real then we have it. However, we cannot exclude $\lambda_1>\lambda_2$ both real. Now provide the response and nothing else.
The explanation is pretty simple with a suitable change of basis. Letting $$B = \begin{pmatrix} 1 & 0 & 1 & 0 \\i & 0 & -i & 0 \\0 & 1 & 0 & 1 \\ 0 & i & 0 & -i \end{pmatrix}$$ we have $$B^{-1}M_{\mu}B = \begin{pmatrix} 1+i\mu & 1 & 0 & 0 \\-1 & 0 & 0 & 0 \\0 & 0 & 1-i\mu & 1 \\ 0 & 0 & -1 & 0 \end{pmatrix}$$ Letting $N_\mu = \begin{pmatrix} 1+i\mu & 1 \\-1 & 0 \\\end{pmatrix}$ , we thus have $$B^{-1}AB = \begin{pmatrix} \prod N_{\mu_i} & 0 \\0 & \overline{\prod N_{\mu_i}}\end{pmatrix}$$ where the bar denotes entry-wise complex conjugation. Thus the eigenvalues of $A$ are those of $\prod N_{\mu_i}$ plus those of $\overline{\prod N_{\mu_i}}$ , which are their complex conjugates.Moreover, since $N_\mu$ has determinant $1$ , so does $\prod N_{\mu_i}$ , so its two eigenvalues are inverses of each other.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/393607', 'https://mathoverflow.net', 'https://mathoverflow.net/users/239367/']}
jdg_373944
stackexchange
llm_judgeable_groundtruth_similarity
155829
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 do this problem completely on my own but I can not get a proper answer for some reason $$\begin{align}\int \cos^2 x \tan^3x dx&=\int \cos^2 x \frac{ \sin^3 x}{ \cos^3 x}dx\\&=\int \frac{ \cos^2 x\sin^3 x}{ \cos^3 x}dx\\&=\int \frac{ \sin^3 x}{ \cos x}dx\\&=\int \frac{ \sin^2 x \sin x}{ \cos x}dx\\&=\int \frac{ (1 -\cos^2 x) \sin x}{ \cos x}dx\\&=\int \frac{ (\sin x -\cos^2 x \sin x) }{ \cos x}dx\\&=\int \frac{ \sin x -\cos^2 x \sin x }{ \cos x}dx\\&=\int \frac{ \sin x }{ \cos x}dx - \int \cos x \sin x dx\\&=\int \tan x dx - \frac{1}{2}\int 2 \cos x \sin x dx\\&=\ln|\sec x| - \frac{1}{2}\int \sin 2x dx\\&=\ln|\sec x| + \frac{\cos 2x}{4} + C\end{align}$$ This is the wrong answer, I have went through and back and it all seems correct to me. Now provide the response and nothing else.
A very simple way to check if the answer to an indefinite integral is correct is to differentiate the answer. If you get the original function, your answer is correct, and is equal, up to a constant, with any other solutions. We have$$\begin{align*}\frac{d}{dx}\left(\ln|\sec x| + \frac{\cos 2x}{4} + C\right) &= \frac{1}{\sec x}(\sec x)' + \frac{1}{4}(-\sin(2x))(2x)' + 0\\&= \frac{\sec x\tan x}{\sec x} - \frac{1}{2}\sin(2x)\\&= \tan x - \frac{1}{2}\left(2\sin x\cos x\right)\\&= \frac{\sin x}{\cos x} - \sin x\cos x\\&= \frac{ \sin x - \sin x\cos^2 x}{\cos x}\\&= \frac{\sin x(1 - \cos^2 x)}{\cos x}\\&= \frac{\sin^3 x}{\cos x}\\&= \frac{\sin ^3 x \cos^2 x}{\cos^3x}\\&= \frac{\sin^3 x}{\cos^3 x}\cos^2 x\\&= \tan^3 x \cos^2 x.\end{align*}$$So your answer is right. This happens a lot with integrals of trigonometric identities, because there are a lot of very different-looking expressions that are equal "up to a constant". So the answer to $$\int\sin x\cos x\,dx$$can be either $\sin^2 x + C$ or $-\cos^2x + C$; both correct, though they look different, because they differ by a constant: $-\cos^2x + C = 1-\cos^2x + (C-1) = \sin^2x + (C-1)$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/155829', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_373945
stackexchange
llm_judgeable_groundtruth_similarity
9405124
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 SUM two rows obtained from differente SQL queries in UNION, is this possible?All I can achieve is the two separate rows but I can't SUM them, DB engine keeps me telling that there's an error in the syntax near the *) FROM (the part next to the SUM)... Here's the query: SELECT * FROM(SELECT COUNT(*) as cntclients FROM (SELECT DISTINCT clientkey AS clients FROM <table> WHERE <conditions...>) ) AS clients ) cntclientsUNION(SELECT SUM(occurrences) AS cntclientsad FROM <table2> WHERE <conditions...> ) This throws me for example: cntclients----------90150 Adding a SELECT SUM(*) FROM instead of the SELECT * FROM in the first line, and surrounding the two queries with parentheses just throws me the mentioned error... I would like cntclients <- or whatever name...----------951 Any ideas how this sum should work? Now provide the response and nothing else.
You don't actually need to use a UNION for this - you can just add them together manually: SELECT a.countKey + b.sumOccur as totalFROM (SELECT COUNT(DISINCT clientkey) as countKey FROM <table> WHERE <conditions>) as aCROSS JOIN (SELECT SUM(occurrences) as sumOccur FROM <table2> WHERE <conditions>) as b
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9405124', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/264632/']}
jdg_373946
stackexchange
llm_judgeable_groundtruth_similarity
3524457
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 suffering from the procedure I found, which is contradictory. The original question is: Let $f$ be differentiable. For all $x, y \in \mathbb R$ , $$f(x+y)=f(x-y)+2f(y)+xy$$ Suppose $f'(0)=1$ and find $f(x)$ . My procedure was: Put $x=y=0$ : $$f(0)=f(0)+2f(0)+0$$ $$f(0)=0$$ Put $x=y=\frac{h}{2}$ : $$f(h)=2f\left(\frac{h}{2}\right)+\frac{h^2}{4}$$ Substituting $x=x+\frac{h}{2}, y=\frac{h}{2}$ brings: $$f'(x)=\lim_{h\to0} \frac{f(x+h)-f(x)}{h}=\lim_{h \to 0}\frac{2f\left(\frac{h}{2}\right)+\frac{h}{2}\left(x+\frac{h}{2}\right)}{h}=\lim_{h\to0}\frac{f(h)+\frac{h}{2}x}{h}\\=\lim_{h\to0}\frac{f(h)-f(0)}{h-0}+\frac{x}{2}=\frac{x}{2}+1$$ $$f(x)=\frac{x^2}{4}+x+c$$ where $c$ is constant. Since $f(0)=0,\space\space c=0$ However, when we substitute $x=0$ to the given condition, $$f(y)=f(-y)+2f(y)+0(y)$$ $$-f(y)=f(-y)$$ which informs that $f$ is odd: contradiction! Could you please help me to find the error? Thanks. Now provide the response and nothing else.
I think you made no mistake. It's just that the conditions are incoherent, they offer no solution (even without the condition $f'(0)=1$ ). There is no differentiable $f$ that satisfies $$\tag1f(x+y)=f(x-y)+2f(y)+xy. $$ If we take $(1)$ and differentiate with respect to $x$ , we get $$\tag2f'(x+y)=f'(x-y)+y.$$ If instead we differentiate $(1)$ with respect to $y$ , we get $$\tag3f'(x+y)=-f'(x-y)+2f'(y)+x.$$ If we add $(2)$ and $(3)$ we get $$2f'(x+y)=2f'(y)+x+y. $$ When $x=0$ , we get $$2f'(y)=2f'(y)+y,$$ so $(1)$ can only hold for a differentiable function if $y=0$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3524457', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/745329/']}
jdg_373947
stackexchange
llm_judgeable_groundtruth_similarity
34253
Below is a question asked on the forum astronomy.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have been reading about the deviation of galactic rotation curves from the predicted Keplerian curve to a flat curve at large galactocentric distances. They were the first indicators of the existence of dark matter but I do not understand how the curve is obtained from Doppler shift data (as mentioned by some papers as the method of determination for the curve.) Doppler shift data would allow measurement of radial velocity but how can that alone be enough to extrapolate the rotation curve? Now provide the response and nothing else.
Imagine a spiral galaxy where the rotation of gas and stars within the disk is close to circular (generally true for gas clouds, though less true for stars) in a single plane (the disk), and imagine that it is tilted at some intermediate angle with respect to your line of sight. A circular disk galaxy will then project to form an apparent ellipse, with a major axis and a minor axis (see figure). If you look at points which lie along the minor axis (say, points b1 or b2), you will see stars and clouds which are moving perpendicular to your line of sight, so they have zero radial velocity relative to you, and there will be no Doppler shift. If, instead, you look at points which lie along the major axis (say, points a1 or a2), your line of sight will intersect gas clouds and stars which are moving (mostly) along your line of sight (either towards you or away from you), so you will observe the maximum possible radial velocity and thus the maximum possible Doppler shift (either positive = velocities away from you, or negative = velocities toward you). There's one further factor, which is the effect of inclination. If the galaxy is genuinely face-on (inclination $i = 0$ ), then you won't seem any Doppler shifts, because all the motion is in the plane of the sky, perpendicular to your line of sight. (In practice there will really be some motions up and down with respect to the galaxy plane, but this won't tell you about the rotation curve.) If the galaxy is edge-on , then you get the maximum possible Doppler shift, which gives you the rotation velocity $V$ directly. If the galaxy has an in-between inclination, then the radial velocity is the part of the cloud/star velocity in the direction of your line of sight, which is $V \sin i$ . So if you can determine the galaxy's inclination, you can divide the observed velocity along the major axis by $\sin i$ to get $V$ . Up until relatively recently, the practice (in optical astronomy) was to use a long-slit spectrograph and orient it so that the slit lies along the galaxy's major axis. Then at each point along the major axis, from the center outward, you measure the Doppler shift, apply the $\sin i$ inclination correction, and then you have the rotation curve: $V$ as a function of radius $r$ along the major axis. If you have fully two-dimensional spectroscopy (e.g., from a radio telescope interferometric array observing emission from atomic hydrogen or molecular gas, or an optical or infrared integral field spectrograph), then you can use the data at intermediate locations within the disk (not just along the major axis), where the observed velocity is $= V \sin i \cos \alpha$ , where $\alpha$ is the angle between the major axis and the location you're looking at (so for locations on the major axis, the observed velocity is just $V \sin i$ ). Then you can fit a model to the set of observed velocities (which you get from the Doppler shifts) and work out $V$ as a function of radius. (The standard approach is called a "tilted ring" model, where you assume the velocity is a simple function of radius, but allow for the possibility that the disk might be warped, so that the orientation -- including the inclination -- might change with radius.)
{}
{'log_upvote_score': 4, 'links': ['https://astronomy.stackexchange.com/questions/34253', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/31162/']}
jdg_373948
stackexchange
llm_judgeable_groundtruth_similarity
233220
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 paired off the zero divisors in these two rings, and there are exactly 4 pairs of distinct zero divisors in both rings: In $\Bbb Z_3[x]/\langle x^2 - 1\rangle$ the zero divisor pairs are $$x+1, x+2 \qquad x+1, 2x+1, \qquad 2x+1, 2x+2 \qquad x+2, 2x+2$$ Similarly, in $\Bbb Z_3 \times \Bbb Z_3$ the zero divisor pairs are $$(0, 1), (1, 0) \qquad (0,1), (2,0) \qquad (0, 2), (1, 0) \qquad (0, 2), (2, 0) $$ The fact that the zero divisors match up indicates to me that these rings should indeed be isomorphic, as zero divisors are one of the structures which have failed checks in the past on rings such as $\Bbb Z_2 [x] / \langle x^2 \rangle \ncong \Bbb Z_2 \times \Bbb Z_2$. My Question Is the only homomorphism (and thus isomorphism) between these two rings an enumerative one, where I explicitly map each of the nine elements of $\Bbb Z_3[x]/ \langle x^2 - 1\rangle$ to an element in $\Bbb Z_3 \times \Bbb Z_3$? I can do that if necessary, but it seems an inelegant and brute force method. However, since these rings are so small, it may be the best way to go about it. Thanks! Now provide the response and nothing else.
$Z_3[x]/(x^2-1)\cong Z_3[x]/(x-1)\times Z_3[x]/(x+1)\cong Z_3\times Z_3$.The map is induced by $ax+b\rightarrow (a+b, -a+b)$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/233220', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/34736/']}
jdg_373949
stackexchange
llm_judgeable_groundtruth_similarity
4721770
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Hi normally in Log4j priority levels are as follows DEBUG < INFO < WARN < ERROR < FATAL Can we change this priority levels.My requirement is I need to log only details which have priority level INFO and FATAL. Logs with priority level DEBUG, WARN and ERROR shouldn't log. If I can change the priority levels as DEBUG < WARN < ERROR < INFO < FATAL it is possible. Or is there any other way to do that. Pls help.. Now provide the response and nothing else.
I was never needed to do this, but since I have once read Log4J - The Complete Manual , I hope these pointers will help. Write your own custom filter by extending org.apache.log4j.spi.Filter Override decide method Use loggingEvent.getLevel() , to identify the level of log that was triggered. Write following logic in decide if(event.getLevel() == Level.INFO || event.getLevel() == Level.FATAL) return ACCEPT;return DENY; This filter will accept all the logs that are either INFO or FATAL. You may get more creative. Please note that I have not tested this code. This is just a guideline, hope this helps Edit : on a bit search, I found something that might be easier. I guess, You can use LevelMatchFilter , this way <filter class="org.apache.log4j.varia.LevelMatchFilter"> <param name="LevelToMatch" value="info" /> <param name="AcceptOnMatch" value="true" /> </filter> <filter class="org.apache.log4j.varia.LevelMatchFilter"> <param name="LevelToMatch" value="fatal" /> <param name="AcceptOnMatch" value="true" /> </filter> <filter class="org.apache.log4j.varia.DenyAllFilter"/> refer: http://wiki.apache.org/logging-log4j/Log4jXmlFormat for XML configurarion. There is a section on Filter Configuration I don't know what stops OP in accepting this answer. I've just tested, it works: Here is the XML. <?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"><log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> <appender name="util" class="org.apache.log4j.FileAppender"> <param name="File" value="D:/util.log" /> <param name="Append" value="true" /> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%t %-5p %c{2} - %m%n"/> </layout> <filter class="org.apache.log4j.varia.LevelMatchFilter"> <param name="LevelToMatch" value="info" /> <param name="AcceptOnMatch" value="true" /> </filter> <filter class="org.apache.log4j.varia.LevelMatchFilter"> <param name="LevelToMatch" value="fatal" /> <param name="AcceptOnMatch" value="true" /> </filter> <filter class="org.apache.log4j.varia.DenyAllFilter"/> </appender> <root> <priority value ="debug" /> <appender-ref ref="util" /> </root></log4j:configuration> Here is the Java code DOMConfigurator.configure("log4j.xml"); Logger log = Logger.getLogger(Test.class); log.debug("DEBUG"); log.info("INFO"); log.warn("WARN"); log.error("ERROR"); log.fatal("FATAL"); Here is the output in (as configured) D:/util.log main INFO test.Test - INFOmain FATAL test.Test - FATAL
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4721770', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/458680/']}
jdg_373950
stackexchange
llm_judgeable_groundtruth_similarity
590262
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: So we're looking at migrating our single dedicated server (set up like shared web hosting) to an architecture with multiple load-balanced front-end servers plus separate database servers (due to traffic growth and availability concerns). TLDR; I want some way of failing over to a local read-only mirror of the site files when the file server goes down. The scenario: About 200 vhosts with a few aliases each Each site is basically only a "wrapper" with ~30 local files, mostly just template files, the rest is just included from a centralised code base Sites are basically read only, except for maybe a cache directory (which can be separate on each host) No 3rd party access to site files (ie. not shared) Each site only gets a 2-10k hits/month Goals / requirements: Be resilient to any single server being taken offline for maintenance or due to an error Some centralised way to make low volumes of file updates regularly (manually, just normal site updates), preferably via FTP It would be acceptable for changes to be propagated to front-end servers in up to 5 seconds If a server went offline unexpectedly I'd be happy for up to 10 minutes of file changes to be lost At this stage we'd probably only be looking at 2 front end servers running full time, plus a file server Will probably be implemented on AWS More front end servers may be added and removed periodically I realise a typical approach would be to deploy via version control, which is what we already do in some instances but our staff (non-developers, who mainly manage banners, text updates, etc.) are pretty used to an "FTP" workflow, which I'd like to reform but perhaps not yet. Here are the solutions I've come up with: rsync deployment File server hosts the "master" copy of the site files which can be accessed via FTP and exposes these via an rsync server. I have some kind of "deployment" interface which triggers each front end server to rsync a site and "deploy it". Pros Pretty simple Allows for a "staging" version on the file server which might be useful Each front end server has their own copy of the files, no problem if the file server is offline Cons How reliable? Potential for confusion over what's been deployed and what hasn't NFS NFS file server with local cache, periodically rsync a local backup and then possibly fail over by switching the mount point of a bind to the local backup. Pros Possibly supports writing (not that necessary) NFS is in some ways simpler Unless there's an outage they should always all be in sync Cons I'm not sure how well local NFS caching works and whether it'll invalidate caches of modified objects automatically. Without local cache NFS is pretty slow? I'm pretty sure I'd need some kind of heart-beat to trigger the fail over and also to mount the master when it comes back online Gluster, etc. I'm not super familiar with this option, but I believe this is a common approach when you have a large number of servers. I looked at some of the documentation and it might be suitable, but I don't see many people recommending it on such a small scale. Pros Would allow read and writing Supports caching I think, should be faster than non-cached NFS? Automatic replication, recovery and fail over Cons I like the idea of having a single "master" volume which I can snapshot and backup, I don't think there's an option to say "this node must have a complete copy" in gluster? With such a small pool of servers it seems like you could easily accidentally terminate two servers which happen to have the only copy of some data So, my questions: Is NFS really the only option for me? Are there other options I should be considering? Are any of these options the best fit for my needs? Edit: Thanks for your responses guys, I am starting to realise that I'm making things far too complicated considering the (relatively small) scale of my needs. I think the correct solution in my instance is that I need to introduce an explicit "deploy" event which triggers the local files to be updated, ether from version control or some other source. Although files are updated regularly, when spread out across ~200 sites the reality is that it's unlikely most sites will be updated more than once a month, so having a mechanism to sync any arbitrary change instantly on any file at any time seems unnecessary. Now provide the response and nothing else.
The file count and SSH encryption overhead are likely the biggest barriers. You're not going to see wire-speed on a transfer like this. Options to improve include: Using rsync+SSH with a less costly encryption algorithm (e.g. -e "ssh -c arcfour" ) Eliminating encryption entirely over the SSH transport with something like HPN-SSH . Block-based transfers. Snapshots, dd , ZFS snapshot send/receive , etc. If this is a one-time or infrequent transfer, using tar , netcat ( nc ), mbuffer or some combination. Check your CentOS tuned-adm settings . Removing the atime from your filesystem mounts. Examining other filesystem mount options. NIC send/receive buffers. Tuning your rsync command. Would -W , the whole-files option make sense here? Is compression enabled? Optimize your storage subsystem for the type of transfers (SSDs, spindle-count, RAID controller cache.)
{}
{'log_upvote_score': 6, 'links': ['https://serverfault.com/questions/590262', 'https://serverfault.com', 'https://serverfault.com/users/217100/']}
jdg_373951
stackexchange
llm_judgeable_groundtruth_similarity
129799
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I want to do a cross or dot product involving a vector of Pauli matrices $ \vec\sigma=(\sigma^1, \sigma^2, \sigma^3) $ ; for example, $ \vec\sigma\times\vec\sigma=2\mathrm i\vec\sigma $ and $ \vec\sigma\cdot\vec\sigma=3 I_{2\times2} $ . Is there a simple way to do these operations? Now provide the response and nothing else.
The Pauli vector: σ = Table[PauliMatrix[i], {i, 1, 3}]MatrixForm /@ σ One can define a dot product of matrices (in spaces of arbitrary dimension): dot[a_, b_] := Total @ MapThread[Dot, {a, b}] Then dot[σ, σ] // MatrixForm For the cross product of matrices , I literally took the cross product of vectors Cross[{a, b, c}, {x, y, z}] /. {Times[A_Symbol, B_Symbol] -> Dot[A, B]} {b.z - c.y, -a.z + c.x, a.y - b.x} and redefined it as (in a 3D space) cross[{a_, b_, c_}, {x_, y_, z_}] := {b.z - c.y, -a.z + c.x, a.y - b.x} This gives MatrixForm /@ cross[σ, σ] i.e. cross[σ, σ] == 2 I σ True Because I particularly like the multidimensional cross product of vectors, I'd like to post a few links: Multi-dimensional vector product - an arXiv paper showing it can exist only in 3- and 7-dimensional spaces, Cross Products of Vectors in Higher Dimensional Euclidean Spaces - jstor, Seven-dimensional cross product on Wikipedia, Mathematica implementation of a 7D cross product , Is the vector cross product only defined for 3D? - a Mathematics.SE thread, Cross product in $\mathbb{R}^n$ - another Mathematics.SE thread.
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/129799', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/44122/']}
jdg_373952
stackexchange
llm_judgeable_groundtruth_similarity
2819915
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 writing a page which uses a lot of in situ editing and updating using jQuery for AJAX. I have come accross a problem which can best be summarized by the workflow described below: Clicking on 'element1' on the page results in a jQuery AJAX POST Data is received in json format The data received in json format The received data is used to update an existing element 'results' in the page The received data is actual an HTML form I want jQuery to be responsible for POSTing the form when the form button is clicked The problem arises at point 6 above. I have code in my main page which looks like this: $(document).ready(function(){ $('img#inserted_form_btn').click(function(){ $.ajax({'type': 'POST', 'url': 'www.example.com', 'success': function($data){ $(data.id).html($data.frm); }), 'dataType': 'json'} });}); However, the event is not being triggered. I think this is because when the document is first loaded, the img#inserted_form_btn element does not exist on the page (it is inserted into the DOM as the result of an element being clicked on the page (not shown in the code above - to keep the question short) My question therefore is: how can I get jQuery to be able to respond to events occuring in elements that were added to the DOM AFTER the page has loaded? Now provide the response and nothing else.
Use a live handler. deprecated since some time, check the second part of my answer for better solutions! $('img#inserted_form_btn').live('click', function() { // Your click() code}); Assuming the image is a child of some element that already exists when binding the event, you can use a delegate instead: $('#parent-element').on('click', '#inserted_form_btn', function() { // Your click() code}); If you do not have jQuery 1.7+: $('#parent-element').delegate('#inserted_form_btn', 'click', function() { // Your click() code}); In any case, you can use a delegate and use $(document) instead of $('#parent-element') if there is no suitable parent element.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2819915', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/312675/']}
jdg_373953
stackexchange
llm_judgeable_groundtruth_similarity
523207
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: WhenI try to research overfitting and underfitting, the most common algorithm and explanation I see revolves around polynomial regression. Why is this so? Is it just because it can be easily visualised like the graphs here: https://scikit-learn.org/stable/auto_examples/model_selection/plot_underfitting_overfitting.html Why is polynomial regression deemed suitable to give an insight into these overfitting/underfitting concepts? Are there any other similar algorithms that could be used? Now provide the response and nothing else.
Easy visualization is a huge point in favor of using polynomial regression for illustration. (Note that both "illustration" and "demonstration", etymologically, have to do with showing pictures !) It also helps that the degree of the polynomial controls the amount of overfitting, and that polynomial regression allows looking at bona fide nonlinearity in the relationship (although splines are a better way of dealing with this). An alternative that is also commonly employed is to simply add spurious predictors. Your true data generating process might be $y=b_1x_1+b_2x_2+\epsilon$ , so a model $y=\beta_1x_1$ is underfitted, $y=\beta_1x_1+\beta_2x_2$ is fitted correctly, and $y=\beta_1x_1+\beta_2x_2+\beta_3x_3$ is overfitted - but it's hard to visualize the increased variability of fits from the overfitted model.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/523207', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/317636/']}
jdg_373954
stackexchange
llm_judgeable_groundtruth_similarity
1226789
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to get a substring in SQL Server from last sequence of a split on dot ( . ). I have a column which contains file names such as hello.exe , and I want to find the extension of the file exactly as Path.GetExtension("filename") does in C#. Now provide the response and nothing else.
You can use reverse along with substring and charindex to get what you're looking for: select reverse(substring(reverse(filename), 1, charindex('.', reverse(filename))-1)) as FileExtfrom mytable This holds up, even if you have multiple . in your file (e.g.- hello.world.exe will return exe ). So I was playing around a bit with this, and this is another way (only one call to reverse ): select SUBSTRING(filename, LEN(filename)-(CHARINDEX('.', reverse(filename))-2), 8000) as FileExtfrom mytable This calculates 10,000,000 rows in 25 seconds versus 29 seconds for the former method.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1226789', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/130289/']}
jdg_373955
stackexchange
llm_judgeable_groundtruth_similarity
128144
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 major problem with verifying a Trigonometric identity. (My teacher couldn't really get it, so I would like to find it just in case it appears on a test) The problem goes like this: $$\sin(\theta) + \cos(\theta) = \frac{\sin(\theta)}{1 - \cot(\theta)} + \frac{\cos(\theta)}{1 - \tan(\theta)}$$ Where I must verify that this is true. I have tried numerous operations, mostly getting to $\sin + \cos$ along with a crazy fraction in the numerator and another fraction in the numerator. As I have said, my teacher showed my something, but it really did not work after I continued simplifying. If there is anyone who would help guide me in this, it would be much appreciated. Now provide the response and nothing else.
$$\eqalign{{\sin\theta\over 1-\cot\theta} +{\cos\theta\over 1-\tan\theta}&={\sin\theta\over 1-{\cos\theta\over \sin\theta}} +{\cos\theta\over 1-{\sin\theta\over \cos\theta}}\cr&={\sin^2\theta\over \sin\theta-{\cos\theta }} +{\cos^2\theta\over\cos\theta-{\sin\theta }}\phantom{{a\over b}\over{c\over d}}\cr&={\sin^2\theta-\cos^2\theta\over \sin\theta-{\cos\theta }}\phantom{{a\over b}\over{c\over d}} \cr &={(\sin\theta +\cos)(\sin\theta -\cos\theta)\over \sin\theta-{\cos\theta }}\phantom{{a\over b}\over{c\over d}}\cr&=\sin\theta+\cos\theta .} $$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/128144', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/17716/']}
jdg_373956
stackexchange
llm_judgeable_groundtruth_similarity
41200
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I was going through the properties of titanium when a certain thing caught my eye: It was the reaction of burning of titanium in nitrogen. I was astonished to read it as I knew that neither is nitrogen a supporter of combustion nor does it burn itself. But then how can titanium burn in nitrogen? Moreover it is one of the few elements to do so. It was written that titanium burns in pure nitrogen. Now provide the response and nothing else.
There are two questions one has to answer when asking ‘will $\ce{X}$ react with $\ce{Y}$?’ Thermodynamics This basically asks ‘will the products of a hypothetical reaction be more stable than the reactants?’, i.e. whether the entire process will release energy. A quick web search tells me that $\Delta_\mathrm{f} H^0 (\ce{TiN}) = - 337.65~\mathrm{\frac{kJ}{mol}}$ and therefore the reaction is thermodynamically possible. Kinetics This is asking ‘can I overcome the activation energy required for said hypothetical reaction to occur?’ And this is where it gets complicated. The process of titanium burning can be split into the following sub-equations: $$\ce{2 Ti + N2 -> 2 TiN} \\ ~\\\ce{Ti(s) -> Ti(g)}\\\ce{Ti(g) -> Ti^3+ (g) + 3 e-}\\\ce{N2(g) -> 2 N(g)}\\\ce{N(g) + 3 e- -> N^3- (g)}\\\ce{Ti^3+ (g) + N^3- (g) -> TiN(g)}\\\ce{TiN(g) -> TiN(s)}$$ Broken down in this way, we should immediately realise: The first step is generally okay-ish but may require some activation. (We don’t need to make the entire material gaseous in one step; an atom a time is enough.) The second step requires energy (no surprises there). The third step is extremely hard to do, since the $\ce{N#N}$ is so strong. The fourth step also requires energy since nitrogen has an endothermic electron affinity. The fifth and sixth steps are the ones where huge amounts of energy are liberated; especially the sixth one where lattice enthalpy is liberated. Now if we consider a block of titanium, as DavePhD mentioned, the the first step is already rather hard to do. The block’s crystal lattice is rather stable as is so we cannot easily extract atoms from there. However, the larger the surface to volume ratio gets the easier this can happen, especially since we have multiple ‘attacking’ points at the same time. Thus, solid metal blocks are usually hard to burn, while metal powder often burns just by putting it in pure oxygen. (Iron wool doesn’t even need to be a powder, the surface to volume ratio is small enough already to oxidise in pure oxygen at room temperature.) As Jon Custer mentioned in a comment and as I mentioned earlier, the cleavage of dinitrogen molecules is also extremely difficult. It will take a lot of activation energy to do so. This means, that a lot of energy must be gained in the formation of the ion lattice so that at least the dinitrogen cleavage can be overcome and combustion can continue. Thus, the kinetics part of the question can be answered with: ‘it can, but.’ The question remains how to supply activation energy. Since we are most likely dealing with powder, it could be too slow to ignite titanium in air and then immediately immerse in nitrogen. Since nitrogen cleaving is so hard, many other ignition ideas that rely on, say, a match’s flame won’t work (the match is too weak). Maybe the activation energy is ‘low’ enough that heating to a few hundred degres will suffice. Unfortunately, I do not know the experimental details.
{}
{'log_upvote_score': 5, 'links': ['https://chemistry.stackexchange.com/questions/41200', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/21645/']}
jdg_373957
stackexchange
llm_judgeable_groundtruth_similarity
5444394
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This is what I've got so far but it is not working: class Node: rChild,lChild,data = None,None,None def __init__(self,key): self.rChild = None self.lChild = None self.data = keyclass Tree: root,size = None,0 def __init__(self): self.root = None self.size = 0 def insert(self,node,someNumber): if node is None: node = Node(someNumber) else: if node.data > someNumber: self.insert(node.rchild,someNumber) else: self.insert(node.rchild, someNumber) returndef main(): t = Tree() t.root = Node(4) t.root.rchild = Node(5) print t.root.data #this works print t.root.rchild.data #this works too t = Tree() t.insert(t.root,4) t.insert(t.root,5) print t.root.data #this fails print t.root.rchild.data #this fails tooif __name__ == '__main__': main() Now provide the response and nothing else.
Here is a quick example of a binary insert: class Node: def __init__(self, val): self.l_child = None self.r_child = None self.data = valdef binary_insert(root, node): if root is None: root = node else: if root.data > node.data: if root.l_child is None: root.l_child = node else: binary_insert(root.l_child, node) else: if root.r_child is None: root.r_child = node else: binary_insert(root.r_child, node)def in_order_print(root): if not root: return in_order_print(root.l_child) print root.data in_order_print(root.r_child)def pre_order_print(root): if not root: return print root.data pre_order_print(root.l_child) pre_order_print(root.r_child) r = Node(3)binary_insert(r, Node(7))binary_insert(r, Node(1))binary_insert(r, Node(5)) 3 / \ 1 7 / 5 print "in order:"in_order_print(r)print "pre order"pre_order_print(r)in order:1357pre order3175
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/5444394', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/423000/']}
jdg_373958
stackexchange
llm_judgeable_groundtruth_similarity
34517520
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 give notification to my app on a specific time. Say everyday i have to give notification on 7 AM even if the app is closed. How can i do this? Any tutorial?Please mention the link. Now provide the response and nothing else.
first you need to use a broadcastreceiver. and because a broadcast receiver up only for a short time from the android developer blog.When handling a broadcast, the application is given a fixed set of time (currently 10 seconds) in which to do its work. If it doesn't complete in that time, the application is considered to be misbehaving, and its process immediately tossed into the background state to be killed for memory if needed. its a better practice to use also intent service here you have a example how to do it. this is the broadcast receiver class. public class MyReceiver extends BroadcastReceiver { public MyReceiver() { } @Override public void onReceive(Context context, Intent intent) { Intent intent1 = new Intent(context, MyNewIntentService.class); context.startService(intent1); }} and register it in the manifest. <receiver android:name=".MyReceiver" android:enabled="true" android:exported="false" ></receiver> this is the intent service class. public class MyNewIntentService extends IntentService { private static final int NOTIFICATION_ID = 3; public MyNewIntentService() { super("MyNewIntentService"); } @Override protected void onHandleIntent(Intent intent) { Notification.Builder builder = new Notification.Builder(this); builder.setContentTitle("My Title"); builder.setContentText("This is the Body"); builder.setSmallIcon(R.drawable.whatever); Intent notifyIntent = new Intent(this, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 2, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT); //to be able to launch your activity from the notification builder.setContentIntent(pendingIntent); Notification notificationCompat = builder.build(); NotificationManagerCompat managerCompat = NotificationManagerCompat.from(this); managerCompat.notify(NOTIFICATION_ID, notificationCompat); }} and register it in the manifest. <service android:name=".MyNewIntentService" android:exported="false" ></service> and then in your activity set the alarm manger to start the broadcast receiver at a specific time and use AlarmManager setRepeating method to repeat it this example bellow will repeat it every day. Intent notifyIntent = new Intent(this,MyReceiver.class);PendingIntent pendingIntent = PendingIntent.getBroadcast (context, NOTIFICATION_REMINDER_NIGHT, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 60 * 24, pendingIntent); i hope this will help you.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/34517520', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5350310/']}
jdg_373959
stackexchange
llm_judgeable_groundtruth_similarity
21459785
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Not sure if anyone else posted this question, didn't find any, though there are similar ones. This is my manifest xml: <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.listCalc.tutorial.simpleinappbillingv3.ui.StartUpActivity" android:label="@string/activity_startup_label" android:screenOrientation="portrait" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.listCalc.tutorial.simpleinappbillingv3.ui.MainActivity" android:label="@string/activity_main_label" android:screenOrientation="portrait" /> <activity android:name="com.listCalc.tutorial.simpleinappbillingv3.ui.PurchasePassportActivity" android:label="@string/activity_purchase_label" android:screenOrientation="portrait" /> </application> String.xml: <?xml version="1.0" encoding="utf-8"?><resources> <string name="app_name">List Calc in-app billing V3</string> <string name="hello_world">Hello world!</string> <string name="menu_settings">Settings</string> <string name="main_button_purchase_passport_text">Purchase Passport</string> <string name="main_cont_desc_image_passport">purchased passport</string> <string name="activity_startup_label">Loading</string> <string name="activity_main_label">Main Menu</string> <string name="activity_purchase_label">Making Purchase</string></resources> The application name i.e. the launcher icon name is being picked up as "activity_startup_label" and not "app_name" What am I doing wrong? Now provide the response and nothing else.
What am I doing wrong? Nothing. This is working as designed. You are welcome to also have an android:label attribute on the <intent-filter> , which should be used for the launcher icon label, according to the documentation : The icon and label set for an intent filter are used to represent a component whenever the component is presented to the user as fulfilling the function advertised by the filter. For example, a filter with "android.intent.action.MAIN" and "android.intent.category.LAUNCHER" settings advertises an activity as one that initiates an application — that is, as one that should be displayed in the application launcher. The icon and label set in the filter are therefore the ones displayed in the launcher.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21459785', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2235839/']}
jdg_373960
stackexchange
llm_judgeable_groundtruth_similarity
25991789
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to create a war file without embedded tomcat with maven.Here the relevant part of my pom ...<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.1.6.RELEASE</version></parent><dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <!-- Add tomcat only if I want to run directly --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency></dependencies><build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins></build>... How ever if I run mvn package I get a war, where the tomcat*.jar are in a provided-lib folder but still in the lib-folder. I read build-tool-plugins-maven-packaging , but can't find what's wrong. I know a main idea is to run it as an application, how ever our customer want's to deploy it on his application-server. Now provide the response and nothing else.
Following the Hint from M. Deinum I excluded the tomcat-depedency. With the following pom.xml (relevant snippet) a maven clean package has the result I want to get. ...<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.1.6.RELEASE</version></parent><dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <!-- Add tomcat only if I want to run directly --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency></dependencies><build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins></build>... Warning for idea-user : You must activate "Include dependencies with the provided scope" in the run-configuration (see Unable to start spring-boot application in IntelliJ Idea for more information)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/25991789', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/432115/']}
jdg_373961
stackexchange
llm_judgeable_groundtruth_similarity
317393
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 experiencing 502 Gateway errors when accessing a PHP file in a directory ( http://example.com/dev/index.php ). The logs simply says this: 2011/09/30 23:47:54 [error] 31160#0: *35 connect() failed (111: Connection refused) while connecting to upstream, client: xx.xx.xx.xx, server: domain.com, request: "GET /dev/ HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000", host: "domain.com" I've never experienced this before. What is the solution for this type of 502 Gateway error? This is the nginx.conf : user www-data;worker_processes 4;pid /var/run/nginx.pid;events { worker_connections 768; # multi_accept on;}http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; gzip_disable "msie6"; # gzip_vary on; # gzip_proxied any; # gzip_comp_level 6; # gzip_buffers 16 8k; # gzip_http_version 1.1; # gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript; ## # Virtual Host Configs ## include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*;} Now provide the response and nothing else.
It sounds like you haven't started and configured the backend for Nginx. Start php-fpm and add the following to nginx.conf , in the http context: server { listen 127.0.0.1; server_name localhost; error_log /var/log/nginx/localhost.error_log info; root /var/www/localhost/htdocs; location ~ \.php$ { fastcgi_pass 127.0.0.1:9000; include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; fastcgi_intercept_errors on; error_page 404 /error/404.php; }}
{}
{'log_upvote_score': 7, 'links': ['https://serverfault.com/questions/317393', 'https://serverfault.com', 'https://serverfault.com/users/54403/']}
jdg_373962
stackexchange
llm_judgeable_groundtruth_similarity
47541032
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am new to React JS and Redux and it has been too overwhelming to get going. I am trying to make a POST request using Axios, but I am unable to make it. May be I am missing something in the container file. Below is the code. Check plnkr Update: I am getting @@redux-form/SET_SUBMIT_SUCCEEDED message after submitting. But when I am checking in the network tab, I don't see the call to API. And also when I am consoling the submitted values, I see only name and fullname values. It doesn't consist of logo and details. What am I missing? Component file import React, { PureComponent } from 'react' import PropTypes from 'prop-types' import { Field,reduxForm } from 'redux-form' import { Columns,Column, TextArea, Label,Button } from 'bloomer' import FormField from 'FormField' const validate = (values) => { const errors = {} const requiredFields = ['organizationName','organizationFullName','organizationDetails'] requiredFields.forEach((field) => { if (!values[field]) { errors[field] = 'This field can\'t be empty!' } }) return errors} const formConfig = { validate, form: 'createOrganization', enableReinitialize: true } export class CreateOrganization extends PureComponent { static propTypes = { isLoading:PropTypes.bool.isRequired, handleSubmit: PropTypes.func.isRequired, // from react-redux submitting: PropTypes.bool.isRequired // from react-redux } onSubmit = data => { console.log(data) } render () { const { handleSubmit,submitting,isLoading } = this.props return ( <Columns isCentered> <form onSubmit={handleSubmit(this.onSubmit.bind(this))} > <Column isSize='3/6' > <Label>Organization Name</Label> <Field name="organizationName" component={FormField} type="text" placeholder="Organization Name" /> </Column> <Column isSize='3/6'> <Label>Organization Full Name</Label> <Field name="organizationFullName" component={FormField} type="text" placeholder="Organization Full Name" /> </Column> <Column isSize='3/6'> <Label>Organization Logo</Label> <Input name="organizationLogo" type="file" placeholder="Logo" /> </Column> <Column isSize='3/6'> <Label>Organization Details</Label> <TextArea placeholder={'Enter Details'} /> </Column> <Column > <span className="create-button"> <Button type="submit" isLoading={submitting || isLoading} isColor='primary'> Submit </Button> </span> <Button type="button" isColor='danger'> Cancel </Button> </Column> </form> </Columns> ) }} export default reduxForm(formConfig)(CreateOrganization) Container File import React, { PureComponent } from 'react' import PropTypes from 'prop-types' import { connect } from 'react-redux' import Loader from 'Loader' import organization from 'state/organization' import CreateOrganization from '../components/createOrganization' export class Create extends PureComponent { static propTypes = { error: PropTypes.object, isLoaded: PropTypes.bool.isRequired, create: PropTypes.func.isRequired, } onSubmit = data => { this.props.create(data) } render () { const { isLoaded, error } = this.props return ( <CreateOrganization onSubmitForm={this.onSubmit} isLoading= {isLoading} /> ) } } const mapStateToProps = state => ({ error: organization.selectors.getError(state), isLoading: organization.selectors.isLoading(state) }) const mapDispatchToProps = { create: organization.actions.create } export default connect(mapStateToProps, mapDispatchToProps)(Create) Now provide the response and nothing else.
Your redux action creators must be plain, object and should dispatch and action with a mandatory key type . However using custom middlewares like redux-thunk you could call axios request within your action creators as without custom middlewares your action creators need to return plain object Your action creator will look like export function create (values) { return (dispatch) => { dispatch({type: CREATE_ORGANIZATION}); axios.post('/url', values) .then((res) =>{ dispatch({type: CREATE_ORGANIZATION_SUCCESS, payload: res}); }) .catch((error)=> { dispatch({type: CREATE_ORGANIZATION_FAILURE, payload: error}); }) }} and your reducer will look like export default (state = initialState, action) => { const payload = action.payload switch (action.type) { case CREATE: return { ...state, loading: true, loaded: false } case CREATE_SUCCESS: return { ...state, data: state.data.concat(payload.data), loading: false, loaded: true, error: null } } case CREATE_FAILURE: return { ...state, loading: false, loaded: true, error: payload } default: return state }} now while creating the store you can do it like import thunk from 'redux-thunk';import { createStore, applyMiddleware } from 'redux';const store = createStore( reducer, applyMiddleware(thunk)); Apart from this you also need to setUp the redux form you need to use combineReducers and Provider to pass on the store import reducer from './reducer';import { combineReducers } from 'redux';import { reducer as formReducer } from 'redux-form'export const rootReducer = combineReducers({ reducer, form: formReducer}) CodeSandbox
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47541032', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5733368/']}
jdg_373963
stackexchange
llm_judgeable_groundtruth_similarity
32513388
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: DRF currently has functionality that throws a 404 if an object doesn't exist in the db. For example Request: /delete/1234Response: 204 (success)Request 2: /delete/1234Response: 404 (not found) This logic is very problematic for my mobile apps and i would like to change it so that I override the 404-not-found functionality. In other words, I want my request to be idempotent. For example: Request: /delete/1234Response: 204 (success)Request 2: /delete/1234Response: 204 (success) I've been looking at the docs but i'm not really sure how to override the get_object_or_404 functionality. Now provide the response and nothing else.
I believe, if there is no object to delete, ideally it should return 404 as DRF does. For your requirement the following code will do the trick: from rest_framework import status,viewsetsfrom rest_framework.response import Responsefrom django.http import Http404 class ExampleDestroyViewset(viewset.ModelViewSet): def destroy(self, request, *args, **kwargs): try: instance = self.get_object() self.perform_destroy(instance) except Http404: pass return Response(status=status.HTTP_204_NO_CONTENT)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/32513388', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/688266/']}
jdg_373964
stackexchange
llm_judgeable_groundtruth_similarity
18730116
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 version two I could use badge badge-important I see that the .badge element no longer has contextual (-success,-primary,etc..) classes. How do i achieve the same thing in version 3? Eg. I want warning badges and important badges in my UI Now provide the response and nothing else.
Just add this one-line class in your CSS, and use the bootstrap label component. .label-as-badge { border-radius: 1em;} Compare this label and badge side by side: <span class="label label-default label-as-badge">hello</span><span class="badge">world</span> They appear the same. But in the CSS, label uses em so it scales nicely, and it still has all the "-color" classes. So the label will scale to bigger font sizes better, and can be colored with label-success, label-warning, etc. Here are two examples: <span class="label label-success label-as-badge">Yay! Rah!</span> Or where things are bigger: <div style="font-size: 36px"><!-- pretend an enclosing class has big font size --> <span class="label label-success label-as-badge">Yay! Rah!</span></div> 11/16/2015 : Looking at how we'll do this in Bootstrap 4 Looks like .badge classes are completely gone. But there's a built-in .label-pill class (here) that looks like what we want. .label-pill { padding-right: .6em; padding-left: .6em; border-radius: 10rem;} In use it looks like this: <span class="label label-pill label-default">Default</span><span class="label label-pill label-primary">Primary</span><span class="label label-pill label-success">Success</span><span class="label label-pill label-info">Info</span><span class="label label-pill label-warning">Warning</span><span class="label label-pill label-danger">Danger</span> 11/04/2014 : Here's an update on why cross-pollinating alert classes with .badge is not so great. I think this picture sums it up: Those alert classes were not designed to go with badges. It renders them with a "hint" of the intended colors, but in the end consistency is thrown out the window and readability is questionable. Those alert-hacked badges are not visually cohesive. The .label-as-badge solution is only extending the bootstrap design. We are keeping intact all the decision making made by the bootstrap designers, namely the consideration they gave for readability and cohesion across all the possible colors, as well as the color choices themselves. The .label-as-badge class only adds rounded corners, and nothing else. There are no color definitions introduced. Thus, a single line of CSS. Yep, it is easier to just hack away and drop in those .alert-xxxxx classes -- you don't have to add any lines of CSS. Or you could care more about the little things and add one line.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/18730116', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/402941/']}
jdg_373965
stackexchange
llm_judgeable_groundtruth_similarity
40073149
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Please consider the following entities public class What { public int Id { get; set; } public string Name { get; set; } public ICollection<Track> Tracks { get; set; } public int? LastTrackId { get; set; }] public Track LastTrack { get; set; }}public class Track { public Track(string what, DateTime dt, TrackThatGeoposition pos) { What = new What { Name = what, LastTrack = this }; } public int Id { get; set; } public int WhatId { get; set; } public What What { get; set; }} I use the following to configure the entities: builder.HasKey(x => x.Id);builder.HasMany(x => x.Tracks). WithOne(y => y.What).HasForeignKey(y => y.WhatId);builder.Property(x => x.Name).HasMaxLength(100);builder.HasOne(x => x.LastTrack). WithMany().HasForeignKey(x => x.LastTrackId); Has you can see there is a wanted circular reference: What.LastTrack <-> Track.What when I try to add a Track to the context (on SaveChanges in fact): Track t = new Track("truc", Datetime.Now, pos);ctx.Tracks.Add(t);ctx.SaveChanges(); I get the following error: Unable to save changes because a circular dependency was detected in the data to be saved: ''What' {'LastTrackId'} -> 'Track' {'Id'}, 'Track' {'WhatId'} -> 'What' {'Id'}'. I would like to say... yes, I know but... Is such a configuration doable with EF Core ? Now provide the response and nothing else.
This is what I like to call the favored child problem: a parent has multiple children, but one of them is extra special. This causes problems in real life... and in data processing. In your class model, What (is that a sensible name, by the way?) has Tracks as children, but one of these, LastTrack is the special child to which What keeps a reference. When both What and Track s are created in one transaction, EF will try to use the generated What.Id to insert the new Track s with WhatId . But before it can save What it needs the generated Id of the last Track . Since SQL databases can't insert records simultaneously, this circular reference can't be established in one isolated transaction. You need one transaction to save What and its Track s and a subsequent transaction to set What.LastTrackId . To do this in one database transaction you can wrap the code in a TransactionScope : using(var ts = new TransactionScope()){ // do the stuff ts.Complete();} If an exception occurs, ts.Complete(); won't happen and a rollback will occur when the TransactionScope is disposed.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/40073149', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1501073/']}
jdg_373966
stackexchange
llm_judgeable_groundtruth_similarity
9661447
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 Prompt:A program that accepts a candy name (for example, “chocolate-covered blueberries”), price per pound, and number of pounds sold in the average month, and displays the item’s data only if it is a best-selling item. Best-selling items are those that sell more than 2000 pounds per month.b. A program that accepts candy data continuously until a sentinel value is entered and displays a list of high- priced, best-selling items. Best-selling items are defined in Exercise 2a. High-priced items are those that sell for $10 per pound or more. Here is an example of a good design in operation: High-priced, Best-selling CandyFudge $12.50 4500 lbsVanilla Creme $13.75 2200 lbs.Fudge, 12.50, 4500 Jawbreakers, 6.50, 5500 Chocolate, 14.00, 790 Butterscotch, 9.50, 4500 Vanilla Creme, 13.75, 2200Item that sold most pounds: Jawbreakers but the problem I am having is that my teacher is not letting me use for loops, or arrays. And I do not want to define multiple instances of the same variable because it is finite to a certain amount.... What would be the most efficient way of doing this? start // Declarations num QUIT = "Y"; final String HEADING = "High Priced, Best Selling Candy" + "\n" + "\n"; final String HSPS = candyName + " " + candyPrice + " " + candySold + " "; final String MOSTSOLD = "Item that sold the most pounds is " while <> QUIT; enterCandy(); printHighPriceBestSelling(); printSoldMostPounds(); endwhile; stopentercandy() String candyName = "poop"; double candyPrice = 0.0; double candyWeight = 0.0; int candySold = 0; output "Please enter name of candy."; input candyName; output "Please enter candy price."; input candyPrice; output "Please enter pounds sold."; input candySold;printHighPriceBestSelling() if(candySold > 2000 && candyPrice > 10) { output HEADING; output HSPS; } else { output "There were/are no best selling, high priced candy!" } printSoldMostPounds(); //There is no basis for comparison. There are only two ways of doing this. Create lots of different, artbitrary, and predefined variables to be filled by the loop until they are overwritten. Lets say 10. Or create an array. I am sure there is an overly complex way of doing it with nested if/switch/while loops, but why teach us/force us to use the ugly inefficient way? output "MOSTSOLD "; Now provide the response and nothing else.
No, there's no way to supply defaults inside the store call. The store macro is quite simple: def store(store_attribute, options = {}) serialize store_attribute, Hash store_accessor(store_attribute, options[:accessors]) if options.has_key? :accessorsend And all store_accessor does is iterate through the :accessors and create accessor and mutator methods for each one. If you try to use a Hash with :accessors you'll end up adding some things to your store that you didn't mean to. If you want to supply defaults then you could use an after_initialize hook: class User < ActiveRecord::Base store :settings, accessors: [ :color, :homepage ] after_initialize :initialize_defaults, :if => :new_record?private def initialize_defaults self.color = 'blue' unless(color_changed?) self.homepage = 'rubyonrails.org' unless(homepage_changed?) endend
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9661447', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1251814/']}
jdg_373967
stackexchange
llm_judgeable_groundtruth_similarity
321108
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: A simple, undirected graph $G = (V,E)$ is said to be strongly rigid if the identity is the only graph endomorphism . For which positive integers $k>2$ is there a strongly rigid $k$ - regular graph? Now provide the response and nothing else.
Let $X(\mathcal{S)}$ be the block graph of a Steiner triple system $\mathcal{S}$ on $v$ points. The triple system consists of $b=v(v-1)/6$ triples from a set $V$ of size $v$ such that each pair of points from $V$ lies in exactly one triple. Necessarily $v\equiv1,3$ mod 6 and, if this condition holds, triple systems on $v$ points exist. The block graph has the triples of $\mathcal{S}$ as itvertices, two triples are adjacent if they have exactly one point in common. The block graph is strongly regular. A coclique in $X(\mathcal{S})$ is given by a set of pairwise disjoint triple, whence $\alpha(X(\mathcal{S})) =\lfloor v/3\rfloor$ . If $v>15$ , the cliques of maximum size come from the triple containing a given point, and so $\omega(X(\mathcal{S}))=(v-1)/2$ . So we see that, if $v\equiv1$ mod 6, then $\chi(X(\mathcal{S})) > \omega(X(\mathcal{S}))$ . Now in "Cores of geometric graphs" ( arXiv:0806.1300v1 ), Gordon Royle and I prove that every endomorphism of the block graph of a Steiner triple system is either an automorphism, or is a homomorphism to a maximum clique. It follows that if $v\cong1$ mod 6, the block graph of a Steiner triple system has no non-identity endomorphism. Finally Babai proved that almost all Steiner triple systems are asymmetric, whence it follows that almost all Steiner triple systems on $v\equiv1$ mod 6 points have no non-identity automorphism. (See L. Babai " Almost all Steiner triple systems are asymmetric " in Topics on Steiner systems. Ann. Discrete Math. 7 (1980), 37–39.) When $v>15$ all cliques of maximum size come from points of $V$ (exercise), when $v>15$ the automorphism group of a triple system and its block graphare isomorphic. So we have lots of strongly rigid regular graphs. In "Homomorphisms of strongly regular graphs" ( arXiv:1601.00969 ), David Roberson proves that the core of a strongly regular graph is either the graph itself, or is a complete graph. Hence any strongly regular graph with $\chi>\omega$ must be a core and, if the graph is asymmetric, it will not admit a non-trivial endomorphism.I suspect that almost all Latin square graphs on a given order are strongly rigid. There is a second way to potentially produce more examples. In a book somewhere, Gordon Royle and I prove that a triangle-free graph with diameter two and no "twinned vertices" is a core. It follows that is $X$ is connected, triangle-free and asymmetric, it is strongly rigid. Unfortunately no examples come to mind just now. Finally none of this helps in finding finite cubic graphs with only trivial endomorphisms.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/321108', 'https://mathoverflow.net', 'https://mathoverflow.net/users/8628/']}
jdg_373968
stackexchange
llm_judgeable_groundtruth_similarity
2421307
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Suppose I have a Base class and a Child class that inherits from Base . What is the right way to call the constructor of base class from a child class in Python? Do I use super ? Here is an example of what I have so far: class Base(object): def __init__(self, value): self.value = value ...class Child(Base): def __init__(self, something_else): super(Child, self).__init__(value=20) self.something_else = something_else ... Is this correct? Thanks, Boda Cydo. Now provide the response and nothing else.
That is correct. Note that you can also call the __init__ method directly on the Base class, like so: class Child(Base): def __init__(self, something_else): Base.__init__(self, value = 20) self.something_else = something_else That's the way I generally do it. But it's discouraged, because it doesn't behave very well in the presence of multiple inheritance. Of course, multiple inheritance has all sorts of odd effects of its own, and so I avoid it like the plague. In general, if the classes you're inheriting from use super , you need to as well.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2421307', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/257942/']}
jdg_373969
stackexchange
llm_judgeable_groundtruth_similarity
5504152
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to debug some PHP code and wanted to download the XDebug debugger for PHP. All I see there is Windows binaries for downloading. Is it at all possible to use it on Ubuntu? Now provide the response and nothing else.
Execute the following commands in your terminal. Download Xdebug - you will need to follow alternate instructions if you don't have PHP5 working on your machine already. sudo apt-get install php5-xdebug The package should modify your INI file for you, but just in case you need to edit it yourself open it up and make the following modification - on Ubuntu its typically at /etc/php5/apache2/php.ini - add the following line. zend_extension="/usr/lib/php5/20110331/xdebug.so" That path might be a little different on your system - just make sure its a fully qualified path to the xdebug.so file on your machine. Also remember to comment out any references to the Zend Debugger - you can't run both at the same time. Now restart Apache. sudo /etc/init.d/apache2 restart You may also need want enable html_errors. Search for html_errors in /etc/php5/apache2/php.ini and make sure it is set to On. A restart of Apache is also required. html_errors = On Double-check with phpinfo() to make sure that everything is installed properly - you may also want to set configurations for Xdebug in your php.ini file.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/5504152', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/478573/']}
jdg_373970
stackexchange
llm_judgeable_groundtruth_similarity
6036357
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 valid to do something such as CREATE SYNONYM [dbo].[MyTable] FOR [AnotherDatabase].dbo.[MyTable] and then modify Entity Framework's edmx file to read this object like it would any other table? I did a quick sample test and it seems to work fine for selecting and updating, but I wanted to know if there was any reason why I shouldn't be doing this I am getting the table definition by creating an edmx file pointing to the 2nd database, building out the entities there, then copy/pasting the definition into the 1st database's edmx file. UPDATE If anyone is interested, I wrote up what I did to make an edmx file span mulitple databases here . It includes scripts for generating synonyms and merging edmx files. Now provide the response and nothing else.
If you made a test and it worked you probably showed something nobody else know about. Till now I always answered this type of question: It is not possible to use single model with two databases (with some more ugly workaround based on views hiding tables from the second database). Now I know two workarounds. The only disadvantage of this approach is that all changes made manually to SSDL part of your EDMX are always lost if you run Update model from database . This means either manual development of EDMX (which is quite hard work) or using some tool / script which will add your changes after each update from database.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6036357', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/302677/']}
jdg_373971
stackexchange
llm_judgeable_groundtruth_similarity
2396556
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 seems to be an often repeated, "folklore-ish" statement, that diffeomorphism is an equivalence relation on smooth manifolds, and two smooth manifolds that are diffeomorphic are indistinguishable in terms of their smooth atlases. There is a strange counter example in Lee's Introduction to Smooth Manifolds though, let us define two smooth manifolds modelled on the real line. Let $\mathcal A$ be a smooth maximal atlas on $\mathbb{R}$ that is generated by the global chart $\varphi:\mathbb{R}\rightarrow\mathbb{R}$, $\varphi(x)=x$, and let $\bar{\mathcal A}$ be the maximal smooth atlas on $\mathbb{R}$ generated by the global chart $\bar{\varphi}(x)=x^3$. The transition function $\varphi\circ\bar{\varphi}^{-1}$ is not smooth, so these two smooth structures are incompatible. However the map $F:(\mathbb{R},\mathcal A)\rightarrow(\mathbb{R},\bar{\mathcal{A}})$ given by $F(x)=x^{1/3}$ is a diffeo, because $$ (\bar{\varphi}\circ F\circ \varphi^{-1})(x)=x, $$ and this map is smooth. So the smooth manifolds $(\mathbb{R},\mathcal A)$ and $(\mathbb{R},\bar{\mathcal{A}})$ are diffeomorphic. Yet the two manifolds have incompatible, thus, different smooth structures. Question: I guess I don't have a clear question, I am just somewhat confused. Because this is a counterexample , it seems to prove that the statement "two diffeomorphic manifolds cannot be told apart by their smooth structures" is wrong. However how wrong it is? Can we consider the two manifolds given in this example equivalent? Is there any practical difference between the two? Is differential geometry the same on them? Now provide the response and nothing else.
The counterexample just shows that two diffeomorphic smooth structures on the same set $X$ do not need to share a common atlas. However, in any case, two diffeomorphic structures cannot be distinguished in the smooth category, in the sense that every true statement in the smooth category still remains true after replacing one structure with the other one. This also happens in the topological category: it is possible to have two homeomorphic, but different, topological structures on a set $X$. For instance, the two topologies on $\mathbb{R}$ given by $$\mathcal{T}_1 = \{[a, \, + \infty) \; : \; a \in \mathbb{R} \cup \{-\infty\} \}, \quad \mathcal{T}_2 = \{(- \infty, \, a] \; : \; a \in \mathbb{R} \cup \{+\infty\} \}$$are clearly different. However, the map $$f \colon (\mathbb{R}, \, \mathcal{T}_1) \to (\mathbb{R}, \, \mathcal{T}_2), \quad x \mapsto -x$$is a homeomorphism, so from the topological point of view the two spaces have exactly the same properties.
{}
{'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/2396556', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/171560/']}
jdg_373972
stackexchange
llm_judgeable_groundtruth_similarity
401583
Below is a question asked on the forum meta.stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When reporting a syntax highlighting problem to highlight.js , one of the questions is: Are you using highlight or highlightAuto ? What's the answer for SO? Now provide the response and nothing else.
It uses both. Or rather, it is using highlightElement() , plus a plug-in to switch to highlightAuto() when no language tag is present. See the full.en.js source file , which contains: // highlightjs.initHighlighting highlights all `pre code`s by default and requires the lang class to be on the `code` block.// We only want to highlight our `pre.s-code-block`s specifically and our lang class is on the `pre` block.// Highlight each of these manually while skipping already highlighted blocks with the added hljs class$("pre.s-code-block code:not(.hljs)").each(function () { StackExchange.highlightjs.instance.highlightElement(this);}); See the section at the end of highlightjs-loader.en.js to see how the library is configured, including the switch to highlightAuto() : instance.addPlugin({ "before:highlight": function (data) { if (data.language === "no-highlight") { data.result = instance.highlightAuto(data.code); } }});
{}
{'log_upvote_score': 5, 'links': ['https://meta.stackoverflow.com/questions/401583', 'https://meta.stackoverflow.com', 'https://meta.stackoverflow.com/users/157247/']}
jdg_373973
stackexchange
llm_judgeable_groundtruth_similarity
6934330
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 generate a unique 8 character random alphanumeric string in TSQL, for a mail confirm link. We are currently using a GUID but it is not very user friendly. It only really has to obey a few rules: be 8 Characters long be unique be generated efficiently Now provide the response and nothing else.
Here are 2 ways of solving it Method 1: This will generate 8 random characters and store them in varchar @r, in order to prevent all the individual characters from being identical, I added a seed to RAND(). DECLARE @r varchar(8)SELECT @r = coalesce(@r, '') +CHAR(CASE WHEN r between 0 and 9 THEN 48WHEN r between 10 and 35 THEN 55ELSE 61 END + r)FROMmaster..spt_valuesCROSS JOIN(SELECT CAST(RAND(ABS(CHECKSUM(NEWID()))) *61 as int) r) aWHERE type = 'P' AND number < 8 Method 2: This method is using a tally table, each character will never occur more than once. The rows used to generate these characters are randomized by ordering on newid() DECLARE @r varchar(8)SELECT @r = coalesce(@r, '') + nFROM (SELECT top 8 CHAR(number) n FROMmaster..spt_valuesWHERE type = 'P' AND (number between ascii(0) and ascii(9)or number between ascii('A') and ascii('Z')or number between ascii('a') and ascii('z'))ORDER BY newid()) a In order to ensure uniqueness for each varchar(8) you can store the results in a table and compare with result in that table. You can also make the varchar longer and just hope for the best
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6934330', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/680877/']}
jdg_373974
stackexchange
llm_judgeable_groundtruth_similarity
2202717
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Inside of my QGraphicsRectItem::paint(), I am trying to draw the name of the item within its rect(). However, for each of the different items, they can be of variable width and similarly names can be of variable length. Currently I am starting with a maximum font size, checking if it fits and decrementing it until I find a font size that fits. So far, I haven't been able to find a quick and easy way to do this. Is there a better, or more efficient way to do this? Thanks! void checkFontSize(QPainter *painter, const QString& name) { // check the font size - need a better algorithm... this could take awhile while (painter->fontMetrics().width(name) > rect().width()) { int newsize = painter->font().pointSize() - 1; painter->setFont(QFont(painter->font().family(), newsize)); }} Now provide the response and nothing else.
Johannes from qtcentre.org offered the following solution: float factor = rect().width() / painter->fontMetrics().width(name); if ((factor < 1) || (factor > 1.25)) { QFont f = painter->font(); f.setPointSizeF(f.pointSizeF()*factor); painter->setFont(f); } I gave it a try in my program and so far, it seems to work quite well. I like it because it produces results in one pass, but it assumes that font width scales like its height. http://www.qtcentre.org/threads/27839-For-Qt-4-6-x-how-to-auto-size-text-to-fit-in-a-specified-width
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2202717', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/245179/']}
jdg_373975
stackexchange
llm_judgeable_groundtruth_similarity
348943
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to write a bespoke learning curve function. I was wondering how is it usually implemented. When the size of the training set is increased - Is it normally increased by adding new samples to the already existing set incrementally? Or is the training size size is selected randomly? To give an example: Suppose the train-set size ratios are [0.2, 0.3, 0.4 ...], then when we go from 0.2 to 0.3, do we add an extra 0.1 on top of what existed before(0.2) incrementally? Or do we just get another random sample from the full set? Now provide the response and nothing else.
There is no difference in the definition - in both cases, the likelihood function is any function of the parameter that is proportional to the sampling density. Strictly speaking we do not require that the likelihood be equal to the sampling density; it needs only be proportional, which allows removal of multiplicative parts that do not depend on the parameters. Whereas the sampling density is interpreted as a function of the data, conditional on a specified value of the parameter, the likelihood function is interpreted as a function of the parameter for a fixed data vector. So in the standard case of IID data you have: $$L_\mathbf{x}(\theta) \propto \prod_{i=1}^n p(x_i|\theta).$$ In Bayesian statistics, we usually express Bayes' theorem in its simplest form as: $$\pi (\theta|\mathbf{x}) \propto \pi(\theta) \cdot L_\mathbf{x}(\theta).$$ This expression for Bayes' theorem stresses that both of its multilicative elements are functions of the parameter, which is the object of interest in the posterior density. (This proportionality result fully defines the rule, since the posterior is a density, and so there is a unique multiplying constant that makes it integrate to one.) As you point out in your update, Bayesian and frequentist philosophy have different interpretive structures. Within the frequentist paradigm the parameter is generally treated as a "fixed constant" and so it is not ascribed a probability measure. Frequentists therefore reject the ascription of a prior or posterior distribution to the parameter (for more discussion on these philosophic and interpretive differences, see e.g., O'Neill 2009 ).
{}
{'log_upvote_score': 6, 'links': ['https://stats.stackexchange.com/questions/348943', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/132059/']}
jdg_373976
stackexchange
llm_judgeable_groundtruth_similarity
2915672
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 unfortunate enough to be stuck using VS 2010 for a project, and noticed the following code still doesn't build using the non-standards compliant compiler: #include <stdio.h>#include <stdlib.h>int main (void){ char buffer[512]; snprintf(buffer, sizeof(buffer), "SomeString"); return 0;} (fails compilation with the error: C3861: 'snprintf': identifier not found) I remember this being the case way back with VS 2005 and am shocked to see it still hasn't been fixed. Does any one know if Microsoft has any plans to move their standard C libraries into the year 2010? Now provide the response and nothing else.
Short story: Microsoft has finally implemented snprintf in Visual Studio 2015. On earlier versions you can simulate it as below. Long version: Here is the expected behavior for snprintf: int snprintf( char* buffer, std::size_t buf_size, const char* format, ... ); Writes at most buf_size - 1 characters to a buffer. The resulting character string will be terminated with a null character, unless buf_size is zero. If buf_size is zero, nothing is written and buffer may be a null pointer. The return value is the number of characters that would have been written assuming unlimited buf_size , not counting the terminating null character. Releases prior to Visual Studio 2015 didn't have a conformant implementation. There are instead non-standard extensions such as _snprintf() (which doesn't write null-terminator on overflow) and _snprintf_s() (which can enforce null-termination, but returns -1 on overflow instead of the number of characters that would have been written). Suggested fallback for VS 2005 and up: #if defined(_MSC_VER) && _MSC_VER < 1900#define snprintf c99_snprintf#define vsnprintf c99_vsnprintf__inline int c99_vsnprintf(char *outBuf, size_t size, const char *format, va_list ap){ int count = -1; if (size != 0) count = _vsnprintf_s(outBuf, size, _TRUNCATE, format, ap); if (count == -1) count = _vscprintf(format, ap); return count;}__inline int c99_snprintf(char *outBuf, size_t size, const char *format, ...){ int count; va_list ap; va_start(ap, format); count = c99_vsnprintf(outBuf, size, format, ap); va_end(ap); return count;}#endif
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2915672', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/351242/']}
jdg_373977
stackexchange
llm_judgeable_groundtruth_similarity
7367152
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 have 2 classes named A and B. A has a method "public void Foo()". B has several other methods. What i need is a variable in class B, that will be assigned the Foo() method of class A.This variable should afterwards be "executed" (=> so it should execute the assigned method of class A). How to do this? Now provide the response and nothing else.
It sounds like you want to use a delegate here. Basically, you can add, in class "B": class B{ public Action TheMethod { get; set; }}class A{ public static void Foo() { Console.WriteLine("Foo"); } public static void Bar() { Console.WriteLine("Bar"); }} You could then set: B b = new B();b.TheMethod = A.Foo; // Assign the delegateb.TheMethod(); // Invoke the delegate...b.TheMethod = A.Bar;b.TheMethod(); // Invoke the delegate... This would print out "Foo" then "Bar".
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7367152', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/749047/']}
jdg_373978
stackexchange
llm_judgeable_groundtruth_similarity
31171
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: All the mouse movements, USB connections and other PC peripherals such as printers etc. are what is called serial communication. One bit per time. So far so good. But when it comes to TCP protocol, Ethernet and internet it is not called serial communication anymore. But this is also bit per second stuff. Why is that so? What is the main difference? I couldn't understand why it is not serial communication. Now provide the response and nothing else.
At least three reasons, probably: In the era when RS-232 ports were common, it so by far the most common means of bit-at-a-time communication, so much so that the term "serial port" became synonymous with "RS-232 port"; using the term "serial" in connection with anything else would add confusion. Note that USB avoids such confusion mainly because it seldom referred to as "Universal Serial Bus", so the existence of the word "serial" in its long-form name is a non-issue. In nearly all cases, RS-232 ports their logic-level equivalents transmit individual bytes as they are received from software, and individual incoming bytes available to software as they are received. By contrast, most Ethernet devices will wait until software has supplied an entire packet (between 64 and 1536 bytes) before they begin transmission, and will wait until they have received and validated an entire packet before they make any of it available to software. Although bits and bytes might be sent over the wire serially, software neither knows nor cares. It just knows that some short time after one controller is fed a packet and told to send it, another controller will report that a packet is available, and allow software to read it. A "serial port" is guaranteed to transmit bytes of data in the chronological sequence that software supplies them, and make them available to software in the chronological sequence they are received; it would be rather useless if it did not. All Ethernet and Internet systems guarantee that when a packet is sent from one node to another the arrangement of bytes made available to the recipient will match the arrangement of bytes supplied by the sender, but there is no common specification requiring that the chronological order in which data are transmitted have any relation to their arrangement within a packet. Further, there only guarantees that can be made with regard to chronological sequencing of packets relative to each other are highly vague. If packet X is delivered Sunday at 11:47am and packet Y is delivered the next day at 3:28pm, one can safely assume that Y was sent after X. On the other hand, if X is delivered at 1:47:12 and Y is delivered at 1:47:15, it's entirely possible that Y was sent first but X took longer to arrive. Incidentally, a 10-base-T Ethernet connection sends individual bits in sequence, but higher-speed cabling often uses various signalling methods to send multiple bits at once.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/31171', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/16307/']}
jdg_373979
stackexchange
llm_judgeable_groundtruth_similarity
35598
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 the addition and multiplication operators are both commutative, and the exponentiation operator is not. My question is why . As background there are plenty of mathematical schemes that can be used to define these operators. One of these is hyperoperation where $H_0(a,b) = b+1$ (successor op) $H_1(a,b) = a+b$ (addition op) $H_2(a,b) = ab $ (multiplication op) $H_3(a,b) = a^b$ (exponentiation op) $H_4(a,b) = a\uparrow \uparrow b$ (tetration op: $a^{(a^{(...a)})}$ nested $b$ times ) etc. Here it is not obvious to me why $H_1(a,b)=H_1(b,a)$ and $H_2(a,b)=H_2(b,a)$ but not $H_3(a,b)=H_3(b,a)$ Can anyone explain why this symmetry breaks, in a reasonably intuitive fashion? Thanks. Now provide the response and nothing else.
My personal opinion is that the exponential is not naturally regarded as the next step in the progression from addition to multiplication, so there's no reason to expect it to share properties with the other two. Notice what happens if you demand that all of your quantities have units. Addition is an operation you do to two quantities with the same units: for example, you can add two distances to get another distance. Multiplication is an operation you do to two quantities with units $a$ and $b$ to get a quantity with units $ab$; for example, you can multiply two distances to get an area. However, you cannot exponentiate two unital quantities. In computing $a^b$, the quantity $b$ needs to be unitless or else there's no sensible way to assign a value to the result. This tells us that $a$ and $b$ are being treated very differently, so there's no reason to expect that switching them is a physically meaningful operation. As I've discussed on math.SE before , the exponential has many generalizations in mathematics, and in most of them the base and the exponent are very different objects: in fact, in most of them the base is just $e$.
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/35598', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/10171/']}
jdg_373980
stackexchange
llm_judgeable_groundtruth_similarity
503199
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 run a couple of game tunnelling servers and would like to have a page where the client can run a ping on all the servers and find out which is the most responsive. As far as I can see there seems to be no proper way to do this in JavaScript, but I was thinking, does anybody know of a way to do this in flash or some other client browser technology maybe? Now provide the response and nothing else.
Most applet technology, including Javascript, enforces a same-origin policy. It may be possible to dynamically add DOM elements, such as images, and collect timing information using the onload event handler. Psuedo-code for (server in servers) { var img = document.createElement('IMG'); server.startTime = getCurrentTimeInMS(); img.onload=function() { server.endTime = getcurrentTimeInMS(); } img.src = server.imgUrl;} Then wait an appropriate time and check the timing for each server object. Repeat as needed and compute averages if you want. I'm not sure what kind of accuracy you can expect. Disadvantages: You are probably using the wrong tool for the job. A browser is not equipped for this sort of application. It's probably quite inaccurate. If the resource you request is cached it won't give you the results you want, but you can work around that by changing the url each time. This is bandwidth-intensive compared to a normal ping. Make the image tiny, such as a spacer.gif file. The timing depends not only on the latency of the remote server but the bandwidth of that server. This may be a more or less useful measure but it's important to note that it is not simply the latency. You need to be able to serve HTTP requests from the various servers and, crucially, each server should serve the exact same resource (or a resource of the same length). Conditions on the server can affect the response time, such as if one server is compressing the data and another isn't.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/503199', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11421/']}
jdg_373981
stackexchange
llm_judgeable_groundtruth_similarity
244660
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: Proposition Suppose $\{a_n\}$ and $\{b_n\}$ are real sequences such that $a_n \to 0$. Show that $\sum a_kb_k$ converges under the following two conditions: $\sum_{k=1}^{\infty} |a_{k+1}-a_k|< \infty$ and $|\sum_{k=1}^{n} b_k| \leq M$. I'm stuck on this proof because I'm not sure how this: $\sum_{k=1}^{\infty} |a_{k+1}-a_k|< \infty$ fits into the bigger picture. In terms of finite sums this would be a telescoping series. Now provide the response and nothing else.
The limit is $\frac{1}{e-1}$. I wrote a paper on this sum several years ago and used the Euler-Maclaurin formula to prove the result. The paper is " The Euler-Maclaurin Formula and Sums of Powers ," Mathematics Magazine , 79 (1): 61-65, 2006. Basically, I use the Euler-Maclaurin formula to swap the sum with the corresponding integral. Then, after some asymptotic analysis on the error term provided by Euler-Maclaurin we get $$\lim_{n\to \infty}\frac{1^n+2^n+\cdots+(n-1)^n}{n^n} = \sum_{k=0}^{\infty} \frac{B_k}{k!},$$ where $B_k$ is the $k$th Bernoulli number. The exponential generating function of the Bernoulli numbers then provides the $\frac{1}{e-1}$ result. I should mention that I made a mistake in the original proof, though! The correction, as well as the generalization$$\lim_{n\to \infty}\frac{1^n+2^n+\cdots+(n+k)^n}{n^n} = \frac{e^{k+1}}{e-1}$$are contained in a letter to the editor ( Mathematics Magazine 83 (1): 54-55, 2010).
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/244660', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/8324/']}
jdg_373982
stackexchange
llm_judgeable_groundtruth_similarity
36912216
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 define a Binding as a Resource and then reuse it with different Controls properties? Example: Binding: <Window.Resources> <Binding x:Key="MyBinding" Path="MyProperty" Mode="TwoWay" /></Window.Resources> Reuse in XAML: <TextBox Text="{StaticResource MyBinding}" /> After declaring Binding as above I got the error: "The name 'InitializeComponent' does not exist in the current context" Is there any way to reuse the same Binding in different contexts? Now provide the response and nothing else.
Direct answer to your question is "yes, you can define a binding as a resource". The problem here is how do you then make any use of it? One possibility is to create an extension class which would pull the binding from the resources and apply it: public class BindingResourceExtension : StaticResourceExtension{ public BindingResourceExtension() : base() { } public BindingResourceExtension(object resourceKey) : base(resourceKey) { } public override object ProvideValue(IServiceProvider serviceProvider) { var binding = base.ProvideValue(serviceProvider) as BindingBase; if (binding != null) return binding.ProvideValue(serviceProvider); else return null; //or throw an exception }} Usage example: <Window.Resources> <ResourceDictionary> <Binding x:Key="MyBinding" Path="MyProperty" Mode="TwoWay" /> </ResourceDictionary></Window.Resources>(...)<TextBox Text="{ns:BindingResource MyBinding}" /> Can this solution be used in MultiBinding ? Yes, it can: <TextBlock> <TextBlock.Text> <MultiBinding StringFormat="First: {0}, Second: {1}"> <Binding Path="SomeProperty" /> <ns:BindingResource ResourceKey="MyBinding" /> </MultiBinding> </TextBlock.Text></TextBlock> There is however one drawback to this - although everything will work in run-time, the XAML Designer will complain that BindingResourceExtension is not of proper type to be put in the MultiBinding.Bindings collection. But, thankfully, there is a quick solution - simply use StaticResourceExtension instead! So this, while being functionally equivalent in run-time, will be accepted by the designer: <TextBlock> <TextBlock.Text> <MultiBinding StringFormat="First: {0}, Second: {1}"> <Binding Path="SomeProperty" /> <StaticResource ResourceKey="MyBinding" /> </MultiBinding> </TextBlock.Text></TextBlock>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36912216', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4576125/']}
jdg_373983
stackexchange
llm_judgeable_groundtruth_similarity
47211
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: The famous Zebra Puzzle (Wikipedia) , often called "Einstein's Riddle," is a logic puzzle that can be solved deductively by applying a list of logical rules. One version of the riddle (from Wikipedia) begins: There are five houses. The Englishman lives in the red house. The Spaniard owns the dog. ... The idea is that there are five houses, painted different colors, with occupants (one in each house) of different nationalities each of whom smokes a different brand, drinks a different beverage, and keeps a different pet. Given the "clues," the puzzle asks which resident owns the zebra. Given that Mathematica is a rule-based language, it seems that there should be a way of solving the puzzle without resorting to brute-force (i.e. while loops or searching). Can Mathematica be used to elegantly deduce the solution? How? Now provide the response and nothing else.
You can use LinearProgramming or more simply Minimize to solve this problem. The idea is to minimize an objective function of some decision variables subject to some constraints. The objective function doesn't matter, can be a constant function, the only relevant thing is the constraint satisfaction. First, setup the parameters, sets and clues (in an abstract way): n = 5;set[] = {"Color", "Nationality", "Drink", "Pet", "Smoke"};set["Color"] = {"Yellow", "Red", "Green", "Ivory", "Blue"};set["Nationality"] = {"Norwegian", "Ukrainian", "Englishman", "Spaniard", "Japanese"};set["Pet"] = {"Fox", "Horse", "Dog", "Snails", "Zebra"};set["Drink"] = {"Water", "Orange Juice", "The", "Coffee", "Milk"};set["Smoke"] = {"Kools", "Lucky Strike", "Chesterfield", "Old Gold", "Parliament"};clues = { (* 02 *) PairConstraint["Nationality", "Englishman", "Color", "Red"], (* 03 *) PairConstraint["Nationality", "Spaniard", "Pet", "Dog"], (* 04 *) PairConstraint["Drink", "Coffee", "Color", "Green"], (* 05 *) PairConstraint["Drink", "The", "Nationality", "Ukrainian"], (* 06 *) OrderConstraint["Color", "Ivory", "Color", "Green"], (* 07 *) PairConstraint["Smoke", "Old Gold", "Pet", "Snails"], (* 08 *) PairConstraint["Smoke", "Kools", "Color", "Yellow"], (* 09 *) PositionConstraint[3, "Drink", "Milk"], (* 10 *) PositionConstraint[1, "Nationality", "Norwegian"], (* 11 *) NeighborConstraint["Smoke", "Chesterfield", "Pet", "Fox"], (* 12 *) NeighborConstraint["Smoke", "Kools", "Pet", "Horse"], (* 13 *) PairConstraint["Smoke", "Lucky Strike", "Drink", "Orange Juice"], (* 14 *) PairConstraint["Nationality", "Japanese", "Smoke", "Parliament"], (* 15 *) NeighborConstraint["Nationality", "Norwegian", "Color", "Blue"] };search = {"Water", "Zebra"}; Then build decision variables. Every variable x[i_, p_, v_] is 1 if the property value v (Red, Englishman, ...) is assigned for the property p (Color, Nationality, ...) to the house number i and 0 otherwise. vars = Outer[\[FormalX], Range[n], {#}, set[#]] & /@ set[]; Then build constraints. Each decision variable should be greather than or equal to 0 (andalso less than or equal to 1, but this is taken into account at 2., and also aninteger, but this is taken into during optimization). Sums of decisions variables x[i_, p_, v_] for fixed {p,v} or forfixed {i,p} should be 1, because each property value ("Red", "Englishman" and soon) should be assigned exactly once, and because each house should have assignedexactly one property value per property (color, nationality and so on). Each of the previous 4 types of clues can then be translated to a(set of) relation between decision variables. Specifically: PositionConstraint[i_, p_, v_] means the property value v should be assigned for property p to the house number i , so simply x[i, p, v] == 1 . PairConstraint[p1_, v1_, p2_, v2_] means that if the property value v1 is assigned for property p1 to some house number i_ , also the property value v2 should be assigned for property p2 to the same house number i . For every {i, n} we need to have x[i, p1, v1] == x[i, p2, v2] . OrderConstraint[p1_, v1_, p2_, v2_] means that the property value v2 for property p2 should assigned to house number i+1 iff the property value v1 is assigned for property p1 to the number i_ . So for every {i, 0, n} we need to have x[i, p1, v1] == x[i+1, p2, v2] . At the end of building constraints a replacement x[0 | (n + 1), _, _] -> 0 is done. NeigborConstraint[p1_, v1_, p2_, v2_] means that if v1 for p1 is assigned to house i_ , v2 for p2 should be assigned to house i-1 or i+1 and if v2 for p2 is assigned to house i_ , v1 for p1 should be assigned to house i-1 or i+1 . For every {i, n} the first requirement can be formultad asking that x[i, p1, v1] <= x[i-1, p2, v2] + x[i+1, p2, v2] and the second with x[i, p2, v2] <= x[i-1, p1, v1] + x[i+1, p1, v1] Joinin all these kind of constraints is done with: constraints = Join[ (* Every Decision Variable is an assignment, should be \[GreaterEqual] 0 (and \[LessEqual] 1, and \[Element] Integers) *) Map[# >= 0 &, vars, {4}], (* Each property value ("Red", "Englishman" and so on) should be assigned exactly once *) (* Each house should have assigned exactly one property value per propery (color, nationality and so on) *) Map[Plus @@ # == 1 &, #, {4}] &@({#, Transpose[#, {1, 4, 3, 2}]} &@ vars), (* Clues constraints translated *) clues /. { PositionConstraint[i_, p_, v_] :> \[FormalX][i, p, v] == 1, PairConstraint[p1_, v1_, p2_, v2_] :> Table[\[FormalX][i, p1, v1] == \[FormalX][i, p2, v2], {i, n}], OrderConstraint[p1_, v1_, p2_, v2_] :> Table[\[FormalX][i, p1, v1] == \[FormalX][i + 1, p2, v2], {i, 0, n}], NeighborConstraint[p1_, v1_, p2_, v2_] :> Table[{ \[FormalX][i, p1, v1] <= \[FormalX][i - 1, p2, v2] + \[FormalX][i + 1, p2, v2], \[FormalX][i, p2, v2] <= \[FormalX][i - 1, p1, v1] + \[FormalX][i + 1, p1, v1] }, {i, n}] } /. \[FormalX][0 | (n + 1), _, _] :> 0 ]; Compute the solution. Compute the minimum value of constant function 0 subject to the constraints, with integers decision variables. Discard the optimal value and keep only rules for devision variables values. solution = Last@Minimize[{0, constraints}, Flatten[vars], Integers]; Finally display the result: Outer[First@Cases[solution, HoldPattern[\[FormalX][#2, #1, v_] -> 1] :> v] &, set[], Range[n]] /. {p : Alternatives @@ search -> Style[p, Bold, Red]} // MapThread[Prepend[#1, #2] &, {#, set[]}] & // Prepend[#, Prepend[Range[n], ""]] & // Grid[#, Dividers -> All, ItemSize -> {8, 1.5}, Alignment -> Center] & // Style[#, "DialogStyle"] & This is the output: UPDATE Maybe it would be easier to use solution = ToRules@Reduce[Flatten[constraints], Flatten[vars], Integers]; but on my machine this command is slower. Using LinearProgramming instead is a bit more complicated because we need to construct the cost vector and Matrix, but the function is very fast. vars = Flatten[vars];constraints = DeleteCases[Flatten@constraints, \[FormalX][__] >= 0];bm = CoefficientArrays[Equal @@@ constraints, vars]solution = Thread[vars -> LinearProgramming[ Table[0, Length[vars]], bm[[2]], Transpose@{-bm[[1]], constraints[[All, 0]] /. {Equal -> 0, LessEqual -> -1, GreaterEqual -> 1}}, 0, Integers]];
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/47211', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/9150/']}
jdg_373984
stackexchange
llm_judgeable_groundtruth_similarity
3301733
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: some_integer = 97.45 * 1# what does this notation mean? what will some_integer = ? Now provide the response and nothing else.
Just to expand on what everyone else has added... As mentioned, the hash mark (#) is a Type Declaration Character (TDC) and forces the literal "1" to the type Double. This Data-Type conversion belongs to a class of conversions called “Explicit Conversions”. Also in this class are Casts (such as CStr(), CLng(), etc.). Explicit Conversion are generally used to avoid an incorrect Implicit conversion. Implicit Conversion being conversions that VBA performs automatically. If you declare and Type all of your variables (example Dim j As Long ) it is easier to control how data is interpreted. However, there are still a few edge cases involving how literals (“hard coded numbers”) are handled. The most common reasons I know to use Type Declaration Characters with a literal are: Forcing Hex and Octal literals to Longs to avoid a known problem. (More here: http://support.microsoft.com/kb/38888 ) Preventing a common overflow condition caused when a math operation produces a result that is larger that the largest DataType used in the operation. Avoiding a floating-point calculation anomaly. Micro-optimization. Conversions caused by a Type Declaration Character happen at compile time. Casted conversions and implicit conversions happen at runtime. In 99.999% of cases, this will produce no measurable gain whatsoever and is generally a waste of time. As your example doesn’t do anything, I can only guess its not real code. So it makes it hard to intuit the author’s intent. 1 doesn’t apply. Reason 2 is a possibility. I will describe the problem and a possible fix. There are two things you need to know to understand the overflow issue. How literals are typed and how implicit conversion works. If there is no Type Declaration Character, a Literal will have a type assigned by default. Here are the rules: If the value is in quotes, it is a String even if it is a numeric value. If the value is numeric and has a decimal, it is a Double. If the value is numeric, has no decimal, and is between -32,767 and 32,767 (inclusive) it is of the type Integer. If the value is numeric, has no decimal, and is between -2,147,483,647 and 2,147,483,647 (inclusive) but not between -32,767 and 32,767 it is of the type Long. If the value is numeric, has no decimal, and outside the range of -2,147,483,647 to 2,147,483,647 it is of the type Double. Any Literal in Scientific notation will be a Double. Now that you know how a literal will be typed, you need to understand implicit conversion. All math operations work on two input values and output one result. The DataType of the result is chosen by analyzing the DataTypes of the input values. The output DataType is chosen based on three rules: 1. If either of the input values is of the DataType Variant VBA will choose the output DataType based on same rules described for literals. 2. If both input values are typed then it will choose the larger of the two data types. 3. If both input values are typed the same then the output DateType will be the same as the input DataType (assuming that type is not “Variant”). The problem occurs for condition 3. If you have two integers (ex. 500 and 400) and you perform an operation on them (ex. 500*400) that yields a result (200,000) to large to put into the resulting DateType (Integer). Then you get an overflow error. As 500 and 400 are Integers by default you would have to avoid this by explicitly typing one of them to a Long or a Double via a Type Declaration Character (ex. 500& * 400). Then when the output type was chosen it would choose the larger of the two (Long) which would be large enough to hold the result. I can say for certain that if the reason was 2 then there is no cause for concern (at least in the given example). Any literal with a decimal point is of the type Double by default. As implicit conversion always chooses the largest type in an operation and a Double will always be present there is zero chance whatsoever of producing an overflow no matter what. If the cause for concern is a Floating Point issue, that would take some more serious consideration with a real example to be able to see if you needed the Type Declaration Character. If the reason was Micro-Optimization, it really doesn’t matter if you leave it there or not. Technically, it’s better to use a Double with a Double. So there is no harm in leaving it. However, there isn’t any reason to go out of your way to put one in either. Misc The various type declaration characters are as follows: Type Declaration Character Data Type % Integer & Long ! Single # Double $ String @ Currency To add a little more information: Type declaration character can be used in place their corresponding type in a Dim statement (although this is considered by many a poor practice due). Thus : Dim s As String is the same as Dim s$ s will be created as a String in both cases. Similarly, you can type a Functions Return value using TDCs. So Public Function MyFunc()& is the same as Public Function MyFunc() As Long . Conversion Functions Function Return TypeCBool BooleanCByte ByteCCur Currency CDate Date CDbl Double CDec DecimalCInt IntegerCLng LongCSng SingleCStr StringCVar Variant
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3301733', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/117700/']}
jdg_373985
stackexchange
llm_judgeable_groundtruth_similarity
13471129
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 call some jQuery function targeting div with table. That table is populated with ng-repeat . When I call it on $(document).ready() I have no result. Also $scope.$on('$viewContentLoaded', myFunc); doesn't help. Is there any way to execute function right after ng-repeat population completes? I've read an advice about using custom directive , but I have no clue how to use it with ng-repeat and my div... Now provide the response and nothing else.
Indeed, you should use directives, and there is no event tied to the end of a ng-Repeat loop (as each element is constructed individually, and has it's own event). But a) using directives might be all you need and b) there are a few ng-Repeat specific properties you can use to make your "on ngRepeat finished" event. Specifically, if all you want is to style/add events to the whole of the table, you can do so using in a directive that encompasses all the ngRepeat elements. On the other hand, if you want to address each element specifically, you can use a directive within the ngRepeat, and it will act on each element, after it is created. Then, there are the $index , $first , $middle and $last properties you can use to trigger events. So for this HTML: <div ng-controller="Ctrl" my-main-directive> <div ng-repeat="thing in things" my-repeat-directive> thing {{thing}} </div></div> You can use directives like so: angular.module('myApp', []).directive('myRepeatDirective', function() { return function(scope, element, attrs) { angular.element(element).css('color','blue'); if (scope.$last){ window.alert("im the last!"); } };}).directive('myMainDirective', function() { return function(scope, element, attrs) { angular.element(element).css('border','5px solid red'); };}); See it in action in this Plunker . Hope it helps!
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/13471129', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/324400/']}
jdg_373986
stackexchange
llm_judgeable_groundtruth_similarity
53408
Below is a question asked on the forum raspberrypi.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have followed the following tutorial ( http://mygeeks014.blogspot.nl/2015/01/audio-streaming-to-bluetooth-speaker.html ) to connect a Bluetooth speaker to my Raspberry Pi. Everything works as it's supposed to, but the speaker will not automatically reconnect when the Raspberry gets restarted or the speaker gets turned on/off. Right now I manually reconnect the speaker via the Raspbian GUI, but I wonder if there's a simple solution to reconnect the speaker via the CLI. I will then be able to write a simple CRON to reconnect the speaker if it's not connected yet. Now provide the response and nothing else.
Here is a very detail explanation: Den3243 Here is a command line solution: First, let's scan, pair, trust your device with "bluetoothctl". To do that, run this at the command line, your terminal: bluetoothctl -a You should get a different command promptlike: [bluetooth] With your BT speaker on, type this: scan on In a few moments, you should see the BTdevices available. Next to the device will beit's MAC address, like: 00:AA:22:BB:33. Nowtype this: info <your mac address> Exclude the greater than and less than characters. What your looking for is somekind of previous association with yourBT speaker. You will know that there wasa previous association because bluetoothctlwill show information about your BT device.Some of this information will be about thedevice being paired and trusted. This is good. If bluetoothctl complains aboutthere is no device, then we need to set thatup at this moment. To do that, type this: pair <your mac address> You should see a success message aboutyour device pairing successfully. Now let's trust our new BT device. Type this: trust <your mac address> Again, you should see a success messageabout trusting. Let me pre-warn you. YourBT device might connect then again it mightnot. Never fear, we don't want it to connect.Go ahead and let's exit "bluetoothctl". To do that, type: quit Now you will be brought back to the command line prompt. In a previous postI suggested for you to create a scripts directory in your home directory. If youhaven't, go ahead and do that now. Typethis at the command prompt: mkdir -p ~/scripts Press enter and now let's create ourautopair bash script. Type this: nano ~/scripts/autopair Enter this code into the script: #!/bin/bashbluetoothctl << EOFconnect [enter your MAC add]EOF Exclude the brackets! Now press CTRL + x at the same time, and now press enter to save the script. We needto make it executable. To do that, type this: chmod +x ~/scripts/autopair I'm assuming that you don't use external analog speakers plug into the 3.5 mm jack. If this is true, let's disable alsa.To do that, let's edit a file in the /bootdirectory called config.txt. To do that,type this in your terminal: sudo nano /boot/config.txt Page down to the bottom of the file andlook for two lines that read: # Enable audio (loads snd_bcm2835)dtparam=audio=on Place a (pound sign #) in front ofthe line that reads: dtparam=audio=on To look like: #dtparam=audio=on Press CTRL + x and then press Enterto save your file. I'm assuming you have pulseaudio installed?If not, go ahead and run this command fromthe command line: sudo apt-get update && sudo apt-get install pulseaudio -y This will get you a very important component to making bluetooth work! Now let's edit our .bashrcfile in our home directory. Type this: nano ~/.bashrc Page down to the bottom and add this line: pulseaudio --start Press CTRL + x and now press Enter to saveyour file. OK! We need to enter over into the Pythonworld. I have wrote a Python program thatwill watch for the bluetooth device. In short, it will activate the connectionbetween RPi and your bluetooth speaker,once your bluetooth speaker is turned on.And vice versa. Let's create a directorycalled python in your home directoryTo do that, type this: mkdir -p ~/python Now let's create the python program file.To do that, type this: nano ~/python/on.py Inside that file, we need to copy andpaste the following: #!/usr/bin/python## Monitor removal of bluetooth recieverimport osimport sysimport subprocessimport timedef blue_it(): status = subprocess.call('ls /dev/input/event0 2>/dev/null', shell=True) while status == 0: print("Bluetooth UP") print(status) time.sleep(15) status = subprocess.call('ls /dev/input/event0 2>/dev/null', shell=True) else: waiting()def waiting(): subprocess.call('killall -9 pulseaudio', shell=True) time.sleep(3) subprocess.call('pulseaudio --start', shell=True) time.sleep(2) status = subprocess.call('ls /dev/input/event0 2>/dev/null', shell=True) while status == 2: print("Bluetooth DOWN") print(status) subprocess.call('~/scripts/autopair', shell=True) time.sleep(15) status = subprocess.call('ls /dev/input/event0 2>/dev/null', shell=True) else: blue_it() blue_it() Now press CTRL + x and then press Enter to savethe Python program file. Now we need to makethis file executable. To do that, type this: chmod +x ~/python/on.py Finally, let's add this to our .bashrc scriptin our home directory: nano ~/.bashrc Page down to the bottom of the file and add these two lines: wait~/python/on.py Now press CTRL + x and then press Enter to save.Turn your bluetooth speaker on and reboot yourRaspberry Pi. Good Luck! -nitrolinux
{}
{'log_upvote_score': 6, 'links': ['https://raspberrypi.stackexchange.com/questions/53408', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/51824/']}
jdg_373987
stackexchange
llm_judgeable_groundtruth_similarity
36615496
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Trying to create a recursive method that raises a double value to an int power for a java course. The instructions say "However, write the code so that when n is even the method will return (x ^ (n/2))^2." This is what I have thus far: public static double powerFaster(double x, int n) { if (n == 0) { return 1; } else if ((n % 2) == 0) { return ((x ^ (n / 2.0) ^ 2.0)); //Error occurs here. } else { return x * powerFaster(x, (n - 1)); } } Now provide the response and nothing else.
^ is a XOR operator, not power. Use Math.pow() for power. That said, I think you missed the point of the exercise. You should return powerFaster(x, n/2) * powerFaster(x, n/2); when n is even (actually make one recursive call, store its result in a variable and multiply it by itself). public static double powerFaster(double x, int n) { if (n == 0) { return 1; } else if ((n % 2) == 0) { double pow = powerFaster(x, n/2); return pow * pow; } else { return x * powerFaster(x, (n - 1)); } }
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36615496', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6112922/']}
jdg_373988
stackexchange
llm_judgeable_groundtruth_similarity
11928637
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 receive some information per request, so I think instead of having a function for each request and obtaining those information from requests separately, it's better to have a filter. So every request shall pass that filter and I gain what I want. The question is: How can I write a custom filter? Suppose it is not like any predefined spring security filters and it is totally new. Now provide the response and nothing else.
You can use the standard Java filter. Just place it after authentication filter in web.xml (this means that it will go later in the filter chain and will be called after security filter chain). public class CustomFilter implements Filter{ @Override public void destroy() { // Do nothing } @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Set<String> roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities()); if (roles.contains("ROLE_USER")) { request.getSession().setAttribute("myVale", "myvalue"); } chain.doFilter(req, res); } @Override public void init(FilterConfig arg0) throws ServletException { // Do nothing }} Fragment of web.xml: <!-- The Spring Security Filter Chain --><filter> <filter-name>springSecurityFilterChain</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class></filter><filter-mapping> <filter-name>springSecurityFilterChain</filter-name> <url-pattern>/*</url-pattern></filter-mapping><!-- Your filter definition --><filter> <filter-name>customFilter</filter-name> <filter-class>com.yourcompany.test.CustomFilter</filter-class></filter><filter-mapping> <filter-name>customFilter</filter-name> <url-pattern>/VacationsManager.jsp</url-pattern></filter-mapping> Also you can add handler that will be invoked after successfull login (you need to extend SavedRequestAwareAuthenticationSuccessHandler ). Look here how to do this. And I think that this is even better idea. UPDATED: Or you can have this filter at the end of your security filters like this: <security:filter-chain-map> <sec:filter-chain pattern="/**" filters=" ConcurrentSessionFilterAdmin, securityContextPersistenceFilter, logoutFilterAdmin, usernamePasswordAuthenticationFilterAdmin, basicAuthenticationFilterAdmin, requestCacheAwareFilter, securityContextHolderAwareRequestFilter, anonymousAuthenticationFilter, sessionManagementFilterAdmin, exceptionTranslationFilter, filterSecurityInterceptorAdmin, MonitoringFilter"/> <!-- Your Filter at the End --></security:filter-chain-map> And to have your filter, you may use this: public class MonitoringFilter extends GenericFilterBean{@Overridepublic void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { //Implement this Function to have your filter working}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/11928637', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/491527/']}
jdg_373989
stackexchange
llm_judgeable_groundtruth_similarity
288990
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: Does an object have to represent an entity? By an entity I mean something like a Product , Motor , a ParkingLot etc, a physical, or even a clear-cut non-physical conceptual object -- something that is well defined, with some core data clearly belonging to the object, and some functions/methods that clearly operate on the core data. For example, I can have an object of a Demon , an entity in itself, an imaginary one perhaps and not physical but an entity nevertheless Can an object be just a collection of methods , a common set of procedures that tie in with a common goal? Example: can a class be called MotorOperations or MotorActions , where there is no entity, but methods inside the class do things like getMotorDataFromHTMLForm() getMotorManufacturers() selectMotorFromUserRequirements($requirements) canMotorCanHandleOperatingConditions($conditions) computePowerConsumptionForMotor($id) A class is typically defined as data central to the object + operations on data. So for a Motor there may be some motor variables relating to motor specifications, and there can be operations that combine those data to produce something. In my case it is more like I have a class with operations on data + data that is passed through the class, there is no data centric to "Motor Operations", other than temporary pass-through-the-class data. Question Can classes represent entity-less objects?If not, why they are bad/incomplete/non-OOP-centric? Are there ways they need to be changed/improved conceptually to be in line with OOP? Now provide the response and nothing else.
No , an object does not have to represent an entity. In fact, I would argue that when you stop thinking about objects as physical entities is when you finally get the benefits that OOP promises. This isn't the best example, but the Coffee Maker design is probably where the light started to come on for me. Objects are about messages. They're about responsibilities. They're not about Cars, Users, or Orders. I know we teach OO this way, but it becomes apparent after a few tries how fundamentally frustrating it is to figure out where things go when you try to do MVC, MVVM or MVWhatever. Either your models become ridiculously bloated or your controllers do. For navigability, it's great to know that anything that touches Vehicles is in the Vehicle.ext file, but when your application is about Vehicles, you inevitably end up with 3000 lines of spaghetti in that file. When you have a new message to send, you have at least one new object, and perhaps a pair of them. So in your question about a bundle of methods, I would argue that you're potentially talking about a bundle of messages. And each one could be its own object, with it's own job to do. And that's ok. It will become apparent as you split things apart which things really, really need to be together. And you put them together. But you don't immediately drop every method in a vaguely appropriate drawer for convenience sake if you want to enjoy OO. Let's talk about bags of functions An object can be just a collection of methods and still be OO, but my "rules" are pretty strict. The collection should have a single responsibility, and that responsibility can't be as generic as "Does stuff to motors". I might do such a thing as a service-layer facade, but I'm acutely aware that I'm being lazy for navigability/discovery reasons, not because I'm trying to write OO code. All the methods should be at a consistent layer of abstraction. If one method retrieves Motor objects and another returns Horsepower, that's probably too far apart. The object should work on the same "kind" of data. This object does stuff to motors(start/stop), this one does things with crank lengths, this one handles ignition sequencing, this one takes an html form. This data could conceivably be fields on the object and it would seem cohesive. I generally build objects of this sort when I'm doing transforms, composition, or just don't want to worry about mutability. I find focusing on object responsibilities leads me towards cohesion. There has to be some cohesion to be an object, but there doesn't need to be any fields nor very much behavior for it to be an object. If I was building a system that needed those 5 motor methods, I would start out with 5 different objects that do those things. As I found commonality, I would either start to merge things together or use common "helper" objects. That moves me into open/closed concerns - how can I extract this bit of functionality so I never have to modify that particular file again but still use it where needed? Objects are about messages Fields barely matter to an object - getting and setting registers doesn't change the world outside the program. Collaborating with other objects gets the work done. However, the strength of OO is that we can create abstractions so we don't have to think about all the individual details at once. Abstractions that leak or don't make sense are problematic, so we think deeply (too much, maybe) about creating objects that match our mental models. Key question: Why do these two objects need to talk to each other? Think of the object as an organ in a person - it has a default purpose and only changes behavior when it receives a specific message that it cares about. Imagine a scenario where you're in the crosswalk and a car is coming fast. As the brain object, I detect a stressor. I tell the hypothalamus to send corticotrophin-releasing hormone. The pituitary gland gets that message and releases adrenal corticotrophic hormone. The adrenal glands get that message and create adrenaline. When the muscle object gets that adrenaline message it contracts. When the heart get the same message, it beats faster. There's a whole chain of players involved in starting the complex behavior of sprinting across the street and it's the messages that matter. The brain object knows how to get the hypothalamus to send out the alert, but it doesn't know the chain of objects that will eventually make the behavior happen. Likewise the heart has no idea where adrenaline comes from, it just knows to do something different when that shows up. So in this ( simplified ) example, the adrenal gland object only needs to know how to take ACTH and make adrenaline. It doesn't need any fields to do that, yet it still seems like an object to me. Now if our application is designed only to sprint across the street, I may not need the pituitary gland and the adrenal gland objects. Or I only need a pituitary gland object that only does a small part of what we might conceptually see as the "pituitary gland model". These concepts all exist as conceptual entities, but it's software and we can make the AdrenalineSender or MuscleContractor or whatever and not worry much about the "incompleteness" of our model.
{}
{'log_upvote_score': 8, 'links': ['https://softwareengineering.stackexchange.com/questions/288990', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/119333/']}
jdg_373990
stackexchange
llm_judgeable_groundtruth_similarity
7617587
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 run several instances of a piece of code (2000 instances or so) concurrently in a computing cluster. The way it works is that I submit the jobs and the cluster will run them as nodes open up every so often, with several jobs per node. This seems to produce the same values for a good number of the instances in their random number generation, which uses a time-seed. Is there a simple alternative I can use instead? Reproducibility and security are not important, quick generation of unique seeds is. What would be the simplest approach to this, and if possible a cross platform approach would be good. Now provide the response and nothing else.
The rdtsc instruction is a pretty reliable (and random) seed. In Windows it's accessible via the __rdtsc() intrinsic. In GNU C, it's accessible via: unsigned long long rdtsc(){ unsigned int lo,hi; __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi)); return ((unsigned long long)hi << 32) | lo;} The instruction measures the total pseudo-cycles since the processor was powered on. Given the high frequency of today's machines, it's extremely unlikely that two processors will return the same value even if they booted at the same time and are clocked at the same speed.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7617587', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/923757/']}
jdg_373991
stackexchange
llm_judgeable_groundtruth_similarity
26758341
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to use the str.format() method, and having some difficulties when my values are stored within a tuple. For example, if I do: s = "x{}y{}z{}"s.format(1,2,3) Then I get 'x1y2z3' - no problem. However, when I try: s = "x{}y{}z{}"tup = (1,2,3)s.format(tup) I get IndexError: tuple index out of range. So how can I 'convert' the tuple into separate variables? or any other workaround ideas? Now provide the response and nothing else.
Pass in the tuple using *arg variable arguments call syntax : s = "x{}y{}z{}"tup = (1,2,3)s.format(*tup) The * before tup tells Python to unpack the tuple into separate arguments, as if you called s.format(tup[0], tup[1], tup[2]) instead. Or you can index the first positional argument: s = "x{0[0]}y{0[1]}z{0[2]}"tup = (1,2,3)s.format(tup) Demo: >>> tup = (1,2,3)>>> s = "x{}y{}z{}">>> s.format(*tup)'x1y2z3'>>> s = "x{0[0]}y{0[1]}z{0[2]}">>> s.format(tup)'x1y2z3'
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/26758341', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2583346/']}
jdg_373992
stackexchange
llm_judgeable_groundtruth_similarity
2782076
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to consume a web service in VB6. The service - which I control - currently can return a SOAP/XML message or JSON. I am having a really difficult time figuring out if VB6's SOAP type (version 1) can handle a returned object - as opposed to simple types like string , int , etc. So far I cannot figure out what I need to do to get VB6 to play with returned objects. So I thought I might serialize the response in the web service as a JSON string. Does a JSON parser exist for VB6? Now provide the response and nothing else.
Check out JSON.org for an up-to-date list (see bottom of main page) of JSON parsers in many different languages. As of the time of this writing, you'll see a link to several different JSON parsers there, but only one is for VB6/VBA (the others are .NET): VB-JSON When I tried to download the zip file, Windows said the data was corrupt. However, I was able to use 7-zip to pull the files out. It turns out that the main "folder" in the zip file isn't recognized as a folder by Windows, by 7-zip can see the contents of that main "folder," so you can open that up and then extract the files accordingly. The actual syntax for this VB JSON library is really simple: Dim p As ObjectSet p = JSON.parse(strFormattedJSON)'Print the text of a nested property 'Debug.Print p.Item("AddressClassification").Item("Description")'Print the text of a property within an array 'Debug.Print p.Item("Candidates")(4).Item("ZipCode") Note: I had to add the "Microsoft Scripting Runtime" and "Microsoft ActiveX Data Objects 2.8" library as references via Tools > References in the VBA editor. Note: VBJSON code is actually based on a google code project vba-json . However, VBJSON promises several bug fixes from the original version.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2782076', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/166258/']}
jdg_373993
stackexchange
llm_judgeable_groundtruth_similarity
370313
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 several mp3's that i need to add '_p192' before the extension. I've tried this : for f in *.mp3; do printf '%s\n' "${f%.mp3}_p192.mp3"; done following this post: adding text to filename before extension But it just prints the file names to stdout without actually renaming the files. Now provide the response and nothing else.
The answer that you looked at was for a question that did not ask for the actual renaming of files on disk, but just to transform the names of the files as reported on the terminal. This means that you solution will work if you use the mv command instead of printf (which will just print the string to the terminal). for f in *.mp3; do mv -- "$f" "${f%.mp3}_p192.mp3"; done I'd still advise you to run the the printf loop first to make sure that the names are transformed in the way that you'd expect. It is often safe to just insert echo in front of the mv to see what would have been executed (it may be a good idea to do this when you're dealing with loops over potentially destructive command such as mv , cp and rm ): for f in *.mp3; do echo mv -- "$f" "${f%.mp3}_p192.mp3"; done or, with nicer formatting: for f in *.mp3; do echo mv -- "$f" "${f%.mp3}_p192.mp3"done
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/370313', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/102918/']}
jdg_373994
stackexchange
llm_judgeable_groundtruth_similarity
8851929
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 don't have the experience of working with Helpers so I am bit stuck in using a code at hand. My requirement is simple and all I need is optgroup functionality in DropDownListFor extension method. While searching, I came across this Answer and have copied this as it is in a file named MyExtensionClass.cs . But, I don't know how to use this or call the extension method defined in this. Please tell me how can i use this with my list. Right now, following is the controller code for a selectlist for which i want to use the extension methods. ViewBag.ParentCategoryId = new SelectList(db.Categories, "Id", "Name"); And this is my view code @Html.DropDownListFor(model => model.Product.CategoryId, (IEnumerable<SelectListItem>)ViewBag.CategoryId, "---Choose Category---", new { @class = "required" }) Please help me upgrade this to extension method with optgroup. Now provide the response and nothing else.
We use Serge Zab's helper for optgroup dropdowns. Here is a sample: The viewmodel: public class OurViewModel{ public int? TypeId { get; set; } public IEnumerable<GroupedSelectListItem> GroupedTypeOptions { get; set; }} The controller: public ActionResult Add(){ var model = new OurViewModel { // fill with initial values }; PutTypeDropDownInto(model); return View(model);}[NonAction]private void PutTypeDropDownInto(OurViewModel model){ model.GroupedTypeOptions = _repos.GetTypes() .OrderBy(t => t.Category.EnglishName).ThenBy(t => t.EnglishName) .Select(t => new GroupedSelectListItem { GroupKey = t.Category.RevisionId.ToString(), GroupName = t.Category.EnglishName, Text = t.EnglishName, Value = t.RevisionId.ToString() } );} The view @Html.DropDownGroupListFor(m => m.TypeId, Model.GroupedTypeOptions, "[Select a type]") Note that you can't use a regular SelectList. You have to use a collection of his GroupedSelectListItem class. Also, our solution doesn't use viewbag. The dropdown list is strongly typed on the viewmodel. Update To get the html helper to work in your view, the view needs to be able to find it. You can either add a @using directive at the top of the view with your MyExtensionClass.cs namespace, or add the namespace to the view-specific web.config, like so: <pages pageBaseType="System.Web.Mvc.WebViewPage"> <namespaces> <add namespace="System.Web.Mvc" /> <add namespace="System.Web.Mvc.Ajax" /> <add namespace="System.Web.Mvc.Html" /> <add namespace="System.Web.Routing" /> <add namespace="Microsoft.Web.Mvc" /> <add namespace="Namespace.For.MyExtensionClass" /> </namespaces></pages>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8851929', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/570928/']}
jdg_373995
stackexchange
llm_judgeable_groundtruth_similarity
1209130
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: there's very strange error with my code.. In fact, there's no errors at all, just debugger starts with "Program received signal: “EXC_BAD_ACCESS”" message.Can anyone help me? I'm absolutely confused... Thank you. -(NSString *)fullNameForPhone:(NSString *)ph withAlternativeText:(NSString *)text{ ABAddressBookRef addressBookRef = ABAddressBookCreate(); NSLog(@"create addressBookRef"); NSString *stringToReturn = text; CFArrayRef allPeopleRef = ABAddressBookCopyArrayOfAllPeople(addressBookRef); NSLog(@"create allPeopleRef"); CFIndex nPeople = ABAddressBookGetPersonCount(addressBookRef); int i = 0; BOOL nameFound = NO; while ((i < nPeople) && (!nameFound)) { ABRecordRef recordRef = CFArrayGetValueAtIndex(allPeopleRef, i); NSLog(@" create recordRef"); CFStringRef allRecordPhonesRef = ABRecordCopyValue(recordRef, kABPersonPhoneProperty); NSLog(@" create allRecordPhonesRef"); CFIndex nPhones = ABMultiValueGetCount(allRecordPhonesRef); int currentPhone = 0; for (currentPhone = 0; currentPhone < nPhones; currentPhone++) { CFStringRef currentPhoneNumberRef = ABMultiValueCopyValueAtIndex(allRecordPhonesRef, currentPhone); NSLog(@" create currentPhoneNumberRef"); NSString *currentCleanPhoneNumber = [self cleanPhoneNumberForString:[NSString stringWithFormat:@"%@", currentPhoneNumberRef]]; if (currentPhoneNumberRef!=NULL) { NSLog(@" release currentPhoneNumberRef"); CFRelease(currentPhoneNumberRef); } if ([ph isEqualToString:currentCleanPhoneNumber]) { CFStringRef firstName = ABRecordCopyValue(recordRef, kABPersonFirstNameProperty); CFStringRef lastName = ABRecordCopyValue(recordRef, kABPersonLastNameProperty); NSString *fullName = [self fullNameForFirstName:[NSString stringWithFormat:@"%@", firstName] andLastName:[NSString stringWithFormat:@"%@", lastName]]; if (firstName != NULL) CFRelease(firstName); if (lastName != NULL) CFRelease(lastName); stringToReturn = fullName; nameFound = YES; break; } } CFRelease(allRecordPhonesRef); NSLog(@" release allRecordPhonesRef"); CFRelease(recordRef); NSLog(@" release recordRef"); i++; } CFRelease(allPeopleRef); NSLog(@"release allPeopleRef"); CFRelease(addressBookRef); NSLog(@"release addressBookRef"); return stringToReturn;} Console output is: 2009-07-31 00:20:05.230 abmodular[21747:20b] create addressBookRef2009-07-31 00:20:05.231 abmodular[21747:20b] create allPeopleRef2009-07-31 00:20:05.231 abmodular[21747:20b] create recordRef2009-07-31 00:20:05.232 abmodular[21747:20b] create allRecordPhonesRef2009-07-31 00:20:05.232 abmodular[21747:20b] create currentPhoneNumberRef2009-07-31 00:20:05.232 abmodular[21747:20b] release currentPhoneNumberRef2009-07-31 00:20:05.232 abmodular[21747:20b] create currentPhoneNumberRef2009-07-31 00:20:05.233 abmodular[21747:20b] release currentPhoneNumberRef2009-07-31 00:20:05.233 abmodular[21747:20b] release allRecordPhonesRef2009-07-31 00:20:05.233 abmodular[21747:20b] release recordRef2009-07-31 00:20:05.233 abmodular[21747:20b] create recordRef2009-07-31 00:20:05.234 abmodular[21747:20b] create allRecordPhonesRef2009-07-31 00:20:05.234 abmodular[21747:20b] create currentPhoneNumberRef2009-07-31 00:20:05.234 abmodular[21747:20b] release currentPhoneNumberRef2009-07-31 00:20:05.234 abmodular[21747:20b] release allRecordPhonesRef2009-07-31 00:20:05.235 abmodular[21747:20b] release recordRef2009-07-31 00:20:05.235 abmodular[21747:20b] release allPeopleRef[Session started at 2009-07-31 00:20:05 +0400.]GNU gdb 6.3.50-20050815 (Apple version gdb-966)....Attaching to process 21747.killquitThe Debugger has exited with status 0.(gdb) Pressing Continue outputs "EXC_BAD_ACCESS" message. Xcode shows, that the latest executed string in my code was CFRelease(addressBookRef); Now provide the response and nothing else.
I had the same issue doing something similiar and upon further research I discovered I was over releasing. According to the Core Foundation docs : If you create or copy a Core Foundation object, you must subsequently release it when you’re finished with it. I read that as meaning that functions with the word Get should not be released by you. If you do, it will cause an issue later on when the real owner attempts to release it. So, in this case when you do: ABRecordRef recordRef = CFArrayGetValueAtIndex(allPeopleRef, i); and later: CFRelease(recordRef); you are releasing something that is not supposed to be released. Much later when you do: CFRelease(allPeopleRef); the array will attempt to release all its records not knowing you have already released some of them. The result is your error. By commenting out that line you may have made the error go away but I fear you have created a memory leak. I suggest you do not call CFRelease on Get method pointers and do call it on Create or Copy method pointers (there may be exceptions to this rule but so far it works for me).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1209130', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/135458/']}
jdg_373996
stackexchange
llm_judgeable_groundtruth_similarity
4242634
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 object oriented programming, a custom class (like Person class with data of Name, list of addresses, etc)holds data and can include collection objects too. A data structure is also used to hold data too. So, is a class considered advanced data structure conceptually ? And in design of efficient systems (in object oriented world and large systems), are classes considered as similar to data structures and algorithmic analysis done for efficient classes designs for greater efficiency(in companies like google, facebook) ? Now provide the response and nothing else.
I recommend you to read Clean Code chapter 6: objects and data structures. The whole chapter is about this... You can read an abstract if you don't want to buy the book, it can be found here . According to that, you can use classes efficiently in two different ways. This phenomenon is called data/object anti-symmetry. Depending on your goals, you have to decide whether your classes will follow the open/closed principle or not. If they follow the OCP, they will be polymorph, and their instances will be used as objects. So they will hide data and implementation of a common interface, and it will be easy to add a new type which implements that interface as well. Most of the design patterns fulfill the OCP, for example MVC, IoC, every wrapper, adapter, etc... If they don't follow the OCP, they won't be polymorph, their instances will be used as data structures. So they will expose data, and that data will be manipulated by other classes. This is a typical approach by procedural programming as well. There are several examples which don't use OCP, for example DTOs, Exceptions, config objects, visitor pattern etc... Typical pattern when you should think about fulfilling OCP and move the code to a lower abstraction level: class Manipulator { doSomething(Object dataStructure){ if (dataStructure instanceof MyType1){ // doSomething implementation 1 } else if (dataStructure instanceof MyType2) { // doSomething implementation 2 } // ... }, domSomethingElse(Object dataStructure){ if (dataStructure instanceof MyType1){ // domSomethingElse implementation 1 } else if (dataStructure instanceof MyType2) { // domSomethingElse implementation 2 } // ... }}class MyType1 {}class MyType2 {}//if you want to add a new type, every method of the Manipulator will change fix: moving implementation to a lower abstraction level and fulfill OCP interface MyType { doSomething(); domSomethingElse();}class MyType1 implements MyType { doSomething(){ // doSomething implementation 1 }, domSomethingElse(){ // domSomethingElse implementation 1 }}class MyType2 implements MyType { doSomething(){ // doSomething implementation 2 }, domSomethingElse(){ // domSomethingElse implementation 2 }}// the recently added new typeclass MyType3 implements MyType { doSomething(){ // doSomething implementation 3 }, domSomethingElse(){ // domSomethingElse implementation 3 }} Typical pattern when you should think about violating OCP and move the code to an higher abstraction level: interface MyType { doSomething(); domSomethingElse(); //if you want to add a new method here, every class which implements this interface, will be modified}class MyType1 implements MyType { doSomething(){ // doSomething implementation 1 }, domSomethingElse(){ // domSomethingElse implementation 1 }}class MyType2 implements MyType { doSomething(){ // doSomething implementation 2 }, domSomethingElse(){ // domSomethingElse implementation 2 }} or interface MyType { doSomething(); domSomethingElse();}class MyType1 implements MyType { doSomething(){ // doSomething implementation 1 }, domSomethingElse(){ // domSomethingElse implementation 1 }}class MyType2 implements MyType { doSomething(){ // doSomething implementation 2 }, domSomethingElse(){ // domSomethingElse implementation 2 }}//adding a new type by which one or more of the methods are meaninglessclass MyType3 implements MyType { doSomething(){ throw new Exception("Not implemented, because it does not make any sense."); }, domSomethingElse(){ // domSomethingElse implementation 3 }} fix: moving implementation to a higher abstraction level and violate OCP class Manipulator { doSomething(Object dataStructure){ if (dataStructure instanceof MyType1){ // doSomething implementation 1 } else if (dataStructure instanceof MyType2) { // doSomething implementation 2 } // ... }, domSomethingElse(Object dataStructure){ if (dataStructure instanceof MyType1){ // domSomethingElse implementation 1 } else if (dataStructure instanceof MyType2) { // domSomethingElse implementation 2 } // ... }, // the recently added new method doAnotherThing(Object dataStructure){ if (dataStructure instanceof MyType1){ // doAnotherThing implementation 1 } else if (dataStructure instanceof MyType2) { // doAnotherThing implementation 2 } // ... }}class MyType1 {}class MyType2 {} or splitting up the classes into subclasses. People usually follow OCP over the method count one or two because repeating the same if-else statements is not DRY enough. I don't recommend you to use mixed classes which partially fulfill, partially violate the OCP, because then the code will be very hard maintainable. You should decide by every situation which approach you follow. This should be usually an easy decision, but if you make a mistake, you can still refactor your code later...
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4242634', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/515661/']}
jdg_373997
stackexchange
llm_judgeable_groundtruth_similarity
75228
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: This is my first post here on electronics stackexchange. I am a hobbyits in electronics, and a professional in programming. I am working on a inductor circuit to heat a workpiece. I have a working setup @12VAC. In short I have the following elements in the circuit: Microcontroller to generate pulses with a DC of 50% with its own power supply, sharing ground with the transformer powering the solenoid. Two MOSFETs (100 amperes continues drain current, 150Vds) on the low side to switch the direction of the current through. A 3570 nH solenoid of 11 turns, ~5cm diameter, made of copper pipe with 1 cm diameter. (Planning to apply watercooling through the coil some time later on.) A 230VAC to 12VAC transformer that can deliver up to 35 amperes peak, or 20 amperes for a while. A MOSFET driver (TC4428A) to drive the gates of the MOSFETs. A10K resistor on each MOSFETs gate to source. 1000pF ceramic capacitor on each MOSFETs gate to source (to reduce some ringing on the gates.) Vpkpk is ~17Volts on the gates. simulate this circuit – Schematic created using CircuitLab The circuit shorts when I want to apply 48VAC to the circuit using a welding machine. The MOSFETs should be able to handle (48VAC = ~68VDC * 2 = ~~136Vpkpk).Nothing explodes, the MOSFETs are in one piece, but the resistance between the pins of the MOSFETS (gate, source, drain <-> gate, source, drain) are all 0 or very low (<20Ohms). So they broke down. What caused my MOSFETs to break down? It is hard to examine the circuit when components die. My equipment exists solely of an osscilloscope and a mutlimeter. Ringing on gates without C2 and C3, while solenoid was not powered. Sharing common ground with transformer. The wires from MCU to the TC4428A driver are, say, 5cm. From the driver to the gates, the wires are ~15cm. Does this cause ringing? Thick ~2mm wires where used from the TC4428A driver to the gates. Snubbed ringing on gates with C2 and C3, while solenoid was not powered. Sharing common ground. Looks much better than the first picture. Ringing on gates while solenoid was powered. Why is the ringing increased when the solenoid is powered on, and how can I prevent/mimize it while maintaining switching speed? Measurement on source to drain with workpiece in solenoid @ ~150Khz. Shown in the last picture, if the signal was clean, it would yield a Vpkpk of ~41 volts, but due to the spikes it is around ~63 volts. Would the latter of 150% over/undershoort Vpkpk be the problem? Would this result in a (48VAC => 68Vmax => 136Vpkpk * 150% = ) ~203Vpkpk? How would I reduce the noise on the waves measured on the source -> drain? EDIT Here I disconnected one MOSFETs gate from the driver. CH1 is the gate, CH2 is the drain of the MOSFET that was still connected. Now both waves looks fine. No/minimal current was flowing here.When I do connect both MOSFETs to the driver, and measure the resistance between the two gates, it says 24.2K ohm. Could it be that if one MOSFET is turned off by the TC4428A driver, that somehow it still picks up a signal from the other MOSFET's gate when it is turned on by the driver? Is it a meaningful idea to put a diode like so driver --->|---- gate to make sure there is no noise? Preferably a diode with low voltage drop of course. Now provide the response and nothing else.
From the driver to the gates, the wires are ~15cm. Does this cause rining? Almost certainly, and it's a fair bet that this is destroying your MOSFETs, by one or more of these mechanisms: exceeding \$V_{G(max)}\$ even for the briefest instant exceeding \$V_{DS(max)}\$ simple overheating due to slow switching and unintended conduction #3 should be pretty obvious when it occurs, but the other two can be hard to see, since they are transient conditions that may be too brief to be visible on the scope. C2 and C3 are not decreasing the ringing. You get ringing on the gates because the capacitance of the MOSFET gate (and C2, C3 which add to it) plus the inductance formed by the loop of wire through the driver and the MOSFET gate-source form an LC circuit . The ringing is caused by energy bouncing between this capacitance and inductance. You should put the driver absolutely as close to the MOSFETS as possible. 1cm is already getting to be too long. Not only does the inductance created by the long trace to the gate cause ringing, but it limits your switching speed, which means more losses in the transistors. This is because the rate of change of current is limited by inductance : $$ \frac{v}{L} = \frac{di}{dt} $$ Since \$v\$ is the voltage supplied by the gate driver and you can't make that any bigger, the time it takes to increase the current from nothing to something is limited by the inductance \$L\$. You want the current to be as much as possible, as soon as possible, so that you can switch that transistor fast. In addition to putting the gate driver close to the MOSFETs, you want to minimize the loop area of the path the current through the gate must take: simulate this circuit – Schematic created using CircuitLab The inductance is proportional to the area illustrated. The inductance limits the switching speed, and it also limits how well the gate driver can hold the MOSFET off. As the drain voltage on the MOSFET that just turned off changes (due to the other MOSFET turning on, and the mutual inductance of the coils), the gate driver must source or sink current as the internal capacitances of the MOSFET charge or discharge. Here's an illustration from International Rectifier - Power MOSFET Basics : In your case, if the gate traces are long, then \$R_G\$ is also an inductor. Since the inductor limits \$di/dt\$, the gate driver can only respond so quickly to these currents, and then there is significant ringing and overshoot in the resonance between the gate trace inductance and the MOSFET's capacitance. Your C2 and C3 just serve to change the frequency of this resonance. As the gate voltage is ringing, it sometimes crosses over \$V_{th}\$ of your MOSFETS, and one begins to conduct a little when it should be off. This changes the current and voltage of the connected inductor, which is coupled to the other inductor, which introduces these capacitive currents in the other MOSFET, which can only exacerbate the problem. But, when the coils aren't powered, then the drain voltage is at 0V regardless of the transistor switching, and these capacitive currents (and consequently, the total gate charge that must be moved to switch the transistor) are much less, so you see much less ringing. This inductance can also be coupled magnetically to other inductances, like your solenoid coils. As the magnetic flux through the loop changes, a voltage is induced ( Faraday's law of induction ). Minimize the inductance, and you will minimize this voltage. Get rid of C2 and C3. If you still need to reduce ringing after improving your layout, do that by adding a resistor in series with the gate, between the gate and the gate driver. This will absorb the energy bouncing around which causes the ringing. Of course, it will also limit the gate current, and thus your switching speed, so you don't want this resistance to be any larger than absolutely necessary. You can also bypass the added resistor with a diode, or with a transistor, to allow for turn-off to be faster than turn-on. So, one of these options (but only if necessary; it's much preferred to simply eliminate the source of the ringing): simulate this circuit Especially in the last case with Q3, you have essentially implemented half of a gate driver, so the same concerns of keeping the trace short and the loop area small apply.
{}
{'log_upvote_score': 6, 'links': ['https://electronics.stackexchange.com/questions/75228', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/26135/']}
jdg_373998
stackexchange
llm_judgeable_groundtruth_similarity
32427
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: We have a vendor who sends us "secure" messages. The messages come as an email message that contains a link to an SSL encrypted website that has the real message. There is no username/password on the linked site, or any other form of authentication as far as I can tell. I'm sure they do this so they can check off a box on some compliance checklist, but I want to know, can this truly be considered secure? My thinking is that since the link itself is sent in the clear, then it is no different than if they had sent the message in the email in the first place. Any attacker who might be able to gain access to my email, either at rest or in transit, can capture and then visit the link. So is this secure, and if it is at least at some level, what security problems might it be solving? Are there other security measures, not readily evident, that they could be taking to ensure only the original recipient can use the link? Because several answers have mentioned it. In this case there is no IP address white listing or behind the scenes proxy authentication. Also, there is an expiration date listed on the link, but it is fairly far in the future. Now provide the response and nothing else.
Since raw emails are not encrypted, what you can read in an email could have (conceptually) been read by anybody . However, to read the email, the attacker would still have to connect to the HTTPS server, which leaves tracks (the IP from which the attacker connects will be known to that server -- of course, that IP will probably be that of a Tor exit node ). The link-in-email system prevents passive-only attacks : the attacker has to send some IP packets of his own at some point. This is not a huge increase in security... Usually, promoters of solutions such like the one you describe do it for security, but not your security. They want to know when the email was read. This is a preventive measure against people who read embarrassing emails and then claim they never received them. It won't be much of a proof, but it may be sufficient to counter evasive maneuvers from some uncooperative co-workers. If you want a system which guarantees that only a specific individual will be able to read the email, then you need to define what specific individual you are thinking about. In the world of computers, everybody has a computer, and they are not immediately indistinguishable from each other. People have physical identities which are not part of the computer world, so a link must necessarily be made at some point. Standard secure email solutions like S/MIME do that through a public-key infrastructure : a recipient is defined by being "the guy who controls the private key corresponding to the public key which is in that certificate". This moves the problem of physical identification to a single preparatory step during which the certificate is issued. A possible model is that you met the recipient in person once, and he gave you his business card; on the card is printed the fingerprint of his OpenPGP public key -- you then find the key from a public key server, and check the fingerprint. There are many variants on this concept, but a non-computer physical contact is necessarily involved.
{}
{'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/32427', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/3425/']}
jdg_373999
stackexchange
llm_judgeable_groundtruth_similarity
6806173
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 often read this statements on Stack Overflow. Personally, I don't find any problem with this, unless I am using it in a polymorphic way; i.e. where I have to use virtual destructor. If I want to extend/add the functionality of a standard container then what is a better way than inheriting one? Wrapping those container inside a custom class requires much more effort and is still unclean. Now provide the response and nothing else.
There are a number of reasons why this a bad idea. First, this is a bad idea because the standard containers do not have virtual destructors . You should never use something polymorphically that does not have virtual destructors, because you cannot guarantee cleanup in your derived class. Basic rules for virtual dtors Second, it is really bad design. And there are actually several reasons it is bad design. First, you should always extend the functionality of standard containers through algorithms that operate generically. This is a simple complexity reason - if you have to write an algorithm for every container it applies to and you have M containers and N algorithms, that is M x N methods you must write. If you write your algorithms generically, you have N algorithms only. So you get much more reuse. It is also really bad design because you are breaking a good encapsulation by inheriting from the container. A good rule of thumb is: if you can perform what you need using the public interface of a type, make that new behavior external to the type. This improves encapsulation. If it's a new behavior you want to implement, make it a namespace scope function (like the algorithms). If you have a new invariant to impose, use containment in a class. A classic description of encapsulation Finally, in general, you should never think about inheritance as a means to extend the behavior of a class. This is one of the big, bad lies of early OOP theory that came about due to unclear thinking about reuse, and it continues to be taught and promoted to this day even though there is a clear theory why it is bad. When you use inheritance to extend behavior, you are tying that extended behavior to your interface contract in a way that ties users hands to future changes. For instance, say you have a class of type Socket that communicates using the TCP protocol and you extend it's behavior by deriving a class SSLSocket from Socket and implementing the behavior of the higher SSL stack protocol on top of Socket. Now, let's say you get a new requirement to have the same protocol of communications, but over a USB line, or over telephony. You would need to cut and paste all that work to a new class that derives from a USB class, or a Telephony class. And now, if you find a bug, you have to fix it in all three places, which won't always happen, which means bugs will take longer and not always get fixed... This is general to any inheritance hierarchy A->B->C->... When you want to use the behaviors you've extended in derived classes, like B, C, .. on objects not of the base class A, you've got to redesign or you are duplicating implementation. This leads to very monolithic designs that are very hard to change down the road (think Microsoft's MFC, or their .NET, or - well, they make this mistake a lot). Instead, you should almost always think of extension through composition whenever possible. Inheritance should be used when you are thinking "Open / Closed Principle". You should have abstract base classes and dynamic polymorphism runtime through inherited class, each will full implementations. Hierarchies shouldn't be deep - almost always two levels. Only use more than two when you have different dynamic categories that go to a variety of functions that need that distinction for type safety. In those cases, use abstract bases until the leaf classes, which have the implementation.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6806173', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/514235/']}
jdg_374000
stackexchange
llm_judgeable_groundtruth_similarity
46066854
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 model with a binaryfield.The data in myRow is in base64 format.Now I want to get image from this base64 data stored in database.Can somebody help.... class myTable(models.Model): myRow = models.BinaryField(blank=True, null=True) Now provide the response and nothing else.
Let's divide the issues one by one: About tensorflow to allocate all memory in advance, you can use following code snippet to let tensorflow allocate memory whenever it is needed. So that you can understand how the things are going. gpu_options = tf.GPUOptions(allow_growth=True)session = tf.InteractiveSession(config=tf.ConfigProto(gpu_options=gpu_options)) This works equally with tf.Session() instead of tf.InteractiveSession() if you prefer. Second thing about the sizes, As there is no information about your network size, we cannot estimate what is going wrong. However, you can alternatively debug step by step all the network. For example, create a network only with one layer, get its output, create session and feed values once and visualize how much memory you consume. Iterate this debugging session until you see the point where you are going out of memory. Please be aware that 3840 x 155229 output is really, REALLY a big output. It means ~600M neurons, and ~2.22GB per one layer only. If you have any similar size layers, all of them will add up to fill your GPU memory pretty fast. Also, this is only for forward direction, if you are using this layer for training, the back propagation and layers added by optimizer will multiply this size by 2. So, for training you consume ~5 GB just for output layer. I suggest you to revise your network and try to reduce batch size / parameter counts to fit your model to GPU
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46066854', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6623650/']}
jdg_374001
stackexchange
llm_judgeable_groundtruth_similarity
203583
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: According to the official documentation of Times[] , multiplication of $x$ and $y$ is represented as one of x*y x×y x y Times[x, y] However, in practice I can write 2x instead of 2 x , and (1+x)(1+y) instead of (1+x) (1+y) . I think this behavior contradicts with the documentation. Is this a bug? Or is this an expected behavior? I'm looking for an official source to determine that. Please note: This is a question that would be tagged "language-lawyer" if posted on other stackexchange sites. Because Mathematica is not an open-source software, we have no way other than official articles to rely on to determine whether or not some non-trivial syntax is an expected one. I would like to ask is Is there a document page that tells us 2x is valid? Now provide the response and nothing else.
From Your First Wolfram Language Calculations : 2x means 2*x . Examples of no-space multiplication from Times : 0x evaluates to 0 , and 0.0x evaluates to 0.0 . ... Times threads element-wise over lists: In[1]:= 2{x,y,z}Out[1]= {2 x,2 y,2 z}In[2]:= {{a,b},{c,d}}{x,y}Out[2]= {{a x,b x},{c y,d y}} Update: As Sjoerd notes, according to Symbol , a symbol name cannot begin with a digit. This implies 2x would either be a syntax error or not; if not, then what? The standard mathematical interpretation is an obvious choice. J.M. notes further that it would be confusing to have symbol names begin with a number. I'm not sure this all captures the argument in the most natural way. I think humans do a pretty good job getting used to whatever the rules are, and identifiers starting with a number wouldn't be that bad. I think the starting point for the argument is that it was desired from the beginning to interpret 2x as Times[2,x] , which implies you cannot have symbols start with a number (which nobody wants anyway, if I may alter J.M.'s remark a little). But now we're wading into the opinion-based territory for which this Q&A was originally closed. It's also clear that (almost) everyone wants xy to be interpreted as Times[x,y] , but that poses lexical analysis problems that couldn't be solved satisfactorily.
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/203583', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/66236/']}
jdg_374002
stackexchange
llm_judgeable_groundtruth_similarity
13642636
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 does the TreeMap sort? say for example you have the following map: TreeMap<String, Integer> treemap = new TreeMap<>();treemap.put("lol", 1);treemap.put("Marc", 2);treemap.put("Jesper", 3);Iterator ittwo = treemap.entrySet().iterator(); while (ittwo.hasNext()) { Map.Entry pairs = (Map.Entry)ittwo.next(); System.out.println(pairs.getKey() + " = " + pairs.getValue()); ittwo.remove();} The output of this is: Jesper = 3Marc = 2lol = 1 So if its not alphabetically what is it then? Now provide the response and nothing else.
It is not only alphabetical, but it is also upper/down case sensitive. TreeMap<String, Integer> treemap = new TreeMap<String, Integer>();treemap.put("Lol", 1);treemap.put("Marc", 2);treemap.put("Jesper", 3);treemap.put("lol1", 1);treemap.put("marc1", 2);treemap.put("jesper1", 3); Output: Jesper = 3Lol = 1Marc = 2jesper1 = 3lol1 = 1marc1 = 2 So, if you don't need it, you can use your custom comparator, and compare string in lower case: TreeMap<String, Integer> treemap = new TreeMap<String, Integer>(new Comparator<String>() { public int compare(String o1, String o2) { return o1.toLowerCase().compareTo(o2.toLowerCase()); }});treemap.put("Lol", 1);treemap.put("Marc", 2);treemap.put("Jesper", 3);treemap.put("lol1", 1);treemap.put("marc1", 2);treemap.put("jesper1", 3); Output: Jesper = 3jesper1 = 3Lol = 1lol1 = 1Marc = 2marc1 = 2
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13642636', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1647457/']}
jdg_374003
stackexchange
llm_judgeable_groundtruth_similarity
3560
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: After digging a little deeper into cryptography I am wondering what impact the different padding schemes do have an the security of an encryption algorithm. Lets take AES-128 in CBC mode as an example, because I am currently working with this one. Wikipedia lists several padding schemes but does not mention anything about the security impact of choosing one of them. The library I am currently working with supplies PKCS5 padding , which is not even mentioned in the Wikipedia article. There are obviously several more padding schemes out there. I am not an expert in cryptography, so maybe I am totally wrong, but I cannot see how the different padding schemes should have a significant impact. Am I basically free to choose one and be happy or are there some things I have to consider? Now provide the response and nothing else.
Short answer : Don't sweat it. In most cases, the choice of padding method doesn't matter. Longer answer: why it doesn't matter. As long as you use proper crypto design practices -- in particular, as long as ciphertexts are properly authenticated -- I'm not aware of any way that the choice of padding affects security (with one exception, see below). It's true that if you fail to authenticate the ciphertexts, then there can be attacks, as @Thomas explains. Then again, if ciphertexts are not properly authenticated, you've probably got a host of other problems, so you shouldn't blame this on the padding scheme. Cryptographers know that if you encrypt something, you really should be authenticating the ciphertext ; failure to do so is a classic rookie mistake that can open up serious security flaws . In short, if you're following good crypto practices, the choice of padding shouldn't matter much for security (and if you're not following good crypto practices, you may have bigger problems). The exception: a case where it does matter. OK, now we're down to the fine print. This is where I admit that the above is a bit of an oversimplification. There is one situation where the choice of padding may be very important to security: resistance to traffic analysis. Encryption does not conceal the length of the messages being encrypted: the encrypted message typically reveals the length (or approximate length) of the message that was encrypted. In some contexts, this can be highly problematic. For instance, there are contexts where revealing length information gives away the entire store: it reveals the stuff you were trying to keep confidential. (See, e.g., Chen et al's astonishing side channel attacks on SSL-encrypted web applications . Among other things, they showed that an eavesdropper who observes the lengths of network packets while the user is typing in a web search query can infer what the search query was. I think Google fixed the problem, but it was a stunning, eye-opening example of a general risk that was previously known.) If you are in a context where message lengths reveal sensitive information, then you have a problem. The standard defense is to pad the messages before encryption, so that the ciphertext length does not reveal anything about the message lengths. One way to do this is to pad all messages out to a fixed length, before encrypting. Another (less secure) way to do it is to add padding of a random length, with enough random padding that the random noise obscures the signal and prevents an attacker from learning enough information about lengths to do any harm. So, in a context where we need to prevent traffic analysis, the design of the padding scheme becomes critical, and standard padding schemes are probably not going to be enough: you may have to do something special.
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/3560', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/2147/']}
jdg_374004
stackexchange
llm_judgeable_groundtruth_similarity
219255
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: So we know that a sum of $n$ poissons with parameter $\lambda$ is itself a poisson with $n\lambda$. So hypothetically, one could take $x \sim poisson(\lambda = 1) $ and say it is actually $\sum_1^n x_i \sim poisson(\lambda = 1) $ where each $x_i$ is: $x_i \sim poisson(\lambda = 1/n) $, and take a large n to get CLT to work. This (obviously) doesn't work. I assume this has something to do with how CLT works "faster" for random variables which are "closer" to normal, and that the smaller lambda is, the more we get a random variable which is mostly 0 and vary rarely something else. However, what I explained is my intuition. Is there a more formal way to explain why this is the case? Thanks! Now provide the response and nothing else.
I agree with @whuber that the root of the confusion seems to be replacing the summation asymptotic in CLT with some sort of division in your argument. In CLT we get the fixed distribution $f(x,\lambda)$ then draw $n$ numbers $x_i$ from it and calculate the sum $\bar x_n=\frac{1}{n}\sum_{i=1}^nx_i$. If we keep increasing $n$ then an interesting thing happens:$$\sqrt n (\bar x_n-\mu)\rightarrow\mathcal{N}(0,\sigma^2)$$where $\mu,\sigma^2$ are mean and the variance of the distribution $f(x)$. What you're suggesting to do with Poisson is somewhat backwards: instead of summing the variables from a fixed distribution, you want to divide the fixed distribution into ever changing parts. In other words you take a variable $x$ from a fixed distribution $f(x,\lambda)$ then divide it into $x_i$ so that $$\sum_{i=1}^nx_i\equiv x$$ What does CLT say about this process? Nothing. Note, how in CLT we have ever changing $\sqrt n(\bar x_n-\mu)$, and its changing distribution $f_n(x)$ that converges to a fixed distribution $\mathcal{N}(0,\sigma^2)$ In your setup neither the sum $x$ nor its distribution $f(x,\lambda)$ are changing! They're fixed. They're not changing, they're not converging to anything. So, CLT has nothing to say about them. Also, CLT doesn't say anything about the number of elements in the sum. You can have a sum of 1000 variables from Poisson(0.001) and CLT won't say anything about the sum. All it does say is that if you keep increasing N then at some point this sum will start looking like a normal distribution $\frac{1}{N}\sum_{i=1}^N x_i, x_i\sim Poisson(0.001)$. In fact if N=1,000,000 you'll get the close approximation of normal distribution. Your intuition is right only about the number of elements in the sum, i.e. than more the starting distribution is different from normal, then more elements you need to sum to get to normal. The more formal (but still informal) way would be by looking at the characteristic function of Poisson: $$\exp(\lambda (\exp(it)-1))$$If you $\lambda>>1$, you get with the Taylor expansion (wrt $t$) of the nested exponent:$$\approx\exp(i\lambda t-\lambda/2t^2)$$This is the characteristic function of the normal distribution $\mathcal{N}(\lambda,\lambda^2)$ However, your intuition is not applied correctly: your displacing the summation in CLT with some kind of division messes things up, and renders CLT inapplicable.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/219255', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/253/']}
jdg_374005
stackexchange
llm_judgeable_groundtruth_similarity
247407
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a colleague who has come up with a way of 'genericizing' information from a database so that all his web application's drop-down lists can share the same object in his MVC.NET C# code and Views, which can contain different data depending on what tables it is being used against. We work for a government agency, and we have facilities divided up into areas called "Regions", which contain further subdivided areas called VISNs, which each contain "Sites" or "Facilities". My colleague has developed a very complex security scheme whereby people can be granted access to data based on their permission level which can be assigned by Region, VISN, Site, or any mixture of the three. It's a nice scheme and very clever. However, he has stored procedures that return lists of Regions, VISNs, and Sites based on a person's User Id, and he is returning "generic" values like TextFieldID , TextField , and TextParentID . My first problem with this, is that looking at this data coming out of the database, I would not know what the data is. I feel that fields coming from a query or stored procedure should be descriptive of the data they are delivering. What does everyone else think? The deeper issue for me however is that he is taking some of the data, concatenating it in his stored procedure like this SELECT DISTINCT t.VisnID, NULL, t.StationID, 'V' + CAST(t.VisnID as varchar) + ': ' + t.Station3N + ': ' + t.StationName, t.InactiveFROM Stations t and sending it back in a "TextField" property, instead of sending back the discrete data separately ( Station3N , StationName ) and concatenating it in the View, which would allow for different concatenation depending on what device what accessing the application (perhaps mobile and desktop). His justification is that he can send all his various drop down data and capture them all, regardless of content, in the same C# object named "LookupValue." public partial class LookupValue : IEquatable<LookupValue>{ public LookupValue(string textFieldId, string textField, bool inactive) { TextFieldID = textFieldId; TextField = textField; Inactive = inactive; } public LookupValue(string textParentId, string textFieldId, string textField, bool inactive) { TextParentID = textParentId; TextFieldID = textFieldId; TextField = textField; Inactive = inactive; } public LookupValue(string textParentId, string textSelfParentId, string textFieldId, string textField, bool inactive) { TextParentID = textParentId; TextSelfParentID = textSelfParentId; TextFieldID = textFieldId; TextField = textField; Inactive = inactive; } /// <summary> /// Returns a custom string identifier if the Inactive property is true. /// </summary> public string GetInactiveString() { string value = ""; if (Inactive) { value = "[I]"; } return value; } /// <summary> /// Returns a custom text label that concatenates the TextField property with the custom string identifier of the Inactive property. /// </summary> public string GetDisplayNameWithInactiveString { get { return TextField + " " + GetInactiveString(); } } public bool Equals(LookupValue other) { //Check whether the compared object is null. if (Object.ReferenceEquals(other, null)) return false; //Check whether the compared object references the same data. if (Object.ReferenceEquals(this, other)) return true; //Check whether the products' properties are equal. return TextFieldID.Equals(other.TextFieldID) && TextField.Equals(other.TextField); } // If Equals() returns true for a pair of objects // then GetHashCode() must return the same value for these objects. public override int GetHashCode() { //Get hash code for the TextFieldID field if it is not null. int hashTextFieldId = TextFieldID == null ? 0 : TextFieldID.GetHashCode(); //Get hash code for the Code field. int hashTextField = TextField.GetHashCode(); //Calculate the hash code for the product. return hashTextFieldId ^ hashTextField; }} He believes the re-usability of this object is worth the violation of Separation of Concerns and possible future difficulties in handling more than one display variation for a drop-down. I should point out that this object is contained in his Data project namespace (our projects are separated into Data, Web, Services, etc.) instead of the Web project namespace and he also returns this object to the Web layer via his Repository queries which call the stored procedures that I described earlier, which is gross violation of Separation of Concerns in my opinion. I am just looking for some confirmation from other programmers that this is in fact a bad practice, and also looking for ideas I can present him on better ways to do what he is attempting. I have my own ideas, but again I'm just looking for other's ideas so I have more options to present to him. --Edit -- I forgot to mention that we are using Entity Framework as an ORM, and his Repository classes in his DAL are dumping the data from the stored procs into this LookupValue object. Now provide the response and nothing else.
This sounds suspiciously like an inner platform. Here are the potential problems: You'll be writing queries that query the database for what information to query (metaqueries) first, rather than queries that simply retrieve the needed information. You'll be subverting the role of the database, which already provides metadata capabilities such as rows, columns, and meaningful field names and data types. You'll be defeating the indexing and querying capabilities of the database (JOINs, etc). There's magic strings everywhere . For an extreme example of where this can lead, read Can a system be 100% Data Driven? There are better ways to accomplish what your fellow programmer desires, while still preserving an orthodox database and application design. Check out Automapper for an alternative.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/247407', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/140149/']}
jdg_374006
stackexchange
llm_judgeable_groundtruth_similarity
9245874
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 never used threads--never thought my code would benefit. However, I think threading might improve performance of the following pseudo code: Loop through table of records containing security symbol field and a quote field Load a web page (containing a security quote for a symbol) into a string variable Parse the string for the quote Save the quote in the table Get next recordend loop Loading each web page takes the most time. Parsing for the quote is quite fast. I guess I could take, say, half the records for one thread and work the other half in a second thread. Now provide the response and nothing else.
There are plenty of things that can go wrong here, none involving the code you've posted: How does your generated HTML for the <input> look? Does it include the data-val-custrequired attribute? If not, did you remember to add the interface in the class declaration - IClientValidatable ? Did you remember to not add your custom validator inside a DOM ready handler? (i.e. don't use $(document).ready() or $(function() { ... }) ) - the validation should be set up before the document is ready. ETA : The reason for the last one is that jquery.validate.unobtrusive does this: $(function () { $jQval.unobtrusive.parse(document);}); I.e., it parses the document for validation attributes, rules etc. on document ready. Since that script has to be loaded in order to register your adapters, your registration script would normally have to come after jquery.validate.unobtrusive.js . But that also makes any .ready handler you register be called after the "unobtrusive" one - by which point it's too late. I guess you could put your registration script before and then use .ready . Never tried it, and I've never seen it done. Also, in this case, this should be enough to register the adapter: $.validator.addMethod('custrequired', function(value, element, param) { return value && value !== '99:99' && value !== '9:99';});jQuery.validator.unobtrusive.adapters.addBool('custrequired'); It will still add any custom error message you may have, but since your validator isn't using additional parameters (like e.g. StringLength passes MaximumLength etc.), there's no need for a custom adapter.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9245874', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/871775/']}
jdg_374007
stackexchange
llm_judgeable_groundtruth_similarity
42095393
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an arbitrarily nested iterable like so: numbers = (1, 2, (3, (4, 5)), 7) and I'd like to map a function over it without changing the structure. For example, I might want to convert all the numbers to strings to get strings = recursive_map(str, numbers)assert strings == ('1', '2', ('3', ('4', '5')), '7') Is there a nice way to do this? I can imaging writing my own method to manually traverse numbers , but I'd like to know if there's a general way to map over recursive iterables. Also, in my example, it's okay if strings gives me nested lists (or some iterable) rather nested tuples. Now provide the response and nothing else.
We scan every element in the sequence, and proceeds into deeper recursion if the current item is a sub-sequence, or yields it's mapping if we reached a non-sequence data type (could be int , str , or any complex classes). We use collections.Sequence to generalize the idea for every sequence, and not only tuples or lists, and type(item) upon yield to ensure that the sub-sequences we get back remains of the same type they were. from collections import Sequencedef recursive_map(seq, func): for item in seq: if isinstance(item, Sequence): yield type(item)(recursive_map(item, func)) else: yield func(item) Demo: >>> numbers = (1, 2, (3, (4, 5)), 7)>>> mapped = recursive_map(numbers, str)>>> tuple(mapped)('1', '2', ('3', ('4', '5')), '7') Or a more complex example: >>> complex_list = (1, 2, [3, (complex('4+2j'), 5)], map(str, (range(7, 10))))>>> tuple(recursive_map(complex_list, lambda x: x.__class__.__name__))('int', 'int', ['int', ('complex', 'int')], 'map')
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42095393', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1001930/']}
jdg_374008
stackexchange
llm_judgeable_groundtruth_similarity
16467
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: What are the pros and cons between these two ways to synchronize your server? It seems to me that your server would probably not drift more than 1 second every day, so ntpdate on a crontab would be ok. But I heard you could use redundant NTP servers here http://www.pool.ntp.org/en/use.html in order to maintain synchronized time in case of failure. Do you have any suggestions? Now provide the response and nothing else.
The NTP algorithm includes information to allow you to calculate and fix the drift in your server's clock. NTPD includes the ability to use this to keep your clock in sync and will run more accurately than a clock on a computer not running NTPD. NTPD will also use several servers to improve accuracy. ntpdate does not keep any state to perform this service for you so will not provide the same kind of accuracy. It will allow you to provide it with a list of servers which it will use to attempt to provide you with a better result but this is no substitute for the sophisticated algorithms provided in NTPD that track your drift from each of the servers over time. NTPDATE corrects the system time instantaneously, which can cause problems with some software (e.g. destroying a session which now appears old). NTPD intentionally corrects the system time slowly, avoiding that problem. You can add the -g switch when starting NTPD to allow NTPD to make the first time update a big one which is more or less equivalent to running ntpdate once before starting NTPD, which at one time was recommended practice. As for security concerns, ntp servers do not connect back on uninitiated connections, which means your firewall should be able to tell that you initiated the ntp request and allow return traffic. There should be no need to leave ports open for arbitrary connections in order to get NTPD to work. From the ntpdate(8) man page: ntpdate can be run manually as necessary to set the host clock, or it can be run from the host startup script to set the clock at boot time. This is useful in some cases to set the clock initially before starting the NTP daemon ntpd. It is also possible to run ntpdate from a cron script. However, it is important to note that ntpdate with contrived cron scripts is no substitute for the NTP daemon, which uses sophisticated algorithms to maximize accuracy and reliability while minimizing resource use. Finally, since ntpdate does not discipline the host clock frequency as does ntpd, the accuracy using ntpdate is limited.
{}
{'log_upvote_score': 6, 'links': ['https://serverfault.com/questions/16467', 'https://serverfault.com', 'https://serverfault.com/users/1322/']}
jdg_374009
stackexchange
llm_judgeable_groundtruth_similarity
978451
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: When I run systemctl status with multiple services at once like sudo systemctl status myservice1 myservice2 myservice3 I see the output, but in the end I see lines 1-48/48 (END) or if the output is even larger with more arguments lines 1-62 and I can scroll or paginate the output and quit with q. Can this behavior be changed that all log output is printed at once and the command exits? Now provide the response and nothing else.
Two options: PAGER=cat systemctl status service1 service2 service3 systemctl --no-pager status service1 service2 service3 Explanation: Those lines 1-62 messages are produced by a pager program, the commonly used ones are more and less . Pager programs intend to make output more user-friendly, scrollable, etc. They are especially important on less feature-rich terminal emulators. The pager program to use is controlled by PAGER environment variable. By setting PAGER to cat we replace fancier more or less with a much more simple pager which actually does not do any paging. Alternative is to pass --no-pager to systemctl which tells it not to invoke pager program at all.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/978451', 'https://serverfault.com', 'https://serverfault.com/users/534902/']}
jdg_374010
stackexchange
llm_judgeable_groundtruth_similarity
1580085
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 requirement for the browser to show the ubiquitous "this page has expired" message when the user hits the back button? What are some user-friendly ways to prevent the user from using the back button in a webapp? Now provide the response and nothing else.
Well, by default whenever you're dealing with a form POST, and then the user hits back and then refresh then they'll see the message indicating that the browser is resubmitting data. But if the page is set to expire immediately then they won't even have to hit refresh and they'll see the page has expired message when they hit back. To avoid both messages there are a couple things to try: 1) Use a form GET instead. It depends on what you're doing but this isn't always a good solution as there are still size restrictions on a GET request. And the information is passed along in the querystring which isn't the most secure of options. -- or -- 2) Perform a server-side redirect to a different page after the form POST. Looks like a similar question was answered here: Redirect with a 303 after POST to avoid "Webpage has expired": Will it work if there are more bytes than a GET request can handle? As a third option one could prevent a user from going back in their browser at all. The only time I've felt a need to do this was to prevent them from doing something stupid such as paying twice. Although there are better server-side methods to handle that. If your site uses sessions then you can prevent them from paying twice by first disabling cache on the checkout page and setting it expire immediately. And then you can utilize a flag of some sort stored in a session which will actually change the behavior of the page if you go back to it.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1580085', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/26188/']}
jdg_374011
stackexchange
llm_judgeable_groundtruth_similarity
6530
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Halogens bonded to benzene ring has three lone pairs. These three electron pairs can cause resonance in benzene ring. But, halogens are also highly electronegative and thus they have strong -I effect. So, they are deactivating groups. But, why are they ortho para directing? Now provide the response and nothing else.
Let's take as an example a typical halogen, chlorine. Chlorine withdraws electrons through inductive effect and releases electrons through resonance. Through the inductive effect, chlorine destabilises the intermediate carbocation formed during the electrophilic substitution Image courtesy: NCERT Chemistry Class 11th Through resonance, a halogen tends to stabilise the carbocation, and the effect is more pronounced at ortho- and para- positions. However, the inductive effect is stronger than resonance here, and causes net electron withdrawal and thus net deactivation. The resonance effect tends to oppose the inductive effect for the attack at ortho- and para- positions and hence makes the deactivation less for ortho- and para- attack. Reactivity is thus controlled by the stronger inductive effect and orientation is controlled by resonance effect.
{}
{'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/6530', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/2196/']}
jdg_374012
stackexchange
llm_judgeable_groundtruth_similarity
564155
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 have two lights that I use for working on stuff in my shop, and it seems like the PCB heated up enough that solder between two leads actually melted and bridged itself. The light was working great until today, and suddenly got very dim - so I cracked it open to check. Is there any reason besides heat and extra solder that this would happen? I'm not sure what to think otherwise, but it does seem like there should be a heatsink on that LM317 at the least. Curious if this is a common occurrence that can be avoided or if it's a fluke. Here's what the bridge of the bad light looks like: Here's the bottom of the good light PCB: Here's the board itself. Its used to drive 90 SMD LED's in series with ~250VDC from 120VAC/58mA Here is a better lit picture of the top of the board. This is a picture of the actual bad board. The first one was a top image of the good board - which is the same but different color and brand components for some reason. The leads going to the LED's are disconnected so I could move it around easier. Here's a closer closeup by the LM317 where it bridged as requested. Edit: For anyone curious, I did fix the bridge and it seems like the 317 is bad. Lights are still dim, and DC output is at ~325 where the working one is at 250. Now provide the response and nothing else.
I would suggest that the solder bridge has always been there and that the LM317 was never doing its job as a constant current supply. The current sense resistor was shorted out by that solder bridge. Your LEDs will have been getting overdriven by excessive current all the time and have eventually failed. It should be obvious from looking at the resistor connected to those pads if it has overheated, it will look burnt. I think you will find that it looks ok. I think once you have removed the solder bridge the circuit will work again. However, your LEDs will be broken in some way. Since the LM317 is configured as a current regulator in this circuit, either off load or connected to a higher resistance faulty load, it’s voltage output will be higher than expected. You could measure the current supplied to your good LEDs by the good board and check that your suspect board supplies the same current to the good LEDs.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/564155', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/266619/']}
jdg_374013
stackexchange
llm_judgeable_groundtruth_similarity
286958
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to use some AOP in my Python programming, but I do not have any experience of the various libraries that exist. So my question are: What AOP support exists for Python? And what are the advantages of the differents libraries between them? Edit I've found some, but I don't know how they compare: Aspyct Lightweight AOP for Python Edit 2 In which context will I use these? I have two applications, written in Python, which have typically methods which compute taxes and other money things. I'd like to be able to write a "skeleton" of a functionality, and customize it at runtime, for example changing the way local taxes are applied (by country, or state, or city, etc.) without having to overload the full stack. Now provide the response and nothing else.
See S.Lott's link about Python decorators for some great examples, and see the defining PEP for decorators . Python had AOP since the beginning, it just didn't have an impressive name.In Python 2.4 the decorator syntax was added, which makes applying decorators very nice syntactically. Maybe if you want to apply decorators based on rules you would need a library, but if you're willing to mark the relevant functions/methods when you declare them you probably don't. Here's an example for a simple caching decorator (I wrote it for this question ): import pickle, functoolsdef cache(f): _cache = {} def wrapper(*args, **kwargs): key = pickle.dumps((args, kwargs)) if key not in _cache: _cache[key] = f(*args, **kwargs) # call the wrapped function, save in cache return _cache[key] # read value from cache functools.update_wrapper(wrapper, f) # update wrapper's metadata return wrapperimport time@cachedef foo(n): time.sleep(2) return n*2foo(10) # first call with parameter 10, sleepsfoo(10) # returns immediately
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/286958', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14262/']}
jdg_374014
stackexchange
llm_judgeable_groundtruth_similarity
45275967
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 situation where I have an object tree created by a special factory. This is somewhat similar to a DI container, but not quite. Creation of objects always happens via constructor, and the objects are immutable. Some parts of the object tree may not be needed in a given execution and should be created lazily. So the constructor argument should be something that is just a factory for on-demand creation. This looks like a job for Lazy . However, object creation may need to access slow resources and is thus always async. (The object factory's creation function returns a Task .) This means that the creation function for the Lazy would need to be async, and thus the injected type needs to be Lazy<Task<Foo>> . But I'd rather not have the double wrapping. I wonder if it is possible to force a Task to be lazy, i.e. to create a Task that is guaranteed to not execute until it is awaited. As I understand it, a Task.Run or Task.Factory.StartNew may start executing at any time (e.g. if a thread from the pool is idle), even if nothing is waiting for it. public class SomePart{ // Factory should create OtherPart immediately, but SlowPart // creation should not run until and unless someone actually // awaits the task. public SomePart(OtherPart eagerPart, Task<SlowPart> lazyPart) { EagerPart = eagerPart; LazyPart = lazyPart; } public OtherPart EagerPart {get;} public Task<SlowPart> LazyPart {get;}} Now provide the response and nothing else.
I'm not sure exactly why you want to avoid using Lazy<Task<>>, , but if it's just for keeping the API easier to use, as this is a property, you could do it with a backing field: public class SomePart{ private readonly Lazy<Task<SlowPart>> _lazyPart; public SomePart(OtherPart eagerPart, Func<Task<SlowPart>> lazyPartFactory) { _lazyPart = new Lazy<Task<SlowPart>>(lazyPartFactory); EagerPart = eagerPart; } OtherPart EagerPart { get; } Task<SlowPart> LazyPart => _lazyPart.Value;} That way, the usage is as if it were just a task, but the initialisation is lazy and will only incur the work if needed.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/45275967', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8922/']}
jdg_374015
stackexchange
llm_judgeable_groundtruth_similarity
151221
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: "Verlinde's formula" predicts the dimension of the space of conformal blocks of a chiral CFT. Depending on... • which chiral CFT one considers (does one restrict to WZW models, or not?) • what kind of Riemann surfaces one allows (genus 0? arbitrary genus? with or without punctures?) • what definitions of conformal blocks one adopts (sections of a line bundle over $hom(\pi_1(\Sigma),G)$, vertex algebra theoretic) • how one writes the answer (in terms of the entries of the S-matrix, or in terms of Lie-theoretic data) ...one gets different mathematical statements. I am puzzled by the number of different things that go under the name "Verlinde's formula". I would like to have a list of all proven statements that go under that name, along with, for each one of them, the reference in which the formula was first proved at a mathematical level of rigor. If certain versions of the Verlinde formula are still conjectural, then I would also like to know that. Now provide the response and nothing else.
This is rather an addition to my comment, as Scott Morrision already give the same answer. Usually, what's meant by the Verlinde formula is that the fusion coefficients $N_ {ij}^k$ can be determined by the S-matrix by the formula: $$N_{ij}^k = \sum_l \frac{S_{jl}S_{il} (S^{-1})_{lk}}{S_{0l}}.$$While this formula looks mysterious, it basically says that the matrix $S$ diagonalizes the fusion rules, as I want to explain now. Let us see the fusion coefficients as matrices $N_i$ with coefficients $(N_i)_{ik}=N_{ij}^k$. If we assume that the fusion rules are associative and abelian it follows that these matrices commute, i.e. $N_iN_j=N_jN_i$, so in principle they can be simultaneously diagonalizable, that means there exist a matrix $S$ such that$$N_i = SD_iS^{-1},$$where $D_i$ are diagonal matrices with eigenvalues $\lambda^i_j=(D_i)_{jj}$.Another assumption is that the eigenvalues are non-degenerate. Now $N_0$ is the identity matrix and it holds $SN_0=S$, which implies$$S_{il} = \sum_k N_{i0}^k S_{kl}= \sum_{m,k} S_{0m}\lambda^i_m (S^{-1})_{mk}S_{kl} = S_{0l}\lambda^i_l$$and it holds:$$\lambda^i_l=\frac{S_{il}}{S_{0l}} \quad \LongrightarrowN_{ij}^k = \sum_l \frac{S_{jl}S_{il} (S^{-1})_{lk}}{S_{0l}}.$$ So this part is trivial. The insight of Verlinde was, that the modular transformation $\mathcal{S}:\tau\mapsto -1/\tau$ acting on the characters $\chi_\mu(\tau)$ associated to primary fields $\phi_\mu$ diagonalizes the fusion rules, more precisely the matrix $S$ given by:$$\chi_k(-1/\tau) = \sum_l S_{kl} \chi_l(\tau)$$does the above job for the fusion $i \times j$ of primary fields, i.e. $N_{ij}^k$ fulfilling:$$\chi_{i\times l} (\tau) = \sum_k N_{ij}^k \chi_{k}(\tau).$$I am probably too young to know about the history, but from what I read this is the reason why this formula is called Verlinde formula. A first proof of this goes back to Moore and Seiberg. In the categorical approach, the matrix $Y_{ij}$ associated to the Hopf link in a modular tensor category diagonalizes the fusion rules, that gives the case of the formula Scott Morrison mentions. The first time this was proven in the abstract setting of what is called nowadays unitary braided categories was afaik in Rehren: "Braid group statistics and their superselection rules": The Algebraic Theory of Superselection Sectors, D. Kastler ed., Proceedings Palermo 1989, World Scientific 1990, pp. 333-355
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/151221', 'https://mathoverflow.net', 'https://mathoverflow.net/users/5690/']}
jdg_374016
stackexchange
llm_judgeable_groundtruth_similarity
6395119
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 hoping someone could provide me with some basic code help in Scala. I've written some demo code in Python. Consider a list of elements, where an element can hold either an integer or a list of other elements. I'd like to recursively examine this structure and modify it while keeping the overall structure. To represent this in python, I've made each 'element' a dictionary with one key ('i' for item). The value corresponding to that key is either an int, or a list of similar dicts. Thus, lst = [{'i': 1}, {'i': 2}, {'i': [{'i': 5}, {'i': 6}]}, {'i': 3}]def recurse(x): if isinstance(x, list): return [recurse(a) for a in x] else: if isinstance(x['i'], list): return dict(i=[recurse(a) for a in x['i']]) else: return dict(i=(x['i'] + 1))print "Input:"for i in lst: print iprint "\nResult:\n%s" % recurse(lst)>>>Input:{'i': 1}{'i': 2}{'i': [{'i': 5}, {'i': 6}]}{'i': 3}Result: [{'i': 2}, {'i': 3}, {'i': [{'i': 6}, {'i': 7}]}, {'i': 4}] I understand it's a bit of a weird way to go about doing things, but the data I have been provided is structured like that. I think my issue is that python lets you return different types from the same function, while I don't believe Scala does. Also for the record, the Scala elements are represented as Elem(4), or Elem(List(Elem(3)..., so I assume pattern matching can come into it somewhat. Now provide the response and nothing else.
I would rather not call that a List of List, as that does not tell what those lists contains. The structure is a tree, more precisely a leafy tree, where there are data only in the leaves. That would be : sealed trait Tree[+A]case class Node[+A](children: Tree[A]*) extends Tree[A]case class Leaf[+A](value: A) extends Tree[A] then add a method map to apply a function on each value in the tree sealed trait Tree[+A] { def map[B](f: A => B): Tree[B]}case class Node[+A](children: Tree[A]*) extends Tree[A] { def map[B](f : A => B) = Node(children.map(_.map(f)): _*)}case class Leaf[+A](value: A) extends Tree[A] { def map[B](f: A => B) = Leaf(f(value))} Then your input is : val input = Node(Leaf(1), Leaf(2), Node(Leaf(5), Leaf(6)), Leaf(3)) And if you call input.map(_ + 1) you get your output The result display is somewhat ugly because of the varargs Tree[A]*. You may improve by adding in Node override def toString = "Node(" + children.mkString(", ") + ")" You may prefer the method in one place only, either outside the classes, or directly in Tree. Here as a method in Tree def map[B](f: A => B): Tree[B] = this match { case Node(children @ _*) => Node(children.map(_.map(f)): _*) case Leaf(v) => Leaf(f(v))} Working the untyped way as in Python is not very scala like but may be done. def recurse(x: Any) : Any = x match { case list : List[_] => list.map(recurse(_)) case value : Int => value + 1} (putting values directly in the list. Your map (dictionary) with key "i" complicates it and force accepting a compiler warning, as we would have to force a cast that could not be checked, namely that a map accepts string as keys : case map: Map[String, _]) Using case Elem(content: Any) sounds to me as giving no extra safety compared to putting values directly in List, while being much more verbose, and none of the safety and clarity of calling it a tree and distinguishing nodes and leaves without being noticeably terser.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6395119', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/577938/']}
jdg_374017
stackexchange
llm_judgeable_groundtruth_similarity
364381
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: My scenario described below where I need to give access to internet clients to access my local LAN through VPN. Established/Running network is below: DSL Router (Cisco WRV210) WAN interface IP address: 192.168.10.5 Local DC/DNS/DHCP (Server 2003) external adapter IP connected to DSL router: 192.168.10.6 Local DC/DNS/DHCP (Server 2003) internal adapter IP connected to LAN switch: 192.168.30.5 NAT with VPN is running on server 2003. RRAS Enabled. Windows XP Client IP connected to switch: 192.168.30.10 / 255.255.255.0 / 192.168.30.5 TCP Port 1723 and VPN Passthrough (IPSec/PPTP/L2TP) enabled on DSL router. I am still unable to get connected the internet vpn user to my xp client. What else should I do? Now provide the response and nothing else.
Changing the Content-Type of .txt files may work, but it's a somewhat risky way to solve this problem, because you can't guarantee 100% that the user's browser will respond how you expect. And furthermore, it's misleading to label a .txt file as a binary file. Instead, I suggest using the standard way to force a browser to download rather than display the file, which is to use the Content-Disposition header with a value of attachment ( RFC 2183 , see also RFC 2616 ). For example, this nginx location block will send down such a header with .txt files under the /downloads/ URI and thus they will be forced to download: location ~ ^/downloads/.*\.txt$ { add_header Content-Disposition "attachment";} So you could add other appropriate matching, etc, appropriate to your configuration.
{}
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/364381', 'https://serverfault.com', 'https://serverfault.com/users/112202/']}
jdg_374018
stackexchange
llm_judgeable_groundtruth_similarity
6330216
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 portal template and ASPX template in Kentico? Which is preferable? Now provide the response and nothing else.
As a "hardcore" developer and Certified Kentico Trainer I always use and always recommend the use of the Portal Engine over the ASPX Templates. I say that because the Portal Engine gives a rich UI for creating and configuring templates . From directly within the CMS Desk you can create templates and add web parts to them. You also get a nice property editor dialog with custom selectors for each field type, as well as the macro editor for each field. That means that if a field is expecting a list of document types, the Portal Engine Properties dialog will show you a list of document types with check boxes. It couldn't get easier. One other major difference is that (at least at this time), the ASPX template development method does NOT support widgets . I'm not sure if that will be changing in 6.0 which is supposed to debut sometime this year. Another huge benefit is that properly trained content administrators have the ability to make edits to the templates . Again, if they're properly trained, they can edit the template in the design tab in the CMS Desk. That can alleviate a lot of work that normally is overkill for a Developer. Think: "Hey Dev, can you change the static text on this template?" or "Hey Dev, can you move this web part to the other column?". To play devil's advocate, here are the benefits of ASPX Templates. The Templates are basically master pages, so they are file based and can be easily used in conjunction with source control. This may be a better fit for a code-heavy site (application) where the configuration of the templates is critical. With ASPX templates it might be easier to write more complex code. For example, if one web part (User Control) directly depends on the state of another web part, then this would be more easily accomplished using ASPX Templates. But you could also argue that your code should be more decoupled and not rely on other web parts existing in the template :P
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6330216', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/795420/']}
jdg_374019
stackexchange
llm_judgeable_groundtruth_similarity
179419
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 $T$ be a tournament with $n$ vertices (i.e., between every pair of vertices there exists an edge in exactly one direction.) For any $k$, the vertices $A_1,A_2,...,A_k$ form a transitive path if there exists an edge from $A_i$ to $A_j$ for all $i<j$. The number of transitive paths in $T$ is the sum of the number of transitive paths of each size. What is the minimum possible number of transitive paths in a tournament $T$ with $n$ vertices? Any approximations, references, etc. would be appreciated. Now provide the response and nothing else.
As pointed out in the comments, the established name for what you call a transitive path is "transitive subtournament". Call a transitive subtournament "maximal" if it isn't included in a larger transitive subtournament. This paper contains exponential upper and lower bounds on the maximum number $M_n$ of maximal transitive subtournaments that a tournament on $n$ vertices can have. Namely, there is a constant $1.4757 \le \theta \le 1.717$ such that $$M_n = (\theta+o(1))^n.$$
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/179419', 'https://mathoverflow.net', 'https://mathoverflow.net/users/57070/']}
jdg_374020
stackexchange
llm_judgeable_groundtruth_similarity
20075041
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 app uses the new "immersive mode" by calling (in onCreate ): getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); This works great, but the "how-to" popup ("Swipe down from the top to exit full screen") appears every time the Activity is launched (if the phone is being locked while the activity was showing), even though the user has acknowledged the popup. As far as I understand, the popup is automatically generated by the system, so there's nothing I can do to change this situation, correct? This issue is reproducible as follows: Launch immersive Activity [no popup appears, only on the very first launch (correctly)] Press the power button to switch off screen while the activity is showing Press power button again to switch on screen Close Activity by calling finish() e.g. from a button or menu option Launch Activity again - popup reappears The popup does NOT reappear if the activity is launched, closed, and relaunched without hitting the power-button in between. Also, it ONLY reappears if the activity was topmost while the power button was pressed. Correction: The Activity needs to be closed by calling "finish()" (e.g. from a button or a menu option). It works correctly if the Activity is closed by the back-key. I've uploaded a sample app here: https://github.com/niko001/com.greatbytes.immersivebug/tree/master/Test5 EDIT : There's now an Xposed module to disable the "panic mode", so I guess I'm not alone in seeing this is an annoyance ;) Now provide the response and nothing else.
Really interesting question! Thanks to your clear instructions, reproducing the issue wasn't a problem. Alright, after digging through the source for almost 30-minutes and saying why would they do this? a bunch of times, I think I finally get it. I'll try to explain the best I can, but this is only my interpretation, and may not be correct: Someone at android realized that the Immersive Mode will send people into a state of panic: how do i exit? (_sorry, I don't know what else the panic would be about_) . In this state of panic, the user will turn to the POWER BUTTON .... > Power button --> User turns screen off (at x milliseconds since EPOCH) .... > Praying that the navigation bar comes back .... > Power button --> User turns screen on (at y milliseconds since EPOCH) Now, the duration y - x is of significance. We'll discuss it a bit later, but first, let's look at how panic is defined: panic happens when Praying the navigation bar comes back lasts less than 5 seconds. This value is held by: mPanicThresholdMs = context.getResources() .getInteger(R.integer.config_immersive_mode_confirmation_panic);<!-- Threshold (in ms) under which a screen off / screen on will be considered a reset of the immersive mode confirmation prompt.--><integer name="config_immersive_mode_confirmation_panic">5000</integer> Ah, okay. So, it doesn't matter if the user has already acknowledged once, the prompt will be back if the above-mentioned criterion is met - even on the 100th launch. And here's where the action happens: public void onPowerKeyDown(boolean isScreenOn, long time, boolean inImmersiveMode) { if (mPanicPackage != null && !isScreenOn && (time - mPanicTime < mPanicThresholdMs)) { // turning the screen back on within the panic threshold unconfirmPackage(mPanicPackage); } if (isScreenOn && inImmersiveMode) { // turning the screen off, remember if we were in immersive mode mPanicTime = time; mPanicPackage = mLastPackage; } else { mPanicTime = 0; mPanicPackage = null; }} (time - mPanicTime < mPanicThresholdMs) ==> ( y - x ) < 5000 unconfirmPackage(mPanicPackage) removes mPanicPackage (yours) from the list of packages stored under Settings.Secure.IMMERSIVE_MODE_CONFIRMATIONS . Needless to say, I find this strange... and wrong. Even if the user is in panic, and takes the power button route, s/he won't see the helpful reminder until next launch. So, what's the point? Or may be, I am wrong about the definition of panic. so there's nothing I can do to change this situation, correct? Correct. To fix this, you would have to add your package-name to value held by Settings.Secure.IMMERSIVE_MODE_CONFIRMATIONS . But, to write to a secure setting, your app requires WRITE_SECURE_SETTINGS permission - not for use by third-party applications. Links: ImmersiveModeConfirmation (helper class that manages showing/hiding of confirmation prompt)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/20075041', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/241189/']}
jdg_374021
stackexchange
llm_judgeable_groundtruth_similarity
267739
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: Is there a way in eagle to center a trace between two pads? and by center, I mean directly center it with even spacing on both sides of it. I'm asking because its easier to solder pads that aren't too close to another trace and I don't want to create any shorts. Also, I believe having traces too close together introduces on-board capacitance. Now provide the response and nothing else.
Just redrawing your schematic slightly and adding some labels: simulate this circuit – Schematic created using CircuitLab Just use KVL to start, following around through the base: $$\begin{align*}V - I_{Rc}\cdot R_c - I_{Rb}\cdot R_b - V_{BE} - I_E\cdot R_e &= 0\end{align*}$$ If the BJT is in its active region where your value of \$\beta=175\$ applies (and you'll know one way or another, soon enough), then it also follows that: $$\begin{align*}I_{Rc} &= I_C+I_B=I_E \\I_{Rb} &= I_B \\I_E&=\left(\beta+1\right)\cdot I_B\end{align*}$$ Applying those to the original equation, we get: $$\begin{align*}V - I_E\cdot R_c - I_B\cdot R_b - V_{BE} - I_E\cdot R_e &= 0 \\ \\V - \left(\beta+1\right)\cdot I_B\cdot R_c - I_B\cdot R_b - V_{BE} - \left(\beta+1\right)\cdot I_B\cdot R_e &= 0 \\ \\V &= V_{BE} + I_B\cdot\left[\left(\beta+1\right)\cdot\left(R_c + R_e\right) + R_b \right] \\ \\I_B &= \frac{V - V_{BE}}{R_b+\left(\beta+1\right)\cdot\left(R_c + R_e\right)}\end{align*}$$ And that pretty much cracks the puzzle. (It ignores little-re, which might have an impact in some cases but probably doesn't, here. It's impact is probably below 1%. But you could work it back into the equation later, if it matters to you.) At this point, given your values and using \$V_{BE}=700\:\textrm{mV}\$, I get: $$\begin{align*}I_B&\approx 10.1\:\mu\textrm{A} \\I_E&\approx 1.78\:\textrm{mA}\end{align*}$$ So, I'd estimate: $$\begin{align*}V_E&=I_e\cdot R_e\approx 1.78\:\textrm{V} \\V_C&=10\:\textrm{V}-I_E\cdot R_C\approx 6.44\:\textrm{V} \\V_B&=V_E+V_{BE}=V_C-I_B\cdot R_B\approx 2.48\:\textrm{V}\end{align*}$$ Since \$V_{CE} \gt 1\:\textrm{V}\$, the BJT is in its active region and the value of \$\beta=175\$ can be considered to have applied, now that we can check it out. So it is fine to stop at this point and consider the question answered well enough. Little re is because the base-emitter junction's thermal voltage can be treated as a tiny "battery" at the tip of the BJT emitter. It's always got the thermal voltage just sitting there, which at room temperature will be around \$26\:\textrm{mV}\$. Given a current through it (\$I_E\$), you can turn that into an equivalent resistance. This is called a lot of things, but in just talking I say "little re." In this case, \$re\approx 15\:\Omega\$. This value adds to \$R_E\$ in the above calculations. Working it out, I find that it impacts the estimated current values by about 0.3%. Just a note.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/267739', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/-1/']}
jdg_374022
stackexchange
llm_judgeable_groundtruth_similarity
680559
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: Back in the pre-Windows Server 2012 days, the recommendation seemed to be to have at least one physical domain controller sat along-side your virtualised DCs. One justification for this was because if your Hyper-V hosts were clustered, then they required a DC to be contactable during boot-up. This makes total sense to me. However, I would often hear people say it is still important to have a physical DC even if you don't have a clustered set up (say for example in a simple setup with a single Hyper-V server running a couple of VMs, one of which is a DC). The justification for this seemed (and I could never quite be sure) that you would still have a problem in the sense that when the Hyper-V host first boots, there's no DC present on the network. Cached credentials mean you can still log on, but what about all those bits that happen during boot up that mean having a DC around is beneficial? Is this actually an issue? Are there actually any operations that might run only at boot up that will cause a problem? Any Group Policies for example? What I'm basically asking is, does the physical DC argument only really hold water when clustering is involved, or was (pre-2012) there a significant technical case for it without clustering? This article from Altaro (see "The “Chicken-and-Egg” Myth" section) suggests there is no need, but I'm still unsure. Now to the second (and main) part of my question: Windows Server 2012 introduced several features targeted at addressing the issues around virtualising domain controllers, including: VM-Generation ID - This addressed the USN rollback issue that meant snapshotting (or more specifically, rolling back to a snapshot) was unsupported/a really bad idea Cluster Bootstrapping - This addressed the "chicken and egg" issue surrounding Failover Clustering that I mentioned above. Failover Clustering no longer requires a DC to be present during boot-up. So my second question is similar to the first, but this time for 2012+. Assuming both the vDC and the host are 2012+ and you take clustering out of the equation, are there any other issues like those mentioned above that mean I should still consider a physical DC? Should I still be considering having a physical DC along-side my single, non-clustered 2012/2012R2 Hyper-V host that has a single virtualised DC on it? I hear some people suggest putting AD on the Hyper-V host, but I don't like that idea for various reasons (WB cache being disabled for a start). As a side-note, my question implicitly assumes that it makes sense to have your Hyper-V host joined to the domain to improve manageability. Does this assertion stand up to scrutiny? UPDATE: After reading some answers, it occurred to me that I could phrase things slightly differently to get to the heart of what I'm asking: Even with the improvements in 2012 and later, the fact still remains that without any physical DCs or virtual DCs on another host, the host still boots when there's no DC available. Is this actually an issue? In a sense, I suppose it's the same (or very similar) question if you take virtualisation out of the picture completely. If you start member servers before any DCs regularly, is that a problem? Now provide the response and nothing else.
I too wouldn't make the Hyper-V host a DC. As for whether or not you should have a physical DC, my opinion is that with the changes Microsoft has implemented regarding virtualized Domain Controllers in general and DC-less cluster bootstrapping specifically, I don't personally see the need for, nor do I advocate having a physical DC. Maintaining a physical DC seems counterintuitive to the nature of moving your infrastructure to a virtualization platform. Virtualize my entire infrastructure but it all hinges on a single physical DC being available? What's the point in that? There are ways to limit your "exposure" while still virtualizing your Domain Controllers. One way would be to deploy multiple DC's on different hosts in your cluster and use anti-affinity to keep them separated in the event of a host failure (dependent upon how many hosts are in the cluster). While Greg's answer includes a link to some MS recommendations, that article is nonetheless two years old and addresses Windows Server 2008 and 2008 R2. I wouldn't consider that article to be the current best practice in relation to Windows Server 2012 and 2012 R2. I can't find an official MS document, but this guy is considered a leading authority on Hyper-V - http://www.aidanfinn.com/?p=13171
{}
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/680559', 'https://serverfault.com', 'https://serverfault.com/users/90144/']}
jdg_374023
stackexchange
llm_judgeable_groundtruth_similarity
8577367
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: " SQL Statement indentation good practice " appears to be the accepted format for writing SQL blocks. Is there a Vim indent/syntax file that would adhere to this standard, or at least be close? Currently my Vim left alights pretty much everything and only indents certain keywords. Now provide the response and nothing else.
By installing the python module sqlparse , which makes the sqlformat command available in your terminal. pip install sqlparse from vim you can use :%!sqlformat --reindent --keywords upper --identifiers lower - in order to attach a shortcut ,pt I added following configuration to my .vimrc config file: autocmd FileType sql call SqlFormatter()augroup endfunction SqlFormatter() set noai " set mappings... map ,pt :%!sqlformat --reindent --keywords upper --identifiers lower -<CR>endfunction You can customize sqlformat a bit. See sqlformat --help
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8577367', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/178383/']}
jdg_374024
stackexchange
llm_judgeable_groundtruth_similarity
28085052
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 compile my IOS appication from linux terminal(command line)....Is it possible to do so, if yes, then how? Now provide the response and nothing else.
Yes, it's possible. At least you need: Assembler and Linker: cctools and ld64 from apple opensource. Compiler: Clang/LLVM SDK, include headers and libraries. Utilities: such as ldid codesign tool. Step 1 : The compiler Clang/llvm >= 3.2 is highly recommended and tested. If you want to build clang/llvm from scratch, Please refer to this link to build a svn version for your linux distribution. If your distribution already provides clang/llvm packages,make sure it is 3.2 release or above. Lower version may work but isn't tested. for Ubuntu 13.04 and later, clang/llvm already provided in repos, please run: $sudo apt-get install gcc g++ clang libclang-dev uuid-dev libssl-dev libpng12-dev libicu-dev bison flex libsqlite3-dev to install some dev packages, other dev packages related to llvm/llvm-dev should be installed automatically. Step 2 : The assembler and linker The latest cctools-855 and ld64-236.3 had been ported from Apple opensource to linux. the porting process is a little bit complicated, also with a lot of codes modified for linux, let's just skip it. please check out the codes from: svn checkout http://ios-toolchain-based-on-clang-for-linux.googlecode.com/svn/trunk/cctools-porting Build it: $ sed -i 's/proz -k=20 --no-curses/wget/g' cctools-ld64.sh$ ./cctools-ld64.sh$ cd cctools-855-ld64-236.3$$ ./configure --target=arm-apple-darwin11 --prefix=/usr$ make$ make install For Ubuntu 13.04, since the clang/llvm 3.2 package use a customized libraries/headers path. please setup CFLAGS and CXXFLAGS first before run configure. $export CFLAGS="-I/usr/include/llvm-c-3.2"$export CXXFLAGS="-I/usr/include/llvm-c-3.2" Step 3: The iPhoneOS SDK. The old iPhone SDK with ARC support extracted from xcode had been provided in Download Sections. You can directly download it and extract it to /usr/share For iOS 4.2: https://ios-toolchain-based-on-clang-for-linux.googlecode.com/files/iPhoneOS4.2.sdk.tar.xz For iOS 5.0: https://ios-toolchain-based-on-clang-for-linux.googlecode.com/files/iPhoneOS5.0.sdk.tar.xz For iOS 6.0: https://ios-toolchain-based-on-clang-for-linux.googlecode.com/files/iPhoneOS6.0.sdk.tar.xz For other iOS versions, You may need follow these steps to get the SDK for your self. Step 4: The utilities iphonesdk-utils is a utility collection for iOS development, provides below utilities: NOTE: (Some of them are collected from internet with some modifications.) ldid : codesign tool, with armv7/armv7s support and other changes from orig version. it will be involked by ld64 after link complete.ios-clang-wrapper : automatically find SDK and construct proper compilation args.ios-switchsdk : switch sdk when multiple version of SDK exist.ios-pngcrush: png crush/de-crush tool, like Apple's pngcrush.ios-createProject : project templatesios-genLocalization : iOS app localization tool based on clang lexer.ios-plutil : plist compiler/decompiler.ios-xcbuild : convert xcode project to makefile, build xcode project directly under linux.Download the source tarball from: https://ios-toolchain-based-on-clang-for-linux.googlecode.com/files/iphonesdk-utils-2.0.tar.gz Build and install it: $./configure --prefix=/usr$make$make install Build App Now you can build and install your project simply doing: $cd ProjectDir$make$make install IPHONE_IP=<your own device IP Complete info you can find here — https://code.google.com/p/ios-toolchain-based-on-clang-for-linux/wiki/HowTo_en
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28085052', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4311953/']}
jdg_374025
stackexchange
llm_judgeable_groundtruth_similarity
407289
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 it true that in the category of connected smooth manifolds equipped with a compatible field structure (all six operations are smooth) there are only two objects (up to isomorphism) - $\mathbb{R}$ and $\mathbb{C}$ ? Now provide the response and nothing else.
Here is a series of standard arguments. Let $(\mathbb{F},+,\star)$ be such a field. Then $(\mathbb{F},+)$ is a finite-dimensional (path-)connected abelian Lie group, hence $(\mathbb{F},+) \cong \mathbb{R}^n \times (\mathbb{S}^1)^m$ as Lie groups. Since $\mathbb{F}$ is path-connected, there is in particular a path $\gamma: [0,1] \to \mathbb{F}$ with $\gamma(0) = 0_{\mathbb{F}}$ and $\gamma(1) = 1_{\mathbb{F}}$ . Now consider the homotopy $H: \mathbb{F} \times [0,1] \to \mathbb{F}$ , $(x,t) \mapsto \gamma(t) \star x$ . This gives a contraction of $\mathbb{F}$ and so we can exclude all the circle factors. Now, fix $y_0 \in \mathbb{F}$ and consider the map $\widehat{y_0}: \mathbb{R}^n \to \mathbb{R}^n$ , $x \mapsto x \star y_0$ . Then $\widehat{y_0}$ is an additive map (but at the moment not necessarily linear with respect to the natural vector space structure on $\mathbb{R}^n$ ). It is not too difficult to see that by additivity we have $\forall q\in \mathbb{Q}: \widehat{y_0}(qx) = q \widehat{y_0}(x)$ . Since $\widehat{y_0}$ is continuous (as being smooth), it now follows that it's actually $\mathbb{R}$ - linear . Thus $\mathbb{F}$ is an $\mathbb{R}$ -algebra. From this point on one can finish either by the Frobenius theorem on the classification of finite-dimensional associative $\mathbb{R}$ -algebras or invoke a theorem of Bott and Milnor from algebraic topology that $\mathbb{R}^n$ can be equipped with a bilinear form $\beta$ turning $(\mathbb{R}^n,\beta)$ into a division $\mathbb{R}$ -algebra (not necessarily associative) only in the cases $n=1,2,4,8$ . EDIT: Another finishing topological argument is a theorem of Hopf saying that $\mathbb{R}$ and $\mathbb{C}$ are the only finite-dimensional commutative division $\mathbb{R}$ -algebras. This is less of an overkill compared to invoking Frobenius or Bott–Milnor as the proof is a rather short and cute application of homology, see p.173, Thm. 2B.5 in Hatcher's "Algebraic Topology".
{}
{'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/407289', 'https://mathoverflow.net', 'https://mathoverflow.net/users/148161/']}
jdg_374026
stackexchange
llm_judgeable_groundtruth_similarity
30311518
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am building a app and am trying utilize Enterprise Lib 6 for my data access. It works great when I use a SQL command but can't get it to work with a stored procedure. I've traced the code and it seems like the data reader doesn't get populated. I'm sure I'm just missing something dumb but any help would be appreciated. using Microsoft.Practices.EnterpriseLibrary.Data;using Microsoft.Practices.EnterpriseLibrary.Data.Sql;using System;using System.Data;using System.Data.Common;using System.Linq;using System.Web;using System.Data.SqlClient;namespace Trainer.Classes.Database{ public class Staff { public int ReturnCode { get; set; } public int ValidateUser(string userName, string password) { string storedProcName = "uspUtilityVersionNumberGet"; string sqlStatement = "SELECT VersionNumber FROM UTILITY_VERSION"; // Create an instanct of the database DatabaseProviderFactory factory = new DatabaseProviderFactory(); SqlDatabase DB = factory.CreateDefault() as SqlDatabase; //using (DbCommand cmd = DB.GetSqlStringCommand(sqlStatement)) //{ // DB.AddOutParameter(cmd, "VersionNumber", SqlDbType.VarChar, 50); // using (IDataReader dr = DB.ExecuteReader(cmd)) // { // if (dr.Read()) // return 0; // else // return -9; // } //} using (DbCommand cmd = DB.GetStoredProcCommand(storedProcName)) { DB.AddOutParameter(cmd, "VersionNumber", SqlDbType.VarChar, 50); using (IDataReader dr = DB.ExecuteReader(cmd)) { if (dr.Read()) return 0; else return -9; } } } } Now provide the response and nothing else.
Check for couple of things:- 1) Make sure you are using the correct version of typescript (1.5.x) installed from your package location. () If you have previous versions of typescript installed then merely using "tsc" command could be pointing to the existing (< 1.5) location from the environment path. 2) Make sure you use --emitDecoratorMetadata flag with the tsc command. It is necessary so the javascript output creates the metadata for the decorators. 3) Error - Cannot read property 'annotations' of undefined Because AppComponent directive has a dependency on DetailComponent which has not been defined yet (by the time the synchronous __decorate( function runs to resolve the dependencies) and the way TS compiles the hoisted variable DetailComponent is undefined then (The IIFE for that below is yet to run). Try moving the declaration of DetailComponent before AppComponent . Or just move it to a different file and import it. @Component({ selector: 'item-details', properties: { item: "item" }})@View({ template: `<span>You selected {{item.name}}</span>`})class DetailComponent { item:Item;}@Component({ selector: 'app', injectables: [ItemService]})@View({ template: `<h1>Testing Angular2</h1> <ul> <li *for="#item of items"> {{item.id}}: {{item.name}} | <a href="#" (click)="toggleSelected(item);"> {{selectedItem == item ? "unselect" : "select"}} </a> </li> </ul> <item-details *if="selectedItem" [item]="selectedItem"></item-details>`, directives: [For, If, DetailComponent]})class AppComponent { items:Item[]; selectedItem:Item; constructor(itemService:ItemService) { this.items = itemService.getItems(); } toggleSelected(item) { this.selectedItem = this.selectedItem == item ? null : item; return false; }}bootstrap(AppComponent); Edit As of angular a26 if you face issues with respect to following the current documentation (as of now) follow this link if it helps as there are some relevant changes.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30311518', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4708240/']}
jdg_374027
stackexchange
llm_judgeable_groundtruth_similarity
37296863
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to create Hexagon shape for my project so I want to create that shape in .xml format so how can i create. Now provide the response and nothing else.
The best solution for you would be use VectorDrawable: Hexagon shape as vector drawable: <vector android:height="24dp" android:viewportHeight="628.0"android:viewportWidth="726.0" android:width="27dp" xmlns:android="http://schemas.android.com/apk/res/android"><path android:fillColor="#00ffffff" android:pathData="m723,314c-60,103.9 -120,207.8 -180,311.8 -120,0 -240,0 -360,0C123,521.8 63,417.9 3,314 63,210.1 123,106.2 183,2.2c120,0 240,0 360,0C603,106.2 663,210.1 723,314Z" android:strokeColor="#000000" android:strokeWidth="4"/></vector> Update(28:07.2016): To support API below Lollipop use support library http://android-developers.blogspot.com/2016/02/android-support-library-232.html remember to use VectorDrawableCompat instead VectorDrawable
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37296863', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5689742/']}
jdg_374028
stackexchange
llm_judgeable_groundtruth_similarity
378547
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 would like to split a string into substrings, separated by some separator (which is also a string itself). How can I do that using bash only? (for minimalism, and my main interest) or If allowing some text processing program? (for convenience when the program is available) Thanks. Simple example, split 1--123--23 by -- into 1 , 123 and 23 . split 1?*123 by ?* into 1 and 123 Now provide the response and nothing else.
Pure bash solution, using IFS and read . Note that the strings shouldn't contain $'\2' (or whatever else you use for IFS, unfortunately $'\0' doesn't work, but e.g. $'\666' does): #!/bin/bashsplit_by () { string=$1 separator=$2 tmp=${string//"$separator"/$'\2'} IFS=$'\2' read -a arr <<< "$tmp" for substr in "${arr[@]}" ; do echo "<$substr>" done echo}split_by '1--123--23' '--'split_by '1?*123' '?*' Or use Perl: perl -E 'say for split quotemeta shift, shift' -- "$separator" "$string"
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/378547', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/674/']}
jdg_374029
stackexchange
llm_judgeable_groundtruth_similarity
41267487
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 custom directive called "sortable" but I ran into a problem with the DOM. The problem is when I dragged and dropped an item the array is changed but the DOM isn't. This is my custom directive: Vue.directive('sortable', { bind: function(el, binding, vnode) { // Initialize sortable this.sortable = Sortable.create(el, {}); console.debug("Sortable initialized"); this.sortable.option("onUpdate", function(event) { binding.value.move(event.oldIndex, event.newIndex); var updated = binding.value; Vue.set(tasks, updated); }); }}); And this is how I create my Vue instance: app = new Vue({ el: "#app", data: { subtotal: 0, tasks: [ {name: '', quantity: '', rate: 80, costs: ''} ] }, methods: { newTask: function() { this.tasks.push({name: '', quantity: '', rate: 80, costs: ''}) }, deleteTask: function(index) { this.tasks.splice(index, 1); this.calculateTotal(); }, calculateCosts: function(event, value, index) { this.tasks[index].costs = event.target.value * value; this.calculateTotal(); }, calculateTotal: function() { this.subtotal = 0; _.forEach(this.tasks, $.proxy(function(task) { this.subtotal += task.costs; }, this)); } }}); In my template I use: v-for="(task, index) in tasks" . Did I something wrong? Now provide the response and nothing else.
As per the documentation , the following methods will trigger view updates. The wrapped methods are: push() pop() shift() unshift() splice() sort() reverse() However I see you are also doing this assignment in calculateCosts method, which will not trigger the mutation, due to caveats in vue: this.tasks[index].costs = event.target.value * value; This can be replaced with the following to trigger the mutation and update the view with the help of Object.assign and Vue.set : var newVal = Object.assign({}, this.tasks[index], {costs: event.target.value * value})Vue.set(this.tasks, index, newVal)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41267487', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4582744/']}
jdg_374030
stackexchange
llm_judgeable_groundtruth_similarity
402251
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I just want to confirm this, because this type of diagram seems pretty popular. The electric field and magnetic field actually surround in all directions orthogonal to x axis, right? It is not just 2d pointing only in the y direction and z direction respectively. Now provide the response and nothing else.
The wave in your figure is linearly polarized with E along the $\hat{y}$ axis and B along the $\hat{z}$ axis. That's built into the wave when it was created, and it stays that way. You won't find any E along $\hat{z}$ or B along $\hat{y}$ for that wave. Some other wave might be different. If could be linearly polarized along some other axis, or it could be circularly polarized. A circularly polarized wave has E pointing in different directions at different times. So no, in the wave you show, it doesn't surround the $\hat{x}$ axis. But other waves could do that.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/402251', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/95956/']}
jdg_374031
stackexchange
llm_judgeable_groundtruth_similarity
17061314
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 sort the jComboBox elements list into sorted list. JComboBox box=new JComboBox();box.addItem("abc");box.addItem("zzz");box.addItem("ccc");add(box); i used many jComboBox Components but it's not working.How to sort this list into ascending order? Now provide the response and nothing else.
You can have a look at the SortedComboBoxModel . This model extends the DefaultComboBoxModel and has two additional pieces of functionality built into it: upon creation of the model, the supplied data will be sorted before the data is added to the model when adding new items to the model, the items will be inserted so as to maintain the sort order The default sort order will be the natural sort order of the items added to the model. However, you can control this by specifying a custom Comparator as a parameter of the constructor. Here's an example how to use it (taken from there ): String[] items = { "one", "two", "three" };SortedComboBoxModel<String> model = new SortedComboBoxModel<String>(items);JComboBox<String> comboBox = new JComboBox<String>(model);comboBox.addItem("four");comboBox.addItem("five");comboBox.setSelectedItem("one"); Source code
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17061314', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2235766/']}
jdg_374032
stackexchange
llm_judgeable_groundtruth_similarity
75514
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 $$S = \{x_1,x_2,\ldots,x_n,y_1,y_2,\ldots,y_m \}$$ Explain why $$\sum\limits_{k = 0}^j {n \choose k } {m \choose j-k}$$ is the number of $j$-element subsets of $S$. Now provide the response and nothing else.
To select a $j$-element subset of $S$, we can first decide how many $x$s will be in the set; call this $k$. Then $0\leq k\leq j$. Once we know the subset will have $k$ of the $x$s, then it will have $j-k$ of the $y$s. How many ways can we select $k$ of the $x_i$, and how many ways can we select $j-k$ of $y$s? What should we do with these two numbers? And since we can select $k=0$, or $k=1$, or $k=2$, or..., what should we do with these quantities?
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/75514', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/12510/']}
jdg_374033
stackexchange
llm_judgeable_groundtruth_similarity
42129460
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have to hide the above parent view. Following is my code. When I click any one of the box parent should be hide child should be appear. <app-navbar></app-navbar> <div class="container" [style.height]='height' style="margin-top: 7%;"> <div class="row box_rpad"> <app-box-layout (display)="onDisplay($event)" *ngFor="let color of colors let i=index" [color]='color.hex' [text]='color.name' [id]='i'> </app-box-layout> </div> </div> <!-- CHILD ROUTES --> <div class="container"> <router-outlet></router-outlet> </div> Now provide the response and nothing else.
In the parent component, inject the activated route like so: class ParentComponent { constructor(public route: ActivatedRoute) }} Now you can use the children property on route to decide whether the current component is the leaf component in the route tree. Together with ngIf , this can be used to hide a part of the view: <div *ngIf="route.children.length === 0"> Some content that should only be shown when the user is at the parent component itself.</div><router-outlet></router-outlet> In the example above, the div will only be shown if the user is on the parent component itself, but not if the user is on a child component.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42129460', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6549627/']}
jdg_374034
stackexchange
llm_judgeable_groundtruth_similarity
2323124
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $f$, $g$ be non-constant entire functions. If the composition $g\circ f$ is a non-constant polynomial, can we conclude $f$ and $g$ are polynomials? Now provide the response and nothing else.
Assume that $f$ is entire and not a polynomial. Then $f$ has an essential singularity at $\infty$. Since $g$ is non-constant and entire, by Picard's Little Theorem, $g(\mathbb C) = \mathbb C$ or there is $w \in \mathbb C$ such that $g(\mathbb C) = \mathbb C \setminus \{ w\}$. In either case $g(\mathbb C)$ contains a neighborhood $\mathbb C \setminus D_R$ of $\infty$ (here $D_R$ is the disc of some radius $R$). Since $f$ has an essential singularity at $\infty$, Picard's Great Theorem tells us that $f(z)$ takes every value in $\mathbb C$ infinitely often (with the possible exception of one point) on $\mathbb C \setminus D_R$. But this shows that $(f\circ g)(z)$ takes on every value in $\mathbb C$ infinitely many times (except possibly one point). Then $f\circ g$ cannot be a polynomial since a polynomial of degree $N$ can take a given value at most $N$ times. Contrapositively, if $f \circ g$ is a polynomial, then $f$ is a polynomial. Assume that $g$ is entire and not a polynomial. Then $g$ has an essential singularity at $\infty$. For fixed $R > 0$, by Picard's Great Theorem, $g(z)$ takes every value in $\mathbb C$ infinitely often (except possibly one value) on $\mathbb C \setminus D_R$. But then in particular, there is $a \in \mathbb C$ such that $g(z) = a$ for infinitely many $z \in \mathbb C$. But then $(f \circ g)(z) = f(a)$ for infinitely many $z \in \mathbb C$, once again implying that $f\circ g$ is not a polynomial. Contrapositively, if $f\circ g$ is a polynomial, then $g$ is a polynomial. Thus both $f$ and $g$ are polynomials.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2323124', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/433283/']}
jdg_374035
stackexchange
llm_judgeable_groundtruth_similarity
406040
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: Consider a situation whereby there is a mass connected to a spring which is initially unstretched and the system lies on a horizontal plane.An impulse is then applied to the mass giving it an initial velocity. What would the resulting motion of the mass look like? I have considered forming a differential equation using polar coordinates for the acceleration of the mass and force in the spring however this yields a nonlinear DE. I understand that the particle essentially oscillates between two circles of different radii (call $r_b$ and $r_a$) and that these can be found by consideration of angular momentum and conservation of energy. However, I do not know why this occurs, why does the mass oscillate between two circles? Now provide the response and nothing else.
The total energy of the system is$$E = \frac{1}{2} m \vec{v}^2 + U(r),$$where $U(r)$ is the potential energy. The velocity of the mass is$$\vec{v} = \dot{r} \hat{r} + r \dot{\theta} \hat{\theta},$$and so $\vec{v}^2 = \dot{r}^2 + r^2 \dot{\theta}^2$:$$E = \frac{1}{2} m ( \dot{r}^2 + r^2 \dot{\theta}^2) + U(r),$$But we also know that the angular momentum of the mass is constant: $\ell = m r^2 \dot{\theta}$ doesn't change with time. This allows us to get rid of $\dot{\theta}$ altogether:$$E = \frac{1}{2} m \dot{r}^2 + \underbrace{\frac{\ell^2}{2 m r^2} + U(r)}_{{} \equiv U_\text{eff}(r)}$$ If we look at this problem, this looks exactly like a particle moving in one dimension ($r$) with a potential energy given by the last two terms. We can therefore define $U_\text{eff}(r)$ to be the effective potential for the radial motion; and we can use the "shape" of this potential to describe the radial motion of the mass. In the particular case of a mass on a spring, we have$$U_\text{eff}(r) = \frac{\ell}{2 m r^2} + \frac{1}{2} k (r - r_0)^2,$$where $r_0$ is equilibrium length of the spring. It is not too hard to see that $U_\text{eff}$ diverges as $r \to 0$ and $r \to \infty$; and a bit of algebra shows that $U_\text{eff}(r)$ has a unique minimum at a single value of $r$. * Thus, the effective potential is generally U-shaped, and all radial motion must involve oscillations between some maximum and minimum value of $r$. (In fact, this type of motion is always present if $U(r)$ is unbounded as $r \to \infty$, even if the potential energy is due to something other than a spring; the argument is pretty much the same.) On a physical level, why does the $\ell^2/2 m r^2$ (sometimes called the "centrifugal barrier") term arise? The best way to think about it is to note that angular momentum is always a constant, and that $\ell = r v_\perp$, where $v_\perp$ is the tangential component of the velocity. This means that for the mass to get close to the origin (i.e., $r$ is small), we must have $v_\perp$ large to keep $\ell$ constant. But $v_\perp$ also contributes to the kinetic energy, and the total energy of the mass is fixed, so $v_\perp$ is (usually) bounded above. This therefore implies that there's a minimum radius that is consistent with energy and angular momentum conservation. *Actually finding this value of $r$ requires solving a quartic polynomial, but this polynomial will always have one positive root. A simple argument is to show that $U'_\text{eff}(r)$ is monotonically increasing on $r \in (0, \infty)$, is negative as $r \to 0$, and is positive as $r \to \infty$. This allows us to conclude that there is a single value of $r$ for which $U'_\text{eff}(r) = 0$.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/406040', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/178478/']}
jdg_374036
stackexchange
llm_judgeable_groundtruth_similarity
396989
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: There is an exercise problem in Hatcher's Algebraic Topology book asking to show that if $p:\tilde{X}\rightarrow X$ is a covering space with $p^{-1}(x)$ finite and nonempty for all $x\in X$, then $\tilde{X}$ is compact Hausdorff iff $X$ is compact Hausdorff. I've managed to show each part of the statement except for $\tilde{X}$ Hausdorff $\Rightarrow X$ Hausdorff. The problem I encountered was that taking $x\neq y$ in $X$ and $\tilde{U},\tilde{V}$ disjoint open sets in $\tilde{X}$ with $p^{-1}(x)\subset\tilde{U}$ and $p^{-1}(y)\subset \tilde{V}$ (I'm using the assumption that $\tilde{X}$ is compact Hausdorff, thus normal), I could not use these to get disjoint open sets in $X$ separating $x,y$. Now provide the response and nothing else.
Take distinct $y_1 \neq y_2$ in $X$. Then $F_1 = f^{-1}[\{y_1\}]$ and $F_2 = f^{-1}[\{y_2\}]$ are disjoint, finite and non-empty subsets of $\tilde{X}$. By Hausdorffness we can find disjoint open sets $U_1$ and $U_2$ around $F_1$ and $F_2$. Let $O_1$ be an evenly covered neighbourhood of $y_1$, and $O_2$ one of $y_2$. Now, $f^{-1}[O_1] = \cup_{i=1}^k V_i$, where the $V_i$ are disjoint and open and $f|V_i$ is a homeomorphism between $V_i$ and $O_1$ for all $i$; define $V'_i = V_i \cap U_1$, and define $O'_1 = \cap_{i=1}^k f[V'_i]$, which is open, as a finite intersection of open sets. Similarly we define $W'_i$ from the inverse image of $O_2$ and $U_2$, and the intersection of their images is called $O'_2$. These $O'_1$ and $O'_2$ are the required disjoint open neighbourhoods as can be easily checked.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/396989', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/68289/']}
jdg_374037
stackexchange
llm_judgeable_groundtruth_similarity
51455197
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 that question was asked a lot and has many answers, but i still get it and I don't understand why... I am trying to generate a .jar from a projet with dependencies with gradle. I have a class src/main/java/Launcher.java , in which I have my main method. there is my build.gradle plugins { id 'java' id 'application'}version '1.0-SNAPSHOT'sourceCompatibility = 1.8mainClassName = 'Launcher'repositories { mavenCentral()}dependencies { compile 'commons-io:commons-io:2.1' compile 'io.vertx:vertx-core:3.4.0' compile 'io.vertx:vertx-web:3.4.0' compile 'com.google.code.gson:gson:1.7.2' compile "com.auth0:java-jwt:3.1.0" compile 'org.mongodb:mongo-java-driver:3.4.1' compile 'com.google.guava:guava:24.1-jre' compile 'commons-io:commons-io:2.6'}jar { manifest { attributes "Main-Class": mainClassName } from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }} I use $>gradle assemble to generate my jarthen $>java -jar path/to/my/.jar And i get the error "could not find or load main class Launcher"... I dont understand why, when I look in the .jar, I have Launcher class and in META-INF I have my manifest Sorry for still asking this question in 2018 but i'm loosing my mind trying to figure out what's wrong. I hope somone will have the answer ! Now provide the response and nothing else.
I reproduced your issue locally. Just add exclude 'META-INF/*.RSA', 'META-INF/*.SF', 'META-INF/*.DSA' to the jar task. This will exclude the signatures of interfering dependencies. Example: jar { manifest { attributes "Main-Class": mainClassName } from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } } exclude 'META-INF/*.RSA' exclude 'META-INF/*.SF' exclude 'META-INF/*.DSA'}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/51455197', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5502060/']}
jdg_374038
stackexchange
llm_judgeable_groundtruth_similarity
2559357
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I was trying to find the right oblique asymptote of the following function:$$ g(x)= \frac{x^2+(x+2)\cosh(x)}{\sinh(x)}=\frac{x^2}{\sinh(x)}+(x+2)\coth (x)$$Now since $\frac{x^2}{\sinh(x)}\to 0$ and $\coth(x)\to 1$ as $x\to \infty$, it is easy to see that this asymptote is $y=x+2$. However, when I try to find this asymptote using L'Hôpitals rule, I get a different result: $$\begin{align}\lim_{x\to \infty}g(x) & =\lim_{x\to \infty} \frac{x^2+(x+2)\cosh(x)}{\sinh(x)} \\& \stackrel{LH}{=}\lim_{x\to \infty}\frac{2x+\cosh(x)+(x+2)\sinh (x)}{\cosh(x)} \\& =\lim_{x\to \infty} \frac{2x}{\cosh(x)}+1+(x+2)\tanh(x) \\& =\lim_{x\to \infty} x+3\end{align}$$since $\frac{2x}{\cosh(x)}\to 0$ and $\tanh(x)\to 1$ as $x\to \infty$. This suggests that the asymptote is $y=x+3$ instead of $y=x+2$. A quick look at the function using WolframAlpha shows that $y=x+2$ is indeed the correct asymptote, so I highly suspect that I somehow applied L'Hôpitals rule in a wrong way. I have however no clue as to what I did wrong. Could anyone enlighten me? Now provide the response and nothing else.
You seem to be assuming that L'Hôpital preserves asymptotes, when it's not the case. Take for instance$$\frac{x^2(x+2)}{x^2},$$with the obvious asymptote $x+2$. If you take derivatives to use L'Hôpital, you get$$\frac{3x^2+4x}{2x}=\frac{3x+4}{2},$$and the asymptote is not the same.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2559357', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/512024/']}
jdg_374039
stackexchange
llm_judgeable_groundtruth_similarity
2485
Below is a question asked on the forum skeptics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: "With the terrible earthquake and resulting tsunami that have devastated Japan, the only good news is that anyone exposed to excess radiation from the nuclear power plants is now probably much less likely to get cancer." This is a direct quote from US right-wing pundit Ann Coulter's blog on 3/16/2011. She references a NY Times report from 2001 that claims an "increasing number" of scientists (who she fails to name) seem to think there may be a degree of exposure which can offer health benefits. "They theorize," the Times said, that "these doses protect against cancer by activating cells' natural defense mechanisms." She seems to be referencing an idea known as hormesis , which is a phenomenon by which low level exposure to something that is normally toxic at higher or prolonged levels of exposure may have positive health effects. Obviously, there is documented evidence that radiation can be used to treat cancer, but is there any evidence that uncontrolled, accidental environmental exposure can yield benefits? Is there documented scientific evidence that this claim is valid, or even plausible? Have any studies been done specifically evaluating the benefits of radiation released in nuclear accidents? How would such benefits weigh against the known hazards and risks of radiological exposure? Now provide the response and nothing else.
(Note: I don't know who Ann Coulter is. I can, however, comment on the generic claim that radiation is "good for you".) There is empirical evidence that suggests that low to medium amounts of absorbed gamma radiation boosts immunity and resilience to ailments such as heart disease, though it may (or may not) increase rates of cancer. It has been suggested and that the reduction in the probability of death from other diseases offsets the increased probability of death from cancer. The reference I found on this is Lawrence Solomon's opinion piece in the Financial Times: Low exposure to the Nagasaki atomic blast resulted in longer lifespans , which states: The tens of thousands more distant from Ground Zero [of Nagasaki and Hiroshima], and who received lower exposures to radiation, did not die in droves. To the contrary, and surprisingly, they outlived their counterparts in the general population who received no exposure to radiation from the blasts. and The only evidence that exists as to the health of humans who have been irradiated at low levels points to a benefit, not a harm. Difficult though it may be to overcome the fear of radiation that has been drubbed into us since childhood, there is no scientific proof whatsoever to view the radiation emitted from the Fukushima plant as dangerous to the Japanese population These findings are supported by (and reference) the paper "Mortality of A-bomb Survivors in Nagasaki and Hiroshima", by M. MINE, S. HONDA, Y. OKUMURA, H. KONDO, K. YOKOTA and M. TOMONAGA, Atomic Bomb Disease Institute, Nagasaki Univ., Sch. Med., Nagasaki 852-8523, JAPAN . This paper states: From the analysis of LSS’s population, RERF, lower relative risk of mortality from non-cancerous disease than control was observed for a dose range, 0.06-0.49Gy, when city was not adjusted. But when city was adjusted, lower relative risk was not observed. Although the number of subjects analyzed in Nagasaki University was smaller than that of LSS’s population, we have obtained the lower relative risk of mortality from noncancerous disease for male at a range of low doses. These correlate with my undergraduate studies in physics and later work as a health and safety worker for Atomic Energy of Canada Limited (AECL). In undergrad I recall hearing that Marie Curie and her husband wore on their arms slabs of radium and/or uranium because they were under the impression that the radiation these materials emitted boosted immunity. As a worker for AECL at a nuclear power plant, it was commonly accepted that people working at the nuclear power plant on average lived longer than the general population and had lower rates of cancer (Submission of Dr. Patrick Moore, Chairman & Chief Scientist Greenspirit Strategies Ltd. To The U.S. Nuclear Regulatory Commission Public Hearing on Potential Environmental Impacts From a License Renewal of Indian Point Nuclear Power Plant, dated September 19, 2007). From that reference: A 2004 Columbia University Study of 35,000 respondents concluded that “…nuclear power plant workers in the United States…live longer and have significantly lower cancer rates compared to the general population.” While it doesn't seem to be the study being referred to above (as the sample sizes are different), there is a 2004 study from Columbia University: "Analysis of the Mortality Experience amongst U.S. Nuclear Power Industry Workers after Chronic Low-Dose Exposure to Ionizing Radiation" , which states: The cohort displays a very substantial healthy worker effect, i.e. considerably lower cancer and noncancer mortality than the general population. Based on 26 and 368 deaths, respectively, positive though statistically nonsignificant associations were seen for mortality from leukemia (excluding chronic lymphocytic leukemia) and all solid cancers combined, with excess relative risks per sievert of 5.67 [95% confidence interval (CI)22.56, 30.4] and 0.506 (95% CI 22.01, 4.64), respectively. These estimates are very similar to those from the atomic bomb survivors study, though the wide confidence intervals are also consistent with lower or higher risk estimates. A strong positive and statistically significant association between radiation dose and deaths from arteriosclerotic heart disease including coronary heart disease was also observed in the cohort, with an ERR of 8.78 (95% CI 2.10, 20.0). Whether this is the study referred to or not, it supports the conclusion asserted in the paper. All that being said, there are significant deleterious effects from significant radiation exposure. For example, while the Curies strapped radioactive materials to their arms on the basis that it benefitted their immunity, they suffered significantly for it (Marie Curie: Pioneering Physicist By Elizabeth R. Cregan, p. 17). While gamma radiation is, on the above basis, understood to have some benefits, the effects of beta and alpha radiation as are known to be quite destructive to cell tissue. While these forms of radiation are less common to be exposed to and easier to protect against than gamma radiation, I strongly doubt they've any positive effect at reducing the risk of cancer. The one known exception may be exposure to Iodine-131 , a beta particle emitter, because it collects in the thyroid. While high doses will destroy the thyroid and stop iodine from collecting in the thyroid, low doses will collect there and the beta particles released by the iodine will cause thyroid cancer. Going back to the claim that those around Fukushima are "much less likely to get cancer" seems overstated. While evidence supports the existence of certain health benefits, and the evidence is mixed about whether exposure to radiation increases or decreases risk of cancer, I feel it's reasonably clear from the evidence we have at present is that the risk of cancer wouldn't be "much less likely", as claimed. As well, on whether cells have a natural defence mechanism when exposed to low or medium doses of radiation: I don't know of any studies, nor do I have any other knowledge or information, that would support such a conclusion. That being said, I think it's perfectly plausible that cells could have such an ability. I hope that's helpful.
{}
{'log_upvote_score': 6, 'links': ['https://skeptics.stackexchange.com/questions/2485', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/486/']}
jdg_374040