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
3728709
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 ideally like to write something like this: myValue1 = 1 :: IntmyValue2 = 2 :: IntmyFunc :: Int -> BoolmyFunc myValue1 = TruemyFunc myValue2 = False Calling myFunc myValue2 returns True - not what I intend. I know why this happens, but is there a way to express this in Haskell without resorting to C-style #define statements? Now provide the response and nothing else.
Well, Haskell doesn't unify names like this. Those new 'myValue1' and '2' identifiers are new variables you're binding. The most Haskelly way is to use strong types and pattern matching: data Values = D1 | D2myFunc :: Values -> BoolmyFunc D1 = TruemyFunc D2 = False Giving you a static guarantee only "1" or "2" can be passed to myFunc, proper symbolic matching and you even retain conversion to integers by deriving Enum.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3728709', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/449761/']}
jdg_85641
stackexchange
llm_judgeable_groundtruth_similarity
423866
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I need to find the cardinality of the set $S$ of all infinite subsets of $\mathbb{Q}$. It's easy to prove $\operatorname{card} S=\mathfrak c$ if you first prove that the cardinality of the set of all finite subsets of $\mathbb{Q}$ is $\aleph_0$. But is there some other proof for the statement without using the second one (about finite subsets)? Probably there is =) Now provide the response and nothing else.
To each real number $r$, you can associate the set $\{q\in\mathbb Q:q<r\}$. Distinct real numbers produce in this way distinct infinite sets of rational numbers. So there are at least $\mathfrak c$ infinite sets of rational numbers. Since you seem to already know tha there are at most $\mathfrak c$ such sets, the Schröder-Bernstein Theorem finishes the proof.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/423866', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/76798/']}
jdg_85642
stackexchange
llm_judgeable_groundtruth_similarity
78296
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: At each time step, I have 1/2 probability of walking one step to the right, and the same probability of walking one step to the left. Let X be the random variable corresponding to the final position of the $n$ step I walk. Compute a) $E[X^4]$ for this random variable b) Show that $P(|X|>c) \le \dfrac{E[X^4]}{c^4}$ My thought: I tried to use the definition of expectation to compute but the polynomial of degree 4 got really messy. I was wondering if there is an elegant way to approach this problem. And I also tried to use generating function but how to write the generating function for this random variable. Now provide the response and nothing else.
A less elegant, but simple approach: $X=Z_1 + Z_2 + \cdots + Z_n$ with $Z_i =\pm 1$.We must compute $E[ (Z_1 + Z_2 + \cdots + Z_n)^4]$ . If we expand this, we get a sum of $n^4$ fourth degree monomials. But because $Z_i$ are iid with zero mean, all terms vanish except those that contains exclusively even exponents; that is, those that are of the form $E(Z_i^4)$ or $E(Z_i^2 Z_j^2)$. Now, there are $n$ terms of the first form, and $ {4 \choose 2} {n \choose 2} = 3 n (n-1)$ terms of the second. Besides, $E(Z_i^2) = E(Z_i^4)=1$ trivially. Hence $$E(X^4) = n + 3 \; n( n - 1) = n \; (3 n -2)$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/78296', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/17322/']}
jdg_85643
stackexchange
llm_judgeable_groundtruth_similarity
21242
Below is a question asked on the forum mechanics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I changed the rear brake pads on my BMW last week, following the steps outlined in this video . Unfortunately the brake pedal now feels spongy. The pedal feel was firm prior to the brake swap, so it is definitely a sudden change and not a gradual degradation of brake fluid. One thing I forgot to do was undo the brake fluid reservoir cap before pushing the piston calipers back with a C-clamp, so I suspect that the the sponginess is due to trapped air in the system since the reservoir was never exposed to outside air. Or is it possible that the extra pressurization of the system via the C-clamp resulted in moisture absorption? The only issue I see with this reasoning is that the system was never exposed to outside air. Now provide the response and nothing else.
Two things to look for. 1) air in the brake fluid. 2) incorrectly assembled brake pads, especially the anti noise shims. Air in the brake fluid is the most common cause of low, spongy brake pedal feel. Moisture in the fluid will not substantially change the pedal feel until the fluid temperature exceeds the boiling point of any water in the fluid, then the pedal feel gets very soft. Brake fluid absorbs water if exposed, so the systems are to remain sealed. Brake fluid older than three years or any color other than that of tea should be flushed. Improper assembly of the brakes can cause the pistons to be pushed back too far into their bores when the brakes are released. this cause a longer than normal stroke of the brake pedal before resistance is felt. Also new brake pads installed without surfacing the rotors can result in more pedal effort required for normal braking.
{}
{'log_upvote_score': 4, 'links': ['https://mechanics.stackexchange.com/questions/21242', 'https://mechanics.stackexchange.com', 'https://mechanics.stackexchange.com/users/675/']}
jdg_85644
stackexchange
llm_judgeable_groundtruth_similarity
2283745
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: In a mathematical physical problem related to the search of Green's functions in an anisotropic medium, I came across a non-trivial double integral. Is it possible to evaluate analytically the following double integral? $$\varphi(h, A, B) = -\frac{1}{(2\pi)^2} \int_0^{\infty} \int_{0}^\pi \frac{\sin^3\theta \, e^{ihk\cos\theta}}{\cos^4\theta-A\cos^2\theta-B}\, \mathrm{d}\theta \, \mathrm{d}k \, , $$where $h$, $A$ and $B$ are all positive real numbers. Making the change of variable $q=\cos\theta$, the above integral can conveniently be written as$$\varphi(h, A, B) = -\frac{1}{(2\pi)^2} \int_0^{\infty} \int_{-1}^1 \frac{(1-q^2) \, e^{ihkq}}{q^4-Aq^2-B}\, \mathrm{d}q \, \mathrm{d}k \, .$$ Now, by changing the integration range for $q$ we obtain$$\varphi(h, A, B) = -\frac{1}{2\pi^2} \int_0^{\infty} \int_{0}^1 \frac{(1-q^2) \, \cos(hkq)}{q^4-Aq^2-B}\, \mathrm{d}q \, \mathrm{d}k \, .$$ By making use of Maple, I have noticed that the function $\varphi$ depends solely on $h$ and $B$ and does not depend on $A$. More precisely $$\varphi (h,A,B) = \varphi(h,B) = \frac{1}{4\pi B h} \, .$$Is there a way to show that mathematically in a rigorous way? Is that true?Any help / hints / indication would be highly appreciated. Thank you, Fede Now provide the response and nothing else.
As pointed out by various comments, the integral is not well-defined in the usual sense if the denominator has zero at some $q \in (-1, 1)$. Instead, we may consider the following regularized version $$ \tilde{\varphi}(h,A,B) := -\frac{1}{4\pi^2} \lim_{\epsilon \to 0^+} \int_{0}^{\infty} \left( \operatorname{PV} \int_{-1}^{1} \frac{1-q^2}{q^4 - Aq^2 - B} e^{ihkq} \, dq \right) e^{-\epsilon k} \, dk. \tag{1} $$ We write $\alpha = \frac{1}{2}(\sqrt{A+4B} + A)$ and $\beta = \frac{1}{2}(\sqrt{A+4B} - A)$. Then $$ \frac{1-q^2}{q^4 - Aq^2 - B} = \frac{1-q^2}{(q^2 + \beta)(q^2 - \alpha)}. $$ If $\alpha \geq 1$, then it has no singularity on $[-1 ,1]$ (upon resolving the possible singularity at $q = \pm 1$ when $\alpha = 1$). Otherwise, poles at $p = \pm \sqrt{\alpha}$ should be taken into consideration. So we divide into cases. Case I. Assume first that $\alpha \geq 1$, which turns the inner principal value into a genuine Lebesgue integral. Under this assumption, we have the uniform estimate $$ \forall q \in (-1,1), \qquad \left| \frac{1-q^2}{q^4 - Aq^2 - B} \right|=\frac{1-q^2}{(q^2 + \beta)(\alpha - q^2)}\leq \frac{1}{\beta}, \tag{2}$$ hence Fubini's theorem is applicable and we have \begin{align*}\tilde{\varphi}(h,A,B)&= -\frac{1}{4\pi^2} \lim_{\epsilon \to 0^+} \int_{-1}^{1} \int_{0}^{\infty} \frac{1-q^2}{q^4 - Aq^2 - B} e^{ihkq}e^{-\epsilon k} \, dkdq \\&= -\frac{1}{4\pi^2} \lim_{\epsilon \to 0^+} \int_{-1}^{1} \frac{1-q^2}{q^4 - Aq^2 - B} \cdot \frac{1}{\epsilon - ihq} \, dq.\end{align*} Now the inner integral is ready to be computed. Indeed, use symmetry to write $$ = -\frac{1}{4\pi^2} \lim_{\epsilon \to 0^+} \int_{-1}^{1} \frac{1-q^2}{q^4 - Aq^2 - B} \cdot \frac{\epsilon}{\epsilon^2 + h^2q^2} \, dq. $$ By the standard approximation-to-the-identity argument, we easily check that this limit converges to $$ = -\frac{1}{4\pi^2} \cdot \frac{\pi}{h} \left( \left. \frac{1-q^2}{q^4 - Aq^2 - B}\right|_{q=0} \right)= \frac{1}{4\pi Bh}. $$ Alternatively, utilize the substitution $hq = \epsilon t$ and notice that the integrand of $$ \tilde{\varphi}(h,A,B)= -\frac{1}{4\pi^2} \lim_{\epsilon \to 0^+} \int_{-h/\epsilon}^{h/\epsilon} \frac{1-(\epsilon t/h)^2}{(\epsilon t/h)^4 - A(\epsilon t/h)^2 - B} \cdot \frac{1}{h(1+t^2)} \, dt. $$ is dominated by $\frac{1}{\beta h(1+t^2)}$ in view of $\text{(2)}$ again. So we can invoke the dominated convergence theorem to obtain the same answer. Case II. Assume next that $\alpha < 1$ so that the inner principal value cannot be reduced to ordinary integral. In order to resolve this case, we extract out the contribution of poles at $p = \pm \sqrt{\alpha}$. First, note that $$ \underset{q = \pm \sqrt{\alpha}}{\operatorname{Res}} \, \frac{1-q^2}{q^4 - Aq^2 - B} = \pm \frac{1-\alpha}{2\sqrt{\alpha}(2\alpha - A)} =: \pm C. $$ Now choose $\delta > 0$ sufficiently small so that $0 < \alpha - \delta < \alpha + \delta < 1$ and an even smooth function $\eta \in C_c^{\infty}(\Bbb{R})$ which is $1$ near $0$ and vanishes outside $(-\delta, \delta)$. Then consider the following function $$ f(q) = \frac{C}{q - \sqrt{\alpha}} \eta(q - \sqrt{\alpha}) - \frac{C}{q + \sqrt{\alpha}} \eta(q + \sqrt{\alpha}). $$ This function is designed to cancel the poles of $(1-q^2)/(q^4 - Aq^2 - B)$ at $q = \pm \sqrt{\alpha}$, so we can write \begin{align*}&\operatorname{PV} \int_{-1}^{1} \frac{1-q^2}{q^4 - Aq^2 - B} e^{ihkq} \, dq \\&\hspace{1em} = \int_{-1}^{1} \left( \frac{1-q^2}{q^4 - Aq^2 - B} - f(q) \right) e^{ihkq} \, dq+ \operatorname{PV} \int_{-1}^{1} f(q) e^{ihkq} \, dq.\end{align*} The integrand of the first term now extends to a continuous as function of $q$ on $[-1, 1]$. So it can be resolved by the same idea as in the former case. This gives \begin{align*}&-\frac{1}{4\pi^2} \lim_{\epsilon \to 0^+} \int_{0}^{\infty} \left( \int_{-1}^{1} \left( \frac{1-q^2}{q^4 - Aq^2 - B} - f(q) \right) e^{ihkq} \, dq \right) e^{-\epsilon k} \, dk \tag{3} \\&\hspace{4em} = -\frac{1}{4\pi^2} \cdot \frac{\pi}{h} \left( \left. \frac{1-q^2}{q^4 - Aq^2 - B} - f(q) \right|_{q=0} \right) \\&\hspace{5em} = \frac{1}{4\pi Bh}.\end{align*} For the second term, we write \begin{align*}\operatorname{PV} \int_{-1}^{1} f(q) e^{ihkq} \, dq&= C \cdot \operatorname{PV} \int_{-\infty}^{\infty} \frac{e^{ihk(q+\sqrt{\alpha})} - e^{ihk(q-\sqrt{\alpha})}}{q} \, \eta(q) \, dq \\&= C \int_{-\infty}^{\infty} \frac{\cos (hk(q+\sqrt{\alpha})) - \cos(hk(q-\sqrt{\alpha}))}{q} \, \eta(q) \, dq.\end{align*} By utilizing trigonometric identities, it is easy to check that the integrand is uniformly bounded by $2kh |\eta(q)|$. So we can invoke Fubini's theorem to write \begin{align*}&\int_{0}^{\infty} \left( \operatorname{PV} \int_{-1}^{1} f(q) e^{ihkq} \, dq \right) e^{-\epsilon k} \, dk \tag{4} \\&\hspace{2em} = \int_{-\infty}^{\infty} \frac{C}{q}\left( \frac{\epsilon}{\epsilon^2 + h^2(q+\sqrt{\alpha})^2} - \frac{\epsilon}{\epsilon^2 + h^2(q-\sqrt{\alpha})^2} \right)\, \eta(q) \, dq \\&\hspace{2em} = - \epsilon \int_{-\infty}^{\infty} \frac{2\sqrt{\alpha}C h^2}{\left( \epsilon^2 + h^2(q+\sqrt{\alpha})^2 \right)\left( \epsilon^2 + h^2(q-\sqrt{\alpha})^2 \right)}\, \eta(q) \, dq \\&\hspace{2em} = \mathcal{O}(\epsilon) \quad \text{as } \epsilon \to 0^+.\end{align*} By $\text{(3)}$ and $\text{(4)}$, we again have $\tilde{\varphi}(h,A,B) = 1/(4\pi Bh)$. Combining altogether, we have proved that $$ \tilde{\varphi}(h,A,B) = \frac{1}{4\pi Bh} $$ Remarks. When $\alpha \geq 1$, the regularization process in $\text{(1)}$ is unnecessary. Indeed, integration by parts shows that $$ \int_{-1}^{1} \frac{1-q^2}{q^4 - Aq^2 - B} e^{ihkq} \, dq= \begin{cases}\mathcal{O}(k^{-2}), & \alpha > 1 \\\\-\dfrac{2\sin(hk)}{(1+\beta)hk} + \mathcal{O}(k^{-2}), & \alpha = 1.\end{cases} $$ Consequently, $\varphi(h, A, B)$ is well-defined for $\alpha > 1$. Then the regularized version reduces to the original version and hence $$\varphi(h,A,B) = \tilde{\varphi}(h,A,B) = \frac{1}{4\pi Bh}. $$ On the other hand, the decay speed is worse enough that the exponential regularization in $\text{(1)}$ is essential for $\alpha < 1$. Indeed, a similar comment applies to $\text{(3)}$, showing that $$ \int_{-1}^{1} \left( \frac{1-q^2}{q^4 - Aq^2 - B} - f(q) \right) e^{ihkq} \, dq = \mathcal{O}(k^{-2}). $$ However, the remaining part satisfies $$ \operatorname{PV} \int_{-1}^{1} f(q) e^{ihkq} \, dq= -2C \sin (hk\sqrt{\alpha}) \int_{-\infty}^{\infty} \frac{\sin q}{q} \, \eta\left(\frac{q}{hk}\right) \, dq\sim -2C\pi \sin (hk\sqrt{\alpha}) $$ as $k \to \infty$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2283745', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/140351/']}
jdg_85645
stackexchange
llm_judgeable_groundtruth_similarity
29703330
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 got a Bootstrap carousel implemented on my page and for some reason I cannot get the caption text to re-position according to the size of the web browser. Here is my HTML code: <!-- =======================CAROUSEL=========================== --><div id="myCarousel" class="carousel slide" data-ride="carousel"> <!-- Indicators --> <ol class="carousel-indicators"> <li data-target="#myCarousel" data-slide-to="0" class="active"></li> <li data-target="#myCarousel" data-slide-to="1"></li> </ol> <div class="carousel-inner" role="listbox"> <div class="item active"> <img class="first-slide" src="img/main-banner.png" alt="First slide"> <div class="container"> <div class="carousel-caption"> <h1>Democratizing the Internet of Things!</h1> <p><a class="btn btn-lg btn-primary" href="./index.php?d=splash" role="button">Try Splash</a></p> </div> </div> </div> <div class="item"> <img class="second-slide" src="img/banner-2.png" alt="Second slide"> <div class="container"> <div class="carousel-caption"> <h1>Another Heading!</h1> </div> </div> </div> <a class="left carousel-control" href="#myCarousel" role="button" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="right carousel-control" href="#myCarousel" role="button" data-slide="next"> <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span> <span class="sr-only">Next</span> </a></div> I'm using Bootstrap CDN: <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css"> These are all my CSS changes I've made to the carousel: .carousel-caption {position: relative !important;width: 550px;top: 210px;left: 380px !important;z-index: 600;max-height:177px;}.carousel-caption h1 { font-family: sans-serif !important; font-size: 44px !important; font-weight: 700 !important; line-height:36px !important; color: #444 !important; margin: 0px !important; padding: 0px !important; text-shadow: 0px 0px 4px #fff !important; text-align: left !important;}.carousel-caption p { margin-top: 11px !important; font-size:18px !important; line-height:21px !important; color:#333 !important; padding-bottom: 11px !important; margin-bottom: 11px !important; text-shadow: 0px 0px 4px #fff !important; text-align: left !important;}.carousel-control.left, .carousel-control.right { background-image: none !important;}.carousel-indicators { left: 405px !important;} This is what the carousel looks at full screen: And here's what happens as I start to change the size of the web browser: I have tried all the different type of positions, but for the life of me cannot figure out what I'm doing wrong. Any help is appreciated! Now provide the response and nothing else.
To vertically align the caption in the center I used the CSS function translateY or property transform . I also wanted the caption to be placed directly beside the left carousel control. I also removed extra bottom space that was added by the default bootstrap CSS. .carousel-caption {width: 550px;left: 15%;top: 50% !important;transform: translateY(-50%);text-align: left;bottom: initial;} The caption now appears properly regardless of the screen size:
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29703330', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2100620/']}
jdg_85646
stackexchange
llm_judgeable_groundtruth_similarity
22972066
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So I'm writing this RESTful backend in Go, which will be called with cross-site HTTP requests, i.e. from content served by another site (actually, just another port, but the same-origin policy kicks in, so here we are). In this scenario, the user agent will, in some cases, send preflight OPTIONS requests to check if the actual request is safe to send. My question is how to best deal with, and adequately respond to, these preflight requests in a Go context. The ways I have conceived don't feel very elegant, and I'm wondering if there's some other approach to this that I haven't thought of. Using the standard net/http package, I can check the request method in the handler func, perhaps like this: func AddResourceHandler(rw http.ResponseWriter, r *http.Request) { switch r.Method { case "OPTIONS": // handle preflight case "PUT": // respond to actual request }} I can also use Gorilla's mux package, and register a preflight "OPTIONS" handler for each relevant URL path. r := mux.NewRouter()r.HandleFunc("/someresource/item", AddResourceHandler).Methods("PUT")r.HandleFunc("/someresource/item", PreflightAddResourceHandler).Methods("OPTIONS") Maybe the response to this question is simply: Yup, those are your basic options. But I thought there might be some best practice around this that I'm unaware of. Now provide the response and nothing else.
One simple way to separate out your logic and re-use the CORS handler you define would be to wrap your REST handler. For example, if you're using net/http and the Handle method you could always do something like: func corsHandler(h http.Handler) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if (r.Method == "OPTIONS") { //handle preflight in here } else { h.ServeHTTP(w,r) } }} You can wrap like this: http.Handle("/endpoint/", corsHandler(restHandler))
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/22972066', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/919665/']}
jdg_85647
stackexchange
llm_judgeable_groundtruth_similarity
135912
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: The question Solutions to the Continuum Hypothesis states that the continuum hypothesis was posed by Cantor in 1890. In http://en.wikipedia.org/wiki/Continuum_hypothesis the year 1878 is quoted without source. What is the correct date? Now provide the response and nothing else.
Finally, a good use for the newly purchased copy of "Zermelo's Axiom of Choice". Moore writes that Cantor formulated the following problem in 1878: Every infinite subset of $\Bbb R$ is either denumerable or has the power of the continuum. The given reference is: Cantor G. " Ein Beitrag zur Mannigfaltigkeitslehre ." Journal für die reine und angewandte Mathematik 84 (1878), pp. 242-258. Although searching for the reference, it seems that it may have published in 1877, so it's unclear which one is the correct date. The paper was written in 1877, though. Moore points that the hypothesis was given on page 257 , but I don't read German very well (or at all, for that matter), so I can't tell. Moore also adds that in 1895 Cantor pointed out that in $\aleph$ notation, which introduced in the paper below, that this is equal to $2^{\aleph_0}=\aleph_1$. Cantor already made this observation in 1882 in a letter to Dedekind, where he used the terminology "numbers of the second number-class" to talk about $\aleph_1$. Cantor G. " Beiträge zur Begründung der transfiniten Mengenlehre ." Mathematische Annalen 46 pp. 481-512. However it is good to note that this equivalence requires the axiom of choice. The question you cite refers to this statement, and not the first statement. (Both the statements appear on page 41 of the book " Zermelo's Axiom of Choice: Its Origins, Developments & Influence " by Gregory H. Moore)
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/135912', 'https://mathoverflow.net', 'https://mathoverflow.net/users/-1/']}
jdg_85648
stackexchange
llm_judgeable_groundtruth_similarity
38616771
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 in the middle of studying the ASP.NET Core, and I have implemented logging with a file system successfully, but how about implementing logging feature with a database solution. How to pass EF context to my ' LoggerDatabaseProvider ', and still have those two decoupled? The code below should clear some upfront questions: Startup.cs: public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddEntityFramework() .AddEntityFrameworkSqlServer() .AddDbContext<WorldContext>(); services.AddTransient<WorldContextSeedData>(); services.AddScoped<IWorldRepository, WorldRepository>(); //this one adds service with Dependency Injection that calls 'MyLogger' constructor with two parameters, instead the default one parametereless constructor. services.AddScoped<ILogger, LoggerFileProvider.Logger>(provider => new LoggerFileProvider.Logger("CustomErrors", Startup.Configuration["Data:LogFilePath"])); //services.AddScoped<ILogger, LoggerDatabaseProvider.Logger>(provider => new LoggerDatabaseProvider.Logger("CustomErrors")); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, WorldContextSeedData seeder) { string basePath = Startup.Configuration["Data:LogFilePath"]; loggerFactory.AddProvider(new LoggerFileProvider(basePath)); loggerFactory.AddProvider(new LoggerDatabaseProvider()); app.UseStaticFiles(); app.UseMvc(config => { config.MapRoute( name: "Default", template: "{controller}/{action}/{id?}", defaults: new { controller = "App", action = "index" } ); }); seeder.EnsureSeedData(); } Here is my successfully implemented logger with text file: public class LoggerFileProvider : ILoggerProvider{ private readonly string _logFilePath; public LoggerFileProvider(string logFilePath) { _logFilePath = logFilePath; } public ILogger CreateLogger(string categoryName) { return new Logger(categoryName, _logFilePath); } public void Dispose() { } public class Logger : ILogger { private readonly string _categoryName; private readonly string _path; public Logger(string categoryName, string logFilePath) { _path = logFilePath; _categoryName = categoryName; } public bool IsEnabled(LogLevel logLevel) { return true; } public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) { try { RecordMsg(logLevel, eventId, state, exception, formatter); } catch (Exception ex) { //this is being used in case of error 'the process cannot access the file because it is being used by another process', could not find a better way to resolve the issue RecordMsg(logLevel, eventId, state, exception, formatter); } } private void RecordMsg<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) { string msg = $"{logLevel} :: {_categoryName} :: {formatter(state, exception)} :: username :: {DateTime.Now}"; using (var writer = File.AppendText(_path)) { writer.WriteLine(msg); } } public IDisposable BeginScope<TState>(TState state) { return new NoopDisposable(); } private class NoopDisposable : IDisposable { public void Dispose() { } } }} But how about the very similar implementation, but with database solution? My WorldContext is utilized by EF to communicate with database, but if it would be easier I could utilize my repository. I would like to keep the context/repository decoupled from ' LoggerDatabaseProvider ' that I am about to implement, so I could utilize it in other projects. Now provide the response and nothing else.
Per specification, here is how I managed to implemented it, just in case someone would look for similar solution. 'Startup.cs': public void ConfigureServices(IServiceCollection services){ services.AddMvc(); services.AddEntityFramework() .AddEntityFrameworkSqlServer() .AddDbContext<WorldContext>(); services.AddLogging(); services.AddTransient<WorldContextSeedData>(); services.AddScoped<IMailService, MailServiceDebug>(); services.AddScoped<IWorldRepository, WorldRepository>();}// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, WorldContextSeedData seeder, IWorldRepository worldRepo){ string basePath = Startup.Configuration["Data:LogFilePath"]; loggerFactory.AddProvider(new LoggerFileProvider(basePath)); loggerFactory.AddProvider(new LoggerDatabaseProvider(worldRepo)); app.UseStaticFiles(); app.UseMvc(config => { config.MapRoute( name: "Default", template: "{controller}/{action}/{id?}", defaults: new { controller = "App", action = "index" } ); }); seeder.EnsureSeedData();} Custom 'LoggerFileProvider.cs': public class LoggerFileProvider : ILoggerProvider{ private readonly string _logFilePath; public LoggerFileProvider(string logFilePath) { _logFilePath = logFilePath; } public ILogger CreateLogger(string categoryName) { return new Logger(categoryName, _logFilePath); } public void Dispose() { } public class Logger : ILogger { private readonly string _categoryName; private readonly string _path; public Logger(string categoryName, string logFilePath) { _path = logFilePath; _categoryName = categoryName; } public bool IsEnabled(LogLevel logLevel) { return true; } public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) { try { RecordMsg(logLevel, eventId, state, exception, formatter); } catch (Exception ex) { //this is being used in case of error 'the process cannot access the file because it is being used by another process', could not find a better way to resolve the issue RecordMsg(logLevel, eventId, state, exception, formatter); } } private void RecordMsg<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) { string msg = $"{logLevel} :: {_categoryName} :: {formatter(state, exception)} :: username :: {DateTime.Now}"; using (var writer = File.AppendText(_path)) { writer.WriteLine(msg); } } public IDisposable BeginScope<TState>(TState state) { return new NoopDisposable(); } private class NoopDisposable : IDisposable { public void Dispose() { } } }} Custom 'LoggerDatabaseProvider.cs': public class LoggerDatabaseProvider : ILoggerProvider{ private IWorldRepository _repo; public LoggerDatabaseProvider(IWorldRepository repo) { _repo = repo; } public ILogger CreateLogger(string categoryName) { return new Logger(categoryName, _repo); } public void Dispose() { } public class Logger : ILogger { private readonly string _categoryName; private readonly IWorldRepository _repo; public Logger(string categoryName, IWorldRepository repo) { _repo = repo; _categoryName = categoryName; } public bool IsEnabled(LogLevel logLevel) { return true; } public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) { if (logLevel == LogLevel.Critical || logLevel == LogLevel.Error || logLevel == LogLevel.Warning) RecordMsg(logLevel, eventId, state, exception, formatter); } private void RecordMsg<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) { _repo.Log(new Log { LogLevel = logLevel.ToString(), CategoryName = _categoryName, Msg = formatter(state, exception), User = "username", Timestamp = DateTime.Now }); } public IDisposable BeginScope<TState>(TState state) { return new NoopDisposable(); } private class NoopDisposable : IDisposable { public void Dispose() { } } }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38616771', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3220603/']}
jdg_85649
stackexchange
llm_judgeable_groundtruth_similarity
6644362
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 defined an alert view in my .h file (@property...), and in my .m file (@synthesize...) so that I can refer to it in multiple methods. When I have an alert view alloc, how do I tell it that this is the alert view that I've defined in the h and m files? Now provide the response and nothing else.
After searching a little in PlayFramework's source code, I've stumbled upon ImageIO ibrary already used in Play. Cannot understand, why such easy checks have not been added to the core library... Here's the check part, I've created for : dimension check, type check, size check. package validators;import java.awt.image.BufferedImage;import java.io.IOException;import javax.imageio.ImageIO;import play.Logger;import play.data.validation.Check;import play.db.jpa.Blob;import play.i18n.Messages;public class ImageValidator extends Check { public final static int MAX_SIZE = 4048; public final static int MAX_HEIGHT = 1920; @Override public boolean isSatisfied(Object parent, Object image) { if (!(image instanceof Blob)) { return false; } if (!((Blob) image).type().equals("image/jpeg") && !((Blob) image).type().equals("image/png")) { return false; } // size check if (((Blob) image).getFile().getLength() > MAX_SIZE) { return false; } try { BufferedImage source = ImageIO.read(((Blob) image).getFile()); int width = source.getWidth(); int height = source.getHeight(); if (width > MAX_WIDTH || height > MAX_HEIGHT) { return false; } } catch (IOException exption) { return false; } return true; }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6644362', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/775624/']}
jdg_85650
stackexchange
llm_judgeable_groundtruth_similarity
141501
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Definition. A topological space $X$ has the Fixed Point Property (FPP) if every continuous self-map $X\to X$ has a fixed point. Question. If $X$ and $Y$ are homotopy-equivalent compact metrizable spaces and $X$ has the FPP, does it follow that $Y$ also has FPP? Another way to put it: Can one force a fixed point for a self-map of a compact by a "non-homological" argument? I do not know an answer to this even for finite simplicial complexes, but my primary interest is in locally connected finite-dimensional compacts. Now provide the response and nothing else.
Lovely question! Sadly, the answer is "no" in the sense that the fixed point property is not homotopy-invariant even in the category of finite polyhedra. In fact, it is also not invariant under the operations of taking products or suspensions. See the three page paper of W Lopez called " An example in the fixed point theory of polyhedra " for the construction of an explicit counterexample to your desired property as well as the two properties listed above. Basically, Lopez's construction involves two finite polyhedra $X$ and $Y$ whose wedge product has the fixed point property but whose union along an edge does not (!!). The Corollary to Theorem 3 on the second page of the linked pdf is of interest. Update (4th Oct 2015): I have also been looking for positive results lately, and one good source is Robert Brown's Handbook of Topological Fixed Point Theory (the Google book is here . Theorem 8.11 in the book is this cool result of Jerrard: Suppose $X$ and $Y$ are compact polyhedra so that the Lefschetz numbers of every self-map $X \to X$ and $Y \to Y$ are nonzero, and so that every composite $H_n(X) \to H_n(Y) \to H_n(X)$ is trivial for $n > 0$. Then $X \times Y$ has the fixed point property. So if you can decompose your space as a nice enough product of fixed point spaces, then there is some hope depending on their homology...
{}
{'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/141501', 'https://mathoverflow.net', 'https://mathoverflow.net/users/21684/']}
jdg_85651
stackexchange
llm_judgeable_groundtruth_similarity
21741131
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Say I have a simple console application: public static class Program{ private static ILog Log { get; set; } public static void Main() { Log.Write("Hello, world!"); }} What is the simplest way I can use Autofac to inject the Log instance and ensure that the Log property will not be null at run time? The issue is that I can't pass it in through Main() and I'm trying to avoid service location using the container (just because). Now provide the response and nothing else.
What you should do is extract all logic from your main into a class. This class can have a constructor with dependencies. You resolve this class in the main and call it. This class should then be considered to be the entire application . Everything that happens inside the Program class can now be considered your Composition Root . // ** Begin composition rootpublic static class Program{ public static void Main(string[] args) { var container = ConfigureContainer(); var application = container.Resolve<ApplicationLogic>(); application.Run(args); // Pass runtime data to application here } private static IContainer ConfigureContainer() { var builder = new ContainerBuilder(); builder.RegisterType<ApplicationLogic>.AsSelf(); builder.RegisterType<Log>().As<ILog>(); // Register all dependencies (and dependencies of those dependencies, etc) return builder.Build(); }}// ** End composition rootpublic class ApplicationLogic{ private readonly ILog log; public ApplicationLogic(ILog log) => this.log = log; public void Run(string[] args) => this.log.Write("Hello, world!");} Note that container.Resolve<ApplicationLogic>() doesn't just resolve the ApplicationLogic class, it resolves the entire object graph including all of ApplicationLogic 's dependencies, and dependencies of those dependencies, etc. no matter how deep the graph is. The only thing you are responsible for is registering those dependencies in the ConfigureContainer() method. Therefore, it is somewhat unusual to have any more than 1 Resolve() method call a console application, and if there are, they should always be called or wired up inside the Composition Root.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21741131', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2962837/']}
jdg_85652
stackexchange
llm_judgeable_groundtruth_similarity
394367
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: Found a question which asks you to find all integer solutions $y^3 =x^2 +2$ . In order to do so, it first asks you to show that y is odd. How would one go about showing this? Many Thanks Now provide the response and nothing else.
Suppose $\,y\,$ is even, then also $\,x\,$ must be even, but then $\;x^2+2 \equiv 2\pmod 4\;$ , and since $\,y^3 \not \equiv 2 \pmod 4\;\;\forall\,y\in\Bbb Z\;$ we're done.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/394367', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/77989/']}
jdg_85653
stackexchange
llm_judgeable_groundtruth_similarity
13728739
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 seeing this a lot in someone's code: null-check conditions are written like this: if (null == value) rather than if (value == null) I don't think there is any reason to have the null precede the operator in Java. Is there any benefit to doing it this way? Is this simply a case of a C++ programmer applying his skill to Java incorrectly, or am I missing something important? Now provide the response and nothing else.
This is a case of so-called "Yoda Conditions" (item #1) . Although it is possible to rationalize them in C/C++, there is no reason to use them in Java. In C/C++, expressions of any type can go into if s and while s. Writing if (var = NULL) // No compile-time error in C/C++ instead of if (var == NULL) is a common error among novices. Yoda conditions were supposedly a remedy to address this problem, at the cost of "Yodifying" your code: C/C++ would trap assignments to NULL if (NULL = var) // Compile-time error but "reversed" NULL checks are OK: if (NULL == var) Since Java considers non-boolean expressions inside control blocks of if , while , and for to be errors, it would trap var = null in place of var == null , triggering an error. Therefore, there is no reason to give up readability by "Yodifying" your expressions.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13728739', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1061426/']}
jdg_85654
stackexchange
llm_judgeable_groundtruth_similarity
44213921
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 run this Matplotlib example using Python 3. To run this I needed to install gi first (I am using pyenv ): $ python --versionPython 3.6.1$ pip --versionpip 9.0.1 from /home/hakon/.pyenv/versions/3.6.1/lib/python3.6/site-packages (python 3.6)$ pip install giCollecting gi Downloading gi-1.2.tar.gzCollecting requests (from gi) Downloading requests-2.16.0-py2.py3-none-any.whl (85kB) 100% |████████████████████████████████| 92kB 959kB/s Collecting idna<2.6,>=2.5 (from requests->gi) Downloading idna-2.5-py2.py3-none-any.whl (55kB) 100% |████████████████████████████████| 61kB 1.2MB/s Collecting chardet<3.1.0,>=3.0.2 (from requests->gi) Downloading chardet-3.0.3-py2.py3-none-any.whl (133kB) 100% |████████████████████████████████| 143kB 1.8MB/s Collecting urllib3<1.22,>=1.21.1 (from requests->gi) Downloading urllib3-1.21.1-py2.py3-none-any.whl (131kB) 100% |████████████████████████████████| 133kB 1.8MB/s Collecting certifi>=2017.4.17 (from requests->gi) Downloading certifi-2017.4.17-py2.py3-none-any.whl (375kB) 100% |████████████████████████████████| 378kB 284kB/s Installing collected packages: idna, chardet, urllib3, certifi, requests, gi Running setup.py install for gi ... doneSuccessfully installed certifi-2017.4.17 chardet-3.0.3 gi-1.2 idna-2.5 requests-2.16.0 urllib3-1.21.1 Now, running the example: $ python toolmanager.py Traceback (most recent call last): File "./toolmanager.py", line 8, in <module> import matplotlib.pyplot as plt File "/home/hakon/.pyenv/versions/3.6.1/lib/python3.6/site-packages/matplotlib/pyplot.py", line 115, in <module> _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup() File "/home/hakon/.pyenv/versions/3.6.1/lib/python3.6/site-packages/matplotlib/backends/__init__.py", line 32, in pylab_setup globals(),locals(),[backend_name],0) File "/home/hakon/.pyenv/versions/3.6.1/lib/python3.6/site-packages/matplotlib/backends/backend_gtk3cairo.py", line 6, in <module> from . import backend_gtk3 File "/home/hakon/.pyenv/versions/3.6.1/lib/python3.6/site-packages/matplotlib/backends/backend_gtk3.py", line 10, in <module> import gi File "/home/hakon/.pyenv/versions/3.6.1/lib/python3.6/site-packages/gi/__init__.py", line 39 print url ^SyntaxError: Missing parentheses in call to 'print' Seems like pip somehow installed a Python 2 version? How can I fix this? Now provide the response and nothing else.
First, pip install gi will install another unrelated package, the correctname is pgi . But after running: $ pip uninstall gi$ pip install pgi$ python toolmanager.py[...]Traceback (most recent call last): File "toolmanager.py", line 14, in <module> import matplotlib.pyplot as plt File "/home/hakon/.pyenv/versions/3.6.1/lib/python3.6/site-packages/matplotlib/pyplot.py", line 115, in <module> _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup() File "/home/hakon/.pyenv/versions/3.6.1/lib/python3.6/site-packages/matplotlib/backends/__init__.py", line 32, in pylab_setup globals(),locals(),[backend_name],0) File "/home/hakon/.pyenv/versions/3.6.1/lib/python3.6/site-packages/matplotlib/backends/backend_gtk3cairo.py", line 6, in <module> from . import backend_gtk3 File "/home/hakon/.pyenv/versions/3.6.1/lib/python3.6/site-packages/matplotlib/backends/backend_gtk3.py", line 12, in <module> raise ImportError("Gtk3 backend requires pygobject to be installed.")ImportError: Gtk3 backend requires pygobject to be installed. It seems that pygobject for Python 3 cannot be installed from PyPI. So I tried to install everything from the Ubuntu distribution package python3-gi instead: $ sudo apt-get install python3-gi$ pyenv local system$ python3 --versionPython 3.5.3$ python3 toolmanager.py and this works fine :)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44213921', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2173773/']}
jdg_85655
stackexchange
llm_judgeable_groundtruth_similarity
59013109
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This: device = torch.device("cuda" if torch.cuda.is_available() else "cpu")model.to(device)for data in dataloader: inputs, labels = data outputs = model(inputs) Gives the error: RuntimeError: Input type (torch.FloatTensor) and weight type (torch.cuda.FloatTensor) should be the same Now provide the response and nothing else.
You get this error because your model is on the GPU, but your data is on the CPU. So, you need to send your input tensors to the GPU. inputs, labels = data # this is what you hadinputs, labels = inputs.cuda(), labels.cuda() # add this line Or like this, to stay consistent with the rest of your code: device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")inputs, labels = inputs.to(device), labels.to(device) The same error will be raised if your input tensors are on the GPU but your model weights aren't. In this case, you need to send your model weights to the GPU. model = MyModel()if torch.cuda.is_available(): model.cuda() See the documentation for cuda() , and its opposite, cpu() .
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/59013109', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10168730/']}
jdg_85656
stackexchange
llm_judgeable_groundtruth_similarity
669675
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 daemon I have written using Python. When it is running, it has a PID file located at /tmp/filename.pid. If the daemon isn't running then PID file doesn't exist. On Linux, how can I check to ensure that the PID file exists and if not, execute a command to restart it? The command would be python daemon.py restart which has to be executed from a specific directory. Now provide the response and nothing else.
[ -f /tmp/filename.pid ] || python daemon.py restart -f checks if the given path exists and is a regular file (just -e checks if the path exists) the [] perform the test and returns 0 on success, 1 otherwise the || is a C-like or , so if the command on the left fails, execute the command on the right. So the final statement says, if /tmp/filename.pid does NOT exist then start the daemon.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/669675', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2183/']}
jdg_85657
stackexchange
llm_judgeable_groundtruth_similarity
11498
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: We are given a matroid. Our goal is to find a set of elements of minimum size that has non-empty intersection with every base of the matroid. Is the problem studied before? Is it in P?For example, in a spanning tree matroid, the minimum hitting set should be a minimum cut. Thanks. Now provide the response and nothing else.
I meant to leave this as a comment, but I don't have the reputation to do so yet. This question was crossposted over at Mathoverflow, where I mention that the problem is NP-complete. See here . To avoid a contradiction with Chandra Chekuri's answer, I do not believe that the LP given in his answer is integral. To see this consider the uniform matroids $U_{k,n}$, where the bases are all $k$-subsets of a $n$-set. Note that the vector $(1/k, 1/k, \dots, 1/k)$ is a feasible solution to the LP. Thus, if $c$ is identically 1, then the minimum value of the LP is at most $n/k$. On the other hand, a minimum hitting for $U_{k,n}$ has size $n-k+1$.
{}
{'log_upvote_score': 4, 'links': ['https://cstheory.stackexchange.com/questions/11498', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/383/']}
jdg_85658
stackexchange
llm_judgeable_groundtruth_similarity
15955798
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Similar to this question: How to make ios App Store link with parameters? I am interested in passing parameters to the download link in the iOS app store. From what I've read, it seems that the parameters are only passed to the application if it was already installed, and the user tapped the smart app banner. What I want to do is pass parameters to the download link such that when a user downloads, the first time they open the app, the parameters will be passed. Mainly, I want to allow users to invite their friends to play my app through email or facebook and when the friend downloads using their link, it will send a push to the original player to notify that their friend now has the app. Thanks! Now provide the response and nothing else.
This is now easier with the coming iOS 9, because cookies can be shared between Safari and the in-app Safari View Controller! Simply keep a cookie in the browser and track the last link clicked on. Then when the user opens your app, open up an invisible Safari View Controller in the background while you show a spinner. As soon as you can inspect the cookie and see the last link clicked, you can stop the spinner--it should be a very fast operation. We offer this for no cost at Branch , where we've had a customizable web banner for some time. Now we're excited to incorporate the Safari View Controller into our open-source SDK! We also have a version of digital fingerprinting that allows you to do the same on pre-iOS 9 devices. We use IP address, OS, OS version and more to compare a click in a browser to an open in an app. This approach has pros and cons.. happy to go into further detail if you're interested.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15955798', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/800620/']}
jdg_85659
stackexchange
llm_judgeable_groundtruth_similarity
3931234
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 is taken from a text which tries to proves a relation between dimensions of subspaces. My first question comes from the canonical injections $in_1:M\to M\oplus N$ in line 3 and 4. My understanding of direct sum $M\oplus N$ is that, when we write down this notation, $M$ and $N$ must be independent, i.e., $M\cap N=0$ . But since $M$ and $N$ are two arbitrary subspaces as indicated in line 1 an 2, they are not necessarily independent. What does the author mean here? Does $\oplus$ mean something other than direct sum? Furthermore, If we assume $M\oplus N$ denotes direct sum, problems comes out immediately. In line 4, the author wrote injections $f:M\cap N\to M\oplus N$ If $M\cap N=0$ , then the function $f$ is just the trivial $0\to 0$ . So is the following $g$ . I believe this is not what the author intended to define. The second question arises from the third line if Lemma 2.14. I don't really know what that line of symbols and "a short exact sequence" in the subsequent line mean. Does that line of arrows mean something arcane in the circle of math? Of course, the question may due to I don't understand what $f$ means in the first place. I wish I could understand what the author wanted to say, after I have tried hard, so could you please help me understand all these stuff? Thanks a lot. Now provide the response and nothing else.
If $$\dots\to P_2\to P_1\to P_0 \to M\to0$$ is a projective resolution of $M$ as a module, then $\dots\to0\to M\to0\to\dots$ has a resolution (by projective chain complexes) in the category of chain complexes of the following form (I'll let you figure out the differentials): $\require{AMScd}$ \begin{CD}@.\vdots@.\vdots@.\vdots@.\vdots@.\vdots@.\vdots@.\\@.@VVV@VVV@VVV@VVV@VVV@VVV\\\cdots@>>>0@>>>P_2@>>>P_2\oplus P_1@>>>P_1\oplus P_0@>>> P_0@>>>0@>>>\cdots\\@.@VVV@VVV@VVV@VVV@VVV@VVV\\\cdots@>>>0@>>> P_1@>>>P_1\oplus P_0@>>>P_0@>>>0@>>>0@>>>\cdots\\@.@VVV@VVV@VVV@VVV@VVV@VVV\\\cdots@>>>0@>>>P_0@>>>P_0@>>>0@>>>0@>>>0@>>>\cdots\\@.@VVV@VVV@VVV@VVV@VVV@VVV\\\cdots@>>>0@>>>M@>>>0@>>>0@>>>0@>>>0@>>>\cdots\\@.@VVV@VVV@VVV@VVV@VVV@VVV\\@[email protected]@[email protected]@[email protected]\end{CD}
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3931234', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/308280/']}
jdg_85660
stackexchange
llm_judgeable_groundtruth_similarity
6214780
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Why should Android 3.0 fragments be used instead of compound controls? One can create a View inheritor or compound control once and use it everywhere. I've read http://android-developers.blogspot.com/2011/02/android-30-fragments-api.html but did not find the answer. Now provide the response and nothing else.
The difference is that fragments have a life cycle (onPause, onCreate, onStart...) of their own. By having a life cycle, fragments can respond independently to events, save their state through onSaveInstanceState, and be brought back (i.e. such as when resuming after an incoming call or when the user clicks the back button). The life cycle is summarized in the fragment documentation: https://developer.android.com/guide/components/fragments.html#Lifecycle You can always wrap a fragment or activity around a compound view, so just think of fragments as containers to your compound views that give them an independent life cycle.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6214780', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/781137/']}
jdg_85661
stackexchange
llm_judgeable_groundtruth_similarity
467930
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Evaluate the integral \begin{equation}\int\limits_{0}^{+\infty}\frac{dx}{1 + x^{1000}}\end{equation} I tried using the change of variable, integration by parts, even wolframalpha... Nothing helped. Theoretically speaking, it can be solved by using residue calculus, but we have 500 residues in the upper half-plane. I would be grateful for just a hint. Now provide the response and nothing else.
Consider the contour integral $$\oint_C \frac{dz}{1+z^{1000}}$$ where $C$ is a wedge having an outer circular arc of radius $R$ in the 1st quadrant of the complex plane (real, imaginary both positive), and having an angle $\pi/500$. Then there is only one pole inside $C$ at $z=e^{i \pi/1000}$, and we have by the residue theorem $$\left (1-e^{i \pi/500}\right) \int_0^{\infty} \frac{dx}{1+x^{1000}} = i 2 \pi \frac{1}{1000 e^{i 999 \pi/1000}} = -i \frac{\pi}{500} e^{i \pi/1000}$$ because the integral along the outer circular arc vanishes as $R \to \infty$. Then we may write the integral as $$\int_0^{\infty} \frac{dx}{1+x^{1000}} = \frac{\pi/1000}{\sin{(\pi/1000)}}$$ ADDENDUM Why does the integral vanish along the arc? Consider $$\oint_C \frac{dz}{1+z^{1000}} = \int_0^{R} \frac{dx}{1+x^{1000}} + i R \int_0^{\pi/500} d\theta \, e^{i \theta} \frac{1}{1+R^{1000} e^{i 1000 \theta}} + \\ e^{i \pi/500} \int_R^0 \frac{dt}{1+t^{1000} e^{i 1000 \pi/500}}$$ Note that, as $R\to\infty$, the second integral on the RHS has a magnitude that is bounded by $$\frac{\pi/500}{R^{999}}$$ which clearly vanishes as $R\to\infty$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/467930', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_85662
stackexchange
llm_judgeable_groundtruth_similarity
5224881
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 table in a Rails app with hundreds of thousands of records, and they only have a created_at timestamp. I'm adding the ability to edit these records, so I want to add an updated_at timestamp to the table. In my migration to add the column, I want to update all rows to have the new updated_at match the old created_at , since that's the default for newly created rows in Rails. I could do a find(:all) and iterate through the records, but that would take hours because of the size of the table. What I really want to do is: UPDATE table_name SET updated_at = created_at; Is there a nicer way to do that in a Rails migration using ActiveRecord rather than executing raw SQL? Now provide the response and nothing else.
I would create a migration rails g migration set_updated_at_values and inside it write something like: class SetUpdatedAt < ActiveRecord::Migration def self.up Yourmodel.update_all("updated_at=created_at") end def self.down endend This way you achieve two things this is a repeatable process, with each possible deploy (where needed) it is executed this is efficient. I can't think of a more rubyesque solution (that is as efficient). Note: you could also run raw sql inside a migration, if the query gets too hard to write using activerecord. Just write the following: Yourmodel.connection.execute("update your_models set ... <complicated query> ...")
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/5224881', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/318760/']}
jdg_85663
stackexchange
llm_judgeable_groundtruth_similarity
2562315
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Consider the following base code: (function($) { $.fn.myPlugin = function(settings) { return this.each(function() { //whatever }); };}); The plugin returns a jQuery object. The question is how am I supposed to write a plugin that returns a custom object so that I can do something like this: var api = $('div.myelement').myPlugin();api.onMyEventName(function(e, whateverParam) { //whatever}); It'd be highly appreciated if you could write some lines of code that describes me how to do that, how to call the onMyEventName function on a custom api object... Thanks. Now provide the response and nothing else.
(function($) { function MyApi($this, settings) { this.$this = $this; this.settings = settings; }; MyApi.prototype.output = function (val) { // use this.$this to access the original jQuery object return this.settings[val]; }; $.fn.myPlugin = function(settings) { return new MyApi(this, settings); };}); Note that we've passed this from $.fn.myPlugin() into the MyApi constructor; this allows you to access the jQuery object that myPlugin() was originally called on within MyApi methods. You can also do the same using the object literal syntax: (function($) { $.fn.myPlugin = function(settings) { return { settings: settings, output: function (val) { // use this.$this to access the original jQuery object return this.settings[val]; }, $this: this }; };}); Then; var something = $('#something').myPlugin({ val: 'Lemon'});alert(something.output('val')); // Lemon ... again, we've captured the value of this (the jQuery object) into a property $this on the newly constructed objected, to gain access to the original jQuery object.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2562315', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/307102/']}
jdg_85664
stackexchange
llm_judgeable_groundtruth_similarity
45744569
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I need to download chart data from poloniex rest client with multiple options using bash only. I tried getopts but couldn't really find a way to use mutliple options with multiple parameters. here is what I want to achieve ./getdata.sh -c currency1 currency2 ... -p period1 period2 ... having the arguments I need to call wget for c x p times for currency in c for period in p wget https://poloniex.com/public?command=returnChartData&currencyPair=BTC_{$currency}&start=1405699200&end=9999999999&period={$period} well I am explicitly writing my ultimate goal as probably many others looking for it nowadays. Now provide the response and nothing else.
Could something like this work for you? #!/bin/bashwhile getopts ":a:p:" opt; do case $opt in a) arg1="$OPTARG" ;; p) arg2="$OPTARG" ;; \?) echo "Invalid option -$OPTARG" >&2 ;; esacdoneprintf "Argument 1 is %s\n" "$arg1"printf "Argument 2 is %s\n" "$arg2" You can then call your script like this: ./script.sh -p 'world' -a 'hello' The output for the above will be: Argument 1 is helloArgument 2 is world Update You can use the same option multiple times. When parsing the argument values, you can then add them to an array. #!/bin/bashwhile getopts "c:" opt; do case $opt in c) currs+=("$OPTARG");; #... esacdoneshift $((OPTIND -1))for cur in "${currs[@]}"; do echo "$cur"done You can then call your script as follows: ./script.sh -c USD -c CAD The output will be: USDCAD Reference: BASH: getopts retrieving multiple variables from one flag
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45744569', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/944768/']}
jdg_85665
stackexchange
llm_judgeable_groundtruth_similarity
10334901
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using an IntentService to handle network communications with a server via JSON. The JSON/server part is working fine, but I'm having trouble getting the results back where they are needed. The following code shows how I am starting the intent service from inside onClick(), and then having the service update a global variable to relay the results back to the main activity. public class GXActivity extends Activity { private static final String TAG = "GXActivity"; @Override public void onCreate(Bundle savedInstanceState) { // === called when the activity is first created Log.i(TAG, "GXActivity Created"); super.onCreate(savedInstanceState); setContentView(R.layout.start); View.OnClickListener handler = new View.OnClickListener() { public void onClick(View v) { // === set up an application context to hold a global variable // === called user, to contain results from the intent service GXApp appState = ((GXApp) getApplicationContext()); User user = new User(-1); // initialize user id to -1 appState.setUser(user); // === next start an intent service to get JSON from the server; // === this service updates the user global variable with // === results from the JSON transaction Intent intent = new Intent(this, GXIntentService.class); startService(intent); // === check app context for results from intent service appState = ((GXApp) getApplicationContext()); if (appState.getUser().getId() != -1)... } } }} The problem I'm having is that the intent service that parses the JSON doesn't get invoked until after onCreate() completes, so my code that's looking for the results is stuck looking at uninitialized results. What should I do differently so the intent service gets called before I check the results? Would it work if I pulled the click listener out of the onCreate() function? Is there a another/better to structure this code? Many thanks. Now provide the response and nothing else.
You should look at creating your own ResultReceiver subclass in your activity. ResultReceiver implements Parcelable so can be passed from your Activity to your Service as an extra on the Intent . You'll need to do something like this: Implement a subclass of ResultReceiver within your activity class. The key method to implement is onReceiveResult() . This method provides you a with Bundle of result data which can be used to pass whatever information you are retrieving in your Service . Simply unpack the data you need and use it to update your activity. In your activity, create a new instance of your custom ResultReceiver and add it to the Intent you use to start your service. In your Service 's onStartCommand() method, retrieve the ResultReceiver passed in on the Intent and store it in a local member variable. Once your Service completes its work, have it call send() on the ResultReceiver passing whatever data you want to send back to the activity in a Bundle . This is a pretty effective pattern and means you're not storing data in nasty static variables.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/10334901', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1322527/']}
jdg_85666
stackexchange
llm_judgeable_groundtruth_similarity
9796174
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 Usercontrol(TabUserControl) which contains a TabControl. The Viewmodel of that UserControl loads ab Observable collection of TabItems. One od those items is another user control. When I just load text in the tabcontrol there is no problem, but how can I load the other user control into the tabitem of the TabUserControl.I'm using MVVM. Here's my code: public class TabItem{ public string Header { get; set; } public object Content { get; set; } // object to allow all sort of items??} The Viewmodel of the TabUserControl public class TabViewModel{ public ObservableCollection<TabItem> Tabs {get;set;} public TabViewModel() { Tabs = new ObservableCollection<TabItem>(); //Tabs.Add(new TabItem { Header = "Overview", Content = new OverviewViewModel() }); How to load a usercontrol here if it's in the ItemCollection? Tabs.Add(new TabItem { Header = "Overview", Content = "Bla bla bla" }); Tabs.Add(new TabItem { Header = "Two", Content = "Two's content" }); }} And then the TabControl XAML: <TabControl x:Name="_tabControl" ItemsSource="{Binding Tabs}"> <TabControl.ItemContainerStyle> <Style TargetType="TabItem"> <Setter Property="Header" Value="{Binding Header}" /> <Setter Property="Content" Value="{Binding Content}" /> </Style> </TabControl.ItemContainerStyle></TabControl> It works as long as I dont load the viewmodel of the usercontrol in the tabItems collection. how can I make the UserTabControl load on to the TabItem?The intention is that every tabitem will contain a usercontrol. Each usercontrol then does it's own thing. Hope someone can help me as I am a WPF beginner.Thx! Now provide the response and nothing else.
Ideally, the TabControl.ItemsSource should be set to a collection of ViewModels , and DataTemplates should be used to tell the WPF to draw each ViewModel with a specific UserControl . This keeps between your business logic ( ViewModels ) completely separate from your UI ( Views ) For example, <TabControl x:Name="MyTabControl" ItemsSource="{Binding TabViewModels}" SelectedItem="{Binding SelectedTabViewModel}"> <TabControl.Resources> <DataTemplate DataType="{x:Type my:ViewModelA}"> <my:ViewAUserControl /> </DataTemplate> <DataTemplate DataType="{x:Type my:ViewModelB}"> <my:ViewBUserControl /> </DataTemplate> <DataTemplate DataType="{x:Type my:ViewModelC}"> <my:ViewCUserControl /> </DataTemplate> </TabControl.Resources> <TabControl.ItemContainerStyle> <Style TargetType="TabItem"> <Setter Property="Header" Value="{Binding Header}" /> </Style> </TabControl.ItemContainerStyle></TabControl> ViewModel containing TabControl's DataContext: TabViewModels = new ObservableCollection<ITabViewModel>();TabViewModels.Add(new ViewModelA { Header = "Tab A" });TabViewModels.Add(new ViewModelB { Header = "Tab B" });TabViewModels.Add(new ViewModelC { Header = "Tab C" });SelectedTabViewModel = TabViewModels[0];
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9796174', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/731127/']}
jdg_85667
stackexchange
llm_judgeable_groundtruth_similarity
54891965
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Recently I started to learn sklearn, numpy and pandas and I made a function for multivariate linear regression. Im wondering, is it possible to make multivariate polynomial regression? This is my code for multivariate polynomial regression, it shows this error: in check_consistent_length " samples: %r" % [int(l) for l in lengths])ValueError: Found input variables with inconsistent numbers of samples: [8, 3] Do you know whats the problem? import numpy as npimport pandas as pdimport xlrdfrom sklearn import linear_modelfrom sklearn.model_selection import train_test_splitdef polynomial_prediction_of_future_strenght(input_data, cement, blast_fur_slug,fly_ash, water, superpl, coarse_aggr, fine_aggr, days): variables = prediction_accuracy(input_data)[4] results = prediction_accuracy(input_data)[5] var_train, var_test, res_train, res_test = train_test_split(variables, results, test_size = 0.3, random_state = 4) Poly_Regression = PolynomialFeatures(degree=2) poly_var_train = Poly_Regression.fit_transform(var_train) poly_var_test = Poly_Regression.fit_transform(var_test) input_values = [cement, blast_fur_slug, fly_ash, water, superpl, coarse_aggr, fine_aggr, days] regression = linear_model.LinearRegression() model = regression.fit(poly_var_train, res_train) predicted_strenght = regression.predict([input_values]) predicted_strenght = round(predicted_strenght[0], 2) score = model.score(poly_var_test, res_test) score = round(score*100, 2) print(prediction, score)a = polynomial_prediction_of_future_strenght(data_less_than_28days, 260.9, 100.5, 78.3, 200.6, 8.6, 864.5, 761.5, 28) Now provide the response and nothing else.
You can transform your features to polynomial using this sklearn module and then use these features in your linear regression model. from sklearn.preprocessing import PolynomialFeaturesfrom sklearn import linear_modelpoly = PolynomialFeatures(degree=2)poly_variables = poly.fit_transform(variables)poly_var_train, poly_var_test, res_train, res_test = train_test_split(poly_variables, results, test_size = 0.3, random_state = 4)regression = linear_model.LinearRegression()model = regression.fit(poly_var_train, res_train)score = model.score(poly_var_test, res_test) Also, in your code you are training your model on the entire dataset and then you split it into train and test. This means that your model has already seen your test data while training. You need to split first, then train your model only on training data and then test the score on the test set. I have included these changes as well. :)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/54891965', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9749124/']}
jdg_85668
stackexchange
llm_judgeable_groundtruth_similarity
295174
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'm working on C# code where a static method of an abstract base class is being overridden by the class that inherits the base class. Why is this being done? I thought that only a virtual method of an abstract base class should be overridden. What purpose does it serve to make the base method static, or is it the case that what I'm encountering is a suboptimal or incorrect practice? The code is allowed by the compiler. My understanding is that a static method allows the method to be called without the encompassing type being instantiated as an object. I've only used static methods previously in static classes, and I've viewed abstract classes as simply being inheritable classes that aren't supposed to be instantiated. In this case, I wouldn't expect a static method of the abstract class to be overrideable but made virtual, as a virtual method could still contain a default implementation, and I would think that a virtual method better hides the implementation details. Now provide the response and nothing else.
Overloading of static methods should not be compared to overriding of instance methods. They are fundamentally different concepts. Overriding is when implementations of a virtual method are selected at runtime based on the instance. Overloading is when one of multiple methods with the same name are selected at compile time . Overriding is a fundamental feature of object oriented polymorphism, while overloading is more like a convenience. On the surface, overloading static methods may look like overriding. If the compiler does not find a static method in the specified class, it looks up in the inheritance hierarchy until a matching method is found. The important difference is that the method is resolved and fixed at compile time. This is why you cannot mark static methods as virtual or override (or new ) since this is not real overriding. Overriding should conform to the LSP (Liskov substitution principle) and more generally the behavior of an overriding method should conform to the contract of the virtual method. Overloaded static methods does not have such constraints, and should really be though of as distinct methods which just happen to have the same name.
{}
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/295174', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/194077/']}
jdg_85669
stackexchange
llm_judgeable_groundtruth_similarity
3843060
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This isn't a case-sensitive comparison in LINQ to Entities: Thingies.First(t => t.Name == "ThingamaBob"); How can I achieve case sensitive comparison with LINQ to Entities? Now provide the response and nothing else.
That's because you are using LINQ To Entities which is ultimately convert your Lambda expressions into SQL statements. That means the case sensitivity is at the mercy of your SQL Server which by default has SQL_Latin1_General_CP1_CI_AS Collation and that is NOT case sensitive. Using ObjectQuery.ToTraceString to see the generated SQL query that has been actually submitted to SQL Server reveals the mystery: string sqlQuery = ((ObjectQuery)context.Thingies .Where(t => t.Name == "ThingamaBob")).ToTraceString(); When you create a LINQ to Entities query, LINQ to Entities leverages the LINQ parser to begin processing the query and converts it into a LINQ expression tree. The LINQ expression tree is then passed to Object Services API, which converts the expression tree to a command tree. It is then sent to the store provider (e.g. SqlClient), which convert the command tree into the native database command text. Query get executed on the data store and the results are Materialized into Entity Objects by Object Services . No logic has been put in between to take case sensitivity into account. So no matter what case you put in your predicate, it will always treat as the same by your SQL Server unless you change your SQL Server Collates for that column. Server side solution: Therefore, the best solution would be to change the collation of the Name column in the Thingies table to COLLATE Latin1_General_CS_AS which is case sensitive by running this on your SQL Server: ALTER TABLE ThingiesALTER COLUMN Name VARCHAR(25)COLLATE Latin1_General_CS_AS For more information on the SQL Server Collates , take a a look at SQL SERVER Collate Case Sensitive SQL Query Search Client-side solution: The only solution that you can apply on client side is to use LINQ to Objects to do yet another comparison which doesn't seem to be very elegant: Thingies.Where(t => t.Name == "ThingamaBob") .AsEnumerable() .First(t => t.Name == "ThingamaBob");
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/3843060', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/64334/']}
jdg_85670
stackexchange
llm_judgeable_groundtruth_similarity
2574016
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How does a T9 dictionary work? What is the data structure behind it. If we type '4663' we get 'good' when we press down button we get 'gone' then 'home' etc... EDIT: If the user types in 46 then it should show 'go' and when pressed down arrow should show 'gone' etc... Now provide the response and nothing else.
It can be implemented in several ways, one of them is Trie . The route is represented by the digits and the nodes point to collection of words. It can be implemented using nested hash tables as well, the key of the hash table is a letter and on every digit the algorithm calculates all possible routes (O(3^n) routes).
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2574016', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/271784/']}
jdg_85671
stackexchange
llm_judgeable_groundtruth_similarity
11874096
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 file which stores many JavaScript objects in JSON form and I need to read the file, create each of the objects, and do something with them (insert them into a db in my case). The JavaScript objects can be represented a format: Format A: [{name: 'thing1'},....{name: 'thing999999999'}] or Format B: {name: 'thing1'} // <== My choice....{name: 'thing999999999'} Note that the ... indicates a lot of JSON objects. I am aware I could read the entire file into memory and then use JSON.parse() like this: fs.readFile(filePath, 'utf-8', function (err, fileContents) { if (err) throw err; console.log(JSON.parse(fileContents));}); However, the file could be really large, I would prefer to use a stream to accomplish this. The problem I see with a stream is that the file contents could be broken into data chunks at any point, so how can I use JSON.parse() on such objects? Ideally, each object would be read as a separate data chunk, but I am not sure on how to do that . var importStream = fs.createReadStream(filePath, {flags: 'r', encoding: 'utf-8'});importStream.on('data', function(chunk) { var pleaseBeAJSObject = JSON.parse(chunk); // insert pleaseBeAJSObject in a database});importStream.on('end', function(item) { console.log("Woot, imported objects into the database!");});*/ Note, I wish to prevent reading the entire file into memory. Time efficiency does not matter to me. Yes, I could try to read a number of objects at once and insert them all at once, but that's a performance tweak - I need a way that is guaranteed not to cause a memory overload, not matter how many objects are contained in the file. I can choose to use FormatA or FormatB or maybe something else, just please specify in your answer. Thanks! Now provide the response and nothing else.
To process a file line-by-line, you simply need to decouple the reading of the file and the code that acts upon that input. You can accomplish this by buffering your input until you hit a newline. Assuming we have one JSON object per line (basically, format B): var stream = fs.createReadStream(filePath, {flags: 'r', encoding: 'utf-8'});var buf = '';stream.on('data', function(d) { buf += d.toString(); // when data is read, stash it in a string buffer pump(); // then process the buffer});function pump() { var pos; while ((pos = buf.indexOf('\n')) >= 0) { // keep going while there's a newline somewhere in the buffer if (pos == 0) { // if there's more than one newline in a row, the buffer will now start with a newline buf = buf.slice(1); // discard it continue; // so that the next iteration will start with data } processLine(buf.slice(0,pos)); // hand off the line buf = buf.slice(pos+1); // and slice the processed data off the buffer }}function processLine(line) { // here's where we do something with a line if (line[line.length-1] == '\r') line=line.substr(0,line.length-1); // discard CR (0x0D) if (line.length > 0) { // ignore empty lines var obj = JSON.parse(line); // parse the JSON console.log(obj); // do something with the data here! }} Each time the file stream receives data from the file system, it's stashed in a buffer, and then pump is called. If there's no newline in the buffer, pump simply returns without doing anything. More data (and potentially a newline) will be added to the buffer the next time the stream gets data, and then we'll have a complete object. If there is a newline, pump slices off the buffer from the beginning to the newline and hands it off to process . It then checks again if there's another newline in the buffer (the while loop). In this way, we can process all of the lines that were read in the current chunk. Finally, process is called once per input line. If present, it strips off the carriage return character (to avoid issues with line endings – LF vs CRLF), and then calls JSON.parse one the line. At this point, you can do whatever you need to with your object. Note that JSON.parse is strict about what it accepts as input; you must quote your identifiers and string values with double quotes . In other words, {name:'thing1'} will throw an error; you must use {"name":"thing1"} . Because no more than a chunk of data will ever be in memory at a time, this will be extremely memory efficient. It will also be extremely fast. A quick test showed I processed 10,000 rows in under 15ms.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/11874096', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1141692/']}
jdg_85672
stackexchange
llm_judgeable_groundtruth_similarity
15319967
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: PHP has a decimal type, which doesn't have the "inaccuracy" of floats and doubles, so that 2.5 + 2.5 = 5 and not 4.999999999978325 or something like that. So I wonder if there is such a data type implementation for C or C++? Now provide the response and nothing else.
The Boost.Multiprecision library has a decimal based floating point template class called cpp_dec_float , for which you can specify any precision you want. #include <iostream>#include <iomanip>#include <boost/multiprecision/cpp_dec_float.hpp>int main(){ namespace mp = boost::multiprecision; // here I'm using a predefined type that stores 100 digits, // but you can create custom types very easily with any level // of precision you want. typedef mp::cpp_dec_float_100 decimal; decimal tiny("0.0000000000000000000000000000000000000000000001"); decimal huge("100000000000000000000000000000000000000000000000"); decimal a = tiny; while (a != huge) { std::cout.precision(100); std::cout << std::fixed << a << '\n'; a *= 10; } }
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15319967', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/991484/']}
jdg_85673
stackexchange
llm_judgeable_groundtruth_similarity
1826711
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 an extension method that needs to return non-vowel words.I designed public static IEnumerable<T> NonVowelWords<T>(this IEnumerable<T> word) { return word.Any(w => w.Contains("aeiou")); } I received error as "T" does not contain extanesion method "Contains". Now provide the response and nothing else.
You don't need to use a generic method if you're always dealing with strings. public static IEnumerable<string> NonVowelWords(this IEnumerable<string> words){ char[] vowels = { 'a', 'e', 'i', 'o', 'u' }; return words.Where(w => w.IndexOfAny(vowels) == -1);}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1826711', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/215675/']}
jdg_85674
stackexchange
llm_judgeable_groundtruth_similarity
271944
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Let $v_q(n,r)=\sum_{i=0}^r \binom{n}i (q-1)^i$ denote a number of points in a ball of radius $r$ in the Hamming metric on the cube $\Sigma^n$, where $|\Sigma|=q$. What is the maximal number of points in $\Sigma^n$ with mutual distances at least $d$ (later: $d$-distant point sets)? Gilbert 's bound says that we may find $M$ such points if $(M-1)\cdot v_q(n,d-1)< q^n$: add points one by one, while we have less than $M$ points, the $(d-1)$-balls centered at them do not cover $\Sigma^n$ and we may add another point. If $q$ is a power of prime, Varshamov 's bound improves the previous result by claiming that we may find $q^k$ $d$-distant points whenever $q^{k-1}v_q(n,d-1)<q^n$. For the proof, we identify $\Sigma$ with a finite field and consider the maximal subspace $X$ of $\Sigma^n$ into which all points are $d$-distant. If $\dim X\geqslant k$, we are done, else there exists a point $v$ not covered by $(d-1)$-balls centered at elements of $X$, and the span of $X$ and $v$ is larger $d$-distant subspace. My question is: is Varshamov's bound true if we do not require that $q$ is a prime power (say, for $q=6$)? This often happens and always does astonish me when arithmetical properties like being prime powers are crucial for purely combinatorial or topological claims, and I wonder what is the situation in this particular case. Now provide the response and nothing else.
The analogue of the Varshamov inequality need not hold for instance for $\lvert\Sigma\rvert=q=6$: For $n=4$ and $d=3$ it would give a code $C\subseteq\Sigma^4$ with $d(C)\ge3$ and $\lvert C\rvert=36$. But such a code gives a pair of orthogonal Latin squares of order $6$, which is known not to exist (by Tarry's negative answer to Euler's thirty-six officers problem ). (The construction of the orthogonal pair $A,B$ is as follows: Since $d(C)\ge3$, the map $C\to\Sigma^2$, $(i,j,a,b)\mapsto(i,j)$ is bijective. For $(i,j,a,b)\in C$ let $A$ and $B$ have entry $a$ and $b$ in the $i$-th row and $j$-th column, respectively.)
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/271944', 'https://mathoverflow.net', 'https://mathoverflow.net/users/4312/']}
jdg_85675
stackexchange
llm_judgeable_groundtruth_similarity
1438
Below is a question asked on the forum raspberrypi.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have to admit, the research that I've done suggests that it is not possible to do this (and that it is more complicated than originally thought). The Raspberry Pi outputs HDMI, and iMacs (at least those from mid-2010) do not accept HDMI inputs -- they only accept Mini DisplayPort inputs, which typically come from other Apple products. As far as I'm aware, HDMI and Mini DisplayPort are incompatible formats, and the only way to get from HDMI to DisplayPort is to use a bulky, expensive converter . You cannot do this with a passive adapter; however, if you want to go in the other direction (e.g. use the iMac as an output device by connecting a DisplayPort on your iMac to a HDMI television) then this is possible, quite cheaply . Basically, the iMac can be a HDMI output device, but not a HDMI input device. Is this the case? And if so, does anyone know a workaround (that doesn't involve spending £150 on a Kanex XD)? Now provide the response and nothing else.
You can start a GUI on the host machine, in this case your Mac, over SSH. This is only two steps, three if you count setup. Before you do anything you need to install and configure SSH on your machine. You need to be able to ssh into the Raspberry Pi via your Mac. Now you have to SSH into the Raspberry Pi. This can be accomplished like so. $ ssh -X username@hostname NOTE You need to use the -X flag. This enables X11 port forwarding allowing you to view the GUI on your Mac. Make sure that you use the uppercase version and not -x as the lowercase version disables X11 port forwarding. Now you need to use exec to start your window manager. For example, in order to start LXDE you would run the following command. $ exec startlxde What should happen is that you should see the Raspberry Pi's screen on your Mac. Now you should be able to control the Raspberry Pi via your Mac and see what is on your Raspberry Pi's screen. References Get RaspberryPi display on iMac
{}
{'log_upvote_score': 5, 'links': ['https://raspberrypi.stackexchange.com/questions/1438', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/955/']}
jdg_85676
stackexchange
llm_judgeable_groundtruth_similarity
19876993
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 my own module in python 2.7. It resides in ~/Development/.../myModule instead of /usr/lib/python2.7/dist-packages or /usr/lib/python2.7/site-packages . The internal structure is: /project-root-dir /server __init__.py service.py http.py /client __init__.py client.py client/client.py includes PyCachedClient class. I'm having import problems: project-root-dir$ pythonPython 2.7.2+ (default, Jul 20 2012, 22:12:53) [GCC 4.6.1] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> from server import httpTraceback (most recent call last): File "<stdin>", line 1, in <module> File "server/http.py", line 9, in <module> from client import PyCachedClientImportError: cannot import name PyCachedClient I didn't set PythonPath to include my project-root-dir , therefore when server.http tries to include client.PyCachedClient, it tries to load it from relative path and fails. My question is - how should I set all paths/settings in a good, pythonic way? I know I can run export PYTHONPATH=... in shell each time I open a console and try to run my server, but I guess it's not the best way. If my module was installed via PyPi (or something similar), I'd have it installed in /usr/lib/python... path and it'd be loaded automatically. I'd appreciate tips on best practices in python module development. Now provide the response and nothing else.
My Python development workflow This is a basic process to develop Python packages that incorporates what I believe to be the best practices in the community. It's basic - if you're really serious about developing Python packages, there still a bit more to it, and everyone has their own preferences, but it should serve as a template to get started and then learn more about the pieces involved. The basic steps are: Use virtualenv for isolation setuptools for creating a installable package and manage dependencies python setup.py develop to install that package in development mode virtualenv First, I would recommend using virtualenv to get an isolated environment to develop your package(s) in. During development, you will need to install, upgrade, downgrade and uninstall dependencies of your package, and you don't want your development dependencies to pollute your system-wide site-packages your system-wide site-packages to influence your development environment version conflicts Polluting your system-wide site-packages is bad, because any package you install there will be available to all Python applications you installed that use the system Python, even though you just needed that dependency for your small project. And it was just installed in a new version that overrode the one in the system wide site-packages , and is incompatible with ${important_app} that depends on it. You get the idea. Having your system wide site-packages influence your development environment is bad, because maybe your project depends on a module you already got in the system Python's site-packages . So you forget to properly declare that your project depends on that module, but everything works because it's always there on your local development box. Until you release your package and people try to install it, or push it to production, etc... Developing in a clean environment forces you to properly declare your dependencies. So, a virtualenv is an isolated environment with its own Python interpreter and module search path. It's based on a Python installation you previously installed, but isolated from it. To create a virtualenv, install the virtualenv package by installing it to your system wide Python using easy_install or pip : sudo pip install virtualenv Notice this will be the only time you install something as root (using sudo), into your global site-packages. Everything after this will happen inside the virtualenv you're about to create. Now create a virtualenv for developing your package: cd ~/pyprojectsvirtualenv --no-site-packages foobar-env This will create a directory tree ~/pyprojects/foobar-env , which is your virtualenv. To activate the virtualenv, cd into it and source the bin/activate script : ~/pyprojects $ cd foobar-env/~/pyprojects/foobar-env $ . bin/activate(foobar-env) ~/pyprojects/foobar-env $ Note the leading dot . , that's shorthand for the source shell command. Also note how the prompt changes: (foobar-env) means your inside the activated virtualenv (and always will need to be for the isolation to work). So activate your env every time you open a new terminal tab or SSH session etc.. If you now run python in that activated env, it will actually use ~/pyprojects/foobar-env/bin/python as the interpreter, with its own site-packages and isolated module search path. A setuptools package Now for creating your package. Basically you'll want a setuptools package with a setup.py to properly declare your package's metadata and dependencies. You can do this on your own by by following the setuptools documentation , or create a package skeletion using Paster templates . To use Paster templates, install PasteScript into your virtualenv: pip install PasteScript Let's create a source directory for our new package to keep things organized (maybe you'll want to split up your project into several packages, or later use dependencies from source): mkdir srccd src/ Now for creating your package, do paster create -t basic_package foobar and answer all the questions in the interactive interface. Most are optional and can simply be left at the default by pressing ENTER. This will create a package (or more precisely, a setuptools distribution) called foobar . This is the name that people will use to install your package using easy_install or pip install foobar the name other packages will use to depend on yours in setup.py what it will be called on PyPi Inside, you almost always create a Python package (as in "a directory with an __init__.py ) that's called the same. That's not required, the name of the top level Python package can be any valid package name, but it's a common convention to name it the same as the distribution. And that's why it's important, but not always easy, to keep the two apart. Because the top level python package name is what people (or you) will use to import your package using import foobar or from foobar import baz So if you used the paster template, it will already have created that directory for you: cd foobar/foobar/ Now create your code: vim models.py models.py class Page(object): """A dumb object wrapping a webpage. """ def __init__(self, content, url): self.content = content self.original_url = url def __repr__(self): return "<Page retrieved from '%s' (%s bytes)>" % (self.original_url, len(self.content)) And a client.py in the same directory that uses models.py : client.py import requestsfrom foobar.models import Pageurl = 'http://www.stackoverflow.com'response = requests.get(url)page = Page(response.content, url)print page Declare the dependency on the requests module in setup.py : install_requires=[ # -*- Extra requirements: -*- 'setuptools', 'requests', ], Version control src/foobar/ is the directory you'll now want to put under version control: cd src/foobar/git initvim .gitignore .gitignore *.egg-info*.py[co] git add .git commit -m 'Create initial package structure. Installing your package as a development egg Now it's time to install your package in development mode: python setup.py develop This will install the requests dependency and your package as a development egg. So it's linked into your virtualenv's site-packages, but still lives at src/foobar where you can make changes and have them be immediately active in the virtualenv without re-installing your package. Now for your original question, importing using relative paths: My advice is, don't do it. Now that you've got a proper setuptools package, that's installed and importable, your current working directory shouldn't matter any more. Just do from foobar.models import Page or similar, declaring the fully qualified name where that object lives. That makes your source code much more readable and discoverable, for yourself and other people that read your code. You can now run your code by doing python client.py from anywhere inside your activated virtualenv. python src/foobar/foobar/client.py works just as fine, your package is properly installed and your working directory doesn't matter any more. If you want to go one step further, you can even create a setuptools entry point for your CLI scripts. This will create a bin/something script in your virtualenv that you can run from the shell. setuptools console_scripts entry point setup.py entry_points=''' # -*- Entry points: -*- [console_scripts] run-fooobar = foobar.main:run_foobar ''', client.py def run_client(): # ... main.py from foobar.client import run_clientdef run_foobar(): run_client() Re-install your package to activate the entry point: python setup.py develop And there you go, bin/run-foo . Once you (or someone else) installs your package for real, outside the virtualenv, the entry point will be in /usr/local/bin/run-foo or somewhere simiar, where it will automatically be in $PATH . Further steps Creating a release of your package and uploading it PyPi, for example using zest.releaser Keeping a changelog and versioning your package Learn about declaring dependencies Learn about Differences between distribute, distutils, setuptools and distutils2 Suggested reading: The Hitchhiker’s Guide to Packaging The pip cookbook
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19876993', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/769384/']}
jdg_85677
stackexchange
llm_judgeable_groundtruth_similarity
55830575
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 Flutter app and I'm testing Google Analytics for Firebase on Flutter. I wanted to see the routes our users (well, me for now) are visiting. I followed the setup steps in firebase_analytics and I checked their example app, too. I enabled debugging for Analytics as described in the Debug View docs Unfortunately, the only two kinds of screen views ( firebase_screen_class ) I receive in my Analytics Debug view are Flutter and MainActivity . I'd expect to see /example-1 , /example-2 and /welcome somewhere, but I don't. This is the app I'm running in Flutter class App extends StatelessWidget { final FirebaseAnalytics analytics = FirebaseAnalytics(); @override Widget build(BuildContext context) { return MaterialApp( routes: <String, WidgetBuilder>{ '/example-1': (_) => Example1(), '/example-2': (_) => Example2(), '/welcome': (_) => Welcome(), }, home: Welcome(), navigatorObservers: [FirebaseAnalyticsObserver(analytics: analytics)], ); }} Now provide the response and nothing else.
This exact use-case is in the documentation for Firebase Analytics under the Track Screenviews section. Manually tracking screens is useful if your app does not use a separate UIViewController or Activity for each screen you may wish to track, such as in a game. This is exactly the case with Flutter, as Flutter is taking care of the screen updates: most simple Flutter apps run one single FlutterActivity / FlutterAppDelegate and it takes care of rendering different screens on its own, so letting Firebase Analytics automatically track screens will not bring the desired effect. As far as my past experience goes, the FirebaseAnalyticsObserver was not very helpful, however, I recommend you, too, check their docs again , they do imply that things should "just work". My best guess is that it didn't work well for me because I didn't use RouteSettings on any of my routes * . In case FirebaseAnalyticsObserver won't work or apply for your app, the next approach worked quite well for me over the past months of development. You can set the current screen with FirebaseAnalytics at any point, if you call the setCurrentScreen method with the screen name: import 'package:firebase_analytics/firebase_analytics.dart';// Somewhere in your widgets...FirebaseAnalytics().setCurrentScreen(screenName: 'Example1'); As a first attempt I did this in the widget constructor, but that will not work well and miscount the events: if you pop or push routes, all widget constructors in the stack will be called, even though only the top route really qualifies as "the current screen". To solve this, we need to use the RouteAware class and only set the current screen in case it's the top route: either our route is added to the stack or the previous top route was popped and we arrived onto the route. RouteAware comes with boilerplate code and we don't want to repeat that boilerplate for all of our screens. Even for small apps, you have tens of different screens, so I created the RouteAwareAnalytics mixin: import 'package:firebase_analytics/firebase_analytics.dart';import 'package:flutter/widgets.dart';// A Navigator observer that notifies RouteAwares of changes to state of their Routefinal routeObserver = RouteObserver<PageRoute>();mixin RouteAwareAnalytics<T extends StatefulWidget> on State<T> implements RouteAware { AnalyticsRoute get route; @override void didChangeDependencies() { routeObserver.subscribe(this, ModalRoute.of(context)); super.didChangeDependencies(); } @override void dispose() { routeObserver.unsubscribe(this); super.dispose(); } @override void didPop() {} @override void didPopNext() { // Called when the top route has been popped off, // and the current route shows up. _setCurrentScreen(route); } @override void didPush() { // Called when the current route has been pushed. _setCurrentScreen(route); } @override void didPushNext() {} Future<void> _setCurrentScreen(AnalyticsRoute analyticsRoute) { print('Setting current screen to $analyticsRoute'); return FirebaseAnalytics().setCurrentScreen( screenName: screenName(analyticsRoute), screenClassOverride: screenClass(analyticsRoute), ); }} I created an enum to track the screens (and functions to turn the enum to screen names). I used the enums to be able to easily track all routes, refactor route names. Using these enums and functions, I can unit test all possible values and enforce consistent naming: no accidental spaces or special characters, no inconsistent capitalization. There could be other, better ways to determine screen class values, but I went with this approach. enum AnalyticsRoute { example }String screenClass(AnalyticsRoute route) { switch (route) { case AnalyticsRoute.example: return 'ExampleRoute'; } throw ArgumentError.notNull('route');}String screenName(AnalyticsRoute route) { switch (route) { case AnalyticsRoute.example: return '/example'; } throw ArgumentError.notNull('route');} Next step in the inital setup is to register the routeObserver as a navigatorObserver of your MaterialApp : MaterialApp( // ... navigatorObservers: [ routeObserver, // FirebaseAnalyticsObserver(analytics: FirebaseAnalytics()), ],); Finally, we can add our first example route that's tracked. Add the with RouteAwareAnalytics to your states and override get route . class ExampleRoute extends StatefulWidget { @override _ExampleRouteState createState() => _ExampleRouteState();}class _ExampleRouteState extends State<ExampleRoute> with RouteAwareAnalytics{ @override Widget build(BuildContext context) => Text('Example'); @override AnalyticsRoute get route => AnalyticsRoute.example;} Every time you add a new route, you can do so with little effort : first, add a new enum value, then the Dart compiler will guide you what to add next: add the screen name and class override values in their respective switch-case . Then, find your state that's building your route, add with RouteAwareAnalytics , and add the route getter. * The reason why I didn't use RouteSettings is that I prefer Simon Lightfoot's approach with the typed arguments instead of the Object arguments the settings provide: class ExampleRoute extends StatefulWidget { const ExampleRoute._({@required this.integer, Key key}) : super(key: key); // All types of members are supported, but I used int as example final int integer; static Route<void> route({@required int integer}) => MaterialPageRoute( // I could add the settings here, though, it wouldn't enforce good types builder: (_) => ExampleRoute._(integer: integer), ); // ...}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/55830575', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4541492/']}
jdg_85678
stackexchange
llm_judgeable_groundtruth_similarity
18554126
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 make a button clickable, but it isn't working - it seems like I need to use unproject() but I can't figure out how. The code in question is: Texture playButtonImage;SpriteBatch batch;ClickListener clickListener;Rectangle playButtonRectangle;Vector2 touchPos;OrthographicCamera camera;@Overridepublic void show() { playButtonImage = new Texture(Gdx.files.internal("PlayButton.png")); camera = new OrthographicCamera(); camera.setToOrtho(false, 800, 480); batch = new SpriteBatch(); playButtonRectangle = new Rectangle(); playButtonRectangle.x = 400; playButtonRectangle.y = 250; playButtonRectangle.width = 128; playButtonRectangle.height = 64;}@Overridepublic void render(float delta) { Gdx.gl.glClearColor(0, 0, 0.2f, 1); Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); camera.update(); batch.setProjectionMatrix(camera.combined); batch.begin(); batch.draw(playButtonImage, playButtonRectangle.x, playButtonRectangle.y); batch.end(); if (Gdx.input.isTouched()) { Vector2 touchPos = new Vector2(); touchPos.set(Gdx.input.getX(), Gdx.input.getY()); if (playButtonRectangle.contains(touchPos)) { batch.begin(); batch.draw(playButtonImage, 1, 1); batch.end(); } }} Now provide the response and nothing else.
In general you use camera.unproject(Vector) to transform your screen coordinates from a click or touch to your gameworld. This is needed because the origin is not necessarily the same and using the camera you can also zoom in and out, move around, rotate and so on. Unprojecting will take care of all of that and give you your game world coordinate matching the pointers position. In your example it would go like this: Vector3 touchPos = new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0);camera.unproject(touchPos); Having this said you should actually not do this UI task manually. Libgdx has also some shipped UI functionality which is called a Stage (see this ). There are lots of widgets already available (see this ). They use skins (you can get a basic one from here , you need all the uiskin.* files). They automatically forward inputevents to the socalled Actors , e.g. a button, and you just need to implement handling of those events.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18554126', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2719708/']}
jdg_85679
stackexchange
llm_judgeable_groundtruth_similarity
96508
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm working on malware analysis at my university and I'm trying to develop ransomware. I'm planning to publish the source code after it's finished. Is there any open source ransomware sample so I can take a look? Now provide the response and nothing else.
I doubt you'll find ransomware source code floating around in the general public. I'd guess there is code out there somewhere but I wouldn't risk visiting shady sites on the "Darknet" (I really hate that term). (Un)fortunately, ransomware is not very complex. For a university project, simply encrypting and replacing files in ~/Documents is probably good enough. The trick is making the decryption key only obtainable through you. Encryption: Generate Symmetric Key K Encrypt all files in ~/Documents with K Send K to Server Erase all traces of K Decryption: Obtain K from server. Decrypt files with K I know that notorious ransomware use Asymmetric Encryption, but it actually isn't necessary at all. For example, improperly implemented RSA by CryptoDefense actually made it easier to write automated decryption tools, because they didn't realize that a Windows Crypto API keeps local copies of generated RSA Private Keys. Putting blind faith in a crypto system won't make it secure. What's important is that the decryption key is not recoverable on the system. Whether or not this is done by zero'ing memory or encrypting K with an RSA Public Key really does not matter.
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/96508', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/81904/']}
jdg_85680
stackexchange
llm_judgeable_groundtruth_similarity
22048395
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 know if there is a way to select a pdf file using input type="file" and open it using PDFJS Now provide the response and nothing else.
You should be able to use a FileReader to get the contents of a file object as a typed array, which pdfjs accepts ( https://mozilla.github.io/pdf.js/examples/ ) //Step 1: Get the file from the input element inputElement.onchange = function(event) { var file = event.target.files[0]; //Step 2: Read the file using file reader var fileReader = new FileReader(); fileReader.onload = function() { //Step 4:turn array buffer into typed array var typedarray = new Uint8Array(this.result); //Step 5:pdfjs should be able to read this const loadingTask = pdfjsLib.getDocument(typedarray); loadingTask.promise.then(pdf => { // The document is loaded here... }); }; //Step 3:Read the file as ArrayBuffer fileReader.readAsArrayBuffer(file); } Edit: The pdfjs API changed at some point since I wrote this first answer in 2015. Updating to reflect the new API as of 2021(thanks to @Chiel) for the updated answer
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/22048395', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2422940/']}
jdg_85681
stackexchange
llm_judgeable_groundtruth_similarity
138496
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 would you go about producing reports by user selected date ranges in a rails app? What are the best date range pickers? edit in response to patrick : I am looking for a bit of both widget and active record advice but what I am really curious about is how to restfully display a date ranged list based on user selected dates. Now provide the response and nothing else.
Are we asking an interface question here (i.e. you want a widget) or an ActiveRecord question? Date Picking Widgets 1) Default Rails Solution : See date_select documentation here . 2) Use a plugin : Why write code? I personally like the CalendarDateSelect plugin, using a pair of the suckers when I need a range. 3) Adapt a Javascript widget to Rails : It is almost trivial to integrate something like the Yahoo UI library (YUI) Calendar , which is all Javascript, to Rails. From the perspective of Rails its just another way to populate the params[:start_date] and params[:end_date] . YUI Calendar has native support for ranges. Getting the data from the Widgets 1) Default Rails Solution See date_select documentation here . #an application helper method you'll find helpful#credit to http://blog.zerosum.org/2007/5/9/deconstructing-date_select# Reconstruct a date object from date_select helper form paramsdef build_date_from_params(field_name, params) Date.new(params["#{field_name.to_s}(1i)"].to_i, params["#{field_name.to_s}(2i)"].to_i, params["#{field_name.to_s}(3i)"].to_i)end#goes into view<%= date_select "report", "start_date", ... %><%= date_select "report", "end_date", ... %> #goes into controller -- add your own error handling/defaults, please!report_start_date = build_date_from_params("start_date", params[:report])report_end_date = build_date_from_params("end_date", params[:report]) 2) CalendarDateSelect : Rather similar to the above, just with sexier visible UI. 3) Adapt a Javascript widget : Typically this means that some form element will have the date input as a string. Great news for you, since Date.parse is some serious magic. The params[:some_form_element_name] will be initialized by Rails for you. #goes in controller. Please handle errors yourself -- Javascript != trusted input.report_start_date = Date.parse(params[:report_start_date]) Writing the call to ActiveRecord Easy as pie. #initialize start_date and end_date up here, by pulling from params probably @models = SomeModel.find(:all, :conditions => ['date >= ? and date <= ?', start_date, end_date]) #do something with models
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/138496', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6805/']}
jdg_85682
stackexchange
llm_judgeable_groundtruth_similarity
23711928
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 question about my javascript code.I got this script from internet, but the problem is that it displays text, I want to make a div of it because I want it like a button instead. This is the code: <script type="text/javascript">$(document).ready(function () { var maxheight=218; var showText = "Lees meer.."; var hideText = "Inklappen"; $('.leesmeer').each(function () { var text = $(this); if (text.height() > maxheight){ text.css({ 'overflow': 'hidden','height': maxheight + 'px' }); var link = $('<a href="#">' + showText + '</a>'); var linkDiv = $('<div></div>'); linkDiv.append(link); $(this).after(linkDiv); link.click(function (event) { event.preventDefault(); if (text.height() > maxheight) { $(this).hktml(showText); text.css('height', maxheight + 'px'); } else { $(this).html(hideText); text.css('height', 'auto'); } }); } }); Thanks for the advice! Now provide the response and nothing else.
Update (7 Dec 2014) The connect middleware from node-sass has been extracted into node-sass-middleware , see this answer Install node-sass In you project folder run: $ npm install node-sass Modify app.js Assuming you have generated your app using $ express my_app Your app.js should look somewhat like this: var express = require('express'), routes = require('./routes');var app = module.exports = express.createServer();app.configure(function(){ app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(__dirname + '/public'));});.... Here are the modifications: var express = require('express'), routes = require('./routes'), sass = require('node-sass'), // We're adding the node-sass module path = require('path'); // Also loading the path modulevar app = module.exports = express.createServer();app.configure(function(){ app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); // notice that the following line has been removed // app.use(express.static(__dirname + '/public')); // adding the sass middleware app.use( sass.middleware({ src: __dirname + '/sass', dest: __dirname + '/public', debug: true, }) ); // The static middleware must come after the sass middleware app.use(express.static( path.join( __dirname, 'public' ) ) );}); It is important to note that app.use( sass.middleware ... ); must come before app.use( express.static ... ) The reason is that we first want sass to compile any sass files that has changed, only then serve them (which is done by express.static ). Restart your app You'd have to restart your app in order for these changes to take place. Include it somewhere so it compiles We can now include app.scss in our /sass folder. But it won't compile just yet. The sass middleware will only compile files that are requested by your applications, so we must include the (to be rendered) css file somewhere, like in `/views/layout.jade': doctype htmlhtml(lang="en") head title= title link(rel='stylesheet', href='/stylesheets/style.css') link(rel="stylesheet", href="app.css") < we've added this body!= body `/views/layout.jade` Notice that unlike style.css which is under the stylesheets sub-folder, the app.css is read from the root (in this case /public ). Fixing paths With app.use( sass.middleware({ src: __dirname + '/sass', dest: __dirname + '/public', debug: true, }) ); After the first compilation, the file and folder hierarchy will look like so: Project folder app.js public app.css < This is where the compiled file goes sytlesheets style.css sass app.scss < This is where the sass file is You may want to have the compiled output in the stylesheets folder, rather than the public one; like so: Project folder app.js public sytlesheets app.css style.css sass app.scss This way, the view will link to the css files like so: link(rel='stylesheet', href='/stylesheets/style.css')link(rel="stylesheet", href="/stylesheets/app.css") However, if you change the sass middleware configuration to app.use( sass.middleware({ src: __dirname + '/sass', dest: __dirname + '/public/stylesheets', debug: true, }) ); things will go pear shape. When linking to the css file like so: link(rel="stylesheet", href="stylesheets/app.css") the resultant request will be for stylesheets/app.css . But since we gave the sass middleware the following config: src: __dirname + '/sass', it will go and look for /sass/stylesheets/app.scss , and no such file exists. One solution is to keep the config as is, but the put all sass files in the subfolder `/sass/stylesheets/. But there is a better solution. If you define a prefix config like so: app.use( sass.middleware({ src: __dirname + '/sass', dest: __dirname + '/public/stylesheets', prefix: '/stylesheets', // We've added prefix })); it will tell the sass compiler that request file will always be prefixed with /stylesheets and this prefix should be ignored, thus for a request for /stylesheets/app.css , the sass middleware will look for the file /sass/app.scss rather than /sass/stylesheets/app.scss . Final code app.js var express = require('express'), routes = require('./routes'), sass = require('node-sass'), path = require('path');var app = module.exports = express.createServer();app.configure(function(){ app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use( sass.middleware({ src: __dirname + '/sass', dest: __dirname + '/public/stylesheets', prefix: '/stylesheets', debug: true, }) ); app.use(express.static(path.join(__dirname, 'public')));}); layout.jade doctype htmlhtml(lang="en") head title= title link(rel='stylesheet', href='/stylesheets/style.css') link(rel="stylesheet", href="/stylesheets/app.css") body!= body Folders and files Project folder app.js public sytlesheets app.css style.css sass app.scss
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/23711928', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3313878/']}
jdg_85683
stackexchange
llm_judgeable_groundtruth_similarity
18053059
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 load properties file. Here is my structure Now i am trying to load test.properties file. But i am getting null. Here how i am doing public class Test { String workingDir = System.getProperty("user.dir"); System.out.println("Current working directory : " + workingDir); File temp = new File(workingDir + "\\" + "test.properties"); String absolutePath = temp.getAbsolutePath(); System.out.println("File path : " + absolutePath); Properties properties = null; try { properties = new Properties(); InputStream resourceAsStream = Test.class.getClassLoader().getResourceAsStream(absolutePath); if (resourceAsStream != null) { properties.load(resourceAsStream); } } catch (IOException e) { e.printStackTrace(); } System.exit(0);} //end of class Test This program prints Current working directory : D:\Personal Work\eclipse 32 Bit\workspace\Spring Integration\LS360BatchImportIntegrationFile path : D:\Personal Work\eclipse 32 Bit\workspace\Spring Integration\LS360BatchImportIntegration\test.properties But it is not loading properties file from this path. Although it is present there. Why i am getting null ? Thanks Edit------------------------------- String workingDir = System.getProperty("user.dir");System.out.println("Current working directory : " + workingDir);File temp = new File(workingDir, "test.properties");String absolutePath = temp.getAbsolutePath();System.out.println("File path : " + absolutePath);try { properties = new Properties(); InputStream resourceAsStream = new FileInputStream(temp); if (resourceAsStream != null) { properties.load(resourceAsStream); } } catch (IOException e) { e.printStackTrace();}System.exit(0);Current working directory : D:\Personal Work\eclipse 32 Bit\workspace\Spring Integration\LS360BatchImportIntegrationFile path : D:\Personal Work\eclipse 32 Bit\workspace\Spring Integration\LS360BatchImportIntegration\test.propertiesjava.io.FileNotFoundException: D:\Personal Work\eclipse 32 Bit\workspace\Spring Integration\LS360BatchImportIntegration\test.properties (The system cannot find the file specified)at java.io.FileInputStream.open(Native Method)at java.io.FileInputStream.<init>(Unknown Source)at com.softech.ls360.integration.BatchImport.main(BatchImport.java:57) Now provide the response and nothing else.
Oh oh ... There are several problems here: 1) In your first provided code snippet, you are using a ClassLoader for loading a resource file. This is indeed a good decision. But the getResourceAsStream method needs a "class-path relative" name. You are providing an absolute path. 2) Your second code snippet (after edit) results in not being able to find the file "D:...\LS360BatchImportIntegration\test.properties". According to your screenshot, the file should be "D:...\LS360AutomatedRegulatorsReportingService\test.properties". This is another directory. I fear, that your descriptions are not up to date with the findings on your machine. But let's just move to a reasonable solution: 1) In your Eclipse project (the screenshot tells us, that you are using Eclipse), create a new directory named "resources" in the same depth as your "src" directory. Copy - or better move - the properties file into it. 2) This new directory must be put into the "build path". Right-click the directory in the Package Explorer or Project Explorer view, select "Build Path", then "Use as Source Folder". Note: This build path will be the class path for the project, when you run it. 3) As the resources directory now is part of your class path and contains your properties file, you can simply load it with getResourceAsStream("test.properties") . EDIT I just see, that you also use Maven (the pom.xml file). In Maven, such a resources directory exists by default and is part of the build path. It is "src/main/resources". If so, just use this.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18053059', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1000510/']}
jdg_85684
stackexchange
llm_judgeable_groundtruth_similarity
999573
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: This is a problem given by Aad W. van der Vaart and Jon A. Wellner in their "weak convergence and stochastic process". It aims at constructing an example of "$E^{\ast}T$ is not always $ET^{\ast}$". Let $(\Omega,\mathcal{A},P)$ be $\mathbb{R}$ with the $\sigma$-field generated by $[0,\infty)$ and the Borel sets in $(-\infty,0)$ and $P$ equal to the Cauchy measure. The map $T:\Omega\rightarrow\mathbb{R}$ defined by $T(\omega)=\omega$ has $E^{\ast}T=\infty$, but $ET^{\ast}$ does not exist. Can someone help me to see why the statement is true? For the definition of "Outer Expectation": $E^{\ast}T=\inf\{EU:U\geq T,U:\Omega \rightarrow\bar{\mathbb{R}}\; \text{measurable and} \;EU \; \text{exists} \}$. For the definition of "Minimal Measurable majorant": For any map $T:\Omega\rightarrow\bar{\mathbb{R}}$, there exists a measurable function $T^{\ast}:\Omega \rightarrow \bar{\mathbb{R}}$ with (i) $T^{\ast}\geq T$; (ii) $T^{\ast}\leq U$ a.s., for every measurable $U:\Omega \rightarrow \bar{\mathbb{R}}$ with $U\geq T$ a.s. Now provide the response and nothing else.
I would draw a $m \times n$ grid and fill it with numbers from $1$ to $mn$ like this: Start with a $1$ in the bottom-left square of the grid and keeping moving diagonally up and right, wrapping around the edges whenever you reach them. Because $m$ and $n$ are coprime, all the numbers from $1$ to $mn$ will fit exactly in the grid with no overlap or empty square. This is a geometric interpretation of being coprime. Now begin crossing out numbers that are not coprime to $mn$. One pattern that will emerge is, when a number is crossed out, either all the numbers in the same row are also crossed out, or all the numbers in the same column. This is because if you cross out a number $k$, then it either has a factor common with $m$ or with $n$. If it's $m$, then every other number in the same row will also be crossed out, since $\gcd(k,m)=\gcd(k\pm m,m)$. Similarly if $\gcd(k,n)\neq 1$, every other number in the same column is also crossed out. Now if we remove all the crossed-out numbers we will get a rectangle consisting of $\phi(mn)$ squares. The width will be $\phi(n)$ and the height will be $\phi(m)$, so $\phi(mn)=\phi(m)\phi(n)$. Here are the pictures for $m=14$, $n=9$.
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/999573', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/89344/']}
jdg_85685
stackexchange
llm_judgeable_groundtruth_similarity
3309484
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 get the delete button to show when swiping on a UITableViewCell ? The event is never raised and the delete button never appears. Now provide the response and nothing else.
During startup in (-viewDidLoad or in storyboard) do: self.tableView.allowsMultipleSelectionDuringEditing = false Override to support conditional editing of the table view. This only needs to be implemented if you are going to be returning NO for some items. By default, all items are editable. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { // Return YES if you want the specified item to be editable. return YES;}// Override to support editing the table view.- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) { //add code here for when you hit delete } }
{}
{'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/3309484', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/351126/']}
jdg_85686
stackexchange
llm_judgeable_groundtruth_similarity
4852
Below is a question asked on the forum astronomy.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: There are several sci-fi movies where planetary bodies are shown in the sky in order to indicate that the characters are on an alien planet. A good example is in Predators (2010): Is it actually possible for such planetary bodies to exist so close to each other as to be visible in such detail to the naked eye? Wouldn't gravitational forces cause disruptions on them that inhibit the development of life (whether plant or animal)? In our Solar system there's a good example in Io which has severe volcanic activity resulting from tidal heating due to its proximity to Jupiter. Now provide the response and nothing else.
Quick calculation of Roche limit for two identical earthlike (fluid) bodies.Roche distance is about equal to 2.44 X radius X(density1/density2)^1/3.For identical bodies the density conveniently cancels, so we getRd = 2.44 X radius.Earth radius is 6378 km.So Rd = 2.44 X 6378 = 15500 km (center to center).The distance surface to surface (15500- 6378) is 9184km. At that distance, by trigonometry, another earth would subtend about 44° of sky, pretty big!, and just at the bleeding edge of stability. The nearest planet in the provided picture looks like it might be at about that distance. Evacuation might be in order as the other three planets or moons will degrade the close binary's orbital stability.
{}
{'log_upvote_score': 4, 'links': ['https://astronomy.stackexchange.com/questions/4852', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/2030/']}
jdg_85687
stackexchange
llm_judgeable_groundtruth_similarity
2136
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Is possible to construct infinitely differentiable functions that interpolate through arbitrary points, the way polynomial splines do? If so, do they have a name and is there an algorithm for constructing the curves. I suppose a infinite degree polynomial spline might qualify but I was hoping there might be something more like a bump function. I definitely am a novice when it comes to this stuff, so please do not hesitate to correct me if I misusing any terminology. Now provide the response and nothing else.
For n data points, there is a unique polynomial of degree n −1 that passes through the points; one way to get it is the Lagrange polynomial . Another class of interpolating functions is the thin plate spline , which is typically used for 2D image warping, but can easily be applied to 1D interpolation as well, which is a strictly simpler problem. The Wikipedia article on polyharmonic splines , of which the thin plate spline is a special case, has examples of other infinitely differentiable splines. I believe that in principle, you can choose any basis function whose translations are linearly independent, and find an interpolating function as a sum of translations and scalings of the basis. The above are essentially examples of particular basis functions people have used because of their other nice properties. Edit: Sorry, thin plate splines and other examples in the article, apart from the Gaussian, are infinitely differentiable almost everywhere. However, if you really want infinite differentiability everywhere, you can use any infinitely differentiable function as basis instead, such as the Gaussian, or $x^2/\sqrt{x^2+1}$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2136', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/99/']}
jdg_85688
stackexchange
llm_judgeable_groundtruth_similarity
11542243
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 find the number of child processes of a bash script, from within the script itself? Now provide the response and nothing else.
To obtain the PID of the bash script you can use variable $$ . Then, to obtain its children, you can run: bash_pid=$$children=`ps -eo ppid | grep -w $bash_pid` ps will return the list of parent PIDs. Then grep filters all the processes not related to the bash script's children. In order to get the number of children you can do: num_children=`echo $children | wc -w` Actually the number you will get will be off by 1, since ps will be a child of the bash script too. If you do not want to count the execution of ps as a child, then you can just fix that with: let num_children=num_children-1 UPDATE: In order to avoid calling grep , the following syntax might be used (if supported by the installed version of ps ): num_children=`ps --no-headers -o pid --ppid=$$ | wc -w`
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11542243', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/51197/']}
jdg_85689
stackexchange
llm_judgeable_groundtruth_similarity
11377
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: The standard definition is that $a\in\mathbb{Z}$ is a primitive root modulo $p$ if the order of $a$ modulo $p$ is $p-1$. Let me rephrase, to motivate my generalization: $a\in\mathbb{Z}$ is a primitive root modulo $p$ if the linear recurrence defined by $x_0=1$, $x_n=ax_{n-1}$ for $n\geq1$ has maximum possible period in $\mathbb{Z}/p\mathbb{Z}$. So, we could define $(a_1,\ldots,a_r)\in\mathbb{Z}^r$ to be an $r$-primitive root modulo $p$ when the order $r$ linear recurrence defined by $x_0=\cdots=x_{r-2}=0$, $x_{r-1}=1$, and $x_n=a_1x_{n-1}+\cdots+a_rx_{n-r}$ for $n\geq r$ has the maximum possible period (for such sequences) in $\mathbb{Z}/p\mathbb{Z}$. Is anything known about the generalized version of primitive roots I've described? I chose my initial values $x_0=\cdots=x_{r-2}=0$, $x_{r-1}=1$ in analogy with the Fibonacci numbers, but is there a standard / most general choice? The starting values affect the period a lot, so it's important to be working with the "right" ones, I guess. What is the maximum achievable period for a linear recurrence in $\mathbb{Z}/p\mathbb{Z}$? An obvious upper bound is $p^r-1$, but it's not clear to me that this is the correct number to replace $p-1$ in the standard definition of primitive root. Is anything known in the direction of Artin's conjecture for "$r$-primitive roots", as I've called them? Other thoughts: because there is no "formula" for the order of $a$ modulo $p$ (this would amount to a formula for the discrete logarithm), there certainly isn't a formula for the period of the linear recurrence defined by $(a_1,\ldots,a_r)$ modulo $p$. I tried to come up with one for a while before I realized this, so I just wanted to save anyone else the trouble. Now provide the response and nothing else.
If $(a_1,\ldots,a_r)$ is an $r$-primitive root in your definition, then the polynomial $x^r-a_1x^{r-1}-\cdots-a_r$ is irreducible in $Z/pZ[x]$ and any ofits roots is a generator (i.e. a primitive root) of the multiplicative group of the field of $p^r$ elements and conversely. This maximal period is $p^r-1$. See, e.g., Lidl-Niederreiter Finite Fields.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/11377', 'https://mathoverflow.net', 'https://mathoverflow.net/users/1916/']}
jdg_85690
stackexchange
llm_judgeable_groundtruth_similarity
25493757
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 wanted to define the function: accumulate_list' :: Num a => [a] -> ( a -> a -> a ) -> aaccumulate_list' l f | [] f = 0 | (x:xs) f = f x (accumulate_list xs f) but it doesn't compile, complaining that x, xs, x, xs, are Not in scope. Trying to achieve the same result, I have defined this function accumulate_list :: Num a => [a] -> ( a -> a -> a ) -> aaccumulate_list [] f = 0accumulate_list (x:xs) f = f x $ accumulate_list xs f it compiles well, and does like sum does on a list if the functgion passed in parameter is (+) . Yes, I finally found that indeed what I wanted to achieve was already existing in Prelude as the sum function. However, I don't understand why the first version with mixed guards and pattern matching doesn't compile. What is the problem ? Now provide the response and nothing else.
It is because guards are basically a boolean expression. They have to evaluate to either True or False . Something like this should typecheck: accumulate_list' :: (Eq a, Num a) => [a] -> ( a -> a -> a ) -> aaccumulate_list' l f | l == [] = 0 | otherwise = undefined -- fill out undefined It's also worth mentioning that since pattern guards were added to Haskell 2010, you're allowed to mix patterns and guards like so: accumulate_list' :: (Eq a, Num a) => [a] -> ( a -> a -> a ) -> aaccumulate_list' l f | [] <- l = 0 --pattern for the empty list case | 10 < 5 = 10 --arbitrary regular guard just because | (x:xs) <- l = undefined --pattern for the non-empty case
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/25493757', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/356440/']}
jdg_85691
stackexchange
llm_judgeable_groundtruth_similarity
17950351
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Ok, I have a problem with joining 2 tables (with INNER JOIN). First table containts categories list (ecc. for photo albums, or blog posts) while the second table contains "the data" I tried like this: SELECT galeries_id, galeries_title, photos.photos_id, photos.photos_gal_id, photos.photos_link FROM galeries INNER JOIN photos ON galeries.galeries_id=photos.photos_gal_id GROUP BY photos_gal_id This gives me fair result, joining my tables nicely, just as I want them to with one crucial exeption. If table "photos" doesn't have a row which contains "photos_gal_id" (for example "2"), than it will NOT return any category (galeries_id, galeries_title) for that category even if it does egzist in galeries table. It is logical because of: ON galeries.galeries_id=photos.photos_gal_id Now I need to adopt this part to show me even thoes which doesn't have a related row in the second table The result I'm trying to get is: galeries_id galeries_title photos_id photos_link 1 blabla 3 test.jpg 2 bla bla2 3 etata 5 test.jpg I hope I explained it good enough :)Thank you.. Now provide the response and nothing else.
To retain the rows from galeries with no matching ID in photos, you will need to join photos on galeries with LEFT JOIN instead of INNER JOIN : SELECT galeries_id, galeries_title, photos.photos_id, photos.photos_gal_id, photos.photos_link FROM galeries LEFT JOIN photos ON galeries.galeries_id=photos.photos_gal_id GROUP BY photos_gal_id This will give you: galeries_id galeries_title photos_id photos_link 1 blabla 3 test.jpg 2 bla bla2 NULL NULL 3 etata 5 test.jpg And if you wish to replace NULL with an empty string, you can use: SELECT IFNULL(photos.photos_id, ''), IFNULL(photos.photos_link, '')
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17950351', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2534234/']}
jdg_85692
stackexchange
llm_judgeable_groundtruth_similarity
250254
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 trouble with a definition. I simply don't get what is asked. This is asked: Give the significance level --> this is 0.05 Give the test statistic and its distribution under the null hypothesis Main question: Michael and Bernard have evening shifts at a supermarket. Michael hascomplained to the manager that he works, on average, much more thanBernard. The manager claims that on average they both work the sameamount of time. After a short discussion between the manager andMichael, the manager randomly selected 50 evenings whenMichael worked, and 50 evenings when Bernard worked (notnecessarily the same evenings as each other). Now, I am using R Studio . I can get these datasets and load them in. I've decided to use the t test, because n > 30 and I don't know the standard deviation. That's something I get. The test statistic should be a t-value / t-score (am I correct?). I can get this in R Studio via: t.test(Michael, Bernard) which gives me the value of t = 1.548 and a degrees of freedom = 91.778 ... Now, they ask for its distribution under the null hypothesis , but I just don't get what they mean with this. What I think and what I did, is to check the critical t-values table... but there, I can't find the degrees of freedom of 91.778. So clearly, this must be wrong... Beside that, I don't get how it's 91.778. I would expect df = n-1 or df = (n1 + n2) - 2 (because it's two samples), so at least 98 would have been the df, but clearly it isn't. What am I doing wrong in my thinkings? And what is being asked with "under the null hypothesis"? What do they want as an answer? A score? A percentage? Can someone explain this to me please? Edit: the data set is asked, of course I can provide them: Michael: [1] 4.32 3.82 4.11 4.75 3.58 3.93 3.50 4.69 4.28 3.75 3.58 4.96 3.72 4.97 3.57 4.06[17] 3.14 4.04 3.81 5.07 3.81 4.38 3.72 2.56 4.46 3.39 3.43 3.36 3.88 3.31 4.11 4.34[33] 4.03 4.00 4.03 3.66 4.62 4.46 3.97 3.94 3.56 4.33 3.03 3.25 3.96 3.97 2.68 4.66[49] 4.78 3.75 Bernard: [1] 3.06 4.78 4.12 4.19 4.34 5.04 3.96 4.25 3.54 3.07 3.17 3.17 3.25 4.19 3.75 3.65[17] 2.25 3.36 2.53 3.44 2.86 4.56 2.44 2.25 3.71 3.31 3.38 2.19 2.92 3.36 2.88 3.91[33] 4.39 4.41 4.44 3.84 4.00 4.75 4.21 4.31 3.78 4.59 4.97 3.69 4.31 3.53 4.75 4.03[49] 4.16 3.92 Now provide the response and nothing else.
Wow, there's lots to deal with here. I'm assuming this is homework, so my first advice is that you catch up on the expected reading! Second, the "significance level" has a different meaning depending on whether you are working within the dichotomous hypothesis testing framework of Neyman or the significance testing framework of Fisher. In the former case the significance level is an unfortunate phrase indicating the alpha level or 'size' of the test, and it might be 0.05 as you indicate, but only if that level is explicitly decided prior to the data being analysed. In the latter case the significance level refers to the observed significance level, the p-value. (That distinction is not always observed by introductory stats texts and may be unknown to some instructors.) Next, if you are doing a Student's t-test then the test statistic is t. I expect that the question would be answered by an explanation of the meaning of the t statistic and how it is calculated for the particular experiment. Next, the t-test that you have calculated using R is a Welch's variant. It relaxes the assumption of the original Student's t-test that the variances of the populations are equal. The way it is calculated leads to fractional degrees of freedom. For a conventional Student's t-test your degrees of freedom would be n1-1 + n2-1. Finally, the distribution that you have been asked for is the distribution of t under the assumption that the parameter of interest (mean difference) is equal to the null hypothesised value (usually zero, but it can be any value desired). The tabulated critical values of t that you consulted will not suffice.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/250254', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/138010/']}
jdg_85693
stackexchange
llm_judgeable_groundtruth_similarity
1998297
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 written a small bash script which needs an ssh tunnel to draw data from a remote server, so it prompts the user: echo "Please open an ssh tunnel using 'ssh -L 6000:localhost:5432 example.com'" I would like to check whether the user had opened this tunnel, and exit with an error message if no tunnel exist. Is there any way to query the ssh tunnel, i.e. check if the local port 6000 is really tunneled to that server? Now provide the response and nothing else.
This is my test. Hope it is useful. # $COMMAND is the command used to create the reverse ssh tunnelCOMMAND="ssh -p $SSH_PORT -q -N -R $REMOTE_HOST:$REMOTE_HTTP_PORT:localhost:80 $USER_NAME@$REMOTE_HOST"# Is the tunnel up? Perform two tests:# 1. Check for relevant process ($COMMAND)pgrep -f -x "$COMMAND" > /dev/null 2>&1 || $COMMAND# 2. Test tunnel by looking at "netstat" output on $REMOTE_HOSTssh -p $SSH_PORT $USER_NAME@$REMOTE_HOST netstat -an | egrep "tcp.*:$REMOTE_HTTP_PORT.*LISTEN" \ > /dev/null 2>&1if [ $? -ne 0 ] ; then pkill -f -x "$COMMAND" $COMMANDfi
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1998297', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/51197/']}
jdg_85694
stackexchange
llm_judgeable_groundtruth_similarity
2254872
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 class definition that contains a property that returns an interface. public class Foo{ public int Number { get; set; } public ISomething Thing { get; set; }} Attempting to serialize the Foo class using Json.NET gives me an error message like, "Could not create an instance of type 'ISomething'. ISomething may be an interface or abstract class." Is there a Json.NET attribute or converter that would let me specify a concrete Something class to use during deserialization? Now provide the response and nothing else.
One of the things you can do with Json.NET is: var settings = new JsonSerializerSettings();settings.TypeNameHandling = TypeNameHandling.Objects;JsonConvert.SerializeObject(entity, Formatting.Indented, settings); The TypeNameHandling flag will add a $type property to the JSON, which allows Json.NET to know which concrete type it needs to deserialize the object into. This allows you to deserialize an object while still fulfilling an interface or abstract base class. The downside, however, is that this is very Json.NET-specific. The $type will be a fully-qualified type, so if you're serializing it with type info,, the deserializer needs to be able to understand it as well. Documentation: Serialization Settings with Json.NET
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2254872', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/19112/']}
jdg_85695
stackexchange
llm_judgeable_groundtruth_similarity
7971575
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: A question: I have 2 tables: Productid INTname VARCHAR(64)something TEXTelse INTentirely BOOL and Ingredientid INTname VARCHAR(64)description TEXT Now I also have a link table Products_Ingredientsproduct_id INTingredient_id INT for my many to many relation. Now both products and ingredients will have unique names. So I can use names as natural keys... however will that be a good idea? Say I have a product: Paint Thinner Supreme with ingredient: Butylonitrotetrocycline Will that be a good idea to use those names as composite key in the link table? As much as I understand idea behind using natural keys over the surrogates, I kinda can't stop thinking that using simple integers as primary keys (and foreign ones) will be much faster. Will there be a difference in a way in which MySQL server digests those different keys? What is your opinion? Now provide the response and nothing else.
Opinions don't matter when you can measure. I implemented this on PostgreSQL using both natural keys and surrogates. I used 300,000 total products, 180 ingredients, and populated two "product ingredient" tables with 3 to 17 ingredients per product, for 100,000 randomly selected products (1053462 rows). Selecting all the ingredients for a single product using natural keys returned in 0.067 ms. Using surrogates, 0.199ms. Returning all the non-id columns for a single product using natural keys returned in 0.145 ms. Using surrogates, 0.222 ms So natural keys were about 2 to 3 times faster on this data set. Natural keys don't require any joins to return this data. Surrogate keys require two joins. The actual performance difference depends on the width of your tables, number of rows, page size, and length of names, and things like that. There will be a point where surrogate keys start outperforming natural keys, but few people try to measure that. When I was designing the database for my employer's operational database, I built a testbed with tables designed around natural keys and with tables designed around id numbers. Both those schemas have more than 13 million rows of computer-generated sample data. In a few cases, queries on the id number schema outperformed the natural key schema by 50%. (So a complex query that took 20 seconds with id numbers took 30 seconds with natural keys.) But 80% of the test queries had faster SELECT performance against the natural key schema. And sometimes it was staggeringly faster--a difference of 30 to 1. We expect natural keys to outperform surrogates in our database for years to come. (Unless we move certain tables over to an SSD, in which case natural keys will probably outperform surrogates forever.)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7971575', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/838519/']}
jdg_85696
stackexchange
llm_judgeable_groundtruth_similarity
44948858
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 two classes Child extends Parent . I need to put @Builder annotation on the classes such that I do not need to create the builder my self. package jerry;// Internal compiler error: java.lang.NullPointerExceptionimport lombok.AllArgsConstructor;import lombok.Builder;@AllArgsConstructor(onConstructor=@__(@Builder))public class Child extends Parent { //Multiple markers at this line// - Implicit super constructor Parent() is undefined. Must explicitly invoke another constructor// - overrides java.lang.Object.toString private String a; private int b; private boolean c;}@Builderpublic class Parent { private double d; private float e;} I need to be able to build child instance such that Child child = Child.builder().a("aVal").b(1000).c(true).d(10.1).e(20.0F).build(); But so far I am getting the errors mentioned in side that code comments. Can any one point me to the right direction how to achieve it with lombok or any other similar library ? Sub-question Why does @AllArgsConstructor(onConstructor=@__(@Autowired)) compile but @AllArgsConstructor(onConstructor=@__(@Builder)) does not? Now provide the response and nothing else.
See in https://blog.codecentric.de/en/2016/05/reducing-boilerplate-code-project-lombok/ ( @Builder and inheritance part) Adjusted to your classes @AllArgsConstructorpublic class Parent { private double d; private float e;}public class Child extends Parent { private String a; private int b; private boolean c; @Builder public Child(String a, int b, boolean c, double d, float e) { super(d, e); this.a = a; this.b = b; this.c = c; }} With this setup Child child = Child.builder().a("aVal").b(1000).c(true).d(10.1).e(20.0F).build(); works correctly
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/44948858', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5462398/']}
jdg_85697
stackexchange
llm_judgeable_groundtruth_similarity
20195544
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 flatMap method of the Success is implemented like this: def flatMap[U](f: T => Try[U]): Try[U] = try f(value) catch { case NonFatal(e) => Failure(e) } I kinda understand what this method is doing, it helps us to avoid writing a lot of catching code. But in what sense is it similar to the regular flatMap? A regular flatMap takes a sequence of sequences, and put all the elements into one big "flat" sequence. But the flatMap method of Try is not really flattening anything. So, how to understand the flatMap method of Try? Now provide the response and nothing else.
Without entering into monads, instead of thinking about it in terms of collections, you could think of it in terms of structures (where a collection becomes a structure with many entries). Now, take a look at the signature of Try.flatmap (from your post): def flatMap[U](f: T => Try[U]): Try[U] the function f transforms T into a Try[U] in the context of Try[T]. In contrast, imagine the operation were 'map', the result would be: def badMap[U](f: T => Try[U]): Try[Try[U]] As you can see, flatmap is 'flattening' the result into the context of Try[T] and producing Try[U] instead of the nested Try[Try[U]] . You can apply the same 'flattening of nested structure' concept to collections as you mention.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20195544', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/290284/']}
jdg_85698
stackexchange
llm_judgeable_groundtruth_similarity
4312
Below is a question asked on the forum earthscience.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The fractions of albite $\ce{NaAlSi_3O_8}$ and anorthite $\ce{CaAl_2Si_2O_8}$, which I call $\ce{Ab}$ and $\ce{An}$ in the following list, present in a plagioclase are often used to define it in the following way: Anorthite: $\ce{An}=90\%-100\%$, $\ce{Ab}=0\%-10\%$; Bytownite: $\ce{An}=70\%-90\%$, $\ce{Ab}=10\%-30\%$; Labradorite: $\ce{An}=50\%-70\%$, $\ce{Ab}=30\%-50\%$; Andesine: $\ce{An}=30\%-50\%$, $\ce{Ab}=50\%-30\%$; Oligoclase: $\ce{An}=10\%-30\%$, $\ce{Ab}=70\%-90\%$; Albite: $\ce{An}=0\%-10\%$, $\ce{Ab}=90\%-100\%$. What I am not sure of is whether these fractions are intended as applying to mass, molarity, volume. Now provide the response and nothing else.
According to the pages Plagioclase composition (from the textbook: Introduction to Mineralogy Nesse, 2000), the percentage definitions are due to the mole percent of $\ce{Ca^{2+}}$ (from anorthite) and the presumed subsequent $\ce{Na+}$ (from albite) ions present in the sample. This is done under the assumption that the anorthite% + albite% = 100% in a plagioclase sample. The mole percent are usually represented by percentage proportions of the plagioclase end member anorthite, often in the form of An x , where 'x' is the mole percent of $\ce{Ca^{2+}}$ present in the plagioclase sample. Consider the following diagram below - the relevent part for your question is across the base of the triangle: Image source . For example, oligoclase is An 10%-30% means that it would possess a $\ce{Ca^{2+}}$ mole percent of between 10% to 30%, and a corresponding $\ce{Na+}$ mole percent of between 70% to 90%.
{}
{'log_upvote_score': 4, 'links': ['https://earthscience.stackexchange.com/questions/4312', 'https://earthscience.stackexchange.com', 'https://earthscience.stackexchange.com/users/620/']}
jdg_85699
stackexchange
llm_judgeable_groundtruth_similarity
32545270
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 the following code recently; it uses a lot of exception handling. I think it makes the code look very unreadable. I could shorten the code by catching generic exception, such as catch (Exception e){ e.printStackTrace();} but I also heard that catching generic exception is not a good coding practice. public class DataAnalyzerTester { /** * @param args args[0] stores the filename * @exception NoSuchElementException if user attempts to access empty list element * @exception ArithmeticException if user attempts to divide by 0 * @exception ArrayIndexOutOfBoundsException if user supplied less than 3 arguments * @exception IOException problems with creating and writing files * @exception RuntimeException if user attempts to pass empty list to constructor */ public static void main(String[] args) { try{ //some code } catch (NoSuchElementException e) { System.out.println("Accessing element that does not exist: " + e.toString()); } catch (ArithmeticException e) { System.out.println("Division by zero: " + e.toString()); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Please supply a command line arguement that specifies your file path: " + e.toString()); } catch (IOException e) { System.out.println("Other IO errors: " + e.toString()); } catch (RuntimeException e) { System.out.println(e.toString()); } }} I would like to know if there is any better and cleaner way to catch multiple exceptions. Now provide the response and nothing else.
First, unless you have very good reason, never catch RuntimeException , Exception or Throwable . These will catch most anything that is thrown, and Throwable will catch everything , even those things you're not meant to catch, like OutOfMemoryError . Second, avoid catching runtime exceptions unless it directly impedes with the critical operation of your program. (But seriously, if anyone sees you catch a NullPointerException , they are within their full rights to call you out on it.) The only exceptions you should be bothering with are those that you are required to handle. Out of your list of exceptions, the only one you should bother with is IOException . The rest are the result of not enough tests, or sloppy coding; those shouldn't occur in the normal run time of your application. Third, in Java 7, you have the ability to do a multi-catch statement for your exceptions, if the exceptions are mutually exclusive. The example linked does a good job of explaining it, but if you were to encounter code that threw both an IOException and an SQLException , you could handle it like this: try { // Dodgy database code herecatch (IOException|SQLException ex) { logger.log(ex); throw ex;} This cleans things up a bit, as you don't have unwieldy and huge chains of exceptions to catch.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32545270', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4480571/']}
jdg_85700
stackexchange
llm_judgeable_groundtruth_similarity
2070890
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 an easy way to get the MvcRouteHandler to convert all hyphens in the action and controller sections of an incoming URL to underscores as hyphens are not supported in method or class names. This would be so that I could support such structures as sample.com/test-page/edit-details mapping to Action edit_details and Controller test_pagecontroller while continuing to use MapRoute method. I understand I can specify an action name attribute and support hyphens in controller names which out manually adding routes to achieve this however I am looking for an automated way so save errors when adding new controllers and actions. Now provide the response and nothing else.
I have worked out a solution. The requestContext inside the MvcRouteHandler contains the values for the controller and action on which you can do a simple replace on. Public Class HyphenatedRouteHandler Inherits MvcRouteHandler Protected Overrides Function GetHttpHandler(ByVal requestContext As System.Web.Routing.RequestContext) As System.Web.IHttpHandler requestContext.RouteData.Values("controller") = requestContext.RouteData.Values("controller").ToString.Replace("-", "_") requestContext.RouteData.Values("action") = requestContext.RouteData.Values("action").ToString.Replace("-", "_") Return MyBase.GetHttpHandler(requestContext) End FunctionEnd Class Then all you need to replace the routes.MapRoute with an equivalent routes.Add specifying the the new route handler. This is required as the MapRoute does not allow you to specify a custom route handler. routes.Add(New Route("{controller}/{action}/{id}", New RouteValueDictionary(New With {.controller = "Home", .action = "Index", .id = ""}), New HyphenatedRouteHandler()))
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2070890', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/33/']}
jdg_85701
stackexchange
llm_judgeable_groundtruth_similarity
19845167
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 stuck with this problem: <body onload="document.body.innerHTML="<script>alert('hi')</script>""> The problem is that i cant use quotes within quotes within quotes.Any ideas? Now provide the response and nothing else.
To represent a " character inside an HTML attribute delimited by " characters, use the entity &quot; I'd recommend attaching event listeners using JavaScript rather then using intrinsic event attributes though. It simplifies things greatly. Note however, that browsers will not execute JavaScript added to the document with innerHTML . If you want to add a script programatically, the use createElement / appendChild et al.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19845167', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2966346/']}
jdg_85702
stackexchange
llm_judgeable_groundtruth_similarity
51053222
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So, I was reading some stuff regarding Node.js and I was amazed when I came across Worker Threads . Having threads in my opinion is a great plus especially if you combine it with shared memory access. As you might think already -> SharedArrayBuffer ... Yeap that's what I thought. So The first thing that came into my mind was to give it a little test and try to implement a simple store (a simple object for now) that would be shared among the threads. The question is, (unless I'm missing something here) how can you make an object accessible from n threads with the use of SharedArrayBuffer ? I know that for a simple Uint32Array is doable, but regarding the object what can be done? At first I thought to convert it to a Uint32Array as you may see bellow, but even looking at the damn source code makes me wanna cry... const { Worker, isMainThread, workerData} = require('worker_threads');const store = { ks109: { title: 'some title 1', description: 'some desciption 1', keywords: ['one', 'two'] }, ks110: { title: 'some title 2', description: 'some desciption 2', keywords: ['three', 'four'] }, ks111: { title: 'some title 3', description: 'some desciption 3', keywords: ['five', 'six'] }}const shareObject = (obj) => { let OString = JSON.stringify(obj); let SABuffer = new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * OString.length); let sArray = new Int32Array(SABuffer); for (let i = 0; i < OString.length; i++) { sArray[i] = OString.charCodeAt(i); } return sArray;}if (isMainThread) { const sharedStore = shareObject(store); console.log('[Main][Data Before]:', sharedStore.slice(-10)); let w = new Worker(__filename, { workerData: sharedStore }); w.on('message', (msg) => { console.log(`[Main][Thread message]: ${msg}`); }); w.on('error', (err) => { console.error(`[Main][Thread error] ${err.message}`); }); w.on('exit', (code) => { if (code !== 0) { console.error(`[Main][Thread unexpected exit]: ${code}`); } }); setInterval(() => { // At some point you ll see a value change, // it's 'six' becoming 'sax' (big time!) console.log('[Main][Data Check]:', sharedStore.slice(-10)); }, 1000);} else { let str = String.fromCharCode.apply(this, workerData); let obj = JSON.parse(str); obj.ks111.keywords[1] = 'sax'; // big time! let OString = JSON.stringify(obj); for (let i = 0; i < OString.length; i++) { workerData[i] = OString.charCodeAt(i); }} In conclusion, shared object among threads in Node.js 10.5.0, is it possible? How? Now provide the response and nothing else.
ECMA Script contains no shared objects but it has SharedArrayBuffer . And you can implement such behavior on your own writing data directly in buffer using DataView and wrapper: // Shared valueclass SharedPoint { constructor(array) { this.dataview = new DataView(array); } set x(value) { this.dataview.setUint8(0, value); } set y(value) { this.dataview.setUint8(1, value); } get x() { return this.dataview.getUint8(0); } get y() { return this.dataview.getUint8(1); }}// Usageconst buffer = new SharedArrayBuffer(2);// Create two instances of shared point.const point0 = new SharedPoint(buffer);const point1 = new SharedPoint(buffer);// Get initial values for point #1console.log('x', point1.x); // 0console.log('y', point1.y); // 0// Update point #0point0.x = 64;point0.y = 32;// Get changes in point #1console.log('x', point1.x); // 64console.log('y', point1.y); // 32 You are able to create class which can manipulate strings or C-like structures . While SharedArrayBuffer is transferable object it can be shared between worker and main process. ⚠️ Note Due to Spectre attack SharedArrayBuffer was disabled by all major browsers and reenabled. Though the API is mature, its' support could be lower than one might expect. Check browsers support at can i use .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/51053222', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1592836/']}
jdg_85703
stackexchange
llm_judgeable_groundtruth_similarity
28587698
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Here are two function signatures I saw in the Rust documentation: fn modify_foo(mut foo: Box<i32>) { *foo += 1; *foo }fn modify_foo(foo: &mut i32) { *foo += 1; *foo } Why the different placement of mut ? It seems that the first function could also be declared as fn modify_foo(foo: mut Box<i32>) { /* ... */ } Now provide the response and nothing else.
mut foo: T means you have a variable called foo that is a T . You are allowed to change what the variable refers to : let mut val1 = 2;val1 = 3; // OKlet val2 = 2;val2 = 3; // error: re-assignment of immutable variable This also lets you modify fields of a struct that you own: struct Monster { health: u8 }let mut orc = Monster { health: 93 };orc.health -= 54;let goblin = Monster { health: 28 };goblin.health += 10; // error: cannot assign to immutable field foo: &mut T means you have a variable that refers to ( & ) a value and you are allowed to change ( mut ) the referred value (including fields, if it is a struct): let val1 = &mut 2;*val1 = 3; // OKlet val2 = &2;*val2 = 3; // error: cannot assign to immutable borrowed content Note that &mut only makes sense with a reference - foo: mut T is not valid syntax. You can also combine the two qualifiers ( let mut a: &mut T ), when it makes sense.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/28587698', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/690061/']}
jdg_85704
stackexchange
llm_judgeable_groundtruth_similarity
11452796
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 simple function in one of my R packages, with one of the arguments symbol = "£" : formatPound <- function(x, digits = 2, nsmall = 2, symbol = "£"){ paste(symbol, format(x, digits = digits, nsmall = nsmall)) } But when running R CMD check , I get this warning: * checking R files for non-ASCII characters ... WARNINGFound the following files with non-ASCII characters: formatters.R It's definitely that £ symbol that causes the problem. If I replace it with a legitimate ASCII character, like $ , the warning disappears. Question: How can I use £ in my function argument, without incurring a R CMD check warning? Now provide the response and nothing else.
Looks like "Writing R Extensions" covers this in Section 1.7.1 "Encoding Issues" . One of the recommendations in this page is to use the Unicode encoding \uxxxx . Since £ is Unicode 00A3, you can use: formatPound <- function(x, digits=2, nsmall=2, symbol="\u00A3"){ paste(symbol, format(x, digits=digits, nsmall=nsmall))}formatPound(123.45)[1] "£ 123.45"
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11452796', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/602276/']}
jdg_85705
stackexchange
llm_judgeable_groundtruth_similarity
1559742
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: If one is able to use classes, it seems to me that the proof of transfinite induction is a simple extension of the usual proof of induction (and equal to the proof of transfinite induction on sets). However, if one cannot argue on classes, how can one prove transfinite induction? PS: I'm sorry if my question is confused. That would be because my knowledge on set theory is not thorough and barely enough for me to be confortable with it. Now provide the response and nothing else.
If $C$ is any well-ordered set, we have the Principle of Transfinite Induction. Let $P$ be a property with$$ \tag1\forall \alpha\in C\colon (\forall \beta \in C\colon \beta<\alpha \to P(\beta))\to P(\alpha).$$Then$$ \forall \alpha\in C\colon P(\alpha).$$ Proof: We can define the set $A=\{\,\alpha\in C\mid \neg P(\alpha)\,\}$. Assume $A\ne \emptyset$. As $C$ is well-ordered $A$ has a minimal element $\alpha$. By minimality we have $\forall \beta \in C\colon \beta<\alpha \to P(\beta)$, hence from $(1)$ we get $P(\alpha)$, contradicting $\neg P(\alpha)$. Therefore $A=\emptyset$, which is the claim. $\square$ Interestingly, the principle works also if $C$ is the well-ordered proper class $ \operatorname{On}$ of all ordinals (which also happens to be the most common application of transfinite induction), even though one might be discouraged by the fact that we deal with a proper class here: Principle of Transfinite Induction for Ordinals. Let $P$ be a property with$$ \tag2\forall \alpha\in \operatorname{On}\colon (\forall \beta \in \operatorname{On}\colon \beta<\alpha \to P(\beta))\to P(\alpha).$$Then$$ \forall \alpha\in \operatorname{On}\colon P(\alpha).$$ Proof. Let $\gamma\in \operatorname{On}$ be an arbitrary ordinal. Then $\gamma$ itself is a well-ordererd set of ordinals, so that we can apply the principle of Transfinite induction above to the well-ordered set $C=\gamma$. We conclude $\forall \beta\in\gamma\colon P(\beta)$ or more wordy $\forall \beta\in \operatorname{On}\colon\beta\in \gamma \to P(\beta)$. As $\beta\in\gamma$ is the same as $\beta<\gamma$, we learn from $(2)$ that $P(\gamma)$. As $\gamma$ was an arbitrary ordinal, we obtain the desired claim. $\square$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1559742', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/59234/']}
jdg_85706
stackexchange
llm_judgeable_groundtruth_similarity
9555889
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: First a caveat: I posted this question here on SuperUser, but it is clearly the wrong place to ask R questions. I recognize that it is not directly a programming question, but I believe it can be solved by changing how plots are produced (i.e. by coding appropriately). So I hope readers find this appropriate for the forum. R plots usually consist entirely of vector graphics elements (i.e. points, lines, polygons, text). R permits you to save your figure (or copy-paste) in various formats including various raster formats, as a PDF, or as a Windows meta-file. I usually save my images as PDFs and print them. This renders the images exactly as I intended them on paper, in the highest quality. I avoid raster formats (e.g. JPG, TIFF) for printing as inevitably the quality is poorer and publishers prefer vector formats. However, I need to make a large multi-page desktop published document using Microsoft Word 2007, and therefore using PDFs is not an option. When I import my figures from meta-files, or copy and paste directly from R into Word both the screen and print rendering of the image changes slightly (e.g. polygons and their fills become slightly misaligned). Given that I want to retain high vector quality (and not use raster formats), what can I do to make R vector graphics work with Word? (Of course Sweave and LaTeX would be nice, but again, not a realistic option). Consider this example: plot(c(1:100), c(1:100), pch=20)## Copy and paste to Word 2007 as Windows metafile## Print## Quality is poorer (e.g. dot fills misaligned with borders)pdf("printsPerfectly.pdf")plot(c(1:100), c(1:100), pch=20)dev.off()## Now print PDF## Quality is as expected EDIT: Further to suggestions by @John I produced it as an EPS postscript file (see below), inserted it as a picture into Word. Because ultimately it will be printed from a PDF created from Word, I converted it to a PDF using default Word 2007 settings, printed it on my HP Laserjet P1606dn laser printer, and then took aphotograph to illustrate the issue of polygons borders and fills misaligning (image on left, below). I also produced it directly as PDF from R using pdf() and printed the PDF and took a photograph (image on right, below). It may seem like small potatoes! But when you have gone to a lot of trouble to achieve high quality, it is disappointing to be thwarted at the end. In addition, it is not really obvious here, but the numerals are not as high-quality (left) as in the PDF (right), disregarding differences in focus on the photograph. Now provide the response and nothing else.
Your only option is to use high resolution raster graphics. Once you're over 300 dpi it will be completely indistinguishable from vector printed; it will just make larger files.. Your copy and paste method is coming in at 72 dpi and will look terrible. If you import from a file you can get the resolution in the file and things will be much better. Fortunately Office 2007 is supposed to handle png images, which have the best compression for typical graphs. Let's say you wanted the image 4" wide and 6" high... png('printsGreat.png', width = 4, height = 6, units = 'in', res = 300)plot(c(1:100), c(1:100), pch=20)dev.off() Also, Office 2007 is supposed to be able to handle EPS files and R postscript files are by default EPS compatible when you print one page. postscript("printsPerfectly.eps", width = 4, height = 6, horizontal = FALSE, onefile = FALSE)plot(c(1:100), c(1:100), pch=20)dev.off() But if you don't have luck with them go back to the high resolution image.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9555889', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1165618/']}
jdg_85707
stackexchange
llm_judgeable_groundtruth_similarity
14016031
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 client which is subscribed to several multicast feeds via a third party library with a callback. The third party library does something like this: sockaddr_in senderAddr;socklen_t len = sizeof(struct sockaddr_in);for fd in allMulticastFeeds:{ recvfrom(fd, buf, sizeof(buf), 0, (struct sockaddr*)&senderAddr, &len); (*func)(buf, rc, &senderAddr, 0, stuff*);} Several listeners subscribe to me, and my job is to parse the messages contained in buf and callback on the appropiate clients subscribed to me. One of the options clients who subscribe to me give me is whether they want to receive messages outgoing from the local host or not. Because different subscribers to me might want different behavior I simply cannot translate this to a disabling of multicast and I must, for each client, check whether he or she requested local messages, and if not, then hand them over only if I can verify from the sockaddr_in that they are not local. My approach to do this was to do the following in the constructor of my service: sockaddr_in self;hostent *he;char local[HOST_NAME_MAX];gethostname(local, sizeof(local));he = gethostbyname(local);if (he){ memcpy(&self.sin_addr, he->h_addr_list[0], he->h_length); selfAddr_ = self.sin_addr.s_addr;} where selfAddr_ is a member variable of type long . Then, when I get the callback described above from the network listener I do something like this: //code to get the correct listener for this type of packet after parsing itif (listener->AskedForLocal || selfAddr_ != s_addr) listener->onFoo(bla,bla); where s_addr is the sin_addr.s_addr contained in the sockaddr_in* I get from the third party library calling recvfrom . This seemed to work when I tested it but I have a feeling it is failing sometimes and it might have to do with the adhoc using of the first element of he->h_addr_list . Is this method unreliable and if so, is the only reliable method to check every element of the he->h_addr_list against the incoming s_addr ? Now provide the response and nothing else.
Your program is a perfectly syntactically correct OpenMP code by the current OpenMP standards (e.g. it compiles unmodified with GCC 4.7.1), except that x should be declared private (which is not a syntactic but rather a semantic error). Unfortunately Microsoft Visual C++ implements a very old OpenMP specification (2.0 from March 2002) which only allows the following statements as acceptable in an atomic construct: x binop= expr x ++ ++ x x -- -- x Later versions included x = x binop expr , but MSVC is forever stuck at OpenMP version 2.0 even in VS2012. Just for comparison, the current OpenMP version is 3.1 and we expect 4.0 to come up in the following months. In OpenMP 2.0 your statement should read: #pragma omp atomicsum += 4.0/(1.+ x*x); But as already noticed, it would be better (and generally faster) to use reduction: #pragma omp parallel for private(x) reduction(+:sum)for (i=0; i<num_steps; i++){ x = (i + .5)*step; sum = sum + 4.0/(1.+ x*x); } (you could also write sum += 4.0/(1.+ x*x); )
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14016031', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/970171/']}
jdg_85708
stackexchange
llm_judgeable_groundtruth_similarity
59232370
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 query Inserts a value and returns the new row inserted INSERT INTO event_comments(date_posted, e_id, created_by, parent_id, body, num_likes, thread_id) VALUES(1575770277, 1, '9e028aaa-d265-4e27-9528-30858ed8c13d', 9, 'December 7th', 0, 'zRfs2I') RETURNING comment_id, date_posted, e_id, created_by, parent_id, body, num_likes, thread_id I want to join the created_by with the user_id from my user's table. SELECT * from users WHERE user_id = created_by Is it possible to join that new returning row with another table row? Now provide the response and nothing else.
Consider using a WITH structure to pass the data from the insert to a query that can then be joined. Example: -- Setup some initial tablescreate table colors ( id SERIAL primary key, color VARCHAR UNIQUE);create table animals ( id SERIAL primary key, a_id INTEGER references colors(id), animal VARCHAR UNIQUE);-- provide some initial data in colorsinsert into colors (color) values ('red'), ('green'), ('blue');-- Store returned data in inserted_animal for use in next querywith inserted_animal as ( -- Insert a new record into animals insert into animals (a_id, animal) values (3, 'fish') returning *) select * from inserted_animal left join colors on inserted_animal.a_id = colors.id;-- Output-- id | a_id | animal | id | color-- 1 | 3 | fish | 3 | blue Explanation:A WITH query allows a record returned from an initial query, including data returned from a RETURNING clause, which is stored in a temporary table that can be accessed in the expression that follows it to continue work on it, including using a JOIN expression.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/59232370', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11628353/']}
jdg_85709
stackexchange
llm_judgeable_groundtruth_similarity
442924
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 normally try to avoid duplication and adhere to the DRY principle. However, I'm wondering about a case like this: public class Feature { final static String FEATURE_LABEL = "blah"; public void doSomething() { ... } ...}public class FeatureTest { ... @Test public void doSomethingShouldMakeSomethingHappen() { assertEquals(Feature.FEATURE_LABEL, feature.getSomethingHappens().getLabel()); } If the requirement is that the the label be "blah" and someone changes FEATURE_LABEL to "bleh", the test will pass even though it no longer meets the requirement. Is this a valid place to violate DRY? Now provide the response and nothing else.
Yes, use a literal here. Quoting myself from a question on literals : Hardcoded literals should appear in unit tests for the test values, unless there is so much reuse of a value within a single test class that a local constant is useful. The unit tests are a description of expected values without any abstraction or redirection. Imagine yourself reading the test - you want the information literally in front of you.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/442924', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/18995/']}
jdg_85710
stackexchange
llm_judgeable_groundtruth_similarity
137161
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 know that a MOSFET is a four-terminal device, but nearly every discrete MOSFET you can buy has its bulk/body/substrate internally connected to the source. Why is this? It makes it inconvenient to use in certain types of circuit, for example when breadboarding a basic IC design (for instructional purposes) in which all the body terminals are connected either to VCC or to ground. Are discrete 4-terminal MOSFETs just not that useful? Or is there some easy way to simulate them with a few 3-terminal MOSFETs? Now provide the response and nothing else.
Although the FETs in on a monolithic chip are symmetric, many discrete FETs have a very different structure which tries to maximize the usable surface area as well as source/drain connectivity. The bulk substrate connection on a transistor or chip has excellent current-handling capability, and if one were designing an NMOS LSI chip in which every single transistor needed to have its source or drain tied to a common point, performance would probably be optimized by having the substrate serve as the source or drain for all the transistors. Most chips, however, use the bulk connection as a common base, wasting its current-handling abilities, but allowing the source and drain connections of each transistor to be independent. A typical "discrete" MOSFET will in fact be not one transistor, but dozens or hundreds of transistors in parallel. Because all the transistors are supposed to have their drains tied together, using the substrate as the drain won't cause the same design problems as it would in an LSI chip. Since the substrate can be very well solidly connected to an outside terminal, such a design will both improve drain conductivity, and also eliminate the need to use top-side metal for the drain connection, thus allowing the use of more metal to connect the sources. Unfortunately, if the transistors are arranged so that all their sources form a "mesh" (good for connectivity), that will leave their bases as isolated islands. While it would be possible to run metal tracks to connect all the bases together, doing so would require either subdividing the source-connected metal into many strips (degrading performance) or adding an extra metal layer and an extra insulating layer (significantly increasing cost). Since each base section has the metal layer for the source connection sitting directly above it, it's much easier to simply have have the bases as well as the sources connect to that.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/137161', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/57556/']}
jdg_85711
stackexchange
llm_judgeable_groundtruth_similarity
6762283
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Suppose i have 3 java classes A , B and C I need to create an object of class C that is used in both A and B but the problem in creating the object separately is that the constructor of class c is called 2 times. But i want the constructor to be called just once. So i want to use the object created in class A into class b. Now provide the response and nothing else.
So create the object once, and pass it into the constructors of A and B: C c = new C();A a = new A(c);B b = new B(c);...public class A { private final C c; public A(C c) { this.c = c; }} Note that this is very common in Java as a form of dependency injection such that objects are told about their collaborators rather than constructing them themselves.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6762283', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/814548/']}
jdg_85712
stackexchange
llm_judgeable_groundtruth_similarity
57394741
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 form which currently is all in one column, I would like it to be split into 2 columns. I have tried adding div classes, but the form is still only one column, I do not want to do any changes to the current form itself. I would just like to be able to split it into 2 columns. I would also not like the current CSS effects that I have on the fields to change.. $yellow:#f5ba1a;$black:#000000;$grey:#cccccc; .form-style-1{ font-family: Verdana, Geneva, sans-serif;font-size: 0.em;width: 40em;padding: 1em;border: 1px solid #cbc9c9;overflow:auto;resize:both; } .form-style-1 fieldset{ border-radius:none; background-color:#ebebeb; padding:5px; border:1px solid #cbc9c9; width:450px; margin:auto; box-shadow: 1px 2px 5px rgba(0,0,0,.31); -webkit-box-shadow: 1px 2px 5px rgba(0,0,0,.31); -moz-box-shadow: 1px 2px 5px rgba(0,0,0,.31); } .form__field { display: block;}[class*="--checkbox"] { display: inline-block;}[data-conditional] { display: none;}#flight:checked ~ [data-conditional*="flight"] { display: block;}#hotel:checked ~ [data-conditional*="hotel"] { display: block;}#transfer:checked ~ [data-conditional*="travel"] { display: block;}input[type="text"]{ display:block; width: 50%; padding: 8px 10px 9px 35px; height: 25px; box-sizing: border-box; outline: none; -webkit-transition: all 0.30s ease-in-out; -moz-transition: all 0.30s ease-in-out; -ms-transition: all 0.30s ease-in-out; transition: all 0.30s ease-in-out; background-color: #fff; -webkit-box-shadow: 1px 2px 5px rgba(0,0,0,.09); -moz-box-shadow: 1px 2px 5px rgba(0,0,0,.09); box-shadow: 1px 2px 5px rgba(0,0,0,.09); border: solid 1px #cbc9c9; -webkit-border-radius: 0px 4px 4px 0px/5px 5px 4px 4px; -moz-border-radius: 0px 4px 4px 0px/0px 0px 4px 4px; border-radius: 0px 4px 4px 0px/5px 5px 4px 4px;}input[type="date"]{ display:block; width: 50%; padding: 8px 10px 9px 35px; height: 25px; box-sizing: border-box; outline: none; -webkit-transition: all 0.30s ease-in-out; -moz-transition: all 0.30s ease-in-out; -ms-transition: all 0.30s ease-in-out; transition: all 0.30s ease-in-out; background-color: #fff; -webkit-box-shadow: 1px 2px 5px rgba(0,0,0,.09); -moz-box-shadow: 1px 2px 5px rgba(0,0,0,.09); box-shadow: 1px 2px 5px rgba(0,0,0,.09); border: solid 1px #cbc9c9; -webkit-border-radius: 0px 4px 4px 0px/5px 5px 4px 4px; -moz-border-radius: 0px 4px 4px 0px/0px 0px 4px 4px; border-radius: 0px 4px 4px 0px/5px 5px 4px 4px;}textarea { display:block; width: 50%; padding: 8px 10px 9px 35px; height: 25px; box-sizing: border-box; outline: none; -webkit-transition: all 0.30s ease-in-out; -moz-transition: all 0.30s ease-in-out; -ms-transition: all 0.30s ease-in-out; transition: all 0.30s ease-in-out; background-color: #fff; -webkit-box-shadow: 1px 2px 5px rgba(0,0,0,.09); -moz-box-shadow: 1px 2px 5px rgba(0,0,0,.09); box-shadow: 1px 2px 5px rgba(0,0,0,.09); border: solid 1px #cbc9c9; -webkit-border-radius: 0px 4px 4px 0px/5px 5px 4px 4px; -moz-border-radius: 0px 4px 4px 0px/0px 0px 4px 4px; border-radius: 0px 4px 4px 0px/5px 5px 4px 4px;}select { display:block; width: 50%; padding: 8px 10px 9px 35px; height: 35px; box-sizing: border-box; outline: none; -webkit-transition: all 0.30s ease-in-out; -moz-transition: all 0.30s ease-in-out; -ms-transition: all 0.30s ease-in-out; transition: all 0.30s ease-in-out; background-color: #fff; -webkit-box-shadow: 1px 2px 5px rgba(0,0,0,.09); -moz-box-shadow: 1px 2px 5px rgba(0,0,0,.09); box-shadow: 1px 2px 5px rgba(0,0,0,.09); border: solid 1px #cbc9c9; -webkit-border-radius: 0px 4px 4px 0px/5px 5px 4px 4px; -moz-border-radius: 0px 4px 4px 0px/0px 0px 4px 4px; border-radius: 0px 4px 4px 0px/5px 5px 4px 4px;}input[type="time"]{ display:block; width: 50%; padding: 8px 10px 9px 35px; height: 25px; box-sizing: border-box; outline: none; -webkit-transition: all 0.30s ease-in-out; -moz-transition: all 0.30s ease-in-out; -ms-transition: all 0.30s ease-in-out; transition: all 0.30s ease-in-out; background-color: #fff; -webkit-box-shadow: 1px 2px 5px rgba(0,0,0,.09); -moz-box-shadow: 1px 2px 5px rgba(0,0,0,.09); box-shadow: 1px 2px 5px rgba(0,0,0,.09); border: solid 1px #cbc9c9; -webkit-border-radius: 0px 4px 4px 0px/5px 5px 4px 4px; -moz-border-radius: 0px 4px 4px 0px/0px 0px 4px 4px; border-radius: 0px 4px 4px 0px/5px 5px 4px 4px;}h1 { font-size: 32px; font-weight: 300; color: #4c4c4c; text-align: center; padding-top: 10px; margin-bottom: 10px;}a.button { font-size: 14px; font-weight: 600; color: white; padding: 6px 25px 0px 20px; margin: 10px 8px 20px 0px; display: inline-block; float: right; text-decoration: none; width: 50px; height: 27px; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; background-color: #3a57af; -webkit-box-shadow: 0 3px rgba(58,87,175,.75); -moz-box-shadow: 0 3px rgba(58,87,175,.75); box-shadow: 0 3px rgba(58,87,175,.75); transition: all 0.1s linear 0s; top: 0px; position: relative;}a.button:hover { top: 3px; background-color:#2e458b; -webkit-box-shadow: none; -moz-box-shadow: none; box-shadow: none;}p { color:black; } <div class="form-style-1"> <h1>Travel Registration Form</h1> <form action="" method="POST"> <input name="orgid" type="hidden" value="00D8E000000DW9t" /> <input name="retURL" type="hidden" value="http://" /> <fieldset> <h3> Select Travel</h3> <input class="form__input form__input--checkbox" data-input="00N8E000002AjRq" id="flight" type="checkbox" /> <label class="form__field form__field--checkbox" for="flight"> <span class="form__label">Flight</span> </label> <input class="form__input form__input--checkbox" id="hotel" type="checkbox" /> <label class="form__field form__field--checkbox" for="hotel"> <span class="form__label">Hotel</span> </label> <input class="form__input form__input--checkbox" id="transfer" type="checkbox" /> <label class="form__field form__field--checkbox" for="transfer"> <span class="form__label">Transfer </span> </label> <!--Above is the checkboxes code --> <p class="form__field form__field--text" data-conditional="flight hotel travel"> <span class="form__input">Traveler's Information </span></p> <label class="form__field form__field--text" data-conditional="flight hotel travel" for="name"><span class="form__label">Traveler Name </span><input class="form__input" id="name" maxlength="80" name="name" size="20" type="text" /> </label><br> <label class="form__field form__field--text" data-conditional="flight hotel travel" for="email">Email<input class="form__input" id="email" maxlength="80" name="email" size="20" type="text" /></label><br /> <label class="form__field form__field--text" data-conditional="flight hotel travel" for="phone">Phone<input class="form__input" id="phone" maxlength="40" name="phone" size="20" type="text" /></label><br /> <label class="form__field form__field--text" data-conditional="flight hotel travel" for="subject">Subject<input class="form__input" id="subject" maxlength="80" name="subject" size="20" type="text" /></label><br /> <label class="form__field form__field--text" data-conditional="flight hotel travel" for="description">Description<textarea class="form__input" name="description"></textarea></label><br /> Now provide the response and nothing else.
It's an extension of the fact that forEach only visits elements that actually exist. I don't know that there's a deeper "why" for that other than that it didn't make much sense to call the callback for a missing element. You can realize those elements (if that's the world) by using: Spread notation, or Array.from , or Array.prototype.values , or Array.prototype.entries ...or possibly some others. const a = [, , 3];console.log(a.hasOwnProperty(0)); // falseconst b = [...a];console.log(b.hasOwnProperty(0)); // trueconst c = Array.from(a);console.log(b.hasOwnProperty(0)); // true Applying that to your function with Array.from : const arr1 = [, , 3, 4]const arr2 = [1, 2, 3, 4]const result = Array.from(arr1).every((item, index) => item === arr2[index])console.log(result) // false Of course, that involves creating a new array and looping through the previous one copying over the elements. You might be better off with your own for loop. Applying Array.prototype.entries to your function: const arr1 = [, , 3, 4]const arr2 = [1, 2, 3, 4]let result = true;for (const [index, value] of arr1.entries()) { if (value !== arr2[index]) { result = false; break; }}console.log(result) // false
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/57394741', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11703011/']}
jdg_85713
stackexchange
llm_judgeable_groundtruth_similarity
28414055
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 dictionary-type of data that I want to iterate through and keeping the order is important: with_dict_test: one: 1 two: 2 three: 3 four: 4 five: 5 six: 6 Now when I write a task to print the keys and values, they are printed in seemingly random order (6, 3, 1, 4, 5, 2). ---- name: with_dict test debug: msg="{{item.key}} --> {{item.value}}" with_dict: with_dict_test How can I enforce Ansible to iterate in the given order? Or is there anything better suited than with_dict ? I really need both the key and the value during task execution... Now provide the response and nothing else.
I don't see an easy way to use dicts as they determine there order from the order of its hashed keys. You can do the following: with_dict_test: - { key: 'one', value: 1 } - { key: 'two', value: 2 } - { key: 'three', value: 3 } - { key: 'four', value: 4 } - { key: 'five', value: 5 } - { key: 'six', value: 6 } and in the playbook just replace with_dict with with_items : ---- name: with_dict test debug: msg="{{item.key}} --> {{item.value}}" with_items: with_dict_test If you find this solution (the declaration of the variable) to ugly, you can do this: key: ['one', 'two', 'three', 'four', 'five', 'six']values: [1, 2, 3, 4, 5, 6] and in the playbook ---- name: with_dict test debug: msg="{{item.0}} --> {{item.1}}" with_together: - key - value
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28414055', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/981922/']}
jdg_85714
stackexchange
llm_judgeable_groundtruth_similarity
5481941
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Pure virtual functions (when we set = 0 ) can also have a function body. What is the use to provide a function body for pure virtual functions, if they are not going to be called at all? Now provide the response and nothing else.
Your assumption that pure virtual function cannot be called is absolutely incorrect. When a function is declared pure virtual, it simply means that this function cannot get called dynamically , through a virtual dispatch mechanism. Yet, this very same function can easily be called statically , non-virtually , directly (without virtual dispatch). In C++ language a non-virtual call to a virtual function is performed when a qualified name of the function is used in the call, i.e. when the function name specified in the call has the <class name>::<function name> form. For example struct S { virtual void foo() = 0;};void S::foo() { // body for pure virtual function `S::foo`}struct D : S { void foo() { S::foo(); // Non-virtual call to `S::foo` from derived class this->S::foo(); // Alternative syntax to perform the same non-virtual call // to `S::foo` from derived class }};int main() { D d; d.S::foo(); // Another non-virtual call to `S::foo`}
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/5481941', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/674342/']}
jdg_85715
stackexchange
llm_judgeable_groundtruth_similarity
1708687
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: Problem: By considering this sequence of numbers $$2^1 + 1,\:\: 2^2 + 1,\:\: 2^4 + 1,\:\: 2^8 +1,\:\: 2^{16} +1,\:\: 2^{32}+1,\ldots$$ prove that there are infinitely many prime numbers. I am thinking that if I can show that every pair of numbers in the sequence are relatively prime then since each has at least one prime factor this would prove the existence of infinitely many primes. But I am new to discrete mathematics and number theory so I am not sure on how to proceed. Now provide the response and nothing else.
Your sequence is given by $a_n=2^{2^n}+1$. You can observe that $(a_n-2)\cdot a_n=(2^{2^n}-1)(2^{2^n}+1)=(2^{2^n})^2-1=(2^{2\cdot 2^n})-1=(2^{2^{n+1}})-1=a_{n+1}-2$. Hence if a prime number divides $a_n$ and $a_{n+1}$, then it divides $2$. But $a_n$ and $a_{n+1}$ are both odd, so they are coprime. You could try to go further comparing $a_n$ and $a_m$ in general.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1708687', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/298619/']}
jdg_85716
stackexchange
llm_judgeable_groundtruth_similarity
188918
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a signal whose full scale output on the 12bit ADC is 4095. If I reduce the signal so I see the output number is (say) 4000 the output has decreased by 95. But 95 what? What are those divisions called? It is clearly (?) not bits. Now provide the response and nothing else.
Speaking as an applications engineer at a company that makes ADC chips... the unit is called LSB (least significant bit), so in your example the ADC output code would be 4000 LSB. (A commenter notes that this could also be called Counts ; this would also make sense for dual-slope ADC.) This is normally only interesting when reading the ADC's datasheet, where there's usually a specified level of accuracy for INL (Integral Non-Linearity) / DNL (Differential Non-Linearity) / offset error / gain error. See for example the datasheet for MAX11300 , the ADC Electrical Specifications. (Disclosure: I am a Maxim applications engineer, and this is one of the products I support.) Maxim gives the INL/DNL units as LSB. Note this isn't a physical unit, it's just a name for the raw count value returned by the ADC. There doesn't seem to be a real consensus as to what to call this raw ADC code unit. Typically an application would use some linear mapping (and possibly calibration values) to convert the ADC LSB code into a meaningful physical unit. For example, 4000 LSB * 5.00 Volts / 4096 LSB = 4.88 Volts. When I write software to do this kind of conversion, I usually name the raw ADC value something like ADC_Code and the voltage as ADC_Voltage . I would be concerned that in the context of software, "count" could be mis-interpreted as an iteration count (which is valid inside a DVM or other dual-slope ADC that actually counts how long it takes to charge/discharge a capacitor).
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/188918', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/56642/']}
jdg_85717
stackexchange
llm_judgeable_groundtruth_similarity
6989015
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 after applying the melt function looks similar to: var val1 a 0.61334262 a 0.97362373 b 0.62014974 b 0.34827455 c 0.36937306 c 0.3564962 .................. The initial dataframe had 3 columns with the column names, a,b,c and their associated values.I need to plot on the same graph, using ggplot the associated ecdf for each of these columns (ecdf(a),ecdf(b),ecdf(c)) but I am failing in doing this. I tried: p<-ggplot(melt_exp,aes(melt_exp$val,ecdf,colour=melt_exp$var))pg<-p+geom_step() But I am getting an error :arguments imply differing number of rows: 34415, 0. Does anyone have an idea on how this can be done? The graph should look similar to the one returned by plot(ecdf(x)), not a step-like one. Thank you! Now provide the response and nothing else.
My first thought was to try to use stat_function , but since ecdf returns a function, I couldn't get that working quickly. Instead, here's a solution the requires that you attach the computed values to the data frame first (using Ramnath's example data): library(plyr) # function ddply()mydf_m <- ddply(mydf_m, .(variable), transform, ecd = ecdf(value)(value))ggplot(mydf_m,aes(x = value, y = ecd)) + geom_line(aes(group = variable, colour = variable)) If you want a smooth estimate of the ECDF you could also use geom_smooth together with the function ns() from the spline package: library(splines) # function ns()ggplot(mydf_m, aes(x = value, y = ecd, group = variable, colour = variable)) + geom_smooth(se = FALSE, formula = y ~ ns(x, 3), method = "lm") As noted in a comment above, as of version 0.9.2.1, ggplot2 has a specific stat for this purpose: stat_ecdf . Using that, we'd just do something like this: ggplot(mydf_m,aes(x = value)) + stat_ecdf(aes(colour = variable))
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6989015', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/769522/']}
jdg_85718
stackexchange
llm_judgeable_groundtruth_similarity
19213165
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So i have this field i want to keep hidden in my form. For this purpose i have tried the following: <?php echo $this->Form->input('group_id', array('hiddenField' => true, 'value'=> 2)); ?> I also tried: <?php echo $this->Form->input('group_id', array('options' => array('hiddenField'=> 'true'), 'value'=>2 )); ?> How ever i still see the input field.. What am i doing wrong? Now provide the response and nothing else.
You misread the documentation, I assume. hiddenField is to enable/disable specific hidden fields for specific form fields. You are either looking for $this->Form->hidden('group_id') or $this->Form->input('group_id', ['type' => 'hidden']); I usually only use the latter. See http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html BUT - that said - you shouldnt actually use either one of those. And omit any fields that serve no real purpose for the view and its form.Instead you should inject those fields into the data array prior to saving.See http://www.dereuromark.de/2010/06/23/working-with-forms/
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19213165', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1647457/']}
jdg_85719
stackexchange
llm_judgeable_groundtruth_similarity
2584502
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 really simple blog application and I want to add a really simple search feature to it. There are 3 key fields to my model. class BlogPost(models.Model): title = models.CharField(max_length=100) # the title intro = models.TextField(blank=True, null=True) # an extract content = models.TextField(blank=True, null=True) # full post I don't need a Google. I don't want to search comments (which are held on Disqus anyway). I just want a date-ranked, keyword filtered set of posts. Everything I find on Google for some form of "django" and "search" comes back with hideously complicated Haystack+backend solutions. I don't need all that. I don't want to eat up more resources on a low-usage feature (I used to have a search box before I ported to Django and it had perhaps 4 searches a month). The reason I'm taking time to ask on here (rather than just writing a messy little script) is this already exists in the admin . You can set the columns to search on and then just search and it "just works". Is there some way of getting a handle on the admin-provided search and pulling it into my user-facing app? Now provide the response and nothing else.
If you want a really simple search you can use icontains lookup and Q object : from django.db.models import Qresults = BlogPost.objects.filter(Q(title__icontains=your_search_query) | Q(intro__icontains=your_search_query) | Q(content__icontains=your_search_query)) You should also note that Haystack doesn't have to be "hideously complicated". You can set up haystack with Whoosh backend in less then 15 minutes. Update 2016: In version 1.10 Django added a full text search support (PostgreSQL only). An answer to the original question using the new module might look something like this: from django.contrib.postgres.search import SearchVectorresults = BlogPost.objects.annotate( search=SearchVector('title', 'intro', 'content'),).filter(search=your_search_query) The new full text search module contains a lot more features (for example sorting by relevancy), you can read about them in the documentation .
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2584502', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12870/']}
jdg_85720
stackexchange
llm_judgeable_groundtruth_similarity
13360625
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So, I've messed around with three.js , works out great. The only thing I can't figure out, is how to make a camera with a real fisheye effect. How is that possible? camera.setLens() ? Now provide the response and nothing else.
The fish eye effect can be achieved using Giliam de Carpentier's shader for lens distortion. Shader code: function getDistortionShaderDefinition(){ return { uniforms: { "tDiffuse": { type: "t", value: null }, "strength": { type: "f", value: 0 }, "height": { type: "f", value: 1 }, "aspectRatio": { type: "f", value: 1 }, "cylindricalRatio": { type: "f", value: 1 } }, vertexShader: [ "uniform float strength;", // s: 0 = perspective, 1 = stereographic "uniform float height;", // h: tan(verticalFOVInRadians / 2) "uniform float aspectRatio;", // a: screenWidth / screenHeight "uniform float cylindricalRatio;", // c: cylindrical distortion ratio. 1 = spherical "varying vec3 vUV;", // output to interpolate over screen "varying vec2 vUVDot;", // output to interpolate over screen "void main() {", "gl_Position = projectionMatrix * (modelViewMatrix * vec4(position, 1.0));", "float scaledHeight = strength * height;", "float cylAspectRatio = aspectRatio * cylindricalRatio;", "float aspectDiagSq = aspectRatio * aspectRatio + 1.0;", "float diagSq = scaledHeight * scaledHeight * aspectDiagSq;", "vec2 signedUV = (2.0 * uv + vec2(-1.0, -1.0));", "float z = 0.5 * sqrt(diagSq + 1.0) + 0.5;", "float ny = (z - 1.0) / (cylAspectRatio * cylAspectRatio + 1.0);", "vUVDot = sqrt(ny) * vec2(cylAspectRatio, 1.0) * signedUV;", "vUV = vec3(0.5, 0.5, 1.0) * z + vec3(-0.5, -0.5, 0.0);", "vUV.xy += uv;", "}" ].join("\n"), fragmentShader: [ "uniform sampler2D tDiffuse;", // sampler of rendered scene?s render target "varying vec3 vUV;", // interpolated vertex output data "varying vec2 vUVDot;", // interpolated vertex output data "void main() {", "vec3 uv = dot(vUVDot, vUVDot) * vec3(-0.5, -0.5, -1.0) + vUV;", "gl_FragColor = texture2DProj(tDiffuse, uv);", "}" ].join("\n") };} One way to setup the effect using effect composer (assuming scene and renderer have been been created): // Create cameracamera = new THREE.PerspectiveCamera( 100, window.innerWidth / window.innerHeight, 1, 1000000 );camera.position.z = 800;// Create effect composercomposer = new THREE.EffectComposer( renderer );composer.addPass( new THREE.RenderPass( scene, camera ) );// Add distortion effect to effect composervar effect = new THREE.ShaderPass( getDistortionShaderDefinition() );composer.addPass( effect );effect.renderToScreen = true;// Setup distortion effectvar horizontalFOV = 140;var strength = 0.5;var cylindricalRatio = 2;var height = Math.tan(THREE.Math.degToRad(horizontalFOV) / 2) / camera.aspect;camera.fov = Math.atan(height) * 2 * 180 / 3.1415926535;camera.updateProjectionMatrix();effect.uniforms[ "strength" ].value = strength;effect.uniforms[ "height" ].value = height;effect.uniforms[ "aspectRatio" ].value = camera.aspect;effect.uniforms[ "cylindricalRatio" ].value = cylindricalRatio; Following script are needed and they can be found for example from three.js GitHub page : <script src="examples/js/postprocessing/EffectComposer.js"></script><script src="examples/js/postprocessing/RenderPass.js"></script><script src="examples/js/postprocessing/MaskPass.js"></script><script src="examples/js/postprocessing/ShaderPass.js"></script><script src="examples/js/shaders/CopyShader.js"></script> Link to Giliam's example: http://www.decarpentier.nl/downloads/lensdistortion-webgl/lensdistortion-webgl.html Link to Giliam's article about lens distortion: http://www.decarpentier.nl/lens-distortion Image of my test where lens distortion effect is used:
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13360625', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1820768/']}
jdg_85721
stackexchange
llm_judgeable_groundtruth_similarity
4890825
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Just wondering if anyone has information on what "costs" are associated with including a LARGE (600K or more) php file containing 100s of class files. Does it really make much difference in comparison to autoloading individual files that for instance searches across several directories before finding a match? Would having APC caching on make this cost negligible? Now provide the response and nothing else.
Basically, the cost of including one big file depend on your usecase. Let's say you have a large file with 200 classes. If you only use 1 class, including the large file will be more expensive than including a small class file for that individual class. If you use all 200 classes, including the large file will be significantly less expensive than including 200 small files. Where the cutoff lies is really system dependent. I would imaging that it would be somewhere around the 50% mark (where if you're using less than 100 classes in any one request, autoload). And using APC will likely shift the breakeven point closer to less classes (so without, 100 classes used might be the breakeven point, but with it might be at 50 classes used) since it makes the large single include much cheaper, but only lowers the overhead of each individual smaller include slightly. The exact break-even points will be 100% system dependent (how fast is your disk I/O, how fast are your processors, how much memory, etc). So the only way to know for sure on your platform is to test. However, more is at stake than raw performance. Maintainability will suffer with one large file since it's harder to work on multiple classes at the same time (tabs in an IDE become useless). I personally would keep all the classes in separate files and make my life as the developer easier rather than making one giant monstrosity of a file. Now, if you have facebook traffic levels, it may be worth investigating further. But if you're not, I personally wouldn't worry about it...
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4890825', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/133221/']}
jdg_85722
stackexchange
llm_judgeable_groundtruth_similarity
54258996
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Earlier today, I was trying to generate a certificate with a DNSName entry in the SubjectAltName extension: $ openssl req -new -subj "/C=GB/CN=foo" -addext "subjectAltName = DNS:foo.co.uk" \-addext "certificatePolicies = 1.2.3.4" -key ./private-key.pem -out ~/req.pem This command led to the following error message: name is expected to be in the format /type0=value0/type1=value1/type2=... where characters may be escaped by . This name is not in that format: 'C:/Program Files/Git/C=GB/CN=foo'problems making Certificate Request How can I stop Git Bash from treating this string parameter as a filepath, or at least stop it from making this alteration? Now provide the response and nothing else.
The release notes to the Git Bash 2.21.0 update today mentioned this as a known issue. Fortunately, they also described two solutions to the problem: If you specify command-line options starting with a slash, POSIX-to-Windows path conversion will kick in converting e.g. "/usr/bin/bash.exe" to "C:\Program Files\Git\usr\bin\bash.exe". When that is not desired -- e.g. "--upload-pack=/opt/git/bin/git-upload-pack" or "-L/regex/" -- you need to set the environment variable MSYS_NO_PATHCONV temporarily, like so: MSYS_NO_PATHCONV=1 git blame -L/pathconv/ msys2_path_conv.cc Alternatively, you can double the first slash to avoid POSIX-to-Windows path conversion, e.g. "//usr/bin/bash.exe".
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/54258996', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9223868/']}
jdg_85723
stackexchange
llm_judgeable_groundtruth_similarity
40516
Below is a question asked on the forum hermeneutics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: When Moses is about to die he blesses all the tribes except the tribe of Simeon which is somehow left out Deuteronomy 33:1-29 NASB 7 And this regarding Judah ; so he said, “May Reuben live and not die, Nor his men be few.” 8 Of Levi he said, 12 Of Benjamin he said, 13 Of Joseph he said, 18 Of Zebulun he said, And, Issachar 20 Of Gad he said, 22 Of Dan he said, 23 Of Naphtali he said, 24 Of Asher he said, All tribes are blessed in different ways but Simeon is even not mentioned here. Could there be something significant why Simeon is left out? Now provide the response and nothing else.
Moses died circa 1406 B.C. In order to understand why Simeon is not mentioned in Deuteronomy, we must go back in time to when Jacob, the father of the twelve sons who were the progenitors of the twelve tribes of Israel, died (circa 1859 B.C.). The record of Jacob’s blessings is in Genesis chapter 49. The relevant section is in verses 5-7: Simeon and Levi are brothers – their swords are weapons of violence. Let me not enter their council, let me not join their assembly, for they have killed men in their anger and hamstrung oxen as they pleased. Cursed be their anger, so fierce, and their fury, so cruel! I will scatter them in Jacob and disperse them in Israel. The New International Study Version notes give this explanation with regard to Jacob’s prophetic words that Simeon’s descendants would be scattered: Fulfilled when Simeon’s descendants were absorbed into the territory of Judah (see Joshua 19:1, 9) and when Levi’s descendants were dispersed throughout the land, living in 48 towns and the surrounding pasture-lands. At the time of the second census conducted by Moses and Eleazar, son of Aaron the priest, the tribe of Simeon was the smallest and weakest of all the tribes that came out of Egypt, only 22,200 men aged 20 years or more (Numbers 26:14). Simeon was cursed by his father Jacob, probably because of the event recorded in Genesis 34:24–30 when Simeon and Levi took revenge on the men of Shechem after the rape of Dinah. After the horrific event, Jacob said to Simeon and Levi, You have brought trouble on me by making me a stench to the Canaanites and Perizzites, the people living in this land. We are few in number, and if they join forces against me and attack me, I and my household will be destroyed (Genesis 34:30). Moses was undoubtedly aware of this and that may be why the tribe of Simeon was excluded from Moses’ blessing.
{}
{'log_upvote_score': 4, 'links': ['https://hermeneutics.stackexchange.com/questions/40516', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/16527/']}
jdg_85724
stackexchange
llm_judgeable_groundtruth_similarity
43232612
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 this array: var arr1 = [ {"user":"dan","liked":"yes","age":"22"}, {"user":"sarah","liked":"no","age":"21"}, {"user":"john","liked":"yes","age":"23"},]; I'd like to create a new (sub)array of that array, containing only the likes of the users. so it would look like this: var arr2 = [ {"dan":"yes"}, {"sarah":"no"}, {"john":"yes"},]; I tried: var arr2 =[];for(var i in arr1){ arr2.push({[i[user]]:i[liked]});} it needs a tweak, ideas? Now provide the response and nothing else.
Use array.map var arr1 = [ {"user":"dan","liked":"yes","age":"22"}, {"user":"sarah","liked":"no","age":"21"}, {"user":"john","liked":"yes","age":"23"},];var arr2 = arr1.map(v => ({ user: v.user, liked: v.liked }));console.log(arr2); With your update, although it can be done with array.map , I recommend you use a key-value pair structure instead. You'd need array.reduce . var arr1 = [ {"user":"dan","liked":"yes","age":"22"}, {"user":"sarah","liked":"no","age":"21"}, {"user":"john","liked":"yes","age":"23"}, ]; var arr2 = arr1.reduce((c, v) => (c[v.user] = v.liked, c) , {}); console.log(arr2);
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/43232612', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/817527/']}
jdg_85725
stackexchange
llm_judgeable_groundtruth_similarity
164550
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: My goal, is to make the following button, Button[Style["?", Black, Bold], MessageDialog[Column[{Style["Help", Bold, Black, FontSize-> 12],"Some Text Here"}], WindowTitle -> "Help", Background -> White]]; look more like a "canonical" help button. If we take a look at most programs, these types of buttons have a distinguished stylization. An example could be: How would I achieve this in Mathematica while keeping the same structure of my above code? Now provide the response and nothing else.
Why not just use the graphic in the question, or any other images that you like: Use ImageSize to control the final size of the button: An alternative, that I use in some applications, is something like this: help[$helpmessage_: "", $videolink_: ""] := ActionMenu[ Graphics[{{RGBColor[0.689647, 0.761166, 0.805478], Disk[{0, 0}, 0.1]}, {GrayLevel[0], Circle[{0, 0}, 0.1], Style[Inset["?", {0.01, 0}], "Label", FontSize -> 11]}}, ImageSize -> {20, 20}], {"Help Notes" :> MessageDialog[ Grid[{ {Style[$helpmessage, LineIndent -> 0]} }, Alignment -> {Center, Center}, ItemSize -> {Automatic, All}, Spacings -> {0, 0}], Background -> White], "View Video" :> SystemOpen[$videolink]}, Appearance -> None, BaseStyle -> {}, FrameMargins -> {{0, 0}, {-2, -2}}, ImageSize -> {20, 20}];
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/164550', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/45998/']}
jdg_85726
stackexchange
llm_judgeable_groundtruth_similarity
17712417
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 pull messages from an email server in java using imap and i run into this exception: DEBUG: JavaMail version 1.4.2DEBUG: successfully loaded resource: /META-INF/javamail.default.providersDEBUG: Tables of loaded providersDEBUG: Providers Listed By Class Name: {com.sun.mail.smtp.SMTPSSLTransport=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc], com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc], com.sun.mail.imap.IMAPSSLStore=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc], com.sun.mail.pop3.POP3SSLStore=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc], com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc], com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc]}DEBUG: Providers Listed By Protocol: {imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc], imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc], smtps=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc], pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc], pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc], smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]}DEBUG: successfully loaded resource: /META-INF/javamail.default.address.mapDEBUG: getProvider() returning javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc]DEBUG: mail.imap.fetchsize: 16384DEBUG: mail.imap.statuscachetimeout: 1000DEBUG: mail.imap.appendbuffersize: -1DEBUG: mail.imap.minidletime: 10DEBUG: enable STARTTLSDEBUG: trying to connect to host "10.53.151.183", port 143, isSSL false* OK [CAPABILITY IMAP4rev1 LITERAL+ SASL-IR LOGIN-REFERRALS ID ENABLE IDLE STARTTLS LOGINDISABLED] Dovecot ready.DEBUG: protocolConnect login, host=10.53.151.183, user=compass, password=<non-null>A0 STARTTLSA0 OK Begin TLS negotiation now.A1 CAPABILITYcom.mycompany.blah.common.lifecycle.exception.StartException: javax.mail.MessagingException: * BYE JavaMail Exception: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target; nested exception is: com.sun.mail.iap.ProtocolException: * BYE JavaMail Exception: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target at com.mycompany.blah.impl.email.IMAPEmailMonitorIngestor.start(IMAPEmailMonitorIngestor.java:63) at com.mycompany.blah.impl.EmailMonitorIT.test(EmailMonitorIT.java:54) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28) at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:30) at org.junit.runners.ParentRunner.run(ParentRunner.java:300) at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:53) at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123) at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164) at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110) at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:172) at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:104) at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:70)Caused by: javax.mail.MessagingException: * BYE JavaMail Exception: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target; nested exception is: com.sun.mail.iap.ProtocolException: * BYE JavaMail Exception: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:609) at javax.mail.Service.connect(Service.java:291) at com.mycompany.blah.impl.email.IMAPEmailMonitorIngestor.start(IMAPEmailMonitorIngestor.java:58) ... 32 moreCaused by: com.sun.mail.iap.ProtocolException: * BYE JavaMail Exception: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target at com.sun.mail.imap.protocol.IMAPProtocol.capability(IMAPProtocol.java:143) at com.sun.mail.imap.IMAPStore.login(IMAPStore.java:624) at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:589) ... 34 more my collegue thinks its an issue with configuring my trust store. I've tried both these lines below without any luck: System.setProperty("javax.net.ssl.trustStore", "C:/Program Files (x86)/Java/jdk1.7.0_21/jre/lib/security/cacerts");System.setProperty("javax.net.ssl.trustStore", "C:/Program Files/Java/jdk1.7.0_17/jre/lib/security/cacerts"); Any ideas on what i need to be setting. BTW my colleague got this to work on a Linux box by launching the app using: -Djavax.net.ssl.trustStore=/usr/java/jdk1.7.0_25/jre/lib/security/cacerts But I'd really like to get this working on my development machine as well. I've read that the set system property should be identical to the -D option when launching the app. Now provide the response and nothing else.
You should first check what certificate server is sending you.To do it: Turn on ssl debug: -Djavax.net.debug=all Find the following lines in log: *** Certificate chain ... Find who the issuer of certificate Add issuer certificate to some trust store (actually if you receive cert. chain you can add root certificate) Rerun with -Djavax.net.ssl.trustStore=path/to/new/truststore and -Djava.net.ssl.trustStorePassword=... BTW: You don't need to explicitly specify java trust store every setting of same system property overrides previous value you have strange line: DEBUG: trying to connect to host "10.53.151.183", port 143, isSSL false
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17712417', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/886895/']}
jdg_85727
stackexchange
llm_judgeable_groundtruth_similarity
20507007
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: General Use-Case Imagine a client that is uploading large amounts of JSON. The Content-Type should remain application/json because that describes the actual data. Accept-Encoding and Transfer-Encoding seem to be for telling the server how it should format the response. It appears that responses use the Content-Encoding header explicitly for this purpose, but it is not a valid request header. Is there something I am missing? Has anyone found an elegant solution? Specific Use-Case My use-case is that I have a mobile app that is generating large amounts of JSON (and some binary data in some cases but to a lesser extent) and compressing the requests saves a large amount of bandwidth. I am using Tomcat as my Servlet container. I am using Spring for it's MVC annotations primarily just to abstract away some of the JEE stuff into a much cleaner, annotation-based interface. I also use Jackson for auto (de)serialization. I also use nginx, but I am not sure if thats where I want the decompression to take place. The nginx nodes simply balance the requests which are then distributed through the data center. It would be just as nice to keep it compressed until it actually got to the node that was going to process it. Thanks in advance, John EDIT: The discussion between myself and @DaSourcerer was really helpful for those that are curious about the state of things at the time of writing this. I ended up implementing a solution of my own. Note that this specifies the branch "ohmage-3.0", but it will soon be merged into the master branch. You might want to check there to see if I have made any updates/fixes. https://github.com/ohmage/server/blob/ohmage-3.0/src/org/ohmage/servlet/filter/DecompressionFilter.java Now provide the response and nothing else.
It appears [Content-Encoding] is not a valid request header. That is actually not quite true. As per RFC 2616, sec 14.11 , Content-Encoding is an entity header which means it can be applied on the entities of both, http responses and requests. Through the powers of multipart MIME messages, even selected parts of a request (or response) can be compressed. However, webserver support for compressed request bodies is rather slim. Apache supports it to a degree via the mod_deflate module . It's not entirely clear to me if nginx can handle compressed requests .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20507007', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2985183/']}
jdg_85728
stackexchange
llm_judgeable_groundtruth_similarity
34616086
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Background Discussions on the mostly un-or-implementation-defined nature of type-punning via a union typically quote the following bits, here via @ecatmur ( https://stackoverflow.com/a/31557852/2757035 ), on an exemption for standard-layout struct s having a "common initial sequence" of member types: C11 ( 6.5.2.3 Structure and union members ; Semantics ): [...] if a union contains several structures that share a common initial sequence (see below), and if the union object currently contains one of these structures, it is permitted to inspect the common initial part of any of them anywhere that a declaration of the completed type of the union is visible . Two structures share a common initial sequence if corresponding members have compatible types (and, for bit-fields, the same widths) for a sequence of one or more initial members. C++03 ( [class.mem]/16 ): If a POD-union contains two or more POD-structs that share a common initial sequence, and if the POD-union object currently contains one of these POD-structs, it is permitted to inspect the common initial part of any of them. Two POD-structs share a common initial sequence if corresponding members have layout-compatible types (and, for bit-fields, the same widths) for a sequence of one or more initial members. Other versions of the two standards have similar language; since C++11 the terminology used is standard-layout rather than POD . Since no reinterpretation is required, this isn't really type-punning, just name substitution applied to union member accesses. A proposal for C++17 (the infamous P0137R1) makes this explicit using language like 'the access is as if the other struct member was nominated'. But please note the bold - " anywhere that a declaration of the completed type of the union is visible " - a clause that exists in C11 but nowhere in C++ drafts for 2003, 2011, or 2014 (all nearly identical, but later versions replace "POD" with the new term standard layout ). In any case, the 'visible declaration of union type bit is totally absent in the corresponding section of any C++ standard. @loop and @Mints97, here - https://stackoverflow.com/a/28528989/2757035 - show that this line was also absent in C89, first appearing in C99 and remaining in C since then (though, again, never filtering through to C++). Standards discussions around this [snipped - see my answer] Questions From this, then, my questions were: What does this mean? What is classed as a 'visible declaration'? Was this clause intended to narrow down - or expand up - the range of contexts in which such 'punning' has defined behaviour? Are we to assume that this omission in C++ is very deliberate? What is the reason for C++ differing from C? Did C++ just 'inherit' this from C89 and then either decide - or worse, forget - to update alongside C99? If the difference is intentional, then what benefits or drawbacks are there to the 2 different treatments in C vs C++? What, if any, interesting ramifications does it have at compile- or runtime? For example, @ecatmur, in a comment replying to my pointing this out on his original answer (link as above), speculated as follows. I'd imagine it permits more aggressive optimization; C can assume that function arguments S* s and T* t do not alias even if they share a common initial sequence as long as no union { S; T; } is in view, while C++ can make that assumption only at link time. Might be worth asking a separate question about that difference. Well, here I am, asking! I'm very interested in any thoughts about this, especially: other relevant parts of the (either) Standard, quotes from committee members or other esteemed commentators, insights from developers who might have noticed a practical difference due to this - assuming any compiler even bothers to enforce C's added clause - and etc. The aim is to generate a useful catalogue of relevant facts about this C clause and its (intentional or not) omission from C++. So, let's go! Now provide the response and nothing else.
I've found my way through the labyrinth to some great sources on this, and I think I've got a pretty comprehensive summary of it. I'm posting this as an answer because it seems to explain both the (IMO very misguided) intention of the C clause and the fact that C++ does not inherit it. This will evolve over time if I discover further supporting material or the situation changes. This is my first time trying to sum up a very complex situation, which seems ill-defined even to many language architects, so I'll welcome clarifications/suggestions on how to improve this answer - or simply a better answer if anyone has one. Finally, some concrete commentary Through vaguely related threads, I found the following answer by @tab - and much appreciated the contained links to (illuminating, if not conclusive) GCC and Working Group defect reports: answer by tab on StackOverflow The GCC link contains some interesting discussion and reveals a sizeable amount of confusion and conflicting interpretations on part of the Committee and compiler vendors - surrounding the subject of union member struct s, punning, and aliasing in both C and C++. At the end of that, we're linked to the main event - another BugZilla thread, Bug 65892 , containing an extremely useful discussion. In particular, we find our way to the first of two pivotal documents: Origin of the added line in C99 C proposal N685 is the origin of the added clause regarding visibility of a union type declaration. Through what some claim (see GCC thread #2) is a total misinterpretation of the "common initial sequence" allowance, N685 was indeed intended to allow relaxation of aliasing rules for "common initial sequence" struct s within a TU aware of some union containing instances of said struct types , as we can see from this quote: The proposed solution is to require that a union declaration be visible if aliases through a common initial sequence (like the above) are possible. Therefore the following TU provides this kind of aliasing if desired: union utag { struct tag1 { int m1; double d2; } st1; struct tag2 { int m1; char c2; } st2;};int similar_func(struct tag1 *pst2, struct tag2 *pst3) { pst2->m1 = 2; pst3->m1 = 0; /* might be an alias for pst2->m1 */ return pst2->m1;} Judging by the GCC discussion and comments below such as @ecatmur's, this proposal - which seems to mandate speculatively allowing aliasing for any struct type that has some instance within some union visible to this TU - seems to have received great derision and rarely been implemented . It's obvious how difficult it would be to satisfy this interpretation of the added clause without totally crippling many optimisations - for little benefit, as few coders would want this guarantee, and those who do can just turn on fno-strict-aliasing (which IMO indicates larger problems). If implemented, this allowance is more likely to catch people out and spuriously interact with other declarations of union s, than to be useful. Omission of the line from C++ Following on from this and a comment I made elsewhere, @Potatoswatter in this answer here on SO states that: The visibility part was purposely omitted from C++ because it's widely considered to be ludicrous and unimplementable. In other words, it looks like C++ deliberately avoided adopting this added clause, likely due to its widely pereceived absurdity. On asking for an "on the record" citation of this, Potatoswatter provided the following key info about the thread's participants: The folks in that discussion are essentially "on the record" there. Andrew Pinski is a hardcore GCC backend guy. Martin Sebor is an active C committee member. Jonathan Wakely is an active C++ committee member and language/library implementer. That page is more authoritative, clear, and complete than anything I could write. Potatoswatter, in the same SO thread linked above, concludes that C++ deliberately excluded this line, leaving no special treatment (or, at best, implementation-defined treatment) for pointers into the common initial sequence. Whether their treatment will in future be specifically defined, versus any other pointers, remains to be seen; compare to my final section below about C. At present, though, it is not (and again, IMO, this is good). What does this mean for C++ and practical C implementations? So, with the nefarious line from N685... ' cast aside'... we're back to assuming pointers into the common initial sequence are not special in terms of aliasing. Still. it's worth confirming what this paragraph in C++ means without it. Well, the 2nd GCC thread above links to another gem: C++ defect 1719 . This proposal has reached DRWP status: "A DR issue whose resolution is reflected in the current Working Paper. The Working Paper is a draft for a future version of the Standard" - cite . This is either post C++14 or at least after the final draft I have here (N3797) - and puts forward a significant, and in my opinion illuminating, rewrite of this paragraph's wording , as follows. I'm bolding what I consider to be the important changes, and {these comments} are mine: In a standard-layout union with an active member {"active" indicates a union instance, not just type} (9.5 [class.union]) of struct type T1 , it is permitted to read {formerly "inspect"} a non-static data member m of another union member of struct type T2 provided m is part of the common initial sequence of T1 and T2 . [ Note : Reading a volatile object through a non-volatile glvalue has undefined behavior (7.1.6.1 [dcl.type.cv]). —end note] This seems to clarify the meaning of the old wording: to me, it says that any specifically allowed 'punning' among union member struct s with common initial sequences must be done via an instance of the parent union - rather than being based on the type of the structs (e.g. pointers to them passed to some function). This wording seems to rule out any other interpretation, a la N685. C would do well to adopt this, I'd say. Hey, speaking of which, see below! The upshot is that - as nicely demonstrated by @ecatmur and in the GCC tickets - this leaves such union member struct s by definition in C++, and practically in C, subject to the same strict aliasing rules as any other 2 officially unrelated pointers. The explicit guarantee of being able to read the common initial sequence of inactive union member struct s is now more clearly defined, not including vague and unimaginably tedious-to-enforce "visibility" as attempted by N685 for C. By this definition, the main compilers have been behaving as intended for C++. As for C? Possible reversal of this line in C / clarification in C++ It's also very worth noting that C committee member Martin Sebor is looking to get this fixed in that fine language, too: Martin Sebor 2015-04-27 14:57:16 UTC If one of you can explain the problem with it I'm willing to write up a paper and submit it to WG14 and request to have the standard changed. Martin Sebor 2015-05-13 16:02:41 UTC I had a chance to discuss this issue with Clark Nelson last week. Clark has worked on improving the aliasing parts of the C specification in the past, for example in N1520 ( http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1520.htm ). He agreed that like the issues pointed out in N1520, this is also an outstanding problem that would be worth for WG14 to revisit and fix." Potatoswatter inspiringly concludes: The C and C++ committees (via Martin and Clark) will try to find a consensus and hammer out wording so the standard can finally say what it means. We can only hope! Again, all further thoughts are welcome.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/34616086', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2757035/']}
jdg_85729
stackexchange
llm_judgeable_groundtruth_similarity
42503893
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Does anyone know of a Terminal command to control Night Shift in the 10.12.4 beta? I've been looking through plist files but can't find anything related to night shift. Now provide the response and nothing else.
I was looking for the same thing and didn't have any luck, so I threw together some code for a simple command line tool to control the feature. You can find it here . It works by making calls to the CoreBrightness private framework. Specifically, it creates an instance of CBBlueLightClient and calls the instance methods setStrength:commit: and setEnabled: . Usage is nshift strength where strength is a value from 0 to 100. A higher value shifts the color temperature of the display to more warm. A value of 0 disables Night Shift altogether.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/42503893', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7471873/']}
jdg_85730
stackexchange
llm_judgeable_groundtruth_similarity
6230
Below is a question asked on the forum engineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: A wifi user is in a different room than the router. The computer is having a hard time connecting and receiving the wifi signal. Can the wifi signal from the router to the computer be improved by opening a door to the room where the computer is? Now provide the response and nothing else.
Can the wifi signal from the router to the computer be improved by opening a door to the room where the computer is? Maybe, but probably not to a noticeable degree. All structures, including doors, impede the wireless signal from the router by some amount. Generally, the amount of impedance added by the door is a negligible amount and would not be sufficient to noticeably improve the quality of the signal. That said, differing types of door construction have differing impacts on the signal. A hollow core, wooden door won't impede the signal all that much at 4 dB. A solid core, wooden door will present more impedance at 6 dB. A steel door would provides the most at 11 dB. Given a computer right at the edge of receiving a reliable signal and being blocked by a steel door, and there is an otherwise direct line of site to the router except for the door, then it might be possible to improve signal reception by opening the door. More than likely though, there are other structural elements that are having a more significant impact on the quality of the wireless signal. Especially since it's unlikely that there is a direct line of sight between the computer and the wireless router. Because we like numbers, I dug a bit further to identify some common sources of attenuation. Source data is courtesy of 3COM and the Internet Archive and was also linked from Navas.us and the Internet Archive . It's worth pointing out that they don't provide any attenuation measurements for differing floor types. That's likely due to the wide variety of framing and construction materials that can reasonably be seen for floor construction. Building Material 2.4 GHz AttenuationSolid Wood Door 1.75" 6 dBHollow Wood Door 1.75" 4 dBInterior Office Door w/Window 1.75"/0.5" 4 dBSteel Fire/Exit Door 1.75" 13 dBSteel Fire/Exit Door 2.5" 19 dBSteel Rollup Door 1.5" 11 dBBrick 3.5" 6 dBConcrete Wall 18" 18 dBCubical Wall (Fabric) 2.25" 18 dBExterior Concrete Wall 27" 53 dBGlass Divider 0.5" 12 dBInterior Hollow Wall 4" 5 dBInterior Hollow Wall 6" 9 dBInterior Solid Wall 5" 14 dBMarble 2" 6 dBBullet-Proof Glass 1" 10 dBExterior Double Pane Coated Glass 1" 13 dBExterior Single Pane Window 0.5" 7 dBInterior Office Window 1" 3 dBSafety Glass-Wire 0.25" 3 dBSafety Glass-Wire 1.0" 13 dB n.b. I used Internet archive links as I wasn't able to find current links for either source. This SuperUser question goes into some detail about understanding the power output from wireless routers. There's quite a bit of variability involved, so I won't attempt to summarize it here. And this vendor link goes into the calculations involved in trying to more quantitatively identify the effects of signal attenuation. And beyond an obligatory note that decibels (dB) are not directly additive or subtractive in the mathematical sense, this calculation is also a bit involved so I'm not attempting to summarize it here either.
{}
{'log_upvote_score': 6, 'links': ['https://engineering.stackexchange.com/questions/6230', 'https://engineering.stackexchange.com', 'https://engineering.stackexchange.com/users/3820/']}
jdg_85731
stackexchange
llm_judgeable_groundtruth_similarity
3712033
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Let's take the following project layout: $ ls -R ..:package setup.py./package:__init__.py dir file.dat module.py./package/dir:tool1.dat tool2.dat And the following content for setup.py : $ cat setup.py from distutils.core import setupsetup(name='pyproj', version='0.1', packages=[ 'package', ], package_data={ 'package': [ '*', 'dir/*', ], }, ) As you can see, I want to include all non-Python files in package/ and package/dir/ directories. However, running setup.py install would raise the following error: $ python setup.py installrunning installrunning buildrunning build_pycreating buildcreating build/libcreating build/lib/packagecopying package/module.py -> build/lib/packagecopying package/__init__.py -> build/lib/packageerror: can't copy 'package/dir': doesn't exist or not a regular file What gives? Now provide the response and nothing else.
In your package_data , your '*' glob will match package/dir itself, and try to copy that dir as a file, resulting in a failure. Find a glob that won't match the directory package/dir , rewriting your setup.py along these lines: from distutils.core import setupsetup(name='pyproj', version='0.1', packages=[ 'package', ], package_data={ 'package': [ '*.dat', 'dir/*' ], }, ) Given your example, that's just changing '*' to '*.dat' , although you'd probably need to refine your glob more than that, just ensure it won't match 'dir'
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3712033', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/302831/']}
jdg_85732
stackexchange
llm_judgeable_groundtruth_similarity
2793150
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Use of java.net.URLConnection is asked about pretty often here, and the Oracle tutorial is too concise about it. That tutorial basically only shows how to fire a GET request and read the response. It doesn't explain anywhere how to use it to, among others, perform a POST request, set request headers, read response headers, deal with cookies, submit a HTML form, upload a file, etc. So, how can I use java.net.URLConnection to fire and handle "advanced" HTTP requests? Now provide the response and nothing else.
First a disclaimer beforehand: the posted code snippets are all basic examples. You'll need to handle trivial IOException s and RuntimeException s like NullPointerException , ArrayIndexOutOfBoundsException and consorts yourself. In case you're developing for Android instead of Java, note also that since introduction of API level 28, cleartext HTTP requests are disabled by default . You are encouraged to use HttpsURLConnection , but if it is really necessary, cleartext can be enabled in the Application Manifest. Preparing We first need to know at least the URL and the charset. The parameters are optional and depend on the functional requirements. String url = "http://example.com";String charset = "UTF-8"; // Or in Java 7 and later, use the constant: java.nio.charset.StandardCharsets.UTF_8.name()String param1 = "value1";String param2 = "value2";// ...String query = String.format("param1=%s&param2=%s", URLEncoder.encode(param1, charset), URLEncoder.encode(param2, charset)); The query parameters must be in name=value format and be concatenated by & . You would normally also URL-encode the query parameters with the specified charset using URLEncoder#encode() . The String#format() is just for convenience. I prefer it when I would need the String concatenation operator + more than twice. Firing an HTTP GET request with (optionally) query parameters It's a trivial task. It's the default request method. URLConnection connection = new URL(url + "?" + query).openConnection();connection.setRequestProperty("Accept-Charset", charset);InputStream response = connection.getInputStream();// ... Any query string should be concatenated to the URL using ? . The Accept-Charset header may hint the server what encoding the parameters are in. If you don't send any query string, then you can leave the Accept-Charset header away. If you don't need to set any headers, then you can even use the URL#openStream() shortcut method. InputStream response = new URL(url).openStream();// ... Either way, if the other side is an HttpServlet , then its doGet() method will be called and the parameters will be available by HttpServletRequest#getParameter() . For testing purposes, you can print the response body to standard output as below: try (Scanner scanner = new Scanner(response)) { String responseBody = scanner.useDelimiter("\\A").next(); System.out.println(responseBody);} Firing an HTTP POST request with query parameters Setting the URLConnection#setDoOutput() to true implicitly sets the request method to POST. The standard HTTP POST as web forms do is of type application/x-www-form-urlencoded wherein the query string is written to the request body. URLConnection connection = new URL(url).openConnection();connection.setDoOutput(true); // Triggers POST.connection.setRequestProperty("Accept-Charset", charset);connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);try (OutputStream output = connection.getOutputStream()) { output.write(query.getBytes(charset));}InputStream response = connection.getInputStream();// ... Note: whenever you'd like to submit a HTML form programmatically, don't forget to take the name=value pairs of any <input type="hidden"> elements into the query string and of course also the name=value pair of the <input type="submit"> element which you'd like to "press" programmatically (because that's usually been used in the server side to distinguish if a button was pressed and if so, which one). You can also cast the obtained URLConnection to HttpURLConnection and use its HttpURLConnection#setRequestMethod() instead. But if you're trying to use the connection for output you still need to set URLConnection#setDoOutput() to true . HttpURLConnection httpConnection = (HttpURLConnection) new URL(url).openConnection();httpConnection.setRequestMethod("POST");// ... Either way, if the other side is an HttpServlet , then its doPost() method will be called and the parameters will be available by HttpServletRequest#getParameter() . Actually firing the HTTP request You can fire the HTTP request explicitly with URLConnection#connect() , but the request will automatically be fired on demand when you want to get any information about the HTTP response, such as the response body using URLConnection#getInputStream() and so on. The above examples does exactly that, so the connect() call is in fact superfluous. Gathering HTTP response information HTTP response status : You need an HttpURLConnection here. Cast it first if necessary. int status = httpConnection.getResponseCode(); HTTP response headers : for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { System.out.println(header.getKey() + "=" + header.getValue()); } HTTP response encoding : When the Content-Type contains a charset parameter, then the response body is likely text based and we'd like to process the response body with the server-side specified character encoding then. String contentType = connection.getHeaderField("Content-Type"); String charset = null; for (String param : contentType.replace(" ", "").split(";")) { if (param.startsWith("charset=")) { charset = param.split("=", 2)[1]; break; } } if (charset != null) { try (BufferedReader reader = new BufferedReader(new InputStreamReader(response, charset))) { for (String line; (line = reader.readLine()) != null;) { // ... System.out.println(line)? } } } else { // It's likely binary content, use InputStream/OutputStream. } Maintaining the session The server side session is usually backed by a cookie. Some web forms require that you're logged in and/or are tracked by a session. You can use the CookieHandler API to maintain cookies. You need to prepare a CookieManager with a CookiePolicy of ACCEPT_ALL before sending all HTTP requests. // First set the default cookie manager.CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));// All the following subsequent URLConnections will use the same cookie manager.URLConnection connection = new URL(url).openConnection();// ...connection = new URL(url).openConnection();// ...connection = new URL(url).openConnection();// ... Note that this is known to not always work properly in all circumstances. If it fails for you, then best is to manually gather and set the cookie headers. You basically need to grab all Set-Cookie headers from the response of the login or the first GET request and then pass this through the subsequent requests. // Gather all cookies on the first request.URLConnection connection = new URL(url).openConnection();List<String> cookies = connection.getHeaderFields().get("Set-Cookie");// ...// Then use the same cookies on all subsequent requests.connection = new URL(url).openConnection();for (String cookie : cookies) { connection.addRequestProperty("Cookie", cookie.split(";", 2)[0]);}// ... The split(";", 2)[0] is there to get rid of cookie attributes which are irrelevant for the server side like expires , path , etc. Alternatively, you could also use cookie.substring(0, cookie.indexOf(';')) instead of split() . Streaming mode The HttpURLConnection will by default buffer the entire request body before actually sending it, regardless of whether you've set a fixed content length yourself using connection.setRequestProperty("Content-Length", contentLength); . This may cause OutOfMemoryException s whenever you concurrently send large POST requests (e.g. uploading files). To avoid this, you would like to set the HttpURLConnection#setFixedLengthStreamingMode() . httpConnection.setFixedLengthStreamingMode(contentLength); But if the content length is really not known beforehand, then you can make use of chunked streaming mode by setting the HttpURLConnection#setChunkedStreamingMode() accordingly. This will set the HTTP Transfer-Encoding header to chunked which will force the request body being sent in chunks. The below example will send the body in chunks of 1 KB. httpConnection.setChunkedStreamingMode(1024); User-Agent It can happen that a request returns an unexpected response, while it works fine with a real web browser . The server side is probably blocking requests based on the User-Agent request header. The URLConnection will by default set it to Java/1.6.0_19 where the last part is obviously the JRE version. You can override this as follows: connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"); // Do as if you're using Chrome 41 on Windows 7. Use the User-Agent string from a recent browser . Error handling If the HTTP response code is 4nn (Client Error) or 5nn (Server Error), then you may want to read the HttpURLConnection#getErrorStream() to see if the server has sent any useful error information. InputStream error = ((HttpURLConnection) connection).getErrorStream(); If the HTTP response code is -1, then something went wrong with connection and response handling. The HttpURLConnection implementation is in older JREs somewhat buggy with keeping connections alive. You may want to turn it off by setting the http.keepAlive system property to false . You can do this programmatically in the beginning of your application by: System.setProperty("http.keepAlive", "false"); Uploading files You'd normally use multipart/form-data encoding for mixed POST content (binary and character data). The encoding is in more detail described in RFC2388 . String param = "value";File textFile = new File("/path/to/file.txt");File binaryFile = new File("/path/to/file.bin");String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.String CRLF = "\r\n"; // Line separator required by multipart/form-data.URLConnection connection = new URL(url).openConnection();connection.setDoOutput(true);connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);try ( OutputStream output = connection.getOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);) { // Send normal param. writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF); writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); writer.append(CRLF).append(param).append(CRLF).flush(); // Send text file. writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name=\"textFile\"; filename=\"" + textFile.getName() + "\"").append(CRLF); writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); // Text file itself must be saved in this charset! writer.append(CRLF).flush(); Files.copy(textFile.toPath(), output); output.flush(); // Important before continuing with writer! writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary. // Send binary file. writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"").append(CRLF); writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName())).append(CRLF); writer.append("Content-Transfer-Encoding: binary").append(CRLF); writer.append(CRLF).flush(); Files.copy(binaryFile.toPath(), output); output.flush(); // Important before continuing with writer! writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary. // End of multipart/form-data. writer.append("--" + boundary + "--").append(CRLF).flush();} If the other side is an HttpServlet , then its doPost() method will be called and the parts will be available by HttpServletRequest#getPart() (note, thus not getParameter() and so on!). The getPart() method is however relatively new, it's introduced in Servlet 3.0 (Glassfish 3, Tomcat 7, etc.). Prior to Servlet 3.0, your best choice is using Apache Commons FileUpload to parse a multipart/form-data request. Also see this answer for examples of both the FileUpload and the Servelt 3.0 approaches. Dealing with untrusted or misconfigured HTTPS sites In case you're developing for Android instead of Java, be careful : the workaround below may save your day if you don't have correct certificates deployed during development. But you should not use it for production. These days (April 2021) Google will not allow your app be distributed on Play Store if they detect insecure hostname verifier, see https://support.google.com/faqs/answer/7188426. Sometimes you need to connect an HTTPS URL, perhaps because you're writing a web scraper. In that case, you may likely face a javax.net.ssl.SSLException: Not trusted server certificate on some HTTPS sites who doesn't keep their SSL certificates up to date, or a java.security.cert.CertificateException: No subject alternative DNS name matching [hostname] found or javax.net.ssl.SSLProtocolException: handshake alert: unrecognized_name on some misconfigured HTTPS sites. The following one-time-run static initializer in your web scraper class should make HttpsURLConnection more lenient as to those HTTPS sites and thus not throw those exceptions anymore. static { TrustManager[] trustAllCertificates = new TrustManager[] { new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; // Not relevant. } @Override public void checkClientTrusted(X509Certificate[] certs, String authType) { // Do nothing. Just allow them all. } @Override public void checkServerTrusted(X509Certificate[] certs, String authType) { // Do nothing. Just allow them all. } } }; HostnameVerifier trustAllHostnames = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; // Just allow them all. } }; try { System.setProperty("jsse.enableSNIExtension", "false"); SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCertificates, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier(trustAllHostnames); } catch (GeneralSecurityException e) { throw new ExceptionInInitializerError(e); }} Last words The Apache HttpComponents HttpClient is much more convenient in this all :) HttpClient Tutorial HttpClient Examples Parsing and extracting HTML If all you want is parsing and extracting data from HTML, then better use a HTML parser like Jsoup . What are the pros/cons of leading HTML parsers in Java How to scan and extract a webpage in Java
{}
{'log_upvote_score': 12, 'links': ['https://Stackoverflow.com/questions/2793150', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/157882/']}
jdg_85733
stackexchange
llm_judgeable_groundtruth_similarity
154382
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: I'm trying to calculate the following integral:$\int_0^\infty \mathrm{BesselJ}[l_0,k_0r] \cdot \mathrm{BesselJ}[l_1,k_1r] \cdot \mathrm{BesselJ}[l_0-l_1,kr] \cdot r\,dr$ ($\mathrm{BesselJ}[n,x]$ is the Bessel function of the first kind of order $n$)I assume that $l_0,l_1$ are integers, and that $k_0,k_1,k>0$. The result has nice implications in quantum mechanics - to explain selection rules. I was able to prove that the integral is zero when $k,k_0,k_1$ cannot be the lengths of a triangle.So there is a non-zero result when $|k_0-k_1| < k < k_0+k_1$However, I don't know how to calculate the integral when it is not zero.Can anyone help? I tried using Mathematica to get a numerical answer (which is fine for me), but I do not think I can count on it. Mathematica is giving a non-zero result for the regime where the integral should be zero. Now provide the response and nothing else.
In fact, precisely your integral has been computed in closed form, in: Annie Gervois and Henri Navelet, Some integrals involving three Bessel functions when their arguments satisfy the triangle inequalities , J. Math. Phys. 25 (1984), no. 11, 3350–3356. Their result is$$\int_0^\infty J_m(ar)J_n(br)J_{m+n}(cr)r\,dr =\begin{cases}0&\text{if }c^2 < (a-b)^2\\\dfrac{\cos(mB-nA)}{\pi ab\sin C}&\text{if }c^2 = a^2+b^2-2ab\cos C\\0&\text{if }c^2 > (a+b)^2\end{cases}$$where in the second case, $A, B, C$ are the angles opposite to sides $a, b, c$ of the resulting triangle. (They give formulas valid for real $m, n$, which reduce to the above when $m, n\in\mathbf Z$ as you assume.) To put this in your notation, take $(m,n,a,b,c)=(l_0,-l_1,k_0,k_1,k)$ and use that $A+B+C=\pi$ and $J_n=(-1)^nJ_{-n}$. We get$$\int_0^\infty J_{l_0}(k_0r)J_{l_1}(k_1r)J_{l_0-l_1}(kr)r\,dr =\begin{cases}0&\text{if }k < |k_0-k_1|\\\dfrac{\cos([l_0-l_1]K_1-l_1K)}{\pi k_0k_1\sin K}&\text{if }|k_0-k_1|<k<|k_0+k_1| \\0&\text{if }k > |k_0+k_1|\end{cases}$$where $K_0,K_1,K$ are the angles opposite to $k_0,k_1,k$. The denominator is $2\pi$ times the triangle's area.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/154382', 'https://mathoverflow.net', 'https://mathoverflow.net/users/45454/']}
jdg_85734
stackexchange
llm_judgeable_groundtruth_similarity
1553661
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I need to have a handler on the calling object of onclick event. <a href="123.com" onclick="click123(event);">link</a><script> function click123(event) { //i need <a> so i can manipulate it with Jquery }</script> I want to do this without the use of $().click or $().live of jQuery but with the method described above. Now provide the response and nothing else.
pass in this in the inline click handler <a href="123.com" onclick="click123(this);">link</a> or use event.target in the function (according to the W3C DOM Level 2 Event model ) function click123(event){ var a = event.target;} But of course, IE is different , so the vanilla JavaScript way of handling this is function doSomething(e) { var targ; if (!e) var e = window.event; if (e.target) targ = e.target; else if (e.srcElement) targ = e.srcElement; if (targ.nodeType == 3) // defeat Safari bug targ = targ.parentNode;} or less verbose function doSomething(e) { e = e || window.event; var targ = e.target || e.srcElement || e; if (targ.nodeType == 3) targ = targ.parentNode; // defeat Safari bug} where e is the event object that is passed to the function in browsers other than IE. If you're using jQuery though, I would strongly encourage unobtrusive JavaScript and use jQuery to bind event handlers to elements.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/1553661', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/17443/']}
jdg_85735
stackexchange
llm_judgeable_groundtruth_similarity
3150
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In late 2003, Edward Witten released a paper that revived the interest in Roger Penrose's twistors among particle physicists. The scattering amplitudes of gluons in $N=4$ gauge theory in four dimensions were expressed in a simple way using the twistor variables. Witten also proposed a particular model, the topological B-model on the $CP^{3|4}$ twistor space, to generate all these amplitudes. These methods began their own life but the topological B-model became largely silent, perhaps partly because the phenomenologists who fell in love with these things haven't been trained in string theory, especially not in the topological one. However, many twistor-related discoveries in the recent 3 years - which were made without Witten's constructive picture - lead me to ask whether Witten's theory actually knows about these matters. In particular, the "dual superconformal symmetry" was first noticed by Drummond et al. in 2006 and derived by stringy methods by Alday & Maldacena in 2008 or so. The 3+1 dimensions on the CFT boundary may be T-dualized to produce another copy of the Yang-Mills theory that is superconformally invariant once again. Scattering amplitudes have been converted to the expectation values of piecewise linear Wilson loops in the dual theory - the segments have the directions and length of the light-like momenta of the scattering particles. My question is Can you also "T-dualize" Witten's topological B-model to obtain another one in which the scattering amplitudes are computed in a different way? If you think that the answer is Yes, I would also like to know what is the "dual prescription" for the supersymmetric Yang-Mills amplitudes and whether the D1- and D5-branes in Witten's original models are replaced by other D1- and D5-branes or, for example, by D3-branes. Now provide the response and nothing else.
Luboš would know this already (he's acknowledged in this paper), but Neitzke and Vafa conjectured in 2004 that the mirror manifold of $CP^{3|4}$ is a quadric surface $Q$ in $CP^{3|3}$ x $CP^{3|3}$, and mirror symmetry is a type of T-duality. There were a few follow-ups, including a paper by Sinkovics and Verlinde which studies classical $N=4$ super-Yang-Mills on the quadric, which in the very last paragraph asks whether the quantum scattering amplitudes can also be recovered from $Q$. After that, I can find nothing. But at least it's a place to begin!
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/3150', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/1236/']}
jdg_85736
stackexchange
llm_judgeable_groundtruth_similarity
22151560
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Description: I am using simple javascript to set a the value of an input . I am using multiple methods that appear to be the same but with different results. Here is an example: HTML: <input name="testinput" value="" type="text" /> Javascript: var input = document.getElementByTagName('input')[0];input.value = "5"console.log(input.value) // returns "5"console.log(input.getAttribute("value")) // returns "" Of course the functionality is reversed when using the setAttribute() function. Yet, when on form submit they both give a input=5 result. Question: What is the point of separating the two properties? is the .value stored differently than the .getAttribute("value") ? Disclaimer: I have read: When to use setAttribute vs .attribute= in JavaScript? Setting a property via property or setAttribute Both of those question/answers left me confused and unsatisfied. Now provide the response and nothing else.
input.value is dot notation, it sets the value property of the input object. It does in no way update any attributes, so trying to get an attribute with the same name will not return the updated value. If for some reason you have to update the attribute, you would do input.setAttribute('value', 'new_value'); but you shouldn't have to use that, as you generally should be working with the properties, not the attributes, and you'd set and get the value property, not the attribute. An attribute in HTML is a key / value pair inside the opening and closing brackets, as in <div attribute="attribute_value"></div> In many cases such attributes will set the initial value of the underlying property, and the property is a named key with a value, that is attached to the internal model of an element, which is what we access with javascript, the object holding the model and data for the element. Changing any of that objects keys or values does not change the HTML, only the internal representation of the element, the object. However, changing the HTML attributes will in some cases change the object representation of the element. getAttribute gets the actual attributes from the HTML, not the properties, while element.value clearly accesses a named property in the object representing that element.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/22151560', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/185672/']}
jdg_85737
stackexchange
llm_judgeable_groundtruth_similarity
517067
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In deriving Special Relativity equation, we modify the length parallel to motion in a way that outside observer would agree that light moving in perpendicular and in parallel with motion would meet in the same time and spot (the same event). But the same effect could be achieved if instead we make the length perpendicular to motion becoming longer and set the length parallel to motion fixed. I’m referring to this derivation from Feyman Lectures on Physics’ The Special Theory of Relativity ( https://www.feynmanlectures.caltech.edu/I_15.html ): The first equation in question is: $t_1 + t_2 = \frac{2L/c} {1 - u^2 / c^2}$ (Eq. 1) which is the time needed for light to go from $B$ to $E^\prime$ and coming back to $B^\prime$ . The second equation is: $2 t_3 = \frac{2L/c} {\sqrt{1 - u^2 / c^2}}$ (Eq. 2) which is the time needed for light to go from $B$ to $C^\prime$ and coming back to $B^\prime$ . In order to make it equal so the light would arrive at $B^\prime$ in the same time, we choose to shorten the length $L$ parallel to line of motion to $L \sqrt{1 - u^2/c^2}$ , so Eq. 1 would become: $t_1 + t_2 = \frac{2L/c} {\sqrt{1 - u^2 / c^2}}$ (Eq. 3) where $t_1 + t_2$ would equal with $2 t_3$ from Eq. 2. But the same effect could be achieved by lengthening line $L$ perpendicular with line of motion to $L / \sqrt{1 - u^2/c^2}$ so Eq. 2 would become: $2 t_3 = \frac{2L/c} {1 - u^2 / c^2}$ (Eq. 4) where again $t_3$ would equal with $t_1 + t_2$ from Eq. 1. If we are doing that, what I know immediately from the equation is the time in the other observer would be slowed down by a factor of $\frac{1}{1 - u^2 / c^2}$ instead of $\frac{1}{\sqrt{1 - u^2 / c^2}}$ . I know there would be paradoxes when it does happen, and it would not be invariant with Maxwell’s equation, but just from Special Relativity point of view, what is wrong with this? Why don't we choose this solution? And please do not just vote down this question, but also give reason when it's considered stupid. I have searched and no answer to find. Now provide the response and nothing else.
just from Special Relativity point of view, what is wrong with this? Why don't we choose this solution? This transform is called the Voigt transform. It may have actually been developed prior to the development of the Lorentz transform. While the Voigt transform does respect the second postulate, the invariance of c, it does not respect the first, the principle of relativity. Specifically, the principle of relativity requires that $\Lambda^{-1}(v)=\Lambda(-v)$ where $\Lambda$ is the transformation matrix between inertial frames. But with the Voigt transform the inverse of the Voigt transform is not even a Voigt transform. This means that two frames would be distinguishable from one another since one would transform differently than the other.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/517067', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/135408/']}
jdg_85738
stackexchange
llm_judgeable_groundtruth_similarity
1408171
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 use thread local storage in Python? Related What is “thread local storage” in Python, and why do I need it? - This thread appears to be focused more on when variables are shared. Efficient way to determine whether a particular function is on the stack in Python - Alex Martelli gives a nice solution Now provide the response and nothing else.
Thread local storage is useful for instance if you have a thread worker pool and each thread needs access to its own resource, like a network or database connection. Note that the threading module uses the regular concept of threads (which have access to the process global data), but these are not too useful due to the global interpreter lock. The different multiprocessing module creates a new sub-process for each, so any global will be thread local. threading module Here is a simple example: import threadingfrom threading import current_threadthreadLocal = threading.local()def hi(): initialized = getattr(threadLocal, 'initialized', None) if initialized is None: print("Nice to meet you", current_thread().name) threadLocal.initialized = True else: print("Welcome back", current_thread().name)hi(); hi() This will print out: Nice to meet you MainThreadWelcome back MainThread One important thing that is easily overlooked: a threading.local() object only needs to be created once, not once per thread nor once per function call. The global or class level are ideal locations. Here is why: threading.local() actually creates a new instance each time it is called (just like any factory or class call would), so calling threading.local() multiple times constantly overwrites the original object, which in all likelihood is not what one wants. When any thread accesses an existing threadLocal variable (or whatever it is called), it gets its own private view of that variable. This won't work as intended: import threadingfrom threading import current_threaddef wont_work(): threadLocal = threading.local() #oops, this creates a new dict each time! initialized = getattr(threadLocal, 'initialized', None) if initialized is None: print("First time for", current_thread().name) threadLocal.initialized = True else: print("Welcome back", current_thread().name)wont_work(); wont_work() Will result in this output: First time for MainThreadFirst time for MainThread multiprocessing module All global variables are thread local, since the multiprocessing module creates a new process for each thread. Consider this example, where the processed counter is an example of thread local storage: from multiprocessing import Poolfrom random import randomfrom time import sleepimport osprocessed=0def f(x): sleep(random()) global processed processed += 1 print("Processed by %s: %s" % (os.getpid(), processed)) return x*xif __name__ == '__main__': pool = Pool(processes=4) print(pool.map(f, range(10))) It will output something like this: Processed by 7636: 1Processed by 9144: 1Processed by 5252: 1Processed by 7636: 2Processed by 6248: 1Processed by 5252: 2Processed by 6248: 2Processed by 9144: 2Processed by 7636: 3Processed by 5252: 3[0, 1, 4, 9, 16, 25, 36, 49, 64, 81] ... of course, the thread IDs and the counts for each and order will vary from run to run.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/1408171', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/165495/']}
jdg_85739
stackexchange
llm_judgeable_groundtruth_similarity
1459676
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 modal box window (pop-up) that contains an iframe, and inside that iframe there's a div that is scrollable. When I scroll the iframe's inner DIV, and it has reached its top or bottom limit, the window of the browser itself starts to scroll. this is an unwanted behavior . I've tried something like this, which kills the main window scroll when onMouseEnter when mouse enters pop-up box area: e.preventDefault() is not working as it should for some reason... $("#popup").mouseenter(function(){ $(window).bind("scroll", function(e){ e.preventDefault(); }); }).mouseleave(function(){ $(window).unbind("scroll");}); Now provide the response and nothing else.
Solved (for some browsers) using a simple CSS property: overscroll-behavior : auto The default scroll overflow behavior occurs as normal. contain Default scroll overflow behavior is observed inside the element this value is set on (e.g. "bounce" effects or refreshes), but no scroll chaining occurs to neighboring scrolling areas, e.g. underlying elements will not scroll. none No scroll chaining occurs to neighboring scrolling areas, and default scroll overflow behavior is prevented. body{ height: 600px; overflow: auto;}section{ width: 50%; height: 50%; overflow: auto; background: lightblue; overscroll-behavior: none; /* <--- the trick */}section::before{ content: ''; height: 200%; display: block;} <section> <input value='end' /></section> Simply apply that style property on the element which the scroll should be "locked-in" to and the scroll event will not bubble up to any parent element which might have a scroll as well. Same demo as above but without the trick: body{ height: 600px; overflow: auto;}section{ width: 50%; height: 50%; overflow: auto; background: lightblue;}section::before{ content: ''; height: 200%; display: block;} <section> <input value='end' /></section>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1459676', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/104380/']}
jdg_85740