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
|
17590832
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have the following code: foreach(// Some condition here){ while (// Some condition here) { foreach (// Some condition here) { if (// Condition again) { //Do some code } if (// Condition again) { //Stop the first foreach then go back to first foreach } } }} What I want to do is when I hit the 2nd if statement on the last foreach loop is to return on the first foreach loop. Note: If the 2nd if statement is not true, it should continue the last foreach loop until the condition is not true. Thanks in advance!
Now provide the response and nothing else.
|
The only way to this directly is with a goto . Another (better) option is to restructure until the problem goes away. For instance by putting the inner code (while + foreach) in a method and use return to get back.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17590832', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2423585/']}
|
jdg_374641
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
228285
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
How can I get the negation of $\exists!$ (unique existential quantification)? if it's $\forall$, So if I wanna re-negate the last one, I'll get $\exists$ but it's not the same as what we started with! Did I do something wrong here? For example: $$P : \exists! x\in \mathbb{R} \text{ such that } x^2 = 0$$ it means $\exists x \in \mathbb{R}\text{ such that } x^2 = 0\wedge x $ is unique, So the negation is $\forall x \in \mathbb{R}\space x^2 \ne 0 \vee x \text{ isn't unique}$ is this a false statement?
Now provide the response and nothing else.
|
I think the best thing to do is unpack what $\exists !$ means. $\exists ! x \phi(x)$ is shorthand for$$\exists x (\phi(x) \wedge \forall y (\phi(y) \rightarrow y=x))$$ so negating this gives$$\forall x(\neg \phi(x) \vee \exists y(\phi(y) \wedge y \ne x))$$which is to say: either no $x$ satisfies $\phi$ or there is a $y$ distinct from $x$ which satisfies $\phi$. This is of the form $\forall x (\neg A \vee B)$, which is the same as $\forall x(A \to B)$, so we could write$$\forall x(\phi(x) \to \exists y(\phi(y) \wedge y \ne x))$$which is to say: if $x$ satisfies $\phi$ then there is a $y$ distinct from $x$ which does too. This is closer to how I'd think intuitively about the negation of $\exists!$. Unfortunately there isn't a very succinct way of writing it.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/228285', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/34920/']}
|
jdg_374642
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
270769
|
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:
In my script /usr/local/bin/backup , that I call every hour from /etc/crontab , I use rsync to copy data to an off-site server.That all worked fine, even in cases where we had somewhat more new data than can be pushed out in an hour. Last week someone copied an 11GB file on the data partition and when I found out the next day there were 14 rsync programs running in parallel, each of then getting no bandwidth and each probably working on the same huge file. I killed them all (before realising I should have kept the first one running), stopped the cron job and ran the backup script by hand. I can write out a file in the script before starting rsync and check in the script if that file is already there to prevent backup from running in parallel. Is there an easier way of doing this? My /etc/crontab entry: 5 * * * * root /usr/local/bin/backup
Now provide the response and nothing else.
|
There are different ways of doing this, but IMO the easiest is inserting flock before the command in the crontab file: 5 * * * * root flock -n /var/lock/backup /usr/local/bin/backup The /var/lock/backup file is the lock that flock uses and -n immediately makes the command fail if the lock already exists. This could of course mean that if one backup takes 1 hour and 1 minute, that the next one starts 59 minutes later. If that is a problem you could look into using -x .
|
{}
|
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/270769', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/161824/']}
|
jdg_374643
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18788784
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to run this LINQ simple code to have record number in LINQ but result is beneath error var model = _db2.Persons.Select( (x, index) => new { rn = index + 1, col1 = x.Id }).ToList(); Error: LINQ to Entities does not recognize the method 'System.Linq.IQueryable 1[<>f__AnonymousType2 2 [System.Int32,System.Int32]] Select[Person,<>f__AnonymousType2 2](System.Linq.IQueryable 1 [MvcApplication27.Models.Person], System.Linq.Expressions.Expression 1[System.Func 3 [MvcApplication27.Models.Person,System.Int32,<>f__AnonymousType2`2 [System.Int32,System.Int32]]])' method, and this method cannot be translated into a store expression.
Now provide the response and nothing else.
|
The problem is that LINQ to Entities doesn't understand how to convert that Select overload (the one that gives you the index) into a SQL query. You can fix this by first selecting the portion from the DB you need (to avoid selecting every column unnecessarily), then doing AsEnumerable() to take it as an IEnumerable<T> instead of an IQueryable<T> , and then doing the Select purely in C# (in short, IQueryable<T> s are converted to SQL, while IEnumerable<T> s are run in code). var model = _db2.Persons.Select(x => x.Id).AsEnumerable().Select( (id, index) => new { rn = index + 1, col1 = id }).ToList(); Note that the query as you have it appears to be unordered, so the id/index pairings can change each time you call this. If you expected consistency, you should order by something (e.g. _db2.Persons.OrderBy(...) ). Edit Adding comment from Scott : As a nice reference here is the list of all Linq statements built in to the framework and a listing if it is compatible or not .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18788784', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2774025/']}
|
jdg_374644
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14321127
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a data frame which I would like to write it to a pdf file in organized fashion. For example, my df looks like this: Date County Trade1/1/2012 USA 51/1/2012 Japan 41/2/2012 USA 101/3/2012 Germany 15 I would like to output to be group by Date, place a space or line break after each group; I have this piece of code but this prints out everything to the pdf file without grouping: library(gridExtra)pdf("trade.pdf", height=11, width=8.5)grid.table(df)dev.off() Any ideas how can best present this data set in a pdf file with grouping on Date? I like to use grid.Extra. Anybody knows how to put a title to grid.Extra?
Now provide the response and nothing else.
|
This code should work: library(gridExtra)df <- read.table(text = "1/1/2012 USA 51/1/2012 Japan 41/2/2012 USA 101/3/2012 Germany 15")names(df) <- c("Date","Country","Trade")EqDatedf <- as.data.frame(df[1,])EmptyLine <- data.frame(Date = "",Country = "",Trade = "")pdf(file = "q.pdf")for (i in 2:nrow(df)) {if (as.vector(df$Date[i]) == as.vector(df$Date[i-1])) {EqDatedf <- rbind(EqDatedf, df[i,])}else {EqDatedf <- rbind(EqDatedf, EmptyLine)EqDatedf <- rbind(EqDatedf, df[i,]) }}grid.table(EqDatedf, show.rownames = FALSE)dev.off()
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14321127', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1471980/']}
|
jdg_374645
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
38285223
|
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 stuck while accessing array inside json using newly introduced JSON_VALUE function. Please consider following code - IF EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='JsonData') DROP TABLE JsonData;goCREATE TABLE JsonData(JsonData nvarchar(max));DECLARE @SQL nvarchar(max);DECLARE @Table AS TABLE(JsonPath VARCHAR(256));INSERT INTO JsonData(JsonData)VALUES('{ "firstName": "John", "lastName" : "doe", "age" : 26, "address" : { "streetAddress": "naist street", "city" : "Nara", "postalCode" : "630-0192" }, "phoneNumbers": [ { "type" : "iPhone", "number": "0123-4567-8888" }, { "type" : "home", "number": "0123-4567-8910" } ]}')INSERT INTO @TableSELECT VALUE FROM OPENJSON('{"Path1":"$.firstName","Path2":"$.phoneNumbers[:1].number"}') ;SELECT @SQL=(SELECT 'UNION SELECT '''+ CAST(JsonPath AS VARCHAR(256)) +''',JSON_VALUE(JsonData,'''+a.JsonPath+''') FROM JsonData a' FROM @Table a FOR XML PATH(''), TYPE) .value('.','NVARCHAR(MAX)')FROM @Table t;SELECT @SQL=RIGHT(@SQL,LEN(@SQL)-5)PRINT @SQL EXEC SP_EXECUTESQL @SQL; Here If I want to access specific phone number then usual syntax of accessing this node is not working. I am getting following error in this case JSON path is not properly formatted. Unexpected character ':' is found at position 15. Though when I checked at http://jsonpath.com , I am able to retrieve value. Does SQL server 2016 uses some different syntax for accessing JSON values?
Now provide the response and nothing else.
|
To get all from phoneNumbers: DECLARE @json nvarchar(max)= '{ "firstName": "John", "lastName" : "doe", "age" : 26, "address" : { "streetAddress": "naist street", "city" : "Nara", "postalCode" : "630-0192" }, "phoneNumbers": [ { "type" : "iPhone", "number": "0123-4567-8888" }, { "type" : "home", "number": "0123-4567-8910" } ] }' SELECT [Type], [Number] FROM OPENJSON( @json, '$.phoneNumbers' ) WITH ([Type] NVARCHAR(25) '$.type', [Number] NVARCHAR(25) '$.number');
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/38285223', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2941322/']}
|
jdg_374646
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
167576
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I would like this to be the ultimate discussion on how to check if a table exists in SQL Server 2000/2005 using SQL Statements. Here are two possible ways of doing it. Which one is the standard/best way of doing it? First way: IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' AND TABLE_NAME='mytablename') SELECT 1 AS res ELSE SELECT 0 AS res; Second way: IF OBJECT_ID (N'mytablename', N'U') IS NOT NULL SELECT 1 AS res ELSE SELECT 0 AS res; MySQL provides the simple SHOW TABLES LIKE '%tablename%'; statement. I am looking for something similar.
Now provide the response and nothing else.
|
For queries like this it is always best to use an INFORMATION_SCHEMA view. These views are (mostly) standard across many different databases and rarely change from version to version. To check if a table exists use: IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'TheSchema' AND TABLE_NAME = 'TheTable'))BEGIN --Do StuffEND
|
{}
|
{'log_upvote_score': 12, 'links': ['https://Stackoverflow.com/questions/167576', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1508/']}
|
jdg_374647
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
16292
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
This is more of a textbook semantics issue. Is the alternative hypothesis always two-tailed when all that is known is a null hypothesis $H_0$ where $p$ equals some arbitrary figure, where an arbitrary sample proportion and significance level are also given (assuming all requirements are met)?
Now provide the response and nothing else.
|
Yes, although it's more than just a textbook semantics issue. In the absence of information about the form the alternate hypothesis should take (e.g., in the absence of a research question like "Does the new drug work better than the best-known drug on the market?") then the formulation of the alternate should just be the negation of the null. Thus the form of $H_0$ and $H_a$ should be $p = p_0$ and $p \neq p_0$, respectively. As non-expert points out in the comments, this then means that you need to perform a two-tailed test. Two comments: Remember that the statements of the null and alternate hypotheses don't have anything to do with the sample proportion or with the significance level. In particular, it's good practice to formulate the hypotheses before the results from the sample are known. It is interesting that Ronald Fisher, one of the developers of tests of significance, effectively took the position that one should always use the two-sided alternate hypothesis. To quote from the Wikipedia article on the alternative hypothesis , "[The alternate hypothesis] was not part of Ronald Fisher's formulation of statistical hypothesis testing, and he violently opposed its use. In Fisher's approach to testing, the central idea is to assess whether the observed dataset could have resulted from chance if the null hypothesis were assumed to hold, notionally without preconceptions about what other model might hold. Modern statistical hypothesis testing accommodates this type of test since the alternative hypothesis can be just the negation of the null hypothesis."
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/16292', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/2054/']}
|
jdg_374648
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3182920
|
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 trouble solving this exercise: find the first three terms of the Laurent series of $\sin z/(1 - \cos z)$ centered at $z=0$ . I have found the first two. I proved that at $z=0$ we have a first order pole and the first one I calculated the residue. I also thought that the second term is zero because this function is odd. Now I have problems with the third. Someone can help me?
Now provide the response and nothing else.
|
You know that laurent series of $sin(z) = z - \frac{z^3}{6} + \frac{z^5}{120} + O (z^{7})$ . Then, the laurent series of $ 1-cos(z)= \frac{z^2}{2}-\frac{z^4}{24}+O(z^{6})$ Overall you have $\frac{z - \frac{z^3}{6} + \frac{z^5}{120} + O (z^{7})}{\frac{z^2}{2}-\frac{z^4}{24}+O(z^{6})}$ . Now look at the denominator: $(\frac{z^2}{2}-\frac{z^4}{24}+\frac{z^6}{720}+O(z^8))^{-1}=(\frac{z^2}{2})^{-1}(1-\frac{z^2}{12}+\frac{z^4}{360}+O(z^{6}))^{-1}=\frac{2}{z^2}(1-(-\frac{z^2}{12}+\frac{z^4}{360})+\frac{z^4}{144}+O(z^6))=\frac{2}{z^2}(1+\frac{z^2}{12}+\frac{z^4}{240})=\frac{2}{z^2}+\frac{1}{6}+\frac{z^2}{120}$ Multiply everything together to get: $(z - \frac{z^3}{6} + \frac{z^5}{120} + O (z^{7}))$ $(\frac{2}{z^2}+\frac{1}{6}+\frac{z^2}{120} )$ $ =\frac{2}{z}-\frac{z}{6}-\frac{z^3}{360} +O(z^5).$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3182920', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/652058/']}
|
jdg_374649
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
36035733
|
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 read all documentation about script tag but I cannot find how to include a custom JavaScript in AMP HTML. I know the <script> tag is prohibited unless its type is application/ld+json . There are default AMP HTML runtime components and extended components which contain specific form for different components, but I could not find a specific one for custom JavaScript. Here is the script tag I want to include in AMP HTML; <script src="https://arifkarim.com/widget/layouts/global/js/legaltext.js"></script>
Now provide the response and nothing else.
|
The whole point of AMP is to only allow a subset of web technologies to stop your page being slow. Javascript is often the cause of slow websites and so AMP pages do not allow them (except for the AMP scripts themselves), though they've tried to fill in the gap this leaves with amp components which are specially written to not be slow. So if you want to use Javascript you've several choices: Don't use AMP. Nobody is forcing this on you. Remove the script tag from your amp document and live without that functionality. Find an amp-component which does the same as your JavaScript and use that instead. Not having a clue what legaltext.js I would guess by the name it displays some legal text like a cookie notice so maybe the amp-user-notification widget would work instead? Use your Javascript in an amp iframe . These are allowed in amp pages but will presumable be loaded with a lower priority to ensure they don't slow down the main page.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36035733', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/583261/']}
|
jdg_374650
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
56832
|
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 guess the answer should be yes, but I still feel something is not right. There should be some general results in the literature, could anyone help me?
Now provide the response and nothing else.
|
No. Consider three variables, $X$, $Y$ and $Z = X+Y$. Their covariance matrix, $M$, is not positive definite, since there's a vector $z$ ($= (1, 1, -1)'$) for which $z'Mz$ is not positive. Population covariance matrices are positive semi-definite. (See property 2 here .) The same should generally apply to covariance matrices of complete samples (no missing values), since they can also be seen as a form of discrete population covariance. However due to inexactness of floating point numerical computations, even algebraically positive definite cases might occasionally be computed to not be even positive semi-definite; good choice of algorithms can help with this. More generally, sample covariance matrices - depending on how they deal with missing values in some variables - may or may not be positive semi-definite, even in theory. If pairwise deletion is used, for example, then there's no guarantee of positive semi-definiteness. Further, accumulated numerical error can cause sample covariance matrices that should be notionally positive semi-definite to fail to be. Like so: x <- rnorm(30) y <- rnorm(30) - x/10 # it doesn't matter for this if x and y are correlated or not z <- x+y M <- cov(data.frame(x=x,y=y,z=z)) z <- rbind(1,1,-1) t(z)%*%M%*%z [,1][1,] -1.110223e-16 This happened on the first example I tried (I probably should supply a seed but it's not so rare that you should have to try a lot of examples before you get one). The result came out negative , even though it should be algebraically zero. A different set of numbers might yield a positive number or an "exact" zero. -- Example of moderate missingness leading to loss of positive semidefiniteness via pairwise deletion: z <- x + y + rnorm(30)/50 # same x and y as before.xyz1 <- data.frame(x=x,y=y,z=z) # high correlation but definitely of full rank xyz1$x[sample(1:30,5)] <- NA # make 5 x's missing xyz1$y[sample(1:30,5)] <- NA # make 5 y's missing xyz1$z[sample(1:30,5)] <- NA # make 5 z's missing cov(xyz1,use="pairwise") # the individual pairwise covars are fine ... x y zx 1.2107760 -0.2552947 1.255868y -0.2552947 1.2728156 1.037446z 1.2558683 1.0374456 2.367978 chol(cov(xyz1,use="pairwise")) # ... but leave the matrix not positive semi-definiteError in chol.default(cov(xyz1, use = "pairwise")) : the leading minor of order 3 is not positive definite chol(cov(xyz1,use="complete")) # but deleting even more rows leaves it PSD x y zx 0.8760209 -0.2253484 0.64303448y 0.0000000 1.1088741 1.11270078z 0.0000000 0.0000000 0.01345364
|
{}
|
{'log_upvote_score': 7, 'links': ['https://stats.stackexchange.com/questions/56832', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/22100/']}
|
jdg_374651
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2010255
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
While finding the Taylor Series of a function, when are you allowed to substitute? And why ? For example: Around $x=0$ for $e^{2x}$ I apparently am allowed to substitute $u=2x$ and then use the known series for $e^u$. But for $e^{x+1}$ I am not allowed to substitute $u=x+1$. I know the technique for finding the Taylor Series of $e^{x+1}$ around $x=0$ by taking $e^{x+1}=e\times e^x$. However, I am looking for understanding and intuition for when and why it is allowed to apply substitution. Note: there are several question that are similar to this one, but I have found none that actually answers the question "why"; or that shows a complete proof. EDIT: Thanks to the answer of Markus Scheuer I should refine the question to cases where the series is finite, for example $n\to3$
Now provide the response and nothing else.
|
A function $f(x)$ analytic at $x=0$ can be represented as power series within an open disc with radius of convergence $R$. \begin{align*}f(x)=\sum_{n=0}^\infty a_nx^n\qquad\qquad \qquad |x|<R\end{align*} Any substitution $x=g(u)$ is admissible as long as we respect the radius of convergence . \begin{align*}f(g(u))=\sum_{n=0}^\infty a_n \left(g(u)\right)^n\qquad\qquad\quad |g(u)|<R\end{align*} We know $f(u)=e^u$ can be represented as Taylor series convergent for all $u\in\mathbb{R}$, i.e. the radius of convergence $R=\infty$.\begin{align*}f(u)=e^u=\sum_{n=0}^\infty \frac{u^n}{n!}\qquad\qquad\qquad u\in \mathbb{R}\end{align*} Substitution $u=2x$ We consider \begin{align*}f(2x)=e^{2x}=\sum_{n=0}^\infty \frac{(2x)^n}{n!}\qquad\qquad\qquad 2x\in \mathbb{R}\end{align*} This substitution is admissible for all $x \in \mathbb{R}$ since $$2x\in\mathbb{R}\qquad\Longleftrightarrow\qquad x\in\mathbb{R}$$ So, the radius of convergence of the Taylor series of $f(2x)=e^{2x}$ is $\infty$. We obtain\begin{align*}f(2x)=e^{2x}=\sum_{n=0}^\infty \frac{(2x)^n}{n!}\qquad\qquad\qquad x\in \mathbb{R}\end{align*} Substitution $u=x+1$ We consider \begin{align*}f(x+1)=e^{x+1}=\sum_{n=0}^\infty \frac{(x+1)^n}{n!}\qquad\qquad\qquad x+1\in \mathbb{R}\end{align*} This substitution is admissible for all $x \in \mathbb{R}$ since $$x+1\in\mathbb{R}\qquad\Longleftrightarrow\qquad x\in\mathbb{R}$$ So, the radius of convergence of the Taylor series of $f(x+1)=e^{x+1}$ is $\infty$. We obtain\begin{align*}f(x+1)=e^{x+1}=\sum_{n=0}^\infty \frac{(x+1)^n}{n!}\qquad\qquad\qquad x\in \mathbb{R}\end{align*} We also obtain \begin{align*}e\cdot e^x&=\left(\sum_{k=0}^\infty \frac{1}{k!}\right)\left(\sum_{l=0}^\infty \frac{x^l}{l!}\right)\\&=\sum_{n=0}^\infty \left(\sum_{{k+l=n}\atop{k,l\geq 0}}\frac{1}{k!}\cdot\frac{x^l}{l!}\right)\\&=\sum_{n=0}^\infty \left(\sum_{l=0}^n\frac{1}{(n-l)!}\cdot\frac{x^l}{l!}\right)\\&=\sum_{n=0}^\infty\left(\sum_{l=0}^n\binom{n}{l}x^l\right)\frac{1}{n!}\\&=\sum_{n=0}^\infty\frac{(x+1)^n}{n!}\\&=e^{x+1}\end{align*} Conclusion: We can use any substitution for convenience as long as we respect the radius of convergence.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2010255', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/245761/']}
|
jdg_374652
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
174992
|
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've been following the convention of adding created and modified columns to most of my database tables. I also have been leaving the modified column as null on record creation and only setting a value on actual modification. The other alternative is to set the modified date to be equal to created date on record creation. I've been doing it the former way but I recent ran into one con which is seriously making me think of switching. I needed to set a database cache dependency to find out if any existing data has been changed or new data added. Instead of being able to do the following: SELECT MAX(modified) FROM customer I have to do this: SELECT GREATEST(MAX(created), MAX(modified)) FROM customer The negative being that it's a more complicated query and slower. Another thing is in file systems I believe they usually use the second convention of setting modified date = created date on creation. What are the pros and cons of the different methods? That is, what are the issues to consider? UPDATE I believe given the apparent trade-offs I'm going to go with modified = created strategy. In addition, I was curious how other web databases handled this and I noticed drupal seems to follow the convention of modified = created also.
Now provide the response and nothing else.
|
With modified = created if you want the latest modifications with never edited ones included you can rely on the modified column. However if the modified column is initialized with null you have to do a COALESCE(modified, created) which would perform worse. With modified = created if you want modifications with never edited ones excluded you simply where modified != created , and with modified initialized null you have to do a where modified IS NOT NULL which would have a fairly similar performance, though slightly better and increasing performance with more records having a null modified column. These are really the only differences, both give the same abilities to filter and aggregate data, you just have to use slightly different techniques for each. I prefer initializing modified = created to avoid the coalesces. Though initializing with nulls may depending on your database system save disk space, especially if edits are uncommon to the point that you'll have mostly nulls. Also if you have mostly nulls, then the performance of the where modified IS NOT NULL will be a good bit better than the where modified != created due to the smaller set meeting the condition. Edit:Also, if you are interested in data based on modifications frequently enough that you would put an index on this column (pretty uncommon scenario but I don't know your use case), the index where modified = created would have different performance characteristics than initializing it with null, and any coalesces would with significant enough null's lose any benefit from the index because the coalesces will push the query off the index.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/174992', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/16411/']}
|
jdg_374653
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7036350
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
With ARC, I can no longer cast CGColorRef to id . I learned that I need to do a bridged cast. According clang docs : A bridged cast is a C-style cast annotated with one of three keywords: (__bridge T) op casts the operand to the destination type T . If T is a retainable object pointer type, then op must have a non-retainable pointer type. If T is a non-retainable pointer type, then op must have a retainable object pointer type. Otherwise the cast is ill-formed. There is no transfer of ownership, and ARC inserts no retain operations. (__bridge_retained T) op casts the operand, which must have retainable object pointer type, to the destination type, which must be a non-retainable pointer type. ARC retains the value, subject to the usual optimizations on local values, and the recipient is responsible for balancing that +1. (__bridge_transfer T) op casts the operand, which must have non-retainable pointer type, to the destination type, which must be a retainable object pointer type. ARC will release the value at the end of the enclosing full-expression, subject to the usual optimizations on local values. These casts are required in order to transfer objects in and out of ARC control; see the rationale in the section on conversion of retainable object pointers. Using a __bridge_retained or __bridge_transfer cast purely to convince ARC to emit an unbalanced retain or release, respectively, is poor form. In what kind of situations would I use each? For example, CAGradientLayer has a colors property which accepts an array of CGColorRef s. My guess is that I should use __brige here, but exactly why I should (or should not) is unclear.
Now provide the response and nothing else.
|
I agree that the description is confusing. Since I just grasped them, I'll try to summarize: (__bridge_transfer <NSType>) op or alternatively CFBridgingRelease(op) is used to consume a retain-count of a CFTypeRef while transferring it over to ARC. This could also be represented by id someObj = (__bridge <NSType>) op; CFRelease(op); (__bridge_retained <CFType>) op or alternatively CFBridgingRetain(op) is used to hand an NSObject over to CF-land while giving it a +1 retain count. You should handle a CFTypeRef you create this way the same as you would handle a result of CFStringCreateCopy() . This could also be represented by CFRetain((__bridge CFType)op); CFTypeRef someTypeRef = (__bridge CFType)op; __bridge just casts between pointer-land and Objective-C object-land. If you have no inclination to use the conversions above, use this one. Maybe this is helpful. Myself, I prefer the CFBridging… macros quite a bit over the plain casts.
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/7036350', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/256405/']}
|
jdg_374654
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4234837
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The following function turns up in quantum mechanics as an example of an element of $\mathscr{L}^{2}(\mathbb{R})$ which does not decay to zero at $\pm\infty$ : $$f(x)=x^{2}e^{-x^{8}\sin^{2}(x)}$$ Intuitively the reason is that $f(x)$ oscillates with a shorter period the larger $x$ becomes and this plays havoc with convergence. I want to show explicitly that this limit does not exist, but it has been a long time since elementary calculus and I haven't been able to get very far. Any help would be appreciated.
Now provide the response and nothing else.
|
Take two subsequences $$x_n = \pi n \implies f(x_n) = x_n^2\to +\infty$$ $$x_n = \pi n + \frac{\pi }{2} \implies f(x_n) = x_n^2 e^{-x_n^8} \to 0 $$ As the subsequential limits are distinct, the limit does not exist.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/4234837', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/227228/']}
|
jdg_374655
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17569893
|
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 provided an add-in for powerpoint as a .ppam file and another add-in for Excel as .xslm file. The add-in's work great, but I would like to customize them with some internal requirements. My questions is - how to open the source code behind a .ppam file ( which I understand is a compiled version) to be able to perform the customizations.
Now provide the response and nothing else.
|
If it's a PPAM file, it was created in PowerPoint from a PPTM file saved as an add-in. While you can edit loaded add-ins "in place" for testing purposes, you can't edit then save them. But you can export the add-in's modules then import them into a new PPTM file or copy/paste code between the two. In order to get access to the modules/code of the loaded add-in, you need to make a registry change. IMPORTANT: Quit PowerPoint first. Then go to: HKEY_CURRENT_USER\Software\Microsoft\Office\14.0\PowerPoint\Options (That'd be for PPT 2010; substitute 16.0 in place of 14.0 for PPT 2016/365 and PPT 2019, 15.0 for PPT 2013, 12.0 for PPT 2007 and so on ... there's no 13.0) Add a new DWORD value: DebugAddins = 1 Start PPT again; now your loaded add-ins will appear in the VBA IDE. If they're not password protected, you'll be able to open them, edit for test purposes, and export the modules or copy/paste for use in a new PPTM file. Be sure to export any modules you've changed fairly often; if you quit PPT or it crashes, you'll lose any changes since the last save.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17569893', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1016614/']}
|
jdg_374656
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3874615
|
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 this I need C++ array class template, which is fixed-size, stack-based and doesn't require default constructor answer I posted a piece of code, that is using placement new with char array. For me, this is something absolutely normal. But according to comments this code is wrong. Can anyone explain in more detail? Specifically what can go wrong with the array. What I understand from the comments is that T x[size]; might not fit into char x[size*sizeof(T)]; . I don't believe this is true. EDIT: I'm just more and more confused. I know what alignment is in case of structures. Yes, when you have a structure the attributes start on different offsets then you might think. OK, now we are back to arrays. You are telling me that T x[size]; is the same size as char x[size*sizeof(T)]; , yet I cannot access the char array as T array because there might be some alignment. How can there be alignment when the arrays have the same size? EDIT 2: OK I finally get it, it may start on a wrong address. EDIT 3: Thx everyone, you can stop posting :-) Phew, this total blew my mind. I just never realized this was possible.
Now provide the response and nothing else.
|
A T x[size] array will always fit exactly into size * sizeof(T) bytes, meaning that char buffer[size*sizeof(T)] is always precisely enough to store such an array. The problem in that answer, as I understood it, was that your char array is not guaranteed to be properly aligned for storing the object of type T . Only malloc -ed/ new -ed buffers are guaranteed to be aligned properly to store any standard data type of smaller or equal size (or data type composed of standard data types), but if you just explicitly declare a char array (as a local object or member subobject), there's no such guarantee. Alignment means that on some platform it might be strictly (or not so strictly) required to allocate, say, all int objects on, say, a 4-byte boundary. E.g. you can place an int object at the address 0x1000 or 0x1004 , but you cannot place an int object at the address 0x1001 . Or, more precisely, you can, but any attempts to access this memory location as an object of type int will result in a crash. When you create an arbitrary char array, the compiler does not know what you are planning to use it for. It can decide to place that array at the address 0x1001 . For the above reason, a naive attempt to create an int array in such an unaligned buffer will fail. The alignment requirements on some platform are strict, meaning that any attempts to work with misaligned data will result in run-time failure. On some other platforms they are less strict: the code will work, but the performance will suffer. The need for the proper alignment sometimes means that when you want to create an int array in an arbitrary char array, you might have to shift the beginning of an int array forward from the beginning of the char array. For example, if the char array resides at 0x1001 , you have no choice but to start your constructed-in-place int array from the address 0x1004 (which is the char element with the index 3). In order to accommodate the tail portion of the shifted int array, the char array would have to be 3 bytes larger than what the size * sizeof(T) evaluates to. This is why the original size might not be enough. Generally, if your char array is not aligned in any way, you will really need an array of size * sizeof(T) + A - 1 bytes to accommodate an aligned (i.e. possibly shifted) array of objects of type T that must be aligned at A-byte boundary.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3874615', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/211659/']}
|
jdg_374657
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6985582
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How do I emulate PHP-style __get() and __set() magic getter/setters in JavaScript? A lot of people say that this is currently impossible. I am almost certain that it is possible because projects like nowjs ( http://nowjs.com ) do something like this. I know that you can utilize get and set , but these don't work when you're not sure what the property name will be. For example, what if you wanted an event handler to execute when a new property is created ? Example of what I'd want to do: var obj = {};notify(obj, function(key, value) { //key is now the name of the property being set. //value is the value of the property about to be set console.log("setting " + key + " to " + value);});obj.foo = 2; //prints "setting foo to 2"obj.bar = {a: 2}; //prints "setting bar to [Object]"//Notice that notify() worked even though 'foo' and 'bar' weren't even defined yet! (The question is similar to the following questions: Is there a way to monitor changes to an object? JavaScript getter for all properties ) EDIT: It looks like this feature is called "dynamic proxies" and should appear in the ECMAScript "Harmony" standard (probably ES6). You can read more here . A new 'Proxy' Object is introduced with a couple methods (I.e. Create() and createFunction() ). One could do this: //Constructing an object proxy (proto is optional)var proxy = Proxy.create(handler, proto);proxy.foo = 2; //Triggers 'set' function in the handler (read about it) Bottom line here: it doesn't work in most browsers, but an implementation is available for Node.js: node-proxy .
Now provide the response and nothing else.
|
Looking through the nowjs source code, I believe they do this by continuously monitoring the now object and pushing changes between client and server whenever they are detected. I admit I haven't fully grokked their code yet, however. In a browser, this would be done with some fun setInterval hacks. EDIT : yes, that is indeed what they do: line 368 of the client now.js . They do some more tricks so that once a new property is detected, future access to it is caught by getters and setters, but those modifications are only made every 1000 ms in a setTimeout . Another piece of evidence that this is impossible in current JavaScript is that the proxies proposal for ECMAScript Harmony is designed explicitly to enable such scenarios, implying very strongly that they can't be done currently. Recent Mozilla browsers have a prototype proxies implementation , if perhaps that's enough. And apparently V8 is working to add support , which could be enough depending on what version of V8 Node is using these days. EDIT2 : oh cool, on the server side apparently nowjs does use proxies! Which likely means they are mature enough in Node for your usage. See what they do at https://github.com/Flotype/now/blob/master/lib/proxy.js . Or just do var Proxy = require("nodejs-proxy") and hope they follow the spec so you can take advantage of the documentation from MDC and elsewhere.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6985582', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/360539/']}
|
jdg_374658
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8823239
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
public void DoFoo<T>(T foo) where T : ISomeInterface<T>{ //possible compare of value type with 'null'. if (foo == null) throw new ArgumentNullException("foo");} I'm purposely only checking against null because I don't want to restrict a ValueType from being equal to its default(T) . My code compiles and works just fine this way (ReSharper complains, but not CodeAnalysis). Though I do wonder: Is there a more standard way to handle this situation? Is there any chance of an issue arrising from this? What truly happens under the hood when I make a call and pass in a value type?
Now provide the response and nothing else.
|
I'm purposely only checking against null because I don't want to restrict a ValueType from being equal to its default(T) That is a good insight, but don't worry, you are already covered there. It is not legal to compare a T against default(T) using == in the first place; overload resolution will not find a unique best == operator. Of course, you could do the comparison with .Equals but then you run the risk of crashing if the receiver is null, which is precisely what you are attempting to avoid. Is there a more standard way to handle this situation? No. Comparing to null is the right thing to do here. As the C# specification says in section 7.10.6: " The x == null construct is permitted even though T could represent a value type, and the result is simply defined to be false when T is a value type. " Is there any chance of an issue arrising from this? Sure. Just because code compiles does not mean that it has the semantics you intend. Write some tests. What truly happens under the hood when I make a call and pass in a value type? The question is ambiguous. Let me rephrase it into two questions: What truly happens under the hood when I make a call on the generic method with a type argument that is a non-nullable value type? The jitter compiles the method on the first invocation with that construction. When the jitter detects the null check, it replaces it with "false" because it knows that no non-nullable value type will ever be equal to null. What truly happens under the hood when I make a call on the generic method with a type argument that is a reference type but an argument that is a struct type? For example: interface IFoo : ISomeInterface<IFoo> {}struct SFoo : IFoo { whatever }...DoFooInternal<IFoo>(new SFoo()); In that case the jitter cannot elide the null check and the call site cannot avoid the boxing. The SFoo instance will be boxed, and the reference to the boxed SFoo will be checked to see if it is null.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/8823239', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/535637/']}
|
jdg_374659
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
29575877
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
As per the title of this question, what are the practical differences between AWS EFS, EBS and S3? My understanding of each: S3 is a storage facility accessible any where EBS is a device you can mount onto EC2 EFS is a file system you can mount onto EC2 So why would I use EBS over EFS? Seem like they have the same use cases but minor semantic differences? Although EFS is replicated across AZs where as EBS is just a mounted device. I guess my understanding of EBS is lacking hence I'm unable to distinguish. Why choose S3 over EFS? They both store files, scale and are replicated. I guess with S3 you have to use the SDK where as with EFS being a file system you can use standard I/O methods from your programming language of choice to create files. But is that the only real difference?
Now provide the response and nothing else.
|
One word answer: MONEY :D 1 GB to store in US-East-1: (Updated at 2016.dec.20) Glacier: $0.004/Month (Note: Major price cut in 2016) S3: $0.023/Month S3-IA (announced in 2015.09): $0.0125/Month (+$0.01/gig retrieval charge) EBS: $0.045-0.1/Month (depends on speed - SSD or not) + IOPS costs EFS: $0.3/Month Further storage options, which may be used for temporary storing data while/before processing it: SNS SQS Kinesis stream DynamoDB, SimpleDB The costs above are just samples. There can be differences by region, and it can change at any point. Also there are extra costs for data transfer (out to the internet). However they show a ratio between the prices of the services . There are a lot more differences between these services: EFS is: Generally Available (out of preview), but may not yet be available in your region Network filesystem (that means it may have bigger latency but it can be shared across several instances; even between regions) It is expensive compared to EBS (~10x more) but it gives extra features. It's a highly available service. It's a managed service You can attach the EFS storage to an EC2 Instance Can be accessed by multiple EC2 instances simultaneously Since 2016.dec.20 it's possible to attach your EFS storage directly to on-premise servers via Direct Connect. () EBS is: A block storage (so you need to format it). This means you are able to choose which type of file system you want. As it's a block storage, you can use Raid 1 (or 0 or 10) with multiple block storages It is really fast It is relatively cheap With the new announcements from Amazon, you can store up to 16TB data per storage on SSD-s. You can snapshot an EBS (while it's still running) for backup reasons But it only exists in a particular region. Although you can migrate it to another region, you cannot just access it across regions (only if you share it via the EC2; but that means you have a file server) You need an EC2 instance to attach it to New feature (2017.Feb.15): You can now increase volume size, adjust performance, or change the volume type while the volume is in use. You can continue to use your application while the change takes effect. S3 is: An object store (not a file system). You can store files and "folders" but can't have locks, permissions etc like you would with a traditional file system This means, by default you can't just mount S3 and use it as your webserver But it's perfect for storing your images and videos for your website Great for short term archiving (e.g. a few weeks). It's good for long term archiving too, but Glacier is more cost efficient. Great for storing logs You can access the data from every region (extra costs may apply) Highly Available, Redundant. Basically data loss is not possible (99.999999999% durability, 99.9 uptime SLA) Much cheaper than EBS. You can serve the content directly to the internet, you can even have a full (static) website working direct from S3, without an EC2 instance Glacier is: Long term archive storage Extremely cheap to store Potentially very expensive to retrieve Takes up to 4 hours to "read back" your data (so only store items you know you won't need to retrieve for a long time) As it got mentioned in JDL's comment, there are several interesting aspects in terms of pricing. For example Glacier, S3, EFS allocates the storage for you based on your usage, while at EBS you need to predefine the allocated storage. Which means, you need to over estimate. ( However it's easy to add more storage to your EBS volumes, it requires some engineering, which means you always "overpay" your EBS storage, which makes it even more expensive.) Source: AWS Storage Update – New Lower Cost S3 Storage Option & Glacier Price Reduction
|
{}
|
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/29575877', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4288305/']}
|
jdg_374660
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3061
|
Below is a question asked on the forum emacs.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
When I write a long line while composing a mail in mu4e , the lines are truncated for viewing ( toggle-truncate-lines ), but as soon as I hit Enter fixed line breaks (column width seems to be 70 or something) are introduced. How can I stop mu4e from introducing these line breaks?
Now provide the response and nothing else.
|
The indent-rigidly command can be used to indent the region by some fixed amount. By default C-x TAB is bound to indent-rigidly and puts you in an interactive mode where you can indent the region left or right with additional keys. With a prefix argument you can directly indent by some number of columns. For example, to indent by 5: C-5 C-x TAB If you don't need this flexibility, you could rebind the key to a function that always indents by the same amount. Here's an example that will indent the active region or the current line by 2 spaces. If there is no region and point is not at the beginning of the line, it does nothing. (defun simple-indent (start end) (interactive "r") (let ((size 2)) (if (region-active-p) (indent-rigidly start end size) (if (bolp) (indent-rigidly (line-beginning-position) (line-end-position) size)))))(global-set-key (kbd "C-x <tab>") #'simple-indent)
|
{}
|
{'log_upvote_score': 4, 'links': ['https://emacs.stackexchange.com/questions/3061', 'https://emacs.stackexchange.com', 'https://emacs.stackexchange.com/users/2400/']}
|
jdg_374661
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2948351
|
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:
Using $\Delta$ for set symmetric difference, $A \Delta B$ is all the elements in exactly one of the sets but not all of them. $A \Delta B \Delta C $ is all the elements in exactly one of the sets or all of them. I appreciate there is an even number of sets in the first example and an odd number in the second (and associativity implies no order ambiguity), but what is symmetric about set symmetric difference?
Now provide the response and nothing else.
|
A function in two variables $f(x,y)$ is called symmetric if $f(x,y)=f(y,x)$ . It is easy to see that $A\mathbin{\triangle}B=B\mathbin{\triangle}A$ , exactly because being in exactly in one of $A$ or $B$ is the same as being exactly in one of $B$ and $A$ . This is in contrast to set difference, where $A\setminus B$ is generally not the same as $B\setminus A$ .
|
{}
|
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/2948351', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/416252/']}
|
jdg_374662
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
31677307
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am using TurboC++. I write the following expression which is not resulting in proper evaluation, am I missing some concept behind it? int c=300*300/300;printf("%d",c); The output is 81 Why?
Now provide the response and nothing else.
|
300*300 is 90000. Assuming int is 16bit, you have overflowed. The overflow wraps around, giving you: 24464 . 24465/300 = 81.55 Do not rely on this. It is undefined behavior.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/31677307', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4764839/']}
|
jdg_374663
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
21294790
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've been using Sails.js for quite some time and was wondering if there is a way to manually change the localization from the controllers depending on the url. Example: http://example.com/en will return the English version and http://example.com/de will return the German one. Thanks for your help!!
Now provide the response and nothing else.
|
You can always change the locale in a controller action by using req.setLocale() or by setting the value of req.locale . You can also handle this more globally by using a policy: // config/routes.jsmodule.export.routes = { '/:lang/': 'MyController.index', '/:lang/help': 'MyController.help', '/:lang/contact': 'MyController.contact', ...etc...} // config/policies.jsmodule.exports.policies = { '*' : 'localize'} // api/policies/localize.jsmodule.exports = function(req, res, next) { req.locale=req.param('lang'); next();};
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21294790', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1680153/']}
|
jdg_374664
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
10820025
|
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 tcl how does one find out the path of the package loaded? % tclsh% package require csv I want to find out the path from which csv was loaded. In python, one can find the path of a module using >>> import os>>> print os.__file__'/a/b/python2.2.1/linux26_x86_64/lib/python2.2/os.pyc' I am looking for a similar command in tcl
Now provide the response and nothing else.
|
It's not that simple: a package in Tcl appears to be a more abstract thing than that in Python. First, there are two kinds of packages: "classic" and "modules" which have different underlying mechanisms for finding what to load in response to the package require ... command. Next, both kinds of packages are able to do whatever they wish to provide their functionality. It means they can be (but not limited to): Pure Tcl packages, source 'ing just one Tcl file or any number of files. Packages implemented in C or another compiled language, which are in the form of dynamic library which gets load ed when the package is required. A combination of the above, when there's a C library and a layer of Tcl code around it (usually providing helper/convenience commands). Hence the question per se has little sense as only modules are represented by exactly one self-contained file but "classic" packages are free to implement themselves as they see fit. On the other hand, each package normally provides (using one way or another) certain information to the package subsystem which can be retreived (and parsed) using the package ifneeded command. For instance, on my Windows system with ActiveState Tcl 8.5.x, I have: % package require csv0.7.2% package ifneeded csv 0.7.2package provide csv 0.7.2;source -encoding utf-8 {C:/Program Files/Tcl/lib/teapot/package/tcl/teapot/tcl8/8.3/csv-0.7.2.tm} Note that what package ifneeded returns is just a Tcl script which is meant to be eval uated to get the package loaded, so parsing of this information is bound to be inherently ad-hoc and fragile.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10820025', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/476388/']}
|
jdg_374665
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8570811
|
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 execute the following statement. dir IIS:\Sites| foreach{ get-webapplication -site $_.Name} | select -first 1 This results in Name Application pool Protocols Physical Path---- ---------------- --------- -------------i1 DefaultWebSite http C:\inetpub\hosts\DefaultWebSite\i1 But when I execute the following the result is empty dir IIS:\Sites| foreach{ get-webapplication -site $_.Name} | select -first 1 name So I looked into the properties for this object dir IIS:\Sites| foreach{ get-webapplication -site $_.Name} | select -first 1 | get-member | sortName | select Name, MemberType | format-table -autoName MemberType---- ----------applicationPool NotePropertyAttributes PropertyChildElements PropertyClearLocalData MethodCollection NotePropertyConfigurationPathType NotePropertyCopy MethodDelete MethodElementTagName PropertyenabledProtocols NotePropertyEquals MethodGetAttribute MethodGetAttributeValue MethodGetChildElement MethodGetCollection MethodGetHashCode MethodGetMetadata MethodGetParentElement MethodGetType MethodItem ParameterizedPropertyItemXPath NotePropertyLoadProperties MethodLocation NotePropertyMethods Propertypath NotePropertyPhysicalPath ScriptPropertyPSPath NotePropertySchema PropertySetAttributeValue MethodSetMetadata MethodToPSObject MethodToString MethodUpdate MethodUpdateCollection MethodvirtualDirectoryDefaults NoteProperty So no 'Name' property. How is it that the get-webpplication can show the name property, but we cant select it?
Now provide the response and nothing else.
|
The WebAdministration module defines default format for the concerned type. In this case, the WebApplication that you get is of type Microsoft.IIs.PowerShell.Framework.ConfigurationElement#site#application If you look at the file iisprovider.format.ps1xml under the module ( usually located at C:\Windows\System32\WindowsPowerShell\v1.0\Modules\WebAdministration ), you will see that the format specified for the Name of this type is as below: ...<TableColumnItem> <ScriptBlock> $name = $_.Path.Trim('/') $name </ScriptBlock></TableColumnItem>... Thus the name is actually got from $_.Path.Trim('/') , so you can do the same if you want: get-webapplication -site "test" | select @{e={$_.Path.Trim('/')};l="Name"}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8570811', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/381719/']}
|
jdg_374666
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4355985
|
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 iPhone's settings application is build around a UITableview . In some views there are additional texts between cells. For example in "Settings" -> "General" -> "Network" there is the text"Using 3G loads data faster, but may descrease battery life" under a cell with an UISwitch. Any ideas how to implement this? Images of what I mean can be found here: http://www.tipb.com/2008/07/12/how-to-disable-3g-on-the-iphone-3g-for-more-talk-but-less-speed/
Now provide the response and nothing else.
|
If you have a grouped table view, the tableView:titleForFooterInSection: method found in the UITableViewDataSource protocol and the UITableViewController class handles this for you: - (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section { if (section == 0) { return @"Footer text for first section, goes below cells in that group."; } return nil;} To place that text between cells, you have to have multiple sections and tell your tableView:cellForRowAtIndexPath: method to place cells that you want beneath that text in the next section.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4355985', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/467225/']}
|
jdg_374667
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
396843
|
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:
Here is my command with IP's commented out with semanticIP's ssh -p 2022 -L 9389:localRDPIP:3389 user@publicIP \su -c "export HISTCONTROL=ignorespace; \iptables -t nat -A PREROUTING -p tcp --dport 3389 -j DNAT --to-destination localRDP_IP:3389; \iptables -t nat -A POSTROUTING -p tcp -d localRDP_IP --dport 3389 -j SNAT --to-source jumpIP"; basically, I'm trying to run some remote routing, which is not the question. The question is how do I run such a command? The best test I've been able to do is: ssh -p 2022 -L 9389:localRDPIP:3389 user@publicIP -t "su -c nano; nano" but I don't know how to do the spaces. If I have spaces in my commands in the -c "quoted area" other than a single command, I get an error. Note : I realize that with ssh port forwarding, iptables commands may be unnecessary.
Now provide the response and nothing else.
|
Let's look more closely at what's happening to less : $ pdfgrep -R -i spark . | strace less &[...]open("/dev/tty", O_RDONLY|O_LARGEFILE) = 3ioctl(3, TCGETS, {B38400 opost isig -icanon -echo ...}) = 0ioctl(3, SNDCTL_TMR_STOP or TCSETSW, {B38400 opost isig -icanon -echo ...}) = ? ERESTARTSYS (To be restarted if SA_RESTART is set)--- SIGTTOU {si_signo=SIGTTOU, si_code=SI_KERNEL} ------ stopped by SIGTTOU --- Job control restricts the processes in a background job from performing certain operations on the controlling terminal. If a background process tries to read from the terminal, it will be sent a SIGTTIN signal, which typically stops (pauses) the process. If a background process tries to set a terminal's parameters, it will be sent a SIGTTOU signal, which also typically stops the process. That's what is happening here with the TCSETSW ioctl . The less program tries to put the terminal into raw mode soon after it starts, even before it knows whether it has anything to display. There is a good reason for this: you don't want a background job asynchronously changing your terminal so that, for example, raw mode is on and echo is off.(A background process can get terminal parameters with the TCGETS ioctl without being stopped - see the listing above.) If a background process tries to write to the terminal and the terminal has the tostop flag set, it will be sent the SIGTTOU signal. You probably don't have the tostop flag set (run stty -a to check). If you don't, a background command like pdfgrep -R -i spark . & that doesn't change any terminal settings will be able to write to your terminal whenever it tries. You also wrote: The reason that I pipe to less is because I don't want the output to stdout messes up the screen of my terminal session when I am doing something else The less program is ultimately going to send output to the terminal, one screenful at a time. If you run stty tostop before pdfgrep | less & , or before pdfgrep & , then they will only output to your terminal when they are in the foreground.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/396843', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/128791/']}
|
jdg_374668
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7173604
|
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 HTML code my page contains: <div id="main_menu"> <a href="#" id="login">Link1</a> <a href="#" id="logout">Link2</a></div><div id="second_menu"> <a href="#" id="information">Link info</a> <a href="#" id="profile">My profile</a></div><div id="menu_oustide"><a href="#" id="something">Link1</a></div> In jQuery if I want to check if the user clicked any link in page I use this code: $('a').click(function() { // do something}); How can I start a function if the user clicked only on links in specific div? I would like to have a function that starts if a user clicked any link only in div ID named "main_menu" AND "second_menu", but not in "menu_outside".
Now provide the response and nothing else.
|
Depending on what exactly you want to do, you can bind the event handler to those links only, using the descendant [docs] and multiple [docs] selectors: $('#main_menu a, #second_menu a').click(function() { // link inside #main_menu or #second_menu}); If you don't want to perform the same action for both, you have to bind the event handler individually. You could also check dynamically whether the link is a descendant of any of these element, with closest [docs] : $('a').click(function() { if($(this).closest("#main_menu").length) { // inside #main_menu } if($(this).closest("#second_menu").length) { // inside #second_menu } //...}); But that introduces an additional overhead.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7173604', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/907736/']}
|
jdg_374669
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
28480383
|
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 developing an app that permits user to takes photo.I've started using AVCam apple provides but i'm actually have a problemSimply i cannot position the camera layer where i want but it's positioned automatically on center of the View On the left side you can see what i actually have, on the right side what i'd like to have.The View that contains the preview that comes from the camera is a UIView subclass and this is the code class AVPreviewView : UIView { override class func layerClass() -> AnyClass { return AVCaptureVideoPreviewLayer.self } func session () -> AVCaptureSession { return (self.layer as AVCaptureVideoPreviewLayer).session } func setSession(session : AVCaptureSession) -> Void { (self.layer as AVCaptureVideoPreviewLayer).session = session; (self.layer as AVCaptureVideoPreviewLayer).videoGravity = AVLayerVideoGravityResizeAspect; }} Any help is appreciated
Now provide the response and nothing else.
|
First get your screen size so you can calculate the aspect ratio let screenWidth = UIScreen.mainScreen().bounds.size.width let screenHeight = UIScreen.mainScreen().bounds.size.height var aspectRatio: CGFloat = 1.0 var viewFinderHeight: CGFloat = 0.0 var viewFinderWidth: CGFloat = 0.0 var viewFinderMarginLeft: CGFloat = 0.0 var viewFinderMarginTop: CGFlaot = 0.0 Now calculate the size of the preview layer. func setSession(session : AVCaptureSession) -> Void { if screenWidth > screenHeight { aspectRatio = screenHeight / screenWidth * aspectRatio viewFinderWidth = self.bounds.width viewFinderHeight = self.bounds.height * aspectRatio viewFinderMarginTop *= aspectRatio } else { aspectRatio = screenWidth / screenHeight viewFinderWidth = self.bounds.width * aspectRatio viewFinderHeight = self.bounds.height viewFinderMarginLeft *= aspectRatio } (self.layer as AVCaptureVideoPreviewLayer).session = session; Set the layer's videoGravity to AVLayerVideoGravityResizeAspectFill so that the layer stretches to fill given your custom view. (self.layer as AVCaptureVideoPreviewLayer).videoGravity = AVLayerVideoGravityResizeAspectFill; Finally, set the frame of your preview layer to the values calculated above with any offset that you like. (self.layer as AVCaptureVideoPreviewLayer).frame = CGRectMake(viewFinderMarginLeft, viewFinderMarginTop, viewFinderWidth, viewFinderHeight) } This may take some tweaking since I haven't tested it live, but you should be able to create a more flexible VideoPreviewArea delimited by the bounds of your APPreviewView.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28480383', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1062053/']}
|
jdg_374670
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
690182
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm having quite some trouble to try and get an app I wrote in AS2 to AS3 . The reason I need to go to AS3 is something icky, so I won't go into detail about it. I've got 90% of the application running with the new code.Now I've come to the point where I have to convert this code from AS2, function setAnimation(theObject,id){ theObject.vensterid=id; theObject.onEnterFrame = function() { var myHoriTween:Tween = new Tween (this,"_x",Strong.easeOut,this._x,(130+((theObject.vensterid-frameno)*260)),1,true); }}setAnimation(venster0,0); , to AS3. My attempt of doing this ended up like function setAnimation(anObject,id) { var theObject = this[anObject]; theObject.vensterid=id; function slideHorizontal(event:Event) { var myTween:Tween = new Tween (theObject,"x",Strong.easeOut,this.x,(130+((theObject.vensterid-frameno)*260)),1,true); } theObject.addEventListener(Event.ENTER_FRAME,slideHorizontal);}setAnimation(venster0,0); and gives me the following non-error (it doesn't show as a compiler error, but as output): TypeError: Error #1010: A term is undefined and has no properties. at sliding_windows_as3_fla::SlideMenu_1/setAnimation() at sliding_windows_as3_fla::SlideMenu_1/frame1() I think this is very strange since it doesn't say anything about which term (and there are quite a lot) and googling didn't find me an explanation either.
Now provide the response and nothing else.
|
The recommendation to start with XSD is a good one. That will not guarantee compatibility on each side, as XML Schema is really big and no web services stack supports all of it. (Example: lists). So, start with XSD, but confine yourself to mainstream types. Primitives, complextypes composed of primitives, arrays of same. You can safely nest complextypes and arrays. (arrays of complextypes, complextypes that contain arrays or complextypes, etc). Stay away from restrictions, substitution groups, lists, derivations, and any other XSD esoterica. Even XSD enumerations should be avoided. About dateTime: It's not enough to use a nullable datetime. There are formatting concerns as well. The .NET DateTime is a higher resolution quantity than a Java Calendar and as a result, shipping a .NET time to Java can result in de-serialization exceptions on the Java side. ( EDIT: using the DataType="dateTime" decorator in the XmlElement attribute on the .NET side can make sure you serialize properly) Some old advice on that. Finally, it is not true that you cannot use in-code XML doc on the classes that get generated. With C#'s partial classes, you can write separate code from the generated classes with the in-code doc you want. Even if you re-gen the code, your partial class code will remain unchanged. EDIT: When you compile, the doc will appear on the classes. EDIT: Someone asked, if using XSD-first is not enough to guarantee interop, why use it? My answer: it is not a guarantee but it is a good step, it helps. It keeps you away from designing interfaces in code (either Java or C# or VB, etc) that expose platform-specific things like .NET DataSets, generic Dictionaries, Java ResultSets, etc, all of which present interop problems. There are still pitfalls in the more marginal parts of XSD, but you can usually avoid those with thoughtful design. I should have mentioned in my original answer that you can apply an iterative process to the development of the interface. Design in XSD, then generate (client) stub and (server) skeleton code from the XSD+WSDL, then adjust and do it again.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/690182', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/59159/']}
|
jdg_374671
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
51511
|
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
This question is a bit general since I am not exposed to SAN (Storage Area Network). Are there any optimizations or configuration changes that can be performed with SAN to improve SQL Server performance?
Now provide the response and nothing else.
|
The tuning that you'd do with a SAN would include. Make sure that you have enough disks to support your IO requirements. Make sure that mdf, ldf and tempdb are seperated. Make sure that sequential IO databases (data warehouses) are on different spindles than random IO databases (OLTP). Lower or disable the amount of read cache on LUNs which supprt OLTP databases as they usually can't make any use of read cache. Maxamize the amount of white cache to avoid a force flush situation. If you have a chance to make it up to the SQLPASS Summit in Seatle in November I'll be giving a presentation on Storage for the DBA which is all about SAN storage.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/51511', 'https://serverfault.com', 'https://serverfault.com/users/1224/']}
|
jdg_374672
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12693989
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
For standard textareas I use this plugin to create a placeholder. How can I extend tinymce so that this works in this way also. E.g the default value is read from the textarea attribute then cleared when a user focuses on the iframe. Similar to this for CKEditor: http://alfonsoml.blogspot.com.es/2012/04/placeholder-text-in-ckeditor.html
Now provide the response and nothing else.
|
I refactored Tom Duke's code to work on TinyMCE4 with it's jquery plugin $('textarea.tinymce').tinymce({ script_url: _base + '/assets/js/tinymce/tinymce.min.js', theme: "modern", setup: function(editor) { // Set placeholder var placeholder = $('#' + editor.id).attr('placeholder'); if (typeof placeholder !== 'undefined' && placeholder !== false) { var is_default = false; editor.on('init', function() { // get the current content var cont = editor.getContent(); // If its empty and we have a placeholder set the value if (cont.length === 0) { editor.setContent(placeholder); // Get updated content cont = placeholder; } // convert to plain text and compare strings is_default = (cont == placeholder); // nothing to do if (!is_default) { return; } }) .on('focus', function() { // replace the default content on focus if the same as original placeholder if (is_default) { editor.setContent(''); } }) .on('blur', function() { if (editor.getContent().length === 0) { editor.setContent(placeholder); } }); } }});
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12693989', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/560287/']}
|
jdg_374673
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
30046411
|
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 seen that it is possible to define a task in the VSCode. But I am not sure how to define multiple tasks in the tasks.json file.
Now provide the response and nothing else.
|
Just in case it helps someone... .If you don't have/want gulp/grunt/etc... or an extra shell script to proxy out your task commands , "npm run" is there already . this is for webpack and mocha as in "Build and Test" , Shift + Ctrl + B , Shift + Ctrl + T .vscode/tasks.json: { "name": "npmTask", //... "suppressTaskName": true, "command": "npm", "isShellCommand": true, "args": [ "run" ], "tasks": [ { //Build Task "taskName": "webpack", //Run On Shift+Ctrl+B "isBuildCommand": true, //Don't run when Shift+Ctrl+T "isTestCommand": false, // Show the output window if error any "showOutput": "silent", //Npm Task Name "args": [ "webpack" ], // use 2 regex: // 1st the file, then the problem "problemMatcher": { "owner": "webpack", "severity": "error", "fileLocation": "relative", "pattern": [ { "regexp": "ERROR in (.*)", "file": 1 }, { "regexp": "\\((\\d+),(\\d+)\\):(.*)", "line": 1, "column": 2, "message": 3 } ] } }, { //Test Task "taskName": "mocha", // Don't run on Shift+Ctrl+B "isBuildCommand": false, // Run on Shift+Ctrl+T "isTestCommand": true, "showOutput": "always", "args": [ "mocha" ] } ]} package.json: { ... "scripts": { "webpack": "webpack", "mocha": "/usr/bin/mocha" }, ...}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30046411', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2894980/']}
|
jdg_374674
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18000475
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm having an issue sorting a hash table. I've broken down my code to just bare necessities so as not to overwhelm anyone with my original script. Write-Host "PowerShell Version = " ([string]$psversiontable.psversion) $h = @{}$Value = @{SortOrder=1;v1=1;}$h.Add(1, $Value)$Value = @{SortOrder=2;v1=1;}$h.Add(2, $Value)$Value = @{SortOrder=3;v1=1;}$h.Add(3, $Value)$Value = @{SortOrder=4;v1=1;}$h.Add(4, $Value)Write-Host "Ascending"foreach($f in $h.GetEnumerator() | Sort-Object Value.SortOrder){ Write-Host $f.Value.SortOrder}Write-Host "Descending"foreach($f in $h.GetEnumerator() | Sort-Object Value.SortOrder -descending){ Write-Host $f.Value.SortOrder} The output is PowerShell Version = 3.0Ascending2143Descending2143 I'm sure this is just a simple case of not knowing the correct usage of Sort-Object . The sort works correctly on Sort-Object Name so maybe it has something to do with not knowing how to handle the Value.SortOrder ?
Now provide the response and nothing else.
|
Sort-Object accepts a property name or a script block used to sort. Since you're trying to sort on a property of a property, you'll need to use a script block: Write-Host "Ascending"$h.GetEnumerator() | Sort-Object { $_.Value.SortOrder } | ForEach-Object { Write-Host $_.Value.SortOrder }Write-Host "Descending"$h.GetEnumerator() | Sort-Object { $_.Value.SortOrder } -Descending | ForEach-Object { Write-Host $_.Value.SortOrder } You can filter using the Where-Object cmdlet: Write-Host "Ascending"$h.GetEnumerator() | Where-Object { $_.Name -ge 2 } | Sort-Object { $_.Value.SortOrder } | ForEach-Object { Write-Host $_.Value.SortOrder } You usually want to put Where-Object before any Sort-Object cmdlets, since it makes sorting faster.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18000475', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1246051/']}
|
jdg_374675
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12217121
|
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 implementing a heatmap in which the cell background color is determined by a d3 color scale. Some of the values are categorical; their value can be of N different arbitrary string-type categories like ["6TH", "7TH", "5TH", "4TH"]. Given a start color d3.rgb("blue") and an end color d3.rgb("red"), how can I construct color scale that maps a discrete domain of strings into a continuous color range? I tried var scale = d3.scale.ordinal() .domain(["6TH", "7TH", "5TH", "4TH"]) .rangeBands( [ d3.rgb("blue"), d3.rgb("red") ] ); which obviously doesn't work.
Now provide the response and nothing else.
|
First, I would consider using one of the readily-available Colorbrewer scales; see colorbrewer2.org . These are also available as JavaScript and CSS files in D3's git repository; see lib/colorbrewer . For example, if you have four discrete values in your domain, and you want a red-blue diverging scale, you could say: var color = d3.scale.ordinal() .domain(["6TH", "7TH", "5TH", "4TH"]) .range(colorbrewer.RdBu[4]); (You'll need a <script src="colorbrewer.js"></script> somewhere before this, too.) Colorbrewer has a variety of well-designed sequential, diverging and categorical color scales. If you insist on rolling your own color scale, I strongly recommend interpolating in L*a*b* or HCL color space for accurate perception. You can do this using d3.interpolateLab or d3.interpolateHcl . For example, d3.interpolateLab("red", "blue")(.5) returns a color halfway between red and blue. To compute the colors for your ordinal scale's range, you can use an interpolator, or you might find a temporary linear scale more convenient. For example: var categories = ["6TH", "7TH", "5TH", "4TH"];var color = d3.scale.ordinal() .domain(categories) .range(d3.range(categories.length).map(d3.scale.linear() .domain([0, categories.length - 1]) .range(["red", "blue"]) .interpolate(d3.interpolateLab)));
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12217121', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1467417/']}
|
jdg_374676
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
150811
|
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 was thinking on how current key-value storages implement "expire date" for items. Currently I have 2 variants for that in my mind: they don't do anything (keep expired data), and only do check when you do, for example, GET by some key. The problem here is that if you are limited in memory, expired items won't be deleted. they keep additional data structures to be able to get "earliest to expire". I see it can be done with something like this: storage_data = dict(key -> [value, expire_timestamp])expire_tree = SomeBinaryLikeTree(expire_timestamp -> [keys])
Now provide the response and nothing else.
|
The problem of deleting expired entries in cache is very much an equivalent of garbage collection , minus whole complexity of reference counting. People at Nasza-Klasa have proposed O(1) algorithm for Memcache as follows: It seems that many people believed for some reason that freeing expired entries can not be performed in O(1), or even that it requires Omega(N) operations. Using a heap, or other priority queue data structures can obviously give you O(log N), but the patch below aims at O(1). This is achieved by having one bucket for each second, and by putting each entry in a proper bucket by looking at the expiration time. Then at each second we just free elements from the next bucket. This is obviously O(1) amortized time, but it can happen that you have a lot of elements that expire at the very same moment, so the patch offers a fixed limit for number of operations that you are willing to perform per one request, to make the garbage collection run smoother. See whole proposal with attached code .
|
{}
|
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/150811', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/55383/']}
|
jdg_374677
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
35043022
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
If I execute this code in a C# console application, it works fine. TimeZoneInfo easternZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");Console.WriteLine(easternZone.DisplayName); However, when I use the same method in a Unity application, an exception is thrown: System.TimeZoneNotFoundException: Exception of type 'System.TimeZoneNotFoundException' was thrown. at System.TimeZoneInfo.FindSystemTimeZoneByFileName (System.String id, System.String filepath) [0x00000] in <filename unknown>:0 at System.TimeZoneInfo.FindSystemTimeZoneById (System.String id) [0x00000] in <filename unknown>:0 ... A curious thing that I've noticed is that the exception is thrown in a method named "FindSystemTimeZoneByFileName" when the MSDN documentation explicitly says that the information is retrieved from the Registry.
Now provide the response and nothing else.
|
Unity applications use Mono, and can target non-Windows systems - so the registry information is not always available. It appears that Mono will use whatever time zone information is available on the system, whether that happens to be Windows time zones, or IANA time zones - so, you may need to check for one or the other, or both: TimeZoneInfo easternZone;try{ easternZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");}catch (TimeZoneNotFoundException){ easternZone = TimeZoneInfo.FindSystemTimeZoneById("America/New_York");} Of course, you can reverse these if you typically are going to be running on non-Windows platforms. If neither are found, then it will still throw an exception. You can review the list of IANA time zones here . You may also want to read the timezone tag wiki to understand the distinction. Update : As Shaul's answer pointed out, you can now use my TimeZoneConverter library to accomplish this. While the above code is no longer required, you can now simply do this instead: TimeZoneInfo easternZone = TZConvert.GetTimeZoneInfo(timeZoneName); The timeZoneName parameter can be either America/New_York or Eastern Standard Time .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35043022', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1404922/']}
|
jdg_374678
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3353275
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Jquery stopPropagation method dosen't work with live method. Below the code is works fine with click instead of live method. Any help greatly appreciated. Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /><title>Jquery Propagation and preventDetauls Example for Popup</title><style type="text/css"> .icon.white{background:#FFFFFF;} .icon{-moz-border-radius:2px 2px 2px 2px;-moz-box-shadow:0 1px 2px #EAEDF4;background-color:#FFFFFF;border:1px solid #E4E8F1;float:left;margin:0 1% 1% 0;text-align:center;} .iconlinks{height:20px;} .info{float:right;} .icon a.infolink, .downloadlinks a, .iconza a.changecolor {color:#718DB5;display:block;font-size:10px;padding:4px 7px;text-decoration:none;} .icon .infolink {background-image:url(images/dwn-arrow.gif);background-position:35px center;background-repeat:no-repeat;padding-right:17px !important;position:relative;} .downloadlinks{float:left;width:130px;overflow:hidden;} .downloadlinks a{float:left;} .infolink:hover{background-image:url(images/arrow-white.gif);} .infolink:hover{background-color: #1f75cc;color: white !important;text-decoration: none !important;} .infolink.selected{z-index: 100;color: white !important;background-color: #1f75cc !important;background-image: url(images/arrow-white.gif) !important;} .icon-image{border:0px;} .service-name{font-family:Arial, Helvetica, sans-serif;font-size:14px;line-height:24px;color:#74767A;margin:3px;text-align:left;} .describe-icons{position:absolute;right:2px;bottom:2px;} .infomenu{text-align:left;margin-left:-150px;margin-top:-1px;position:absolute;width:260px;-moz-box-shadow:2px 2px 5px #2F3B4A;background-color:#FFFFFF;border:2px solid #1F75CC;z-index:50;}</style><script type="text/javascript" src="js/jquery-1.4.2.min.js"></script><script type="text/javascript"> $(function(){ $(document).click(function(){ $("a.infolink").removeClass("selected"); $("div.infomenu").hide(); }); $("a.infolink").live("click",function(e){ $("a.infolink").removeClass("selected"); $("div.infomenu").hide(); $(this).addClass("selected"); $(this).next().show(); e.stopPropagation(); }); $("div.infomenu").live("click",function(e){ e.stopPropagation(); //e.preventDefault(); }); $("input.clickme").click(function(e){ alert("I am fired"); }); });</script></head><body><div id="tserviceslist" style="margin:25px;"> <div style="height: 178px; width: 178px;" id="icon-12608" class="icon white"> <div class="iconlinks"> <div class="info"> <a href="#" class="infolink" title="Click here to see more information about this Services." rel="nofollow">INFO</a> <div id="infomenu-12608" class="infomenu" style="display: none;"><input type="button" value="clickme" class="clickme" />Information will come here</div> </div> <div class="downloadlinks"> <h3 class="service-name">Cricket</h3> </div> </div> <br /> </div> </div></body></html> Thanking you,sureace.
Now provide the response and nothing else.
|
You just need to change the order of your handlers a bit, and use/check for propagation stopping, like this: $("a.infolink").live("click",function(e){ $("a.infolink").removeClass("selected"); $("div.infomenu").hide(); $(this).addClass("selected"); $(this).next().show(); e.stopPropagation();});$("div.infomenu").live("click",function(e){ e.stopPropagation();});$(document).click(function(e){ if(e.isPropagationStopped()) return; //important, check for it! $("a.infolink").removeClass("selected"); $("div.infomenu").hide();});$("input.clickme").click(function(e){ alert("I am fired");}); Give it a try here , there are a few important points to keep in mind: .live() handlers are on document Event handlers execute in the order they were bound to any given element You need to stop and check the propagation since we're at the same level. .stopPropagation() would prevent the bubbling from going any higher but that doesn't matter, it's at the same level in the DOM, so you need to check if it was stopped, using .isPropagationStopped() . Also, since the handlers fire in order, you need to bind that document.onclick after your other event handlers, otherwise it'll execute first, before the others tried to stop propagation.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3353275', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/400091/']}
|
jdg_374679
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
104522
|
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 not very well versed on set theory or syntax, but I thought I knew the basics. However, in a book about databases I am reading now, the author uses $2^x$ to signify "a set of $x$." For example, $2^{\text{dogs}}$ is a set of $\text {dogs}$, etc. The author never really explained this or why he does it, I just picked up the meaning from context. I am not sure why the exponent operator is used, nor am I sure what the number $2$ has to do with it. The sets being represented are NOT powers of $2$ (in size)... they come in all sizes. Is this a valid notation? I have not seen it anywhere before...
Now provide the response and nothing else.
|
The notation $2^S$ denotes the power set of S, i.e. the set of all subsets of S, also denoted $\mathcal P(S)$. The notation is in fact well chosen, with regard to the notation $X^Y$ to denote the set of all functions $Y\to X$: if we let $X = 2 = \{0,1\}$, then a function $f:Y\to \{0,1\}$ corresponds uniquely to a subset $S \subseteq Y$ if we let $x\in S\iff f(x)=1$. As a special case, when $S$ is finite the order of $\mathcal P(S)$ is in fact $|\mathcal P(S)| = 2^{|S|}$, a fact useful to remember what the notation means. (This generalizes to $|X|^{|Y|} = |X^Y|$ for arbitrary sets.) The notation $\binom{S}{i}$ is also being used: it is the set of all subsets of $S$ that contain exactly $i$ elements. Here too, $\binom{|S|}{i} = \left|\binom{S}{i}\right|$.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/104522', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/24150/']}
|
jdg_374680
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8454730
|
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 chrome print preview, under Options tab, the default is having Headers and footers ticked on. Is it not possible to set it default to off via javascript / chrome extension / anything outside telling user to do it manually? OR is it possible to remove the date displayed there?
Now provide the response and nothing else.
|
In short, yes you can control this behavior. It is actually very bizzarre -- as appears to have been originally answered in the question " In Google Chrome, Docs Can Control Headers and Footers from Javascript? " The secret to this behavior is in the @page CSS property*. If you set this exact style: @page { margin: 0; } Then you get the desired behavior, the headers & footers option disappears: This appears to be an undocumented behavior of Google Chrome, or at least not widely known -- cursory digging in to their developer docs garnered nothing. Google uses it themselves throughout their own web-apps, so it's probably not a secret, but I couldn't find any official notes on it. Notably, a margin of 0 does not simply disable the "headers & footers" option, it actually causes it to disappear from the menu entirely ( by quickly folding ). Experimentation reveals that other variations of this do not have the same effect. For example margin: 0; margin-left: 10cm; does not cause this behavior. If you do choose to implement this solution, it means forfeiting the ability to control those margins through the @page property -- you should instead be controlling them as part of a CSS print-media stylesheet. Bummer that Chrome kind of destroys the @page property this way. That said, FF still does not support @page ( as of now ) so it's not a perfect solution to begin with. *More information about the @page property The @page CSS is supposed to control the margins of the printed page, the specification says: The page box is a rectangular region that contains two areas: The page area. The page area includes the boxes laid out on that page. The edges of the first page area establish the rectangle that is the initial containing block of the document. The canvas background is painted within and covers the page area. The margin area, which surrounds the page area. The page margin area is transparent. Most modern browsers support the @page CSS property. Firefox is the standout who doesn't, though they do fully document it in their developer resources , and their issue tracker has a ticket for this that goes back 10 years. The most recent action on it was today, so perhaps FF will provide @page support soon.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8454730', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/278191/']}
|
jdg_374681
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
30578976
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Had a crash while trying to use the new TextInputField for Android and wanted to share my solution. Trying the new TextInputField in the android appcompat library was crashing my app. Here was my layout xml. <android.support.design.widget.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <EditText android:id="@+id/email" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="e-mail" android:inputType="textEmailAddress" android:singleLine="true"/></android.support.design.widget.TextInputLayout> The error I got: android.view.InflateException: Binary XML file line #20: Error inflating class android.support.design.widget.TextInputLayout. SOLUTION:Add the hintTextAppearance attribute to your TextInputLayout , so the lead tag looks like this: <android.support.design.widget.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content" app:hintTextAppearance="@android:style/TextAppearance.Medium">
Now provide the response and nothing else.
|
Make sure you have the following dependencies in your gradle file: compile 'com.android.support:appcompat-v7:22.2.0'compile 'com.android.support:design:22.2.0' Working example: <android.support.design.widget.TextInputLayout android:id="@+id/txtEmail_InpLyt" android:layout_width="match_parent" android:layout_height="wrap_content"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textEmailAddress" android:ems="10" android:id="@+id/txtEmail" android:hint="Email Address" android:singleLine="true" android:layout_alignParentTop="true" android:layout_alignParentRight="true" android:layout_alignParentEnd="true"/></android.support.design.widget.TextInputLayout> (Setting hintTextAppearance is not necessary.) Update: If you experience issues with the hint text not appearing in newer versions of Android (Marshmallow / Nougat), update library to version 22.2.1 (see TextInputLayout not showing EditText hint before user focus on it ). compile 'com.android.support:appcompat-v7:22.2.1'compile 'com.android.support:design:22.2.1'
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/30578976', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1647098/']}
|
jdg_374682
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
38961816
|
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 GeoDataFrame: h=pd.DataFrame({'zip':[19152,19047], 'Lat':[40.058841,40.202162], 'Lon':[-75.042164,-74.924594]})crs='none'geometry = [Point(xy) for xy in zip(h.Lon, h.Lat)]hg = GeoDataFrame(h, crs=crs, geometry=geometry)hg Lat Lon zip geometry0 40.058841 -75.042164 19152 POINT (-75.042164 40.058841)1 40.202162 -74.924594 19047 POINT (-74.924594 40.202162) I need to set the CRS as I did with another GeoDataFrame (like this): c=c.to_crs("+init=epsg:3857 +ellps=GRS80 +datum=GGRS87 +units=mi +no_defs") I've tried this: crs={'init': 'epsg:3857'} and this: hg=hg.to_crs("+init=epsg:3857 +ellps=GRS80 +datum=GGRS87 +units=mi +no_defs") ...but no luck. Some important notes: The other GeoDataFrame for which the above .to_crs method worked was from a shape file and the geometry column was for polygons, not points.Its 'geometry' values looked like this after the .to_crs method was applied: POLYGON ((-5973.005380655156 3399.646267693398... and when I try the above with the hg GeoDataFrame, they still look like regular lat/long coordinates. If/when this works out, I'll then concatenate these points with the polygon GeoDataFrame in order to plot both (points on top of polygons). When I try concatenating the GeoDataFrames first before using the .to_crs method, and then I use the method on both the point and polygon rows at once, I get the following error: ValueError: Cannot transform naive geometries. Please set a crs on the object first. Thanks in advance!
Now provide the response and nothing else.
|
Geopandas API got cleaned up, and now works without surprises. Make sure to use the lastest stable version and read the docs . Setting the CRS on a GeoDataFrame using its EPSG code is as simple as gdf.set_crs(epsg=4326, inplace=True) where gdf is a geopandas.geodataframe.GeoDataFrame . Watch out for the explicit inplace ! So in the example above it would be: import pandas as pdfrom shapely.geometry import Pointfrom geopandas import GeoDataFramedf = pd.DataFrame({'zip':[19152,19047], 'Lat':[40.058841,40.202162], 'Lon':[-75.042164,-74.924594]})geometry = [Point(xy) for xy in zip(df.Lon, df.Lat)]gdf = GeoDataFrame(df, geometry=geometry)gdf.set_crs(epsg=4326, inplace=True)# ^ comment out to get a "Cannot transform naive geometries" error below# project to merkatorgdf.to_crs(epsg=3395) zip Lat Lon geometry0 19152 40.058841 -75.042164 POINT (-8353655.485 4846992.030)1 19047 40.202162 -74.924594 POINT (-8340567.652 4867777.107)
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/38961816', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5569314/']}
|
jdg_374683
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
209833
|
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:
It appears that $[expr] performs arithmetic expansion just like $((expr)) . But I can't find any mention of $[ in the bash manual. This command gives no results: gunzip -c /usr/share/man/man1/bash.1.gz | grep -E '\$\[' What is this operator and is its behavior standardized anywhere? My bash version: GNU bash, version 3.2.51(1)-release (x86_64-apple-darwin13)
Now provide the response and nothing else.
|
You can find old bash source here . In particular I downloaded bash-1.14.7.tar.gz . In the documentation/bash.txt you will find: Arithmetic Expansion Arithmetic expansion allows the evaluation of an arithmetic expression and the substitution of the result. There are two formats for arithmetic expansion: $[expression] $((expression)) The references to $[ are gone in doc/bash.html from the bash-doc-2.0.tar.gz download and the NEWS file mentions that: The $[...] arithmetic expansion syntax is no longer supported, in favor of $((...)) . $((...)) is also the standard syntax for an arithmetic expansion, but may have been added to the standard later than the original Bash implementation. However, $[...] does still seem to work in Bash 5.0, so it's not completely removed.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/209833', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/67823/']}
|
jdg_374684
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
22559
|
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:
It is said that string theory is a unification of particle physics and gravitation. Is there a reasonably simple explanation for how the standard model arises as a limit of string theory? How does string theory account for the observed particle spectrum and the three generations? Edit (March 23, 2012): In the mean time, I read the paper arXiv:1101.2457 suggested in the answer by John Rennie. My impression from reading this paper is that string theory currently does not predict any particular particle content, and that (p.13) to get close to a derivation of the standard model one must assume that string theory reduces at low energies to a SUSY GUT. If this is correct, wouldn't this mean that part of what is to be predicted is instead assumed? Thus one would have to wait for a specific prediction of the resulting parameters in order to see whether or not string theory indeed describes particle physics. Some particular observations/quotes substantiating the above: (15) looks like input from the standard model The masses of the superparticles after (27) are apparently freely chosen to yield the subsequent prediction. This sort of arguments only shows that some SUSY GUT (and hence perhaps string theory) is compatible with the standard model, but has no predictive value. p.39: ''The authors impose an intermediate SO(10) SUSY GUT.'' p.58: ''As discussed earlier in Section 4.1, random searches in the string landscape suggest that the Standard Model is very rare. This may also suggest that string theory cannot make predictions for low energy physics.'' p.59: ''Perhaps string theory can be predictive, IF we understood the rules for choosing the correct position in the string landscape.'' So my followup question is: Is the above impression correct, or do I lack information available elsewhere? Edit (March 25, 2012): Ron Maimon's answer clarified to some extent what can be expected from string theory, but leaves details open that in my opinion are needed to justify his narrative. Upon his request, I posted the new questions separately as More questions on string theory and the standard model
Now provide the response and nothing else.
|
String theory includes every self-consistent conceivable quantum gravity situation, including 11 dimensional M-theory vacuum, and various compactifications with SUSY (and zero cosmological constant), and so on. It can't pick out the standard model uniquely, or uniquely predict the parameters of the standard model, anymore than Newtonian mechanics can predict the ratio of the orbit of Jupiter to that of Saturn. This doesn't make string theory a bad theory. Newtonian mechanics is still incredibly predictive for the solar system. String theory is maximally predictive, it predicts as much as can be predicted, and no more . This should be enough to make severe testable predictions, even for experiments strictly at low energies--- because the theory has no adjustable parameters. Unless we are extremely unfortunate, and a bazillion standard model vacua exist, with the right dark-matter and cosmological constant, we should be able to discriminate between all the possibilities by just going through them conceptually until we find the right one, or rule them all out. What "no adjustable parameters" means is that if you want to get the standard model out, you need to make a consistent geometrical or string-geometrical ansatz for how the universe looks at small distances, and then you get the standard model for certain geometries. If we could do extremely high energy experiments, like make Planckian black holes, we could explore this geometry directly, and then string theory would predict relations between the geometry and low-energy particle physics. We can't explore the geometry directly, but we are lucky in that these geometries at short distances are not infinitely rich. They are tightly constrained, so you don't have infinite freedom. You can't stuff too much structure without making the size of the small dimensions wrong, you can't put arbitrary stuff, you are limited by constraints of forcing the low-energy stuff to be connected to high energy stuff. Most phenomenological string work since the 1990s does not take any of these constraints into account, because they aren't present if you go to large extra dimensions. You don't have infinitely many different vacua which are qualitatively like our universe, you only have a finite (very large) number, on the order of the number of sentences that fit on a napkin. You can go through all the vacua, and find the one that fits our universe, or fail to find it. The vacua which are like our universe are not supersymmetric, and will not have any continuously adjustible parameters. You might say "it is hopeless to search through these possibilities", but consider that the number of possible solar systems is greater, and we only have data that is available from Earth. There is no more way of predicting which compactification will come out of the big-bang than of predicting how a plate will smash (although you possibly can make statistics). But there are some constraints on how a plate smashes--- you can't get more pieces than the plate had originally: if you have a big piece, you have to have fewer small piece elsewhere. This procedure is most tightly constrained by the assumption of low-energy supersymmetry, which requires analytic manifolds of a type studied by mathematicians, the Calabi-Yaus, and so observation of low-energy SUSY would be a tremendous clue for the geometry. Of course, the real world might not be supersymmetric until the quntum gravity scale, it might have a SUSY breaking which makes a non-SUSY low-energy spectrum. We know such vacua exist, but they generally have a big cosmological constant. But the example of SO(16) SO(16) heterotic strings shows that there are simple examples where you get a non-SUSY low energy vacuum without work. If your intuition is from field theory, you think that you can just make up whatever you want. This is just not so in string theory. You can't make up anything without geoemtry, and you only have so much geometry to go around. The theory should be able to, from the qualitative structure of the standard model, plus the SUSY, plus say 2-decimal place data on 20 parameters (that's enough to discrimnate between 10^40 possibilities which are qualitatively identical to the SM), it should predict the rest of the decimal places with absolutely no adjustible anything. Further, finding the right vacuum will predict as much as can be predicted about every experiment you can perform. This is the best we can do. The idea that we can predict the standard model uniquely was only suggested in string propaganda from the 1980s, which nobody in the field really took seriously, which claimed that the string vacuum will be unique and identical to ours. This was the 1980s fib that string theorists pushed, because they could tell people "We will predict the SM parameters". This is mostly true, but not by predicting them from scratch, but from the clues they give us to the microscopic geometry (which is certainly enough when the extra dimensions are small).
|
{}
|
{'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/22559', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/7924/']}
|
jdg_374685
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
37797
|
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 having some difficulties interpreting the results of an analysis perfomed using lme. I conducted an experiment where the subjects had to estimate the time elapsed in a task involving a spatial measure (e.g. subjects watched a video game where a car travels a certain distance). My goal is to determine if there is a linear relation between perceived time and the space traveled by the car.Subject underwent 2 different conditions (e.g. the car was traveling two distances), and each condition was repeated twice. Therefore, given the nature of the experimental design involving repeated measures, I cannot use a simple linear model but I have to use a mixed effects linear model with a random intercept for subject. I use the R language, and I adopted this formula to solve my problem library(nlme)summary(lme(Time ~ Distance, data = my_Table, random = ~1 | Subject)) The output that I get is: Linear mixed-effects model fit by REML Data: my_Table AIC BIC logLik 608.315 618.4454 -300.1575Random effects: Formula: ~1 | Subject (Intercept) ResidualStdDev: 2.964139 4.919044Fixed effects: Time ~ Distance Value Std.Error DF t-value p-value(Intercept) 5.518714 0.8212930 64 6.719543 0.0000 Distance 0.013092 0.0053225 64 2.459718 0.0166 Correlation: (Intr) Distance -0.415Standardized Within-Group Residuals: Min Q1 Med Q3 Max -1.2904862 -0.4302117 -0.2593047 0.2081889 5.0914269 Number of Observations: 95Number of Groups: 30 Now, what is this output telling me? As far as I understand from studying the literature that I found online (I am not a statistician...), if I am rght these results are telling me that there is a linear relation between time and space, since b = 0.013092 and p-value is significant. Now, if the p-value was not significant, this would have meant that there is no linear relation between time and space?
Now provide the response and nothing else.
|
I will assume that the modeling assumptions you made are correct and you ran the program properly since your question only addresses the interpretation of the output.In a linear model involving a single covariate, you can test for a linear association either by testing whether the slope coefficient is 0 or not or by testing that the Pearson correlation between the response and the covariate is 0 or not. You tested the slope coefficient and got a small slope that is positive. The test for that coefficient being 0 had a p-value of 0.0166. If that p-value is below your desired significance level, you would conclude that there is some relationship between the covariate and response. Using a traditional significance level of 0.05, you would then reject the null hypothesis that there is no relationship. However, the slope appears to be small and the intercept is the dominant term in the model. Saying that the correlation is not zero is not the same as saying that the correlation is strong. You should look at say a 95% confidence interval for the correlation and think about what its upper bound is telling. If a strong correlation to you is, say, around 0.6 and the upper bound is, say, 0.1, this suggests that the correlation though probably greater than 0 is not strong. Addressing your second question, if the p-value is not below your significance level, you don't conclude anything. What you know is that the data did not supply enough evidence that the correlation is different from 0. This could be because it is 0 or very close to 0. But more importantly, it could be that the sample size is not large enough to reach the conclusion that it is different from 0. Now if you instead address the issue of strong correlation and 0.6 is your definition of strong then it may be the case that the upper bound of the 95% confidence interval for the Pearson correlation is below (perhaps far below) 0.6 and you can still claim at least that the correlation is not strong. Understand that testing for strong correlation is different than testing for non-zero correlation and the p-value in your output address the latter test in my previous sentence and not the former.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/37797', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/4701/']}
|
jdg_374686
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
19025935
|
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 open a dialog window above the center of its parent window, so I use the following formula: Window window = ((Node) actionEvent.getSource()).getScene().getWindow();Scene scene = new Scene(new Group(new DialogWindow()));Stage dialog = new Stage();dialog.initOwner(window);dialog.sizeToScene();dialog.setX(stage.getX() + stage.getWidth() / 2 - dialog.getWidth() / 2); //dialog.getWidth() = NaNdialog.setY(stage.getY() + stage.getHeight() / 2 - dialog.getHeight() / 2); //dialog.getHeight() = NaNdialog.setScene(scene);dialog.show(); //it is better to showAndWait(); I don't set size the manually because I need the window to be sized automatically to the size of its content. Under Linux it sets window straight in the center of the parent window. But in Windows it doesn't work and leads to different results. How can I get the dialog's width and height if I don't set them manually?
Now provide the response and nothing else.
|
The width and height of Stage are calculated after it has been shown ( .show() ). Do the calculation after it: ...dialog.show();dialog.setX(stage.getX() + stage.getWidth() / 2 - dialog.getWidth() / 2); //dialog.getWidth() = not NaNdialog.setY(stage.getY() + stage.getHeight() / 2 - dialog.getHeight() / 2); //dialog.getHeight() = not NaN EDIT: If showAndWait() is used instead of show() , then since showAndWait() blocks the caller event the calculations after the showAndWait() are also blocked. The one way of workaround could be doing calculation before in new Runnable : final Stage dialog = new Stage();dialog.initOwner(window);dialog.initModality(Modality.WINDOW_MODAL);dialog.sizeToScene();dialog.setScene(scene);Platform.runLater(new Runnable() { @Override public void run() { dialog.setX(primaryStage.getX() + primaryStage.getWidth() / 2 - dialog.getWidth() / 2); //dialog.getWidth() = NaN dialog.setY(primaryStage.getY() + primaryStage.getHeight() / 2 - dialog.getHeight() / 2); //dialog.getHeight() = NaN }});dialog.showAndWait(); Note also on initModality . The modality must be set in case of showAndWait() . Otherwise using showAndWait() has no sense.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19025935', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1049521/']}
|
jdg_374687
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1323969
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
What are some examples of groups that can not be given a smooth structure such that they become a Lie Group? Edit: To be a bit more specific, I was hoping that somebody could give an example of a finite dimensional topological group that is a topological manifold but does not admit a smooth structure making it into a Lie Group.
Now provide the response and nothing else.
|
Any group is a Lie group if you give it the discrete topology. The better question is whether a topological group has a smooth structure that makes it a Lie group. Local compactness is obviously necessary (because you want finite dimensions), so any non-locally compact group will be an example. Generally, most locally compact groups are Lie groups. This question is essentially Hilbert's 5th Problem, which has been solved: https://en.wikipedia.org/wiki/Hilbert 's_fifth_problem
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1323969', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/160921/']}
|
jdg_374688
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14342430
|
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 researching queuing solutions for one of my team's apps. Ideally we would like something that can be configured both as a lightweight, in-process broker (for low-throughput messaging between threads) and as an external broker. Is there an MQ server out there that can do this? Most seem to require setup as an external entity. ZeroMQ appears to come the closest to an in-process solution, but it seems to be more of a "UDP socket on steroids", and we need reliable delivery.
Now provide the response and nothing else.
|
Like we said ActiveMQ is a bit heavier than ZeroMQ but it work really well as an embedded process. Here a simple example with Spring and ActiveMQ . The message listener that will be used to test the queue : public class TestMessageListener implements MessageListener { private static final Logger logger = LoggerFactory.getLogger(TestMessageListener.class); @Override public void onMessage(Message message) { /* Receive the text message */ if (message instanceof TextMessage) { try { String text = ((TextMessage) message).getText(); System.out.println("Message reception from the JMS queue : " + text); } catch (JMSException e) { logger.error("Error : " + e.getMessage()); } } else { /* Handle non text message */ } }} ActiveMQ context configuration : <?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="jmsQueueConnectionFactory" class="org.apache.activemq.spring.ActiveMQConnectionFactory"> <property name="brokerURL"> <value>tcp://localhost:61617</value> </property> </bean> <bean id="pooledJmsQueueConnectionFactory" class="org.apache.activemq.pool.PooledConnectionFactory" destroy-method="stop"> <constructor-arg ref="jmsQueueConnectionFactory" /> </bean> <bean id="queueDestination" class="org.apache.activemq.command.ActiveMQQueue"> <constructor-arg value="messageQueue" /> </bean> <bean id="jmsQueueTemplate" class="org.springframework.jms.core.JmsTemplate"> <constructor-arg ref="pooledJmsQueueConnectionFactory" /> <property name="pubSubDomain" value="false"/> </bean> <bean id="testMessageListener" class="com.example.jms.TestMessageListener" /> <bean id="messageQueuelistenerContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer"> <property name="connectionFactory" ref="pooledJmsQueueConnectionFactory" /> <property name="destination" ref="QueueDestination" /> <property name="messageListener" ref="testMessageListener" /> <property name="concurrentConsumers" value="5" /> <property name="acceptMessagesWhileStopping" value="false" /> <property name="recoveryInterval" value="10000" /> <property name="cacheLevelName" value="CACHE_CONSUMER" /> </bean></beans> The JUnit test : @ContextConfiguration(locations = {"classpath:/activeMQ-context.xml"})public class SpringActiveMQTest extends AbstractJUnit4SpringContextTests { @Autowired private JmsTemplate template; @Autowired private ActiveMQDestination destination; @Test public void testJMSFactory() { /* sending a message */ template.convertAndSend(destination, "Hi"); /* receiving a message */ Object msg = template.receive(destination); if (msg instanceof TextMessage) { try { System.out.println(((TextMessage) msg).getText()); } catch (JMSException e) { System.out.println("Error : " + e.getMessage()); } } }} The Dependencies to add to the pom.xml : <!-- Spring --><dependency> <groupId>org.springframework</groupId> <artifactId>spring-jms</artifactId> <version>${org.springframework-version}</version></dependency><!-- ActiveMQ --><dependency> <groupId>org.apache.activemq</groupId> <artifactId>activemq-all</artifactId> <version>5.6.0</version> <scope>compile</scope></dependency><dependency> <groupId>org.apache.activemq</groupId> <artifactId>activemq-pool</artifactId> <version>5.6.0</version></dependency><dependency> <groupId>org.apache.activemq</groupId> <artifactId>activemq-core</artifactId> <version>5.6.0</version></dependency>
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14342430', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/612265/']}
|
jdg_374689
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
32612650
|
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 docker images are built on a Jenkins CI server and are pushed to our private Docker Registry. My goal is to provision environments with docker-compose which always start the originally built state of the images. I am currently using docker-compose 1.3.2 as well as 1.4.0 on different machines but we also used older versions previously. I always used the docker-compose pull && docker-compose up -d commands to fetch the fresh images from the registry and start them up. I believe my preferred behaviour was working as expected up to a certain point in time, but since then docker-compose up started to re-run previously stopped containers instead of starting the originally built images every time. Is there a way to get rid of this behaviour? Could that way be one which is wired in the docker-compose.yml configuration file to not depend "not forgetting" something on the command line upon every invocation? ps. Besides finding a way to achieve my goal, I would also love to know a bit more about the background of this behaviour. I think the basic idea of Docker is to build an immutable infrastructure. The current behaviour of docker-compose just seem to plain clash with this approach.. or do I miss some points here?
Now provide the response and nothing else.
|
docker-compose up --force-recreate is one option, but if you're using it for CI, I would start the build with docker-compose rm -f to stop and remove the containers and volumes (then follow it with pull and up). This is what I use: docker-compose rm -fdocker-compose pulldocker-compose up --build -d# Run some tests./testsdocker-compose stop -t 1 The reason containers are recreated is to preserve any data volumes that might be used (and it also happens to make up a lot faster). If you're doing CI you don't want that, so just removing everything should get you want you want. Update: use up --build which was added in docker-compose 1.7
|
{}
|
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/32612650', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/548915/']}
|
jdg_374690
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
38370979
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it possible to use nested switch statement in javascript. My code is some what look like switch(id1){case 1: switch(id2){ case 1:{ switch(id3){ case 1:{} case 2:{} } } case 2:{ switch(id4){ case 1:{} case 2:{} } }}case 2:} If yes then it is a good practice to do or we can use any alternate approach.
Now provide the response and nothing else.
|
Your approach is absolutely fine. You can make the switch nesting less complex by using switch (true) : switch (true) { case ((id1 === 1) && (id2 === 1) && (id3 === 1)) : case ((id1 === 1) && (id2 === 1) && (id3 === 2)) : case ((id1 === 1) && (id2 === 2) && (id3 === 1)) : case ((id1 === 1) && (id2 === 2) && (id3 === 2)) : case ((id1 === 2) && (id2 === 1) && (id3 === 1)) : case ((id1 === 2) && (id2 === 1) && (id3 === 2)) : case ((id1 === 2) && (id2 === 2) && (id3 === 1)) : case ((id1 === 2) && (id2 === 2) && (id3 === 2)) :}
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/38370979', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6574348/']}
|
jdg_374691
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
192325
|
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:
Definition of a vector space : Let $V$ be a set and $(\mathbb{K}, +, \cdot)$ a field . $V$ is called a vector space over the field $\mathbb{K}$ if: V1 : $(V, +)$ is a commutative group V2 : $\forall \lambda, \mu \in \mathbb{K} \land \forall x, y \in V:$ $1 \cdot x = x$ $\lambda \cdot (\mu \cdot x) = (\lambda \cdot \mu) \cdot x$ $(\lambda + \mu) \cdot x = \lambda \cdot x + \mu \cdot x$ $\lambda \cdot (x + y) = \lambda \cdot x + \lambda \cdot y$ My question: If you have a vector space over a finite field $\mathbb{K}$, is the set $V$ always finite? My examples An example for a finite vector space is $V = (\mathbb{Z}/2\mathbb{Z})^n, n \in \mathbb{N}$ over the field $\mathbb{Z}/2 \mathbb{Z}$. I've tried to find a infinite vector space (I mean the number of vectors should be infinite) over a finite field. I chose $\mathbb{Z}/2 \mathbb{Z}$ as my field and $V = \mathbb{R}^2$. But in this case V2.3 doesn't work: $\lambda = \mu = 1, x = \begin{pmatrix}1\\2\end{pmatrix}$: $(\lambda + \mu) \cdot x = (1+1)\cdot x = \begin{pmatrix}0\\0\end{pmatrix} \cdot x = 0 \neq \begin{pmatrix}2\\4\end{pmatrix} = 1 \cdot x + 1 \cdot x$
Now provide the response and nothing else.
|
Yes to your comment below Ahriman's, Moose. These are not the only examples, though: if $\,\Bbb F=\Bbb F_p\,$ is the prime finite field of order a prime $\,p\,$, then $\,\Bbb F\times \Bbb F\times...\,$ is an infinite vector space over $\,\Bbb F\,$. In short: a vector space over a finite field is finite iff it is finite dimensional.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/192325', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/6876/']}
|
jdg_374692
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
225217
|
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:
When it comes to passwd/user-password-crypted statement in a preseed file, most examples use an MD5 hash. Example: # Normal user's password, either in clear text#d-i passwd/user-password password insecure#d-i passwd/user-password-again password insecure# or encrypted using an MD5 hash.#d-i passwd/user-password-crypted password [MD5 hash] From Debian's Appendix B. Automating the installation using preseeding . A few sources show that it's also possible to use SHA-512: Try using a hashed password like this: $ mkpasswd -m sha-512 [...] And then in your preseed file: d-i passwd/user-password-crypted password $6$ONf5M3F1u$bpljc9f1SPy1w4J2br[...] From Can't automate user creation with preseeding on AskUbuntu . This is slightly better than MD5, but still doesn't resist well against brute force and rainbow tables. What other algorithms can I use? For instance, is PBKDF2 supported, or am I limited by the algorithms used in /etc/shadow , that is MD5, Blowfish, SHA-256 and SHA-512 ?
Now provide the response and nothing else.
|
You can use anything which is supported in the /etc/shadow file. The string given in the preseed file is just put into /etc/shadow. To create a salted password to make it more difficult just use mkpasswd with the salt option (-S): mkpasswd -m sha-512 -S $(pwgen -ns 16 1) mypassword$6$bLyz7jpb8S8gOpkV$FkQSm9YZt6SaMQM7LPhjJw6DFF7uXW.3HDQO.H/HxB83AnFuOCBRhgCK9EkdjtG0AWduRcnc0fI/39BjmL8Ee1 In the command above the salt is generated by pwgen .
|
{}
|
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/225217', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/11229/']}
|
jdg_374693
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
20298126
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Commenting in your source code is generally considered a good practice. But is there any chance that commenting in a program's source code making the program execution slow ? Thanks in advance!
Now provide the response and nothing else.
|
No, not in Java. Comments are removed when you compile your code. Further explaining, it depends on the type of programming language you are using. For compiled programs, only the executable files are used by the computer during running the program instead of the source files. For example in java, .class files files does not have any traces of comments to make the program slow. In case of interpreted languages like PHP, interpreter has to know that its a comment on every line starting with // . So it might take a faction of seconds (usually negligible) more time to execute. But in case web languages like HTML and JavaScript, the comments are actually fetched to the client. When you click on view source of a webpage, you can see the actual HTML and JavaScript comments. This ofcourse will have to be loaded to the machine and will take considerable amount of time. Therefore, we care about minifying HTML, CSS and JS in the production environment. So to sum up, it depends on programming languages whether the comments make a program slower. Hope it was helpful.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20298126', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2949999/']}
|
jdg_374694
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8182882
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Im not good in querying. I would like to ask if this query works.I want to retrieve starttime, endtime and sessioncost from the table SESSION of my database. my program will be an autorun. IT MEANS THAT ID SHOULD BE SELECTED AUTOMATICALLY WHEN IT RUNS. Dim sql As String = "select STARTTIME, ENDTIME, SESSIONCOST from SESSIONS where CLIENTID = (?)" I cant post the image because it requires more than 10 reputation. Im sorry.. If you have a better code/query, I appreciate your help. :)thank you so much for your feedback..
Now provide the response and nothing else.
|
There is no such method as Connection() and getPreparedStatement() on java.sql.Connection . conn.Connection();stmt = conn.getPreparedStatement("select id_usuario, id_grupo from usuarios_grupos where id_grupo ='" + var + "'"); The conn is clearly a homegrown wrapper around JDBC code. Your particular problem is likely caused by the code behind the getPreparedStatement() method. It's apparently appending a ? to the SQL string before delegating through to the real connection.prepareStatement() method. You probably don't want to hear this, but your JDBC approach is totally broken. This design indicates that the JDBC Connection is hold as a static or instance variable which is threadunsafe . You need to totally rewrite it so that it boils down to the following proper usage and variable scoping: public List<UsuariousGrupos> select(Integer idGrupo) throws SQLException { Connection connection = null; PreparedStatement statement = null; ResultSet resultSet = null; List<UsuariousGrupos> usuariousGrupos = new ArrayList<UsariousGrupos>(); try { connection = database.getConnection(); statement = connection.prepareStatement("select id_usuario, id_grupo from usuarios_grupos where id_grupo = ?"); statement.setInt(1, idGrupo); resultSet = statement.executeQuery(); while (resultSet.next()) { usuariousGrupos.add(mapUsuariousGrupos(resultSet)); } } finally { if (resultSet != null) try { resultSet.close(); } catch (SQLException ignore) {} if (statement != null) try { statement.close(); } catch (SQLException ignore) {} if (connection != null) try { connection.close(); } catch (SQLException ignore) {} } return usuariousGrupos;} See also: How to declare a global static class in Java? Unrelated to the concrete question, you've another problem. The following exception javax.el.ELException: /index.xhtml @61,99 value="#{usuariousGruposBean.listOfUserGroups}": Error reading 'listOfUserGroups' on type br.view.UsuariousGruposBean indicates that you're doing the JDBC stuff inside a getter method instead of (post)constructor or (action)listener method. This is also a very bad idea because a getter can be called more than once during render response. Fix it accordingly. See also: Why JSF calls getters multiple times
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8182882', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1053671/']}
|
jdg_374695
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13359327
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
List<Int32> dansConList = new List<Int32>();dansConList[0] = 1;dansConList[1] = 2;dansConList[2] = 3;List<Int32> dansRandomList = new List<Int32>();dansRandomList[0] = 1;dansRandomList[1] = 2;dansRandomList[2] = 4; I need a method that, when evaluating the above lists, will return false for dansRandomList and true for dansConList based on the fact dansConList has a consecutive number sequence in it's values, and dansRandomList does not (missing the value 3). Using LINQ is preferable, if possible. What I've Tried: For the sake of achieving the end result, I have used a for loop and compare with 'i' (loop counter) to evaluate the values, but as mentioned above I'd like to use LINQ for this.
Now provide the response and nothing else.
|
One-liner, only iterates until the first non-consecutive element: bool isConsecutive = !myIntList.Select((i,j) => i-j).Distinct().Skip(1).Any(); Update: a couple examples of how this works: Input is { 5, 6, 7, 8 }Select yields { (5-0=)5, (6-1=)5, (7-2=)5, (8-3=)5 }Distinct yields { 5, (5 not distinct, 5 not distinct, 5 not distinct) }Skip yields { (5 skipped, nothing left) }Any returns false Input is { 1, 2, 6, 7 }Select yields { (1-0=)1, (2-1=)1, (6-2=)4, (7-3=)4 } *Distinct yields { 1, (1 not distinct,) 4, (4 not distinct) } *Skip yields { (1 skipped,) 4 }Any returns true * The Select will not yield the second 4 and the Distinct will not check it, as the Any will stop after finding the first 4.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/13359327', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
|
jdg_374696
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9251635
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I think that my issue should be really simple, yet I can not find any helpon the Internet whatsoever. I am very new to Python, so it is possible thatI am missing something very obvious. I have an array, S, like this [x x x] (one-dimensional) . I now create a diagonal matrix, sigma , with np.diag(S) - so far, so good. Now, I want to resize this new diagonal array so that I can multiply it by another array thatI have. import numpy as np...shape = np.shape((6, 6)) #This will be some pre-determined sizesigma = np.diag(S) #diagonalise the matrix - this worksmy_sigma = sigma.resize(shape) #Resize the matrix and fill with zeros - returns "None" - why? However, when I print the contents of my_sigma , I get "None" . Can someone pleasepoint me in the right direction, because I can not imagine that this should beso complicated. Thanks in advance for any help! Casper Graphical: I have this: [x x x] I want this: [x 0 0][0 x 0][0 0 x][0 0 0][0 0 0][0 0 0] - or some similar size, but the diagonal elements are important.
Now provide the response and nothing else.
|
sigma.resize() returns None because it operates in-place. np.resize(sigma, shape) , on the other hand, returns the result but instead of padding with zeros, it pads with repeats of the array . Also, the shape() function returns the shape of the input . If you just want to predefine a shape, just use a tuple. import numpy as np...shape = (6, 6) #This will be some pre-determined sizesigma = np.diag(S) #diagonalise the matrix - this workssigma.resize(shape) #Resize the matrix and fill with zeros However, this will first flatten out your original array, and then reconstruct it into the given shape, destroying the original ordering. If you just want to "pad" with zeros, instead of using resize() you can just directly index into a generated zero-matrix. # This assumes that you have a 2-dimensional arrayzeros = np.zeros(shape, dtype=np.int32)zeros[:sigma.shape[0], :sigma.shape[1]] = sigma
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9251635', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1205479/']}
|
jdg_374697
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18726102
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Once, my teacher taught me to use randomize() and random() function for generating pseudorandom numbers in C++ Builder. Now I prefer working in VS 2012, but when I tried to use these functions there it says that "identifier not found", even when I added #include <stdlib.h> . After some time of Googling I found that there are also rand() and srand() functions. What is the difference between them and which is it better to use?
Now provide the response and nothing else.
|
randomize() and random() are not part of the standard library. Perhaps your teacher wrote functions with these names for use in your class, or maybe you really mean random() and srandom() which are part of POSIX and not available on Windows. rand() and srand() are part of the standard library and will be provided by any standard conforming implementation of C++. You should avoid rand() and srand() and use the new C++11 <random> library. <random> was added as part of the C++11 standard (and VS2012 does provide it). Video explaining why: rand() Considered Harmful rand() is sometimes a low quality pRNG and not suitable for applications that need a reasonable level of unpredictability. <random> provides a variety of engines with different characteristics suitable for many different use cases. Converting the results of rand() into a number you can use directly usually relies on code that is difficult to read and easy to get wrong, whereas using <random> distributions is easy and produces readable code. The common methods of generating values in a given distribution using rand() further decrease the quality of the generated data. % generally biases the data and floating point division still produces non-uniform distributions. <random> distributions are higher quality as well as more readable. rand() relies on a hidden global resource. Among other issues this causes rand() to not be thread safe. Some implementations make thread safety guarantees, but this is not required by the standard. Engines provided by <random> encapsulate pRNG state as objects with value semantics, allowing flexible control over the state. srand() only permits a limited range of seeds. Engines in <random> can be initialized using seed sequences which permit the maximum possible seed data. seed_seq also implements a common pRNG warm-up. example of using <random> : #include <iostream>#include <random>int main() { // create source of randomness, and initialize it with non-deterministic seed std::random_device r; std::seed_seq seed{r(), r(), r(), r(), r(), r(), r(), r()}; std::mt19937 eng{seed}; // a distribution that takes randomness and produces values in specified range std::uniform_int_distribution<> dist(1,6); for (int i=0; i<100; ++i) { std::cout << dist(eng) << '\n'; }}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18726102', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2371124/']}
|
jdg_374698
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
16453205
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have an array of NSStrings , one UILabel & a UICollectionView . My Question: I want the array's count to determine how many UICollectionViewCell 's there are. Each UICollectionViewCell contains a button. Upon click, I want this button to cause the data in the array that corresponds to the UICollectionViewCell 's number to be displayed in the label. For example, if the user clicks on the 13th UICollectionViewCell 's button, then the 13th NSString in the array would become the UILabel 's text. What I have done: I have made my own subclass of UICollectionViewCell for the nib file that I use for all of the UICollectionViewCell s, & connected the button to the .h file as a IBAction . I have also imported the MainViewController.h , which is the one that contains the array property that stores the NSString s. When I edit the code in the UICollectionViewCell 's action, I cannot access the array property. The button does work - I placed an NSLog in the IBAction 's method, which does work. I have searched through tens of other answers on SO, but none answer my specific question. I can update this with samples of my code if requested.
Now provide the response and nothing else.
|
I have made my own subclass of UICollectionViewCell for the nib file that I use for all of the UICollectionViewCells, and connected the button to the .h file as a IBAction. If you connect the IBAction to the subclass of collectionViewCell you would need to create a delegate to make the touch event available in the viewController where you are displaying the data. One easy tweak is to add the button the collectionViewCell, connect it's IBOutlet to the cell. But not IBAction. In the cellForRowAtIndexPath: add an eventHandler for button in that viewController containing collectionView. - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{ //Dequeue your cell [cell.button addTarget:self action:@selector(collectionViewCellButtonPressed:) forControlEvents:UIControlEventTouchUpInside]; return cell;}- (IBAction)collectionViewCellButtonPressed:(UIButton *)button{ //Acccess the cell UICollectionViewCell *cell = button.superView.superView; NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell]; NSString *title = self.strings[indexPath.row]; self.someLabel.text = title;}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16453205', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1558365/']}
|
jdg_374699
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
29347790
|
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 always getting confused on whether a function would raise an IOError or OSError (or both?). What is the principle rule behind these exception types, what is the difference between them and when is which raised? I've initially thought OSError is for things like permission denial, but opening a file without permissions will raise an IOError.
Now provide the response and nothing else.
|
There is very little difference between the two types. In fact, even the core Python developers agreed that there is no real difference and removed IOError in Python 3 (it is now an alias for OSError ). See PEP 3151 - Reworking the OS and IO exception hierarchy : While some of these distinctions can be explained by implementation considerations, they are often not very logical at a higher level. The line separating OSError and IOError , for example, is often blurry. Consider the following: >>> os.remove("fff")Traceback (most recent call last): File "<stdin>", line 1, in <module>OSError: [Errno 2] No such file or directory: 'fff'>>> open("fff")Traceback (most recent call last): File "<stdin>", line 1, in <module>IOError: [Errno 2] No such file or directory: 'fff' Yes, that's two different exception types with the exact same error message . For your own code, stick to throwing OSError . For existing functions, check the documentation (it should detail what you need to catch), but you can safely catch both: try: # ...except (IOError, OSError): # handle error Quoting the PEP again: In fact, it is hard to think of any situation where OSError should be caught but not IOError , or the reverse.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/29347790', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/791713/']}
|
jdg_374700
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2018984
|
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 is it possible to indent lines in an algorithm (algorithmic) in latex? I would like to be able to write the following: \begin{algorithm}[H]\caption{My Awesome Program} \label{awesome-algorithm}\begin{algorithmic}[1]\FOR { $i=0$ to $logn$ } \STATE Step A: % would like the indent the next lines... \STATE do something \STATE do another thing \STATE Step B\ENDFOR\end{algorithmic}\end{algorithm} How is it possible to indent those lines?I've been trying to find the answer by googling without success. I hope you guys can help me. Thanks. I'm currently using the following for indentation: \STATE \ \ \ \ do something which seems plain wrong. But works.
Now provide the response and nothing else.
|
Try this instead: \STATE\hspace{\algorithmicindent} do something\STATE\hspace{\algorithmicindent} do another thing It should work better because it uses the current indent value to indent. Edit : Using Charles's suggestion, you could define a new command, \INDSTATE : \newcommand{\INDSTATE}[1][1]{\STATE\hspace{#1\algorithmicindent}} and then use that when you want indentation. By default, \INDSTATE indents by one level, but you can change it: \INDSTATE do something % What you want\INDSTATE[2] do something % Indent by twice the amount
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2018984', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/154989/']}
|
jdg_374701
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7281352
|
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 ArrayList<Car> For Example class Car{ String carName; int carType;} Now, I have to find if the list has any cars having same name. What is the best way to do this?
Now provide the response and nothing else.
|
Create a comparator: public class CarComparator implements Comparator<Car>{ public int compare(Car c1, Car c2) { return c1.carName.compareTo(c2.carName); }} Now add all the cars of the ArrayList to a SortedSet , preferably TreeSet ; if there are duplicates add to the list of duplicates: List<Car> duplicates = new ArrayList<Car>();Set<Car> carSet = new TreeSet<Car>(new CarComparator());for(Car c : originalCarList){ if(!carSet.add(c)) { duplicates.add(c); }} Finally in your duplicates you will have all the duplicates.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7281352', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/710051/']}
|
jdg_374702
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
47230536
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I would like to display some kind of animation in my console application during a long process and have no idea how to do this. I already did a research but the solutions I found did not arouse my interest or I was not happy to understand them. My application loads a text file and traverses all lines one by one by performing a search for words to be replaced. It could be a progress bar or any loop animation.
Now provide the response and nothing else.
|
Here's a sample that will produce the message Processing X of Y (Z%) ... in a loop, with a delay that would represent the time spent doing something in the loop. Obviously, it's a contrived example, but it shows one possibility. (Also obviously, you would replace the value for the upper limit of the loop and the Y in the message with a meaningful value, such as TStringList.Count .) program Project1;{$APPTYPE CONSOLE}uses System.SysUtils;var i: Integer; StopValue, Pct: Integer;(* #13 is a carriage return, which moves the cursor back to the left side of the console without adding a line feed (#10). It allows writing on the same line over the same content without moving to the next line. See the demo output.*)const StatusMsg = #13'Processing %d of %d (%d%%) ...';begin StopValue := 150; // Replace with your upper limit, e.g. StringList.Count for i := 1 to StopValue do begin Pct := Trunc((i * 1.0 / StopValue) * 100); Write(Format(StatusMsg, [i, StopValue, Pct])); (**************************************************************** Note: The call to Sleep here is only to introduce an artificial delay in the loop in order to allow the progress to be seen. Otherwise, the empty loop runs so fast that it's not clear when the progress increments are shown. Clearly, you would replace the call to Sleep with your code to actually do some work, such as processing each line of the text file. Explained in detail for clarity, as some commenters have indicated they're not capable of understanding why a call to Sleep is used here, so adding this unnecessarily large comment is needed for them. ****************************************************************) Sleep(250); end; Write(#13'Processing complete. Press Enter to quit.'); ReadLn;end. Snapshot of progress indicator
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47230536', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8920907/']}
|
jdg_374703
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
11005279
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I wrote code which calls the Jersey client API which in turn calls a web service which is out of my control. I do not want my unit test to call the actual web service. What is the best approach for writing a unit test for code which calls the Jersey client API? Should I use the Jersey server API to write a JAX-RS web service and then use the Jersey Test Framework for the unit test? Or should I mock out the Jersey web service calls? I have access to JMock. Or should I try another approach? During my research, I found this discussion describing various options, but I did find a complete solution. Are there any code examples available showing a suggested JUnit approach? I could not find any in the Jersey documentation. Here is the relevant source code: public String getResult(URI uri) throws Exception { // error handling code removed for clarity ClientConfig clientConfig = new DefaultClientConfig(); Client client = Client.create(clientConfig); WebResource service = client.resource(uri); String result = service.accept(accept).get(String.class); return result;} Here are examples of test code I would like to pass. I would like to test (1) passing in a valid URI and getting a valid string back and (2) passing in an invalid (for whatever reason -- unreachable or unauthorized) URI and getting an exception back. @Testpublic void testGetResult_ValidUri() throws Exception { String xml = retriever.getResult(VALID_URI); Assert.assertFalse(StringUtils.isBlank(xml));}@Test(expected = IllegalArgumentException.class)public void testGetResult_InvalidUri() throws Exception { retriever.getResult(INVALID_URI);} Everything above is the simple description of what my code does. In reality, there is a layer on top of that that accepts two URIs, first tries calling the first URI, and if that URI fails then it tries calling the second URI. I would like to have unit tests covering (1) the first URI succeeds, (2) the first URI fails and the second URI succeeds, and (3) both URIs fail. This code is sufficiently complex that I want to test these different scenarios using JUnit, but to do this I either need to run actual stand-in web services or mock out the Jersey client API calls.
Now provide the response and nothing else.
|
Try to use Mockito or Easymock for mocking service calls. You need to mock only these methods which are actually used - no need to mock every method. You can creat mock object for WebResource class, then mock accept method call. In @BeforeClass/@Before JUnit test method write something like (Mockito example) WebResource res = mock(WebResource.class);when(res.accept(something)).thenReturn(thatWhatYouWant); Then in your tests you can use res object as if it was real object and call mock method on it. Instead of returning value you can also throw exceptions. Mockito is pretty cool.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11005279', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/364029/']}
|
jdg_374704
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
111875
|
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:
The particles of the standard model are often displayed in groupings known as multiplets . I know that this somehow relates to the underlying symmetries of the standard model, which can be viewed as tranforming these particles into each other. I have still struggled to pin down exactly what is meant by these multiplet groupings however, and to get a good 'feel' of the concept. Could somebody elaborate please?
Now provide the response and nothing else.
|
Put simply, a particle multiplet is a combination of particles that transform into each other under a symmetry transformation. In order to describe a system you need two main ingredients: Symmetry groups Field content If the system is invariant under a symmetry then the fields must be of the form of multiplets (otherwise its impossible to form an combination of fields). There are many examples of such multiplets. These field combinations are just the most convenient way to describe the system with a symmetry. A particularly rudimentary example is from spin-spin interactions in Quantum Mechanics. We assume the system is invariant under a spin symmetry, $SU(2)$. Then if we suppose the system has two spin 1/2 particles then the four possible states are the singlet and triplet states:\begin{equation} \left|0,0 \right\rangle , \quad \left| 1,1 \right\rangle , \left| 1, 0 \right\rangle , \left| 1 , - 1 \right\rangle \end{equation} Under an SU(2) rotation we have,\begin{align}& \psi ^{ singlet} \rightarrow \psi ^{ singlet} \\ & \psi ^{ triplet} _i \rightarrow U _{ ij} \psi ^{ triplet} _{ j}\end{align} In other words transformations produce rotations between the particles in the multiplet but never take a field outside that multiplet (a triplet can't rotate into a singlet). Another important example is brought up by AnnaV. The SM is approximately invariant under an $ SU(3) $ chiral symmetry, under which the up, down, and strange quark transform into one another. To see this consider the QCD Lagrangian at energies well below the charm mass such that we can effectively ignore it as well as the bottom and top:\begin{equation} {\cal L} _{ QCD} = \sum _{ i = u,d ,c }\bar{\psi} _i ( i D _\mu \gamma ^\mu - m _i ) \psi _i - \frac{1}{4} G _{ \mu \nu } ^a G ^{ \mu \nu } _{ a} \end{equation} This Lagrangian is not invariant under the flavor $ SU(3) $ transformation,\begin{equation} \psi _i \rightarrow U _{ ij} \psi _i \end{equation} since the mass term in not invariant. But if we work well above the strange mass (but still below the charm mass) then we approximately have,\begin{equation} {\cal L} _{ QCD} \approx \sum _{ i = u,d ,c }\bar{\psi} _i ( i D _\mu \gamma ^\mu ) \psi _i - \frac{1}{4} G _{ \mu \nu } ^a G ^{ \mu \nu } _{ a} \end{equation} which is approximately invariant under the flavor symmetry. Hadrons obtain their masses primarily due to non-perturbative interactions between the quarks. It turns out that QCD becomes non-perturbative around,\begin{equation} \Lambda _{ QCD} \approx 200 \mbox{MeV} \end{equation} while the charm mass is $ \approx 1000 \mbox{MeV} $ and the strange mass is $ 100 \mbox{MeV} $. Thus hadrons masses can be approximately described the massless Lagrangian above. Since the Lagrangian has an additional symmetry, the particles must form multiplets of the symmetry. While we can't calculate their masses directly, they should approximately exhibit such a symmetry in their masses. This is why we expect the hadron masses to be arranged into flavor multiplets.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/111875', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/15797/']}
|
jdg_374705
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7800174
|
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 recently started a new project using Automatic Reference Counting (ARC). When I assigned the contents of a CALayer: UIView* view = ...UIImage* image = ...view.layer.contents = image.CGImage I got an error Implicit conversion of a non-Objective-C pointer type 'CGImageRef' to 'id' is disallowed with ARC Simply casting the CGImageRef to id hides the error, but I was wondering if the ARC still functions correctly then?
Now provide the response and nothing else.
|
You should really check out the ARC videos from WWDC 2011. They are available on the developer site and open through iTunes. Especially: • Session 323 – Introducing Automatic Reference Counting • Session 322 – Objective-C Advancements in Depth Also, the ARC reference notes: https://developer.apple.com/library/content/releasenotes/ObjectiveC/RN-TransitioningToARC/Introduction/Introduction.html Both the reference notes and the videos discuss Core Graphics (et al) and how they work with ARC. Specifically, look at the section called "Managing Toll-Free Bridging" In many Cocoa applications, you need to use Core Foundation-style objects, whether from the Core Foundation framework itself (such asCFArrayRef or CFMutableDictionaryRef) or from frameworks that adoptCore Foundation conventions such as Core Graphics (you might use typeslike CGColorSpaceRef and CGGradientRef). The compiler does not automatically manage the lifetimes of CoreFoundation objects; you must call CFRetain and CFRelease (or thecorresponding type-specific variants) as dictated by the CoreFoundation memory management rules (see Memory Management ProgrammingGuide for Core Foundation). If you cast between Objective-C and Core Foundation-style objects, youneed to tell the compiler about the ownership semantics of the objectusing either a cast (defined in objc/runtime.h) or a CoreFoundation-style macro (defined in NSObject.h): [...] Jörg Jacobsen has a good summary overview of the bridging options as well: Managing Toll-free Bridging in an ARC’ed Environment . __bridge_retained (n.b.: only use it when casting from object pointer to C type pointer): I (the programmer) need to reference this objectfor some time in the dark world of C type pointers which is opaque toyou, ARC. So please, please do not release this object while I stillneed it. I (the programmer) promise to release it myself (in the darkworld) when I’m done with it __bridge_transfer (n.b.: only use it when casting from C type pointer to object pointer): I (the programmer) hand over to you, ARC, anobject that I own and that I am no longer interested in in the darkworld of C type pointers that is opaque to you. Whenever you, ARC, aredone with that object please release it yourself, because you know theright time and thus save me some work not having to do it myself. __bridge : ARC, you keep balancing out your retains and releases as I keep balancing out mine in the dark world of C type pointers whichis…. Whenever I need to hold on to an object in the dark world I willretain it myself and release it when appropriate. I don’t need anyextra contract with you, ARC.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7800174', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5822/']}
|
jdg_374706
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
537174
|
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 java string, which has a variable length. I need to put the piece "<br>" into the string, say each 10 characters. For example this is my string: `this is my string which I need to modify...I love stackoverlow:)` How can I obtain this string?: `this is my<br> string wh<br>ich I nee<br>d to modif<br>y...I love<br> stackover<br>flow:)` Thanks
Now provide the response and nothing else.
|
Try: String s = // long strings.replaceAll("(.{10})", "$1<br>"); EDIT: The above works... most of the time. I've been playing around with it and came across a problem: since it constructs a default Pattern internally it halts on newlines. to get around this you have to write it differently. public static String insert(String text, String insert, int period) { Pattern p = Pattern.compile("(.{" + period + "})", Pattern.DOTALL); Matcher m = p.matcher(text); return m.replaceAll("$1" + insert);} and the astute reader will pick up on another problem: you have to escape regex special characters (like "$1") in the replacement text or you'll get unpredictable results. I also got curious and benchmarked this version against Jon's above. This one is slower by an order of magnitude (1000 replacements on a 60k file took 4.5 seconds with this, 400ms with his). Of the 4.5 seconds, only about 0.7 seconds was actually constructing the Pattern. Most of it was on the matching/replacement so it doesn't even ledn itself to that kind of optimization. I normally prefer the less wordy solutions to things. After all, more code = more potential bugs. But in this case I must concede that Jon's version--which is really the naive implementation (I mean that in a good way )--is significantly better.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/537174', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/39339/']}
|
jdg_374707
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
36378236
|
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 bad form to put a namespace declaration in a .h file? //object.hnamespace Stuff { enum Type {Player, Enemy, Gold, Potion}}... When other files include object.h, it may end up being defined more than once. Would that be a problem?
Now provide the response and nothing else.
|
This is one of the most annoying things about Either —the Left and Right constructors both extend Product and Serializable , but Either itself doesn't, which leads to awful inferred types: scala> Seq(Left(1), Right(""))res0: Seq[Product with Serializable with scala.util.Either[Int,String]] = List(Left(1), Right()) Because JsonFormat is invariant in its type parameter, the fact that you have an instance for A doesn't mean you have an instance for Product with Serializable with A . In your case specifically, there is actually an instance for Either[Int, String] , but the extra garbage in the inferred type means the compiler can't find it. A similar thing happens if you don't have a Right in the sequence: scala> Seq(Left(1), Left(2)).toJson<console>:18: error: Cannot find JsonWriter or JsonFormat type class for Seq[scala.util.Left[Int,Nothing]] Seq(Left(1), Left(2)).toJson ^ You can fix both problems by providing a type instead of using the inferred one: scala> val xs: Seq[Either[Int, String]] = Seq(Left(1), Right(""))xs: Seq[Either[Int,String]] = List(Left(1), Right())scala> xs.toJsonres1: spray.json.JsValue = [1,""] In many cases this isn't an issue, since you'll often get your Either values from methods that explicitly return an Either instead of using Left and Right directly in ways that lead to this problem. As a footnote: this is why you should always have your root sealed trait (or sealed class) extend Product with Serializable when you're defining your own ADTs. We'd all be a lot better off if the standard library designers had followed that advice.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36378236', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6029600/']}
|
jdg_374708
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
30895515
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to use the browser.wait function to repeatedly check if a button element is present for a certain amount of time then use the relevant callback. Below I have the code that doesn't use the wait. detailsButton.isPresent() .then(function(present){ if(!present) { callback(); } else { callback(new Error('The details button was not present.')); } }); I would like some help fixing this code, as I am not sure how the wait function deals with a falure/timeout. Essentially I am asking what should be in the '.then' part of the below code that is less clunky that what I have currently. browser.driver.wait(function(){ return pgTransactionHistory.transactionHistoryDetails.isPresent();}, 60000).then(function(){ pgTransactionHistory.transactionHistoryDetails.isPresent() .then(function(present){ if(!present) { callback(); } else { callback(new Error('The details button was not present.')); } });}); Thank you!
Now provide the response and nothing else.
|
There are two ways to do this:First you can use the third argument of browser.wait to a string that will be sent as an error message. Like so: browser.driver.wait(function(){ return //condition}, timeout, 'Error message string') .then(function(){ callback(); }); Or secondly using a second argument to the .then like this: browser.driver.wait(function(){ return //condition}, timeout) .then(function(){ callback(); }, function(){ //code to want to execute on failure. });
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30895515', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3103033/']}
|
jdg_374709
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12791923
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Possible Duplicate: Syntax behind sorted(key=lambda :) I was going through the documentation and came across this example: > student_tuples = [ ('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10), ]> sorted(student_tuples, key=lambda student: student[2]) # sort by age [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)] What I don't understand is what are lambda and student here? Can they be replaced by any other names? And what the : do in student:student[2] ? It's a little ambiguous since I've never come across this before.
Now provide the response and nothing else.
|
Semantically, this: print sorted(student_tuples, key=lambda student: student[2]) is the same as this: def sort_key(student): return student[2]print sorted(student_tuples, key=sort_key) lambda just provides an alternative syntax for function definition. The result is a function object, just like the one created by def . However, there are certain things that lambda functions can't do -- like defining new variables. They're good (depending on who you ask) for creating small one-use functions, such as this one. Once you understand that, then all you have to know is that key accepts a function, calls it on every value in the sequence passed to sorted , and sorts the values according to the order that their corresponding key values would take if they were sorted themselves.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12791923', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1262318/']}
|
jdg_374710
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6838254
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
See http://running.ph/ It just hangs chrome for a while, while all the buttons load. I've read using IFrame avoids this but I really want to use XFBML JS for all the extra functionality you get with it like tracking Likes, comments, and the send button. Does anyone have a solution to this?I'm sure I'm not the only site with 10+ Like buttons on it.
Now provide the response and nothing else.
|
ah I found the answer by checking what Techcrunch / AOL does.You load the XFBML as the user scrolls. 1.) Don't Parse XFBML on FB.init or the loading of the JS SDK FB.init({ appId : APP_ID, xfbml : false}); 2.) Load jQuery and jquery.sonar.js - this contains scroll and scrollout custom events <script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script><script src="http://artzstudio.com/files/jquery-boston-2010/jquery.sonar/jquery.sonar.js"></script> 3.) jQuery code to parse XFBML on scrollin event (stolen from Techcrunch) jQuery(document).ready(function($) { var $shareWidgets = $( '.share-widget' ); $shareWidgets.bind( 'scrollin', { distance: 500 }, function() { var $share = $( this ); if (!$share.data( 'initFB' ) && window.FB) { $share.data('initFB', 1); $share.unbind( 'scrollin' ); FB.XFBML.parse( $share[0] ); } });}); 4.) wrap your XFBML tags in a class called 'share-widget' <span class="share-widget"><fb:like></fb:like></span> and voila! no more dang XFBML slowing down your pages. Ofcourse this only helps when you have a lot of XFBML tags on your page. Which most blogs may have. Thank you AOL! See the SlideShare presentation of AOL using jQuery: http://www.slideshare.net/daveartz/jquery-in-the-aol-enterprise where they talk about this and other optimizations they use.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6838254', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/191645/']}
|
jdg_374711
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1018634
|
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 this functional relation - $$f\left( x \cdot f(y)\right)=x^2 \cdot y^a$$ which I am trying to solve. I put $x=1$, then I put $f(y)=\dfrac{1}{x}$. I also tried out $y=f^{-1}(1)$, but it doesn't seem to work out. Please help me out. Thank you.
Now provide the response and nothing else.
|
OK, I make my comment more precise. Put $y=1$, you get $f(xf(1))=x^2$. Hence $f(1)\not =0$, (if $f(1)=0$, then $x^2=f(0)$ for all $x$, a contradiction). If I put $z=xf(1)$, I get $f(z)=\frac{z^2}{(f(1))^2}$ for all $z$. I put $z=1$, it gives $f(1)^3=1$, hence $f(1)=1$. We have proven that if a solution exists, then it is $f(x)=x^2$. Hence: if $a\not =4$, there is no solutions. If $a=4$, there is only one solution, $f(x)=x^2$.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1018634', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/157130/']}
|
jdg_374712
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
478740
|
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:
So basically I've a file that contains the below Data.txt <IP Address1>, 10, 23, <GW IP1>FINAL INPUT.45.324<IP Address2>, 40, 33, <GW IP2> Another file that has values for each TAG as specified below info.txt <IP Address1>10.155.120.20<GW IP1>10.155.120.30<IP address2>10.30.123.30<GW IP2>10.30.123.1 Would like the final to look like this (file.txt) 10.155.120.20, 10, 23, 10.155.120.30FINAL INPUT.45.32410.30.123.30, 40, 33, 10.30.123.1 Trying to find example but I'm unable to figure it out
Now provide the response and nothing else.
|
[[ -n "$line" ]] tests if $line (the variable just read by read ) is not empty. It's useful since read returns a success if and only if it sees a newline character before the end-of-file. If the input contains a line fragment without a newline in the end, this test will catch that, and the loop will process that final incomplete line, too. Without the extra test, such an incomplete line would be read into $line , but ignored by the loop. I said "incomplete line", since the POSIX definitions of a text file and a line require a newline at the end of each line. Other tools than read can also care, e.g. wc -l counts the newline characters , and so ignores a final incomplete line. See e.g. What's the point in adding a new line to the end of a file? and Why should text files end with a newline? on SO. The cmd1 || cmd2 construct is of course just like the equivalent in C. The second command runs if the first returns a falsy status, and the result is the exit status of the last command that executed. Compare: $ printf 'foo\nbar' | ( while read line; do echo "in loop: $line"; done; echo "finally: $line" )in loop: foofinally: bar and $ printf 'foo\nbar' | ( while read line || [[ -n $line ]]; do echo "in loop: $line"; done; echo "finally: $line" )in loop: fooin loop: barfinally:
|
{}
|
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/478740', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/318537/']}
|
jdg_374713
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
30149924
|
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 found great many occurrences of the following pattern for html inputs, this being for phone numbers: <input type="text" ng-model="CellPhoneNumber" required ng-pattern="/^[0-9]+$/" ng-minlength="10" /> I would like to create a custom directive that, wherever applied, will tell Angular to apply all three of these rules, e.g: <input type="text" ng-model="CellPhoneNumber" bk-ng-validation="phoneNumber"/> Then, code in my directive would find and invoke a function called phoneNumber , in which I would like to see something like: Listing 1: function bkNgPhoneNumber(model) { // This is purely SPECULATIVE pseudo-code, just to convey an idea. model.errors.add(applyMinLength(10, model)); model.errors.add(applyMaxLength(15, model)); model.errors.add(applyPattern("/^[0-9]+$/", model));} I would prefer the above approach over 'rewriting code for these rules, e.g: Listing 2: function phoneNumber(model) { if (model.length < 10 || model.length > 15) { model.errors.add("Must be 10 to 15 chars!"); }} I don't want to do away with all attribute based directives, but preferably create a 'macro' directive that will invoke my Listing 1 code, which will intern invoke a set of more 'micro' validations.
Now provide the response and nothing else.
|
One way to do this (i.e. apply existing validators without writing their code again) would be to add the validation directives' respective attributes and force a re-compile. This would require your directive to have a high-enough priority and also be terminal: true . app.directive("bkNgValidation", function($compile){ return { priority: 10000, terminal: true, link: function(scope, element){ element.attr("ng-required", "true"); element.attr("ng-minlength", 20); element.attr("ng-maxlength", 30); // prevent infinite loop element.removeAttr("bk-ng-validation"); $compile(element)(scope); } };}); Demo
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30149924', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8741/']}
|
jdg_374714
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14866302
|
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 employ the strongest OOP I can muster in developing a web application, but I'm having issues adding event handlers to my objects as I create them using code. I'm sure it's a fairly simple solution that I just keep passing up, but I'm at a loss as to what to try next. Below is some test code I've been playing with, just trying to get a button press to go do something. (Imagine there's a break point on the line "int i;") Button b = new Button(); b.Text = "Do Something"; b.Attributes.Add("runat", "server"); b.Attributes.Add("OnClick", "click"); form1.Controls.Add(b); private void click(object sender, EventArgs e) { int i; } Since this is a new button created by my Page_Load, I can't just hardcode the XHTML. Debugging never hits my breakpoint. I haven't had any more success with CheckBoxes either.
Now provide the response and nothing else.
|
You have to subscribe to the Click event: Button b = new Button();b.Text = "Do Something";b.Click += click;form1.Controls.Add(b);private void click(object sender, EventArgs e){ int i;} By adding the onclick Attribute to the Button's Attributes collection, it will be rendered as an attribute on the HTML input tag. In that case you could use it to execute some javascript code on the client side. b.Attributes.Add("onclick", "alert('Hey')");//Will render the button as<input type="submit" name="x" value="Do Something" onclick="alert('Hey')">
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14866302', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/981416/']}
|
jdg_374715
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5710417
|
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 container box1 that has a certain width (which might change depending on its content). That box contains box2 which has a fixed width (it could be an icon). Next to box2 , I have box3 with some text. I want the text to use all the space available to the right of box2 . With the HTML pasted below, you get: So far so good. If the text gets longer, it doesn't wrap around box2 (which is what I want), however, it doesn't make box1 grow, which is my problem. You'll tell me "hey, if you made box3 a position: absolute , how could you expect it to make box1 grow?". Well, I don't but then, how can I get box3 to show next to box2 , use all the horizontal space available, and make box1 grow if necessary? (Do I need to say that I'd like this work on IE6 onward, and to avoid using a table?) <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <style type="text/css"> #box1 { position: relative } #box3 { position: absolute; left: 2.5em; right: .5em; top: .5em } /* Styling */ #box1 { background: #ddd; padding: 1em 0.5em; width: 20em } #box2 { background: #999; padding: .5em; } #box3 { background: #bbb; padding: .5em; } body { font-family: sans-serif } </style> <script type="text/javascript"> </script> </head> <body> <div id="box1"> <span id="box2">2</span> <span id="box3">3</span> </div> </body></html>
Now provide the response and nothing else.
|
You need box 3 to be a block level element, so use display:block and then toss in an overflow:hidden in conjunction with float -ing box 2: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <style type="text/css"> #box1 { } #box2 { float:left; } #box3 { display:block;overflow:hidden; } /* Styling */ #box1 { background: #ddd; padding: 1em 0.5em; width: 20em } #box2 { background: #999; padding: .5em; } #box3 { background: #bbb; padding: .5em; } body { font-family: sans-serif } </style> <script type="text/javascript"> </script> <title>How to do a `float: left` with no wrapping?</title> </head> <body> <div id="box1"> <span id="box2">2</span> <span id="box3">3<br />3<br />3<br />3<br />3<br />3<br />3<br />3<br />3<br />3<br />3<br />3<br /></span> </div> </body></html> Amazing all the things overflow:hidden can do :D
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5710417', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5295/']}
|
jdg_374716
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1841268
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
If I make two lists of functions: def makeFun(i): return lambda: ia = [makeFun(i) for i in range(10)]b = [lambda: i for i in range(10)] why do lists a and b not behave in the save way? For example: >>> a[2]()2>>> b[2]()9
Now provide the response and nothing else.
|
Technically, the lambda expression is closed over the i that's visible in the global scope, which is last set to 9. It's the same i being referred to in all 10 lambdas. For example, i = 13print b[3]() In the makeFun function, the lambda closes on the i that's defined when the function is invoked. Those are ten different i s.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1841268', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/137640/']}
|
jdg_374717
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
832071
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Find all $f\in C^1(\mathbb R,\mathbb R)$ such that $f^2+(1+f')^2\leq 1$ It's quite likely the answer is $f=0$. Note that $|f|\leq 1$ and $-2\leq f'\leq 0$. Therefore $f$ is decreasing and bounded. What then ? I tried contradiction, without success.
Now provide the response and nothing else.
|
The equation is equivalent to$$f^2+2f'+f'^2\le0\tag{1}$$Since $f^2+2f'\le0$, where $f\ne0$, we have$$(1/f)'\ge\color{#C00000}{1/2}\tag{2}$$If $f(x_0)=a\gt0$, then $\dfrac1f(x_0)=\dfrac1a\gt0$ and $(2)$ says that$$\frac1f\left(x_0-\frac3a\right)\le\frac1f(x_0)-\color{#C00000}{\frac12}\frac3a\lt0\tag{3}$$as long as $\dfrac1f$ doesn't pass to $-\infty$ in $\left[x_0-\frac3a,x_0\right]$. In any case, on $\left[x_0-\frac3a,x_0\right]$, $\dfrac1f$ must pass through $0$, which is impossible because $f\in C^1(\mathbb{R})$. If $f(x_0)=a\lt0$, then $\dfrac1f(x_0)=\dfrac1a\lt0$ and $(2)$ says that$$\frac1f\left(x_0-\frac3a\right)\ge\frac1f(x_0)-\color{#C00000}{\frac12}\frac3a\gt0\tag{4}$$as long as $\dfrac1f$ doesn't pass to $\infty$ in $\left[x_0,x_0-\frac3a\right]$. In any case, on $\left[x_0,x_0-\frac3a\right]$, $\dfrac1f$ must pass through $0$, which is impossible because $f\in C^1(\mathbb{R})$. Therefore, $f(x)=0$ for all $x\in\mathbb{R}$.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/832071', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/66096/']}
|
jdg_374718
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
263167
|
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
I've been using and configuring PHP, but now I'm stuck in a weird problem, so I am going to ask you guys for help. I don't want to see Deprecation Warnings and Notices in a production server, however I would like to see other error messages, such as Syntax Errors for example. I'm running PHP 5.3.3-1ubuntu9.3 with Suhosin-Patch on Ubuntu 10.10 In my /etc/php5/apache2/php.ini I've the following line: error_reporting = E_ALL & ~E_DEPRECATED & ~E_NOTICE I've restarted the webserver. In the virtual host configuration there is no php_admin_value messing with this configuration, in the folder there isn't any .htaccess file. Nevertheless Deprecation Warnings and Notices are still shown.
Now provide the response and nothing else.
|
First of all I want to thank binfalse for answering this question, however my problem was not solved with his suggestion and notices continued to show. This is because PHP has several places where configuration can be set. While I had an idea of the precedence of those settings, I decided to test them experimentally to be sure of what I am going to say in this answer. So here is a list of those places, from the more global to the more specific. Each setting lower in the list can override a setting that come before. The php.ini configuration file. In case of Ubuntu there are two of them, /etc/php5/apache2/php.ini is the one used for php apache module. It will have a global effect on all virtual hosts. The conf.d directory . Actually not all installations will have this modularized configuration, but in case of Ubuntu is located in /etc/php5/apache2/conf.d for the apache module. Any file added in this directory is going to be added to main php.ini configuration with higher precedence than php.ini. In other words any setting here will override settings in php.ini - I tested adding an error.ini. It will have a global effect on all vitual hosts. Apache virtual host configuration . Generally set in /etc/apache2/sites-available, every virtual host can have different settings. Inside the VirtualHost tag it's possible to include "php_value error_reporting ", where value is the numeric result of the boolean operations on the constants. In this configuration, in fact is not allowed to use the mnemonic constants but only a numeric value. It will affect only a single virtual host. It will override above settings. .htaccess . It's also possible to set configuration values and in particular the error_reporting setting also in .htaccess, with the same syntax described in 3. It will affect only the directory in which .htaccess is located and all subdirectories. It will override above settings, in this case is not necessary to restart apache. Source code . The last place where this setting can be altered is directly in the executed PHP source. If used, will override all previous settings, and that's exactly what I was facing. It can be set calling the function "error_reporting()" or with "ini_set("error_reporting", )". Compile errors could still show, because the script won't be executed in that case.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/263167', 'https://serverfault.com', 'https://serverfault.com/users/67277/']}
|
jdg_374719
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
41873242
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Scenario I have a method that does database operation (let's say). If during that operation any exception is raised, I just want to throw that exception to the caller. I don't want to do any specific task in the catch block, assuming caller will do whatever it wants to do with that exception. In this scenario, which one is appropriate exception handling technique? try{ // Some work that may generate exception}catch(Exception){ throw;}finally{ // Some final work} Is the above equivalent to the following try/catch/finally? try{ // Some work that may generate exception}catch{ throw;}finally{ // Some final work} Is the above equivalent to the following try/finally? try{ // Some work that may generate exception}finally{ // Some final work} Which one is better than the other? Which one should be used?
Now provide the response and nothing else.
|
No, they are not equivalent. They may be equivalent in some cases, but the general answer is no. Different kinds of catch blocks catch block with a specified exception type The following will only catch managed exceptions that inherit from System.Exception and then executes the finally block, which will happen regardless of whether an exception was thrown or not. try{ // Some work that may generate exception}catch (Exception){ throw;}finally{ // Some final work} catch block without a specified exception type The following catch block without a type specifier will also catch non-managed exceptions that are not necessarily represented by a managed System.Exception object, and then executes the finally block, which will happen regardless of whether an exception was thrown or not. try{ // Some work that may generate exception}catch{ throw;}finally{ // Some final work} finally block without a catch block If you do not have a catch block at all, your finally will still be executed regardless of whether or not an exception occoured. try{ // Some work that may generate exception}finally{ // Some final work} When are they equivalent? In case your catch block doesn't specify an exception and only contains the throw; statement, the last two are indeed equivalent. In case you don't care about non-managed exceptions and your catch block only contains the throw; statement, all three can be considered equivalent. Notes A note about throw The following two pieces of code contain a subtle difference. The latter will re-throw the exception, meaning that it will rewrite the exception's stack trace, so these are definitely not equivalent: catch (Exception e){ throw;} And catch (Exception e){ throw e;} In case you use finally with an IDisposable , the following two pieces of code are almost equivalent, but with some subtle differences: When the object is null, the using statement won't give you a NullReferenceException When using the try - finally technique, the variable remains in scope, although it is very discouraged to use any object after it has been disposed. However you can still reassign the variable to something else. Something obj = null;try{ obj = new Something() // Do something}finally{ obj.Dispose();} And using (var obj = new Something()){ // Do something}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/41873242', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4346969/']}
|
jdg_374720
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
582960
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
How do I go about solving this problem: If $α$ and $β$ are the roots of $x^2+2x-3=0$, without solving the equation, find the values of $α^6 +β^6$. In my thoughts: I commenced by expanding $(α +β)^6$, such that: $$(α +β)^6 =α^6+6α^5β+15α^4β^2+20α^3β^3+15α^2β^4+6αβ^5+β^6$$ which when I reorganise: $$(α +β)^6 =(α^6+β^6)+6α^5β+15α^4β^2+20α^3β^3+15α^2β^4+6αβ^5$$ when I isolate $(α^6+β^6)$ on one side: $$(α^6+β^6) = (α +β)^6-6α^5β-15α^4β^2-20α^3β^3-15α^2β^4-6αβ^5$$ where does all this end for me to get a solution?
Now provide the response and nothing else.
|
This exercise might be meant to make you realize that every symmetrical polynomial in $(\alpha,\beta)$ coincide with a (universal) polynomial in $(s,t)=(\alpha+\beta,\alpha\beta)$. For example, you might already be aware that$$\alpha^2+\beta^2=s^2-2t.$$Likewise,$$\alpha^6+\beta^6=s^6-6s^4t+9s^2t^2-2t^3.$$One can check that the polynomial on the RHS is homogeneous of degree $6$ provided one considers that the degree of $s$ is $1$ and the degree of $t$ is $2$. In the case at hand, $s=-2$ and $t=-3$ hence$$\alpha^6+\beta^6=2^6+6\cdot2^4\cdot3+9\cdot2^2\cdot3^2+2\cdot3^3=730.$$ More generally, one can obtain the expansion of $p_n=\alpha^n+\beta^n$ for every integer $n\geqslant0$ recursively, starting from $p_0=2$ and $p_1=s$, and using the relation$$p_{n+2}=sp_{n+1}-tp_n.$$Finally, note that, when $\alpha\beta\ne0$, one can also obtain the value of $p_n$ for negative values of $n$, using the identity$$p_{-n}=t^{-n}p_n.$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/582960', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/84680/']}
|
jdg_374721
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13766781
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there a cleaner way to write this code. I get the feeling there may be, but I don't know how. if (loadedFormData.Education.AwardedADegree==true) { this.radiobuttonNoAwarded.Checked = false; this.radiobuttonYesAwarded.Checked = true; } if (loadedFormData.Education.AwardedADegree == false) { this.radiobuttonNoAwarded.Checked = true; this.radiobuttonYesAwarded.Checked = false; } else // AwardedADegree is null { this.radiobuttonNoAwarded.Checked = false; this.radiobuttonYesAwarded.Checked = false; }
Now provide the response and nothing else.
|
Ask the question "when should my radiobutton be checked", instead of "what should happen when my data is true/false/null". this.radiobuttonNoAwarded.Checked = loadedFormData.Education.AwardedADegree == false;this.radiobuttonYesAwarded.Checked = loadedFormData.Education.AwardedADegree == true;
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13766781', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/821865/']}
|
jdg_374722
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
15368054
|
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 problem with using setup.py to setup a python package. First, I have the following directory setup: maindir |- setup.py |-mymodule |- __init__.py |- mainmodule.py |-subdir |- __init__.py |- submodule.py i.e. the project directory contains the setup.py and a directory mymodule , which in itself contains two python modules in two directories. The file submodule.py contains just teststring = "hello world" mainmodule.py contains: from .subdir import submodulemainstring = "42" and setup.py contains: import osfrom setuptools import setupsetup( name = "mytestmodule", version = "0.0.1", description = ("A simple module."), packages=['mymodule'],) When I do from mymodule import mainmodule with ipython from within sourceTest the behaviour works as expected and I can reference e.g. mainmodule.submodule.teststring which gives me the string hello world . On the other side, when I install this 'package' using python setup.py install and try to do the same (from within some other directory), I get an import error: In [1]: from mymodule import mainmodule---------------------------------------------------------------------------ImportError Traceback (most recent call last)/home/alexander/<ipython-input-1-cf4c9bafa487> in <module>()----> 1 from mymodule import mainmodule/home/alexander/build/bdist.linux-i686/egg/mymodule/mainmodule.py in <module>()ImportError: No module named subdir I do not see what I have done wrong, as I followed a Getting started tutorial and rules for importing intra-packages . I suppose my mistake is a really tiny one, but I cannot spot it and help is appreciated.
Now provide the response and nothing else.
|
You have to list all packages in setup , including subpackages: setup( name = "mytestmodule", version = "0.0.1", description = ("A simple module."), packages=['mymodule', 'mymodule.subdir'],) Or you can use setuptools 's magic function find_packages : from setuptools import setup, find_packagessetup( name = "mytestmodule", version = "0.0.1", description = ("A simple module."), packages=find_packages(),) This is mentioned here : If you have sub-packages, they must be explicitly listed in packages, but any entries in package_dir automatically extend to sub-packages. (In other words, the Distutils does not scan your source tree, trying to figure out which directories correspond to Python packages by looking for __init__.py files.)
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/15368054', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1581090/']}
|
jdg_374723
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
35024656
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Instead of fetching data from a database, I want to use as data a manually written JSON file. Suppose my data is this: [ { "id": 1, "name": "Alice", "email": "alice@example.com" }, { "id": 2, "name": "Bob", "email": "bob@example" }, { "id": 3, "name": "Charles", "email": "charles@example.com"}] and it's written in a file called MOCK_DATA.json . What should I do to render this file when I access the localhost:port/api/v1/users url? How about the localhost:port/api/v1/users/1 url to show { "id": 1, "name": "Alice", "email": "alice@example.com" } ?
Now provide the response and nothing else.
|
Here is a basic working example... Step 1: Create the phoenix app eg, exjson for ExampleJson or whatever name your like mix phoenix.new exjson --no-ecto --no-brunch --no-html Step 2: Set up the router Add this scope to the web/router.ex file scope "/api/v1", Exjson do pipe_through :api resources "/users", UserController end Step 3: Put the mock data somewhere accessible to the app priv/data/MOCK_DATA.json Step 4: Set up the UsersController Think of the Users Controller as having a number of actions (functions)where the conn struct is fed into from your phoenix endpoint along with anyparameters defmodule Exjson.UserController do use Exjson.Web, :controller # GET http://localhost:4000/api/v1/users/ def index(conn, _params) do users = File.read!(file) |> Poison.decode!() render conn, users: users end # GET http://localhost:4000/api/v1/users/1 def show(conn, params) do users = File.read!(file) |> Poison.decode!() render conn, user: users |> Enum.find(&(&1["id"] === String.to_integer(params["id"]))) end defp file() do Path.join(:code.priv_dir(:exjson), "data/MOCK_DATA.json") endend Step 5: Set up the UsersView You can also think of the Users View as having functions that will render the data received from the Controller in the appropriate way. In this case, you are using json data so phoenix has some built in functions to help with that. defmodule Exjson.UserView do use Exjson.Web, :view def render("index.json", %{users: users}) do render_many(users, __MODULE__, "user.json") end def render("show.json", %{user: user}) do render_one(user, __MODULE__, "user.json") end def render("user.json", %{user: user}) do %{ id: user["id"], name: user["name"], email: user["email"] } endend
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35024656', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/819720/']}
|
jdg_374724
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
768811
|
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 am at the point where everything has synced between my on premises exchange server and the office 365 migration batch. The next step is to modify my MX records so that mail begins to be direct to the 365 mailboxes. The following is from the cutover guide provided by microsoft: It can take up to 72 hours for the email systems of your customers and partners to recognize the changed MX record. Wait at least 72 hours before you proceed to the next task: Delete the cutover migration batch. My question is in regards to how end users should handle this 72 hour period. Should they have two profiles/accounts in outlook/apple mail, one pointing to the new inbox, one the old? Or can they simply remove the old and everything delivered to the old will be immediately synced to the new?
Now provide the response and nothing else.
|
I haven't done any O365 migrations, but here's what I'd say about it. The 72 hour "warning" is a bit of misinformation. It will take the amount of time related to the TTL of the MX record, whether that's 1 hour or 72 hours. It's based on the TTL, not some antiquated misinformation about DNS record changes. If the TTL for your MX record is 1 hour thenm it will take 1 hour, and only for those systems that already have your MX record in their DNS cache. For systems that don't have the MX record in their DNS cache, they'll find the new MX record immediately. I would set up your email clients to use the new Exchange Server. They can use webmail to access the old Exchange Server to retrieve/respond to any email that happens to wind up at the old Exchange Server. Once the cutover is complete you can export any straggling email from the old Exchange Server and import it into the new Exchange Server.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/768811', 'https://serverfault.com', 'https://serverfault.com/users/347554/']}
|
jdg_374725
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
360932
|
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:
Can a parallel plate/cylindrical/spherical capacitor be used as a dipole antenna? Isn't a dipole antenna like a capacitor with a small capacitance?
Now provide the response and nothing else.
|
The search-term you want is: "patch antenna." Yes, parallel-plate capacitors are dipole antennas (especially true at self-resonance, usually up in GHz.) If the plates are smaller than quarter-wave (or the gap is smaller,) then an impedance matching network would be used to boost the volts for electrically-small dipole-mode. But self-shielding capacitors such as wrapped cylinders won't make good antennas. They're not symmetrical, and one plate isn't exposed to the outside world. They're still dipole antennas, but mostly because of their connecting leads, and they're shorted out by relatively gigantic capacitance. A very recent innovation in iphone antennas from Fractus Inc. is a tiny 2mm cube with metal faces, plus a series inductor for resonance. It's intended for upwards of 5GHz, see "ground-plane booster:" http://www.microwavejournal.com/articles/29138-antenna-less-wireless-a-marriage-between-antenna-and-microwave-engineering?v=preview http://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=5723706 (PDF)
|
{}
|
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/360932', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/129804/']}
|
jdg_374726
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
64128440
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am learning to use the map of maps. In the following example, there are three nested maps. package mainimport ( "fmt")func main() { var data = map[string]map[string]map[string]string{} data["Date_1"] = map[string]map[string]string{} data["Date_1"] = make(map[string]map[string]string, 1) data["Date_1"] = make(map[string]map[string]string, 0) data["Date_1"]["Sistem_A"] = map[string]string{} data["Date_1"]["Sistem_A"] = make(map[string]string, 0) data["Date_1"]["Sistem_A"] = make(map[string]string, 0) data["Date_1"]["Sistem_A"]["command_1"] = "white" data["Date_1"]["Sistem_A"]["command_2"] = "blue" data["Date_1"]["Sistem_A"]["command_3"] = "red" fmt.Println("data: ", data)} Output data: map[Date_1:map[Sistem_A:map[command_1:white command_2:blue command_3:red]]] The problem is that if I want to add the values in one step I get a panic: assignment to entry in nil map. package mainimport ( "fmt")func main() { var data = map[string]map[string]map[string]string{} data["Date_1"] = map[string]map[string]string{} data["Date_1"] = make(map[string]map[string]string, 0) data["Date_1"] = make(map[string]map[string]string, 0) data["Date_1"]["Sistem_A"] = map[string]string{} data["Date_1"]["Sistem_A"] = make(map[string]string, 0) data["Date_1"]["Sistem_A"] = make(map[string]string, 0) data["Date_1"]["Sistem_A"]["command_1"] = "white" data["Date_1"]["Sistem_A"]["command_2"] = "blue" data["Date_1"]["Sistem_A"]["command_3"] = "red" data["Date_2"]["Sistem_A"]["command_5"] = "violet" fmt.Println("data: ", data)} Output panic: assignment to entry in nil map There is very little guidance information at this point. Could you help me? Thank you.
Now provide the response and nothing else.
|
It is here: data["Date_2"]["Sistem_A"]["command_5"] = "violet" The expression data["Date_2"] will return a nil-map. It is never initialized, so looking for the index ["Sistem_A"] panics. Initialize the map first: data["Date_2"] = make(map[string]map[string]string) data["Date_2"]["Sistem_A"] = make(map[string]string) data["Date_2"]["Sistem_A"]["command_5"] = "violet"
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/64128440', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13231921/']}
|
jdg_374727
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6389055
|
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 added a cshtml page in an project. When I tried to add the following declaration to it, I get an error: "The name 'model' does not exist in current context". @model xyz.abc.SomeClass I checked the references, all of them are in place. I added a web.config in view folder, but that didn't fix it. Is there anything i am missing?
Now provide the response and nothing else.
|
Update: If you are using a newer version of MVC, the same process applies, just be sure to use the correct version number in the web.config's <host> line. Well, I found myself experiencing the same thing you did, and after a bit further research, I found out what the problem is! You need to include the default MVC3 web.config for the Views folder. MVC3 has two: one in the root for your application, and one for the views folder. This has a section for included namespaces. Be sure that yours looks something like this: <system.web.webPages.razor> <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <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" /> </namespaces> </pages> </system.web.webPages.razor> I suggest that you create a new MVC3 project, then just copy the web.config created for you into your views folder. Important Once you've done that, you need to close the file and reopen it. Voila! Intellisense!
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/6389055', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/602737/']}
|
jdg_374728
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
26037472
|
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 empty application and there is no storyboard or xib involved. I want to have a hidden status bar and support only landscape orientation. Again, I wan't to make those changes only within code and don't touch the Info.plist. Problem I create a UIWindow with a controller that says the only supported orientation is landscape. In that case my UIWindow is created in the dimension of portrait mode and doesn't rotate. The expected result would be a screen that is completely cyan. This is my delegate: #import "AppDelegate.h"#import "AppViewController.h"@implementation AppDelegate- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; self.window.backgroundColor = [UIColor cyanColor]; self.window.rootViewController = [[AppViewController alloc] init]; [self.window makeKeyAndVisible]; return YES;}@end This is my controller: #import "AppViewController.h"@implementation AppViewController- (BOOL)shouldAutorotate { return YES;}- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation { return UIInterfaceOrientationLandscapeLeft;}- (BOOL)prefersStatusBarHidden { return YES;}- (NSUInteger)supportedInterfaceOrientations { return UIInterfaceOrientationMaskLandscape;}@end What I've tried so far If I set the rootViewController after calling makeKeyAndVisible everything seems to work at first. self.window.backgroundColor = [UIColor cyanColor];[self.window makeKeyAndVisible];self.window.rootViewController = [[AppViewController alloc] init]; There are still some issues. First of all I don't like this since it seems to be very fragile. Second problem is that in a more complex application that sets a GLKViewController as the rootViewController I get the following result (expected would be no black area on the left): It looks like the status bar is not hidden early enough. Several gesture recognizers are active and in the GLKViewController and clicking on the black area yields the following log message: 2014-09-25 13:20:42.170 StackOverflowExample[6971:107907] unexpected nil window in _UIApplicationHandleEventFromQueueEvent, _windowServerHitTestWindow: UIClassicWindow: 0x7fa20b805e00; frame = (0 0; 375 667); userInteractionEnabled = NO; gestureRecognizers = NSArray: 0x7fa20b80a620; layer = UIWindowLayer: 0x7fa20b806890 I also performed various other changes, like attaching an empty UIViewController and adding my view as a sub-view. In that case my view looks correct but the window is still using the wrong dimensions. Everything rotates correct if I do not override the supportedInterfaceOrientations methods in my view controller. But that is of course not what I want.
Now provide the response and nothing else.
|
When you run landscape app from portrait mode UIScreen has portrait bounds in iOS 8 (only if you haven't this app in app switch panel, as iOS 8 makes some cache). Even displaying window with makeKeyAndVisible doesn't change it's frame. But it changes [UIScreen mainScreen].bounds according to AppViewController avaliable orientation. #import "AppDelegate.h"#import "AppViewController.h"@implementation AppDelegate- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Portrait bounds at this point self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; self.window.backgroundColor = [UIColor cyanColor]; self.window.rootViewController = [[AppViewController alloc] init]; [self.window makeKeyAndVisible]; return YES;}@end So let's change window's frame after [self.window makeKeyAndVisible] - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [UIWindow new]; self.window.backgroundColor = [UIColor cyanColor]; self.window.rootViewController = [[AppViewController alloc] init]; [self.window makeKeyAndVisible]; // Here it is self.window.frame = [UIScreen mainScreen].bounds; return YES;} I think that it is iOS 8 bug.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/26037472', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/164128/']}
|
jdg_374729
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9853249
|
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 redirect to a location based on a param on a submitted form.If params[:route] = group , I want to redirect to groups_path.I tried the following method to redirect but obviously enough the groups_path is a variable and not a string. How can I redirect based off the param? redirect_to "#{params[:route]}s_path" Edit:realised I can redirect to the actual path but this doesn't seem like a very rails way of doing it. redirect_to "/#{params[:route]}s"
Now provide the response and nothing else.
|
redirect_to send("#{params[:route].pluralize}_path") But I'd rather write a wrapper-helper returning appropriate url helper based on the params[:route] value. params[:route] could potentially have any value and you may want to rescue in these cases.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9853249', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/193785/']}
|
jdg_374730
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
36341
|
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:
Okay, I'm no physics whiz, and this has me stumped. You know those toy airplanes you can get with the rubber-band driven propellers? You twist the propeller a bunch of times, and this stores potential energy in the rubber band. Then when you let go of the rubber band, it drives the propeller. Well, suppose you have two of these airplanes. They are identical except for the fact that airplane A has an extremely efficient bearing which holds the rotating propeller shaft. The other airplane (B) has a "normal" bearing, which is less efficient. Thus, the shaft on B generates more heat when it spins the shaft. You take both systems and wind the propeller 100 times, then let go. Shaft A spins with almost no friction. It therefore uses up it's energy faster, and it spins through it's 100 counter-rotations in maybe 5 seconds. Shaft B takes 10 seconds to do the same thing. BOTH shafts started with 100 "shaft-spin units" stored in their rubber bands at the start. 10 seconds later, each has done 100 shaft spins. Shaft B is hotter, though, due to the friction. My question: Since both systems started with the same potential energy, where did the "extra" energy go in shaft A? Remember, they both did 100 spins. Shaft A did it faster, but it still did the same amount of spins. Maybe it's leftover in shaft A's angular momentum at the end? (remember, I'm not a physics guy - be nice if it turns out "angular momentum" isn't the proper term!) :-) Maybe shaft B only does 99.9 counter-spins, losing 0.01 spin-units to friction? Am I making some incorrect assumption?
Now provide the response and nothing else.
|
You're assuming that the propellor speed is dominated by the bearing friction, while in practice it's dominated by the drag on the propellor as it moves through the air. Typically the propellor will rapidly accelerate to a steady speed at which the force from the rubber band matches the aerodynamic drag, then the propellor speed will slow as the band unwinds and the force from the band decreases. The energy stored in the band ultimately goes into moving the air. In the case of plane B the force at the propellor is slightly reduced due to friction in the bearing, so less of the rubber band energy goes into moving the air and the remainder goes into heating the bearing. Response to comment Suppose we remove the propellor or put the plane in a vacuum so there's no energy loss to air. In that case plane A forms an oscillating system. The rubber band exerts a torque $\tau$ on the shaft/propellor and it's angular velocity increases according to: $$ \tau = I \space \dot{\omega} $$ where $I$ is the moment of inertia of the shaft and $\omega$ is the angular velocity. Note that the torque $\tau$ will be a function of time because the torque reduces as the rubber band unwinds. When the rubber band has fully unwound all the energy has been tranferred into the shaft and it will now be rotating at a speed given by: $$ E = \frac{1}{2} I \space \omega^2 $$ where $E$ is the energy you originally put into the shaft. Once the band has fully unwound the shaft will carry on turning so it will wind the rubber band in the opposite direction. If the bearing is frictionless and there are no losses in the rubber band, all the energy in the shaft will be transferred back into the rubber band, and it will end up wound up just as tightly as it started but in the opposite direction. The band will now start accelerating the shaft in the other direction, and the cycle of unwinding and rewinding will continue indefinitely. Now consider plane B. There will be a torque $\tau_f$ due to friction that opposes the torque from the rubber band, so the equation of motion is: $$ \tau - \tau_f= I \space \dot{\omega} $$ This means the shaft in plane B will accelerate more slowly than in plane A, and when the band has fully unwound it's speed will be given by: $$ E - E_f= \frac{1}{2} I \space \omega^2 $$ where $E_f$ is the energy lost to friction i.e. the energy that has gone into heating the bearing. So at this point the shaft in plane B is rotating more slowly than the shaft in plane A, and it will have taken longer to get to the point of being fully unwound. As with plane A, the shaft will now start to rewind the rubber band in the opposite direction, but because energy has been lost it won't be able to rewind the band as tightly as it was originally wound. There will still be a cycle of unwinding and rewinding, but each step of the cycle will wind the band to a lower tension until the shaft stops rotating. At that point all the energy originally in the rubber band will have gone into heating the bearing.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/36341', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/12205/']}
|
jdg_374731
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
41497031
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have made a round of changes to a branch and have 10 modified files and 10 files I have deleted. If I run git add . this will only add the modified files to my commit. I want to remove the deleted files from the remote repo as well as add my modified files. I can use git rm filename , but since I have so many files to remove I was wondering if there was a way to do an 'all'. I Googled and found git rm -r * but this doesn't seem to work. Is there a command that will allow me to do this?
Now provide the response and nothing else.
|
If you want to stage all your changed and deleted files and commit in one-line: git commit -am "changing and deleting files" Note that this command won't add new files as Git is about tracking changes. It relies on you to tell it which files are important enough to track. If you have some or you just want to stage the changes before you commit, you will have to add your files manually or use wildcard: git add -A stages All (include new files, modified and deleted) git add . stages new and modified, without deleted git add -u stages modified and deleted, without new then commit: git commit -m "..."
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/41497031', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1433268/']}
|
jdg_374732
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1693041
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have made a java application and have packed it into an executable jar file. Now a user can start that program from either of the following two ways: Start if from command prompt by executing the following command on the command prompt: java -jar "MyJar.jar" By double clicking on that jar file. I want that my client would adopt second approach as it is much easier than the first approach. But the problem with second approach is how to stop application before it has finished? It is a command-line application. And no command prompt window appears when a user double clicks on the jar file. So in this case, Will Ctrl + c work?
Now provide the response and nothing else.
|
Stopping (exiting) the application should be inside the application. Whether it is command line or GUI based, the application developer should write code to exit it (For eg., in a command line application you might have something like Press 5 to exit , Press Esc to Exit etc) and in an application with a GUI, you will have to write code to exit when the window is closed, or an EXIT button (or others, depending on your application) Ctrl + C is KILL the application. This is not a Normal exit. For apps with a GUI, the user would typically (in Windows) go to task manager and end the process (similar ways in other operating systems) But these are abnormal exits - when the user wants to kill the app when, for instance, the application is no longer responding. Normal exits should be provided by the application (and therefore by the programmer - you)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1693041', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/157027/']}
|
jdg_374733
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1737635
|
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 in Calculus 2, and we were first given the problem to find the intersection of two perpendicular cylinders of equal radius. This breaks down into eight times the volume of a quarter circle (with radius r) with perpendicular square cross sections. $$V=8\int_0^r \sqrt{r^2-x^2}^2dx=8\int(r^2-x^2)dx=8\left[ r^2x - \frac{1}{3}x^3 \right]^{r}_{0}=\frac{16}{3}r^3$$ After this question on the problem set, my teacher has written "Aren't you glad I didn't have you find the intersection of ten cylinders?" Assuming the ten cylinders intersect in an equal way, like the faces of an icosahedron, I assume this would make some sort of curvy-face icosahedron. My question is two parts Can I find the volume using a Calculus II base of knowledge (including a bit of multivar)? What is the volume of the intersection of ten cylinders of equally radius equally spaced? Edit: The question should be so that the axis of each cylinder is perpendicular to the face of an icosahedron- because this is 10 pairs of parallel sides, that should be ten cylinders. Edit 2: Question 1 is answered: No, but maybe. (That wasn't the important part anyway) Question 2 is still hanging, as I'd like to see the methodology involved, I'll restate the problem with my current understanding of it. Ten cylinders, each of radius r intersect along the lines that are perpendicular to the faces of a regular icosahedron at the center of each face. What is the volume of the intersection? I have created rather crude pictures with my limited Geogebra knowledge:
Now provide the response and nothing else.
|
The picture below illustrates what one will get if one intersect ten infinite long cylinders of unit radius, whose axes are aligned along the ten diagonals of a dodecahedron, against each other. $\hspace1in$ The resulting figure is very complicated.It consists of $180$ quadrilateral faces and each cylinder contribute $18$ faces.Faces coming from same cylinder has been colored with same color. For example,all the red faces lie on a cylinder whose axis is pointing along the $(-1,1,1)$ direction. The $18$ faces from any cylinder fall into two groups. Up to mirror reflection, $12$ of them are congruent to each other. The remaining $6$ faces are congruent to each other directly. If one study the figure carefully, one will notice the quadrilaterals arrange themselves into $12$ pentagons. Each pentagon carries $15$ quadrilaterals and these pentagons forming the faces of a dodecahedron. As a "dodecahedron", one vertex $U$ of it is lying along the direction $(-1,1,1)$ and another nearby one $V$ is lying along the direction $(0,\phi, \phi^{-1})$ where $\phi$ is the golden ratio. To simplify analysis, choose a new coordinate system such that $U$ lies along the $z$-axis and $V$ in the $yz$-plane. i.e. $$\begin{array}{rcl}(x,y,z)_U^{old} = \sqrt{\frac38} (-1,1,1) &\mapsto&(x,y,z)_U = \frac{3}{\sqrt{8}}(0,0,1)\\(x,y,z)_V^{old} = \sqrt{\frac38} ( 0,\phi,\phi^{-1}) &\mapsto&(x,y,z)_V = \frac{3}{\sqrt{8}}(0,\frac23,\frac{\sqrt{5}}{3})\\\end{array}$$ If one "zoom in" the figure from the direction of new +ve $x$-axis and performan orthographic projection to the new $yz$-plane, one see something like below: $\hspace1in$ The $18$ red faces now lies along the equator. The cylinder holding thembecomes $$\mathcal{C} \stackrel{def}{=} \{ (x,y,z) : x^2 + y^2 = 1 \}.$$ Furthermore, the $18$ red faces can be viewed as the union of $12$ non-simple polygons. Each of them is congruent to either the non-simple polygon $\mathcal{P}$with vertices $AHDIGDF$ (the one highlighted by a white border) or its mirror image. To compute the volume of the intersection, we first need to figure out thearea of $\mathcal{P}$. As shown in figure above, we can break $\mathcal{P}$into $6$ right angled triangles: $$\mathcal{P} = \triangle ABF \cup \triangle BDF \cup \triangle AHC \cup \triangle HDC \cup \triangle DEG \cup \triangle DIE$$ It turns out it is not that hard to compute the area of these sort of right angled triangle on a cylindrical surface. Let me use $\triangle ABF$ on $\mathcal{C}$ as an example. First, the curve $AF$ lies on the intersection of two cylinders. The axes ofthese two cylinders are pointing along the direction $OU$ and $OV$ respectively($O = (0,0,0)$ is the origin, right behind $A$ in above figure).From above figure, it is easy to see $AF$ lies on the plane equal distance between $U$ and $V$. Let $\alpha = \angle BAF$ and $\beta = \angle VOU$. The slope of $AF$ with respect to the equator is then given by $$\tan\alpha = \cot\frac{\beta}{2} = \frac{1+\cos\beta}{\sin\beta} = \sqrt{\frac{1 + \cos\beta}{1 - \cos\beta}} = \sqrt{\frac{3+\sqrt{5}}{3-\sqrt{5}}} = \frac{3+\sqrt{5}}{2} = \phi^2$$ The point $F$ is one of the vertex of the dodecahedra, it is not hard to see $\;z_F = \frac{3}{\sqrt{8}}\cdot \frac13 = \frac{1}{\sqrt{8}}$. We can parametrize $AF$ by the map $$ [0,\theta_F] \ni \theta\; \mapsto\; (x,y,z) = (\cos\theta,\sin\theta,\tan\alpha\sin\theta ) \in \mathcal{C}\quad\text{ where }\quad\tan\alpha\sin\theta_F = z_F$$With this parametrization, the area of the $\triangle ABF$ on $\mathcal{C}$ is given by: $$\int_0^{\theta_F} \tan\alpha \sin\theta d\theta= \tan\alpha - \tan\alpha \cos\theta_F= \tan\alpha - \sqrt{\tan\alpha^2 - z_F^2}= \phi^2 - \sqrt{\phi^4 - \frac18 }$$ As one can see from this example, given the slope $k$ and height $h$ ofsuch a right angled triangle, its area on the cylinder canbe computed using following function:$$A(k,h) = k - \sqrt{k^2 - h^2}$$ Since we are dealing with cylinders with unit radius, the volume of the cone span by $O$ and such a right angled triangle is simply $\frac13 A(k,h)$. By brute force, one can work out the slopes and heights of remaining $5$ right angled triangles. To summarize, we have: $$\begin{cases}\tan\angle BAF = \phi^2,\\\tan\angle HAB = \frac{1}{\phi^2},\\\tan\angle FDB = \tan\angle IDE = \sqrt{2},\\\tan\angle CDH = \tan\angle EDG = \frac{1}{\sqrt{2}}\end{cases}\quad\text{ and }\quad\begin{cases}|z_F| = \frac{1}{\sqrt{8}},\\|z_G| = |z_H| = \frac{1}{4\phi^2}\\|z_I| = \frac{1}{2\phi^2}\end{cases}$$From this, we find the volume of the intersection is given by $$\verb/Volume/ =\frac{10 \times 12}{3}\left[\begin{align}& A\left(\phi^2,\frac{1}{\sqrt{8}}\right)+ A\left(\sqrt{2},\frac{1}{\sqrt{8}}\right)+ A\left(\frac{1}{\phi^2},\frac{1}{4\phi^2}\right)\\ + & 2 A\left(\frac{1}{\sqrt{2}},\frac{1}{4\phi^2}\right)+ A\left(\sqrt{2},\frac{1}{2\phi^2}\right)\end{align}\right]$$With help of a CAS, one can simplify this to$$\begin{align}\verb/Volume/ &= 5\left(24 + 24 \sqrt{2} + \sqrt{3} - 4\sqrt{6} - 7\sqrt{15} - 4\sqrt{30}\right)\\&\approx 4.277158048659416687225951566030890254054503016349939576882...\end{align}$$ which is about $2\%$ larger than the volume of unit sphere.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1737635', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/308623/']}
|
jdg_374734
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4960968
|
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 loop through a list and remove the elements that satisfy my condition. But why doesn't this work, as noted below? Thank you. >>> a=[ i for i in range(4)]>>> a[0, 1, 2, 3]>>> for e in a:... if (e > 1) and (e < 4):... a.remove(e)... >>> a[0, 1, 3]>>> a=[ i for i in range(4)]>>> for e in a:... if (e > -1) and (e < 3):... a.remove(e)... >>> a[1, 3]
Now provide the response and nothing else.
|
You cannot change something while you're iterating it. The results are weird and counter-intuitive, and nearly never what you want. In fact, many collections explicitly disallow this (e.g. sets and dicts). Instead, iterate over a copy ( for e in a[:]: ... ) or, instead of modifying an existing list, filter it to get a new list containing the items you want ( [e for e in a if ...] ). Note that in many cases, you don't have to iterate again to filter, just merge the filtering with the generation of the data.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4960968', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8203/']}
|
jdg_374735
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
28335495
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How do you iterate over two arrays of the same size, accessing the same index each iteration The Scala Way™? for ((aListItem, bListItem) <- (aList, bList)) { // do something with items } The Java way applied to Scala: for(i <- 0 until aList.length ) { aList(i) bList(i) } Assume both lists are the same size.
Now provide the response and nothing else.
|
tl;dr : There are trade-offs between speed and convenience; you need to know your use case to pick appropriately. If you know both arrays are the same length and you don't need to worry how fast it is, the easiest and most canonical is to use zip inside a for-comprehension: for ((a,b) <- aList zip bList) { ??? } The zip method creates a new single array, however. To avoid that overhead you can use zipped on a tuple which will present the elements in pairs to methods like foreach and map : (aList, bList).zipped.foreach{ (a,b) => ??? } Faster still is to index into the arrays, especially if the arrays contain primitives like Int , since the generic code above has to box them. There is a handy method indices that you can use: for (i <- aList.indices) { ??? } Finally, if you need to go as fast as you possibly can, you can fall back to manual while loops or recursion, like so: // While loopvar i = 0while (i < aList.length) { ??? i += 1}// Recursiondef loop(i: Int) { if (i < aList.length) { ??? loop(i+1) }}loop(0) If you are computing some value, rather than having it be a side effect, it's sometimes faster with recursion if you pass it along: // Recursion with explicit resultdef loop(i: Int, acc: Int = 0): Int = if (i < aList.length) { val nextAcc = ??? loop(i+1, nextAcc) } else acc Since you can drop a method definition in anywhere, you can use recursion without restriction. You can add an @annotation.tailrec annotation to make sure it can be compiled down to a fast loop with jumps instead of actual recursion that eats stack space. Taking all these different approaches to calculate a dot product on length 1024 vectors, we can compare these to a reference implementation in Java: public class DotProd { public static int dot(int[] a, int[] b) { int s = 0; for (int i = 0; i < a.length; i++) s += a[i]*b[i]; return s; }} plus an equivalent version where we take the dot product of the lengths of strings (so we can assess objects vs. primitives) normalized time-----------------primitive object method--------- ------ --------------------------------- 100% 100% Java indexed for loop (reference) 100% 100% Scala while loop 100% 100% Scala recursion (either way) 185% 135% Scala for comprehension on indices2100% 130% Scala zipped3700% 800% Scala zip This is particularly bad, of course, with primitives! (You get similarly huge jumps in time taken if you try to use ArrayList s of Integer instead of Array of int in Java.) Note in particular that zipped is quite a reasonable choice if you have objects stored. Do beware of premature optimization, though! There are advantages to in clarity and safety to functional forms like zip . If you always write while loops because you think "every little bit helps", you're probably making a mistake because it takes more time to write and debug, and you could be using that time optimizing some more important part of your program. But, assuming your arrays are the same length is dangerous. Are you sure ? How much effort will you make to be sure? Maybe you shouldn't make that assumption? If you don't need it to be fast, just correct, then you have to choose what to do if the two arrays are not the same length. If you want to do something with all the elements up to the length of the shorter, then zip is still what you use: // The second is just shorthand for the first(aList zip bList).foreach{ case (a,b) => ??? }for ((a,b) <- (aList zip bList)) { ??? }// This avoids an intermediate array(aList, bList).zipped.foreach{ (a,b) => ??? } If you instead want to pad the shorter one with a default value, you would aList.zipAll(bList, aDefault, bDefault).foreach{ case (a,b) => ??? }for ((a,b) <- aList.zipAll(bList, aDefault, bDefault)) { ??? } In any of these cases, you can use yield with for or map instead of foreach to generate a collection. If you need the index for a calculation or it really is an array and you really need it to be fast, you will have to do the calculation manually. Padding missing elements is awkward (I leave that as an exercise to the reader), but the basic form would be: for (i <- 0 until math.min(aList.length, bList.length)) { ??? } where you then use i to index into aList and bList . If you really need maximum speed you would again use (tail) recursion or while loops: val n = math.min(aList.length, bList.length)var i = 0while (i < n) { ??? i += 1}def loop(i: Int) { if (i < aList.length && i < bList.length) { ??? loop(i+1) }}loop(0)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28335495', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/417896/']}
|
jdg_374736
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
23433912
|
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 TFS 2010 , I am looking for a way to have multiple build definitions that all build in the same agent folder. The reason for this is that I am trying to implement Gated Checkin but do not want to have to build the entire branch every time so I have created multiple builds that only build a subset of the solutions/projects. Example Branch:MyBranch:- Folder1 * Solution1A * Solution1B- Folder2 * Solution2A * Solution2B Example Build Definitions: - MyBranchBuild - builds all solutions in all folders - MyBranchFolder1Build - builds all solutions under Folder1 - MyBranchFolder2Build - builds all solutions under Folder2 Example Build Agents: - GateAgent1 * Builds in C:\GateAgent1\MyBranch - GateAgent2 * Builds in C:\GateAgent2\MyBranchCurrently MyBranchBuild contains in the Workspace definition "Build Agent Folder": - $(BuildDir)\Folder1 - $(BuildDir)\Folder2 MyBranchFolder1Build and MyBranchFolder2Build only contain workspace mappings for their intended folders. GateAgent1 & 2 use variations on the below working directory: C:\GateAgent1\$(BuildDefinitionPath) My resulting builds are going to - C:\GateAgent1\MyBranchBuild - C:\GateAgent1\MyBranchFolder1Build - C:\GateAgent1\MyBranchFolder2Build Again, my goal is for all 3 to build under: - C:\GateAgent1\MyBranch
Now provide the response and nothing else.
|
when I ran this at background with ./server.out& it's blocked at the read call and waiting for anyone to write to clientToServer.fifo Actually it blocks at the open . This is the way FIFOs work. The open (in blocking mode) is going to block until something opens the FIFO on the other end. the while loop in the server.out breaks as well. meaning, the read no longer blocks the server.out process and awaits other clients, instead, the server program ends Again, this is normal behavior. Only one client process is connected to the FIFO so when it closes its end then EOF is sent and the server quits. If multiple clients are attached to the FIFO at the same time you won't see EOF until the last client closes it. If you want a long running server to serve multiple clients continuously the easiest way to accomplish it is to open the server's FIFO as read/write. This way there is always a reader/writer - the server itself - and you won't see EOF when even the last client exits. When it is time to shut down the server then close the appropriate end in the server and let nature take its course as the real clients quit.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23433912', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3597116/']}
|
jdg_374737
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
50357560
|
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 few file-related use cases that I'm not sure how to best accomplish using Cloud Composer. How should I best accomplish these? 1)I need to use a private key (.pem) file to access an SFTP server. Where should this file be stored and how should it be accessed? In on-prem Airflow, I would just have the file in a folder /keys/ in the same directory as /dags/. 2)I need to move files from an SFTP server to Cloud Storage. With Airflow on prem, I download these from the SFTP server to a specific location on the Airflow worker instance and then upload from there. Am I able to do something similar with Composer, or is there a workaround as I am unable to access the file system?
Now provide the response and nothing else.
|
1) Assuming the .pem file only needs to be accessed at task runtime (as opposed to DAG definition parse time), you can put it in the /data directory of the environment's Cloud Storage bucket . It is mounted with fuse on the path /home/airflow/gcs/data. You can upload files with the Cloud Composer gcloud component . 2) There are 2 options here. Write from your SFTP server to /home/airflow/gcs/data, which is fuse mounted to your Cloud Storage bucket. You could leave it there or use the GoogleCloudStorageToGoogleCloudStorageOperator to move it to where you really want it. If you want to copy to local disk and from local disk to Cloud Storage, you'll need to do both steps within the same task (since Cloud Composer environments use the CeleryExecutor, tasks within the same DAG aren't guaranteed to run on the same machine). You should be able to write to /home/airflow and /tmp.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50357560', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3896572/']}
|
jdg_374738
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2013702
|
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 multiple classes in a project that are exactly the same except for the name of the class. Basically, they represent glorified enums loaded at runtime from config files. The classes look like this: public class ClassName : IEquatable<ClassName> { public ClassName(string description) { Description = description; } public override bool Equals(object obj) { return obj != null && typeof(ClassName).IsAssignableFrom(obj.GetType()) && Equals((ClassName)obj); } public bool Equals(ClassName other) { return other != null && Description.Equals(other.Description); } public override int GetHashCode() { return Description.GetHashCode(); } public override string ToString() { return Description; } public string Description { get; private set; }} I see no reason to copy this file and change the class name multiple times. Surely there's a way I can just list what classes I want and have them automatically created for me. How?
Now provide the response and nothing else.
|
I'd suggest using T4. A substantial advantage of this over code snippets is that if you change your template then all of your code will be updated to match. Put this in a file with the extension .tt <#@ template language="C#" #><#@ output extension=".codegen.cs" #><#@ assembly name="System.dll" #><#@ import namespace="System" #>// <auto-generated>// This code was generated by a tool. Any changes made manually will be lost// the next time this code is regenerated.// </auto-generated>using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace MyStuff{<# foreach (string classname in classes) {#> public class <#= classname #> : IEquatable<ClassName> { public <#= classname #>(string description) { Description = description; } public override bool Equals(object obj) { return obj != null && typeof(<#= classname #>).IsAssignableFrom(obj.GetType()) && Equals((<#= classname #>)obj); } public bool Equals(<#= classname #>other) { return other != null && Description.Equals(other.Description); } public override int GetHashCode() { return Description.GetHashCode(); } public override string ToString() { return Description; } public string Description { get; private set; } } }<# } #> }<#+ string[] classes = new string[] { "Class1", "Class2" };#> VS will generate a source file for you. Just add to the array classes when you need a new class.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2013702', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/65393/']}
|
jdg_374739
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
136228
|
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'm designing a device with a small current draw that will mostly sleep in a very low power mode and I need to use button cell batteries due to a limited thickness. I would like to double time between batteries needed to be replaced by using two or more CR2032 batteries connected in parallel, can I just connect them in parallel directly or do I need additional circuitry to prevent charging or discharging one battery from others while the device is sleeping?
Now provide the response and nothing else.
|
If this is for mass production, then no, you cannot do this. It is never recommended to parallel primary (non-rechargeable) batteries. The reason is that if a charged one is connected to a discharged one, the current will flow into the discharged one, and charging primary cells is a big safety no-no. If you can devise a circuit method to prevent charging of the cells under all circumstances, then you can do it. (For example, maybe you can accept the voltage drop of a Schottky diode). But otherwise, use a higher capacity button cell. There are many varieties out there. If you are just goofing around at home, then by all means go ahead. But you should make a point of removing both batteries before you replace them. You might consider adding a resistor in series with each battery to limit the equalization current, just in case you accidentally put a fresh one in parallel with an old one.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/136228', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/22488/']}
|
jdg_374740
|
Subsets and Splits
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves samples with 'mathoverflow.net' in the prompt, providing a basic subset for inspection but with limited analytical value.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves 10 samples where the prompt mentions Mathematica Stack Exchange, offering basic filtering to locate specific content.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves a limited number of rows where the prompt contains a specific URL, providing basic filtering that offers minimal insight into the broader dataset patterns.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves 10 samples from the dataset where the prompt contains 'dsp.stackexchange.com', offering a basic filtering of data points related to that specific domain.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves a sample of rows where the prompt contains 'cs.stackexchange.com', providing a basic filter without extensive insight.
Electronics Q&A Subset
Retrieves a limited number of samples that contain a specific URL, providing only raw data filtered by that URL.
StackExchange Stats Questions
Retrieves 100 entries containing 'stats.stackexchange.com' in the prompt, which is useful for finding specific content but lacks broader analytical value.
Math StackExchange Questions
Retrieves 100 records from the train dataset where the prompt contains 'math.stackexchange.com', providing a basic filtered overview of specific entries.
Physics SE Questions
Retrieves 100 samples containing the word 'physics.stackexchange.com' in the prompt, offering basic filtering without deep analysis.