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
|
54701224
|
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 in the process of moving over to react-testing-library, and have no idea how to trigger this event and get the results of the changes. I've tried using the fireEvent function to trigger the change, and then tried the rerender function, but I can't seem to get it to work. App.js import React, { useState } from "react";import logo from "./logo.svg";import "./App.css";const options = { DoTheThing: 'DoTheThing', DoOtherThing: 'DoOtherThing',};function App() { const [action, setAction] = useState(options.DoTheThing); return ( <div className="App"> <header className="App-header"> <form> <fieldset> <label> <input type="radio" name="radio1" value={options.DoTheThing} checked={action === options.DoTheThing} onChange={event => setAction(event.target.value)} /> First </label> <label> <input type="radio" name="radio1" value={options.DoOtherThing} checked={action === options.DoOtherThing} onChange={event => setAction(event.target.value)} /> Second </label> </fieldset> </form> </header> </div> );}export default App; App.test.js import React from 'react';import { render, cleanup, fireEvent } from 'react-testing-library';import App from './App';afterEach(cleanup);it('should change the value ', () => { const {getByLabelText, rerender } = render(<App/>); const second = getByLabelText(/Second/); fireEvent.change(second); rerender(<App/>); expect(document.forms[0].elements.radio1.value).toEqual("DoOtherThing");});
Now provide the response and nothing else.
|
Update As people pointed out my original solution was wrong. Nowadays I suggest you use userEvent for better-simulating user interactions. import { render, screen } from "@testing-library/react";import userEvent from "@testing-library/user-event";test("radio", () => { const user = userEvent.setup(); render( <form> <label> First <input type="radio" name="radio1" value="first" /> </label> <label> Second <input type="radio" name="radio1" value="second" /> </label> </form> ) await user.click(screen.getByLabelText("Second"));}); First, you don't have to call rerender . You use rerender only when you want the component to receive different props. See link . Whenever you call fireEvent the component will render like it would in your normal app. It's correct to fire a change event, but you must pass a second parameter with the event data. This example works: import React from "react";import { render, fireEvent } from "react-testing-library";test("radio", () => { const { getByLabelText } = render( <form> <label> First <input type="radio" name="radio1" value="first" /> </label> <label> Second <input type="radio" name="radio1" value="second" /> </label> </form> ); const radio = getByLabelText('First') fireEvent.change(radio, { target: { value: "second" } }); expect(radio.value).toBe('second')});
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/54701224', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/168005/']}
|
jdg_372041
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
472588
|
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 simple pre-made buck converter that looks something like this: The output voltage can be easily adjusted, by turning the R2 trimpot, which adjusts the voltage the feedback pin is getting. What I would like to do, is to take this mechanical way of setting the output voltage and change it to a digital one, where I can set the output voltage I want with something like an Arduino. My first idea was to simply rip out the R2 trimpot and replace it with a digital potentiometer, but this turned out to be a no-go, since the digital pots I have (and most cheap digi pots I have seen) have voltage limits of around 0 - 5V, and I will be outputting voltages between 1.2 - 23V (The power source feeding the buck is 24V) My second idea would be to somehow use an op amp to replace the R2 trimpot, but I have not been able to figure out how to go about this. What would be some simple way to achieve my goal?
Now provide the response and nothing else.
|
Put the digipot in R1's position. The max normal voltage seen at the FB pin will only be +1.25 volts so a 5 volt device will be fine. However, there might be fault circumstances when this might rise above 5 volts so put a zener diode across that point. The other end of the digipot will be at 0 volts so this is another advantage. However, a digipot will introduce capacitance that may cause ringing in the regulator's output voltage and this might require you to have a small capacitor across R2 (about 47 pF). You should also consider that using a digipot as a rheostat has two disadvantages: - The end-to-end resistance of the pot isn't accurately defined so there will be a larger error than when using a conventional fixed resistor Digipots are much better in terms of temperature stability when operated as a potentiometer rather than a rheostat.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/472588', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/190922/']}
|
jdg_372042
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
107551
|
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a question / confusion about stationary series required for modeling with ARIMA(X). I am thinking of this more in terms of inference (effect of an intervention), but would like to know if forecasting versus inference makes any difference in the response. Question: All the introductory resources I have read state that the series needs to be stationary, which makes sense to me and that is where the "I" in arima comes in (differencing). What confuses me is the use of trends and drifts in ARIMA(X) and implications (if any) for stationary requirements. Does the use of either a constant/drift term and/or trend variable as an exogenous variable (i.e. adding 't' as a regressor) negate the requirement of the series being stationary? Is the answer different depending on if the series has a unit root (e.g. adf test) or has a deterministic trend but no unit root? OR Does a series always have to be stationary, made so via differencing and/or detrending before using ARIMA(X)?
Now provide the response and nothing else.
|
Looking at the comments it seems that we didn't address the question about how to choose between a deterministic or stochastic trend. That is, how to proceed in practice rather than the consequences or properties of each case. One way to proceed is the following: Start by applying the ADF test. If the null of a unit root is rejected we are done. The trend (if any) can be represented by a deterministic linear trend. If the null of the ADF test is not rejected then we apply the KPSS test (where the null hypothesis is the opposite, stationarity or stationarity around a linear trend). o If the null of the KPSS test is rejected then we conclude that there is a unit root and work with the first differences of the data. Upon the first differences of the series we can test the significance of other regressors or choose an ARMA model. o If the null of the KPSS test is not rejected then we would have to say that the data are not much informative because we weren't able to reject none the of the null hypotheses. In this case it may be safer to work with the first differences of the series. As mentioned in a previous answer, remember that these tests may be affected by the presence of outliers (e.g. an outlier at a single time point due to an error when recording the data or a level shift due for example to a policy change that affects the series from a given time point on). Thus, it is advisable to check these issues as well and repeat the previous analysis after including regressors for some potential outliers.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/107551', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/2040/']}
|
jdg_372043
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
257668
|
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 am trying to simplify an expression and find a closed form for$$\sum_{m=0}^l \binom{s-m}{s-l} \binom{s-1+m}{s-1}x^m$$ How could I get rid of this summation?
Now provide the response and nothing else.
|
You may argue as GH from MO from your other post . the coefficient of $y^m$ in $(1-xy)^{-s}$ equals $\binom{s+m-1}{s-1}x^m$; the coefficient of $y^{\ell-m}$ in $(1-y)^{\ell-s-1}$ equals $\binom{s-m}{s-\ell}$. Therefore, the sum on your LHS equals to the coefficient of $y^{\ell}$ in $(1-xy)^{-s}(1-y)^{\ell-s-1}$. Unfortunately, this has no closed form. How can we be sure? To this end, denote your sum by$$f(\ell):=\sum_{m=0}^\ell\binom{s+m-1}{s-1}\binom{s-m}{s-\ell}x^m.$$As I explained the WZ-method in the other post , the procedure generates a recurrence. However, this time it is a three-term relation$$(\ell+2)f(\ell+2)+(-sx-\ell x-s+2\ell-x+2)f(\ell+1)+(x-1)(s-\ell)f(\ell)=0$$ which reveals that $f(s)$ can not have a closed form. If you're not interested in the sum, then formulate this as a contour integral. Let $\gamma$ be a closed path (oriented positive) around $z=0$, and apply Cauchy's Integral Formula :$$f(\ell)=\frac1{2\pi i}\int_{\gamma}\frac{dz}{z^{\ell+1}(1-xz)^s(1-z)^{s+1-\ell}}.$$On a positive note, we can derive a generating function for the sequence $f(\ell)$:$$\sum_{\ell=0}^{\infty}f(\ell)y^{\ell}=\left(\frac{(1+y)^2}{1+y-xy}\right)^s.$$To see this, start by interchanging summations to proceed as follows:\begin{align} \sum_{\ell\geq0}f(\ell)y^{\ell}&=\sum_{m\geq0}\binom{s+m-1}mx^m\sum_{\ell=m}^s\binom{s-m}{\ell-m}y^{\ell} \\&=\sum_{m\geq0}\binom{s+m-1}mx^my^m(1+y)^{s-m} \\&=(1+y)^s\sum_{m=0}^{\infty}\binom{s+m-1}m\left(\frac{yx}{1+y}\right)^m \\&=(1+y)^s\left(1-\frac{yx}{1+y}\right)^{-s} \\&=\left(\frac{(1+y)^2}{1+y-xy}\right)^s.\end{align}
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/257668', 'https://mathoverflow.net', 'https://mathoverflow.net/users/102529/']}
|
jdg_372044
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
613121
|
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm observing a strange behaviour in some of my PCBs: they start working only when I spray isopropyl alcohol on them (or, to be more specific, the boost converter starts doing his job only after I spray it with alcohol, while connected to a power supply). Let me explain this further: given this schematic, if I apply 3.8 volts (with a bench power supply at the moment, but I tried with a lithium polymer battery, too) to the "BATT" connectors, I expect get 3.3 V out of the TPS61201, but I get 0 V. At this point, if I spray some isopropyl alcohol (IPA) over the general area where the TPS61201 sits, I get 3.3 V out of it, and it will keep on supplying 3.3 V until I shut the bench supply off (let it run for more than 5 hours). I'm observing this behavior in the last two PCBs I've soldered, but the three I soldered before these worked flawlessly, so I'm inclined to think that the flaw lies with my handywork (I am currently using a hot air station to solder the components in question), but I can't explain the strange behavior with the alcohol. Any idea why this might happen? Here is a photo of the soldered TPS61201: If it may help, here is a screen of the board's layout. . I've done some probing around the converter, as suggested, and here are my findings: When the converter "doesn't work": Vin: 3.9 V EN: 3.9 V PS: 3.9 V FB: 0 V Vout: 0 V UVLO: ~272 mV After a quick spray: Vin: 3.9 V EN: 3.9 V PS: 3.9 V FB: 3.35 V Vout: 3.35 V UVLO: ~272 mV I've ordered a can of freeze spray for further testing and I'm thinking of a way to measure my board temperature around the converter, to rule out a thermal protection problem. I'm trying to "digest" all the suggestions, but it may take me some time, for my background is lacking in the field, so bear with me. Ok, maybe I find the issue, thanks to @TonyStewartEE75 and @BruceAbbott answer and comment. I didn't understand the UVLO hysteresis at all: according to the datasheet the rising UVLO voltage (that is, if I get this correctly, the minimum voltage needed to turn the converter on) is 350 mV. Back to the UVLO threshold formula I went ( datasheet par 11.2.2.2) and this is what I got: $$2700000 = 249000 *(x/0.35 - 1)\\x = 4.14$$ So I cranked up my Vin from 3.9 V to 4.2 V and the converter works as intended. It seems that I have to switch my R9 resistor with another with more "sane" values, for I doubt my single cell lithium polymer battery would ever reach the full 4.2 V, preventing my board from ever switching on.
Now provide the response and nothing else.
|
The isopropyl alcohol will increase surface capacitance by 18 times or more depending on thickness and then reduces as it evaporates. I am inclined to believe the design is marginal for bias resistors for UVLO, yet follows the datasheet. "The typical current into the UVLO pin is 0.01 μA, and the voltage across R4 is equal to the UVLO voltage threshold that is generated on-chip, which has a value of 250 mV. Therefore, the recommended value for R4 is in the range of 250 kΩ" You can measure UVLO or raise it to confirm it is OK. Then report all pin conditions of OK and not OK with a DSO . But only use the needle coil on the tip/ring of a 10:1 probe.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/613121', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/309925/']}
|
jdg_372045
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14180003
|
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 writing RSpec tests and I have come to a point where I am not reading the same opinions on different websites. The directory structure for RSpec is clear when we are dealing with spec/controllers and spec/models directories, but the conflicting information I am getting deals with testing views. I would like to just put these tests in a spec/integration/ directory, but I have read that it's supposed to be under spec/integration, but another book says spec/requests. Does this matter? To further complicate the situation, I have read conflicting information on naming the actual file names of the tests! For example, if I had a controller/model/view directory called 'people' (I i use haml), I should name the files like this: spec/integration/people.html.haml_spec.rb However, another book suggests this: spec/requests/people_spec.rb I would like a little explanation of naming conventions within RSpec and WHY I should name the view tests specific names, as well as whether or not it matters to put them under spec/integration or spec/requests. I feel like I'm going with the wind here. Any help is greatly appreciated.
Now provide the response and nothing else.
|
Check the dates of the books and the versions of RSpec for which they were written. The naming structure has changed slightly over time. According to the docs for rspec-rails , request specs can go in spec/requests, spec/api, or spec/integration. I prefer to put request specs in spec/requests. To make things more interesting, if you are using Capybara with rspec-rails, it will work with spec/requests for Capybara 1.x, and spec/features for Capybara 2. As to individual spec file names, when there is a specific class under test, like a Rails model, you should use an analogous spec file name: app/models/user.rb -> spec/models/user_spec.rb View specs should use the template name: app/views/users/index.html.erb -> spec/views/users/index.html.erb_spec.rb Namespaced models should include the namespace in the spec file path: app/models/admin/user.rb -> spec/models/admin/user_spec.rb The RSpec scaffold generator is a good guide for showing where these specs belong. When there is no specific class under test, as is the case with request specs, IMHO you should feel free to use a name that describes the thing being tested. E.g. spec/requests/place_an_order_spec.rb .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14180003', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/363243/']}
|
jdg_372046
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2804424
|
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 help verifying why I am getting an incorrect answer for the question evaluate the integral $$\int \tan\left(\frac{x}{3}\right) \, dx$$ I simplify the above equation using trig identities to get$$\int \frac {\sin \left(\frac{x}{3}\right)}{\cos\left(\frac{x}{3}\right)} \, dx$$ I use the substitution method to find $$ du = -\frac{1}{3} \sin(x/3) \, dx$$ and so $dx = \frac{-3\,du}{\sin\frac{x}{3}}$ I plug the $u$ back into equation$$ \int \frac {\sin\left(\frac{x}{3}\right)}{u} \cdot\frac {-3\,du}{\sin \left(\frac{x}{3}\right)}$$ I cross out the $\sin \left(\frac{x}{3}\right)$ and (this is where I may be going wrong), I pull out the $-3$ to be in front of the integral sign since it is a constant and solve for$$-3 \int \frac{1}{u} \, du$$ and get the final answer $$ -3 \biggl|\,\ln \, \cos \frac{x}{3}\biggr| + C $$ But the answer in the back of the book is $ -\frac{1}{3} |\ln \, \cos \frac{x}{3}| + C $
Now provide the response and nothing else.
|
Your book is wrong! As a check, $$\frac{d}{dx}\left(-\frac13\bigg|\ln\cos\frac x3\bigg|\right)=-\frac1{3\cos\frac x3}\cdot\left(-\frac13\sin\frac x3\right)=\color{red}{\frac19}\tan\frac x3\neq \tan\frac x3.$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2804424', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/543604/']}
|
jdg_372047
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3707442
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In C++, for example fmod(-2,2) returns -0 . The expression -0 == 0 is true, but the bits are different. What is the purpose of having something like -0 which should be 0 but is represented differently? Is -0 used exactly the same way as 0 in any computations?
Now provide the response and nothing else.
|
No, +0 and -0 are not used in the same way in every computation. For example: 3·(+0) = +0+0/-3 = -0 I suggest you to read What Every Computer Scientist Should Know About Floating-point arithmetic by David Goldberg, that sheds a light on why +0 and -0 are needed in floating point arithmetic and in which way they differ. Examples on how +0 ad -0 differ (and why that can be useful when dealing with complex values) can be found in Kahan, W. 1987. Branch Cuts for Complex Elementary Functions, in "The State of the Art in Numerical Analysis" (I wasn't able to find a pdf of this article, you may find one at your local university library).
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3707442', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/316448/']}
|
jdg_372048
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1208
|
Below is a question asked on the forum biology.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am looking for a large collection (>1000) of sequence files (eg. FASTA) from any real organism or a tool to create such a collection. The sequence files would be used for teaching and for testing automation methods. Students would be assigned one unique sequence file and asked to look at it (eg. using gORF) and to identify it (using BLASTn). The sequence file would thus need to contain only the sequence data (no meta data about species or gene). I would need an associated answer sheet.
Now provide the response and nothing else.
|
Here is the approach I ended up using, in part thanks to all the contributions here. The associated R script is below or can be downloaded from: BOLDS SEQUENCE RECOVERY This creates 999 unique sequence files in plain text, with each sequence being identified to species level and few species being found across more than one sequence. It also creates the matching answer key. You can start at a random location to so that files change every year/group. I used R to query the BOLDS database (Barcode of Life), to download a file and to split this huge file into separate sequences. Here is the R script rm(list=ls())complete<-"http://services.boldsystems.org/eFetch.php?record_type=full&id_type=sampleid&ids=(*)&return_type=text"write(complete, file="your location on disk")rm(list=ls())sequences.id<-data.frame("file.name", "recordID", "genus_name", "species_name")write.table(x=sequences.id, file="sequences_id.csv", append=F, sep = ",", row.names=F, col.names=F)set.seed(10)start<-sample(1:1000, size=1)i<-startk<-1while(k < 1000){ sequences<-read.delim(file=complete, skip=i, nrows=1, header=F) sequence.compare<-read.csv(file="sequences_id.csv", skip=k-1, nrows=1, header=F) if(! is.na(sequences$V24)){ if(as.character(sequences$V24)!=as.character(sequence.compare$V4)){ writeLines(text=as.character(sequences$V55), con=paste(k, ".txt", sep="")) sequences.id<-c(k, sequences[,c("V3","V22", "V24")]) write.table(x=sequences.id, file="sequences_id.csv", append=T, sep = ",", row.names=F, col.names=F) print("kept") k<-k+1 } } i<-i+1 print(paste(k,"/", i))}
|
{}
|
{'log_upvote_score': 4, 'links': ['https://biology.stackexchange.com/questions/1208', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/553/']}
|
jdg_372049
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
105192
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
For surfaces there are many statements along the lines of: if two simple closed curves are homotopic, they are isotopic. I'm interested in such questions for families of curves. More precisely, let $\Sigma$ be a hyperbolic surface, possibly with boundary. We fix an essential simple closed curve $\gamma$ on $\Sigma$. It is true that the subspace of $Emb(S^1,\Sigma)$ consisting of those curves that are isotopic to $\gamma$ is homotopy equivalent to a circle? Here the circle would come from reparametrisation of the curves. This statement is true if we instead look at the space of all continuous (or smooth) maps of $S^1$ into $\Sigma$ that are homotopic to $\gamma$. Also note that this seems to be false for the torus, as for any essential simple closed curve we get at least $S^1 \times S^1$.
Now provide the response and nothing else.
|
Earlier than Grayson, the determination of the homotopy-types of these spaces was done by Gramain. There are a few special cases, like the torus and sphere and the non-orientable analogue, the case of null curves. But if they're not null homotopic the components of the embedding space have the homotopy type of $S^1$ -- the reparametrizations of the given curve. Andre Gramain, Le type d'homotopie du groupe des diffeomorphisms d'une surface compacte. Ann. Sci. l'ENS $4^e$ serie tome 6 $n^o$ 1 (1973) 53--66
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/105192', 'https://mathoverflow.net', 'https://mathoverflow.net/users/798/']}
|
jdg_372050
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1876559
|
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:
As the definition, the total differential of a differentiable function with two variables equal to:$$dz=\frac{\partial z}{\partial x}dx+\frac{\partial z}{\partial y}dy$$Since there are innumerable derivable directions , I confuse it now. I have two confusion in follow: Why the total differential equal to sum of just two partial differentials? For a differentiable function, the total differential equal to sum of any two different direction's partial differentials?
Now provide the response and nothing else.
|
I prefer to start from a definition of the total derivative that isn’t tied to a specific coordinate system. If $f:\mathbb R^m\to\mathbb R^n$ , it is differentiable at $\mathbf v\in\mathbb R^m$ if there is a linear map $L_{\mathbf v}:\mathbb R^m\to\mathbb R^n$ such that $f(\mathbf v+\mathbf h)=f(\mathbf v)+L_{\mathbf v}[\mathbf h]+o(\|\mathbf h\|)$ . The linear map $L_{\mathbf v}$ is called the differential or total derivative of $f$ at $\mathbf v$ , denoted by $\mathrm df_{\mathbf v}$ or simply $\mathrm df$ . The idea here is that $\mathrm df_{\mathbf v}$ is the best linear approximation to the change in $f$ near $\mathbf v$ , with the error of this approximation vanishing “faster” than the displacement $\mathbf h$ . Relative to some specific pair of bases for the domain and range of $f$ , $\mathrm df$ can be represented by an $n\times m$ matrix. To see what this matrix is, you can treat $f$ as a vector of functions: $$f(\mathbf v)=\pmatrix{\phi_1(\mathbf v)\\\phi_2(\mathbf v)\\\vdots\\\phi_n(\mathbf v)}$$ or, written in terms of coordinates, $$\begin{align}y_1&=\phi_1(x_1,x_2,\dots,x_m)\\y_2&=\phi_2(x_1,x_2,\dots,x_m)\\\vdots\\y_n&=\phi_n(x_1,x_2,\dots,x_m).\end{align}$$ The matrix of $\mathrm df$ then turns out to be the Jacobian matrix of partial derivatives $$\pmatrix{{\partial\phi_1\over\partial x_1}&{\partial\phi_1\over\partial x_2}&\cdots&{\partial\phi_1\over\partial x_m}\\{\partial\phi_2\over\partial x_1}&{\partial\phi_2\over\partial x_2}&\cdots&{\partial\phi_2\over\partial x_m}\\\vdots&\vdots&\ddots&\vdots\\{\partial\phi_n\over\partial x_1}&{\partial\phi_n\over\partial x_2}&\cdots&{\partial\phi_n\over\partial x_m}}.$$ The displacement vector $\mathbf h$ can be written as $\mathrm d\mathbf v=(\mathrm dx^1,\mathrm dx^2,\dots,\mathrm dx^m)^T$ . (The $\mathrm dx^i$ here can themselves be thought of as differentials of affine coordinate functions, but that’s not an important detail for this discussion.) For the special case of a scalar function $f:\mathbb R^m\to\mathbb R$ , $\mathrm df[\mathbf h]$ becomes $${\partial f\over\partial x_1}\mathrm dx^1+{\partial f\over\partial x_2}\mathrm dx^2+\cdots+{\partial f\over\partial x_m}\mathrm dx^m.$$ Now, the partial derivative ${\partial f\over\partial x_i}$ is just the directional derivative of $f$ in the direction of the $x^i$ -axis, so this formula expresses the total derivative of $f$ in terms of its directional derivatives in a particular set of directions. Notice that there was nothing special about the basis we chose for $\mathbb R^m$ . If we choose a different basis, $\mathrm df$ will have the same form, but the derivatives will be taken in a different set of directions. In your case of $\mathbb R^2$ , a basis consists of two vectors, so derivatives in only two directions are sufficient to completely specify the total derivative. If you understand it as a linear map from $\mathbb R^2$ to $\mathbb R$ , this should come as no surprise.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1876559', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/332197/']}
|
jdg_372051
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5596434
|
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 animate a circle and just moving it horizontally which works fine. However while the circle is moving, I have to do a clearRect over that circle so that it redraws it self in the horizontal direction. When I do a clearRect it also makes the background have white box around so effectively its going to be one white horizontal line in the direction the circle is moving. Is there a way to clear the circle without clearRect? If I have to keep redrawing the background after clearRect the canvas will flicker when theres say 10 circles moving in that area. Any other approaches to solving this? function drawcircle() { clear(); context.beginPath(); context.arc(X, Y, R, 0, 2*Math.PI, false); context.moveTo(X,Y); context.lineWidth = 0.3; context.strokeStyle = "#999999"; context.stroke(); if (X > 200) { clearTimeout(t); //stop } else { //move in x dir X += dX; t = setTimeout(drawcircle, 50); } } function clear() { context.clearRect(X-R, Y-R, 2*R, 2*R); }
Now provide the response and nothing else.
|
Basics: HTML5 Canvas as a Non-Retained Drawing Mode Graphics API First, let us discuss the manner in which the HTML5 Canvas works. Like a real-world canvas with fast-drying oil paints, when you stroke() or fill() or drawImage() onto your canvas the paint becomes part of the canvas. Although you drew a 'circle' and see it as such, the pixels of the circle completely replaced the background (or in the case of anti-aliasing at the edges of the circle, blended with and forever changed them). What would Monet say if you asked him to 'move' one of the people in a painting a little bit to the right? You can't move the circle, you can't erase the circle, you can't detect a mouseover of the circle…because there is no circle , there is just a single 2D array of pixels. Some Options If your background is fully static, set it as a background image to your canvas element via CSS. This will be displayed and overlaid with content you draw, but will not be cleared when you clear your canvas. If you cannot do the above, then you might as well just clear the entire canvas and re-paint it every frame. In my tests, the work needed to clear and redraw just a portion of the canvas is not worth the effort unless redrawing the canvas is very expensive. For example, see this test: http://phrogz.net/tmp/image_move_sprites_canvas.html In Safari v5.0.4 I see 59.4fps if I clear and re-draw the entire canvas once per frame, and 56.8fps if I use 20 clearRect() calls and 20 drawImage() calls to re-draw just the dirtied part of the background each frame. In this case it's slower to be clever and keep track of small dirty regions. As another alternative, use a retained-drawing graphics system like SVG or HTML. With these, each element is maintained independently. You can change the position of the item and it will magically move; it is up to the browser to intelligently draw the update in the most efficient manner possible. You can do this while retaining the power of custom canvas drawing by creating and layering multiple canvases in the same HTML page (using CSS absolute positioning and z-index). As seen in this performance test , moving 20 sprites via CSS is significantly faster than trying to do it all yourself on a single canvas. Flickering? You wrote: If I have to keep redrawing the background after clearRect the canvas will flicker when theres say 10 circles moving in that area. That has never been my experience. Can you provide a small example showing this 'flicker' problem you claim will occur (please specify OS, browser, and version that you experience this on)? Here are two comments by prominent browser developers noting that neither Firefox nor Safari should ever show any flickering.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5596434', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/695701/']}
|
jdg_372052
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
41856005
|
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 stream the result of a file download directly into another post using spring's RestTemplate My current approach is the following: ResponseEntity<InputStreamResource> downloadResponse = restTemplate.getForEntity(fileToDownloadUri, InputStreamResource.class); InputStreamResource imageInputStreamResource = downloadResponse.getBody(); ResponseEntity<String> response = restTemplate.exchange(storageUri, POST, new HttpEntity<>(imageInputStreamResource), String.class); However, I get the following exception running the code above: org.springframework.web.client.ResourceAccessException: I/O error on POST request for "http://host:port/path/some.jpg": stream is closed; nested exception is java.io.IOException: stream is closed at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:6...Caused by: java.io.IOException: stream is closed at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.ensureOpen(HttpURLConnection.java:3348) at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(HttpURLConnection.java:3373) It seems that the response is always closed as the final step of processing. With the response, the HttpURLConnection is closed, and the stream is no longer processable. I would like to be able to implement this scenario without having to hold the file completely in memory or writing it to a file (as described here ). Any hints are highly appreciated.
Now provide the response and nothing else.
|
If you want to forward the response directly without ever holding it in memory, you have to directly write to the response: @RequestMapping(value = "/yourEndPoint")public void processRequest(HttpServletResponse response) { RestTemplate restTemplate = new RestTemplate(); response.setStatus(HttpStatus.OK.value()); restTemplate.execute( fileToDownloadUri, HttpMethod.GET, (ClientHttpRequest requestCallback) -> {}, responseExtractor -> { IOUtils.copy(responseExtractor.getBody(), response.getOutputStream()); return null; });}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41856005', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5371736/']}
|
jdg_372053
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1132005
|
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 copy an mp3 file from my Resources folder to a folder inside "Documents" folder of the app. On the simulator this works fine. But when I run it on a device, copying the files gives me this error Operation could not be completed. (Cocoa error 513.) The source and destinations paths are fine but I still cannot copy the file. Any ideas? Where can I find out what the cocoa error code 513 means? Thanks. Here's the relevant source code NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *folderPath = [documentsDirectory stringByAppendingPathComponent:@"Files"]; NSString *insPath = [NSString stringWithFormat:@"%@.mp3", fileName]; NSString *srcPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:insPath]; NSString *destPath = [folderPath stringByAppendingPathComponent:insPath]; NSLog(@"Src: %@, Dest: %@", srcPath, destPath); NSError *err; [fileManager moveItemAtPath:srcPath toPath:destPath error:&err]; NSLog(@"Err desc-%@", [err localizedDescription]); NSLog(@"Err reason-%@", [err localizedFailureReason]); Before making a call to moveItemAtPath, I am also creating the directory "Files" and it returns a YES. Here's the log results Src: /var/mobile/Applications/512D7565-7EF7-4C13-A015-19EEC3F3B465/MyApp.app/MyFile.mp3, Dest: /var/mobile/Applications/512D7565-7EF7-4C13-A015-19EEC3F3B465/Documents/Files/MyFile.mp3Err desc-Operation could not be completed. (Cocoa error 513.)Err reason-(null) A question Is there a limit to the file size when copying data from resources to Documents folder? The file I am trying to copy is about 5MB. Could that be a reason?
Now provide the response and nothing else.
|
EDIT: Just figured out an even simpler solution. Instead of moveItemAtPath:toPath:error:, just use copyItemAtPath:toPath:error: ... since we truly want to copy the file from the mainBundle and not move it. I should have thought of that sooner! E.g. [[NSFileManager defaultManager] copyItemAtPath:mainBundleFilePath toPath:destPath error:&err] See my previous comments below about why this works. I believe I have the answer to this question. I can say for sure that the issue is not the destination file path. I was getting the same Cocoa error 513 (NSFileWriteNoPermissionError) with pretty much the exact same code: [[NSFileManager defaultManager] moveItemAtPath:mainBundleFilePath toPath:destPath error:&err] The problem appears to be that the file, coming from the mainBundle, doesn't have suitable permissions to be moved to another place. I'm not sure if this command, if executed, would actually move the file from the mainBundle or just copy it...but either way, the file manager doesn't seem to like the idea. The solution is simple: just read the mainBundle file into an NSData object and then write the NSData to a new file. Note the destination file path is the same in both examples, which shows us that lostInTransit is correct in saying that his file path is OK. For this example, then, the following code will work and not throw an error: NSData *mainBundleFile = [NSData dataWithContentsOfFile:mainBundleFilePath];[[NSFileManager defaultManager] createFileAtPath:destPath contents:mainBundleFile attributes:nil]; BTW, in my own code, instead of passing a nil for attributes:, I set up an NSDictionary with a NSFileModificationDate attribute. I also wrapped the createFileAtPath:contents:attributes in an error handing if-statement. In other words, if (![[NSFileManager defaultManager] createFileAtPath:destPath contents:mainBundleFile attributes:myAttributes]) { // handle error as necessary, etc... } It took me a while to figure all of this out, so hopefully this solution will be helpful to others.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1132005', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/46297/']}
|
jdg_372054
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
15630
|
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
This one was a bit involved. The alkyl halide turning into an alcohol with retention of stereochemistry suggested that an SN1 mechanism was at work. The addition of NaOH and the inversion of stereochem followed by "only" suggested again an SN2 mechanism. No E2 products; hydroxide isn't basic enough to deprotonate an alkane to a significant extent. The transformation of the alcohol into a nitrile group with inversion of stereochemistry is SN2; attacked with a non-protic solvent for good measure. The transformation into a nitrile group with retention of stereochem is SN1; treatment with tosyl chloride turns the -OH into a good leaving group.
Now provide the response and nothing else.
|
Since Greg E. focused on the first parts of the roadmap, I'll focus on the cyanation reactions. What you have shown for the sequence from (R)-2-butanol to (R)-2-cyanobutane (retention of configuration), actually gives inversion of configuration. It is probably more clear if we look at this as two discrete steps. Step one is reaction with TsCl (and pyridine typically) to give the tosylate with retention. Step 2 is reaction with NaCN to give the cyano compound (S)-2-cyanobutane with inversion. Perhaps that can all be done in one step, but I've never seen it or tried it. Going from (R)-2-butanol to (S)-2-cyanobutane (inversion of configuration) by direct reaction with NaCN will not give the target compound. Hydroxide is not a suitable leaving group for SN2 reaction. The hydroxyl must be converted into a better leaving group first, such as the tosylate above. That leaves the problem of how to synthesize (R)-2-cyanobutane (retention of configuration). Since the SN2 reaction with NaCN is going to invert configuration, you need a method of converting -OH into a leaving group with inversion . Two successive inversions give overall retention of configuration. The two most common ways taught for this transformation are SOCl2 (-OH to -Cl) and PBr3 (-OH to -Br). Both of these reagents install a halide with inversion of configuration, allowing SN2 reaction with NaCN to invert back to the original stereochemistry.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/15630', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/5084/']}
|
jdg_372055
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2954
|
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:
Suppose I have these two sets of data: data1 = {{0, 0}, {5, 0}, {10, .1}, {15, .3}, {20, .7}, {25, 1}, {30, 1}};data2 = {{0, 0}, {5, 0}, {10, 0}, {15, 0}, {20, 0}, {25, .1}, {30, .3}}; and I fit them with a cumulative Gaussian function: cumulativeGauss[x_, μ_, Σ_] := CDF[NormalDistribution[μ, Σ], x] I obtain the parameters that I'll use to plot these functions: fit1 = FindFit[ data1, cumulativeGauss[x, μ, Σ], {{μ, 5}, {Σ, 5}}, x][[All, 2]];fit2 = FindFit[ data2, cumulativeGauss[x, μ, Σ], {{μ, 5}, {Σ, 5}}, x][[All, 2]]; Here below are all the plots that I've produced to show the problem.The left column shows that when only the Plot command is used the function is plotted along the whole range, so no problem. On the other hand, the right column shows the figures produced by combining a ListPlot with a Plot . The first figure shows no problem, however, the figure in the second row does not plot the function along the whole range. This problem can be solved by increasing the range over which the function is plotted (figure in the 3rd row). Any hint about why this problem occurs and/or if there is any other solution? Here the the code to generate the figures: GraphicsGrid[ { { Plot[cumulativeGauss[x, fit1[[1]], fit1[[2]]], {x, 0, 30}, PlotRange -> {{0, 30}, {0, 1}}], Show[ListPlot[data1, PlotRange -> {{0, 30}, {0, 1}}], Plot[cumulativeGauss[x, fit1[[1]], fit1[[2]]], {x, 0, 30}]] }, { Plot[cumulativeGauss[x, fit2[[1]], fit2[[2]]], {x, 0, 30}, PlotRange -> {{0, 30}, {0, 1}}], Show[ListPlot[data2, PlotRange -> {{0, 30}, {0, 1}}], Plot[cumulativeGauss[x, fit2[[1]], fit2[[2]]], {x, 0, 30}]] }, { Plot[cumulativeGauss[x, fit2[[1]], fit2[[2]]], {x, 0, 30}, PlotRange -> {{0, 30}, {0, 1}}], Show[ListPlot[data2, PlotRange -> {{0, 30}, {0, 1}}], Plot[cumulativeGauss[x, fit2[[1]], fit2[[2]]], {x, 0, 40}]] } }]
Now provide the response and nothing else.
|
I'm assuming you want to use the same PlotRange for cell (2,2) as for the other cells. You can change the order: show Plot before ListPlot . Note that Plot will now set the PlotRange ; as I understand it, the first function called by Show controls the graphics settings (if there should be a conflict). Show[Plot[cumulativeGauss[x, fit2[[1]], fit2[[2]]], {x, 0, 30}, PlotRange -> {{0, 30}, {0, 1}}], ListPlot[data2] ] The following questions remain: "Why isn't the full plot range displayed when ListPlot comes before Plot ? "Why can't you specify the PlotRange in Show as follows?" Show[Plot[cumulativeGauss[x, fit2[[1]], fit2[[2]]], {x, 0, 30}], ListPlot[data2], PlotRange -> {{0, 30}, {0, 1}}] According to the documentation , this latter approach should work (but it does not): Either of these result in the following: Edit You can display the data points beneath the model using. Note, however that the points will lie beneath the axes. Plot[cumulativeGauss[x, fit2[[1]], fit2[[2]]], {x, 0, 30}, PlotRange -> {{0, 30}, {0, 1}}, PlotRangePadding -> {{.3, 3}, {0.1, 0}}, Prolog -> {Red, PointSize[Large], Point[data2]}]
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/2954', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/685/']}
|
jdg_372056
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
25602813
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there a way to force an inline function in Clang/LLVM? AFAIK, the following is just a hint to the compiler but it can ignore the request. __attribute__((always_inline)) I don’t mind that the compilation will fail if it can’t inline the function.
Now provide the response and nothing else.
|
There is a good solution if compiling with C99 which is Clang's default.Its simply using inline attribute. inline void foo() {} It is well written in Clang's compatibility page : By default, Clang builds C code according to the C99 standard, which provides different semantics for the inline keyword than GCC's default behavior... In C99, inline means that a function's definition is provided only for inlining, and that there is another definition (without inline) somewhere else in the program. That means that this program is incomplete, because if add isn't inlined (for example, when compiling without optimization), then main will have an unresolved reference to that other definition. Therefore we'll get a (correct) link-time error... GCC recognizes it as an extension and just treats it as a hint to the optimizer. So in order to guarantee that the function is inlined: Don’t use static inline. Don’t add another implementation for the function that doesn't have inline attribute. You must use optimization. But even if there isn't optimization the compilation will fail which is good. Make sure not to compile with GNU89.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25602813', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2338792/']}
|
jdg_372057
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
160070
|
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The $( \frac{1}{2}, 0)$ representation of the Lorentz group acts on left-chiral spinors $\chi_a$, the $( 0,\frac{1}{2} )$ representation on right-chiral spinors $\chi^{\dot a}$. The $( \frac{1}{2}, \frac{1}{2}) = ( \frac{1}{2}, 0) \otimes ( 0,\frac{1}{2} ) $ representation acts therefore on objects with one dotted and one undotted index.My naive, first guess would be that the $( \frac{1}{2}, \frac{1}{2}) $ representation acts on objects with one lower undotted and one upper dotted index: $v_{a}^{\dot{b}}$. An upper dotted index transforms like a right-chiral spinor, a lower undotted like a left-chiral spinor. Quite surprising for me is that $v_{a \dot{b}}= v_\mu \sigma^\mu_{a \dot{b}}$ transforms like a four-vector and $v_{a}^{\dot{b}}$ transforms differently, because the transformation behaviour of a lower dotted index is different than that of an upper dotted index. Why does $v_{a \dot{b}}$ transform like a four-vector and not the naive first guess $v_{a}^{\dot{b}}$? Is there any name for objects transforming like $v_{a}^{\dot{b}}$, just as left-chiral spinors, right-chiral spinors or four-vectors are defined by their transformation behaviour?
Now provide the response and nothing else.
|
Firstly, it doesn't matter whether the indices are up or down here when you ask what representation an object lives in, because the raised and lowered versions are equivalent. Both $\chi_a$ and $\chi^a$ give objects in the $(\frac{1}{2},0)$ rep, and similarly for dotted. The relation between the two is the linear transformation given by $\chi^a=\epsilon^{ab}\chi_b$ (just a change of basis). The matrices that gives the transformations for upstairs and downstairs are then related by a similarity transform (conjugation with the epsilon tensor, or equivalently combined inverse and transpose). Then an object in the $(\frac{1}{2},\frac{1}{2})$ rep can be described in a few different ways: $v_a^\dot{b}$, or equivalently $v_{a\dot{b}}$ are the obvious ones if you know $(\frac{1}{2},\frac{1}{2})=(\frac{1}{2},0)\otimes(0,\frac{1}{2})$ (again using some $\epsilon$ to move between different descriptions/bases). But there happens to be another natural, and more familiar, basis to choose. The change of basis matrix to get to this is the collection $\sigma^\mu_{a \dot{b}}$ of Pauli matrices. (You can think of this, if it helps, as a $4\times 4$ matrix, with $^\mu$ indices on the columns, and $_{a\dot{b}}$ indices on the rows). The appropriate conjugation by this takes a tensor product of $SU(2)$ matrices to a Lorentz transformation of a vector, or vice versa. So the answer is that any of the index structures you suggest describe the same representation, just in a different basis. The choice you make is just a matter of convenience, and there is always some linear map that will move from any one to any other.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/160070', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/65572/']}
|
jdg_372058
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1692538
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What is the difference between primary , unique and foreign key constraints , and indexes ? I work on Oracle 10g and SQL Server 2008
Now provide the response and nothing else.
|
Primary Key and Unique Key are Entity integrity constraints Primary key allows each row in a table to be uniquely identified and ensures that no duplicate rows exist and no null values are entered. Unique key constraint is used to prevent the duplication of key values within the rows of a table and allow null values. (In oracle one null is not equal to another null). KEY or INDEX refers to a normal non-unique index. Non-distinct values for the index are allowed, so the index may contain rows with identical values in all columns of the index. These indexes don't enforce any structure on your data so they are used only for speeding up queries. UNIQUE refers to an index where all rows of the index must be unique. That is, the same row may not have identical non-NULL values for all columns in this index as another row. As well as being used to speed up queries, UNIQUE indexes can be used to enforce structure on data, because the database system does not allow this distinct values rule to be broken when inserting or updating data. Your database system may allow a UNIQUE index on columns which allow NULL values, in which case two rows are allowed to be identical if they both contain a NULL value (NULL is considered not equal to itself), though this is probably undesirable depending on your application. PRIMARY acts exactly like a UNIQUE index, except that it is always named 'PRIMARY', and there may be only one on a table (and there should always be one; though some database systems don't enforce this). A PRIMARY index is intended as a way to uniquely identify any row in the table, so it shouldn't be used on any columns which allow NULL values. Your PRIMARY index should always be on the smallest number of columns that are sufficient to uniquely identify a row. Often, this is just one column containing a unique auto-incremented number, but if there is anything else that can uniquely identify a row, such as "countrycode" in a list of countries, you can use that instead. FULLTEXT indexes are different to all of the above, and their behaviour differs more between database systems. Unlike the above three, which are typically b-tree (allowing for selecting, sorting or ranges starting from left most column) or hash (allowing for selection starting from left most column), FULLTEXT indexes are only useful for full text searches done with the MATCH() / AGAINST() clause. see Differences between INDEX, PRIMARY, UNIQUE, FULLTEXT in MySQL?
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1692538', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/43907/']}
|
jdg_372059
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2842715
|
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:
Recall that a group $G$ satisfies the normalizer condition if for any proper subgroup $H$, its normalizer in $G$, $N_G(H)$ is a strictly larger group. For finite groups, this property is equivalent to $G$ being nilpotent (that is, its lower central series terminates at the trivial group). The proof I know/found is by using yet another criteria for nilpotency: all Sylow subgroups are normal. However, is there a proof that avoids mention of Sylow subgroups? I ask because both the condition of being nilpotent and having the normalizer condition are quite elementary and make no reference to Sylow subgroups. Edit: I can at least show that the derived subgroup is a proper subgroup: Let $M$ be a maximal subgroup of $G$, they exist by finiteness. The normalizer of $M$ properly contains $M$ and hence it is $G$, hence $M$ is normal in $G$. Moreover, $G/M$ has no subgroups and hence is prime cyclic. Now consider [G,G]. We will show that this is contained in $M$. This follows easily since [G/M,G/M] = [G,G]/M but $[G/M,G/M]$ is trivial since $G/M$ is abelian.
Now provide the response and nothing else.
|
Personally, I don't believe that the theory of central series is more elementary than Sylow theory, and in my experience students find Sylow theory easier, probably because it does not involve technical calculations with quotient groups. But if you insist, I think you can do it this way. By using induction on $|G|$, we can assume that $Z(G)=1$. Also all maximal subgroups $M$ of $G$ are normal, so they have prime index $p$. It is not hard to show that $M$ satisfies the normalizer condition, so $M$ is nilpotent by induction. So $Z(M) \ne 1$. Let $N$ be a minimal normal subgroup of $G$ that is contained in $Z(M)$, let $G = \langle M,g \rangle$ with $g^p \in M$, and let $H = \langle N,g \rangle$. So $Z(H) \cap N \le Z(G)$ and hence $Z(H) \cap N = 1$. Since $\langle g \rangle \cap N \le Z(H) \cap N$, we have $\langle g \rangle \cap N =1$. Now $H$ satifies the normalizer condition, by assumption if $H=G$, and by induction otherwise. So $\langle g \rangle < N_H(\langle g \rangle)$, and hence $N_N(\langle g \rangle) \ne 1$. But $[N_N(\langle g \rangle), \langle g \rangle] \le \langle g \rangle \cap N =1$, so $N_N(\langle g \rangle) \le Z(G)$, contradiction.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2842715', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/68188/']}
|
jdg_372060
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18813875
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Taking the binary of 0x80000000 we get 1000 0000 0000 0000 0000 0000 0000 0000 How does this equate to -2147483648 . I got this question with this program. class a{ public static void main(String[] args) { int a = 0x80000000; System.out.printf("%x %d\n",a,a); }}meow@VikkyHacks:~/Arena/java$ java a80000000 -2147483648 EDIT I learned that 2's complement is used to represent negative numbers. When I try to equate this with that 1's complement would be 1's Comp. :: 0111 1111 1111 1111 1111 1111 1111 11112's Comp. :: 1000 0000 0000 0000 0000 0000 0000 0000 which again does not make any sense, How does 0x80000000 equate to -2147483648
Now provide the response and nothing else.
|
This is what happens with signed integer overflow , basically. It's simpler to take byte as an example. A byte value is always in the range -128 to 127 (inclusive). So if you have a value of 127 (which is 0x7f) if you add 1, you get -128. That's also what you get if you cast 128 (0x80) to byte : int x = 0x80; // 128byte y = (byte) x; // -128 Overflow (in 2s complement integer representations) always goes from the highest expressible number to the lowest one. For unsigned types, the highest value overflows to 0 (which is again the lowest expressible number). This is harder to show in Java as the only unsigned type is char : char x = (char) 0xffff;x++;System.out.println((int) x); // 0
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18813875', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/971222/']}
|
jdg_372061
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7246618
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Are trailing commas standard in JavaScript, or do most browsers like Chrome and Firefox just tolerate them? I thought they were standard, but IE8 puked after encountering one—of course IE not supporting something hardly means it’s not standard. Here’s an example of what I mean (after the last element of the books array): var viewModel = { books: ko.observableArray([ { title: "..", display: function() { return ".."; } }, { title: "..", display: function() { return ".."; } }, { title: "..", display: function() { return ".."; } }, // <--right there ]), currentTemplate: ko.observable("bookTemplate1"), displayTemplate: function() { return viewModel.currentTemplate(); }};
Now provide the response and nothing else.
|
Specs: ECMAScript 5 and ECMAScript 3 Section 11.1.5 in the ECMAScript 5 specification: ObjectLiteral : { } { PropertyNameAndValueList } { PropertyNameAndValueList , } So yes, it is part of the specification. Update: Apparently this is new in ES5. In ES3 (page 41), the definition was just: ObjectLiteral : { } { PropertyNameAndValueList } For arrays literals ( Section 11.1.4 ) it is even more interesting ( Update: this already existed in ES3): ArrayLiteral : [ Elisionopt ] [ ElementList ] [ ElementList , Elision_opt ] (where Elision_opt is Elision opt , meaning the Elision is optional) Elision is defined as Elision : , Elision , So, an array literal like var arr = [1,2,,,,]; is perfectly legal. This creates an array with two elements but sets the array length to 2 + 3 = 5 . Don't expect too much from IE (before IE9)...
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/7246618', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/352552/']}
|
jdg_372062
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
30933328
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Using Firebase Library to send data to the server in the form Message(String, String) added to the HashMap<String, Message> Example: Firebase fb = new Firebase(URL);Firebase msgRef = fb.child("finished");HashMap<String, Message> msgList = new HashMap<>();Message msg = new Message(m, n);msgList.put(HASHKEY, msg);msgRef.push().setValue(msgList); While receiving data with Firebase method addValueEventListener() getting String in this Form { key = finished, value = { -Js9Rn0uttjYIGdcv8I1={Moosa={message=email, name=Kamran}}, -Js9Vsmv6BnVzOzpl2L8={Moosa={message=msgs, name=Imran}}, -Js9WtQ8yeDwVxQMFCZb={Moosa={message=samsung, name=Samad}}, -Js9RarxoJPKn4RO2HaM={Moosa={message=Message, name=Moosa}}, -Js9b6f75lwwbsqQNJz0={Moosa={message=Qmobile, name=Bilal}}, -Js9aDxt8TlgTGUccuxu={Moosa={message=last, name=Moosa}}} } How can I convert it into Message Object.....????
Now provide the response and nothing else.
|
There are two more way to get your data out of the Firebase DataSnapshot that don't require using a Map<String, Object> . First appoach is to use the methods of DataSnapshot to traverse the children: ref = FirebaseDatabase.getInstance().getReference("messages").limitToLast(10);ref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for (DataSnapshot messageSnapshot: dataSnapshot.getChildren()) { String name = (String) messageSnapshot.child("name").getValue(); String message = (String) messageSnapshot.child("message").getValue(); } } @Override public void onCancelled(FirebaseError firebaseError) { }}); In the above snippet we use getChildren() to get an Iterable of your messages. Then we use child("name") to get each specific child property. The second approach is to use the built-in JSON-to-POJO serializer/deserializer . When you're sending the message list, the Message objects inside it are serialized to JSON and stored in Firebase. To get them out of it again, you have to do the inverse: ref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for (DataSnapshot messageSnapshot: dataSnapshot.getChildren()) { Message message = messageSnapshot.getValue(Message.class); } } @Override public void onCancelled(FirebaseError firebaseError) { }}); In this second snippet, we're still using getChildren() to get at the messages, but now we deserialize them from JSON straight back into a Message object. For a simple sample application using that last approach, have a look at Firebase's AndroidChat sample . It also shows how to efficiently deal with the list of messages (hint: FirebaseListAdapter ).
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/30933328', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4994239/']}
|
jdg_372063
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1630320
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'd like to know the best way (more compact and "pythonic" way) to do a special treatment for the last element in a for loop. There is a piece of code that should be called only between elements, being suppressed in the last one. Here is how I currently do it: for i, data in enumerate(data_list): code_that_is_done_for_every_element if i != len(data_list) - 1: code_that_is_done_between_elements Is there any better way? Note: I don't want to make it with hacks such as using reduce . ;)
Now provide the response and nothing else.
|
Most of the times it is easier (and cheaper) to make the first iteration the special case instead of the last one: first = Truefor data in data_list: if first: first = False else: between_items() item() This will work for any iterable, even for those that have no len() : file = open('/path/to/file')for line in file: process_line(line) # No way of telling if this is the last line! Apart from that, I don't think there is a generally superior solution as it depends on what you are trying to do. For example, if you are building a string from a list, it's naturally better to use str.join() than using a for loop “with special case”. Using the same principle but more compact: for i, line in enumerate(data_list): if i > 0: between_items() item() Looks familiar, doesn't it? :) For @ofko, and others who really need to find out if the current value of an iterable without len() is the last one, you will need to look ahead: def lookahead(iterable): """Pass through all values from the given iterable, augmented by the information if there are more values to come after the current one (True), or if it is the last value (False). """ # Get an iterator and pull the first value. it = iter(iterable) last = next(it) # Run the iterator to exhaustion (starting from the second value). for val in it: # Report the *previous* value (more to come). yield last, True last = val # Report the last value. yield last, False Then you can use it like this: >>> for i, has_more in lookahead(range(3)):... print(i, has_more)0 True1 True2 False
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/1630320', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/130627/']}
|
jdg_372064
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
27
|
Below is a question asked on the forum emacs.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I often use TRAMP to manage several remote servers, both for editing files and running remote shells in shell-mode . However, this does not work when a command uses the EDITOR variable to edit a file, such as crontab -e especially because shell-mode is a "dumb" terminal that does not support running another editor inside of it. Locally, I do this with an appropriate call to emacsclient which opens up a new buffer and makes life very easy. Unfortunately, this does not work from the remote machine. I guess I could use ed . (Hah!) How can I set up a remote EDITOR that would let me edit files with my local Emacs instance?
Now provide the response and nothing else.
|
[NOTE] this answer was heavily edited to follow the updates of with-editor developments. Most comments likely won't make much sense anymore. There are some new comments which do make sense. Magit contains a library named with-editor available at https://github.com/magit/with-editor which allows you to use your local Emacs as an $EDITOR on remote machines over TRAMP. Another alternative is https://github.com/habnabit/remote-emacsclient , but it seems more complicated & less generic. The simplest way to install with-editor is through MELPA: M-x package-install with-editor Otherwise, just grab https://github.com/magit/with-editor/blob/master/with-editor.el somewhere to your load path and require it (it also depends on dash). Then, simply start shell , eshell or ansi-term and do the following: M-x with-editor-export-editor It'll ask you which $EDITOR you are interested in, just press enter for the default EDITOR variable. Then inside the shell you can type crontab -e and edit your crontab within emacs. Press C-c C-c to save the crontab or C-c C-k to cancel editing. If you want a more permanent setup: (add-hook 'shell-mode-hook 'with-editor-export-editor)(add-hook 'term-mode-hook 'with-editor-export-editor)(add-hook 'eshell-mode-hook 'with-editor-export-editor) Alternatively, you can use M-x with-editor-async-shell-command crontab -e RET for quick commands.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://emacs.stackexchange.com/questions/27', 'https://emacs.stackexchange.com', 'https://emacs.stackexchange.com/users/17/']}
|
jdg_372065
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5791318
|
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 slider control with 2 sliders on it so that you can select min and max values?
Now provide the response and nothing else.
|
Try something like this: private Thread thread; @Overridepublic void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layoutxml); final MyActivity myActivity = this; thread= new Thread(){ @Override public void run(){ try { synchronized(this){ wait(3000); } } catch(InterruptedException ex){ } // TODO } }; thread.start(); }@Overridepublic boolean onTouchEvent(MotionEvent evt){ if(evt.getAction() == MotionEvent.ACTION_DOWN) { synchronized(thread){ thread.notifyAll(); } } return true;} It waits 3 seconds to continue but if the user touches the screen the thread is notified and it stops waiting.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5791318', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/369313/']}
|
jdg_372066
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13900515
|
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 create a class in Python that manages above all static members. These members should be initiliazed during definition of the class already. Due to the fact that there will be the requirement to reinitialize the static members later on I would put this code into a classmethod. My question: How can I call this classmethod from inside the class? class Test(): # static member x = None # HERE I WOULD LOVE TO CALL SOMEHOW static_init! # initialize static member in classmethod, so that it can be #reinitialized later on again @classmethod def static_init(cls): cls.x = 10 Any help is appreciated! Thanks in advance, Volker
Now provide the response and nothing else.
|
At the time that x=10 is executed in your example, not only does the class not exist, but the classmethod doesn't exist either. Execution in Python goes top to bottom. If x=10 is above the classmethod, there is no way you can access the classmethod at that point, because it hasn't been defined yet. Even if you could run the classmethod, it wouldn't matter, because the class doesn't exist yet, so the classmethod couldn't refer to it. The class is not created until after the entire class block runs, so while you're inside the class block, there's no class. If you want to factor out some class initialization so you can re-run it later in the way you describe, use a class decorator. The class decorator runs after the class is created, so it can call the classmethod just fine. >>> def deco(cls):... cls.initStuff()... return cls>>> @deco... class Foo(object):... x = 10... ... @classmethod... def initStuff(cls):... cls.x = 88>>> Foo.x88>>> Foo.x = 10>>> Foo.x10>>> Foo.initStuff() # reinitialize>>> Foo.x88
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13900515', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1907681/']}
|
jdg_372067
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
22082641
|
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 series of tasks to be run from a watcher but I can get them to fire in order: Here is the gulp tasks and watcher. gulp.task('app_scss', function(){ return gulp.src(appScssDir + '/main.scss') .pipe(sass({ style: 'compressed' }).on('error', gutil.log)) .pipe(autoprefix('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4')) .pipe(gulp.dest(appBuilderDir));});gulp.task('app_vendor_css', function(){ return gulp.src(appProviderCssDir + '/*.css') .pipe(minifyCSS({ keepSpecialComments: 0 })) .pipe(concat('app_vendor.css')) .pipe(gulp.dest(appBuilderDir));});gulp.task('app_build_css', function(){ return gulp.src(appBuilderDir + '/*.css') .pipe(concat('style.css')) .pipe(gulp.dest(targetCssDir));});gulp.task('watch', function () { gulp.watch(appScssDir + '/**/*.scss', ['app_scss', 'app_build_css']);});gulp.task('default', ['app_build_clean', 'app_scss', 'app_vendor_css', 'app_build_css', 'watch']); So when I update a scss file it should compile them create a single css file. Then the build task concats the file with the vendor files. But every time I save a file its always one step behind. See the video as an example: http://screencast.com/t/065gfTrY I have renamed the tasks, changed the order in the watch callback etc. Am I making a obvious mistake?
Now provide the response and nothing else.
|
Gulp starts all tasks at the 'same' time, unless you declare dependencies ( or make streams pipe one to the other ). So for example, if you want task app_build_css to wait for tasks app_scss and app_vendor_css to complete, declare the dependencies, gulp.task('app_scss', function(){ return gulp.src(appScssDir + '/main.scss') .pipe(sass({ style: 'compressed' }).on('error', gutil.log)) .pipe(autoprefix('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4')) .pipe(gulp.dest(appBuilderDir));});gulp.task('app_vendor_css', function(){ return gulp.src(appProviderCssDir + '/*.css') .pipe(minifyCSS({ keepSpecialComments: 0 })) .pipe(concat('app_vendor.css')) .pipe(gulp.dest(appBuilderDir));});gulp.task('app_build_css', ['app_scss', 'app_vendor_css'], function(){ return gulp.src(appBuilderDir + '/*.css') .pipe(concat('style.css')) .pipe(gulp.dest(targetCssDir));});gulp.task('watch', function () { gulp.watch(appScssDir + '/**/*.scss', ['app_build_css']);});gulp.task('default', ['app_build_clean', 'app_build_css', 'watch']); Check the Gulp.task() docs
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22082641', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/99877/']}
|
jdg_372068
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
44947
|
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 $M,N$ be complex manifolds and $f : M \to N$ be a bijective holomorphic map. Is then $f^{-1}$ also holomorphic? The open mapping theorem implies that $f^{-1}$ is continuous. In order to apply the inverse function theorem, we need that the differential of $f$ is invertible. This is the case if $M,N$ are open subsets of $\mathbb{C}$. Can we generalize this do higher dimensions? If not, what happens if we assume $dim(M)=dim(N)$?
Now provide the response and nothing else.
|
Yes, $f^{-1}$ is holomorphic. In fact, the following result holds, see [Griffiths-Harris, Principles of Algebraic Geometry p. 19]. Proposition If $f \colon U \to V$ is a one-to-one holomorphic map of open sets in $\mathbb{C}^n$, then$|J_f| \neq 0$, that is $f^{-1}$ is holomorphic. The fact that $N$ is smooth is crucial. For instance, if $N \subset \mathbb{C}^2$ is the cuspidal cubic curve of equation $y^2=x^3$ and $f \colon M \to N$ is the normalization map, then $f$ is bijective and holomorphic but it is not a biholomorphism, since $f^{-1}$ is not holomorphic at the point $(0,0)$.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/44947', 'https://mathoverflow.net', 'https://mathoverflow.net/users/2841/']}
|
jdg_372069
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6545066
|
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 Scala code: package scala_javaobject MyScala { def setFunc(func: Int => String) { func(10) }} Now in Java, I would have liked to use MyScala as: package scala_java;public class MyJava { public static void main(String [] args) { MyScala.setFunc(myFunc); // This line gives an error } public static String myFunc(int someInt) { return String.valueOf(someInt); }} However, the above does not work (as expected since Java does not allow functional programming). What is the easiest workaround to pass a function in Java? I would like a generic solution that works with functions having arbitrary number of parameters. EDIT: Does Java 8 have any better syntax than the classic solutions discussed below?
Now provide the response and nothing else.
|
You have to manually instantiate a Function1 in Java. Something like: final Function1<Integer, String> f = new Function1<Integer, String>() { public int $tag() { return Function1$class.$tag(this); } public <A> Function1<A, String> compose(Function1<A, Integer> f) { return Function1$class.compose(this, f); } public String apply(Integer someInt) { return myFunc(someInt); }};MyScala.setFunc(f); This is taken from Daniel Spiewak’s “Interop Between Java and Scala” article .
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6545066', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/243233/']}
|
jdg_372070
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
26010303
|
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 used to symbolicate the crash report in Xcode 5.1.1 directly as there was "Symbolicate & Re-symbolicate" in Devices section of Organiser. But after upgrading to Xcode 6.1, I could find neither symbolicate nor resymbolicate option to view the crash Log. I'm confused. How to do it? Previously I used to sync the device with iTunes and view the Crashes from ~/Library/Logs/CrashReporter/MobileDevice . Clicking on any crash would open up with Devices(Xcode) and then symbolicate. But now, it opens up with Console and no option to symbolicate. Does Xcode 6.1 have any such option?
Now provide the response and nothing else.
|
Steps to symbolicate crash log manually in Xcode 6 If you archived the release build before release, then go to STEP 2. Otherwise archive your final release build (without any code change). To locate your archive file, open organizer -> choose your project -> choose the latest archive file -> right click over it -> choose 'show in finder' Right click on '*.xcarchive' file and select 'show package content' option then go to Products folder -> Applications Folder ->YourAppName.app (.app extension is hidden in some machine) Copy and paste your .app file in different location. Put the crash log file also in the same folder. Open terminal app and go to the folder which you pasted, through 'cd' command And type the following command in terminal with your crash address xcrun atos -o YourAppName.app/YourAppName -arch armv7 -l 0xbd000 0x0013f745 Note: If the above command doesn't work, then change "armv7 to armv7s" and check. Eg: Crash log look like this, you need to get crash address and put it in the above command 3 CoreGraphics 0x266814d3 CGPathAddLineToPoint + 1714 YourAppName 0x00140a8b 0xbd000 + 5392755 YourAppName 0x0013f745 0xbd000 + 5343416 Foundation 0x27152d6b __NSThreadPerformPerform + 3837 CoreFoundation 0x2640a375
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26010303', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1719339/']}
|
jdg_372071
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
75196
|
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
$ echo $(( 255 ))255$ echo $(( 33 ))33$ echo $(( ~33 ))-34$ echo $(( ~255 ))-256$ and my kernel is: $ uname -aLinux HOSTNAME 3.2.0-40-generic-pae #64-Ubuntu SMP Mon Mar 25 21:44:41 UTC 2013 i686 i686 i386 GNU/Linux QUESTION: ~ is for negating the number AFAIK. But why does ~33 produce -34 and why does ~255 produce -256 ?
Now provide the response and nothing else.
|
The man page of bash says: ! ~ logical and bitwise negation Signed numbers are usually stored in Two's complement representation: ...-4 = 1100-3 = 1101-2 = 1110-1 = 1111 0 = 0000 1 = 0001 2 = 0010 3 = 0011... This means if you take a number like 2 it is bitwise interpreted as 0010. After bitwise negation this becomes 1101, which is the representation of -3.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/75196', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/18526/']}
|
jdg_372072
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6514001
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Very basic question, but I have an error in my code that can only be answered by one assumption: my class isn't being instantiated! I haven't written much in Objective C in some time, and I was never really good, so please point out even the most painfully obvious. I am using: ObjectSelectionViewController *length = [[ObjectSelectionViewController alloc] initWithMeasureType:0];ObjectSelectionViewController *mass = [[ObjectSelectionViewController alloc] initWithMeasureType:1];ObjectSelectionViewController *volume = [[ObjectSelectionViewController alloc] initWithMeasureType:2];NSLog(@"%@", [length measurementType]);NSLog(@"%@", [mass measurementType]);NSLog(@"%@", [volume measurementType]); The NSLogs return whichever measurement was assigned last, regardless of the separate allocs and inits. Here is the constructor of the ObjectSelectionViewController class: #import "ObjectSelectionViewController.h"@implementation ObjectSelectionViewControllerNSString *measurementType;-(ObjectSelectionViewController*) initWithMeasureType:(int)value{switch (value) { case 0: // Length measureType = @"Length"; break; case 1: // Mass measureType = @"Mass"; break; case 2: // Volume measureType = @"Volume"; break;}return self;}-(NSString*) measurementType{return measureType;} Thanks for the help, it's driving me crazy!
Now provide the response and nothing else.
|
You need to make measureType an instance variable, so that each object of this type that you create has its own copy: @interface ObjectSelectionViewController : NSViewController { NSString * measureType; // Declare an NSString instance variable}- (id) initWithMeasureType: (int)value;@end As it is, there is only one copy of the variable, and every time you instantiate a new object, its value changes. Since each instance is referring to the same copy, they all get the same value: ObjectSelectionViewController *length = [[ObjectSelectionViewController alloc] initWithMeasureType:0];NSLog(@"%@", [length measurementType]); // Prints "Length"ObjectSelectionViewController *mass = [[ObjectSelectionViewController alloc] initWithMeasureType:1];NSLog(@"%@", [length measurementType]); // Prints "Mass" You also need to change your init... method as mentioned by other answerers: - (id) initWithMeasureType: (int)value { // Call superclass's initializer self = [super init]; if( !self ) return nil; switch (value) { case 0: // Length measureType = @"Length"; break; case 1: // Mass measureType = @"Mass"; break; case 2: // Volume measureType = @"Volume"; break; } return self;} Since you are assigning a literal string to the instance variable, you do not need to worry about managing its memory; if you were doing anything more complicated, you would probably do well by declaring a property .Another note: initializer methods should always return id , a generic object pointer, to allow subclasses to work properly.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6514001', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/686384/']}
|
jdg_372073
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1647322
|
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 use echo and print_r much, and almost never use print . I feel echo is a macro, and print_r is an alias of var_dump . But that's not the standard way to explain the differences.
Now provide the response and nothing else.
|
print and echo are more or less the same; they are both language constructs that display strings. The differences are subtle: print has a return value of 1 so it can be used in expressions whereas echo has a void return type; echo can take multiple parameters, although such usage is rare; echo is slightly faster than print . (Personally, I always use echo , never print .) var_dump prints out a detailed dump of a variable, including its type and the type of any sub-items (if it's an array or an object). print_r prints a variable in a more human-readable form: strings are not quoted, type information is omitted, array sizes aren't given, etc. var_dump is usually more useful than print_r when debugging, in my experience. It's particularly useful when you don't know exactly what values/types you have in your variables. Consider this test program: $values = array(0, 0.0, false, '');var_dump($values);print_r ($values); With print_r you can't tell the difference between 0 and 0.0 , or false and '' : array(4) { [0]=> int(0) [1]=> float(0) [2]=> bool(false) [3]=> string(0) ""}Array( [0] => 0 [1] => 0 [2] => [3] => )
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/1647322', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/198938/']}
|
jdg_372074
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
149660
|
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I can do df . to get some of the info on the mount that the current directory is in, and I can get all the info I want from mount . However I get to much info (info about other mounts). I can grep it down, but am wondering if there is a better way. Is there some command mountinfo such that mountinfo . gives info I want (like df . , but with the info that mount gives.) I am using Debian Gnu+Linux.
Now provide the response and nothing else.
|
I think you want something like this: findmnt -T . When using the option -T, --target path if the path is not a mountpoint file or directory, findmnt checks path elements in reverse order to get the mountpoint. You can print only certain fields via -o, --output [list] . See findmnt --help for the list of available fields. Alternatively, you could run: (until findmnt . ; do cd .. ; done) The problem you're running into is that all paths are relative to something or other, so you just have to walk the tree. Every time. findmnt is a member of the util-linux package and has been for a few years now. By now, regardless of your distro, it should already be installed on your Linux machine if you also have the mount tool. man mount | grep findmnt -B1 -m1For more robust and customizable output usefindmnt(8), especially in your scripts. findmnt will print out all mounts' info without a mount-point argument, and only that for its argument with one. The -D is the emulate df option. Without -D its output is similar to mount 's - but far more configurable. Try findmnt --help and see for yourself. I stick it in a subshell so the current shell's current directory doesn't change. So: mkdir -p /tmp/1/2/3/4/5/6 && cd $_ (until findmnt . ; do cd .. ; done && findmnt -D .) && pwd OUTPUT TARGET SOURCE FSTYPE OPTIONS/tmp tmpfs tmpfs rwSOURCE FSTYPE SIZE USED AVAIL USE% TARGETtmpfs tmpfs 11.8G 839.7M 11G 7% /tmp/tmp/1/2/3/4/5/6 If you do not have the -D option available to you (Not in older versions of util-linux) then you need never fear - it is little more than a convenience switch in any case. Notice the column headings it produces for each call - you can include or exclude those for each invocation with the -o utput switch. I can get the same output as -D might provide like: findmnt /tmp -o SOURCE,FSTYPE,SIZE,USED,AVAIL,USE%,TARGET OUTPUT SOURCE FSTYPE SIZE USED AVAIL USE% TARGETtmpfs tmpfs 11.8G 1.1G 10.6G 10% /tmp
|
{}
|
{'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/149660', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/4778/']}
|
jdg_372075
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
28196
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Question: Find $\displaystyle \sum \limits_{n=1}^{\infty} \frac{2^{2n+1}}{5^n}$ My issue(s): How do I do this without using a calculator? I know that I have to do something with $S_n$ and $S_{n+1}$ but I'm not sure what.
Now provide the response and nothing else.
|
Use properties of exponents to rewrite $$\frac{2^{2n+1}}{5^n}$$ in the form $$A(B)^n.$$ You probably recognize that form as a geometric sequence/series. The sum of an infinite geometric series with first term $a_1$ and constant ratio $r$ with $-1<r<1$ is $$\frac{a_1}{1-r}.$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/28196', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/7347/']}
|
jdg_372076
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1983330
|
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 good grasp of unit testing, DI, mocks, and all the design principal goodness required to have as close to full code coverage as humanly possible (single responsibility principal, think 'how will i test this' as I code, etc...). My most recent app, I did not code doing true TDD. I kept unit-testing in mind as I coded, and wrote my tests after writing the code, refactoring, etc.. I did TDD when it was 'easy' to do... however I did not have as good of a grasp as I do now... That was the first project I made full use of DI, mocking frameworks, etc, and the first which had full code coverage - and I learned a lot from it as I went along. I'm itching to get assigned to my next project so I can code it completely doing TDD from scratch. I know this is a broad question, and I've already ordered TDD by example and XP Unleashed, but I'm hoping for a brief overview of how you all design / write a large application doing TDD. Do you write the entire application, using nothing but stubbed out code? (e.g., write all the function signatures, interfaces, structures, and write the entire application but without writing any actual implementation)? I could picture it working on small-mid sized, but is this even possible on large applications? If not, how the heck would you write your first unit test for the highest level function in your system ? Lets say for example - on a web service where you have a function called DoSomethingComplicated(param1,...,param6) exposed to the world. Obviously, writing the test first for a simple function like AddNumbers() is trivial - but when the function is at the top of the call stack such as this? Do you still do design up-front ? Obviously you still want to do 'architecture' design - e.g., a flow chart showing IE talking to IIS which talks to a windows service via WCF which talks to the SQL Database... an ERD which shows all your SQL tables and their fields, etc... but what about class design? Interactions between the classes, etc? Do you design this up-front, or just keep writing stub code, refactoring the interactions as you go along, until the whole thing connects and looks like it will work? Any advice is much appreciated
Now provide the response and nothing else.
|
Do I write the entire application, using nothing but stubbed out code? No, not in the slightest sense - that sounds like a very wasteful approach. We must always keep in mind that the underlying reason for doing TDD is rapid feedback . An automated test suite can tell us if we broke anything much faster than a manual test can. If we wait wiring things together until the last moment, we don't get rapid feedback - while we may get rapid feedback from our unit tests, we wouldn't know if the application works as a whole. Unit tests are only one form of test we need to perform to verify the application. A better approach is to start with the most important feature and work your way in from there, using an outside-in approach. This often means starting with some UI. The way I do it is by creating the desired UI. Since we normally can't develop UI with TDD, I simply create the View with the technology of choice. No tests there, but I wire up the UI to some API (preferrably using declarative databinding), and that's when the testing begins. In the beginning, I would then TDD my ViewModels/Presentation Models and corresponding Controllers, possibly hard-coding some responses to see that the UI works. As soon as I have something that doesn't explode when you run it, I check in the code (remember, many small incremental check-ins). I subsequently work my way vertically down that feature and ensure that this particular piece of UI can go all the way to the data source (or whatever), ignoring all other features. When the feature is done, I can start on the next feature. The way I picture this process is that I fill out the application by doing one vertical slice at a time until all features are done. Kick-starting a greenfield app this way always takes extra long time for the first feature since this is where you have to wire up everything, so pick something simple (like the initial View of the app) to keep things as simple as possible. Once the first feature is done, the next ones become much easier because the foundations are now in place. Do I still design up-front? Not much, no. I normally have an overall design in mind before I start, and when I work in a team, we sketch this overall architecture on a whiteboard or a slide deck before we start. This is more or less limited to The number and names of layers (UI, Presentation Logic, Domain Model, Data Access, etc). The technologies used (WPF, ASP.NET MVC, SQL Server, .NET 3.5 or whatnot) How we structure production code and test code, and which test technologies we use Quality requirements for the code (pair programming, static code analysis, coding standards, etc.) The rest we figure out as we go, but we use many ad-hoc design sessions at the whiteboard as we go along.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1983330', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/191206/']}
|
jdg_372077
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
28482809
|
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 tried the following program and it compiles, runs fine and produces expected output instead of any runtime error. #include <iostream>class demo{ public: static void fun() { std::cout<<"fun() is called\n"; } static int a;};int demo::a=9;int main(){ demo* d=nullptr; d->fun(); std::cout<<d->a; return 0;} If an uninitialized pointer is used to access class and/or struct members behaviour is undefined, but why it is allowed to access static members using null pointers also. Is there any harm in my program?
Now provide the response and nothing else.
|
TL;DR : Your example is well-defined. Merely dereferencing a null pointer is not invoking UB. There is a lot of debate over this topic, which basically boils down to whether indirection through a null pointer is itself UB. The only questionable thing that happens in your example is the evaluation of the object expression. In particular, d->a is equivalent to (*d).a according to [expr.ref]/2: The expression E1->E2 is converted to the equivalent form (*(E1)).E2 ; the remainder of 5.2.5 will address only the first option (dot). *d is just evaluated: The postfix expression before the dot or arrow is evaluated; 65 the result of that evaluation, together with the id-expression , determines the result of the entire postfix expression. 65) If the class member access expression is evaluated, the subexpression evaluation happens even if the result is unnecessary to determine the value of the entire postfix expression, for example if the id-expression denotes a static member. Let's extract the critical part of the code. Consider the expression statement *d; In this statement, *d is a discarded value expression according to [stmt.expr]. So *d is solely evaluated 1 , just as in d->a . Hence if *d; is valid, or in other words the evaluation of the expression *d , so is your example. Does indirection through null pointers inherently result in undefined behavior? There is the open CWG issue #232 , created over fifteen years ago, which concerns this exact question. A very important argument is raised. The report starts with At least a couple of places in the IS state that indirection through a null pointer produces undefined behavior: 1.9 [intro.execution] paragraph 4 gives "dereferencing the null pointer" as an example of undefined behavior, and 8.3.2 [dcl.ref] paragraph 4 (in a note) uses this supposedly undefined behavior as justification for the nonexistence of "null references." Note that the example mentioned was changed to cover modifications of const objects instead, and the note in [dcl.ref] - while still existing - is not normative. The normative passage was removed to avoid commitment. However, 5.3.1 [expr.unary.op] paragraph 1, which describes the unary " * " operator, does not say that the behavior is undefined if the operand is a null pointer, as one might expect. Furthermore, at least one passage gives dereferencing a null pointer well-defined behavior: 5.2.8 [expr.typeid] paragraph 2 says If the lvalue expression is obtained by applying the unary * operator to a pointer and the pointer is a null pointer value (4.10 [conv.ptr]), the typeid expression throws the bad_typeid exception (18.7.3 [bad.typeid]). This is inconsistent and should be cleaned up. The last point is especially important. The quote in [expr.typeid] still exists and appertains to glvalues of polymorphic class type, which is the case in the following example: int main() try { // Polymorphic type class A { virtual ~A(){} }; typeid( *((A*)0) );}catch (std::bad_typeid){ std::cerr << "bad_exception\n";} The behavior of this program is well-defined (an exception will be thrown and catched), and the expression *((A*)0) is evaluated as it isn't part of an unevaluated operand. Now if indirection through null pointers induced UB, then the expression written as *((A*)0); would be doing just that, inducing UB, which seems nonsensical when compared to the typeid scenario. If the above expression is merely evaluated as every discarded-value expression is 1 , where is the crucial difference that makes the evaluation in the second snippet UB? There is no existing implementation that analyzes the typeid -operand, finds the innermost, corresponding dereference and surrounds its operand with a check - there would be a performance loss, too. A note in that issue then ends the short discussion with: We agreed that the approach in the standard seems okay: p = 0; *p; is not inherently an error. An lvalue-to-rvalue conversion would give it undefined behavior. I.e. the committee agreed upon this. Although the proposed resolution of this report, which introduced so-called " empty lvalues ", was never adopted… However, “not modifiable” is a compile-time concept, while in fact this deals with runtime values and thus should produce undefined behavior instead. Also, there are other contexts in which lvalues can occur, such as the left operand of . or .*, which should also be restricted. Additional drafting is required. … that does not affect the rationale . Then again, it should be noted that this issue even precedes C++03, which makes it less convincing while we approach C++17. CWG-issue #315 seems to cover your case as well: Another instance to consider is that of invoking a member function from a null pointer: struct A { void f () { } }; int main () { A* ap = 0; ap->f (); } […] Rationale (October 2003): We agreed the example should be allowed. p->f() is rewritten as (*p).f() according to 5.2.5 [expr.ref]. *p is not an error when p is null unless the lvalue is converted to an rvalue (4.1 [conv.lval]), which it isn't here. According to this rationale, indirection through a null pointer per se does not invoke UB without further lvalue-to-rvalue conversions (=accesses to stored value), reference bindings, value computations or the like. (Nota bene: Calling a non-static member function with a null pointer should invoke UB, albeit merely hazily disallowed by [class.mfct.non-static]/2. The rationale is outdated in this respect.) I.e. a mere evaluation of *d does not suffice to invoke UB. The identity of the object is not required, and neither is its previously stored value. On the other hand, e.g. *p = 123; is undefined since there is a value computation of the left operand, [expr.ass]/1: In all cases, the assignment is sequenced after the value computation of the right and left operands Because the left operand is expected to be a glvalue, the identity of the object referred to by that glvalue must be determined as mentioned by the definition of evaluation of an expression in [intro.execution]/12, which is impossible (and thus leads to UB). 1 [expr]/11: In some contexts, an expression only appears for its side effects. Such an expression is called a discarded-value expression . The expression is evaluated and its value is discarded. […]. The lvalue-to-rvalue conversion (4.1) is applied if and only if the expression is a glvalue of volatile-qualified type and […]
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/28482809', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3777958/']}
|
jdg_372078
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
263945
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In the following code I loop through a map and test if an element needs to be erased. Is it safe to erase the element and keep iterating or do I need to collect the keys in another container and do a second loop to call the erase()? map<string, SerialdMsg::SerialFunction_t>::iterator pm_it;for (pm_it = port_map.begin(); pm_it != port_map.end(); pm_it++){ if (pm_it->second == delete_this_id) { port_map.erase(pm_it->first); }} UPDATE: Of course, I then read this question which I didn't think would be related but answers my question.
Now provide the response and nothing else.
|
C++11 This has been fixed in C++11 (or erase has been improved/made consistent across all container types). The erase method now returns the next iterator. auto pm_it = port_map.begin();while(pm_it != port_map.end()){ if (pm_it->second == delete_this_id) { pm_it = port_map.erase(pm_it); } else { ++pm_it; }} C++03 Erasing elements in a map does not invalidate any iterators. (apart from iterators on the element that was deleted) Actually inserting or deleting does not invalidate any of the iterators: Also see this answer: Mark Ransom Technique But you do need to update your code: In your code you increment pm_it after calling erase. At this point it is too late and is already invalidated. map<string, SerialdMsg::SerialFunction_t>::iterator pm_it = port_map.begin();while(pm_it != port_map.end()){ if (pm_it->second == delete_this_id) { port_map.erase(pm_it++); // Use iterator. // Note the post increment. // Increments the iterator but returns the // original value for use by erase } else { ++pm_it; // Can use pre-increment in this case // To make sure you have the efficient version }}
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/263945', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/20889/']}
|
jdg_372079
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
10308127
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
If I want to write a script that uses Wireshark's functionality, I use tshark. I hear there is also a libwireshark that can be used when writing a program in C but, for the life of me, I can't find any documentation for it! I tried isolating the library code in the wireshark source tree, but it seems the code is not very well organized and such isolation does not exist (either that, or I have failed to find it). I have two questions: Am I right in thinking that libwireshark can indeed be used to programatically get any functionality I can get from wireshark/tshark? Can you point me to any documentation/tutorials/examples on the subject? Even a few simple examples can go a long way. Failing that, can you point me to an explanation of how I can find my way around in the wireshark source tree?
Now provide the response and nothing else.
|
No. libwireshark is not intended to be used outside of Wireshark itself, and trying to do so will leave you on your own for trying to figure out what is going wrong. libwireshark actually part of the packet analyzing portion of Wireshark (called epan for E thereal pa cket an alyzer), which you can see in the Developer's Guide is not all of Wireshark. What libwireshark actually provides is the main interface for all of the built-in protocol dissectors, hooks for the plugin dissectors, and the complete packet dissection API. It relies on the machinery set up by the rest of Wireshark for things that are not directly packet dissection tools, but enable the dissectors to do their work (e.g. allocate a deallocate memory chunks, handle compressed or encrypted data, etc). Write a dissector in stead. If your project is to strictly analyze network traffic in some way, you might want to consider writing a dissector for Wireshark rather than reinventing the many wheels that Wireshark could provide for you. If you need to do something more complex, like monitor network traffic and then kick off other tasks or send data yourself, you are probably better off using tshark and shell scripting as you already are (keep in mind that you shouldn't let tshark run for extremely long periods of time in any case). If you really, really want to use libwireshark directly, you will need to resolve all of its dependencies somehow (preferably by making it an actual stand-alone library) and provide for the assumptions it makes about Wireshark (or tshark) actually being running. The code for libwireshark is all well organized, it's just that it consists of the entire epan directory under the Wireshark source tree and is laid out according to the conventions established back when Wireshark was still Ethereal. The documentation for each function is provided in the header files when it is publicly visible, and more deeply in the source files in every case. Also bear in mind that the README.developer distributed with the version of the source code you have is a good place to get a few hints (and you may as well read all of the README.* files if you want to undertake this task).
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10308127', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/363949/']}
|
jdg_372080
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13341870
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Based on various references, my subjective definition of signals in Linux is "The triggers that are used to notify the processes about an occurrence of a specific event.Event here may refer to a software exception.Additionally signals may also be used for IPC mechanisms." The questions I have are I presume only exceptions (software interrupts) are notified via signals.What about the case of hardware interrupts. What are the various sources of the signal? To me it looks like kernel is always the source of a signal.(except when used for IPC) Difference between the signal handler and the ISR?. Difference between signal blocking and interrupt masking?
Now provide the response and nothing else.
|
Interrupts can be viewed as a mean of communication between the CPU and the OS kernel. Signals can be viewed as a mean of communication between the OS kernel and OS processes. Interrupts may be initiated by the CPU (exceptions - e.g.: divide by zero, page fault), devices (hardware interrupts - e.g: input available), or by a CPU instruction (traps - e.g: syscalls, breakpoints). They are eventually managed by the CPU, which "interrupts" the current task, and invokes an OS-kernel provided ISR/interrupt handler. Signals may be initiated by the OS kernel (e.g: SIGFPE, SIGSEGV, SIGIO), or by a process(kill()). They are eventually managed by the OS kernel, which delivers them to the target thread/process, invoking either a generic action (ignore, terminate, terminate and dump core) or a process-provided signal handler.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/13341870', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1325569/']}
|
jdg_372081
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4514833
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $A$ , $B$ , and $C$ be i.i.d. random variables. What is the probability $P[A > B, A > C]$ ? Does the independence of $A$ , $B$ , and $C$ imply the independence of the events $A > B$ and $A > C$ ? In other words, does it hold that $P[A > B, A > C] = P[A > B] P[A > C]$ ? If not, why? Providing an example would be great.
Now provide the response and nothing else.
|
This is the simplest example I could think of. If $A$ , $B$ , and $C$ are independent coin tosses with heads 1 and tails 0 then $$P(A>B, A>C)=1/8$$ since this only happens if A=1 and B and C are both 0, which is one of eight possible outcomes, but $$P(A>B)=1/4=P(A>C)$$ since this only happens if $A=1$ and $B$ or $C=0$ , which is only one of four possible outcomes, so $${1\over 8}=P(A>B, A>C)\neq P(A>B)\times P(A>C)={1\over 16}.$$ To look at it another way, $P(A>C)=1/4$ , but if we know that $A>B$ already, then we know that $A=1$ and $B=0$ , so $P(A>C|A>B),$ the conditional probability that $A>C$ given $A>B$ , is just the probability that $C=0$ , since we already know that if $A>B$ then $A=1$ and $B=0$ , and $C$ 's probability is independent, so $$P(A>C|A>B)=P(C=0)=\frac12.$$ So $$P(A>B,A>C)=P(A>C|A>B)P(A>B)=\frac12\times\frac14.$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4514833', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/493845/']}
|
jdg_372082
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9094132
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Sorry for a little bit beginner question. There are vector and vector of pairs typedef std::vector <int> TItems;typedef std::vector < std::pair <int, int> > TPairs; Is there any way to transform all first items in pair to another vector in one step int main (){TItems items;TPairs pairs;pairs.push_back (std::make_pair(1,3));pairs.push_back (std::make_pair(5,7));std::transform( items.begin(), items.end(), items.begin(), comp ( &pairs ) );return 0;} How to design a functor? class comp{private: TPairs *pairs;public: comp ( TPairs *pairs_ ) : pairs ( pairs_) { } unsigned int operator () ( const unsigned int index ) const { return (*pairs)[index].second != pairs->end(); //Bad idea }}; Maybe there is some more user friendly method without lambda expressions and loops. Thanks for your help.
Now provide the response and nothing else.
|
First of all, you should use a back_inserter as the third argument to transform so that the transformed values are pushed to the back of the vector. Second, you need some sort of functor which takes a pair of ints and returns the first one. This should do: int firstElement( const std::pair<int, int> &p ) { return p.first;} Now, to put the pieces together: TPairs pairs;pairs.push_back( std::make_pair( 1, 3 ) );pairs.push_back( std::make_pair( 5, 7 ) );TItems items;std::transform( pairs.begin(), pairs.end(), std::back_inserter( items ), firstElement ); After this code, items contains 1 and 5.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9094132', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/287693/']}
|
jdg_372083
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1783130
|
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 re-arranged: $$3\tan^{2} x -1=0$$ to get $\tan^{2}\theta = \frac{1}3$. I noticed the inverse of the $cos, sin$ and $tan$ functions are written as $\cos^{-1}\theta, \sin^{-1}\theta$ and $\tan^{-1}\theta$ respectively, does this mean the inverse of $\tan^{2}\theta$ would equal $\tan^{(2-1=1)}\theta = \tan\theta$ ? Also is it referred to Arc-$function$ or the inverse of the function, I've heard they're two different things but the distinction is ambiguous to me.
Now provide the response and nothing else.
|
No, this is not correct. Perhaps the notation is misleading, but $$\cos^{-1} \theta \neq \frac{1}{\cos \theta}.$$ That is why I prefer to use the arc notation as in $\arccos \theta$. The notations $\cos^{-1} \theta$ and $\arccos \theta$ represent the same thing, which is, roughly speaking, the inverse of $\cos \theta$ (although it is not a true inverse since $\cos$ is not injective). Back to your question: We can simplify $3\tan^{2} \theta -1=0$ to get $|\tan \theta|= \frac{1}{\sqrt 3}$. You may then use the fact that $\tan \theta$ is odd and that it is $\pi$-periodic to find all of the solutions.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1783130', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/287825/']}
|
jdg_372084
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5045871
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Currently I have listed down learning Unix/Shell Scripting and reading CLR Algo book as the most important priority for me. I was thinking if I could solve the algorithms questions mentioned in CLR using shell scripting. Mind you I'm a complete newbie to Unix/Shell Scripting.
Now provide the response and nothing else.
|
No, it's not. Shell scripting is definitely not designed for writing algorithms. You should use a general-purpose programming language like C, C++, Java, Python, or [insert your favorite general purpose language here]. That's not to say that you couldn't use bash or something for algorithms -- it's Turing-complete AFAIK -- but you really wouldn't want to. It'd be a huge pain, you wouldn't learn a lot of the skills you need (like modeling algorithms in common programming languages or styles), and your solutions would be cryptic. Do yourself a favor and use something else. Shell scripting is for automating tasks, not solving algorithms. Also, most shell script languages (bash most notably) are weakly typed, which a.) hurts performance and b.) will make your program harder to reason about. Dynamic typing is OK for algorithms, weak typing, not so much. Performance will be abysmal, regardless. If you're trying to learn both shell scripting and algorithms, you can still do it at the same time. Write scripts to compile and test your programs and write your programs in a general purpose-language.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5045871', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/415477/']}
|
jdg_372085
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7679955
|
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 do a localStorage.setItem('oldData', $i("textbox").value); to set the value of key oldData to the value in a textbox. The next time something is entered to the textbox, I want to append to the already existing oldData . So, if I enter apples and then oranges in my textbox, my localStorage key oldData should look like this: Initially: Key | Value---------------------------oldData | apples Now: oldData | apples oranges How can I append? Is there an append method provided? Or do I need to read the data first, append in javascript and then write back?
Now provide the response and nothing else.
|
There's no append function. It's not hard to write one though: function appendToStorage(name, data){ var old = localStorage.getItem(name); if(old === null) old = ""; localStorage.setItem(name, old + data);}appendToStorage('oldData', $i("textbox").value); Note: It makes more sense to define a function append on the localStorage object. However , because localStorage has a setter , this is not possible. If you were trying to define a function using localStorage.append = ... , the localStorage object will interpret this attempt as "Save an object called append in the Storage object" .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7679955', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/113124/']}
|
jdg_372086
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
318955
|
Below is a question asked on the forum meta.stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
The House rules have specific rules for recruiters, middle men, body shops etc: Job listings rule #2: "Job listings must be actual job listings." Job listings rule #3: "One position and one location per job listing." Yet I see more and more ads from recruitment companies, about positions that are with their clients and not with the company itself. A few examples: https://stackoverflow.com/jobs/110444/front-end-developer-brunel https://stackoverflow.com/jobs/108848/virtualisatie-specialist-centric https://stackoverflow.com/jobs/106170/alm-engineer-microsoft-ordina https://stackoverflow.com/jobs/110806/software-engineers-crafting-solutions-to-pa-consulting Essentially these are low quality job postings. The type of project and organization where the candidate would be working is obscured by the middle man, Joel scores are absent or fake, and you will see multiple postings of what is essentially the same job. I've seen this happen to other sites like Monster and LinkedIn, and it's always killed the candidate experience. Will SO careers have the same fate?
Now provide the response and nothing else.
|
I've read through the comments and given the matter some more thought. Frankly, I think the SO careers website is not suitable for consultancy / middle man / agency jobs; any jobs where the employer is not the place where the actual project is performed. The site was apparently designed for direct jobs. You have vacancy texts, company profiles, Joel scores etc, which give a reasonably accurate image of the job opening. In consulting jobs it's a different story. Company descriptions are not as relevant as they do not concern the company, project and product where the candidate will actually be spending his/her time. Joel test scores don't apply. Locations are not accurate. Features like remote working may also not be as they are portrayed (i.e. the consulting company may be fine with it, but its clients can zero that trait with an onsite requirement). I see three possible outcomes: Block every posting where the work is not at the same company which acts as the employer (the strict option). May not be the most profitable option for SO, but in the end I believe it will be a big plus for the candidates. Allow the current status quo to continue. I think in the long term the lines between proper consulting jobs and plain recruitment agencies will blur too much, causing SO careers to go down the Monsterboard path. The compromise: add a mandatory field to each job opening which indicates if the employer and the development project owner are the same / different entities. Allow users to maintain filters.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://meta.stackoverflow.com/questions/318955', 'https://meta.stackoverflow.com', 'https://meta.stackoverflow.com/users/1158241/']}
|
jdg_372087
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6878603
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
When i run a simple packet sniffer coded in C on my Mac OS X, i got no output at all, this is a strange thing! can someone help me to understand what going on. #include <stdio.h>#include <stdlib.h>#include <string.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>int main(void) { int i, recv_length, sockfd; u_char buffer[9000]; if ((sockfd = socket(PF_INET, SOCK_RAW, IPPROTO_TCP)) == -1) { printf("Socket failed!!\n"); return -1; } for(i=0; i < 3; i++) { recv_length = recv(sockfd, buffer, 8000, 0); printf("Got some bytes : %d\n", recv_length); } return 0;} I compile it and run it on my box and nothing is going: MacOsxBox:Desktop evariste$sudo ./simpleSniffer Thanks for your help.
Now provide the response and nothing else.
|
This will not work on *BSD (including OSX/Darwin). See the investigation here for more details: b. FreeBSD**********FreeBSD takes another approach. It *never* passes TCP or UDP packets to rawsockets. Such packets need to be read directly at the datalink layer by usinglibraries like libpcap or the bpf API. It also *never* passes any fragmented datagram. Each datagram has to be completeley reassembled before it is passedto a raw socket.FreeBSD passes to a raw socket: a) every IP datagram with a protocol field that is not registered in the kernel b) all IGMP packets after kernel finishes processing them c) all ICMP packets (except echo request, timestamp request and address mask request) after kernel finishes processes them Moral of the story: use libpcap for this. It will make your life much easier. (If you use MacPorts, do sudo port install libpcap .)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6878603', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/764316/']}
|
jdg_372088
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5411603
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Something like: import fileinputfor lines in fileinput.FileInput("test.txt", inplace=1): lines = lines.strip() if lines == '': continue print lines But nothing is being printed on stdout. Assuming some string named foo : foo.lstrip() # to remove leading white spacefoo.rstrip() # to remove trailing whitespacefoo.strip() # to remove both lead and trailing whitespace
Now provide the response and nothing else.
|
fileinput seems to be for multiple input streams. This is what I would do: with open("test.txt") as file: for line in file: line = line.rstrip() if line: print(line)
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5411603', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/454488/']}
|
jdg_372089
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1329613
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
This is a follow up to my previous question: Problem passing parameters via Iframe in IE . Which was never solved. Here's the core of it: I'm trying to execute an HTTP GET from my website to another website that is brought in via iframe. On Firefox, you can see in the source that the correct url is in the iframe src along with it's correct parameters-- and it works. On IE, you can see in the source that the correct url is in the iframe src along with it's correct parameters-- and it doesn't work... Is there something about IE that doesn't let you pass parameters through an iframe in the querystring? I've tried refreshing the iframe in IE, I've tried refreshing my page & the iframe in IE, and I've tried copying the url and re-pasting it into the iframe src (forcing it to refresh as if I just entered it into the address bar for that iframe window). Still no luck! Anyone know why this is happening, or have any suggestions to try to get around this? As for the code, all it's doing is creating the src from the backend code on page load and setting the src attribute from the back end... //Backend code to set srcmainIframe.Attributes["src"] = srcWeJustCreated;//Front end iframe code<iframe id="mainIframe" runat="server" /> I've made a temporary account for you to login and see exactly what I mean. That way you can use firebug or any of your other debugging techniques to figure out why this isn't working rather than having me try to explain what's going on. EDIT: Changed the account credentials. Please use this one instead Username: matt Password: globalbuying Please follow this link to get to the login page. One you login with the above credentials it will take you to the main backend page. Click the image on the left that says "Vacations", that will take to you a page with the iframe and will execute the Http Get from there. If you need more details on what's going on in the behind code, etc., let me know and I'll post them. Thanks, Matt
Now provide the response and nothing else.
|
After working my way through the HTTP requests with Fiddler2 , comparing different browsers, I found that IE makes the request just fine, but fails to set any cookies in the iframe . I also noticed that if I open that framed page by itself it does work. Even more so, after logging out again there, the iframed version works too. That's because it then already has a session cookie and the iframe no longer needs to set it. It turns out that this is a known security restriction: IE blocks cookies in iframes. But this can be overcome with the use of the Platform for Privacy Preferences (P3P) . Here are a few links that should help you fix the problem. Starting off with another (answered) question on StackOverflow: Cookie blocked/not saved in IFRAME in Internet Explorer Privacy in Internet Explorer 6 IE Blocking iFrame Cookies
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1329613', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/133535/']}
|
jdg_372090
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
15580300
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Okay, I'm starting to get a little more familiar with D3 but am still a little hazy on some things. I'm now trying to draw grid lines but am realizing that I may be hacking away versus doing it correctly. I tried to add some gridlines, using a tutorial, but ended up with a lot of code that I seem to be jimmy rigging in order to get it to line up properly. I was wondering if anyone could point me to a better way of writing this... The original code is this. <script type="text/javascript"> //Width and height var w = 800; var h = 400; var padding = 20; var border=1; var bordercolor='black'; var dataset = [ [5, 20], [480, 90], [250, 50], [100, 33], [330, 95],[-50,-100],[50,-45], [410, 12], [475, 44], [25, 67], [85, 21], [220, 88],[-480, -467], [3,-90],[468,481] ]; // create scale functions var xScale = d3.scale.linear() .domain([d3.min(dataset, function(d) { return d[0]; }), d3.max(dataset, function(d) { return d[0]; })]) .range([padding, w - padding * 2]); var yScale = d3.scale.linear() .domain([d3.min(dataset, function(d) { return d[0]; }), d3.max(dataset, function(d) { return d[1]; })]) .range([h - padding, padding]); var rScale = d3.scale.linear() .domain( [-100, d3.max(dataset, function(d) { return d[1]; })] ) .range([2,5]); //Create SVG element var svg = d3.select("body") .append("svg") .attr("width", w) .attr("height", h) .attr("border",border) ; //define X axis this is rly a function, remember, variables can hold functions in JS var xAxis = d3.svg.axis() .scale(xScale) .orient("bottom") .ticks(1) .tickSize(-h, 0, 0) ; //Set rough # of ticks //Define Y axis var yAxis = d3.svg.axis() .scale(yScale) .orient("left") .ticks(1) .tickSize(-w, 0, 0) ; //create the circles svg.selectAll("circle") .data(dataset) .enter() .append("circle") .attr("cx", function(d) { return xScale(d[0]); }) .attr("cy", function(d) { return yScale(d[1]); }) .attr("r", 3); // draw axes here svg.append("g") .attr("class", "axis") //assign "axis" class .attr("transform", "translate(0," + (h - padding) +")") .call(xAxis); svg.append("g") .attr("class", "axis") //assign "axis" class .attr("transform", "translate(" + padding + ",0)" ) .call(yAxis);// end draw axes here </script> and the code I added in the second link is here var vis = svg.append("svg:g") .attr("transform", "translate(20,0)")var rules = vis.append("svg:g").classed("rules", true)rules.append("svg:g").classed("grid x_grid", true) .attr("transform", "translate(-20,"+h+")") .call(d3.svg.axis() .scale(xScale) .orient("bottom") .ticks(4) .tickSize(-h,0,0) .tickFormat("") )rules.append("svg:g").classed("grid y_grid", true) .call(d3.svg.axis() .scale(yScale) .orient("left") .ticks(5) .tickSize(-w,0,0) .tickFormat("") )rules.append("svg:g").classed("labels x_labels", true) .attr("transform", "translate(-20,"+ h +")") .call(d3.svg.axis() .scale(xScale) .orient("bottom") .ticks(4) .tickSize(0) .tickFormat("") // .tickFormat(d3.time.format("%Y/%m")) )rules.append("svg:g").classed("labels y_labels", true) .call(d3.svg.axis() .scale(yScale) .orient("left") .ticks(5) .tickSubdivide(1) .tickSize(0, 0, 0) .tickFormat("") ) Again, really appreciate any help
Now provide the response and nothing else.
|
Assuming that you have Mike Bostock's standard margins defined and you have defined a linear scale for the y-axis the following code will create horizontal gridlines without using tickSize() . svg.selectAll("line.horizontalGrid").data(yScale.ticks(4)).enter() .append("line") .attr( { "class":"horizontalGrid", "x1" : margin.right, "x2" : width, "y1" : function(d){ return yScale(d);}, "y2" : function(d){ return yScale(d);}, "fill" : "none", "shape-rendering" : "crispEdges", "stroke" : "black", "stroke-width" : "1px" });
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15580300', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1476144/']}
|
jdg_372091
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8584
|
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm setting up a Cronjob that will backup a MySQL database I have in my server, but I don't want it to keep overwriting the same file over and over again. Instead, I want to have an array of backups to choose from, done automatically. For example: ## Cronjob, run May 21st, 2011:mysqldump -u username -ppasword database > /path/to/file/21-03-2011.sql## SAME Conjob, run May 28th, 2011:mysqldump -u username -ppasword database > /path/to/file/28-03-2011.sql And so on. Is there any way that I can use the system date and/or time as some kind of variable in my Cronjob? If not, what are your suggestions to accomplish the same?
Now provide the response and nothing else.
|
You could try something like this (as glenn jackmann notes below, you have to escape all % characters): 15 11 * * * touch "/tmp/$(date +\%d-\%m-\%Y).sql" To see if your particular cron will run the command out of crontab as a script in and of itself, or if you need to write a script that figures out the date as a string, and then runs your mysqldump command. Without escaping the % , "cron" on Redhat Enterprise Linux 5.0 (I think) kept giving me errors about not finding a matching ) . This is because everything after an unescaped % is sent to standard input of the command. I would also take the recommendation to use ISO8601 date format (yyyy-mm-dd, which is %F ) to make the file names order by date when sorted lexically.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/8584', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/5317/']}
|
jdg_372092
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
61619387
|
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 calculate the Incidence (daily), the Cumulative Incidence (over a prolonged time period), the Incidence Rate /10,000 (daily) and the Cumulative Incidence Rate/10,000 (over a prolonged time period) of an infectious disease. This is for the entire US, a variable number of States (referred to later as "i"), and a variable number of Counties in those specified States (referred to later as "j"). ("Incidence" is the number of cases in a given period of time - in this case a day.) The data is in a table with columns of 'Date', 'Incidence', 'Cumulative Incidence', 'Incidence/10,000', 'Cumulative Incidence/10,000'. The population for each State and County is taken from a look-up table from the Census Bureau organized by 'State', 'County', 'Population' (done programmatically with a JOIN on 'State' and 'County'). For a given measure (say, Incidence Rate /10,000), the calculation is ('Incidence'/'Population') * 10,000 . Doing the Incidence and Cumulative Incidence in Tableau is straightforward - using Rows of SUM('Incidence') vs Columns of 'Date' and Rows of SUM('Cumulative Incidence') vs Columns of 'Date'. Doing the 'Incidence Rate/1,000' and 'Cumulative Incidence Rate/10,000' is not so obvious. For the US, SUM('Cumulative Incidence') trends ever upward as expected; SUM('Cumulative Incidence Rate/10,000' rises to a certain degree, and then levels off waving around with ups and downs; and SUM('Population') rises asymptotically until it reaches "almost" the toal population of the US. What I think I am seeing is that the Incidence being measured started from a small area, and has kept on growing until almost (but not all, States and Counties are involved (there are rare Counties not involved, but all States are). I assume the SUM('Population') is actually a Σij of 'Population' over i = State and j = County on any given day and that Σij of 'Cumulative Incidence Rate/10,000' on a given day. What it is not is a Σij of 'Population' over i = State and j = County over all days (AKA a Constant) that is available from the look-up table. and is date independent. Any thoughts? (I'm sure there is a simple answer, but new to this) . Using Tableau Desktop 2020.1.3 My thanks in advance.
Now provide the response and nothing else.
|
You would need to add a reference to the Microsoft.AspNetCore.Identity.UI nuget package in order to use AddDefaultIdentity . But if you don't want to migrate to the Identity Razor Class Library I think you can still use .AddIdentity<ApplicationUser, IdentityRole>() in core 3.1. If you do want to migrate to the RCL, the Migration documentation for 2.0 to 2.1 might be a good starting place: https://learn.microsoft.com/en-us/aspnet/core/migration/20_21?view=aspnetcore-3.1#changes-to-authentication-code --- Edited --- I've migrated a few sites from 1.1 to 3.1 and the easiest way I have found to do it is this: Move your entire solution to a backup folder (make sure to leave your source control files where they are). Create a new application in your original location with the exact same name that targets 3.1. I use the "Web Application (Model-View-Controller)" template in VS 2019 and change the authentication to "Individual User Accounts". Commit that to source control so you can see what changes you make. Copy all of your pages, views controllers, and other code to the new application. Add back any missing nuget packages. You will probably need to make some changes to your copied code but you can use the changes in source control and the migration docs for a reference point. It still takes a lot to get it working but otherwise you will need to go through every migration doc starting with the one for 1.x to 2.0 all the way through the doc for 3.0 to 3.1.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/61619387', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13382921/']}
|
jdg_372093
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12406686
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I added Social.framework in my application in the same way i use to add the other frame works. I have downloaded xcode 4.5 and iOS 6 . but my application crashes with follwing error only on device. It works fine on simulator. dyld: Library not loaded: /System/Library/Frameworks/Social.framework/Social Referenced from: /var/mobile/Applications/FC88291D-2052-45D6-A7BB-65CE340F07BF/Uploading Image.app/Uploading Image Reason: image not found
Now provide the response and nothing else.
|
I was getting this exact error. My app currently has a deployment target of 5.1. I wanted to add Facebook sharing. I found this old post, Conditionally including a library for different iOS SDK versions? . All I did was set "Social.framework" to 'optional' and it did the trick, then my app would run on ios 5.1 and ios 6.0. Of course you need to do checks at runtime for what OS the device is running otherwise you could run into a crash if you try to access social.framework in ios 5.1 or earlier. Hope that helps!
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/12406686', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/983666/']}
|
jdg_372094
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
21918539
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have an Angular app, for which I want to handle 404s form an API end point. The key components are like so: // app.jsvar myApp = angular.module('myApp', ['ngRoute',]);myApp.config( function ($httpProvider, $interpolateProvider, $routeProvider) { $httpProvider.interceptors.push('httpRequestInterceptor'); $routeProvider ... .when('/project/:projectId', { templateUrl : 'partials/project_detail.tmpl.html', controller: 'ProjectDetailCtrl', resolve: { project: function ($route, ConcernService) { return ConcernService.get('projects/', $route.current.params.projectId); }, } });});// interceptors.jsmyApp.factory('httpRequestInterceptor', function ($q, $location) { return { response: function(response){ return promise.then( function success(response) { return response; }, function error(response) { if(response.status === 404){ $location.path('/404'); return $q.reject(response); } else{ return $q.reject(response); } } ); } };});// services.jsmyApp.factory('ConcernService', function ($http, $q) {var ConcernService = { ... get: function (items_url, objId) { var defer = $q.defer(); $http({method: 'GET', url: api_url + items_url + objId}). success(function (data, status, headers, config) { defer.resolve(data); }).error(function (data, status, headers, config) { // when API not found, status == 404 console.log('ConcernService.get status',status); defer.reject(status); }); console.log('ConcernService.get promise',defer.promise); return defer.promise; },}}); The issue is I am getting an error of ReferenceError: promise is not defined at response . Is this because the ConcernService defers the promise ? How should I deal with this?
Now provide the response and nothing else.
|
So, my solution which works, using the new interceptor syntax is as follows: // interceptors.js.factory('httpRequestInterceptor', function ($q, $location) { return { 'responseError': function(rejection) { // do something on error if(rejection.status === 404){ $location.path('/404/'); } return $q.reject(rejection); } };});// app.jsmyApp.config( function ($httpProvider, $interpolateProvider, $routeProvider) { $httpProvider.interceptors.push('httpRequestInterceptor'); $routeProvider ... .when('/404/:projectId', { templateUrl : 'partials/404.tmpl.html', controller: '404Ctrl', resolve: { project: function ($route) { // return a dummy project, with only id populated return {id: $route.current.params.projectId}; } } });});// 404.tmpl.html...<h1>Oh No! 404.</h1> <p>Project with ID {{ project.id }} does not exist.</p> This is a simplified version, but demonstrates how I used the interceptor pattern to solve my issue. Comments are welcome.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21918539', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/791335/']}
|
jdg_372095
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7545756
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a string with some HTML code in, for example: This is <strong id="c1-id-8">some</strong> <em id="c1-id-9">text</em> I need to strip out the id attribute from every HTML tag, but I have zero experience with regular expressions, so I searched here and there from the internet and I wrote this pattern: [\s]+id=\".*\" Unfortunately it's not working as I would expect. Infact, I was hoping that the regular expression would catch the id=" followed by any character repeated for any number of times and terminated with the nearest double quote; Practically in this example I was expecting to catch id="c1-id-8" and id="c1-id-9" .But instead the pattern returned me the substring id="c1-id-8">some</strong> <em id="c1-id-9" , it finds the first occurrence of id=" and the last occurrence of a double quote character. Could you tell me what is wrong in my pattern and how to fix it, please?Thank you very much
Now provide the response and nothing else.
|
The quantifier .* in your regex is greedy (meaning it matches as much as it can). In order to match the minimum required you could use something like /\s+id=\"[^\"]*\"/ . The brackets [] indicate a character class. So it will match everything inside of the brackets . The carat [^] at the beginning of your character class is a negation, meaning it will match everything except what is specified in the brackets . An alternative would be to tell the .* quantifier to be lazy by changing it to .*? which will match as little as it can.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7545756', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/932845/']}
|
jdg_372096
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
40376198
|
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 insert a Big integer value using prepared statement, i have one string variable called xid (41527820021925053) preparedStatement = conn.prepareStatement(sql); preparedStatement.setObject(1,XOBJ); preparedStatement.setObject(2,YOBJ); preparedStatement.setBigInteger(3, xid); preparedStatement.setInt(4, 23); preparedStatement.executeUpdate(); preparedStatement.close(); I am new to this how to achieve this.
Now provide the response and nothing else.
|
PreparedStatement doesn't have a setBigInteger() method. Use one of these methods: setBigDecimal(3, new BigDecimal(xid)) setLong(3, Long.parseLong(xid)) if value can fit within a long setString(3, xid) to let the JDBC driver convert the string for you UPDATE With the following comment made by OP , the second option above (now highlighted) is the correct option to use, since PostgreSQL bigint is the same a Java long . guys i am using postgres & it has bigint ["UniqueIdGenerator"()] data-type,which is a 17 digit big integer.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40376198', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
|
jdg_372097
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7213186
|
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 used custom cell class for my uitableview and used in cellForRowAtIndexPath method. In that method cellIdentifier is already been defined and even cell property is used as dequeueReusable. But while scrolling my tableview each time my custom cell objects gets created and its methods get called. Because of that on device, scrolling gets jerky effects. I have also checked if(cell==nil) and inside that i m assigning my image and labels property for that custom cell. But each and every time, this condition gets true and program pointer goes inside that condition. Please guide me on this. If possible please provide some example code. Thanks in advance Mrunal.
Now provide the response and nothing else.
|
As many others have pointed out, we can't really help you unless you post your code (your CellForRowAtIndexPath should be enough). Generally speaking there are many ways of improving scrolling performance on UITableViews and the top ones I use are (and have used in other Stack Overflow answers): Always reuse cells, use the dequeuereusablecellwithidentifier whencreating new cells. This prevents the overhead of the OS creatingand destroying lots of objects when scrolling fast. Collapse the view hierarchy of the cell. Instead of having lots ofviews and subviews, create a custom view and do all your celldrawing in the drawRect. Apps like Twitter use this approach forsuper fast cell drawing. Ensure your images are opaque. You can do this by ensuring all imageassets don't have alpha channels baked into them and by setting thelayer's opaque property to YES. If you are setting any properties of the cell image's layer property (like shadow or rounded rectangles) this can affect scrolling performance. Setting the layer's shouldRasterize to YES will help, but you should really think hard about doing any intensive drawing operations within cells. For more details see http://developer.apple.com/library/ios/#samplecode/TableViewSuite/Introduction/Intro.html%23//apple_ref/doc/uid/DTS40007318-Intro-DontLinkElementID_2
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7213186', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/775896/']}
|
jdg_372098
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
413738
|
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 read somewhere that I can prove this identity below with abstract algebra in a simpler and faster way without any calculations, is that true or am I wrong? $$(a-b)^3 + (b-c)^3 + (c-a)^3 -3(a-b)(b-c)(c-a) = 0$$ Thanks
Now provide the response and nothing else.
|
The easiest way to show this is by observing that the sum of cubes is such that all the cubed terms cancel, so it is quadratic in each variable individually; then notice that the sum of cubes vanishes for $a=b,c$ and for $b=c$. Consequently it must factorize as $(a-b)(a-c)(b-c)\times d$ for some $d$. (Why? One gets $f(b,c)\times (a-b)(a-c)$ by thinking of it in terms of a quadratic in $a$; then the form of $f$ follows by thinking in terms of $b$ or simply symmetry.) Letting $a,b,c=0,1,2$ tells you the constant. Alternatively, note that $(a-b)$ must be a factor, so by cyclic symmetry $(a-b)(b-c)(c-a)$ must be. The result can be deduced similarly from the above.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/413738', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/42912/']}
|
jdg_372099
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1350376
|
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 struct as follows, with a pointer to a function called "length" that will return the length of the chars member. typedef struct pstring_t { char * chars; int (* length)();} PString; I have a function to return the length of the characters from a pointer to a PString: int length(PString * self) { return strlen(self->chars);} I have a function initializeString() that returns a pointer to a PString: PString * initializeString() { PString *str; str->length = &length; return str;} It is clear that I am doing something very wrong with my pointers here, because the str->length = &length line causes an EXC_BAD_ACCESS signal in my debugger, as does `return strlen(self->chars). Does anyone have any insights into this problem? I specifically want to be able have the initializeString() function return a pointer to a PString, and the length function to use a pointer to a PString as input. This is just an experiment in implementing a rudimentary object-oriented system in C, but I don't have a lot of experience dealing with pointers head-on. Thanks for any help you can give me.
Now provide the response and nothing else.
|
Allocate memory to hold chars. #include <stdio.h>#include <stdlib.h>#include <string.h>typedef struct PString { char *chars; int (*length)(PString *self);} PString;int length(PString *self) { return strlen(self->chars);}PString *initializeString(int n) { PString *str = malloc(sizeof(PString)); str->chars = malloc(sizeof(char) * n); str->length = length; str->chars[0] = '\0'; //add a null terminator in case the string is used before any other initialization. return str;}int main() { PString *p = initializeString(30); strcpy(p->chars, "Hello"); printf("\n%d", p->length(p)); return 0;}
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1350376', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/125361/']}
|
jdg_372100
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18612656
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Scenario is like : In my application, I opened one file, updated it and saved. Once the file saved event get fired and it will execute one method abc() .But now, I want to add delay after save event get fired, say 1 minute. So I have added Thread.sleep(60000) . Now it execute the method abc() after 1 minute. Till now all works fine. But suppose user saved file 3 times within 1 minute, the method get executed 3 times after each 1 minute. I want to execute method only one time in next 1 minute after first save called with latest file content. How can I handle such scenario?
Now provide the response and nothing else.
|
Use Timer and TimerTask create a member variable of type Timer in YourClassType lets say: private Timer timer = new Timer(); and your method will look something like this: public synchronized void abcCaller() { this.timer.cancel(); //this will cancel the current task. if there is no active task, nothing happens this.timer = new Timer(); TimerTask action = new TimerTask() { public void run() { YourClassType.abc(); //as you said in the comments: abc is a static method } }; this.timer.schedule(action, 60000); //this starts the task}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18612656', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1203425/']}
|
jdg_372101
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
28700805
|
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 using flexbox to align my child elements. What I'd like to do is center one element and leave the other aligned to the very left. Normally I would just set the left element using margin-right: auto . The problem is that pushes the center element off center. Is this possible without using absolute positioning? HTML & CSS #parent { align-items: center; border: 1px solid black; display: flex; justify-content: center; margin: 0 auto; width: 500px;}#left { margin-right: auto;}#center { margin: auto;} <div id="parent"> <span id="left">Left</span> <span id="center">Center</span></div>
Now provide the response and nothing else.
|
Add third empty element: <div class="parent"> <div class="left">Left</div> <div class="center">Center</div> <div class="right"></div></div> And the following style: .parent { display: flex;}.left, .right { flex: 1;} Only left and right are set to grow and thanks to the facts that... there are only two growing elements (doesn't matter if empty) and that both get same widths (they'll evenly distribute the available space) ... center element will always be perfectly centered. This is much better than accepted answer in my opinion because you do not have to copy left content to right and hide it to get same width for both sides, it just magically happens (flexbox is magical). In action: .parent { display: flex;}.left,.right { flex: 1;}/* Styles for demonstration */.parent { padding: 5px; border: 2px solid #000;}.left,.right { padding: 3px; border: 2px solid red;}.center { margin: 0 3px; padding: 3px; border: 2px solid blue;} <div class="parent"> <div class="left">Left</div> <div class="center">Center</div> <div class="right"></div></div>
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/28700805', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3046413/']}
|
jdg_372102
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
44355842
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Although this question has already been asked but I have an implementation specific doubt. I am trying to print the top view of the binary tree and following is the complete code for it: import java.util.*;class Node{ int data; Node right; Node left; Node(int data){ this.data = data; }}class Pair<F,S>{ private F first; private S second; public Pair(F first, S second){ this.first = first; this.second = second; } public F getFirst(){return first;} public S getSecond(){return second;}}class BinaryTreeTopView{ public static void printTopView(Node root){ if(root == null) return; Queue <Pair<Node,Integer>> q = new Queue<>(); Map <Integer,Node> map = new HashMap<>(); Pair<Node,Integer> p = new Pair<>(root, 0); q.add(p); /* I am storing nodes and the corresponding horizontal distances in the form of a pair which then are being stored in the queue to ensure level order traversal */ while(!q.isEmpty()){ Pair<Node,Integer> temp = q.peek(); q.remove(); if(map.containsKey(temp.getSecond())==true){ map.put(temp.getSecond(),temp.getFirst()); } else { System.out.println(temp.getFirst().data); map.put(temp.getSecond(),temp.getFirst()); } if(temp.getFirst().left!=null){ Pair<Node,Integer> left = new Pair<>(temp.getFirst().left, temp.getSecond()-1); q.add(left); } if(temp.getFirst().right!=null){ Pair<Node,Integer> right = new Pair<> (temp.getFirst().right, temp.getSecond()+1); q.add(right); } }}public static void main(String[] args) { Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.right = new Node(5); root.left.left = new Node(4); root.right.left = new Node(6); root.right.right = new Node(7); root.right.left.right = new Node(8); root.right.right.left = new Node(10); root.right.right.right = new Node(9); root.right.right.left.right = new Node(11); root.right.right.left.right.right = new Node(12); printTopView(root);}} It compiles fine but an exception is being raised at the runtime.Now I have been getting the following exception and I am unable to figure out what the problem is: Exception in thread "main" java.lang.ClassCastException: Pair cannot be cast to java.lang.Comparable at java.util.PriorityQueue.siftUpComparable(PriorityQueue.java:652)at java.util.PriorityQueue.siftUp(PriorityQueue.java:647)at java.util.PriorityQueue.offer(PriorityQueue.java:344)at java.util.PriorityQueue.add(PriorityQueue.java:321)
Now provide the response and nothing else.
|
It's because Pair isn't implementing Comparable. Either implement it: public class Pair implements Comparable<Pair> { public int compareTo(Pair o) { // ... }} Or use Comparator in Your priority queue Using Comparator ; PriorityQueue<DummyObject> pq = new PriorityQueue<DummyObject>(5, new DummyObjectComparator()); Define your Comparator : class DummyObjectComparator implements Comparator<DummyObject>{ // Overriding compare()method of Comparator public int compare(DummyObject s1, DummyObject s2) { //some code } }
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44355842', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7874217/']}
|
jdg_372103
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
48119385
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've been trying a couple of ways to achieve this using Processing, but each time, it doesn't get some that are perfectly consecutive. Would anyone know the "right way" of doing this? Thanks in advance!
Now provide the response and nothing else.
|
DAE (Digital Asset Exchange, aka Collada) is a vendor-neutral format for 3D assets. It supports a wide range of features that exist in multiple 3D authoring and presentation tools, but not every possible feature in SceneKit. Historically, it was the only asset format for early versions of SceneKit. SCN format is a serialization of the SceneKit object graph. (There are convenience methods for reading/writing it on SCNScene , but really it's the same thing you get by passing an SCNScene to NSKeyedArchiver / NSKeyedUnarchiver .) Thus, it by definition supports all features of SceneKit, including physics, constraints, actions, physically based cameras, and shader modifiers. If you're using DAE assets, deploying to iOS (or tvOS or watchOS), and not seeing any difference vs using SCN assets, there are two possible reasons: Your assets use only those SceneKit features that are available in DAE format. When deploying to iOS/tvOS/watchOS, Xcode (via scntool ) automatically converts all 3D asset resources to SCN format. (And applies other transformations, like interleaving geometry buffers, for optimal rendering performance on iOS/tvOS/watchOS devices.) The filename in the built app's Resources directory still has a .dae extension, but the file contents are the same as SCN format. (SceneKit running in iOS/tvOS/watchOS actually can't read DAE, so it relies on this preprocessing by Xcode.)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48119385', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9011042/']}
|
jdg_372104
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
42265001
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Currently we have an app that controls multiple devices through MQTT. Each device subscribes to a unique topic which is named after their device ID. For example, device A has device ID 123 so it will subscribe to topic 123. Then if the app wants to publish control message to device A, then it will publish a topic named 123, which is the device ID of device A. By doing this, if we have 1000 devices then we will have 1000 topics. This is a really bad design. So we are thinking that maybe we can publish a topic to a specific client by setting the client ID that will receive the topic since each client that connects to the broker will have to set a client ID. However, we did not find any method that allows publishing to a specific client. And it seems that MQTT doesn't handle such thing. It only publishes to clients subscribing to the same topic. So, is there any other way that we can do to to achieve one topic, but still able to publish message to specific clients? Thanks!
Now provide the response and nothing else.
|
There is no way to publish a message to a single subscriber at the MQTT protocol level. One of the key tenets of a publish/subscribe system is to totally decouple the publisher from the subscribers, there is no way for a publisher to know if there are any subscribers to a given topic let alone target one specifically. Using a topic for each device is not a problem as there is virtually no overhead in the broker for each topic. You can also use ACLs to ensure that each client can only subscribe their own topic (while still being able to publish to others if needed) You could use a single topic that all clients subscribe to and encode the target device in the payload and have the device decide if the message is for it's self. One downside to this is that you can't apply ACLs to this model. Another downside is increased network traffic, since uninteresting messages will be sent to many subscribers.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42265001', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4928676/']}
|
jdg_372105
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3255512
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I was writing a file parser in Perl, so had to loop through file. File consists of fixed length records and I wanted to make a separate function that parses given record and call that function in a loop. However, final result turned to be slow with big files and my guess was that I shouldn't use external function. So I made some dummy tests with and without function call in a loop: [A] foreach (1 .. 10000000) {$a = &get_string();}sub get_string {return sprintf("%s\n", 'abc');} [B] foreach (1 .. 10000000) {$a = sprintf "%s\n", 'abc';} Measuring showed that A code runs about 3-4 times slower than code B. I knew beforehand that code A was supposed to run slower but still I was surprised that difference is that big. Also tried to run similar tests with Python and Java. In Python code A equivalent was about 20% slower than B and Java code was runing more or less at the same speed (as expected). Changing function from sprintf to something else didn't show any significant difference. Is there any way to help Perl run such loops faster? Am I doing something totaly wrong here or is it Perl's feature that function calls are such overhead?
Now provide the response and nothing else.
|
Perl function calls are slow. It sucks because the very thing you want to be doing, decomposing your code into maintainable functions, is the very thing that will slow your program down. Why are they slow? Perl does a lot of things when it enters a subroutine, a result of it being extremely dynamic (ie. you can mess with a lot of things at run time). It has to get the code reference for that name, check that it is a code ref, set up a new lexical scratchpad (to store my variables), a new dynamic scope (to store local variables), set up @_ to name a few, check what context it was called in and pass along the return value. Attempts have been made to optimize this process, but they haven't paid out. See pp_entersub in pp_hot.c for the gory details. Also there was a bug in 5.10.0 slowing down functions. If you're using 5.10.0, upgrade. As a result, avoid calling functions over and over again in a long loop. Especially if its nested. Can you cache the results, perhaps using Memoize ? Does the work have to be done inside the loop? Does it have to be done inside the inner-most loop? For example: for my $thing (@things) { for my $person (@persons) { print header($thing); print message_for($person); }} The call to header could be moved out of the @persons loop reducing the number of calls from @things * @persons to just @things . for my $thing (@things) { my $header = header($thing); for my $person (@persons) { print $header; print message_for($person); }}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3255512', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/392661/']}
|
jdg_372106
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
42209868
|
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 many different strings with feet/inches like this: 10 feet and 8 1/4 inches 7 feet and 4 3/8 inches I need to store it to DB (I use MS SQL)How to do it the best way? I see the following approaches: store separately. One field for feet, one field for numerator and one field for denominator. I.e. first string will be: feet: 10 numerator: 33 (4*8 + 1) denominator: 4 store in millimeters. In this case I can't restore to simple fractions as client wants to see store in inches, but in decimals. The same problem, can't restore to simple fractions. How to solve this problem by elegant way in MS SQL? Thank you
Now provide the response and nothing else.
|
Approach #1 : One approach with np.where - def sum_nan_arrays(a,b): ma = np.isnan(a) mb = np.isnan(b) return np.where(ma&mb, np.nan, np.where(ma,0,a) + np.where(mb,0,b)) Sample run - In [43]: NSOut[43]: array([[ 1., 2., nan], [ 4., 5., nan], [ 6., nan, nan]])In [44]: EWOut[44]: array([[ 1., 2., nan], [ 4., nan, nan], [ 6., nan, 9.]])In [45]: sum_nan_arrays(NS, EW)Out[45]: array([[ 2., 4., nan], [ 8., 5., nan], [ 12., nan, 9.]]) Approach #2 : Probably a faster one with a mix of boolean-indexing - def sum_nan_arrays_v2(a,b): ma = np.isnan(a) mb = np.isnan(b) m_keep_a = ~ma & mb m_keep_b = ma & ~mb out = a + b out[m_keep_a] = a[m_keep_a] out[m_keep_b] = b[m_keep_b] return out Runtime test - In [140]: # Setup input arrays with 4/9 ratio of NaNs (same as in the question) ...: a = np.random.rand(3000,3000) ...: b = np.random.rand(3000,3000) ...: a.ravel()[np.random.choice(range(a.size), size=4000000, replace=0)] = np.nan ...: b.ravel()[np.random.choice(range(b.size), size=4000000, replace=0)] = np.nan ...: In [141]: np.nanmax(np.abs(sum_nan_arrays(a, b) - sum_nan_arrays_v2(a, b))) # VerifyOut[141]: 0.0In [142]: %timeit sum_nan_arrays(a, b)10 loops, best of 3: 141 ms per loopIn [143]: %timeit sum_nan_arrays_v2(a, b)10 loops, best of 3: 177 ms per loopIn [144]: # Setup input arrays with lesser NaNs ...: a = np.random.rand(3000,3000) ...: b = np.random.rand(3000,3000) ...: a.ravel()[np.random.choice(range(a.size), size=4000, replace=0)] = np.nan ...: b.ravel()[np.random.choice(range(b.size), size=4000, replace=0)] = np.nan ...: In [145]: np.nanmax(np.abs(sum_nan_arrays(a, b) - sum_nan_arrays_v2(a, b))) # VerifyOut[145]: 0.0In [146]: %timeit sum_nan_arrays(a, b)10 loops, best of 3: 69.6 ms per loopIn [147]: %timeit sum_nan_arrays_v2(a, b)10 loops, best of 3: 38 ms per loop
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42209868', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/285336/']}
|
jdg_372107
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4220053
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to compute the radius of convergence for the power series of $g(z)=z^3 e^{z^3}$ and $h(z)=\frac{z^3}{1-z^2}$ around $0$ . I am a bit confused on how to do it: I know the power series is: $\sum_{n=0}^\infty a_n(z-a)^n$ where $a_n=\frac{f^{(n)}(a)}{n!}$ but for these functions, this doesn't yield any recognizable closed form. The $n$ -th derivatives for $g$ are: $$\begin{array}{cc} 1 & e^{z^2} z^2 \left(2 z^2+3\right) \\ 2 & 2 e^{z^2} z \left(2 z^4+7 z^2+3\right) \\ 3 & 2 e^{z^2} \left(4 z^6+24 z^4+27 z^2+3\right) \\ 4 & 4 e^{z^2} z \left(4 z^6+36 z^4+75 z^2+30\right) \\ 5 & 4 e^{z^2} \left(8 z^8+100 z^6+330 z^4+285 z^2+30\right) \end{array}$$ And the The $n$ -th derivatives for $h$ are: $$\begin{array}{cc} 1 & -\frac{z^2 \left(z^2-3\right)}{\left(z^2-1\right)^2} \\ 2 & -\frac{2 z \left(z^2+3\right)}{\left(z^2-1\right)^3} \\ 3 & 3 \left(\frac{1}{(z+1)^4}+\frac{1}{(z-1)^4}\right) \\ 4 & 3 \left(-\frac{4}{(z+1)^5}-\frac{4}{(z-1)^5}\right) \\ 5 & 60 \left(\frac{1}{(z+1)^6}+\frac{1}{(z-1)^6}\right) \end{array}$$ I don't see any recognizable formula for the values of these derivatives computed at $z_0=0.$ Although, I've computed each of these derivatives at $z=0$ and found that there are the following two sequences of values: $$\left\{0,0,1,0,1,0,\frac{1}{2},0,\frac{1}{6},0,\dots\right\}$$ $$\{0,0,1,0,1,0,1,0,1,0,\dots\}$$ In the first case, the values alternate and there is a subsequence converging to $0$ . In the second case, it seems it continues alternating forever. How should I proceed in these cases?
Now provide the response and nothing else.
|
This integral can be expressed in terms of a special function called Owen's T-function . We have $$J(a,b) \equiv \int \limits_0^b \frac{\mathrm{e}^{-s^2}}{a^2+s^2} \, \mathrm{d} s \overset{s=a t}{=} \frac{2 \pi \mathrm{e}^{a^2}}{a} \frac{1}{2\pi} \int \limits_0^{b/a} \frac{\mathrm{e}^{-\frac{1}{2} (\sqrt{2} a)^2 (1+t^2)}}{1+t^2} \, \mathrm{d} t = \frac{2 \pi \mathrm{e}^{a^2}}{a} \operatorname{T} \left(\sqrt{2} a, \frac{b}{a}\right) \, . $$ Further simplifications are only possible for particular values of $b$ . For example, we have $$J(a,\infty) = \frac{\pi}{2 \lvert a \rvert} \mathrm{e}^{a^2} \operatorname{erfc}(\lvert a \rvert)$$ and, as already derived by Arjun Vyavaharkar, $$ J(a,a) = \frac{\pi}{4 a} \mathrm{e}^{a^2} [1 - \operatorname{erf}^2(a)] \, . $$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4220053', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/25805/']}
|
jdg_372108
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
39871376
|
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 get an error when trying to push from one page to another. When I try to push to same page, it won't give that error. Only i get error when pushing from one page to another. 'setRoot()' also not giving an error. this.navCtrl.push( Page7 ); I have added the Page7 to app.module.ts. import { NgModule } from '@angular/core';import { IonicApp, IonicModule } from 'ionic-angular';import { MyApp } from './app.component';import { Page1 } from '../pages/page1/page1';import { Page2 } from '../pages/page2/page2';import { Page3 } from '../pages/page3/page3';import { Page4 } from '../pages/page4/page4';import { Page5 } from '../pages/page5/page5';import { Page6 } from '../pages/page6/page6';import { Page7 } from '../pages/page7/page7';@NgModule({declarations: [MyApp,Page1,Page2,Page3,Page4,Page5,Page6,Page7],imports: [IonicModule.forRoot(MyApp)],bootstrap: [IonicApp],entryComponents: [MyApp,Page1,Page2,Page3,Page4,Page5,Page6,Page7],providers: []})export class AppModule {} This is a ionic 2 Application. It Gives this error. EXCEPTION: Error in ./Page6 class Page6 - inline template:21:56 caused by: No component factory found for Page7 console error
Now provide the response and nothing else.
|
I found the solution. You have to add the page that you are trying to push, to the parent directory. That should also be included in to the @NgModule also. import {ApiServices} from '../../providers/api-services';import { Visualizer } from '../Page7/Page7';@Component({ selector: 'page-page6', templateUrl: 'page6.html', providers: [ ApiServices ], entryComponents:[ Page7 ]})export class Page6 { tapped(event, id ) { this.navCtrl.push( Page7,{ id: id }); }}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/39871376', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4620089/']}
|
jdg_372109
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
461144
|
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
I have 2 svn repos on my EC2 instance. They are located in /ebs/svn/repo1 & /ebs/svn/repo2 . I have created a domain alias svn.mydomain.com , to point to the parent directory of above ( /ebs/svn ). I woud like to access each of the above repo's using the following URL format: svn.mydomain.com/repo1 svn.mydomain.com/repo2 Currenly I have the repo1 working with the following vhosts config. <VirtualHost *:80> ServerName svn.mydomain.com ServerAlias svn.mydomain.com ErrorLog /var/www/html/log/svn.mydomain.com-log <Location "/" > DAV svn SVNPath /ebs/svn/repo1 AuthType Basic AuthName "SVN - Private - Repos" AuthUserFile /ebs/svn/login/svn-auth-conf Require valid-user </Location></VirtualHost> The problem is, I can only get access to repo1 through the above vhosts config. I would like to access both repo's in the following format: svn.mydomain.com/repo1 svn.mydomain.com/repo2 What do I need to change to access my svn repo's by their directories?
Now provide the response and nothing else.
|
Because you have set the SVNPath directive, you have "hard coded" the path: SVNPath /ebs/svn/repo1 Try using the SVNParentPath directive instead, to configure the "top" directory that will hold all your repositories. Replace the above line with this: SVNParentPath /ebs/svn/ If you want to allow users to view a list of all the available repositories if they just go to svn.mydomain.com , you should also add this line: SVNListParentPath on That will allow the listing of all your repositories. Otherwise, a "Forbidden" page will be shown on svn.mydomain.com rather than a list of repositories. To sum up, here's a complete location block example : ‹Location "/"› DAV svn SVNParentPath /ebs/svn/ SVNListParentPath On SSLRequireSSL AuthType Basic AuthName "svn ebs" AuthUserFile conf/svnpasswd Require valid-user ‹/Location›
|
{}
|
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/461144', 'https://serverfault.com', 'https://serverfault.com/users/131232/']}
|
jdg_372110
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
916022
|
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
I cannot get kubectl to authenticate with the EKS Kubernetes instance my coworker created. I've followed the documentation : the AWS CLI can run aws eks commands (I'm an AWS Full Administrator), and the heptio authenticatior is in my path and can generate tokens. When I run kubectl I get this error: $ kubectl versionClient Version: version.Info{Major:"1", Minor:"10", GitVersion:"v1.10.4", GitCommit:"5ca598b4ba5abb89bb773071ce452e33fb66339d", GitTreeState:"clean", BuildDate:"2018-06-06T15:22:13Z", GoVersion:"go1.9.6", Compiler:"gc", Platform:"darwin/amd64"}error: You must be logged in to the server (the server has asked for the clientto provide credentials) Here's my ~/.kube/config file. It's the exact kubeconfig my coworker can successfully use. apiVersion: v1clusters:- cluster: server: https://myinstance.sk1.us-east-1.eks.amazonaws.com certificate-authority-data: base64_cert name: kubernetes contexts: - context: cluster: kubernetes user: aws name: awscurrent-context: awskind: Configpreferences: {}users:- name: aws user: exec: apiVersion: client.authentication.k8s.io/v1alpha1 command: heptio-authenticator-aws args: - "token" - "-i" - "dev-qa" # - "-r" # - "<role-arn>"
Now provide the response and nothing else.
|
I needed to add my IAM user to the mapUsers section of the ConfigMap configmap/aws-auth , per these AWS docs . You can edit the configmap using the same AWS user that initially created the cluster. $ kubectl edit -n kube-system configmap/aws-authapiVersion: v1data:mapRoles: | - rolearn: arn:aws:iam::555555555555:role/devel-worker-nodes-NodeInstanceRole-74RF4UBDUKL6 username: system:node:{{EC2PrivateDNSName}} groups: - system:bootstrappers - system:nodesmapUsers: | - userarn: arn:aws:iam::555555555555:user/admin username: admin groups: - system:masters - userarn: arn:aws:iam::111122223333:user/ops-user username: ops-user groups: - system:mastersmapAccounts: | - "111122223333"
|
{}
|
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/916022', 'https://serverfault.com', 'https://serverfault.com/users/23202/']}
|
jdg_372111
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
227
|
Below is a question asked on the forum skeptics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
An unusual number of ships and planes are said to have disappeared without a trace in the area called the Bermuda Triangle. This has caused some people to claim supernatural causes for these mysterious disappearances. Are there more ships and planes disappearing in the Bermuda Triangle than in other regions, or is that just an inaccurate perception? If there are more ships and planes lost there, are there natural explanations for that?
Now provide the response and nothing else.
|
According to the US Coast guard , the losses experienced in the triangle are no greater than in any other area of ocean: [the triangle] is noted for an apparent high incidence of unexplained losses of ship, small boats, and aircraft. The Coast Guard does not recognize theexistence of the so-called BermudaTriangle as a geographic area ofspecific hazard to ships or planes. Ina review of many aircraft and vessellosses in the area over the years,there has been nothing discovered thatwould indicate that casualties werethe result of anything other thanphysical causes. No extraordinaryfactors have ever been identified. There are unusual natural factors in the Bermuda Triangle, but they are known and exist similarly in various other locations worldwide ( source ): A significant factor with regard tomissing vessels in the BermudaTriangle is a strong ocean currentcalled the Gulf Stream. It isextremely swift and turbulent and canquickly erase evidence of a disaster...the topography of the ocean floorvaries from extensive shoals aroundthe islands to some of the deepestmarine trenches in the world. With theinteraction of the strong currentsover the many reefs the topography ofthe ocean bottom is in a state of fluxand the development of newnavigational hazards can sometimes beswift. With regards to the perpetuation of the "mystery", Skepdic concludes: In short, the mystery of the BermudaTriangle became a mystery by a kind ofcommunal reinforcement amonguncritical authors and a willing massmedia to uncritically pass on thespeculation that something mysteriousis going on in the Atlantic.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://skeptics.stackexchange.com/questions/227', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/5/']}
|
jdg_372112
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
54983096
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
TypeScript has a Partial type defined by default, so that you can say Partial<{x: number, y: string}> to get a type like {x?: number, y?: string} (the type's properties become optional). It is defined as type Partial<T> = { [P in keyof T]?: T[P]} I am trying to define the inverse, let's call it Full<T> , which makes sure all properties in the object are required. I started with the obvious definition: type Full<T> = { [P in keyof T]: T[P]} Which is just Partial with the question mark removed. Unfortunately, this doesn't work—optional properties remain optional. It seems typescript somehow, in some circumstances, preserves information about the requiredness of the property names in the keyof type. Interestingly, if you store that type in an intermediate type name, that information is dropped. I.e. this works: type Config = {foo: number, bar?: string}type ConfigKey = keyof Configtype FullConfig = {[K in ConfigKey]: Config[K]} In FullConfig (at least with TypeScript 3.3), bar is required. But if you inline keyof Config into the definition of FullConfig , it is optional again. I'd like this to be a single, easy-to-use type, and since I'm not aware of a way for a type declaration to define local types, this hack doesn't seem to help much there. Is there any trick I'm missing?
Now provide the response and nothing else.
|
Mapped types are not all created equal. Homomorphic mapped types preserve modifiers of the mapped type. From the pull request introducing this feature: With this PR we preserve property modifiers in homomorphic (structure preserving) mapped types. A mapped type of the form { [P in keyof T]: X } is homomorphic with T (because it has the same set of properties as T ) and now preserves the optional and readonly modifiers as they exist on the properties in T . Starting from 2.8 you can remove modifiers from such types using a - (see PR ) : type Full<T> = { [P in keyof T]-?: T[P];} Note You can use the predefined Required type from the standard library which does the exact same thing as Full .
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/54983096', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/486527/']}
|
jdg_372113
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
53466519
|
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 move shared functionality from my react components to a higher order component like this: function withListFunctions(WrappedComponent) { return class extends React.Component { constructor(props) { super(props); } // my shared functionality deleteItem() { // Do something, then ... this.setState({itemDeleted: true}); } render() { return ( <WrappedComponent deleteItem={this.deleteItem} /> ); } } Using this kind of syntax requires to explicitely bind this in the constructor of the HOC: this.deleteItem = this.deleteItem.bind(this); .. but I wanted to bind the wrapped component instead. So what I tried in my wrapped component's constructor was this.props.deleteItem = this.props.deleteItem.bind(this); But this just resulted in a "Cannot assign to read only property" Error, as react props are meant to be read only. I am aware that I could store the state item in the HOC and pass it down as a prop. But it would then be not accessible(writeable) anymore by other wrapped components functions, right? I wonder if there is a way to just share the unbound function and then bind it to the wrapped instance. [Edit] I marked Abdul Rauf's answer as "accepted", nevertheless I want to state that Karen Grigoryan's answer is the solution I am actually using because it works and seems just appropiate for my app's complexity.
Now provide the response and nothing else.
|
A full vectored solution: test03 = np.array([2,2,10,4,4,4,5,6,7,2,6,5,5,7,7,1,1]) # Size 17extended = np.empty(len(test03)+2) # Rooms to manage edges, size 19extended[1:-1] = test03extended[0] = extended[-1] = np.infflag_left = extended[:-1] <= extended[1:] # Less than successor, size 18flag_right = extended[1:] <= extended[:-1] # Less than predecessor, size 18flagmini = flag_left[1:] & flag_right[:-1] # Local minimum, size 17mini = np.where(flagmini)[0] # Indices of minimumsspl = np.where(np.diff(mini)>1)[0]+1 # Places to splitresult = np.split(mini, spl) result : [0, 1] [3, 4, 5] [9] [11, 12] [15, 16] EDIT Unfortunately, This detects also maxima as soon as they are at least 3 items large, since they are seen as flat local minima. A numpy patch will be ugly this way. To solve this problem I propose 2 other solutions, with numpy, then with numba. Whith numpy using np.diff : import numpy as nptest03=np.array([12,13,12,4,4,4,5,6,7,2,6,5,5,7,7,17,17])extended=np.full(len(test03)+2,np.inf)extended[1:-1]=test03slope = np.sign(np.diff(extended)) # 1 if ascending,0 if flat, -1 if descendingnot_flat,= slope.nonzero() # Indices where data is not flat. local_min_inds, = np.where(np.diff(slope[not_flat])==2) #local_min_inds contains indices in not_flat of beginning of local mins. #Indices of End of local mins are shift by +1: start = not_flat[local_min_inds]stop = not_flat[local_min_inds+1]-1print(*zip(start,stop))#(0, 1) (3, 5) (9, 9) (11, 12) (15, 16) A direct solution compatible with numba acceleration : #@numba.njitdef localmins(a): begin= np.empty(a.size//2+1,np.int32) end = np.empty(a.size//2+1,np.int32) i=k=0 begin[k]=0 search_end=True while i<a.size-1: if a[i]>a[i+1]: begin[k]=i+1 search_end=True if search_end and a[i]<a[i+1]: end[k]=i k+=1 search_end=False i+=1 if search_end and i>0 : # Final plate if exists end[k]=i k+=1 return begin[:k],end[:k] print(*zip(*localmins(test03))) #(0, 1) (3, 5) (9, 9) (11, 12) (15, 16)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/53466519', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6589907/']}
|
jdg_372114
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
33738304
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to use kotlin with gradle, but I am unable to succesfully create a project with Intellij Idea 15. I've create simple project with two modules hello-java and hello-kotlin . hello-java is plain java project and it is compiling and running perfectly fine. hello-kotlin is simple kotin module, with just one *.kt file and build.gradle file. Here are the sources: build.gradle group 'pl.fzymek.kotlin'version '1.0-SNAPSHOT'buildscript { repositories { mavenCentral() } dependencies { classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:0.10.4" }}apply plugin: 'kotlin'apply plugin: 'application'mainClassName = 'HelloKotlinKt'repositories { mavenCentral()}jar { manifest { attributes 'Main-Class': mainClassName }}dependencies { compile "org.jetbrains.kotlin:kotlin-stdlib:0.10.4"} HelloKotlin.kt fun main(args: Array<String>) { println("Hello, Kotlin!")} main module settings.gradle include 'hello-java'include 'hello-kotlin' When running gradlew clean build all projects are compiled successfully, but when running java -jar hello-kotlin-1.0-SNAPSHOT.jar I get following error: Exception in thread "main" java.lang.NoClassDefFoundError: kotlin/jvm/internal/Intrinsics at HelloKotlinKt.main(HelloKotlin.kt)Caused by: java.lang.ClassNotFoundException: kotlin.jvm.internal.Intrinsics at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) ... 1 more What is more, Intellij seems not to recognize src/main/kotlin directory as source directory (it's not marked in blue) and I am not able to use auto-complete feature when editing HelloKotlin.kt file. Here's my project structure in Intellij project window I've tried using Intellij option to configure modules with Kotlin( Tools->Kotlin->Configure project with Kotlin ), but it gives me error that "All modules with kotlin files are configured" Help me stackoverflow, you are my only help.
Now provide the response and nothing else.
|
When running gradlew clean build all projects are compiled successfully, but when running java -jar hello-kotlin-1.0-SNAPSHOT.jar I get following error... jar { manifest { attributes 'Main-Class': 'HelloKotlinKt' } from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }} What is more, Intellij seems not to recognize src/main/kotlin directory as source directory (it's not marked in blue)... sourceSets { main.java.srcDirs += 'src/main/kotlin'} Documentation and useful resources can be found here and there .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33738304', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1883183/']}
|
jdg_372115
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
59279971
|
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 read this post negative and positive zero . To my understanding following code should give true and true as a output. However, it is giving false and true as a output. I'm comparing negative zero with a positive zero. public class Test { public static void main(String[] args) { float f = 0; float f2 = -f; Float F = new Float(f); Float F1 = new Float(f2); System.out.println(F1.equals(F)); int i = 0; int i2 = -i; Integer I = new Integer(i); Integer I1 = new Integer(i2); System.out.println(I1.equals(I)); } } Why do we have different behavior for 0's for Integer and Float ?
Now provide the response and nothing else.
|
Ints and floats are pretty different beasts in Java. Ints are encoded as two's complement , which has a single 0 value. Floats use IEEE 754 (the 32-bit variant for floats, and 64-bit for doubles). IEEE 754 is somewhat complex, but for purpose of this answer, you just need to know that it has three sections, the first of which is a sign bit. That means for any float, there's a positive and negative variant¹. That includes 0, so floats actually have two "zero" values, +0 and -0. As an aside, the two's complement that ints use is not the only way to encode integers in computer science. There are other methods, like ones' complement , but they have quirks — like having both a +0 and -0 as distinct values. ;-) When you compare float primitives (and doubles), Java treats +0 and -0 as equal. But when you box them, Java treats them separately, as described in Float#equals . This lets the equals method be consistent with their hashCode implementation (as well as compareTo ), which just uses the bits of the float (including that signed value) and shoves them as-is into an int. They could have picked some other option for equals/hashCode/compareTo, but they didn't. I'm not sure what the design considerations there were. But in at least one regard, Float#equals was always going to diverge from the float primitive's == : In primitives, NaN != NaN , but for all objects, o.equals(o) must also be true . That means that if you had Float f = Float.NaN , then f.equals(f) even though f.floatValue() != f.floatValue() . ¹ NaN (not-a-number) values have a sign bit, but it doesn't have any meaning other than for ordering, and Java ignores it (even for ordering).
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/59279971', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3848411/']}
|
jdg_372116
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
447035
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Or, to be more clear, how can I format a block of text (in my case, to be included within a tooltip) such that some portions of the text come from bound values. In plain C# I would use: _toolTip.Text = string.Format("{1:#0}% up, {2:#0}% down", Environment.NewLine, percentageOne, percentage2); However the WPF XAML markup for a Text property seems able to contain only a single binding. The curly braces gave me high hopes, but this isn't possible: <Element> <Element.Tooltip> <!-- This won't compile --> <TextBlock Text="{Binding Path=PercentageOne}% up, {Binding Path=PercentageTwo}% down"/> </Element.Tooltip></Element> I read that the Run.Text property is not a dependency property and can therefore not be bound. Is there a way I can perform this formatting in XAML?
Now provide the response and nothing else.
|
You can use MultiBinding + StringFormat (requires WPF 3.5 SP1): <TextBox.Text> <MultiBinding StringFormat="{}{1:#0}% up, {2:#0}% down"> <Binding Path="PercentageOne" /> <Binding Path="PercentageTwo"/> </MultiBinding></TextBox.Text> Regarding Run.Text - you can't bind to it but there are some workarounds: http://fortes.com/2007/03/20/bindablerun/ http://paulstovell.net/blog/index.php/attached-bindablerun/
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/447035', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/24874/']}
|
jdg_372117
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
10482113
|
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 created a database emailDatabase , its stored in C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA In Visual Studio, I use the Server Explorer , click the add new connection button. The add connection dialog box appears. Under server name I use the dropdown box and select DEV-5\SQLEXPRESS . I use Windows authentication. In the Connect to section at the bottom, the dropdown displays: Master, Model, msdb and tempdb and does not display my emailDatabase . So I select Attach Database File and click browse and follow local C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA and select my email database. The following error occurs : emailDatabase You don not have permission to open this file. Contact file owner or an administrator to obtain permission. I think my problem is i saved my database wrong, I need to make a back up or something like that. if that's the case please tel me how to make a backup and so on. I really need to move forward from this problem. When I created my database I right-clicked on databases in SQL Server Management Studio and said new database, then I added columns with a query. then file save all. How can I get a copy of my database file with all the permissions I need to use it in visual Studio??
Now provide the response and nothing else.
|
When you create a database on the server (using SQL Server Management Studio), you don't have to (and should not!) fiddle around with the database file(s) anymore - let the server handle that for you. Instead: do a Add Connection in Visual Studio and then specify the server instance ( DEV-5\SQLEXPRESS ) and the database name ( emailDatabase ) in your connection dialog. With this, you're connecting and using a SQL Server database the way it's intended to be used - on the SQL Server instance itself. This is much easier, and much less hassle, than having to struggle with "free-floating" .mdf files and attaching them to your solutions and stuff like that.... So here - fill in DEV-5\SQLEXPRESS into your "Server name" dropdown, and then use the "Select or enter database name" option and enter your database name (or pick it from the dropdown) - it should be there! DO NOT use the "Attach a database file" option - this is the free-floating .mdf "feature" which is rather clumsy and hard to use and error-prone - again: I recommend not using that...
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10482113', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1356321/']}
|
jdg_372118
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
488126
|
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've a multiplicative model for which $Y = X*Z$ , for which $Y$ and $Z$ is known. I want this model to be additive (therefore using logarithms) to figure out the variance of $X$ . I have $$ln(Y) = ln(X) + ln(Z)$$ and so $$VAR(ln(Y)) = VAR(ln(X)) + VAR(ln(Z))$$ and finally $$VAR(ln(X) = VAR(ln(Y)) - VAR(ln(Z))$$ . I'm not looking for a way to calculate $X$ , only the variance of $X$ . I now know $VAR(ln(X))$ , but is there I can "revert" this variance to get the variance for $X$ ?
Now provide the response and nothing else.
|
A further comment: I took a look at your data, and it's clear, again,that there is no evidence of systematic variance between the different channels.This is why the mixed model estimates the between-channel variance to be $0$ ,making the model singular. You can see this in the figure below, where the standard errors for almost every channel overlap... ...and can confirm it by ANOVA decomposition of a fixed-effects GLM, showing that there is no significant main effect of Channel (p = .986). m_fixed_effects = glm(cbind(n, total) ~ Pedra + factor(Channel), data=positive, family=binomial)car::Anova(m_fixed_effects)# Analysis of Deviance Table (Type II tests)# # Response: cbind(n, total)# LR Chisq Df Pr(>Chisq) # Pedra 4.9148 1 0.02663 *# factor(Channel) 1.3859 7 0.98600 # ---# Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 Code library(tidyverse)df = read.csv('/path/to/reaction.csv')head(df)# Channel Pedra reaction n# 1 1 No 0 6# 2 1 No 1 7# 3 1 Yes 0 3# 4 1 Yes 1 10# 5 2 No 0 7# 6 2 No 1 7df = df %>% group_by(Channel, Pedra) %>% mutate(total = sum(n), prop = n / total, se = sqrt((prop * (1-prop)) / n)) %>% ungroup()positive = filter(df, reaction==1)ggplot(positive, aes(Pedra, prop, group=Channel, color=factor(Channel))) + geom_path(position = position_dodge(width=.1)) + geom_point(position = position_dodge(width=.1)) + stat_summary(fun.data=mean_se, group=1, color='black', position = position_nudge(x=c(-.2, .2))) + geom_linerange(mapping=aes(ymin=prop-se, ymax=prop+se), position = position_dodge(width=.1)) + geom_hline(linetype='dashed', yintercept=.5) + coord_cartesian(ylim=c(0, 1)) + labs(color='Channel', y='Proportion positive reactions', caption='Error bars show SEM')m_fixed_effects = glm(cbind(n, total) ~ Pedra + factor(Channel), data=positive, family=binomial)car::Anova(m_fixed_effects)# Analysis of Deviance Table (Type II tests)# # Response: cbind(n, total)# LR Chisq Df Pr(>Chisq) # Pedra 4.9148 1 0.02663 *# factor(Channel) 1.3859 7 0.98600 # ---# Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
|
{}
|
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/488126', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/296780/']}
|
jdg_372119
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
623874
|
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a bunch of files and for each row there is a unique value I'm trying to obscure with a hash. However there are 3M rows across the files and a rough calculation of the time needed to complete the process is hilariously long at 32days. for y in files*; do cat $y | while read z; do KEY=$(echo $z | awk '{ print $1 }' | tr -d '"') HASH=$(echo $KEY | sha1sum | awk '{ print $1 }') sed -i -e "s/$KEY/$HASH/g" $y donedone To improve this processes speed I assume I'm going to have to introduce some concurrency. A hasty attempt based of https://unix.stackexchange.com/a/216475 led me to N=4(for y in gta*; do cat $y | while read z; do (i=i%N)); ((i++==0)); wait ((GTA=$(echo $z | awk '{ print $1 }' | tr -d '"') HASH=$(echo $GTA | sha1sum | awk '{ print $1 }') sed -i -e "s/$KEY/$HASH/g) & donedone) Which performs no better. Example input "2000000000" : ["200000", "2000000000"]"2000000001" : ["200000", "2000000001"] Example output "e8bb6adbb44a2f4c795da6986c8f008d05938fac" : ["200000", "e8bb6adbb44a2f4c795da6986c8f008d05938fac"]"aaac41fe0491d5855591b849453a58c206d424df" : ["200000", "aaac41fe0491d5855591b849453a58c206d424df"] Perhaps I should read the lines concurrently then perform the hash-replace on each line?
Now provide the response and nothing else.
|
FWIW I think this is the fastest way you could do it in a shell script: $ cat tst.sh#!/usr/bin/env bashfor file in "$@"; do while IFS='"' read -ra a; do sha=$(printf '%s' "${a[1]}" | sha1sum) sha="${sha% *}" printf '%s"%s"%s"%s"%s"%s"%s"\n' "${a[0]}" "$sha" "${a[2]}" "${a[3]}" "${a[4]}" "$sha" "${a[6]}" done < "$file"done $ ./tst.sh file $ cat file"e8bb6adbb44a2f4c795da6986c8f008d05938fac" : ["200000", "e8bb6adbb44a2f4c795da6986c8f008d05938fac"]""aaac41fe0491d5855591b849453a58c206d424df" : ["200000", "aaac41fe0491d5855591b849453a58c206d424df"]" but as I mentioned in the comments you'd be better of for speed of execution using a tool with sha1sum functionality built in, e.g. python.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/623874', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/106511/']}
|
jdg_372120
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18406991
|
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 modifying a graph built with ggplot by altering the data produced by ggplot_build (for a reason similar to Include space for missing factor level used in fill aesthetics in geom_boxplot ). As far as I understand the help I found on this topic, I should be able to save the result by applying ggplot_gtable and arrangeGrob before calling ggsave on the results ( Saving grid.arrange() plot to file ). However I obtain an error "plot should be a ggplot2 plot", also with this simple reproductible example: require('ggplot2')require('gridExtra')df <- data.frame(f1=factor(rbinom(100, 1, 0.45), label=c("m","w")), f2=factor(rbinom(100, 1, 0.45), label=c("young","old")), boxthis=rnorm(100))g <- ggplot(aes(y = boxthis, x = f2, fill = f1), data = df) + geom_boxplot()dd <- ggplot_build(g)# Printing the graph works:print(arrangeGrob(ggplot_gtable(dd)))# Saving the graph doesn't:ggsave('test.png',arrangeGrob(ggplot_gtable(dd))) Can anybody explain why this does not work ? Is there a way to use ggsave after modifying the data by using ggplot_build() ? (My version of the packages are gridExtra_0.9.1 and ggplot2_0.9.3.1)
Now provide the response and nothing else.
|
it does not work because ggsave wants an object of class ggplot , while you're passing a grob. arrangeGrob will sometimes trick ggsave in pretending inheritance from ggplot , but only when at least one of the grobs belongs to this class; here, however, you're only passing a gtable . Perhaps the easiest workaround is to clone ggsave and bypass the class check, ggsave <- ggplot2::ggsave; body(ggsave) <- body(ggplot2::ggsave)[-2] Edit: The dev version of ggplot2 no longer requires this hack*, as ggsave now works with any grob . *PS: this hack works no longer, as arrangeGrob now returns a gtable, and its print method does not draw on a device.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18406991', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2711569/']}
|
jdg_372121
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3026767
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
It's the special property that void* can also be assigned a pointer to a pointer and cast back and the original value is received. I read this line somewhere. Does it means void* and void** are same?What is the difference? Edit void* can hold any pointer. Then what's void** needed for?
Now provide the response and nothing else.
|
One points at a black hole. The other points at the thing pointing at the black hole. They're not really the same thing, but pointers can be converted to void * . You can convert int * to a void * because, well, it's a pointer. void ** is still a pointer (it just points to a pointer), and since it's a pointer, you can convert it to a void * . That make any sense? That said, I don't think I've ever had a use for a void ** , but if you needed an array of void * s, then the type would be void ** . (In C) void * is often used to hold a pointer to some user data - but you won't know ahead of time what type that data will be. If you had an array of those, then void ** . Since you also have this tagged as C++: The previous case doesn't really apply: you could use a std::vector<void *> . Really, void * might be questionable - an abstract base might fit your purposes better. void * is useful mostly in C.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3026767', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/179855/']}
|
jdg_372122
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
67006
|
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 $$\int_a^b f(x) \,dx > \int_a^b g(x) \,dx$$ and there is a function $h(x)$ that is strictly increasing with $x$, does that imply that$$\int_a^b h(f(x)) \,dx > \int_a^b h(g(x)) \,dx$$?
Now provide the response and nothing else.
|
No. Consider $a=0$, $b=2$,$$f(x) = \begin{cases}3 & x<1 \\ 0 & x \ge 1\end{cases}$$$$g(x) = 1$$$$h(x) = \sqrt{x}$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/67006', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/16069/']}
|
jdg_372123
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
69312640
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
ATTrackingManager.requestTrackingAuthorization stopped working on ios 15. Application rejected from Apple.
Now provide the response and nothing else.
|
According to the discussion in Apple Developer Forum, you need to add delay for about one second when calling requestTrackingAuthorization. https://developer.apple.com/forums/thread/690607 Example: DispatchQueue.main.asyncAfter(deadline: .now() + 1.0, execute: { ATTrackingManager.requestTrackingAuthorization(completionHandler: { status in // Tracking authorization completed. Start loading ads here. // loadAd() })}) P.S.Also if you have requesting push notification permission, firstly you need request push notification then request tracking authorization with a delay => private func requestPushNotificationPermission() { let center = UNUserNotificationCenter.current() UNUserNotificationCenter.current().delegate = self center.requestAuthorization(options: [.sound, .alert, .badge], completionHandler: { (granted, error) in if #available(iOS 14.0, *) { DispatchQueue.main.asyncAfter(deadline: .now() + 1.0, execute: { ATTrackingManager.requestTrackingAuthorization(completionHandler: { status in // Tracking authorization completed. Start loading ads here. // loadAd() }) }) }}) UIApplication.shared.registerForRemoteNotifications()}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/69312640', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6502248/']}
|
jdg_372124
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
10935117
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
For some reason order ID's (increment_id on sales_flat_order table) are not incrementing subsequently on my Magento 1.6.1. This is how it looks after a number of live orders placed: increment_id created_at updated_at100000001 2011-12-14 12:35:24 2011-12-14 12:35:25100000002 2011-12-14 13:02:39 2011-12-14 13:02:39100000003 2011-12-14 13:04:18 2011-12-14 13:04:18100000004 2012-02-01 16:54:58 2012-02-01 16:54:58100000005 2012-03-14 12:22:35 2012-03-14 12:22:35100000006 2012-03-20 13:10:48 2012-03-20 13:10:48100000011 2012-03-29 20:58:48 2012-03-29 20:58:48100000012 2012-03-29 21:06:43 2012-03-29 21:06:43100000013 2012-03-30 10:48:20 2012-03-30 10:48:21100000014 2012-03-30 13:05:40 2012-03-30 13:05:41100000015 2012-04-03 15:51:01 2012-04-03 15:51:02100000016 2012-04-19 15:00:49 2012-04-19 15:00:50100000017 2012-05-09 12:09:21 2012-05-09 12:09:22100000019 2012-05-24 05:35:35 2012-05-24 05:35:36100000020 2012-05-24 05:41:11 2012-05-24 05:41:12100000008 2012-05-24 05:48:52 2012-05-24 05:48:53 My question is why is Magento jumping increments sometimes? And worse yet, in my example order with increment 100000008 goes after 100000020. Does someone know why this is happening and if there's a way to fix it?
Now provide the response and nothing else.
|
This is normal, albeit understandably disconcerting. When Magento enters the checkout process it 'reserves' an increment_id and places it on the quote (cart) object. You can see the code that gets an increment id at: Mage_Eav_Model_Entity_Type::fetchNewIncrementId() The last used ID for each store is stored in eav_entity_store. If a customer abandons their cart (ie the quote object) before completing the checkout process, the reserved increment_id will never show up on an order. You can see this effect sometimes in the order numbers as they come in on a busy store - occassionally a really old order id comes through in the day's orders from a customer that is checking out an old cart. This behaviour exists to allow Magento to send payment gateways the final order id (increment_id), before the order is completed allowing the gateway to associate the order id with the order. If the customer abandons the payment process in the gateway, the order id is dead (or more correctly still attached to the quote). You can see this happening in the PayPal express module at: Mage_Paypal_Model_Express_Checkout::start() which calls Mage_Sales_Model_Quote::reserveOrderId() If you want to find your 'missing' increment_ids, take a look in sales_flat_quote under the field reserved_order_id. You should see them attached to unconverted quote objects (carts). This behaviour can create issues with some payment gateways; Moneris comes to mind. When you send Moneris' hosted paypage the same order id twice, it chokes and creates a cryptic error state for the customer. This condition occurs when the customer visits the hosted pay page, backs out and re-visits the page. Hence in some cases, it is necessary to re-generate the order id associated with the quote object programmatically.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10935117', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/717839/']}
|
jdg_372125
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1741972
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it possible to log to a single destination (i.e. using one FileHandler ) with multiple loggers (i.e. logging.getLogger("base.foo") and logging.getLogger("base.bar") ), and use different formatters for each of the loggers. To my understanding it's only possible to assign one formatter to each handle. Maybe it's possible to associate the formatter with a logger rather than the handler?
Now provide the response and nothing else.
|
It's easy to dispatch to different formatters based on record.name . Below is prove-of-concept sample code: import loggingclass DispatchingFormatter: def __init__(self, formatters, default_formatter): self._formatters = formatters self._default_formatter = default_formatter def format(self, record): formatter = self._formatters.get(record.name, self._default_formatter) return formatter.format(record)handler = logging.StreamHandler()handler.setFormatter(DispatchingFormatter({ 'base.foo': logging.Formatter('FOO: %(message)s'), 'base.bar': logging.Formatter('BAR: %(message)s'), }, logging.Formatter('%(message)s'),))logging.getLogger().addHandler(handler)logging.getLogger('base.foo').error('Log from foo')logging.getLogger('base.bar').error('Log from bar')logging.getLogger('base.baz').error('Log from baz') Another way is to open file manually and create two stream handlers from it with different formatters.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1741972', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/83996/']}
|
jdg_372126
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
53581787
|
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 base with 3 factors ( condition , measure and time ) and would like to plot them using the x-axis, the color/group and the linetype. As an exemple, my data looks like this: DT <- data.frame(condition = rep(c("control", "experimental"), each = 4), measure = rep(c("A", "A", "B", "B"), 2), time = rep(c("pre-test", "post-test"), 4), score = 1:8)> DT condition measure time score1 control A pre-test 12 control A post-test 23 control B pre-test 34 control B post-test 45 experimental A pre-test 56 experimental A post-test 67 experimental B pre-test 78 experimental B post-test 8 My goal is to draw a graph like this: I tried: ggplot(DT, aes(time, score, group = measure, color = measure, linetype = condition)) + geom_line() + geom_point() But it returns this error: Error: geom_path: If you are using dotted or dashed lines, colour, size and linetype must be constant over the line What am I missing?
Now provide the response and nothing else.
|
You want to use ggplot(DT, aes(time, score, group = interaction(measure, condition), color = measure, linetype = condition)) + geom_line() + geom_point() because the actual grouping is not only by measure but also by condition . When grouping by measure alone, I guess it's asking for kind of parallelograms rather than lines.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/53581787', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1612892/']}
|
jdg_372127
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1073744
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a bit trouble distinguishing the following concepts: probability measure probability function (with special cases probability mass function and probability density function ) probability distribution Are some of these interchangeable? Which of these are defined with respect to probability spaces and which with respect to random variables?
Now provide the response and nothing else.
|
The difference between the terms "probability measure" and "probability distribution" is in some ways more of a difference in connotation of the terms rather than a difference between the things that the terms refer to. It's more about the way the terms are used. A probability distribution or a probability measure is a function assigning probabilities to measurable subsets of some set. When the term "probability distribution" is used, the set is often $\mathbb R$ or $\mathbb R^n$ or $\{0,1,2,3,\ldots\}$ or some other very familiar set, and the actual values of members of that set are of interest. For example, one may speak of the temperature on December 15th in Chicago over the aeons, or the income of a randomly chosen member of the population, or the particular partition of the set of animals captured and tagged, where two animals are in the same part in the partition if they are of the same species. When the term "probability measure" is used, often nobody cares just what the set $\Omega$ is, to whose subsets probabilities are assigned, and nobody cares about the nature of the members or which member is randomly chosen on any particular occasion. But one may care about the values of some function $X$ whose domain is $\Omega$ , and about the resulting probability distribution of $X$ . "Probablity mass function", on the other hand, is precisely defined. A probability mass function $f$ assigns a probabilty to each subset containing just one point, of some specified set $S$ , and we always have $\sum_{s\in S} f(s)=1$ . The resulting probability distribution on $S$ is a discrete distribution. Discrete distributions are precisely those that can be defined in this way by a probability mass function. "Probability density function" is also precisely defined. A probability density function $f$ on a set $S$ is a function specifies probabilities assigned to measurable subsets $A$ of $S$ as follows: $$\Pr(A) = \int_A f\,d\mu$$ where $\mu$ is a "measure", a function assigning non-negative numbers to measurable subsets of $A$ in a way that is "additive" (i.e. $\mu\left(A_1\cup A_2\cup A_3\cup\cdots\right) = \mu(A_1)+\mu(A_2)+\mu(A_3)+\cdots$ if every two $A_i,A_j$ are mutually exclusive). The measure $\mu$ need not be a probability measure; for example, one could have $\mu(S)=\infty\ne 1$ . For example, the function $$f(x) = \begin{cases} e^{-x} & \text{if }x>0, \\ 0 & \text{if }x<0, \end{cases}$$ is a probability density on $\mathbb R$ , where the underlying measure is one for which the measure of every interval $(a,b)$ is its length $b-a$ .
|
{}
|
{'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/1073744', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/190908/']}
|
jdg_372128
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7935966
|
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 the following python code: def outer(): string = "" def inner(): string = "String was changed by a nested function!" inner() return string I want a call to outer() to return "String was changed by a nested function!", but I get "". I conclude that Python thinks that the line string = "string was changed by a nested function!" is a declaration of a new variable local to inner(). My question is: how do I tell Python that it should use the outer() string? I can't use the global keyword, because the string isn't global, it just lives in an outer scope. Ideas?
Now provide the response and nothing else.
|
In Python 3.x, you can use the nonlocal keyword: def outer(): string = "" def inner(): nonlocal string string = "String was changed by a nested function!" inner() return string In Python 2.x, you could use a list with a single element and overwrite that single element: def outer(): string = [""] def inner(): string[0] = "String was changed by a nested function!" inner() return string[0]
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/7935966', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/801901/']}
|
jdg_372129
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
16021991
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Set<String> keys = mappings.keySet();String[] keyArray = (String[]) keys.toArray();String hashmapDetails = "";for(int p=0; p < keyArray.length; p++){ String[] details = keyArray[p].split("/"); hashmapDetails += details[1]; hashmapDetails += mappings.get(keyArray[p]); if (p != keyArray.length -1){ hashmapDetails += ";"; }} Pardon my lack of understanding but I'm trying to explore the usage of hashmaps. I understand that the toArray() returns an Object[]. However, is it not possible to type cast it to a String[]? As you can see in the codes, later, I need to go through an array and do some splitting and other String manipulation. By doing this I got an error: java.lang.ClassCastException: java.lang.Object[] cannot be cast to java.lang.String[] Any guidance on how I should tackle this is greatly appreciated. Thanks!
Now provide the response and nothing else.
|
You can't simply cast an Object[] array to a String[] array. You should instead use the generic version of toArray , which should work better: String[] keyArray = keys.toArray(new String[keys.size()]); Also note that you could simply iterate over the entrySet (that will save all the get calls) and use a StringBuilder for better string concatenation efficiency: StringBuilder hashmapDetails = new StringBuilder();for(Map.Entry<String, String> e : mappings.entrySet()) { String[] details = e.getKey().split("/"); hashmapDetails += details[1]; hashmapDetails += e.getValue(); hashmapDetails += ";";}String result = hashmapDetails.substring(0, hashmapDetails.length() - 1);
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16021991', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1749354/']}
|
jdg_372130
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
36452468
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there a way to display all enums as their string value in swagger instead of their int value? I want to be able to submit POST actions and put enums according to their string value without having to look at the enum every time. I tried DescribeAllEnumsAsStrings but the server then receives strings instead of the enum value which is not what we're looking for. Has anyone solved this? Edit: public class Letter { [Required] public string Content {get; set;} [Required] [EnumDataType(typeof(Priority))] public Priority Priority {get; set;}}public class LettersController : ApiController{ [HttpPost] public IHttpActionResult SendLetter(Letter letter) { // Validation not passing when using DescribeEnumsAsStrings if (!ModelState.IsValid) return BadRequest("Not valid") .. } // In the documentation for this request I want to see the string values of the enum before submitting: Low, Medium, High. Instead of 0, 1, 2 [HttpGet] public IHttpActionResult GetByPriority (Priority priority) { }}public enum Priority{ Low, Medium, High}
Now provide the response and nothing else.
|
Enable globally From the docs : httpConfiguration .EnableSwagger(c => { c.SingleApiVersion("v1", "A title for your API"); c.DescribeAllEnumsAsStrings(); // this will do the trick }); Enum/string conversion on particular property Also, if you want this behavior only on a particular type and property, use the StringEnumConverter: public class Letter { [Required] public string Content {get; set;} [Required] [EnumDataType(typeof(Priority))] [JsonConverter(typeof(StringEnumConverter))] public Priority Priority {get; set;}} If you're using Newtonsoft and Swashbuckle v5.0.0 or higher You'll also need this package: Swashbuckle.AspNetCore.Newtonsoft And this in your startup: services.AddSwaggerGenNewtonsoftSupport(); // explicit opt-in - needs to be placed after AddSwaggerGen() There's docs here: https://github.com/domaindrivendev/Swashbuckle.AspNetCore#systemtextjson-stj-vs-newtonsoft
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/36452468', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
|
jdg_372131
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
37590774
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What I learned from Foregenix : The HTTP 404 Not Found Error means that the webpage you were trying to reach could not be found on the server. It is a Client-side Error which means that either the page has been removed or moved and the URL was not changed accordingly, or that you typed in the URL incorrectly But then I also do web app pentests with Python and I am wondering that if I only check for the String 404 on the page, it may not really be a 404 error.It can so happen that the page exists but the heading is 404 just to fool us. So how exactly do I find out?
Now provide the response and nothing else.
|
You can check the HTTP status code, and see if it is 404 or not. The status code is on the first line of the response: HTTP/1.1 404 Not Found If you are using HTTPlib you can just read the status property of the HTTPResponse object. However, it is the server that decides what HTTP status code to send. Just because 404 is defined to mean "page not found" does not mean the server can not lie to you. It is quite common to do things like this: Send 404 instead of 403, to hide the resource that requires authentication. Send 404 instead of 500, to hide the fact something is not working. Send 404 when your IP is blocked for some reason. Without access to the server, it is impossible to know what is really going on behind the curtains.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/37590774', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4546390/']}
|
jdg_372132
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
222107
|
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
I need some help in building a network between hundreds of computers spread across multiple buildings of my college. Yes, I'll be doing this as a part of my college project. Please see this image, it will give you enough idea of what I'm trying to achieve. All the computers in all buildings should be able to connect server. Once network is up, there will be a set of services over intranet and network use will be moderate. Well, say there will be an email server and a http server. My point is, I cannot afford much of performance loss. It feels easy to connect computers inside 1 building to each other, however, I'm clueless as to how to connect all of them to server. I mean, just 1 cable won't be enough to connect 1 building to server, right? How should I go with it ? I am not expecting detailed configuration. Just heads up will do.
Now provide the response and nothing else.
|
Hooo boy. Where to start... You probably want switches in each of the distant buildings, you don't want to have to run a new line from the central building every time you expand a different building. Then, you need to work with facilities and/or contractors to get cables strung between buildings. There's probably existing buried tunnels/pipes with other wires, I hope? At least simply for the phone system, electrical, etc? You should run the cables through there. Then you connect the uplinks of all the remote switches to you central server room. That's the abstract. You'll need to get into a lot of specifics. These days, GB and 10 GB ethernet is so cheap and commonplace, that might be good for the uplinks, as opposed to some type of fiber (SONET, FDDI - I don't even remember if those are the most common local campus links for between buildings.) But for redundancy, you'd want some sort of loop, so that every building has two paths to go through if one is cut. If done with ethernet, this usually implies implementing spanning-tree protocol. If this stuff is making your head spin, you need to figure out if you can realistically do a good job of this in the timeframe allotted. You may want to seek the guidance of a local professional if there's no one at the school to give you help; someone might want to donate (or offer at a reduced rate) their design services to the school. A beginner shouldn't be doing all of this, to my mind.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/222107', 'https://serverfault.com', 'https://serverfault.com/users/66430/']}
|
jdg_372133
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
293525
|
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 decided to write a singly-linked list, and had the plan going in to make the internal linked node structure immutable. I ran into a snag though. Say I have the following linked nodes (from previous add operations): 1 -> 2 -> 3 -> 4 and say I want to append a 5 . To do this, since node 4 is immutable, I need to create a new copy of 4 , but replace its next field with a new node containing a 5 . The problem is now, 3 is referencing the old 4 ; the one without the appended 5 . Now I need to copy 3 , and replace its next field to reference the 4 copy, but now 2 is referencing the old 3 ... Or in other words, to do an append, the entire list seems to need to be copied. My questions: Is my thinking correct? Is there any way to do an append without copying the entire structure? Apparently "Effective Java" contains the reccomendation: Classes should be immutable unless there's a very good reason to make them mutable... Is this a good case for mutability? I don't think this is a duplicate of the suggested answer since I'm not talking about the list itself; that obviously has to be mutable to conform to the interface (without doing something like keeping the new list internally and retrieving it via a getter. On second thought though, even that would require some mutation; it would just be kept to a minimum). I'm talking about whether or not the internals of the list must be immutable.
Now provide the response and nothing else.
|
With lists in functional languages, you nearly always work with a head and tail, the first element and the remainder of the list. Prepending is much more common because, as you surmised, appending requires copying the entire list (or other lazy data structures that don't precisely resemble a linked list). In imperative languages, appending is much more common, because it tends to feel more natural semantically, and you don't care about invalidating references to previous versions of the list. As an example of why prepending doesn't require copying the entire list, consider you have: 2 -> 3 -> 4 Prepending a 1 gives you: 1 -> 2 -> 3 -> 4 But note that it doesn't matter if someone else is still holding a reference to 2 as the head of their list, because the list is immutable and the links only go one way. There's no way to tell the 1 is even there if you only have a reference to 2 . Now, if you appended a 5 onto either list, you'd have to make a copy of the entire list, because otherwise it would appear on the other list as well.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://softwareengineering.stackexchange.com/questions/293525', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/139925/']}
|
jdg_372134
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
30520350
|
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 admission_table containing ADMIT , GRE , GPA and RANK . > head(admission_table) ADMIT GRE GPA RANK1 0 380 3.61 32 1 660 3.67 33 1 800 4.00 14 1 640 3.19 45 0 520 2.93 46 1 760 3.00 2 I'm trying to convert the summary of this table into data.frame . I want to have ADMIT , GRE , GPA and RANK as my column headers. > summary(admission_table) ADMIT GRE GPA RANK Min. :0.0000 Min. :220.0 Min. :2.260 Min. :1.000 1st Qu.:0.0000 1st Qu.:520.0 1st Qu.:3.130 1st Qu.:2.000 Median :0.0000 Median :580.0 Median :3.395 Median :2.000 Mean :0.3175 Mean :587.7 Mean :3.390 Mean :2.485 3rd Qu.:1.0000 3rd Qu.:660.0 3rd Qu.:3.670 3rd Qu.:3.000 Max. :1.0000 Max. :800.0 Max. :4.000 Max. :4.000 > as.data.frame(summary(admission_table)) Var1 Var2 Freq1 ADMIT Min. :0.0000 2 ADMIT 1st Qu.:0.0000 3 ADMIT Median :0.0000 4 ADMIT Mean :0.3175 5 ADMIT 3rd Qu.:1.0000 6 ADMIT Max. :1.0000 7 GRE Min. :220.0 8 GRE 1st Qu.:520.0 9 GRE Median :580.0 10 GRE Mean :587.7 11 GRE 3rd Qu.:660.0 12 GRE Max. :800.0 13 GPA Min. :2.260 14 GPA 1st Qu.:3.130 15 GPA Median :3.395 16 GPA Mean :3.390 17 GPA 3rd Qu.:3.670 18 GPA Max. :4.000 19 RANK Min. :1.000 20 RANK 1st Qu.:2.000 21 RANK Median :2.000 22 RANK Mean :2.485 23 RANK 3rd Qu.:3.000 24 RANK Max. :4.000 As I'm trying to convert into data.frame , this is the only result I get. I want the data frame have the exact output just like the summary table because after that I want to insert that into Oracle database using this line of code: dbWriteTable(connection,name="SUM_ADMISSION_TABLE",value=as.data.frame(summary(admission_table)),row.names = FALSE, overwrite = TRUE ,append = FALSE) Is the any way to do so?
Now provide the response and nothing else.
|
You can consider unclass , I suppose: data.frame(unclass(summary(mydf)), check.names = FALSE, stringsAsFactors = FALSE)# ADMIT GRE GPA RANK# 1 Min. :0.0000 Min. :380.0 Min. :2.930 Min. :1.000 # 2 1st Qu.:0.2500 1st Qu.:550.0 1st Qu.:3.047 1st Qu.:2.250 # 3 Median :1.0000 Median :650.0 Median :3.400 Median :3.000 # 4 Mean :0.6667 Mean :626.7 Mean :3.400 Mean :2.833 # 5 3rd Qu.:1.0000 3rd Qu.:735.0 3rd Qu.:3.655 3rd Qu.:3.750 # 6 Max. :1.0000 Max. :800.0 Max. :4.000 Max. :4.000 str(.Last.value)# 'data.frame': 6 obs. of 4 variables:# $ ADMIT: chr "Min. :0.0000 " "1st Qu.:0.2500 " "Median :1.0000 " "Mean :0.6667 " ...# $ GRE : chr "Min. :380.0 " "1st Qu.:550.0 " "Median :650.0 " "Mean :626.7 " ...# $ GPA : chr "Min. :2.930 " "1st Qu.:3.047 " "Median :3.400 " "Mean :3.400 " ...# $ RANK: chr "Min. :1.000 " "1st Qu.:2.250 " "Median :3.000 " "Mean :2.833 " ... Note that there is a lot of excessive whitespace there, in both the names and the values. However, it might be sufficient to do something like: do.call(cbind, lapply(mydf, summary))# ADMIT GRE GPA RANK# Min. 0.0000 380.0 2.930 1.000# 1st Qu. 0.2500 550.0 3.048 2.250# Median 1.0000 650.0 3.400 3.000# Mean 0.6667 626.7 3.400 2.833# 3rd Qu. 1.0000 735.0 3.655 3.750# Max. 1.0000 800.0 4.000 4.000
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/30520350', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4935351/']}
|
jdg_372135
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
28004358
|
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 say you have a class that takes many (keyword) arguments, most of which are meant to be stored as instance variables: class ManyInitVariables(): def __init__(a=0, b=2, c=1, d=0, e=-1, ... , x=100, y=0, z=9): How would you initialize them in __init__ ? You could do something like this: class ManyInitVariables(): def __init__(a=0, b=2, c=1, d=0, e=-1, ... , x=100, y=0, z=9): self.a = a self.b = b self.c = c ... self.z = z ...but it would take a lot of typing! How could I get __init__ to automatically some of the arguments it takes, noting that other arguments may not need to be assigned as instance variables?
Now provide the response and nothing else.
|
I'm sure there are many other similar solutions out there on the web for this very common issue, but this is one, for example: import functoolsimport inspectdef absorb_args(f): args, _, _, defs = inspect.getargspec(f) args = args[1:] # ignore the leading `self` @functools.wraps(f) def do_absorb(self, *a, **k): ndefs = len(args) - len(a) + 2 for name, value in zip(args, a + defs[-ndefs:]): setattr(self, name, value) for name, value in k.items(): setattr(self, name, value) return f(self, *a, **k) return do_absorb Added: I've been asked to explain this further, but, there's a lot going on here if you're not skilled at Python!-). functools.wraps is a decorator to help make better decorators, see https://docs.python.org/2/library/functools.html#functools.wraps -- not directly germane to the question but useful to support interactive help and tools based on functions' docstrings. Get into the habit of always using it when writing a function decorator that (the most common case) wraps the decorated function, and you won't regret it. The inspect module is the only right way to do introspection in modern Python. inspect.getargspec in particular gives you information on what arguments a function accepts, and what the default values for them are, if any (the two bits of info I'm ignoring, by assigning them to _ , are about *a and **k special args, which this decorator doesn't support). See https://docs.python.org/2/library/inspect.html?highlight=getargspec#inspect.getargspec for more. self , by convention, is always the first arg to a method (and this decorator is meant for methods only:-). So, the first for loop deals with positional args (whether explicitly given in the call or defaulting to default values); then, the second for loop deals with named args (that one, I hope, is simpler to grasp:-). setattr of course is the precious built-in function which sets an attribute with a variable name, https://docs.python.org/2/library/functions.html?highlight=setattr#setattr for more. Incidentally, if you only care to use this in __init__ (as you see in the example below, absorb_attrs per se has no such constraint), then write a class decorator which singles out the class's __init__ for this treatment, and apply that class decorator to the class itself. Also, if your class's __init__ has no work left to do once args are "absorbed" in this way, you must still define the (decorated) __init__ , but its body can be limited to a docstring explaining the arguments (I personally prefer to always also have a pass statement in such cases, but that's a personal style issue). And now, back to the original answer, with an example...!-) And then, e.g, something like class Struggle(object): @absorb_args def __init__(self, a, b, c, bab='bo', bip='bop'): self.d = a + b @absorb_args def setit(self, x, y, z, u=23, w=45): self.t = x + y def __str__(self): attrs = sorted(self.__dict__) r = ['%s: %s' % (a, getattr(self, a)) for a in attrs] return ', '.join(r)s = Struggle('fee', 'fie', 'foo', bip='beeeeeep')s.setit(1, 2, 3, w=99)print(s) would print a: fee, b: fie, bab: bo, bip: beeeeeep, c: foo, d: feefie, t: 3, u: 23, w: 99, x: 1, y: 2, z: 3 as desired. My only excuse for "reinventing the wheel" this way (rather than scouring the web for a solution) is that the other evening my wife and co-author Anna (only ever woman winner of the Frank Willison Memorial Award for contribution to the Python community, BTW:-) asked me about it (we are, slowly alas!, writing the 3rd edition of "Python in a Nutshell") -- it took me 10 minutes to code this (sorry, no tests yet:-) while in the same 10 minutes she (despite being a very skilled web-searcher:-) could not locate an existing solution on the web. And, this way I need not worry about copyright issues if I want to post it here, include it in the next Nutshell, present about it at OSCON or Pycon, and so forth...:-)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28004358', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3486684/']}
|
jdg_372136
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
865403
|
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm just preparing a VM machine (running onver Proxmox) to run a postgresql 9.6 over a Ubuntu 16.04 LTS. This postgres would be used to handle Jira/FisheEye/Confluence databases for a small company. Usually we are a few user at same time, so we not need to tune it for extreme performance/scalability. Well, the case is that we have using BTRFS on the servers as help us to handle the problem of adding extra space to a VM when is necessary, plus we enable lzo compression. Also, we use btrok to handle backups of BTRFS subvolumes to another machine. I have doubts if could be a good idea use BTRFS to handle the postgresql DB files as we would be very helpful on the case that we need to expand the virtual hard disk space, but I read about postgresql bad performance over BTRFS (on special if the datacow is not disabled. Anyone have experience with this situation ?
Now provide the response and nothing else.
|
The general answer : bad idea. You can read a few details about it here . Long story short is that the COW mechanism of BTRFS will cause performance inconsistencies for normal OLTP workload The better answer : in certain cases I would use it. Why and how: You can only notice real performance differences if you really get to stress the filesystem and run really heavy work for the FS in that DB. Unlikely to happen for JIRA and Confluence with normal workloads (assuming you don't work in a company with thousands of developers etc), especially if you tune & configure their caching properly. Also, considering you want to enable compression, it doesn't sound like IO performance is your main concern :). Considering the previous bullet, manageability, good integration into your current tools and environment, and existing knowledge about the technologies you are using should definitely trump the fact that, in much higher workloads, other filesystems provide better performance. I would also consider tuning everything properly to compensate: run on flash memory, do proper data alignment (physical <-> controllers <-> partitioning <-> FS <-> DB), do proper FS (BTRFS requires more maintenance than your throw-in-and-forget-about-it ext4), and DB maintenance and tuning. I hope it helps. Note : A user suggested that COW can be disabled for BTRFS for specific volumes/folders and I disregard the fact. Indeed, it can be disabled, but if you do that, why would you still use BTRFS? - Because you can still use COW on rest of the filesystem and all the other cool features (like snapshots and stuff) without performance hit for the virtualbox and postgres? Sure, it doesn't make sense for pure DB server to use BTRFS and disable COW. But for general purpose machine/server? It allows you to use all the cool features (RAID1, ...) without performance hit. So win-win in my eyes.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/865403', 'https://serverfault.com', 'https://serverfault.com/users/236507/']}
|
jdg_372137
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1756487
|
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 believe Jimmy Nillson said he generally made his webservices singletons. Is this the preferred method, and with WCF? Other than making the service methods static, is there something else to be done?
Now provide the response and nothing else.
|
good responses, but I think there is a problem in the original question. "Typical use" of a technology is a poorly formed question. No one has a "typical" scenario, and you should review the requirements of your particular problem before deciding on an implementation or approach. Your requirements should inform your solution. For instance, Singletons [ie the Singleton pattern] is just another tool in our box, and like any tool, there are cases where it works, and others it does not. Specifically, if you need to centralize business logic [more applicable in a standalone application than a remote WCF service], or share memory or a resource, a Singleton works well. Of course, if you are sharing business logic, state is maintained in the call stack, and multi threading is moot. If sharing memory between consumer calls, then multi threading is an issue. As regards WCF, there are two modes [actually three, but the third is a special case of the first] of multi-threading behaviour you can specify, // we are specifying that this service implementation is single-threaded// and WCF should permit *at most* one call at a time. Any requests made// simultaneously/concurrently are queued.[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Single)]public class SingleThreadedNonThreadSafeService : IService { ... } and // we are specifying that this service implementation is multi-threaded// and [hopefully!] thread-safe. WCF should permit any number of threads,// or any number of simultaneous concurrent calls.[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple)]public class MultiThreadedThreadSafeService : IService { ... } The Xml comments for ConcurrencyMode basically say the same thing as above. If you DO NOT need to share business logic or memory between consumers, then DO NOT use a Singleton, the "model" DOES NOT fit the problem. It's like forcing a glass slipper on a step-sister's foot! And no one should ever have to see that. Conversely, if no state is shared between calls, host an instance per-call\session.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1756487', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/98728/']}
|
jdg_372138
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17217965
|
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 implemented this code: class A { //some code}class B extends A { // some code}class C { public static void main(String []args) { B b1 = (B) new A(); A a1 = (B) new A(); }} Both of these lines, when compiled separately, compile fine,but give runtime errorwith java.lang.ClassException: A cannot be cast into B . Why they compile well, but give a runtime error?
Now provide the response and nothing else.
|
Variables of type A can store references to objects of type A or its subtypes like in your case class B . So it is possible to have code like: A a = new B(); Variable a is of type A so it have only access to API of that class, it can't access methods added in class B which object it refers to. But sometimes we want to be able to access those methods so it should be possible to somehow store reference from a in some variable of more accurate type (here B ) via which we would be able to access those additional methods from class B. BUT HOW CAN WE DO THAT? Lets try to achieve it this way: B b = a;//WRONG!!! "Type mismatch" error Such code gives compile time Type mismatch error. It happens to save us from situation like this: class B1 extends A class B2 extends A and we have A a = new B1(); . Now lets try to assign B1 b = a; . Remember that compiler doesn't know what actually is held under variable a so it needs to generate code which will be safe for all possible values. If compiler wouldn't complain about B1 b = a; it should also allow to compile B2 b = a; . So just to be safe it doesn't let us do it. So what should we do to assign reference from a to B1 ? We need to explicitly tell compiler that we are aware of potential type mismatch issue here, but we are sure that reference held in a can be safely assigned in variable of type B . We do so by casting value from a to type B via (B)a . B b = (B)a; But lets go back to example from your question B b1 = (B) new A();A a1 = (B) new A(); new operator returns reference of the same type as created object, so new A() returns reference of the type A so B b1 = (B) new A(); can be seen as A tmp = new A();B b1 = (B) tmp; Problem here is that you can't store reference to object of superclass in variable of its derived type . Why such limitation exist? Lets say that derived class adds some new methods that supertype doesn't have like class A { // some code}class B extends A { private int i; public void setI(int i){ this.i=i; }} If this would be allowed B b = (B)new A(); you could later end up with invoking b.setI(42); . But will it be correct? No because instance of class A doesn't have method setI nor field i which that method uses. So to prevent such situation (B)new A(); at runtime throws java.lang.ClassCastException .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17217965', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2459789/']}
|
jdg_372139
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
47691
|
Below is a question asked on the forum skeptics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Whenever the cartoon sailor is on the verge of a fight, he squeezes open a can of spinach, pours the greens down his throat, and uses his muscles to pummel his opponent. Some sources claim that this positive depiction of spinach as a source of superpowers was directly sponsored by the U.S. government during the 1930's depression. In the 1930s, America was suffering through the Great Depression, and the government was desperately looking for ways to promote iron-rich spinach as a meat substitute. To help spread the word, they hired one of America’s favorite cartoons characters, Popeye the Sailor Man ... This fact is often mentioned whenever there is a debate over the supposedly miscalculated iron contents of spinach. Has the U.S. government had any direct influence over Popeye's predilection for spinach?
Now provide the response and nothing else.
|
No. The 'eat your vegs' campaign as an established social norm is older, started with World War One, not during the Depression. Further, spinach is no meat substitute, whether you look for any iron or protein. Whether 'the government' provided some funds as well to this is possible, but for example the "Commonwealth Fund is a private U.S. foundation" . Indirectly, this campaign against malnutrition also involved many politicians and a few agencies, like the USDA and US Children's Bureau. But such early efforts meant that there was no need to directly influence a cartoon, which merely drew upon existing stereotypes. That an already hugely popular comic would need such an 'incentive' seems highly questionable. What Popeye allegedly achieved was indeed a certain demand from children for spinach, primarily fresh, but also the canned and thus unsavory Popeye form, protecting American farmers somewhat from the effects of depression. But by that time consumption of greens in general went up steadily to an all-time high in 1945. Despite the processing – not least into cans – destroying a good part of the then en vogue vitamins, which were sometimes re-introduced as 'fortifications' or then sold as popular pills. Spinach sales went up, and so did other leafy vegetables and foods independent of season or region in general. — Harvey Levenstein: "Paradox of Plenty. A Social History of Eating in Modern America" , Oxford University Press: Oxford, New York, 1993. / Harvey Levenstein: "Fear of Food. A History of Why We Worry about What We Eat" , University of Chicago Press: Chicago and London, 2012. That Popeye was then used later as a role-model for to be known as entertainment-education: the process of purposively designing and implementing a mediating communication form with the potential of entertaining and educating people, in order to enhance and facilitate different stages of pro-social (behaviour) change” (Bouman, 1999: 25). — Thomas Tufte: "Entertainment-education in development communication. Between marketing behaviours and empowering people", in: "Media and Glocal Change: Rethinking Communication for Development", CLACSO, Consejo Latinoamericano de Ciencias Sociales, Buenos Aires, 2005 ( PDF ) does not mean that he was designed as one in the first place. Hamblin was wrong. In reality, Popeye’s creator EC Segar never once had his superhero eat spinach for iron. In 1932, in the only cartoon by Segar where Popeye explains exactly why he eats the stuff, the cartoon sailor with the bulging forearms claims in in his garbled English: Spinach is full of Vitamin A. An'tha's what makes hoomans strong and helty. In fact, spinach contains beta-carotene, which is converted to vitamin A in the human body. And Popeye is as right today with his dietary advice as he was in the last century, eating spinach is a good way to get Vitamin A. The scandal of the Spinach Supermyth is not the decimal error myth started by Bender and spread by Hamblin. Rather, it is that people continue to make poor dietary choices based on the belief that spinach is a good source of iron. If only we could discover what the interactive ingredients and contexts are for the enduring success of the Spinach, Popeye and Iron Decimal Point Error Myth, we could reverse engineer the myth and seek to apply the lessons learned from that with an aim to entrench veracious knowledge about nutrition and other information. — Mike Sutton (1): "How the spinach, Popeye and iron decimal point error myth was finally bust", HealthWatch Newsletter 2016;101:7 ( PDF ) For an even more entertaining version of the above, and a proper SkepticsSE recommended reading on proper research and referencing of facts and findings: At least since 1981, literally hundreds of expert scholars in various diverse fields have published materials that treat the SPIDES as unquestionable and yet have apparently not fact checked the actual origin of the story, because they provide no references to support it. — Mike Sutton (2): "Spinach, Iron nd Popeye: Ironic lessons from biochemistry and history on the importance of healthy eating, healthy scepticism and adequate citation", Internet Journal of Criminology , 2010. ( PDF ) The 'wrong being Hamblin' responds to the iron myth himself here . And for the timeline: Popeye ate spinach because the association of spinach with strength was a product of the first national nutrition crisis in the United States: the 1920s fight against child malnutrition. Educators and public health experts sponsored by the Com- monwealth Fund modeled their efforts on propaganda campaigns aimed at instilling nutritional norms by convincing children that everyone was eating spinach, drinking milk, and brushing their teeth. Indeed one of the lasting effects of this nutrition crisis was the construction of social norms regarding health and nutrition embodied in popular admonitions such as “Eat your vegetables” or “Don’t drink coffee; it will stunt your growth.” From his first films in 1933, Popeye the Sailor relied on spinach to allow him to settle scores (Grandinetti 2004). Indeed, for decades, the feisty sailor’s reliance upon canned spinach was credited with increasing its consumption by a third during the Great Depression, making it at the time the third favorite food among children, after turkey and ice cream (Oxford Encyclopedia 2004). Popeye’s producers at Fleischer Studios did not invent the association between spinach and strength; they exploited a social norm instilled in the course of the malnutrition crisis. Programs such as the Commonwealth Fund’s had succeeded in changing social norms regarding nutrition. By the time that the first celluloid representation of Popeye would reach for his trusty spinach in the 1930s, the cartoonists could draw upon a shared understanding of nutrition and vitamins among American children. — Laura Lovett: "The Popeye Principle: Selling Child Health in the First Nutrition Crisis", Journal of Health Politics, Policy and Law, Vol. 30, No. 5, October 2005. ( PDF ) Therefore: The fact that spinach consumption was on a steep upward trend between 1915 and 1928 makes all the more pertinent my Question 4 regarding the need for evidence that Popeye alone was responsible for a 33 percent increase in spinach consumption; particularly since Popeye never ate spinach until June of 1931 (See: Segar 2007 p 40). Was canned spinach perhaps promoted for its iron content at any time before or after Popeye started advocating it? Incidentally, in the earlier newsprint cartoons, Popeye displays superhuman characteristics without recourse to any nutritional assistance. Popeye survives several bullet wounds on May 16th 1929 by stroking the three hairs on the head of Bernice the good luck whiffle hen. Later, in October 1930, Popeye relies solely upon a meal of beef to overcome mere bedridden weakness from a total of 25 bullet wounds. It was around this time, though a little earlier, on July 22nd 1929, that spinach first makes an entry into the Popeye comic strip, not as a foodstuff but as Miss Spinach, the landlady of the cad Mr Herringbone. All of these minor historical details aside, after that beef meal in 1930, Segar settled on spinach for Popeye in 1931 and his comic creation remained faithful to eating and promoting it thereafter. The fact that Popeye was already doing his tough guy stuff well before he became a spinach user suggests that Segar may well have later made a decision to employ his creative work to support programmes promoting spinach consumption during the US nutritional crisis. I am not sure, therefore, how exactly it is possible to isolate the influence of Segar’s Popeye from that of wider nutrition programmes on spinach consumption. (Sutton-2) But a caveat is still needed. The above is by no means the counter fact to provide a narrative that attempts to show a more a less uniform campaign for greens in the US at the time. The field of nutrition was and is always full of contradicting information, and always full of extremists' advice and proscriptive content informed by ideology. Well into the age of Popeye beef and milk were primary targets to promote, with often questionable logic on 'protein' and then 'vitamin A' (yes, just like in spinach, but the more vitamins were discovered the more any one food could advertise that it had 'it/them'), and sometimes with a good measure of added racism mixed in: Therefore, the industry’s economic interests played into the racial rhetoric of the day, which portrayed Asians as effeminate and enfeebled and the Chinese “leaf diet” as a cause of degeneracy. Gastropolitical racial exclusions and the politics of health and nutrition were closely linked in the congruence of the ideal American body politic and the ideal American body. It would be many decades before nutritionists began to publicize the benefits of leafy greens such as spinach, which even then could be touted only because a cartoon sailor, Popeye, ate it in a very safe, very American form: boiled and from a tin can. — E. Melanie du Puis: "Angels and Vegetables A Brief History of Food Advice in America", Gastronomica: The Journal of Food and Culture, vol.7, no.2, pp.34–44, 2007. ( PDF )
|
{}
|
{'log_upvote_score': 5, 'links': ['https://skeptics.stackexchange.com/questions/47691', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/17160/']}
|
jdg_372140
|
Subsets and Splits
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves samples with 'mathoverflow.net' in the prompt, providing a basic subset for inspection but with limited analytical value.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves 10 samples where the prompt mentions Mathematica Stack Exchange, offering basic filtering to locate specific content.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves a limited number of rows where the prompt contains a specific URL, providing basic filtering that offers minimal insight into the broader dataset patterns.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves 10 samples from the dataset where the prompt contains 'dsp.stackexchange.com', offering a basic filtering of data points related to that specific domain.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves a sample of rows where the prompt contains 'cs.stackexchange.com', providing a basic filter without extensive insight.
Electronics Q&A Subset
Retrieves a limited number of samples that contain a specific URL, providing only raw data filtered by that URL.
StackExchange Stats Questions
Retrieves 100 entries containing 'stats.stackexchange.com' in the prompt, which is useful for finding specific content but lacks broader analytical value.
Math StackExchange Questions
Retrieves 100 records from the train dataset where the prompt contains 'math.stackexchange.com', providing a basic filtered overview of specific entries.
Physics SE Questions
Retrieves 100 samples containing the word 'physics.stackexchange.com' in the prompt, offering basic filtering without deep analysis.