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
|
31697426
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
My iOS app is in Arabic (right-to-left) language only. Prior to iOS 9 the views layout and view animations were all by default left-to-right. So, I had customised the complete app and had reversed the default behaviour e.g. back button in navigation bar was set to be on the right instead of default left. But now when the app is compiled using latest SDK (Xcode 7 beta 4), everything is the opposite of what I need. Is there any simple way to force the app to show views and behave like iOS 8 and 7? I searched and found a solution but it involves changing the constraints(Uncheck the "Respect language direction") for all views. But this is not a feasible solution in large projects. This is a screenshot after compiling with Xcode 7 beta 4. and this is a screenshot when compiled with Xcode 6.
Now provide the response and nothing else.
|
Edit: The following code may cause unexpected behavior as @wakachamo pointed out. So, please watch out for issues e.g. Interactive pop gesture doesn't work, alertviews don't show, etc. Its better to follow the instruction provided by @wakachamo if this doesn't work for you Add this to app delegate didFinishLaunchingWithOptions method. [[UIView appearance] setSemanticContentAttribute:UISemanticContentAttributeForceLeftToRight]; Also add guard to support earlier version so that the property doesn't cause any crash. if([[[UIView alloc] init] respondsToSelector:@selector(setSemanticContentAttribute:)]) { [[UIView appearance] setSemanticContentAttribute:UISemanticContentAttributeForceLeftToRight]; } [[UIView alloc] init] instead of [UIView appearance] because respondsToSelector is not currently working with [UIView appearance] for setSemanticContentAttribute. You can also add iOS 9 Check #define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"9.0")) { [[UIView appearance] setSemanticContentAttribute:UISemanticContentAttributeForceLeftToRight]; }
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31697426', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1478181/']}
|
jdg_373741
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
439223
|
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've been reading about "dirty electricity" lately and while I know there's much controversy whether it causes adverse health effects this question is not about that subject. I'm simply trying to understand the facts and physics regarding "dirty electricity". According to GreenWave Filters (which produce and sell filters to "remove" dirty electricity): Dirty electricity is erratic spikes/surges of energy traveling along power lines and wiring where only standard 60Hz AC electricity should be. It is created by electronics, energy-efficient lights, and many other devices, as they manipulate electrical current to operate. Dirty electricity can circulate throughout a building and to other buildings, radiating potentially harmful EMFs as it goes. 1) What exactly is "dirty electricity"? Based on the above text, I understand that certain devices may draw electricity in aberrant ways causing it to spike/surge. What do we mean by electricity "surging"? 2) Do devices that generate "dirty electricity" contaminate all of the wiring in the wall? Or is it just around the outlet they draw power from? Or perhaps just around the device itself? If it does contaminate everything, how does the electricity from the device go back and contaminate the wiring in the whole house? 3) Most importantly, does this "dirty electricity" somehow radiate outside the walls (like WiFi) or is it something that just effects the flow of electricity in the wires? If it does radiate, does it radiate in a single frequency or multiple frequencies? Finally, does the amount of "radiation" depend on the amount of energy drawn by the device? Is there a way to measure it? I understand it may seem like I'm asking several unrelated questions but I think all of my questions stem from a lack of understanding of the simple physics of dirty electricity. I think that if I understood exactly what dirty electricity is, all of my questions would be answered. This is why I'm asking it as one question. P.S I realize there are other threads on stackexchange that address some of the health concerns related to "dirty electricity". Once again, my question is not related to health. I'm just trying to understand the physics of how it all works - what creates it, where does it exists etc. Also, this question seems to address how dirty electricity effects electronics plugged into the wall but of course we are not plugging people into the outlet. So I'm trying to understand the physics of how it interacts with humans.
Now provide the response and nothing else.
|
What exactly is "dirty electricity"? This term isn't a technical one. We might say a power line is dirty if its voltage doesn't vary according to the 50 or 60 Hz sinusoidal waveform we normally expect. I understand that certain devices may draw electricity in aberrant ways causing it to spike/surge. What do we mean by electricity "surging"? It's normal (not aberrant) for some types of loads to draw current in frequent short bursts. If the device is not designed correctly, this current might need to travel along the mains wiring to reach the device. But any device you buy from a reputable seller in a first world country should be tested for conducted emissions , which will limit the amount of quickly changing currents it can draw from the mains. Even if the device requires quickly changing currents internally, these can be delivered from capacitors inside the device rather than from the mains, if the device is well-designed. What do we mean by electricity "surging"? A surge is a relatively long-lasting increase in voltage on the mains, compared to a "spike". A "spike" might last a few milliseconds. A "surge" might last for 100's or milliseconds or a few seconds. Do devices that generate "dirty electricity" contaminate all of the wiring in the wall? As mentioned above, well-designed devices will not. Also, even if they do, there will be no permanent "contaimination" of the wiring in the wall. Most importantly, does this "dirty electricity" somehow radiate outside the walls (like WiFi) or is it something that just effects the flow of electricity in the wires? Rapidly changing voltages or currents can cause radiation in the form of radio waves.Exactly how much they radiate depends on the frequency content of the voltage or current waves, the exact geometry of the wires, the presence of nearby conductive structures, etc., so it is not easily predictable. If it does radiate, does it radiate in a single frequency or multiple frequencies? In whatever frequencies the voltage/current signals contain. Finally, does the amount of "radiation" depend on the amount of energy drawn by the device? Not in any predictable way. Is there a way to measure it? You could use an antenna and spectrum analyzer to measure whatever radio signals are present in a certain area.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/439223', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/222315/']}
|
jdg_373742
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
238172
|
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:
fact-1. Electron 's (or any-other particles) magnetic behavior depends upon mass, charge and spin . fact-2. All electrons are not the same. Though all electron have the same mass and charge; an electron can have any 1 of the 2 possible "Spin"... (+1/2) and (-1/2) (though later-on the electron can flip to opposite spinned state). fact-3. Moving electrons, in CRT TV, deflected using Magnetic Coils. Now , my question is, does all the electrons coming out from the cathode in a CRT TV, deflected irrespective of spin ( i.e. deflection in CRT does not depends on spin )? or some-how the cathode release all electrons of same spin ? or indeed depends upon spin ?
Now provide the response and nothing else.
|
So there are aspects of your question that are wrong, let's first get that out of the way. Your "fact 2": Wrong. All electrons are the same. A more correct statement is that they are indistinguishable from one another. In fact it is this example behaviour that allow fermi statistics to arise and thus gives us a model that is very powerful and accurate in predicting behaviour of the ensemble of particles. In a Quantum system the various states that these fermions can take on are determined by the system, but you can not say which electron is actually in a given state. Another assumption you are making. You are conflating quantum effects to macroscopic effects. In a CRT you're not going to see any quantum effects. The stream of electrons looks like a current and such currents respond of Magnetic fields. Spin effects do take place, but it is such a small effect that other effects are much much more dominant. For example the natural repulsion electrons have for each other is very dominant in determining focus size.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/238172', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/107801/']}
|
jdg_373743
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
172936
|
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 $\alpha$ be irrational and $T: S^1 \rightarrow S^1$ be the rotation by $\alpha$. I'm interested in what type of Central Limit Theorem (if any) can hold for sums $Y_n = \frac{1}{\sqrt{n}}\sum_{k=1}^{n} f(T^k x)$. I've done some googling and found statements like "generic smooth functions $f$ do not obey a CLT for irrational rotation", but was unable to find a definitive cohesive reference. The specific example of sums I'm interested in are of the form $\approx \sum_{k}\log \left\vert \frac{f(T^{2k}x)}{f(T^{2k+1}x)}\right\vert$ for some smooth $f$.
Now provide the response and nothing else.
|
The result depends on the approximation properties of $\alpha$. Of course one has to assume $\int_{S^1} f(z)dz=0$. A rotation by $\alpha$ has the effect that the $k$-th Fourier coefficient of $f$ is multiplied by $\exp(2\pi i \cdot k \alpha)$. Hence, the $k$-th Fourier coefficient (for $k \neq 0$) of $T_n(f)$ is just$$ \frac1{\sqrt{n}} \sum_{l=1}^n \exp(2\pi i \cdot k l \cdot\alpha) \cdot \hat f(k) =\frac1{\sqrt{n}} \cdot \exp(2\pi i \cdot k \cdot\alpha) \cdot \frac{1 - \exp(2\pi i \cdot k n \cdot\alpha)}{1 - \exp(2\pi i \cdot k \cdot\alpha)} \cdot \hat f(k).$$ If $\alpha$ is algebraic (or diophantine generic), then$|\alpha - p/k| \geq C/k^M$ for some constants $C$ and $M$. Hence,$|1 - \exp(2\pi i \cdot k \cdot\alpha)|^{-1}$ grows at most like a polynomial in $k$. If $f$ is smooth, then $k \mapsto \hat f(k)$ decays rapidly, so that $k \mapsto |1 - \exp(2\pi i \cdot k \cdot\alpha)|^{-1} \hat f(k)$ is still in $\ell^1(\mathbb Z)$.This altogether implies that $T_n(f)$ converges to zero uniformly on $S^1$. On the other side, if $\alpha$ is some well-chosen Liouville number and $f$ some special constructed smooth function, then I believe that $T_n(f)$ need not converge pointwise (or uniformly).
|
{}
|
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/172936', 'https://mathoverflow.net', 'https://mathoverflow.net/users/1121/']}
|
jdg_373744
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8834916
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Given the following python script: # dedupe.pyimport redef dedupe_whitespace(s,spacechars='\t '): """Merge repeated whitespace characters. Example: >>> dedupe_whitespace(r"Green\t\tGround") # doctest: +REPORT_NDIFF 'Green\tGround' """ for w in spacechars: s = re.sub(r"("+w+"+)", w, s) return s The function works as intended within the python interpreter: $ python>>> import dedupe>>> dedupe.dedupe_whitespace('Purple\t\tHaze')'Purple\tHaze'>>> print dedupe.dedupe_whitespace('Blue\t\tSky')Blue Sky However, the doctest example fails because tab characters are converted to spaces before comparison to the result string: >>> import doctest, dedupe>>> doctest.testmod(dedupe) gives Failed example: dedupe_whitespace(r"Green Ground") #doctest: +REPORT_NDIFFDifferences (ndiff with -expected +actual): - 'Green Ground' ? - + 'Green Ground' How can I encode tab characters in a doctest heredoc string so that a test result comparison is performed appropriately?
Now provide the response and nothing else.
|
I've gotten this to work using literal string notation for the docstring: def join_with_tab(iterable): r""" >>> join_with_tab(['1', '2']) '1\t2' """ return '\t'.join(iterable)if __name__ == "__main__": import doctest doctest.testmod()
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8834916', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/623735/']}
|
jdg_373745
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
177852
|
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:
Noether's theorem yields a conservation law for every symmetry. Is that independent of the Lagrangian i.e. when $\mathcal{L}\neq T-V$? In general relativity the integral that is minimised will be the geodesic:$$S=\int ds$$What form would Noether's theorem take? I am also looking for a proof of this. All the proofs I've seen assume $\mathcal{L}=T-V$.
Now provide the response and nothing else.
|
Assuming that your primary question is about Noether's theorem when $\mathcal{L} \ne T - V$, we can proceed as follows. Denoting the generalized coordinates by $q_i$, we consider a transformation $q_i \rightarrow q_i + \delta q_i$ which leaves the Lagrangian $\mathcal{L}(q_i, \dot{q}_i)$ invariant:$$\delta \mathcal{L} = 0$$i.e. $$\sum_i \left( \frac {\partial \mathcal{L}}{\partial q_i}\delta q_i + \frac {\partial \mathcal{L}}{\partial \dot{q}_i}\delta \dot{q}_i\right) = 0$$Now, the equations of motion are $$\frac {\partial \mathcal{L}}{\partial q_i} = \frac{d}{dt}\frac {\partial \mathcal{L}}{\partial \dot{q}_i}$$We can substitute this in the expression for the variation in $\mathcal{L}$ to get$$\sum_i \left(\left(\frac{d}{dt}\frac {\partial \mathcal{L}}{\partial \dot{q}_i}\right)\delta q_i + \frac {\partial \mathcal{L}}{\partial \dot{q}_i}\left(\frac{d}{dt} \delta q_i\right)\right) = 0$$We can now combine the terms:$$\frac{d}{dt}\left(\sum_i\frac {\partial \mathcal{L}}{\partial \dot{q}_i}\delta q_i\right) = 0$$Thus, the quantity $Q = \sum_i \frac {\partial \mathcal{L}}{\partial \dot{q}_i}\delta q_i$ is conserved, upto a constant multiplier. Now, considering the action:$$ S = m\int ds = m\int \sqrt{g_{ab}\dot{x}^a\dot{x}^b} dt$$the Lagrangian is $\mathcal{L} = m\sqrt{g_{ab}\dot{x}^a\dot{x}^b}$. As such, what transformation leaves this invariant depends on $g_{ab}$. If, for example, we assume that $g_{ab} = \eta_{ab}$, the Minkowski metric, then the Lagrangian is invariant under displacements $x^a \rightarrow x^a + c^a$ and we get the conserved quantity:$$Q = \eta_{ab}c^a\frac{m\dot{x}^b}{\sqrt{\eta_{ab}\dot{x}^a\dot{x}^b}} = p_a c^a$$Now, this holds for any and all $c^a$, and therefore, the coefficient of each component $c^a$ must also be conserved (as can be seen by setting the other components to zero). Therefore, the conserved quantities are:$$p_a = \eta_{ab} \frac{m\dot{x}^b}{\sqrt{\eta_{ab}\dot{x}^a\dot{x}^b}}$$This is essentially the conservation of the 4-momentum of a free particle in special relativity.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/177852', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/37603/']}
|
jdg_373746
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
29964620
|
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 testing the new code editor from Microsoft : Visual Studio Code. I'm under Windows 7 and i'm trying this example : https://code.visualstudio.com/Docs/nodejs But when i try to add /// <reference path="/typings/node/node.d.ts"/> like it is said in the example. It does'nt work. The file is never downloaded and i don't know where i can find it. Is someone knows how to fix that ? Is it a bug or the problem come from my machine ?
Now provide the response and nothing else.
|
TSD is TypeScript Definition, while TypeScript is a typed superset of JavaScript from Microsoft that compiles to plain JavaScript. You don't need to understand these if you just want to use VSCode to develop common JavaScript-based node.js projects like me. To solve your problem, I think a better way is to install the TSD package manager as a global module. This will enable you to use the command tsd globally. npm install tsd@next -g Then go to the root folder of your project, and type tsd install node This will automatically create a folder 'typings/node' with a .ts file named 'node.d'. If you also need IntelliSense for third party modules like express.js or async.js, you can just add them by yourself tsd install express Just like 'npm' which you already be familiar with is the package manager for node.js, 'tsd' is the package manager for TypeScript Definition (but not for TypeScript itself) There's a list here showing the available repositories. http://definitelytyped.org/tsd/ Once you download all the .tsd files into the 'typings' folder, you still have to manually put these special comments at the beginning of each .js files to help VSCode look up the definitions for node and express, so now VSCode knows the API details of the classes and functions. /// <reference path="typings/node/node.d.ts"/>/// <reference path="typings/express/express.d.ts"/>
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/29964620', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4759067/']}
|
jdg_373747
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
24916435
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Clearly, type aliases and templated type aliases are semantically equivalent to typedefs and an extension of typedefs to support template. How come new syntax with the using keyword was created for these instead of using typedefs for the first and some syntax extension with the word typedef . NOTE: This is not a clone of the "difference between using and typedef" question. I know that using gives the advantage of defining a family of typedef s. What I am asking is why did the standard people decide on having this extension use the using keyword instead of the typedef keyword. This seems like it just adds confusion in the language.
Now provide the response and nothing else.
|
What you suggest was actually proposed back in 2002 in document N1406 by Herb Sutter. It would allow, for example, to write: template<typename T> typedef X<T,int> Xi; This was later revised in N1449 by Gabriel Dos Reis and Mat Marcus. They adopt the using syntax, and note the following: Note that we specifically avoid the term “typedef template” and introduce the new syntax involving the pair “using” and “=” to help avoid confusion: we are not defining any types here, we are introducing a synonym (i.e. alias) for an abstraction of a type-id (i.e. type expression) involving template parameters. They also state: Two straw polls were taken regarding syntax. A strong majority voted to avoid the typedef template syntax, in favor of the “=” syntax. A second vote indicated strong preference for the “using” keyword as opposed to a word like “alias” or the absence of any keyword as in the draft version of this proposal. The motivation for using any keyword at all stemmed partly from the desire to use a syntax that might be compatible with the non-template aliasing direction briefly outlined above. This syntax was then adopted in the final proposal N2258 by Gabriel Dos Reis and Bjarne Stroustrup.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24916435', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1964342/']}
|
jdg_373748
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
22296136
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
All How can I download a file so the user sees that it is downloading (like with a stream?) I am currently using ClosedXML, but if I use the SaveAs method, I have to give a hard-coded URL, and if I just give the file name it does not automatically download to the download folder. The method below works great, but I have to create my own excel file, which is based upon HTML, and the file grows way too large than it should, when I use ClosedXML the file is only 50% or less from the size of the code below:However, the download behaviour is how I would like it to be. Is there a way I can convert the code below so I can give my 'workbook' as an object, and it just downloads this workbook? HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename=Excel.xls");HttpContext.Current.Response.Charset ="UTF-8"; HttpContext.Current.Response.ContentEncoding=System.Text.Encoding.Default;HttpContext.Current.Response.ContentType = "application/ms-excel";ctl.Page.EnableViewState =false; System.IO.StringWriter tw = new System.IO.StringWriter() ;System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter (tw);ctl.RenderControl(hw);HttpContext.Current.Response.Write(tw.ToString());HttpContext.Current.Response.End(); Thanks
Now provide the response and nothing else.
|
The SaveAs() method supports stream, so to get the ClosedXml workbook as a stream I use: public Stream GetStream(XLWorkbook excelWorkbook){ Stream fs = new MemoryStream(); excelWorkbook.SaveAs(fs); fs.Position = 0; return fs;} And then for downloading the file: string myName = Server.UrlEncode(ReportName + "_" + DateTime.Now.ToShortDateString() + ".xlsx");MemoryStream stream = GetStream(ExcelWorkbook);Response.Clear();Response.Buffer = true;Response.AddHeader("content-disposition", "attachment; filename=" + myName);Response.ContentType = "application/vnd.ms-excel";Response.BinaryWrite(stream.ToArray());Response.End();
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/22296136', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/651353/']}
|
jdg_373749
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
24997926
|
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 image that I'm showing with matplotlib. The image is generated by the following code: import numpy as npimport matplotlib.pyplot as pltfrom matplotlib import cmlabels = ['Name1', 'Name2', 'Name3', 'Name4', 'Name5', 'Name6']data = np.array( [[ 0.000, 0.120, 0.043, 0.094, 0.037, 0.045], [ 0.120, 0.000, 0.108, 0.107, 0.105, 0.108], [ 0.043, 0.108, 0.000, 0.083, 0.043, 0.042], [ 0.094, 0.107, 0.083, 0.000, 0.083, 0.089], [ 0.037, 0.105, 0.043, 0.083, 0.000, 2.440], [ 0.045, 0.108, 0.042, 0.089, 2.440, 0.000]])mask = np.tri(data.shape[0], k=-1)data = np.ma.array(data, mask=mask) # Mask out the lower triangle of data.fig, ax = plt.subplots(sharex=True)im = ax.pcolor(data, edgecolors='black', linewidths=0.3)# Formatfig = plt.gcf()fig.set_size_inches(10, 10)ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False)ax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False)# Turn off the frame.ax.set_frame_on(False)ax.set_aspect('equal') # Ensure heatmap cells are square.# Want a more natural, table-like display.ax.invert_yaxis()ax.yaxis.tick_right()ax.xaxis.tick_top()ax.set_xticklabels(labels, minor=False)ax.set_yticklabels(labels, minor=False)# Rotate the upper labels.plt.xticks(rotation=90)ax.grid(False)ax = plt.gca()for t in ax.xaxis.get_major_ticks(): t.tick1On = False t.tick2On = Falsefor t in ax.yaxis.get_major_ticks(): t.tick1On = False t.tick2On = Falsefig.colorbar(im)fig.savefig('out.png', transparent=False, bbox_inches='tight', pad_inches=0) I'd like to apply a custom colormap so that values: between 0-1 are linear gradient from blue and white between 1-3 arelinear gradient from white and red. Any help will be greatly appreciated.
Now provide the response and nothing else.
|
There's more than one way to do this. In your case, it's easiest to use LinearSegmentedColormap.from_list and specify relative positions of colors as well as the colornames. (If you had evenly-spaced changes, you could skip the tuples and just do from_list('my cmap', ['blue', 'white', 'red']) .) You'll then need to specify a manual min and max to the data (the vmin and vmax kwargs to imshow / pcolor /etc). As an example: import matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LinearSegmentedColormapdata = np.array( [[ 0.000, 0.120, 0.043, 0.094, 0.037, 0.045], [ 0.120, 0.000, 0.108, 0.107, 0.105, 0.108], [ 0.043, 0.108, 0.000, 0.083, 0.043, 0.042], [ 0.094, 0.107, 0.083, 0.000, 0.083, 0.089], [ 0.037, 0.105, 0.043, 0.083, 0.000, 2.440], [ 0.045, 0.108, 0.042, 0.089, 2.440, 0.000]])mask = np.tri(data.shape[0], k=-1)data = np.ma.masked_where(mask, data)vmax = 3.0cmap = LinearSegmentedColormap.from_list('mycmap', [(0 / vmax, 'blue'), (1 / vmax, 'white'), (3 / vmax, 'red')] )fig, ax = plt.subplots()im = ax.pcolor(data, cmap=cmap, vmin=0, vmax=vmax, edgecolors='black')cbar = fig.colorbar(im)cbar.set_ticks(range(4)) # Integer colorbar tick locationsax.set(frame_on=False, aspect=1, xticks=[], yticks=[])ax.invert_yaxis()plt.show()
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24997926', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/922130/']}
|
jdg_373750
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4158603
|
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 arrived at the following identity throught an attempt at a homework problem: the LHS is my solution; the RHS, the book's one. And as far I have tested , they are equivalent. $$\sum_{q=1}^n \binom{n}{q}\binom{n-q}{2k-2q}2^{2(k-q)} = \binom{2n}{2k} - \binom{n}{2k}2^{2k}$$ The combinatorial meaning of this identity is rather intuitive as per the homework's verbatim: "Find the number of ways of forming a group of $2k$ people from $n$ couples where $k,n \in \Bbb N$ and $2k \leq n$ so that at least one couple is included in such group". That being said, the combinatorial meaning of the LHS (and even the RHS) is rather clear: it iterates over $q = \{1,2,...,n\}$ couples, selects $2k-2q$ couples from the remaining $n-q$ and then picks one person from each of these $2k-2q$ couples, which can be done in $2^{2k-2q}$ ways, to form the group. The RHS does this by composition: removing those groups that do not contain one couple. However, while I know what the LHS is supposed to do, I don't know how it works. I know that the groups that do not contain 1 couple is given by $\binom{n}{2k}2^{2k}$ (after all, this is the case where $q=0$ ), but I have little idea as to how the $\binom{2n}{2k}$ term counts the "rest". And I have way fewer ideas about how would I prove this thing algebraically. Later edit: I realized that the $\binom{2n}{2k}$ term simply counts the number of ways of grouping $2k$ people from the overall $2n$ people of the $n$ couples. So ofc all you'd need to do after that is remove those groups that do not contain 1 couple.
Now provide the response and nothing else.
|
Algebraic proof . Your identity is equivalent to (note that the upper limit should be $k$ and the lower limit is $0$ because we moved $\binom{n}{2k}2^{2k}$ to the left hand side): $$\sum_{q=0}^k \binom{n}{q}\binom{n-q}{2k-2q}2^{2(k-q)} = \binom{2n}{2k}.$$ Now we have that $$\begin{align*}\sum_{q=0}^k \binom{n}{q}\binom{n-q}{2k-2q}2^{2(k-q)}&=\sum_{q=0}^k \binom{n}{q}2^{2(k-q)}[z^{2k-2q}] (1+z)^{n-q} \\&=[z^{2k}]4^k(1+z)^n\sum_{q\geq 0} \binom{n}{q} \frac{z^{2q}}{4^q(1+z)^{q}} \\&=[z^{2k}]4^k(1+z)^n\left(1+\frac{z^2}{4(1+z)}\right)^n\\&=[z^{2k}]4^k\left(1+z+\frac{z^2}{4}\right)^n\\&=[z^{2k}]4^k\left(1+\frac{z}{2}\right)^{2n}=\binom{2n}{2k}.\end{align*}$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4158603', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/409265/']}
|
jdg_373751
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
92046
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
I'm looking at motivating the standard deformation of $U(\mathfrak{sl}(2))$. As an algebra $U(\mathfrak{sl}(2))$ is generated by $X,Y$ and $H$ and subject to the relations $[X,Y] = H$, $[H,X] = 2X$ and $[H,Y] = -2Y$. From $q$-analysis I have that an integer $n$ is deformed according to $[n] = \frac{q^{n}-q^{-n}}{q-q^{-1}}$. This seems to motivate, at least partially, the means of deforming $U(\mathfrak{sl}(2))$. That is, set $[X,Y] = [H] = \frac{q^{H}-q^{-H}}{q-q^{-1}}$ and then set $K = q^{H}$ and $K^{-1} = q^{-H}$. But what motivates the relations $KX = q^{2}XK$ and $KY = q^{-2}YK$?
Now provide the response and nothing else.
|
Hi Ryan, You can prove that if $a,b$ are some elements in an algebra such that $[a,b]=\lambda b$ for $\lambda$ a scalar, then (in a context where this expression makes sense) $q^a b q^{-a}=q^{\lambda} b$: rewrite the relation as$$ab=b(a+\lambda)$$then$$a^nb=b(a+\lambda)^n$$therefore$$q^ab=\sum \frac{\log(q)^na^n}{n!}b=b\sum \frac{\log(q)^n(a+\lambda)^n}{n!}= bq^{(a+\lambda)}=q^{\lambda}bq^a$$since $\lambda$ commutes with everything. Therefore it's in fact not a deformation but the same relation with $q^H$ instead of $H$. In my opinion, what is more miraculous is the existence of a non-trivial deformation of the Hopf structure. Although it does not leads to explicit formulas, the conceptual explanation for that comes from the Kohno-Drinfeld theorem, or more generally from the Etingof-Kazhdan quantization functor.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/92046', 'https://mathoverflow.net', 'https://mathoverflow.net/users/22360/']}
|
jdg_373752
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12139481
|
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 launch code with this query, sometimes I can see all the tables listed, sometimes only one and I get always this error: Query Error: Error: SQLITE_MISUSE: unknown error I've read that SQLITE_MISUSE occurs when SQLITE API is used unproperly. Could you help me, because I can't find whats wrong in this code. EDIT. I've made changes to the code to get rid of the race issue. The message with SQLITE_MISUSE wrror still occurs, however the vanishing tables issue is gone. Race in my queries was the case. Here is the code. var sqlite3 = require("node-sqlite3");var fs = require('fs');var query_count;var init = function (response) { var db = new sqlite3.Database("test.db", function() { fs.readFile('./assets/sql/initDB.sql', function(err,data){ if(err) { console.error("Could not open file: %s", err); return; } var query = data.toString('utf8'); queries = query.split(";"); db.serialize(function() { query_count = queries.length; for(var i=0; i<queries.length; i++) { queries[i] = queries[i].replace("\r\n",""); db.run(queries[i], function(error) { if(error) { console.log("Query Error: "+error); } query_count--; if( query_count <= 0 ) { db.close(); listAllTables(response); } }); } }); }); });};function listAllTables(response) { var db = new sqlite3.Database("./assets/sql/test.db", function () { db.all("SELECT name FROM sqlite_master WHERE type = 'table'", function (error, records) { for(var record in records) { response.write(record+": "+records[record]+"\n"); for(var prop in records[record]) { response.write("\t"+prop+": "+records[record][prop]+"\n"); } } response.end(); db.close(); }); });}exports.load_customers = function(response) { init(response);}; The query file initDB.sql is like this: CREATE TABLE IF NOT EXISTS TemporaryAuthTokens ( authToken TEXT PRIMARY KEY NOT NULL UNIQUE, expireDate NUMERIC NOT NULL);CREATE TABLE IF NOT EXISTS User ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE , login TEXT NOT NULL , pass TEXT NOT NULL , creationDate NUMERIC NOT NULL , authToken TEXT NULL REFERENCES TemporaryAuthTokens(authToken) );
Now provide the response and nothing else.
|
You've got a race condition; it's possible that your last query (whose callback closes the connection) will finish before one of the earlier queries did, and that will, needless to say, hose the earlier query. You need to rework your code so that the last query to finish , rather than the last query to start , closes the connection (e.g set a counter to the number of queries and have each query decrement it when it finishes. The one that decrements it to zero closes the connection). You might also want to look at the serialize method that's available on database objects. Right now your initialization queries are all independent of each other, but if you started using foreign-key constraints you'd have trouble if the referenced table hadn't been created yet, so you'd need to force the order of execution.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12139481', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1627283/']}
|
jdg_373753
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
30624
|
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
This question is about problems for which there is a big open complexity gap between known lower bound and upper bound, but not because of open problems on complexity classes themselves. To be more precise, let's say a problem has gap classes $A,B$ (with $A\subseteq B$, not uniquely defined) if $A$ is a maximal class for which we can prove it is $A$-hard, and $B$ is a minimal known upper bound, i.e. we have an algorithm in $B$ solving the problem. This means if we end up finding out that the problem is $C$-complete with $A\subseteq C\subseteq B$, it will not impact complexity theory in general, as opposed to finding a $P$ algorithm for a $NP$-complete problem. I am not interested in problems with $A\subseteq P$ and $B=NP$, because it is already the object of this question . I am looking for examples of problems with gap classes that are as far as possible. To limit the scope and precise the question, I am especially interested in problems with $A\subseteq P$ and $B\supseteq EXPTIME$, meaning both membership in $P$ and $EXPTIME$-completeness are coherent with current knowledge, without making known classes collapse (say classes from this list ).
Now provide the response and nothing else.
|
The Knot Equivalence Problem . Given two knots drawn in the plane, are they topologically the same? This problem is known to be decidable, and there do not seem to be any computational complexity obstructions to its being in P. The best upper bound currently known on its time complexity seems to be a tower of $2$s of height $c^n$, where $c = 10^{10^{6}}$, and $n$ is the number of crossings in the knot diagrams. This comes from a bound by Coward and Lackenby on the number of Reidemeister moves needed to take one knot to an equivalent one. See Lackenby's more recent paper for some more recent related results and for the explicit form of the bound I give above (page 16).
|
{}
|
{'log_upvote_score': 5, 'links': ['https://cstheory.stackexchange.com/questions/30624', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/8953/']}
|
jdg_373754
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
49934740
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am using Protocol and Delegates for saving api data into delegate method and in another class, fetching it. But in second class, when i declared this property. It shows an error message. 'DepartmentDataDelegate' cannot be constructed because it has no accessible initializers Class A : Add protocol for saving api data into the delegate method. protocol DepartmentDataDelegate { func showDepttData(departments: [String : Any])}var delegate: DepartmentDataDelegate? Stored api data into protocol method do { //create json object from data if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: [Any]] { //print("POST Method :\(json)") DispatchQueue.main.async { for eachDepartment in json["departments"]! { let eachData = eachDepartment as! [String: Any] self.delegate?.showDepttData(departments: eachData) } self.tableView.reloadData() } // handle json... } } catch let error { print(error.localizedDescription)} Class B : This class is fetching the department data and print here. class ShowEmpVC: UIViewController, DepartmentDataDelegate { //Department Data Delegate var depttDelegate = DepartmentDataDelegate() var depttData = [String : Any]() override func viewDidLoad() { super.viewDidLoad() depttDelegate = self print("Departmens are : \(depttData)") }}
Now provide the response and nothing else.
|
Finally it worked for me, I followed this way How to Write xUnit Test for .net core 2.0 Service that uses AutoMapper and Dependency Injection? Here I am posting my answer and Test Class so if needed other SO's can use. public class SchedulesControllerTests{ [Fact] public void CanGet() { try { //Arrange //Repository Mock<IScheduleRepository> mockRepo = new Mock<IScheduleRepository>(); var schedules = new List<Schedule>(){ new Schedule() { Id=1, Title = "Schedule1" }, new Schedule() { Id=2, Title = "Schedule2" }, new Schedule() { Id=3, Title = "Schedule3" } }; mockRepo.Setup(m => m.items).Returns(value: schedules); //auto mapper configuration var mockMapper = new MapperConfiguration(cfg => { cfg.AddProfile(new AutoMapperProfile()); }); var mapper = mockMapper.CreateMapper(); SchedulesController controller = new SchedulesController(repository: mockRepo.Object, mapper: mapper); //Act var result = controller.Get(); //Assert var okResult = result as OkObjectResult; if (okResult != null) Assert.NotNull(okResult); var model = okResult.Value as IEnumerable<ScheduleDto>; if (model.Count() > 0) { Assert.NotNull(model); var expected = model?.FirstOrDefault().Title; var actual = schedules?.FirstOrDefault().Title; Assert.Equal(expected: expected, actual: actual); } } catch (Exception ex) { //Assert Assert.False(false, ex.Message); } }}
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/49934740', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9673134/']}
|
jdg_373755
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
21997130
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
So, I was trying to make a rectangle move with a KeyEvent ( KeyListener ) and whenever I try to hit the key, the rectangle doesn't move. The rectangle is drawn, but whenever I hit the left and right keys, nothing happens.I have two classes, one is my main class with the keyEvents and the frame and the other, draws the rectangle and holds the function to move the rectangle. Here is my code: import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import javax.swing.JFrame;public class mainFrame extends JFrame implements KeyListener{mainDraw Draw = new mainDraw();public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if(key == KeyEvent.VK_D){ Draw.moveRight(); }}public void keyReleased(KeyEvent e) {}public void keyTyped(KeyEvent e) {}public mainFrame(){ addKeyListener(this); setFocusable(true); setFocusTraversalKeysEnabled(false);}public static void main(String[] args) { mainFrame M1 = new mainFrame(); mainDraw Draw = new mainDraw(); JFrame frame = new JFrame("Square Move Practice"); //frame frame.setVisible(true); frame.setResizable(false); frame.setSize(600, 600); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(Draw);}} And now the second class: import java.awt.Color;import java.awt.Graphics;import javax.swing.JComponent;public class mainDraw extends JComponent{public int x = 50;public int y = 50;public void paint(Graphics g){ g.drawRect(x, y, 50, 50); g.fillRect(x, y, 50, 50); g.setColor(Color.BLACK);}public void moveRight(){ x = x + 5; y = y + 0; repaint();}} Please tell me how I can move the rectangle.Thanks in advance!
Now provide the response and nothing else.
|
The rectangle is not moving because you are not using JFrame correctly. You have to assign frame to new mainFrame() instead of ignoring the instantiated mainFrame object. There are several other issues as @MadProgrammer points out. Here is the code that fixes some of the issues: mainFrame.java import java.awt.*;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import javax.swing.JFrame;public class mainFrame extends JFrame implements KeyListener{ private mainDraw draw; public void keyPressed(KeyEvent e) { System.out.println("keyPressed"); } public void keyReleased(KeyEvent e) { if(e.getKeyCode()== KeyEvent.VK_RIGHT) draw.moveRight(); else if(e.getKeyCode()== KeyEvent.VK_LEFT) draw.moveLeft(); else if(e.getKeyCode()== KeyEvent.VK_DOWN) draw.moveDown(); else if(e.getKeyCode()== KeyEvent.VK_UP) draw.moveUp(); } public void keyTyped(KeyEvent e) { System.out.println("keyTyped"); } public mainFrame(){ this.draw=new mainDraw(); addKeyListener(this); setFocusable(true); setFocusTraversalKeysEnabled(false); } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { mainFrame frame = new mainFrame(); frame.setTitle("Square Move Practice"); frame.setResizable(false); frame.setSize(600, 600); frame.setMinimumSize(new Dimension(600, 600)); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(frame.draw); frame.pack(); frame.setVisible(true); } }); }} mainDraw.java import java.awt.Color;import java.awt.Graphics;import javax.swing.JComponent;public class mainDraw extends JComponent { public int x = 50; public int y = 50; public void paintComponent(Graphics g) { super.paintComponent(g); g.drawRect(x, y, 50, 50); g.fillRect(x, y, 50, 50); g.setColor(Color.BLACK); } public void moveRight() { x = x + 5; repaint(); } public void moveLeft() { x = x - 5; repaint(); } public void moveDown() { y = y + 5; repaint(); } public void moveUp() { y = y - 5; repaint(); }} BTW, use SwingUtilities to put the gui update code because swing objects are not thread-safe.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21997130', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3183679/']}
|
jdg_373756
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13803326
|
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 optimize the performance of a database that my team is using for an application. I have been looking for areas to add foreign keys, and in turn index those columns to improve the performance of joins. However, many of our tables are joined on an id that is a GUID type, generated upon insertion of an item, and the data associated with that item in other tables is generally has column item_id containing the GUID. I have read that adding clustered indexes to GUID type columns is a very bad decision because the index will need to be constantly reconstructed in order to be effective. However, I was wondering, is there any detriment to utilizing a non-clustered index in the scenario described above? Or is it reasonable to assume that it would help performance? I can provide more information if needed.
Now provide the response and nothing else.
|
An index on a <anytype> is by far the best option you have to improve joins and singleton lookups. Lacking this index the query will always have to scan the entire table end-to-end with (often) abysmal performance results and concurrency gone down the drain. It is true that uniqueidentifier makes poor choice for indexes for the reasons you mention, but by no means does that implies that you should not create these indexes. Changing the data type to INT or BIGINT would be advisable, if possible. Using NEWSEQUENTIALID() or UuidCreateSequential to generate them would help with fragmentation issues. If all alternatives fail you may have to do index maintenance (Rebuild, reorganize) operations more often than for other indexes. But by no means do any of these drawbacks outweigh the benefit of having the index in the first place!
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13803326', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/692011/']}
|
jdg_373757
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
396033
|
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:
Here is the function: if (m == 0) return n + 1;else if (n == 0) return A(m-1, 1);else return A(m-1, A(m, n-1)); This seems like an interesting function, especially since its values grow quite rapidly (my computer crashes if I try to run A(4,2) or A(3,10)). From the wikipedia page it seems like it was only invented to show that a total computable function does not have to be primitive recursive. Has anything practical come from this function, other than homework problems in a computer science class?
Now provide the response and nothing else.
|
Generally, if there's two roots whose sum is zero, then it means that two factors are $x-a$ and $x+a$, which means that $x^2-a^2$ must be a factor. So clearly$$(x^2-a^2)(x^2+bx+c)=x^4+2x^3-8x^2-18x-9=0$$Find the values of $a^2$, $b$, and $c$ that satisfy the left equality, and you'll have found factors that you can then solve for all roots. (This works even if there's no rational root)
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/396033', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
|
jdg_373758
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
28715
|
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:
A paper I'm reading claims that the smallest class of monoids which contains $\mathbb{Z}$ and is closed under finite direct product and block product only contains solvable monoids. I think that a proof that solvability of groups is closed under wreath product would be of great help to understand why this is true. Would anyone know where I can find such a proof? In the "converse direction", I would be really interested in reading a proof of the following fact: Any solvable group is in the variety generated by a wreath product of cyclics (taken from Barrington and Thérien, Non-uniform automata over groups (1987) ).
Now provide the response and nothing else.
|
A wreath product $G\wr H$ is a semidirect product of $G^H$ and $H$; since a group $G$ with normal subgroup $N$ is solvable if and only if both $N$ and $G/N$ are solvable, this means that $G\wr H$ is solvable if and only if $G^H$ and $H$ are both solvable. Thus, if $G\wr H$ is solvable, then so are $G^H$ and $H$. The only question then is whether $G$ is solvable if and only if $G^H$ is solvable. This is true. First, if $G^H$ is solvable, then so is the subgroup corresponding to the $e_H$-coordinate (that is, the subgroup $f\colon H\to G$ such that $f(h)=1$ for all $h\neq e_H$, which is isomorphic to $G$). Conversely, if $G$ is solvable, then so is any direct power of $G$ This follows because for any direct product of groups, we have$$\left(\prod_{i\in I} K_i\right)^{(n)} \subseteq \prod_{i\in I}K_i^{(n)}$$where $M^{(n)}$ is the $n$th derived subgroup of $G$. (Simply note that the projection maps $\pi_j\colon \prod_{i\in I} K_i \to K_j$ must map $(\prod K_i)^{(n)}$ into $K_j^{(n)}$, so that gives a map into the product of the $n$th derived subgroups); equality need not hold in general, but the inclusion always does). Since $G$ is solvable, if and only if there exists $n$ such that $G^{(n)} = \{1\}$; then if $G$ is solvable, we have$$\left(\prod_{i\in I}G\right)^{(n)} \subseteq \prod_{i\in I}G^{(n)} = \prod_{i\in I}\{1\} = \{1\}$$so $\prod_{i\in I}G$ is solvable. In particular, taking $I=H$ we get that if $G$ is solvable, then so is $G^H$. In summary: $G\wr H$ is solvable if and only if $G^H$ and $H$ are both solvable. For any nonempty set $I$, $\prod_{i\in I}G$ is solvable if and only if $G$ is solvable. $G^H \cong \prod_{h\in H}G$, so $G^H$ is solvable if and only if $G$ is solvable. So: $G\wr H$ is solvable if and only if $G$ and $H$ are both solvable. Note. It is not true in general that an arbitrary direct product of solvable groups is solvable. What is true is that for fixed $n$, an arbitrary direct product of solvable groups is solvable of length at most $n$ if and only if each direct factor is solvable of length at most $n$. The converse is a little trickier, but I think the following does it. First: a group $G$ generates the variety $\mathfrak{V}$ if and only if every group in $\mathfrak{V}$ is a homomorphic image of a subgroup of a direct power of $G$. For example, $\mathbb{Z}$ generates the variety of abelian groups. A set of groups $S$ generates $\mathfrak{V}$ if and only if every group in $\mathfrak{V}$ is a homomorphic image of a subgroup of a direct product of copies of groups in $S$. Second: a set of groups $S$ discriminates a variety $\mathfrak{V}$ if $S\subset\mathfrak{V}$ and for every finite set $\mathfrak{w}$ of words that are not laws of $\mathfrak{V}$, there is a group $D\in\mathfrak{D}$ in which the equations $w=1$, $w\in\mathfrak{w}$, can be simultaneously falsified. It is a theorem that a set that discriminates a variety also generates that variety; in fact, a set of groups "discriminates" if and only if it discriminates the variety it generates. Theorem. (Baumslag, B.H. Neumann, H. Neumann, and P. Neumann). If the group $G$ generates $\mathfrak{V}$, and the set $S$ discriminates $\mathfrak{W}$, then the set $G\wr S = \{ G \wr D\mid D\in S\}$ discriminates $\mathfrak{VW}$, and therefore also generates $\mathfrak{VW}$. (In fact, one can take the restricted direct product above, rather than the full wreath product). Now, every group word is equivalent to a group word of the form $x^nc$, where $c$ is a commutator word on and $n\geq 0$. Thus, the only words that are not laws of the variety of abelian groups are words of the form $x^nc$ with $n\gt 1$. All these laws can be simultaneously falsified by $\mathbb{Z}$, by evaluating every letter in the words at $1$; The argument above was wrong (a bunch of hooey, really). Here's a proper argument: a word $\mathbf{w}$ is not a law of $\mathfrak{A}$ if and only if the exponent sum of at least one variable is not $0$. For abelian groups, the word can be rewritten as a linear equation in the variables with integer coefficients; an evaluation in $\mathbb{Z}$ satisfies the word if and only if it satisfies the corresponding linear equation with integer coefficients. A finite set of words that are not laws of $\mathfrak{A}$ correspond to a finite system of linear equations with integer coefficients; an element of $\mathbb{Z}^n$ ($n$ the number of variables) satisfies at least one of the equations if it lies in the union of the solution sets of the individual equations. Since the equations are nontrivial, the solution sets are proper submodules of $\mathbb{Z}^n$; since $\mathbb{Z}^n$ is not a union of finite many proper submodules (same argument as for vector spaces over infinite fields), it follows that given a finite collection of words that are not laws of $\mathfrak{A}$ there is always an evaluation in $\mathbb{Z}$ that falsifies all of them simultaneously. Therefore, $\mathbb{Z}$ discriminates $\mathfrak{A}$, the variety of all abelian groups. Also, $\mathbb{Z}$ generates the variety of all abelian groups. Therefore, applying the B+3N theorem, we get that $\mathbb{Z}\wr\mathbb{Z}$ generates $\mathfrak{A}^2$, the variety of solvable groups of length at most $2$; then it follows that $(\mathbb{Z}\wr\mathbb{Z})\wr\mathbb{Z}$ discriminates, and hence generates, $\mathfrak{A}^3$. Continuing this way, the iterated wreath product of $\mathbb{Z}$ discriminates, and hence generates, the variety of solvable groups of length at most $n$. Thus, every solvable group lies in a variety generated by an iterated (restricted) wreath product of cyclic groups. Presumably, if you know a bit more about $G$ some of the copies of $\mathbb{Z}$ could even be replaced by suitable finite cyclic groups. Note. It is false in general that if $S$ generates $\mathfrak{V}$ and $T$ generates $\mathfrak{W}$, then $S\wr T = \{G\wr H\mid G\in S, H\in T\}$ generates $\mathfrak{VW}$. But if $S$ generates $\mathfrak{V}$, then $S\wr F_{\infty}(\mathfrak{W}) = \{ G\wr F_{\infty}(\mathfrak{W})\mid G\in S\}$ generates $\mathfrak{VW}$, where $F_{\infty}(\mathfrak{W})$ is the countably generated relatively free group in $\mathfrak{W}$, and the wreath products are restricted wreath products. This is a consequence of the B+3N theorem above, but it was actually proven earlier by Baumslag.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/28715', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/5270/']}
|
jdg_373759
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
38979801
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Per this question , Java will select the "most specific" option when trying to select between ambiguous overloaded constructors. In this example: public class Test{ private Test(Map map){ System.out.println("Map"); } private Test(Object o){ System.out.println("Object"); } public static void main(String[] args){ new Test(null); }} it will print "Map" However, I was trying to figure out exactly what "most specific" means. I assumed it meant "least ambiguous", as in "may refer to the fewest possible types." In this context, Object may be anything that isn't a primitive, while Map may only be Map or ? extends Map . Basically, I assumed that whichever class was closer to the leaf of the inheritance tree would be selected. That works when one class is a subclass of the other: public class Test{ private Test(A a){ System.out.println("A"); } private Test(B b){ System.out.println("B"); } public static void main(String[] args){ new Test(null); }}class A{}class B extends A{} "B" Then I came up with this: public class Test{ private Test(A a){ System.out.println("A"); } private Test(E e){ System.out.println("E"); } public static void main(String[] args){ new Test(null); }}class A{}class B extends A{}class C{}class D extends C{}class E extends D{} I would think it should print E , as E may only refer to one known type, whereas A may refer to two ( A and B ). But it give an ambiguous reference error. How is it actually choosing the constructor? I read through the docs but frankly I couldn't quite follow how it determines specificity. I'm hoping for a description of exactly why it can't determine that E is more specific than A .
Now provide the response and nothing else.
|
It's not based on the number of types that are convertible to the parameter type - it's whether any value that's valid for one overload is valid for another, due to implicit conversions. For example, there's an implicit conversion from String to Object , but the reverse isn't true, so String is more specific than Object . Likewise there's an implicit conversion from B to A , but the reverse isn't true, so B is more specific than A . With A and E however, neither is more specific than the other - there no conversion from A to E , and no conversion from E to A . That's why overload resolution fails. The relevant bit of the JLS is actually 15.12.2.5 , which includes this that might make it easier for you to understand: The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time error. So if you have: void foo(String x)void foo(Object x) every invocation handled by foo(String) could be handled by foo(Object) , but the reverse is not the case. (For example, you could call foo(new Object()) and that couldn't be handled by foo(String) .)
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/38979801', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/702948/']}
|
jdg_373760
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
24627616
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to use the autocorrection and shortcut list like default English keyboard with my custom keyboard.I check the in keyboard document but don't know how to use it. In keyboard documentation . Every custom keyboard (independent of the value of its RequestsOpenAccess key) has access to a basic autocorrection lexicon through the UILexicon class. Make use of this class, along with a lexicon of your own design, to provide suggestions and autocorrections as users are entering text. The UILexicon object contains words from various sources, including: Unpaired first names and last names from the user’s Address Book database Text shortcuts defined in the Settings > General > Keyboard > Shortcuts list A common words dictionary How to access shortcut list and input from our dictionary in Objective-C? How to use UILexicon with requestSupplementaryLexiconWithCompletion?
Now provide the response and nothing else.
|
Implementing the lexicon would look pretty much like this: Use requestSupplementaryLexiconWithCompletion() to get the lexicon upon launch once. Each type text is inputted add it to a NSString (tracking the current word) When user presses space (end of curent word) check the string against the lexicon If it's a match count the number of characters and delete that number of characters Input the suggestion suggested by the lexicon Clear the string and start again Additionally you could also use UITextChecker to offer more advanced auto-correct features. Code (in Objective-C, this may not be 100% accurate I wrote in SO while on the bus but it should do): UILexicon *lexicon;NSString *currentString;-(void)viewDidLoad { [self requestSupplementaryLexiconWithCompletion:^(UILexicon *receivedLexicon) { self.lexicon = receivedLexicon; }];}-(IBAction)myTypingAction:(UIButton *)sender { [documentProxy insertText:sender.title]; [currentString stringByAppendingString:sender.title];}-(IBAction)space { [documentProxy insertText:@" "]; for (UILexiconEntry *lexiconEntry in lexicon.entries) { if (lexiconEntry.userInput isEqualToString:currentString) { for (int i = 0; currentString.length >=i ; i++) { [documentProxy deleteTextBackwards]; } [documentProxy insertText:lexiconEntry.documentText]; currentString = @""; } } } Feel free to comment if you have any more questions. Source: Personal experience with iOS 8 keyboards and UILexicon
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24627616', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1847431/']}
|
jdg_373761
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
52720
|
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:
Psiram has a page about conspiracy theories around covid vaccines and them supposedly containing graphene oxide and graphene hydroxide. They link to credible sources debunking the claim that vaccines contain graphene oxide, but their section on graphene hydroxide is unsourced: Im November 2021 verbreitete der deutsche Chemiker Andreas Noack die Verschwörungstheorie, dass Hersteller von Corona-Impfstoffen heimlich ihren Impfstoffen Graphenhydroxid beimischten. Das angeblich verimpfte Graphenhydroxid verhalte sich im menschlichen Körper wie ein "molekulares Rasiermesser" und schade dem Organismus. Der Erzählung nach handele es sich um eine nur ein Atom starke "Klinge aus Kohlenstoff", die der menschliche Körper nicht abbauen können, und die daher im Körper verbleibe. My translation: In November 2021, the German chemist Andreas Noack spread the conspiracy theory that producers of Corona vaccines secretly add graphene hydroxide to their vaccines. The supposedly used graphene hydroxide behaves like 'molecular razors' in the human body that the body can't break down, and which thus stays in the body. What is the evidence and how valid is this claim?
Now provide the response and nothing else.
|
The evidence is very questionable and does not support the claim. The linked source, and the claim, both attribute the discovery of the proof to Dr Pablo Campra Madrid , affiliated with the Universidad de Almería (UAL). This is a real person, and the report he published with his findings is available online. However, the linked source is dated Dec 1st, and the report was published on June 28th - and has be thoroughly debunked since then. The above debunkers are from Maldita.es, which describes itself as independent journalistic platform focused on the control of disinformation and public discourse through fact-checking and data journalism techniques The debunking was first published on Jul 2nd, updated with additional expert feedback on July 5th, and the current version is dated Nov 8th. Given the thorough debunking of Campra's already widely-circulated report, the claim that Dr Noack made ground-shaking revelations by revealing Dr. Campra's June 28th study on November 18th does not stand muster. For those who do not read Spanish, the main points of Maldita's analysis are: Dr Campra's report has not been peer-reviewed Its conclussions have been officially disavowed by the UAL Critically, the provenance and custody chain of the single sample analyzed by Dr. Campa are unknown. He claims to have received a refrigerated vial via courier on June 10th, but absolutely anything could be in that vial. Dr Campra claims, in his report, to have received the sample, and a request to analyze it, from Ricardo Delgado Martín, who has participated in previous vaccine-disinformation efforts . Dr Campra uses spectrophotometry to assess the contents of the vial. This technique uses the fact that different compounds absorbs different wavelengths of light in different amounts. RGO presents an absorption peak at 270nm, while peak absorption in the sample was observed between 260-270nm. This is compatible with there being RGO in the sample -- but it is also compatible with a host of alternative explanations, including the fact that nucleic acids (such as the mRNA that the vaccine is known for) have their peak absorption rates between 260-280nm. Therefore, spectrophotometry results are far from conclusive . Dr Campra also uses fluorimetric spectrophotography to quantify the quantity of RNA found in the sample. However, he appears to not have followed lab protocols requiring calibration of the Qubit 2.0 fluorometer prior to use; so the low amounts of RNA reported could be explained by improper measurement or measurement error . Finally, Dr Campra also uses optical and electromicroscopy to attempt to visually identify RGO in the sample. However, as noted by several quoted experts images included in the report and identified as RGO by Dr. Campra could correspond to many alternative nanometric polimeric structures . Therefore, if the proof of the claim submitted by OP is to be found in Campra's report, there is no solid evidence to support the presence of RGO in Pfizer's vaccine .
|
{}
|
{'log_upvote_score': 6, 'links': ['https://skeptics.stackexchange.com/questions/52720', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/61452/']}
|
jdg_373762
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2783
|
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
What are the tell-tale signs that a Linux server has been hacked? Are there any tools that can generate and email an audit report on a scheduled basis?
Now provide the response and nothing else.
|
Keep a pristine copy of critical system files (such as ls, ps, netstat, md5sum) somewhere, with an md5sum of them, and compare them to the live versions regularly. Rootkits will invariably modify these files. Use these copies if you suspect the originals have been compromised. aide or tripwire will tell you of any files that have been modified - assuming their databases have not been tampered with. Configure syslog to send your logfiles to a remote log server where they can't be tampered with by an intruder. Watch these remote logfiles for suspicious activity read your logs regularly - use logwatch or logcheck to synthesize the critical information. Know your servers . Know what kinds of activities and logs are normal.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://serverfault.com/questions/2783', 'https://serverfault.com', 'https://serverfault.com/users/1532/']}
|
jdg_373763
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12031613
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm having difficulty using the CITEXT datatype in PostgreSQL using JPA and Hibernate. CITEXT is supposed to provide a case insensitive text datatype but when used with JPA/Hibernate it doesn't behave in a case insensitive manner. Has anyone else had this issue or know a way around it? I have seen some mention (but very, very little) about a JDBC issue, but that went back at least a year and wasn't very clear. I have a 'nickname' column defined as citext in postgres 9.1. I just did a test to see if it could find a row using a named query as such: create table test( nickname citext)@NamedQuery(name = "Person.findByNickname", query = "SELECT p FROM Person p WHERE p.nickname = :nickname") Insert a nickname into the DB: insert into test values('testNick') Then run this code: String nickname = "testNick";Query q = em.createNamedQuery("Person.findByNickname");q.setParameter("nickname", nickname);if (q.getResultList().isEmpty()) { return (false);}return (true); This returns 'true' (i.e. there is already a 'testNick' in the database). If I make this assignment String nickname = "testnick"; //(lower case 'N') and run it again it returns 'false'. Since the column is CITEXT, it should return 'true' again. i.e. case insensitive text. Using JPA and Hibernate. Anyone have any thoughts? In the meantime I've changed the column back to varchar and created a functional index for lowercase. And I have to create a native query now to search using database functions. Would like to find out if there is a way I can not have to do this to maintain the database abstraction. Regards.
Now provide the response and nothing else.
|
citext provides case-insensitive operators for use within the database, with other citext values . What's happening At a guess, your JPA implementation is explicitly specifying the type of the parameter as text when it creates the parameterized statement. citext doesn't define a citext = text operator, so PostgreSQL casts the citext to text and uses the case-sensitive text = text operator. Effectively, comparing citext to text is case sensitive. Here's what I think is happening. Given the dummy data: regress=# CREATE EXTENSION citext;regress=# CREATE TABLE citest ( x citext );regress=# INSERT INTO citest(x) VALUES ('FRED'), ('FrEd');regress=# SELECT * FROM citest; x ------ FRED FrEd(2 rows) ... a comparison of citext to an unknown string literal will be interpreted as citext=citext and be done case-insensitively: regress=# SELECT * FROM citest WHERE x = 'FRED'; x ------ FRED FrEd(2 rows) ... but a comparison between citext and an explicitly text typed literal will convert the citext argument to text using citext 's implicit cast to text, then do a text=text case sensitive comparison: regress=# SELECT * FROM citest WHERE x = 'FRED'::text; x ------ FRED(1 row) Or rather, what Hibernate is doing will be closer to: regress=# PREPARE blah(text) AS SELECT * FROM citest WHERE x = $1;PREPAREregress=# EXECUTE blah('FRED'); x ------ FRED(1 row) where the type is specified as text when binding a parameter, since Hibernate "knows" that Strings are text . In other words, you need to get Hibernate to, via PgJDBC, explicitly specify the citext datatype as the parameter type to your query, resulting in something like: regress=# PREPARE blah(citext) AS SELECT * FROM citest WHERE x = $1;PREPAREregress=# EXECUTE blah('FRED'); x ------ FRED FrEd(2 rows) Note the explicit citext type parameter to the prepared statement. That will be ... interesting ... to do, especially since PgJDBC doesn't know anything about the citext type. You'd have to write a custom data type handler for Hibernate that uses PgJDBC's setObject ; even then you'll have operator consistency issues between Java and Pg (see below). IMO you'll be much better off using traditional case sensitive types and lower() , ILIKE , etc. It's also possible that Hibernate is relying on what PgJDBC tells it about column case sensitivity. At least as of 9.2-devel PgJDBC doesn't know anything about the citext type, so it'll always say "yup, that's case sensitive" when asked. Tracing It's hard to be sure that's what's happening without seeing the actual queries run by JPA. Try setting log_statement = 'all' in postgresql.conf . Then SIGHUP the postmaster, use pg_ctl reload , or restart Pg to cause the change to take effect. Re-run your test and examine the logs. Test the queries you see in psql to observe the results. If you're unsure what's going on, update your question with them. If you update also include your Hibernate version and your PgJDBC version. It's also possible that Hibernate is relying on what PgJDBC tells it about column case sensitivity. At least as of 9.2-devel PgJDBC doesn't know anything about the citext type, so it'll always say "yup, that's case sensitive" when asked. Operator consistency difficulties WARNING : The citext type cannot affect how Hibernate works with the text once it's come out of the database. It won't have any effect on the String.equals method, for example. You would need to tell Hibernate you want it to treat the text as case insensitive. Otherwise if you have a text or varchar primary/foreign key you can get situations where the Hibernate asks for the key "FRED" , it gets "FrEd" back, and is quite confused because the DB returned a key that isn't equal - according to Hibernate - to the one it was asked for. Similar oddities will occur if you include citext -backed strings in equals and hashCode implementations in your entities. Unfortunately JPA doesn't seem to specify annotation attributes in the @Column mapping for whether the column is case sensitive or not. Java doesn't have the concept of a case-insensitive string data type anyway, so it wouldn't do tons of good even if JPA did specify it. You'll probably avoid confusing Hibernate too badly so long as you don't use citext for keys or include citext values in equals and hashCode .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12031613', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/617964/']}
|
jdg_373764
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8990387
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Sometimes when using ipython you might hit an exception in a function which has opened a file in write mode. This means that the next time you run the function you get a value error, ValueError: The file 'filename' is already opened. Please close it before reopening in write mode. However since the function bugged out, the file handle (which was created inside the function) is lost, so it can't be closed. The only way round it seems to be to close the ipython session, at which point you get the message: Closing remaining open files: filename... done Is there a way to instruct ipython to close the files without quitting the session?
Now provide the response and nothing else.
|
You should try to always use the with statement when working with files. For example, use something like with open("x.txt") as fh: ...do something with the file handle fh This ensures that if something goes wrong during the execution of the with block, and an exception is raised, the file is guaranteed to be closed. See the with documentation for more information on this. Edit : Following a discussion in the comments, it seems that the OP needs to have a number of files open at the same time and needs to use data from multiple files at once. Clearly having lots of nested with statements, one for each file opened, is not an option and goes against the ideal that "flat is better than nested". One option would be to wrap the calculation in a try / finally block. For example file_handles = []try: for file in file_list: file_handles.append(open(file)) # Do some calculations with open filesfinally: for fh in file_handles: fh.close() The finally block contains code which should be run after any try , except or else block, even if an exception occured. From the documentation : If finally is present, it specifies a "cleanup" handler. The try clause is executed, including any except and else clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The finally clause is executed. If there is a saved exception, it is re-raised at the end of the finally clause. If the finally clause raises another exception or executes a return or break statement, the saved exception is lost. The exception information is not available to the program during execution of the finally clause.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8990387', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1038264/']}
|
jdg_373765
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17446981
|
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 are proper way to find a library (via FindPackage() ) which was built with ExternalProject_Add() ? The problem is that CMake cannot find the library at CMake-time because the external library gets build at compile time. I know that it is possible to combine these two CMake function when building the library and the project in a superbuild but I want to use it in a normal CMake project. In fact I would like to build VTK 6 with ExternalProject_Add and find it with FindPackage all inside my CMake project.
Now provide the response and nothing else.
|
there is a way to do this. but it´s kind of hackish.you basically add a custom target, that reruns cmake during build. you will have to try this in a small test project, to decide if it works for you find_package(Beaengine)############################################## BeaEngine#include(ExternalProject)externalproject_add(BeaEngine SOURCE_DIR ${PROJECT_SOURCE_DIR}/beaengine SVN_REPOSITORY http://beaengine.googlecode.com/svn/trunk/ CMAKE_ARGS -DoptHAS_OPTIMIZED=TRUE -DoptHAS_SYMBOLS=FALSE -DoptBUILD_64BIT=FALSE -DoptBUILD_DLL=FALSE -DoptBUILD_LITE=FALSE INSTALL_COMMAND "" )if(NOT ${Beaengine_FOUND}) #rerun cmake in initial build #will update cmakecache/project files on first build #so you may have to reload project after first build add_custom_target(Rescan ${CMAKE_COMMAND} ${CMAKE_SOURCE_DIR} DEPENDS BeaEngine)else() #Rescan becomes a dummy target after first build #this prevents cmake from rebuilding cache/projects on subsequent builds add_custom_target(Rescan)endif()add_executable(testapp testapp.cpp )add_dependencies(testapp Rescan)if(${Beaengine_FOUND}) target_link_libraries(testapp ${Beaengine_LIBRARY})endif() this seems to work well for mingw makefiles / eclipse makefile projects.vs will request to reload all projects after first build.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17446981', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/80480/']}
|
jdg_373766
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2717445
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $f:\mathbb{R} \to \mathbb{R}$ be a differentiable function. Let $a \in \mathbb{R}$ and define the following sets: \begin{align*}M= \{x>a \mid f(t)>f(a), \forall t \in (a,x] \}\\N=\{x>a \mid f(t)=f(a), \forall t \in (a,x] \}\\P=\{x>a \mid f(t)<f(a), \forall t \in (a,x] \}\end{align*} Prove that at least one of these sets is not empty. I tried to prove this by contradiction. If they were all empty, then, for all $n \in \mathbb{N}_{\geq 1}$ there would be some numbers $a_n,b_n,c_n \in (a,a+\frac{1}{n})$ such that $f(a_n) \leq f(a), \: f(b_n) \neq f(a)$ and $f(c_n) \geq f(a)$. But these sequences that are formed seem independent, and I couldn't connect them such that I reach a contradiction. The fact that at least one of these sets is not empty is pretty obvious on a graph, but I didn't manage to prove it rigorously. I think I'm missing something obvious. Edit : Thank you for your counterexamples! As mentioned in one of the comments, I added the differentiability of the function.
Now provide the response and nothing else.
|
If you take $f(x)=\begin{cases}x^2\sin(1/x),& x\neq0\\0,& x=0\end{cases}$and take $a=0$, then for all $x>0$, there are values of $t_1,t_2,t_3\in(0,x]$ such that $f(t_1)>0=f(0)$, such that $f(t_2)=0=f(0)$ and such that $f(t_3)<0=f(0)$, respectively. Therefore $M,N,P$ are empty. Observe that $f$ is even differentiable at all points. Therefore, even for differentiable it is not true . One can even have $f$ smooth. For example, replace the $x^2$ above with $e^{-1/x^2}$ and the function will be smooth, but still have the same oscillatory behavior near $x=0$.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2717445', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/436975/']}
|
jdg_373767
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14551387
|
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 my Schema: var userschema = new mongoose.Schema({ user: String, follow: [String], imagen: [{ title: String, date: { type: Date, default: Date.now } }] }); And this is the code: usermodel.findOne({ user: req.session.user }, function (err, user){ usermodel.aggregate({$unwind: '$imagen'}, {$match: { _id: { $in: user.follow } }}, {imagen: true}, {$sort: {'imagen.date': 1}}, function (err, images){ console.log(images); res.render('home.ejs', { user: user, following: images }); }); }); The follow contains users's _id . The code works, except when I include the $match . I use the $match to filter the result, only getting the images of the user that I'm following, but the console.log show me that the result of the aggregate search is undefined, but when I don't write the $match query, I get the images, but I obtain all the images, not only the images of the user that I'm following. Is there any solution for this...? Thank's advance! EDIT: var express = require('express');var MongoStore = require('connect-mongo')(express);var fs = require('fs');var mongoose = require('mongoose');var app = express();app.listen(9191);var sessionStore = new MongoStore({db: 'session'});app.configure(function(){ app.use(express.bodyParser()); app.set('views',__dirname + '/views'); app.set('view engine', 'ejs'); app.use(express.static(__dirname + '/public')); app.use(express.cookieParser()); app.use(express.session({ store: sessionStore, secret: 'secret' })); app.use(app.router);});var db = mongoose.createConnection('localhost', 'test');var userschema = new mongoose.Schema({ user: String, follow: [String], imagen: [{ title: String, date: { type: Date, default: Date.now } }] });var usermodel = db.model('usermodel', userschema);var ObjectId = require('mongoose').Types.ObjectId;app.get('/', middleware.noses, function (req, res){ res.render('home0.ejs');});app.get('/home', middleware.yeses, function (req, res){ usermodel.findOne({ user: req.session.user }, function (err, user){ if (user.follow.length != 0){ usermodel.find({ _id: {$in: user.follow } }, { user: true }, function (err, users){ var usernames = users.map(function(u){ return u.user }); usermodel.aggregate({$match: { _id: { $in: user.follow.map( function(id){ return new ObjectId(id); })}}}, {$unwind: '$imagen'}, {imagen: true}, {$sort: {'imagen.date': 1}}, function (err, images){ console.log(images); res.render('home.ejs', { user: user, following: images }); }); }); } else { res.render('home.ejs', { user: user, following: undefined }); } });}); EDIT: [ { __v: 4, _id: 50fd9c7b8e6a9d087d000006, follow: ['50fd9cbd1322de627d000006', '50fd9d3ce20da1dd7d000006'], imagen: [{ title: 'foo', _id: 50fd9ca2bc9f163e7d000006, date: Mon Jan 21 2013 20:53:06 GMT+0100 (CET) }, { title: 'foot', _id: 50fda83a3214babc88000005, date: Mon Jan 21 2013 21:42:34 GMT+0100 (CET) }], user: 'Mrmangado' }
Now provide the response and nothing else.
|
Mongoose doesn't do any schema-based casting of the arguments of aggregate , so you need to convert your user.follow array of string ids into an array of ObjectIds in the $match : {$match: { _id: { $in: user.follow.map(function(id){ return new mongoose.Types.ObjectId(id); })}}}, NOTE: Do not use mongoose.Schema.Types.ObjectId for casting. It will not work. You should also move this $match to the beginning of the pipeline for efficiency. UPDATE Your other problem is you need to use a $project operator instead of just including a plain {imagen: true} object in the pipeline. Putting it all together and reordering for a more efficient pipeline, this worked for me with your data: usermodel.aggregate( {$match: { _id: { $in: user.follow.map(function(id){ return new mongoose.Types.ObjectId(id); }) }}}, {$project: {imagen: true}}, {$unwind: '$imagen'}, {$sort: {'imagen.date': 1}}, function (err, images){ ...
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14551387', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1913693/']}
|
jdg_373768
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
63046397
|
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 C++17 if constexpr for conditional compilation, but it does not behave the way I expect. For example, with the code below, C++ still compiles the code defined by the macro X2 , #include <map>#include <string>#include <iostream>#include <type_traits>#define X1 pp("x")#define X2 pp("x", "x")void pp(const std::string str){ std::cout << str << std::endl;}int main(){ std::map<std::string, int> map; if constexpr (std::is_null_pointer_v<decltype(map)>) X2; else X1;} and spits out this error messages: 1.c:6:23: error: too many arguments to function ‘void pp(std::__cxx11::string)’ #define X2 pp("x", "x") ^1.c:18:3: note: in expansion of macro ‘X2’ X2; ^~ How can I skip compilation of X2?
Now provide the response and nothing else.
|
This is not possible outside the template! From cppreference.com Outside a template, a discarded statement is fully checked. if constexpr is not a substitute for the #if preprocessing directive: void f() { if constexpr(false) { int i = 0; int *p = i; // Error even though in discarded statement }} Any idea how to skip compilation of X2 ? One option is to provide a template function for that. template<typename T>void test(){ if constexpr (std::is_null_pointer_v<T>) X2; else X1;}int main(){ std::map<std::string, int> map; test<decltype(map)>(); // now chooses the X1} Thanks to @HolyBlackCat and @MSalters . As they pointed out, the above solution is ill-formed NDR (therefore, compiling with MSVC compiler does not make any sense and on the other handthe GCC and clang at least catch this by providing some compiler errors )which has been detailed in the @HolyBlackCat 's,answer! Therefore can we skip the compilation of X2 ? Unfortunately, NO as per your code!!The preprocessor will be executed before the compilation of the translation unit.Therefore one can not provide the type information (i.e. decltype(map) ) to #if directives.Hence for your case, there is no other way. Good lessons from this post : Your program is, however, is a good example to avoid such kind macroand constexpr if mixing. Secondly, check the correctness of the code by differentcompilers if possible! I would suggest having a function overload for PP (and of course there are many other ways) to your case, by which you could get a well-formed code: See a demo . #include <string>#include <iostream>#include <type_traits>#include <map>void pp(const std::string& str){ std::cout << str << std::endl;}template<typename... T> void pp(const T&... args){ // do something with args!}template<typename T>constexpr void test(){ if constexpr (std::is_null_pointer_v<T>) pp("x", "x"); // call with args else pp("x"); // call with string}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/63046397', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/340851/']}
|
jdg_373769
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
187761
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
POSIX allows mutexes to be recursive. That means the same thread can lock the same mutex twice and won't deadlock. Of course it also needs to unlock it twice, otherwise no other thread can obtain the mutex. Not all systems supporting pthreads also support recursive mutexes, but if they want to be POSIX conform, they have to . Other APIs (more high level APIs) also usually offer mutexes, often called Locks. Some systems/languages (e.g. Cocoa Objective-C) offer both, recursive and non recursive mutexes. Some languages also only offer one or the other one. E.g. in Java mutexes are always recursive (the same thread may twice "synchronize" on the same object). Depending on what other thread functionality they offer, not having recursive mutexes might be no problem, as they can easily be written yourself (I already implemented recursive mutexes myself on the basis of more simple mutex/condition operations). What I don't really understand: What are non-recursive mutexes good for? Why would I want to have a thread deadlock if it locks the same mutex twice? Even high level languages that could avoid that (e.g. testing if this will deadlock and throwing an exception if it does) usually don't do that. They will let the thread deadlock instead. Is this only for cases, where I accidentally lock it twice and only unlock it once and in case of a recursive mutex, it would be harder to find the problem, so instead I have it deadlock immediately to see where the incorrect lock appears? But couldn't I do the same with having a lock counter returned when unlocking and in a situation, where I'm sure I released the last lock and the counter is not zero, I can throw an exception or log the problem? Or is there any other, more useful use-case of non recursive mutexes that I fail to see? Or is it maybe just performance, as a non-recursive mutex can be slightly faster than a recursive one? However, I tested this and the difference is really not that big.
Now provide the response and nothing else.
|
The difference between a recursive and non-recursive mutex has to do with ownership. In the case of a recursive mutex, the kernel has to keep track of the thread who actually obtained the mutex the first time around so that it can detect the difference between recursion vs. a different thread that should block instead. As another answer pointed out, there is a question of the additional overhead of this both in terms of memory to store this context and also the cycles required for maintaining it. However , there are other considerations at play here too. Because the recursive mutex has a sense of ownership, the thread that grabs the mutex must be the same thread that releases the mutex. In the case of non-recursive mutexes, there is no sense of ownership and any thread can usually release the mutex no matter which thread originally took the mutex. In many cases, this type of "mutex" is really more of a semaphore action, where you are not necessarily using the mutex as an exclusion device but use it as synchronization or signaling device between two or more threads. Another property that comes with a sense of ownership in a mutex is the ability to support priority inheritance. Because the kernel can track the thread owning the mutex and also the identity of all the blocker(s), in a priority threaded system it becomes possible to escalate the priority of the thread that currently owns the mutex to the priority of the highest priority thread that is currently blocking on the mutex. This inheritance prevents the problem of priority inversion that can occur in such cases. (Note that not all systems support priority inheritance on such mutexes, but it is another feature that becomes possible via the notion of ownership). If you refer to classic VxWorks RTOS kernel, they define three mechanisms: mutex - supports recursion, and optionally priority inheritance. This mechanism is commonly used to protect critical sections of data in a coherent manner. binary semaphore - no recursion, no inheritance, simple exclusion, taker and giver does not have to be same thread, broadcast release available. This mechanism can be used to protect critical sections, but is also particularly useful for coherent signalling or synchronization between threads. counting semaphore - no recursion or inheritance, acts as a coherent resource counter from any desired initial count, threads only block where net count against the resource is zero. Again, this varies somewhat by platform - especially what they call these things, but this should be representative of the concepts and various mechanisms at play.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/187761', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15809/']}
|
jdg_373770
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
32749148
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Assume we have a collection of objects that are identified by unique String s, along with a class Tree that defines a hierarchy on them. That class is implemented using a Map from nodes (represented by their IDs) to Collection s of their respective children's IDs. class Tree { private Map<String, Collection<String>> edges; // ... public Stream<String> descendants(String node) { // To be defined. }} I would like to enable streaming a node's descendants. A simple solution is this: private Stream<String> children(String node) { return edges.getOrDefault(node, Collections.emptyList()).stream();}public Stream<String> descendants(String node) { return Stream.concat( Stream.of(node), children(node).flatMap(this::descendants) );} Before continuing, I would like to make the following assertions about this solution. (Am I correct about these?) Walking the Stream returned from descendants consumes resources (time and memory) – relative to the size of the tree – in the same order of complexity as hand-coding the recursion would. In particular, the intermediate objects representing the iteration state ( Stream s, Spliterator s, ...) form a stack and therefore the memory requirement at any given time is in the same order of complexity as the tree's depth. As I understand this , as soon as I perform a terminating operation on the Stream returned from descendants , the root-level call to flatMap will cause all contained Stream s – one for each (recursive) call to descendants – to be realized immediately. Thus, the resulting Stream is only lazy on the first level of recursion, but not beyond. (Edited according to Tagir Valeevs answer .) If I understood these points correctly, my question is this: How can I define descendants so that the resulting Stream is lazy? I would like the solution to be as elegant as possible, in the sense that I prefer a solution which leaves the iteration state implicit. (To clarify what I mean by that: I know that I could write a Spliterator that walks the tree while maintaining an explicit stack of Spliterator s on each level. I would like to avoid that.) (Is there possibly a way in Java to formulate this as a producer-consumer workflow, like one could use in languages like Julia and Go?)
Now provide the response and nothing else.
|
To me, your solution is already as elegant as possible and the limited laziness of it not your fault. The simplest solution is to wait until it gets fixed by the JRE developers. It has been done with Java 10 . However, if this limited laziness of today’s implementation really is a concern, it’s perhaps time to solve this in a general way. Well, it is about implementing a Spliterator , but not specific to your task. Instead, it’s a re-implementation of the flatmap operation serving all cases where the limited laziness of the original implementation matters: public class FlatMappingSpliterator<E,S> extends Spliterators.AbstractSpliterator<E>implements Consumer<S> { static final boolean USE_ORIGINAL_IMPL = Boolean.getBoolean("stream.flatmap.usestandard"); public static <T,R> Stream<R> flatMap( Stream<T> in, Function<? super T,? extends Stream<? extends R>> mapper) { if(USE_ORIGINAL_IMPL) return in.flatMap(mapper); Objects.requireNonNull(in); Objects.requireNonNull(mapper); return StreamSupport.stream( new FlatMappingSpliterator<>(sp(in), mapper), in.isParallel() ).onClose(in::close); } final Spliterator<S> src; final Function<? super S, ? extends Stream<? extends E>> f; Stream<? extends E> currStream; Spliterator<E> curr; private FlatMappingSpliterator( Spliterator<S> src, Function<? super S, ? extends Stream<? extends E>> f) { // actually, the mapping function can change the size to anything, // but it seems, with the current stream implementation, we are // better off with an estimate being wrong by magnitudes than with // reporting unknown size super(src.estimateSize()+100, src.characteristics()&ORDERED); this.src = src; this.f = f; } private void closeCurr() { try { currStream.close(); } finally { currStream=null; curr=null; } } public void accept(S s) { curr=sp(currStream=f.apply(s)); } @Override public boolean tryAdvance(Consumer<? super E> action) { do { if(curr!=null) { if(curr.tryAdvance(action)) return true; closeCurr(); } } while(src.tryAdvance(this)); return false; } @Override public void forEachRemaining(Consumer<? super E> action) { if(curr!=null) { curr.forEachRemaining(action); closeCurr(); } src.forEachRemaining(s->{ try(Stream<? extends E> str=f.apply(s)) { if(str!=null) str.spliterator().forEachRemaining(action); } }); } @SuppressWarnings("unchecked") private static <X> Spliterator<X> sp(Stream<? extends X> str) { return str!=null? ((Stream<X>)str).spliterator(): null; } @Override public Spliterator<E> trySplit() { Spliterator<S> split = src.trySplit(); if(split==null) { Spliterator<E> prefix = curr; while(prefix==null && src.tryAdvance(s->curr=sp(f.apply(s)))) prefix=curr; curr=null; return prefix; } FlatMappingSpliterator<E,S> prefix=new FlatMappingSpliterator<>(split, f); if(curr!=null) { prefix.curr=curr; curr=null; } return prefix; }} All you need for using it, is to add a import static of the flatMap method to your code and change expressions of the form stream.flatmap(function) to flatmap(stream, function) . I.e. in your code public Stream<String> descendants(String node) { return Stream.concat( Stream.of(node), flatMap(children(node), this::descendants) );} then you have full lazy behavior. I tested it even with infinite streams… Note that I added a toggle to allow turning back to the original implementation, e.g. when specifying -Dstream.flatmap.usestandard=true on the command line.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32749148', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4235730/']}
|
jdg_373771
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
19316729
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've got this strange issue, ViewPager 's setCurrentItem(position, false) works perfectly fine, then im switching to another activity, and after I'm back to the first activity, the ViewPager always ends up on the first item. Even though I've added setCurrentItem to onResume method it still ignores it. It's not even throwing any exception when I'm trying to set item to out of bounds index.Though later on when I call this method, when the button "next" is tapped, it works like expected.Checked my code 10 times for any possible calls to setCurrentItem(0) or something but it's just not there at all.
Now provide the response and nothing else.
|
i can't really answer WHY exactly this happens, but if you delay the setCurrentItem call for a few milliseconds it should work. My guess is that because during onResume there hasn't been a rendering pass yet, and the ViewPager needs one or something like that. private ViewPager viewPager;@Overridepublic void onResume() { final int pos = 3; viewPager.postDelayed(new Runnable() { @Override public void run() { viewPager.setCurrentItem(pos); } }, 100);} UPDATE: story time so today i had the problem that the viewpager ignored my setCurrentItem action, and i searched stackoverflow for a solution. i found someone with the same problem and a fix; i implemented the fix and it didn't work. whoa! back to stackoverflow to downvote that faux-fix-provider, and ... it was me. i implemented my own faulty non-fix, which i came up with the first time i stumbled over the problem (and which was later forgotten). i'll now have to downvote myself for providing bad information. the reason my initial "fix" worked was not because of of a "rendering pass"; the problem was that the pager's content was controlled by a spinner. both the spinners and the pagers state were restored onResume, and because of this the spinners onItemSelected listener was called during the next event propagation cycle, which did repopulate the viewpager - this time using a different default value. removing and resetting the listener during the initial state restoration fixed the issue. the fix above kind-of worked the first time, because it set the pagers current position after the onItemSelected event fired. later, it ceased to work for some reason (probably the app became too slow - in my implementation i didn't use 100ms, but 10ms). i then removed the postDelayed in a cleanup cycle, because it didn't change the already faulty behaviour. update 2: i can't downvote my own post. i assume, honorable seppuku is the only option left.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/19316729', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1297987/']}
|
jdg_373772
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
41085189
|
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 came across this construct in an Angular example and I wonder why this is chosen: _ => console.log('Not using any parameters'); I understand that the variable _ means don't care/not used but since it is the only variable is there any reason to prefer the use of _ over: () => console.log('Not using any parameters'); Surely this can't be about one character less to type. The () syntax conveys the intent better in my opinion and is also more type specific because otherwise I think the first example should have looked like this: (_: any) => console.log('Not using any parameters'); In case it matters, this was the context where it was used: submit(query: string): void { this.router.navigate(['search'], { queryParams: { query: query } }) .then(_ => this.search());}
Now provide the response and nothing else.
|
The reason why this style can be used (and possibly why it was used here) is that _ is one character shorter than () . Optional parentheses fall into the same style issue as optional curly brackets . This is a matter of taste and code style for the most part, but verbosity is favoured here because of consistency. While arrow functions allow a single parameter without parentheses, it is inconsistent with zero, single destructured, single rest and multiple parameters: let zeroParamFn = () => { ... };let oneParamFn = param1 => { ... };let oneParamDestructuredArrFn = ([param1]) => { ... };let oneParamDestructuredObjFn = ({ param1 }) => { ... };let twoParamsFn = (param1, param2) => { ... };let restParamsFn = (...params) => { ... }; Although is declared but never used error was fixed in TypeScript 2.0 for underscored parameters, _ can also trigger unused variable/parameter warning from a linter or IDE. This is a considerable argument against doing this. _ can be conventionally used for ignored parameters (as the other answer already explained). While this may be considered acceptable, this habit may result in a conflict with _ Underscore/Lodash namespace, also looks confusing when there are multiple ignored parameters. For this reason it is beneficial to have properly named underscored parameters (supported in TS 2.0), also saves time on figuring out function signature and why the parameters are marked as ignored (this defies the purpose of _ parameter as a shortcut): let fn = (param1, _unusedParam2, param3) => { ... }; For the reasons listed above, I would personally consider _ => { ... } code style a bad tone that should be avoided.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/41085189', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/365696/']}
|
jdg_373773
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2280496
|
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 any things to take care of when running your process or executable as service.Things like silent logging.Critical error reporting scenarios? etc? How do you handle it ?
Now provide the response and nothing else.
|
For critical error reporting, you are constrained to using the standard Service settings (in the properties of the installed service), or doing something yourself. This could be as simple a log file that logs unexpected errors (by using AppDomain.UnhandledException to catch and log them), using the Windows event log to log similar info, or having another process watch the service for errors (ie. the service stopping) and alerting someone. Microsoft has an article entitled " Introduction to Windows Service Applications " that is a good general introduction to making services in .Net. Some other things about developing Windows services from my experience: A Windows service is allowed about 30 seconds to start. After that, Windows will report it as not having started correctly. This means that you need to ensure that your OnStart method of the service kicks off a new thread to run the service and then returns. Don't expect any user interaction (ie. message boxes, confirmations) because the service runs "headless" (ie. without a UI), so you cannot expect a user to interact with it. Check the account that the service will run as to ensure that you are not running it as a user with unnecessarily high security privileges. Make extensive use of logging (eg. log4net) so that you can see what the service is doing during runtime, as well as being able to diagnose any errors (by logging stack traces). Make sure you use the correct version of InstallUtil (ie. 32 or 64 bit) to install the service with. Even better, let the service install itself using the ManagedInstallerClass.InstallHelper .
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2280496', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/39278/']}
|
jdg_373774
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
60794343
|
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 try to cast a String to a java.util.Date , the Java compiler catches the error. So why doesn't the compiler flag the following as an error? List<String> strList = new ArrayList<>(); Date d = (Date) strList; Of course, the JVM throws a ClassCastException at runtime, but the compiler doesn't flag it. The behavior is the same with javac 1.8.0_212 and 11.0.2.
Now provide the response and nothing else.
|
The cast is technically possible. It cannot easily be proven by javac that it is not so in your case and the JLS actually defines this as a valid Java program, so flagging an error would be incorrect. This is because List is an interface. So you could have a subclass of a Date that actually implements List disguised as List here - and then casting it to Date would be perfectly ok. For example: public class SneakyListDate extends Date implements List<Foo> { ...} And then: List<Foo> list = new SneakyListDate();Date date = (Date) list; // This one is valid, compiles and runs just fine Detecting such a scenario might not always be possible, as it would require runtime information if the instance is coming from, for example, a method instead. And even if, it would require much more effort for the compiler. The compiler only prevents casts that are absolutely impossible due to there being no way for the class-tree to match at all. Which is not the case here, as seen. Note that the JLS requires your code to be a valid Java program. In 5.1.6.1. Allowed Narrowing Reference Conversion it says: A narrowing reference conversion exists from reference type S to reference type T if all of the following are true : [...] One of the following cases applies : [...] S is an interface type, T is a class type, and T does not name a final class. So even if the compiler could figure out that your case is actually provably impossible, it is not allowed to flag an error because the JLS defines it as valid Java program. It would only be allowed to show a warning.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/60794343', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1313724/']}
|
jdg_373775
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
11921188
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Possible Duplicate: How to send Email Attachments with python I would like to edit the following code and send an email with an attachment. Attachment is a pdf file, it is under /home/myuser/sample.pdf, in linux environment. What should I change below? import smtplib fromaddr = 'myemail@gmail.com' toaddrs = 'youremail@gmail.com' msg = 'Hello' # Credentials (if needed) username = 'myemail' password = 'yyyyyy' # The actual mail send server = smtplib.SMTP('smtp.gmail.com:587') server.starttls() server.login(username,password) server.sendmail(fromaddr, toaddrs, msg) server.quit()
Now provide the response and nothing else.
|
You create a message with an email package in this case - from email.MIMEMultipart import MIMEMultipartfrom email.MIMEText import MIMETextfrom email.MIMEImage import MIMEImagemsg = MIMEMultipart()msg.attach(MIMEText(open("/home/myuser/sample.pdf").read())) and then send the message. import smtplibmailer = smtplib.SMTP()mailer.connect()mailer.sendmail(from_, to, msg.as_string())mailer.close() Several examples here - http://docs.python.org/library/email-examples.html UPDATE Updating the link since the above yields a 404 https://docs.python.org/2/library/email-examples.html . Thanks @Tshirtman Update2: Simplest way to attach pdf To attach the pdf use the pdf flag: def send_email_pdf_figs(path_to_pdf, subject, message, destination, password_path=None): ## credits: http://linuxcursor.com/python-programming/06-how-to-send-pdf-ppt-attachment-with-html-body-in-python-script from socket import gethostname #import email from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import smtplib import json server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() with open(password_path) as f: config = json.load(f) server.login('me@gmail.com', config['password']) # Craft message (obj) msg = MIMEMultipart() message = f'{message}\nSend from Hostname: {gethostname()}' msg['Subject'] = subject msg['From'] = 'me@gmail.com' msg['To'] = destination # Insert the text to the msg going by e-mail msg.attach(MIMEText(message, "plain")) # Attach the pdf to the msg going by e-mail with open(path_to_pdf, "rb") as f: #attach = email.mime.application.MIMEApplication(f.read(),_subtype="pdf") attach = MIMEApplication(f.read(),_subtype="pdf") attach.add_header('Content-Disposition','attachment',filename=str(path_to_pdf)) msg.attach(attach) # send msg server.send_message(msg) inspirations/credits to: http://linuxcursor.com/python-programming/06-how-to-send-pdf-ppt-attachment-with-html-body-in-python-script
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11921188', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/718762/']}
|
jdg_373776
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
33434
|
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
What is the maximum number of bytes for encrypting a plaintext message using RSA that is reasonably secure and also efficient and would AES be better for the same size in bytes? The encryption doesn't have to be public by the way, I'm just wondering if AES is just as good on a short message as it is on a large document. Basically the message or document would be sent encrypted but the key would never be made public. I guess that would also defeat the purpose of RSA but I've read a few times online that RSA is good for short messages and AES is good for long ones.
Now provide the response and nothing else.
|
RSA, as defined by PKCS#1 , encrypts "messages" of limited size. With the commonly used "v1.5 padding" and a 2048-bit RSA key, the maximum size of data which can be encrypted with RSA is 245 bytes. No more. When you "encrypt data with RSA", in practice, you are actually encrypting a random symmetric key with RSA, and then encrypt the data with a symmetric encryption algorithm, which is not limited in size. This is how it works in SSL , S/MIME , OpenPGP ... Regularly, some people suggest doing "RSA only" by splitting the input message into 245-byte chunks and encrypting each of them more or less separately. This is a bad idea because: There can be substantial weaknesses in how the data is split and then rebuilt. There is no well-studied standard for that. Each chunk, when encrypted, grows a bit (with a 2048-bit key, the 245 bytes of data become 256 bytes); when processing large amounts of data, the size overhead becomes significant. Decryption of a large message may become intolerably expensive. When encrypting data with a symmetric block cipher, which uses blocks of n bits, some security concerns begin to appear when the amount of data encrypted with a single key comes close to 2 n/2 blocks, i.e. n*2 n/2 bits. With AES, n = 128 (AES-128, AES-192 and AES-256 all use 128-bit blocks). This means a limit of more than 250 millions of terabytes, which is sufficiently large not to be a problem. That's precisely why AES was defined with 128-bit blocks, instead of the more common (at that time) 64-bit blocks: so that data size is practically unlimited.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://security.stackexchange.com/questions/33434', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/23786/']}
|
jdg_373777
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
271440
|
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 met an interesting issue about C#. I have code like below. List<Func<int>> actions = new List<Func<int>>();int variable = 0;while (variable < 5){ actions.Add(() => variable * 2); ++ variable;}foreach (var act in actions){ Console.WriteLine(act.Invoke());} I expect it to output 0, 2, 4, 6, 8. However, it actually outputs five 10s. It seems that it is due to all actions referring to one captured variable. As a result, when they get invoked, they all have same output. Is there a way to work round this limit to have each action instance have its own captured variable?
Now provide the response and nothing else.
|
Yes - take a copy of the variable inside the loop: while (variable < 5){ int copy = variable; actions.Add(() => copy * 2); ++ variable;} You can think of it as if the C# compiler creates a "new" local variable every time it hits the variable declaration. In fact it'll create appropriate new closure objects, and it gets complicated (in terms of implementation) if you refer to variables in multiple scopes, but it works :) Note that a more common occurrence of this problem is using for or foreach : for (int i=0; i < 10; i++) // Just one variableforeach (string x in foo) // And again, despite how it reads out loud See section 7.14.4.2 of the C# 3.0 spec for more details of this, and my article on closures has more examples too. Note that as of the C# 5 compiler and beyond (even when specifying an earlier version of C#), the behavior of foreach changed so you no longer need to make local copy. See this answer for more details.
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/271440', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/26349/']}
|
jdg_373778
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
28513738
|
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 ServiceWorker registered on my page and want to pass some data to it so it can be stored in an IndexedDB and used later for network requests (it's an access token). Is the correct thing just to use network requests and catch them on the SW side using fetch, or is there something more clever? Note for future readers wondering similar things to me: Setting properties on the SW registration object, e.g. setting self.registration.foo to a function within the service worker and doing the following in the page: navigator.serviceWorker.getRegistration().then(function(reg) { reg.foo; }) Results in TypeError: reg.foo is not a function . I presume this is something to do with the lifecycle of a ServiceWorker meaning you can't modify it and expect those modification to be accessible in the future, so any interface with a SW likely has to be postMessage style, so perhaps just using fetch is the best way to go...?
Now provide the response and nothing else.
|
So it turns out that you can't actually call a method within a SW from your app (due to lifecycle issues), so you have to use a postMessage API to pass serialized JSON messages around (so no passing callbacks etc). You can send a message to the controlling SW with the following app code: navigator.serviceWorker.controller.postMessage({'hello': 'world'}) Combined with the following in the SW code: self.addEventListener('message', function (evt) { console.log('postMessage received', evt.data);}) Which results in the following in my SW's console: postMessage received Object {hello: "world"} So by passing in a message (JS object) which indicates the function and arguments I want to call my event listener can receive it and call the right function in the SW. To return a result to the app code you will need to also pass a port of a MessageChannel in to the SW and then respond via postMessage, for example in the app you'd create and send over a MessageChannel with the data: var messageChannel = new MessageChannel();messageChannel.port1.onmessage = function(event) { console.log(event.data);};// This sends the message data as well as transferring messageChannel.port2 to the service worker.// The service worker can then use the transferred port to reply via postMessage(), which// will in turn trigger the onmessage handler on messageChannel.port1.// See https://html.spec.whatwg.org/multipage/workers.html#dom-worker-postmessagenavigator.serviceWorker.controller.postMessage(message, [messageChannel.port2]); and then you can respond via it in your Service Worker within the message handler: evt.ports[0].postMessage({'hello': 'world'});
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/28513738', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/842506/']}
|
jdg_373779
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
27526891
|
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 be able to add a watch task in gulp to all of the js files in the frontend/js and any other js files below gulp.watch('./frontend/js/**/*.js', ['browserify']); This will only target js files one folder deep
Now provide the response and nothing else.
|
It's supposed to match any number of subdirectories: ** If a "globstar" is alone in a path portion, then it matches zero or more directories and subdirectories searching for matches. It does not crawl symlinked directories. https://github.com/isaacs/node-glob Do you have symlinked directories in there? Symlinks I don't think you'll get gulp to natively traverse your symlinked directories. I recommend you take a look at node.js fs.readdir recursive directory search and see if any of those solutions can be applied to your use case. Nothing in the question or answers specifically addresses symlinks, so I don't know if there's a solution for you there or not. If you can get an array of dereferenced pathnames using one of those solutions, then you can just pass the array to gulp.src() .
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27526891', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/240363/']}
|
jdg_373780
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2460311
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In the decimal system of numeration the number of $6$-digit numbers in which the sum of the digits is divisible by $5$ is $$(A)\space180000 \space\space(B) \space540000\space\space (C) \space 5\times10^5\space \space (D) \space \text{none}$$ First, I noted that $a+b+c+d+e+f=5,10,15\dots50$ where $a\geq1$ and $ b, c, d, e, f\geq0$. From this I got $9C5 + 14C5 +...... 54C5$, which is just too hectic too calculate and I don't know it will give the right answer or not. Then I observed that there are $900000$ total possible numbers and if I divide it by $5$, I will get the correct answer which is $180000$. Is it a coincidence or is there any logic to it? What would be the proper method to solve this?
Now provide the response and nothing else.
|
Hint Suppose you have specified the first five digits of a six-digit number. How many choices are there for the sixth digit such that the sum of all six digits is divisible by $5$?
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2460311', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/459365/']}
|
jdg_373781
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
241888
|
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:
From what I found out until now: A layer in a neural network consists of a parameterizable number of neurons. A neural network consists of multiple layers. A neuron consists of a function f(x1, x2, ..., xn), a sigmoid function which uses f as input and gives a binary output and a weight factor which is multiplied with with the sigmoid function and determines how much this neuron is considered for the output of the layer. Is this correct and what is the function f/how does it combine the inputs to the output? (I tried to read the literature and some course material myself but they all either ignore this part/call it a black box or assume you have a PhD in Theoretical Math but my university only focused on Applied Informatics. So if you have literature understandable for someone like me I would also appreciate it)
Now provide the response and nothing else.
|
You are correct in your overall view of the subject. The neuron is nothing more than a set of inputs, a set of weights, and an activation function. The neuron translates these inputs into a single output, which can then be picked up as input for another layer of neurons later on. While details can vary between neural networks, the function $f(x_1, x_2, \ldots , x_n)$ is often just a weighted sum:$$f(x_1, x_2, \ldots , x_n) = w_1\cdot x_1 + w_2\cdot x_2 + ... + w_n\cdot x_n$$Each neuron has a weight vector $w = (w_1, w_2, ..., w_n)$, where $n$ is the number of inputs to that neuron. These inputs can be either the 'raw' input features — say temperature, precipitation, and wind speed for a weather model — or the output of neurons from an earlier layer. The weights for each neuron are turned during the training stage such that the final network output is biased toward some value (usually 1) for signal, and another (usually -1 or 0) for background. Non-linear behavior in a neural network is accomplished by use of an activation function (often a sigmoid function) to which the output of $f$ is passed and modified. This allows neural networks to describe more complicated systems while still combining inputs in a simple fashion. I found the Deep Learning in a Nutshell series by Tim Dettmers to be a very approachable introduction to the subject of machine learning in general.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/241888', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/135876/']}
|
jdg_373782
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
180061
|
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 $D\subseteq\mathbb C $ be a connected set and consider $f,g\in\mathcal M(D)$.The ratio $r=\frac{f}{g}$ has the pole set $P(r)\subseteq P(f)\cup Z(g)$ (where $Z()$ is the set of all zeros). Why is $P(r) $ discrete in $D$ ? I think that disjoint union of discrete sets isn't discrete, consider for example $$\{0\}\cup\big\{\frac{1}{n} : n\in\mathbb N\big\}$$
Now provide the response and nothing else.
|
The pole set or zero set of a nonzero meromorphic function is not only discrete, it is also closed (meromorphic functions are continuous !), which eliminates your example. The closed and discrete subsets of $\mathbb C$ can also be described by the property that their intersection with any compact subset of $\mathbb C$ is finite.Then it is obvious that the reunion of two such subsets is again closed and discrete. Suppose $S$ is closed and discrete, and let $K$ be a compact subset of $\mathbb C$.Since $S$ is discrete, for each element $x \in S \cap K$, there is an open $U_x$ of $K$ containing $x$ such that $U_x \cap S = \{ x \}$. Since $S$ is closed, $K \setminus S$ is an open of $K$. Then, we have that $K \setminus S$ together with all the $U_x$ form an open cover of $K$. Since $K$ is compact, we can extract a finite subcover. But for each $x \in S \cap K$, $U_x$ was the only open containing $x$ so this finite cover still has to contain every $U_x$, thus there were finitely many $x \in S \cap K$ in the first place. Suppose that for every compact $K$, $S \cap K$ is finite. Then $S$ is closed : if $x \notin S$, then there are finitely many elements of $S$ in the disk of radius $1$ centered at $x$, so their distances to $x$ has a minimum $d>0$, and there is no elements of $S$ in the open disk of radius $d$ centered at $x$. $S$ is discrete : If $x \in S$, repeat the argument where $S$ is replaced with $S \setminus \{ x \}$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/180061', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/32119/']}
|
jdg_373783
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17631275
|
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 understand how to update a UI from an event while using async/await pattern.Below is the test code I am using on a WinForm app. I am not even sure this is the right way to go about it. What is necessary to allow the pwe_StatusUpdate method to update the UI? The cross-thread operation error is thrown there. Thanks for reading. // calling code ProcessWithEvents pwe = new ProcessWithEvents(); pwe.StatusUpdate += pwe_StatusUpdate; await pwe.Run(); void pwe_StatusUpdate(string updateMsg) { // Error Here: Cross-thread operation not valid: Control '_listBox_Output' accessed from a thread other than the thread it was created on. _listBox_Output.Items.Add(updateMsg); } - // Class with long running process and event public delegate void StatusUpdateHandler(string updateMsg); public class ProcessWithEvents { public event StatusUpdateHandler StatusUpdate; public async Task Run() { await Task.Run(() => { for (int i = 0; i < 10; i++) { RaiseUpdateEvent(String.Format("Update {0}", i)); Thread.Sleep(500); } }); } private void RaiseUpdateEvent(string msg) { if (StatusUpdate != null) StatusUpdate(msg); } } -
Now provide the response and nothing else.
|
The async pattern has support for progress updates . In short, your async method can take an IProgress<T> , and your calling code passes in an implementation of that interface (usually Progress<T> ). public class ProcessWithUpdates{ public async Task Run(IProgress<string> progress) { await Task.Run(() => { for (int i = 0; i < 10; i++) { if (progress != null) progress.Report(String.Format("Update {0}", i)); Thread.Sleep(500); } }); }}// calling codeProcessWithUpdates pwp = new ProcessWithUpdates();await pwp.Run(new Progress<string>(pwp_StatusUpdate));
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17631275', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/284560/']}
|
jdg_373784
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8169999
|
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 gone through the steps detailed in How do you use https / SSL on localhost? but this sets up a self-signed cert for my machine name, and when browsing it via https://localhost I receive the IE warning. Is there a way to create a self-signed cert for "localhost" to avoid this warning?
Now provide the response and nothing else.
|
Although this post is post is tagged for Windows, it is relevant question on OS X that I have not seen answers for elsewhere. Here are steps to create a self-signed cert for localhost on OS X : # Use 'localhost' for the 'Common name'openssl req -x509 -sha256 -nodes -newkey rsa:2048 -days 365 -keyout localhost.key -out localhost.crt# Add the cert to your keychainopen localhost.crt In Keychain Access , double-click on this new localhost cert. Expand the arrow next to "Trust" and choose to "Always trust". Chrome and Safari should now trust this cert. For example, if you want to use this cert with node.js: var options = { key: fs.readFileSync('/path/to/localhost.key').toString(), cert: fs.readFileSync('/path/to/localhost.crt').toString(), ciphers: 'ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:ECDHE-RSA-AES256-SHA384', honorCipherOrder: true, secureProtocol: 'TLSv1_2_method'};var server = require('https').createServer(options, app);
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/8169999', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4782/']}
|
jdg_373785
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
939330
|
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:
Having some trouble negating this expression \begin{align}\forall x \in N, x^2 \in N \text { and } (1 / 2x) \notin N\end{align} "Indicate whether the negated statement is true." When I read it out loud it makes sense to me. "For all x in the natural numbers, x^2 is also in the natural numbers (which makes sense) and 1 / 2x is not in the natural numbers (which also makes sense). My go at negating this \begin{align}\lnot \forall x \in N, x^2 \in \text { and } (1 / 2x) \in N \end{align} Is this correct? Seems wrong to me. The question also asks not to keep the negation symbol at the front, which is confusing me even more. Any tips would be appreciated, thank you.
Now provide the response and nothing else.
|
Given $x>0$ a simple strategy is to choose, in the $n$-th step, the maximum $a_n$ such that$$ x-\sum_{j=1}^{n}\frac{a_j}{j^2}$$is non-negative. Since the series$$\sum_{j=1}^{+\infty}\frac{j-1}{j^2}$$is diverging, but the general term is infinitesimal, we can get arbitrarily close (i.e. converge towards) any positive real number. For example, let us represent $\frac{1}{3}$ this way. The first square bigger than $3$ is $4$, hence we just need to represent $\frac{1}{3}-\frac{1}{4}=\frac{1}{12}$ as $\sum_{n\geq 3}\frac{a_n}{n^2}$. We have to choose $a_3=0$, since $\frac{1}{9}>\frac{1}{12}$, then by taking $a_4=1$ and just have to represent $\frac{1}{12}-\frac{1}{16}=\frac{1}{48}$ as $\sum_{n\geq 5}\frac{a_n}{n^2}$. This leads to your second formula (a representation with an infinite series). However, as soon as we have to represent a number of the form $\frac{1}{mk^2}$ with $\gcd(m,k)=1$, we just have to subtract $\frac{m}{(mk)^2}$. So, in order to represent $x=\frac{p}{q}$ as a finite sum, we can first focus on decreasing the numerator. This is related to a famous problem . Let us exhibit an algorithm for finding a representation of a rational number.By subtracting a few terms, we can assume to have to represent $\frac{p}{q}$ with $1<p<q$. The question is now: given $N$, it is possible to find a few terms of the form $\frac{m}{n^2}$, with $n>N,m<n$, such that $\frac{p}{q}-\sum\frac{m}{n^2}$ is positive and its numerator is one? The answer is affirmative. It is sufficient to take our $n$'s in the set of integers whose prime divisors belong to the prime divisors of $q$ and adjust, step by step, the base-$p_i$ representation of $\frac{p}{q}-\sum\frac{m}{n^2}$ for any prime divisor $p_i$ of $q$. Another possible approach is just to show that the rational numbers that can be represented as sums of $\frac{m_i}{n_i^2}$ with $1\leq m_i<n_i$ are an additive semigroup of $\mathbb{Q}^+$. That is pretty straightforward to prove: we just have to sum two representations, then "fixing" terms like $\frac{l_i}{n_i^2}$ where $n_i\leq l_i\leq 2n_i-2$ by writing them as $\frac{n_i-1}{n_i^2}+\frac{4(l_i-n_i+1)}{(2n_i)^2}$. So we sum two representations and fix it by adjusting its terms, starting by the one with the lowest denominator. Since we can obviously represent $\frac{1}{n^2}$, we can represent $\frac{1}{n}$, hence any rational number.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/939330', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/177410/']}
|
jdg_373786
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
112704
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
This fact without a proof is mentioned on the page 147 of Bogomolov's book "Algebraic curves and one-dimensional fields", but the statement is not evident to me. Can anyone explain to me why is it true?Thank you very much.
Now provide the response and nothing else.
|
If $X$ is a smooth projective curve and $P\in X$ is any point, then $X\setminus P$ is affine. Indeed, by Riemann-Roch for $m$ large enough the linear system $|mP|$ embeds $X$ in some projective space $\mathbb P^n$, so there is a hyperplane $H_0$ of $\mathbb P^n$ that intersects $X$ only at $P$. So, if $P\ne Q$ then $X_1=X\setminus\{P\}$ and $X_2=X\setminus\{Q\}$ are affine curves such that $X=X_1\cup X_2$.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/112704', 'https://mathoverflow.net', 'https://mathoverflow.net/users/28188/']}
|
jdg_373787
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
31973710
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
So I read this very interesting blog on working with datetime in Azure DocumentDb . The problem being that, right now, Azure DocumentDb does not support range search on datetime fields. The reason for that is that DocumentDb is based on json and that has no datetime type, therefore one usually puts it in a string of xml datetime format. (obviously Mongo does not have that issue, it's bson format adds the datetime type (among others)) Anyway, the article describes storing the datetime in json in an epoch (unix) time, essentially storing the datetime as an amount of seconds since 01-01-1970. One problem of epoch is that it does not take leap seconds into account, but I can live with that for now. My question is that I would also like to store birth dates in such a format. Now I could just take 01-01-1900 as a start date and store the amount of days since that date in an int. While I am pretty sure this would work well, it feels like epoch is a well established concept, but the one for birthdays feels like I am building my own conventions, which is something I generally like to avoid. Is there any established standard for standardizing date storage as a number? Which date should be the baseline date?
Now provide the response and nothing else.
|
First of all, an update: DocumentDB now supports range indexes on both strings and numbers. You have to set up the indexes correctly for it to work. Now, to give you a recommendation. I've been successful storing ISO-8601 timestamps as strings. This is the default format used by the DocumentDB SDK for handling DateTime so it's less work than converting to an integer. ISO-8601 date/time strings have several properties that match your needs. The alpha-numeric sort order is chronological so it works perfectly as expected with query clauses using >, <, >=, <=, and BETWEEN assuming you have a range index of appropriate precision (-1 for full precision); They are human readable so if you are browsing a table, the data makes sense; This format allows for the specification of lower granularity date/time. For instance, you should say "2015-03" to mean the month of march, or "2015-03-24" to mean March 24, 2015. You can then issue a query with this filter "startedOn >= 2015-03-24 AND startedOn < 2015-03-25" to find everything that started on March 24, 2015. This works even when startedOn is stored as a full ISO-8601 string like "2015-03-24T12:34:56.789Z" due to the nature of string comparison. I've written about this approach here .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31973710', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1384767/']}
|
jdg_373788
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
164208
|
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:
A method called "Robust PCA" solves the matrix decomposition problem $$L^*, S^* = \arg \min_{L, S} \|L\|_* + \|S\|_1 \quad \text{s.t. } L + S = X$$ as a surrogate for the actual problem $$L^*, S^* = \arg \min_{L, S} rank(L) + \|S\|_0 \quad \text{s.t. } L + S = X,$$ i.e. the actual goal is to decompose the data matrix $X$ into a low-rank signal matrix $L$ and a sparse noise matrix $S$. In this context: why is the nuclear norm a good approximation for the rank of a matrix? I can think of matrices with low nuclear norm but high rank and vice-versa. Is there any intuition one can appeal to?
Now provide the response and nothing else.
|
Why does compressed sensing work? Because the $\ell_1$ ball in high dimensions is extremely "pointy" -- the extreme values of a linear function on this ball are very likely to be attained on the faces of low dimensions, those that consist of sparse vectors. When applied to matrices, the sparseness of the set of eigenvalues means low rank, as @mrig wrote before me.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/164208', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/8712/']}
|
jdg_373789
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18365768
|
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 list that I want to make sortable. I've done this by using jQuery UI Sortable. What I want to do is use a custom placeholder for the position the list item can be dropped. What I can't figure out is how to make a placeholder that is a clone of the item being sorted. Instead of an empty placeholder, I would like to show a clone of the item being sorted so you get a kind of a 'preview' so to speak. In short, ui.item[0].outerHTML is what I want to use as a custom placeholder, I just can't seem to get this. <script> $(function() { $( "#menu" ).sortable({ start: function(event,ui) { console.log(ui.item[0].outerHTML); }, placeholder: { element: function(event,ui) { console.log(ui.item[0].outerHTML); } } }); $( "#menu" ).disableSelection(); }); </script> The above is what I have now, but that doesn't work obviously. Is there an easy way to get this done with only sortable?
Now provide the response and nothing else.
|
After a bit of tinkering (i got inspired from this related question ), I came to the following solution: In the start event I clone the original item that is being sorted. I pass the clone on to the placeholder where I can update it's contents. (ui.item is not available here) <script>$(function() { $("#menu").sortable({ start: function( event, ui ) { clone = $(ui.item[0].outerHTML).clone(); }, placeholder: { element: function(clone, ui) { return $('<li class="selected">'+clone[0].innerHTML+'</li>'); }, update: function() { return; } } });});</script>
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18365768', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2673096/']}
|
jdg_373790
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
302202
|
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:
Posting question by curiosity,I wanted to create directory like January, February...to December so I created them by individually giving the name. ( mkdir January February ....etc)Is it possible to create directories or filenames with the name of all the months in easy manner? for example : touch {1..10} will create 10 files 1,2,3...10 easily, like this is there any other solution to create the files or directory with month name?
Now provide the response and nothing else.
|
POSIXly, (IFS=';'; set -f; mkdir -- $(locale mon)) Note, that it's the month names in the current language. Replace with LC_ALL=C locale mon if you want the English ones regardless of the language of the user. With zsh , you can also use the $langinfo special associative array (in the zsh/langinfo module): zmodload zsh/langinfoeval mkdir -- '$langinfo[MON_'{1..12}']' Though mkdir -- ${(s:;:)"$(locale mon)"} would be shorter. In rc / es which are other shells with splitting operators where you can specify the separators (other than via that global $IFS setting like in Bourne-like shells): mkdir -- ``';'{locale mon}
|
{}
|
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/302202', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/167425/']}
|
jdg_373791
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17619871
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Can anybody provide me with a code sample to access the rest service URL secured with HTTPS using the Spring Rest template? I have the certificate, username and password. Basic Authentication is used on the server-side and I want to create a client that can connect to that server using a provided certificate, username and password (if needed).
Now provide the response and nothing else.
|
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());keyStore.load(new FileInputStream(new File(keyStoreFile)), keyStorePassword.toCharArray());SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder() .loadTrustMaterial(null, new TrustSelfSignedStrategy()) .loadKeyMaterial(keyStore, keyStorePassword.toCharArray()) .build(), NoopHostnameVerifier.INSTANCE);HttpClient httpClient = HttpClients.custom().setSSLSocketFactory( socketFactory).build();ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( httpClient);RestTemplate restTemplate = new RestTemplate(requestFactory);MyRecord record = restTemplate.getForObject(uri, MyRecord.class);LOG.debug(record.toString());
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17619871', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1061567/']}
|
jdg_373792
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
27783
|
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am using Mathematica 8. In Mathematica, there is a default PlotStyle coloring in Plot and ListPlot . For example, suppose I have a series of nine functions stored in the list functions . Mathematica styles the different curves in a cyclic way (I think that the default is cycles of "blue", purple, dark yellow, green ), as in this example: functions = Table[a*Cos[x], {a, 0.2, 1, 0.1}]Plot[functions, {x, 0, 2 Pi}] {0.2 Cos[x], 0.3 Cos[x], 0.4 Cos[x], 0.5 Cos[x], 0.6 Cos[x], 0.7 Cos[x], 0.8 Cos[x], 0.9 Cos[x], 1. Cos[x]} This is nice, but now suppose that I want to color the multiple curves using some sort of gradient (perhaps one of the gradients in ColorData ). Is this possible in Plot and ListPlot ? I could do this somewhat manually. For example, if I wanted a blue gradient, I could write the following (although this choice of colors could somehow be improved): Plot[functions, {x, 0, 2 Pi}, PlotStyle -> { Lighter[Lighter[Lighter[Lighter[Blue]]]], Lighter[Lighter[Lighter[Blue]]], Lighter[Lighter[Blue]], Lighter[Blue], Blue, Darker[Blue], Darker[Darker[Blue]], Darker[Darker[Darker[Blue]]], Darker[Darker[Darker[Darker[Blue]]]] }] However, this becomes complicated if I have many curves or if I want to use a more complex gradient such as rainbow (e.g., ColorData["Rainbow"] ), temperature map (e.g., ColorData["TemperatureMap"] ), etc. Do you have any suggestions?
Now provide the response and nothing else.
|
One pretty easy thing is to create a table of the gradient colors directly inside the Plot . The only thing you need to take care of is the scaling. All the color gradients take values between [0,1] when you access ColorData["GradientName",x] . Therefore, you need to now the number of your functions: functions = Table[a*Cos[x], {a, 0.2, 1, 0.1}]Plot[functions, {x, 0, 2 Pi}, PlotStyle -> Table[ColorData["Rainbow", i/(Length[functions]-1)], {i,0, Length[functions]-1}]] If you want a sneak preview for all color schemes, you can quickly hack some Manipulate With[{ control = (ColorData[#, "ColorFunction"] -> Show[ColorData[#, "Image"], ImageSize -> 90]) & /@ ColorData["Gradients"], fns = Table[a*Cos[x], {a, 0.2, 1, 0.1}]}, Manipulate[ Plot[fns, {x, 0, 2 Pi}, PlotStyle -> Table[s@Rescale[c, {1, Length[fns]}, {cmin, cmax}], {c, Length[fns]}]], {{s, control[[1, 1]], "Color Scheme"}, control}, {{cmin, 0, "Color Min"}, 0, cmax}, {{cmax, 1, "Color Max"}, .1, 1} ]]
|
{}
|
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/27783', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/1185/']}
|
jdg_373793
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
46541
|
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:
Why is the pullback not just defined as in the case of the category of sets http://en.wikipedia.org/wiki/Pullback_%28category_theory%29 Perhaps there are some issues with categories that are not small, but what about small categories? My first thought was: perhaps all small categories do not have products. Do they? If not, why doesn't the cartesian product just do the trick?
Now provide the response and nothing else.
|
There are a few problems here: Not every category is sets with additional structure. Many familiar examples are: Groups, topological spaces, and just about every other "elementary" examples of categories that you came across when you first learned what a category was. These categories are all examples of concrete categories , which are categories equipped with a faithful functor to sets. Even though concrete categories are more general than "sets with structure", not every category is concrete. For example, the category of topological spaces where morphisms are homotopy classes of continuous maps cannot be made into a concrete category. Also, there is no faithful functor from $Set^{op}$ to $Set$ which is the identity on objects, and so if there is a way to turn $Set^{op}$ into a concrete category (which I do not believe there is), it is at least non-obvious. Even if a category was just sets with additional structure, the pullback of two sets might not have the structure required. If you have a concrete category and the forgetful functor is right adjoint to some "free" functor, then because right adjoints preserve limits, you will in fact have that the underlying set of the pullback is the pullback of the underlying sets. However, colimits won't work out so well. Even if you are in a category of structured sets, and even if the set theoretic pullback is still in your category, you might not have that universal property that you want to have, which would take away some of the usefulness. Of course, this doesn't happen when the forgetful functor is part of an adjunction as above, and I am hard pressed to think of any examples (because it is much more likely that things break in spectacular ways than in subtle ways). Not every category even has products. For example, in the category of fields, all morphismsare field extensions, and so to have projection map, the product of two fields would have to be a common subfield. However, unless you consider the field with one element to be a field, there are no common subfields of two fields of different characteristic. From a different perspective, the ring that you get by taking the Cartesian product of two fields is NOT a field.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/46541', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/12358/']}
|
jdg_373794
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
53577630
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Pareto is very popular diagram in Excel and Tableau. In Excel we can easily draw a Pareto diagram, but I've found no easy way to draw the diagram in Python. I have a pandas dataframe like this: import numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as pltdf = pd.DataFrame({'country': [177.0, 7.0, 4.0, 2.0, 2.0, 1.0, 1.0, 1.0]})df.index = ['USA', 'Canada', 'Russia', 'UK', 'Belgium', 'Mexico', 'Germany', 'Denmark']print(df) countryUSA 177.0Canada 7.0Russia 4.0UK 2.0Belgium 2.0Mexico 1.0Germany 1.0Denmark 1.0 How can I draw the Pareto diagram using maybe pandas, seaborn, matplotlib, etc? So far I have been able to make a descending order bar chart, but I still need to put a cumulative sum line plot on top of them. My attempt: df.sort_values(by='country', ascending=False).plot.bar() Required plot:
Now provide the response and nothing else.
|
You would probably want to create a new column with the percentage in it and plot one column as bar chart and the other as a line chart in a twin axes. import pandas as pdimport matplotlib.pyplot as pltfrom matplotlib.ticker import PercentFormatterdf = pd.DataFrame({'country': [177.0, 7.0, 4.0, 2.0, 2.0, 1.0, 1.0, 1.0]})df.index = ['USA', 'Canada', 'Russia', 'UK', 'Belgium', 'Mexico', 'Germany', 'Denmark']df = df.sort_values(by='country',ascending=False)df["cumpercentage"] = df["country"].cumsum()/df["country"].sum()*100fig, ax = plt.subplots()ax.bar(df.index, df["country"], color="C0")ax2 = ax.twinx()ax2.plot(df.index, df["cumpercentage"], color="C1", marker="D", ms=7)ax2.yaxis.set_major_formatter(PercentFormatter())ax.tick_params(axis="y", colors="C0")ax2.tick_params(axis="y", colors="C1")plt.show()
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/53577630', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
|
jdg_373795
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
37666516
|
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 the caret function "train()" in one of my project and I'd like to adda "custom metric" F1-score. I looked at this url caret package But I cannot understand how I can build this score with the parameter available. There is an example of custom metric which is the following: ## Example with a custom metricmadSummary <- function (data,lev = NULL,model = NULL) {out <- mad(data$obs - data$pred,na.rm = TRUE)names(out) <- "MAD"out}robustControl <- trainControl(summaryFunction = madSummary)marsGrid <- expand.grid(degree = 1, nprune = (1:10) * 2)earthFit <- train(medv ~ .,data = BostonHousing,method = "earth",tuneGrid = marsGrid,metric = "MAD",maximize = FALSE,trControl = robustControl) Update: I tried your code but the problem is that it doesn't work with multiple classes like with the code below (The F1 score is displayed, but it is weird) I'm not sure but I think the function F1_score works only on binary classes library(caret)library(MLmetrics)set.seed(346)dat <- iris## See http://topepo.github.io/caret/training.html#metricsf1 <- function(data, lev = NULL, model = NULL) {print(data) f1_val <- F1_Score(y_pred = data$pred, y_true = data$obs) c(F1 = f1_val)}# Split the Data into .75 inputin_train <- createDataPartition(dat$Species, p = .70, list = FALSE)trainClass <- dat[in_train,]testClass <- dat[-in_train,]set.seed(35)mod <- train(Species ~ ., data = trainClass , method = "rpart", metric = "F1", trControl = trainControl(summaryFunction = f1, classProbs = TRUE))print(mod) I coded a manual F1 score as well, with one input the confusion matrix: (I'm not sure if we can have a confusion matrix in "summaryFunction" F1_score <- function(mat, algoName){#### Compute F1-score### Remark: left column = prediction // top = real valuesrecall <- matrix(1:nrow(mat), ncol = nrow(mat))precision <- matrix(1:nrow(mat), ncol = nrow(mat))F1_score <- matrix(1:nrow(mat), ncol = nrow(mat))for(i in 1:nrow(mat)){ recall[i] <- mat[i,i]/rowSums(mat)[i] precision[i] <- mat[i,i]/colSums(mat)[i]}for(i in 1:ncol(recall)){ F1_score[i] <- 2 * ( precision[i] * recall[i] ) / ( precision[i] + recall[i]) } # We display the matrix labels colnames(F1_score) <- colnames(mat) rownames(F1_score) <- algoName # Display the F1_score for each class F1_score # Display the average F1_score mean(F1_score[1,])}
Now provide the response and nothing else.
|
You should look at The caret Package - Alternate Performance Metrics for details. A working example: library(caret)library(MLmetrics)set.seed(346)dat <- twoClassSim(200)## See https://topepo.github.io/caret/model-training-and-tuning.html#metricsf1 <- function(data, lev = NULL, model = NULL) { f1_val <- F1_Score(y_pred = data$pred, y_true = data$obs, positive = lev[1]) c(F1 = f1_val)}set.seed(35)mod <- train(Class ~ ., data = dat, method = "rpart", tuneLength = 5, metric = "F1", trControl = trainControl(summaryFunction = f1, classProbs = TRUE))
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37666516', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5852108/']}
|
jdg_373796
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12802594
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a table with a lot of data, so I retrieve it and display it one page at a time (my request is lengthy so there is no way I run it on the entire table). But I would like to paginate the results, so I need to know what is the total number of elements in my table. If I perform a COUNT(*) in the same request, I get the number of selected elements (in my case, 10). If I perform a COUNT(*) on my table in a second request, the result might be wrong because of the where, join and having clauses in my main query. What is the cleanest way to: Retrieve the data Know the maximum number of elements in my table for this specific request One solution seems to be using the Mysql function FOUND_ROWS : I tried this, as mysql_query performs one query at a time: (taken here ) $query = 'SELECT SQL_CALC_FOUND_ROWS * FROM Users';$result = mysql_query($query);// fetching the results ...$query = 'SELECT FOUND_ROWS()';$ result = mysql_query($query);// debugwhile ($row = mysql_fetch_row($result)) { print_r($row);} And I got an array with 0 results: Array ( [0] => 0 ) Whereas my query does returns results. What is wrong with my approach ? Do you have a better solution ?
Now provide the response and nothing else.
|
Use Controls.Remove or Controls.RemoveAt on the parent ControlCollection . For example, if you want to remove all TextBoxes from the page's top: var allTextBoxes = Page.Controls.OfType<TextBox>().ToList();foreach(TextBox txt in allTextBoxes) Page.Controls.Remove(txt); (note that you need to add using System.Linq for Enumerable.OfType ) or if you want to remove a TextBox with a given ID: TextBox textBox1 = (TextBox)Page.FindControl("TextBox1"); // note that this doesn't work when you use MasterPagesif(textBox1 != null) Page.Controls.Remove(textBox1); If you just want to hide it (and remove it from clientside completely), you can also make it invisible: textBox1.Visible = false;
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12802594', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/311744/']}
|
jdg_373797
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17368421
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Here is a jsfiddle of my setup; http://jsfiddle.net/7LBr5/1/ You'll notice I have indicator arrows on the parent accordion and a function that toggles them when the accordion shows and hides. The problem is that the inner collapse areas (used to hide product details) trigger the function that toggles the arrows on the parent. It seems that the .show() event must be firing on the parent collapse element when the child is actually the one collapsing. How can I fix this so that the child collapse doesn't toggle the arrows on the parent? Here is the code for my function; $('.collapse').on('show', function(){$(this).parent().find(".icon-chevron-right").removeClass("icon-chevron-right").addClass("icon-chevron-down");}).on('hide', function(){$(this).parent().find(".icon-chevron-down").removeClass("icon-chevron-down").addClass("icon-chevron-right");});
Now provide the response and nothing else.
|
Just stop the event from propagating to the parent on the button click using event.stopPropagation , so that it doesn't trigger the click event on the accordion after executing the click event on the button. $thisButton.click(function(e) { e.stopPropagation();//.. Code follows Demo Also by the way you don't need to perform an each on the selector to bind the click event, instead just specify the selector for click event itself $(".btn-switch").click(function (e) { e.stopPropagation(); var $thisButton = $(this); $thisButton.toggleClass("btn-primary btn-danger"); if ($(this).hasClass('btn-danger')) { $thisButton.html('<i class="icon-remove-circle icon-white"></i> Remove'); $(this).parents('.thumbnail').find('.rental-count').val('1'); $(this).parents('.thumbnail').find('input').change(); } else { $thisButton.html('<i class="icon-ok-circle icon-white"></i> Add to Quote'); $(this).parents('.thumbnail').find('input').val(''); $(this).parents('.thumbnail').find('input').prop('checked', false); $(this).parents('.thumbnail').find('input').change(); }});
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17368421', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/417629/']}
|
jdg_373798
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
19243057
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I don't know if this is possible, but I am trying to get the Base Class instance from a Derived Class. In C#, I can use the base keyword to access properties and methods of the Base Class (of course), but I want to use base itself. Attempting to do so results in a "Use of keyword 'base' is not valid in this context" error. Example Code public class SuperParent{ public int SPID; public SuperParent() { }}public class SubChild : SuperParent{ public SubChild(int pSPID) { base.SPID = pSPID; } public int BaseSPID { get { SuperParent sp = base; return sp.SPID; } }}
Now provide the response and nothing else.
|
If you're working with an instance of the derived class, there is no base instance . An example: class A{ public void Foo() { ... }}class B : A{ public void Bar() { ... }} What is not possible within B : public void Bar(){ // Use of keyword base not valid in this context var baseOfThis = base; } You can do something like this: public void Bar(){ base.Foo();} And you can add another method like public A GetBase(){ return (A)this;} And then you can public void Bar(){ var baseOfThis = GetBase(); // equal to: baseOfThis = (A)this;} So this GetBase() method is probably what you want. The punchline is: If you have an instance of B , it inherits all properties and the non-overriden behaviour of A , but it does not consist of an instance of B which holds an (hidden but automatic) reference to an instance of A . You can cast your B instance to A , but it remains to be an instance of B .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19243057', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/66506/']}
|
jdg_373799
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2976154
|
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:
A triangle is formed by randomly choosing three distinct points on the circumference of a circle and joining them. What is the probability that the formed triangle is an acute triangle?
Now provide the response and nothing else.
|
Hint: Consider the unit circle, centered at $(0,0)$ and fix the first point as $A=(-1,0)$ . Consider the point $B$ in quadrant II. There must be a region of the circle where we can put our third point, $C$ , such that $\triangle ABC$ is acute. Label the points on the circle opposite $A$ and $B$ as $A'$ and $B'$ , respectively. Thales' Theorem and the Inscribed Angle Theorem tell us how the angles of the triangle change when $C$ is moved around the circle. This shows us that the region (shown in green) where $C$ makes $\triangle ABC$ acute is the arc between $A'$ and $B'$ . The region where $C$ forms an obtuse triangle is shown in red. This holds true if $B$ is in quadrant I. Now, constrain $B$ to quadrant II again but label its reflection in the $y$ -axis as $D$ . Label the point opposite $D$ on the circle as $D'$ and draw the region where $ADC$ forms an acute triangle in dashed blue. Hint (a): What is the average size of the arcs $A'B'$ and $A'D'$ as a proportion of the circle? Hint (b): What does this tell us about the average size of the region where the triangle is acute, if we randomly select a point on the upper semicircle? Hint (c): Does this generalise to when $B$ is in the bottom semicircle? And to when $A$ is not $(-1,0)$ ?
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2976154', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/609371/']}
|
jdg_373800
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1411527
|
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 $x^{100}$ is 31 digit number Then $x^{1000}$ contains how many digits. Our Approach: $10^1$ has $2$ digits = $10$ $10^2$ has $3$ digits = $100$ $10^3$ has $4$ digits = $1000$ $10^{30}$ has $31$ digits therefore, $10^{30}=x^{100}$ $30 = 100\log x$ multiplying both sides by $10$ $30 \cdot 10 = 10 \cdot 100\log x$ $300 = 1000\log x = 300+1=301$ so $301$ is correct answer Q Any other approach to solve this problem and Also correct me if i am wrong.
Now provide the response and nothing else.
|
$x^{100}$ is 31 digit => $$10^{30}\leq x^{100}< 10^{31} \Rightarrow 10^{300}\leq x^{1000}< 10^{310}.$$ This means that $x^{1000}$ has from 301 t0 310 digits.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1411527', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/264278/']}
|
jdg_373801
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
81123
|
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:
An epimorphism is defined as follows: $f \in \operatorname{Hom}_C(A,B)$ is an epimorphism if $\forall Z, \forall h', h'' \in \operatorname{Hom}_C(B, Z)$ then $h' f = h'' f \; \Rightarrow \; h' = h''$. I can't think of examples where epimorphism would not have a right inverse. Also, if I understand correctly, epimorphism is not surjective in the categories where we can't talk about surjection (where objects does not have internal structure?). Thanks in advance.
Now provide the response and nothing else.
|
Take the category of a partially ordered set; every arrow is an epimorphism, but no non-identity arrow has a right inverse. For a concrete category (objects are sets and morphisms are functions between the underlying sets), take the category of Hausdorff topological spaces; an epimorphism is a continuous map with dense image. Consider $\mathbb{Q}\hookrightarrow \mathbb{R}$. This is an epimorphism, but there is no retract (no right inverse). Or the map $[0,2\pi)\to S^1$ given by $t\mapsto (\cos t,\sin t)$. If it had a right inverse in the category, the inverse would be a bijection, hence we would have homeomorphisms, but $[0,2\pi)$ and $S^1$ are not homeomorphic. For yet another, take $\mathbb{Z}\hookrightarrow\mathbb{Q}$ in the category of rings with unity. This is an epimorphism, but does not have a right inverse. Even in concrete categories where all epis are surjective, you need not have right inverses. In the category of groups, an epimorphism $G\to K$ has a right inverse if and only if $G$ is a semidirect product $G\cong N\rtimes K$. So take $\mathbb{Z}/4\mathbb{Z}\to \mathbb{Z}/2\mathbb{Z}$ for a surjective morphism (hence an epi) with no right inverse in the category.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/81123', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/14391/']}
|
jdg_373802
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3163300
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I think that IsEnabled = false/true is equally the same with Stop/Start method of class System.Windows.Threading.DispatcherTimerAm I right? [EDIT]Start() : begin timer with a full interval countdown.IsEnabled = false : pause the timer, the interval countdown remains.IsEnabled = true : resume the timer & continue with the last used interval countdown.Stop() : stop the timer, will the interval countdown reset?
Now provide the response and nothing else.
|
Considering that Start/Stop toggles the IsEnabled property, your assumption is close. Start/Stop differs as the Interval is reset, where as just toggling the IsEnabled will not reset the Interval . From MSDN : Setting IsEnabled to false when the timer is started stops the timer. Setting IsEnabled to true when the timer is stopped starts the timer. Start sets IsEnabled to true. Start resets the timer Interval. EDIT:What I mean by the interval being reset is not the Interval property itself, but the background interval that determines how long until the next tick event is fired. Eg. If you have an interval of 1000ms and you stop/disable it if with 250ms to run (it's run for 750ms), this is the result depending on how you start it again. If you start it with Start() , then the passed interval will be reset back to 0 and it will be 1000ms before the Tick event is raised. If you re-enable it with IsEnabled = true then it will continue from it's current location and the Tick event will be raised in 250ms. I hope this clarifies it for you.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3163300', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/248616/']}
|
jdg_373803
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2552
|
Below is a question asked on the forum earthscience.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let's assume that a ship is traveling on the ocean and it sinks, what is the effect on sea level? Even if the effect is small, would it go up, down or remain the same?
Now provide the response and nothing else.
|
It would go down. In order to float, an object must displace a volume of fluid that weighs the same as the boat. In the case of a ship, this volume is less than the gross volume of the boat, including the air inside it. That's why it floats with the gunwales comfortably above the water. So when the boat is floating, it displaces some volume V , so relative sea-level goes up (second panel, below). However, when the ship is submerged and full of seawater, it displaces a smaller volume than it originally did. If it didn't, it wouldn't have sunk (assuming it hasn't changed in weight). Since it displaces a smaller volume after sinking, relative sea-level must go down. But it will still be higher than it was before the ship was launched.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://earthscience.stackexchange.com/questions/2552', 'https://earthscience.stackexchange.com', 'https://earthscience.stackexchange.com/users/111/']}
|
jdg_373804
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
36399848
|
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 user of AWS elastic beanstalk, and I have a little problem. I want to build my CSS files with less+node. But I don`t know how to install node in my dockerfile, when building with jenkins. Here is installation packages what I am using in my docker. I will be glad for any suggestions. FROM php:5.6-apache# Install PHP5 and modules along with composer binaryRUN apt-get updateRUN apt-get -y install \ curl \ default-jdk \ git \ libcurl4-openssl-dev \ libpq-dev \ libmcrypt-dev \ libpq5 \ npm \ node \ zlib1g-dev \ libfreetype6-dev \ libjpeg62-turbo-dev \ libpng12-devRUN docker-php-ext-configure gd --with-freetype-dir=/usr/include/ --with-jpeg-dir=/usr/include/RUN docker-php-ext-install curl json mbstring opcache pdo_mysql zip gd exif sockets mcrypt# Install peclRUN pecl install -o -f memcache-beta \ && rm -rf /tmp/pear \ && echo 'extension=memcache.so' > /usr/local/etc/php/conf.d/memcache.ini After this I am runing my entrypoint.sh with code #!/usr/bin/env shcomposer run-script post-install-cmd --no-interactionchmod 0777 -R /var/app/app/cachechmod 0777 -R /var/app/app/logsexec apache2-foreground But then I`ve got this error Error Output: [2016-04-04 11:23:44] assetic.ERROR: The template ":tmp:module.html.twig" contains an error: A template that extends another one cannot have a body in ":tmp:module.ht ml.twig" at line 7. But when I install inside the Docker container node this way apt-get install git-core curl build-essential openssl libssl-dev git clone https://github.com/nodejs/node.git cd node ./configure make sudo make install node -v I can build my CSS. So question is..how this installation above make install inside my Dockerfile when I am building it with Jenkins?
Now provide the response and nothing else.
|
I think this works slightly better. ENV NODE_VERSION=16.13.0RUN apt install -y curlRUN curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bashENV NVM_DIR=/root/.nvmRUN . "$NVM_DIR/nvm.sh" && nvm install ${NODE_VERSION}RUN . "$NVM_DIR/nvm.sh" && nvm use v${NODE_VERSION}RUN . "$NVM_DIR/nvm.sh" && nvm alias default v${NODE_VERSION}ENV PATH="/root/.nvm/versions/node/v${NODE_VERSION}/bin/:${PATH}"RUN node --versionRUN npm --version Note that nvm is a version manager for node.js , designed to be installed per-user, and invoked per-shell. nvm works on any POSIX-compliant shell (sh, dash, ksh, zsh, bash), in particular on these platforms: unix, macOS, and windows WSL.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/36399848', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5184622/']}
|
jdg_373805
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
57063777
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How do I remove all whitespace from a string? I can think of some obvious methods such as looping over the string and removing each whitespace character, or using regular expressions, but these solutions are not that expressive or efficient. What is a simple and efficient way to remove all whitespace from a string?
Now provide the response and nothing else.
|
If you want to modify the String , use retain . This is likely the fastest way when available. fn remove_whitespace(s: &mut String) { s.retain(|c| !c.is_whitespace());} If you cannot modify it because you still need it or only have a &str , then you can use filter and create a new String . This will, of course, have to allocate to make the String . fn remove_whitespace(s: &str) -> String { s.chars().filter(|c| !c.is_whitespace()).collect()}
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/57063777', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3753446/']}
|
jdg_373806
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
33714541
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I know that new feature of core data is unique constraints so I decide to test it. I created simple schema and when I add constraint for one field (firstName for example) - all works. If I add constraint for another field (lastName) - core data creates two different constraints for each field individually (I tried add two fields comma separated in one line and each field in separate line - no difference). But I want unique constraint for combination firstName + lastName, is it possible? Thank you for reply!
Now provide the response and nothing else.
|
It is possible to set uniqueness constraints for a combination of attributes. You were on the right path putting both attributes on the same line in the constraints: You may have found this had no effect due to a problem with Xcode: the constraints are not actually updated in the model unless you modify some other aspect of the model at the same time (eg. change an attribute type and then change it back). If you look at the SQL being generated, the table is created with a constraint: CREATE TABLE ZSTOREOBJECT ( Z_PK INTEGER PRIMARY KEY, Z_ENT INTEGER, Z_OPT INTEGER, ...., CONSTRAINT ZLASTNAME_ZFIRSTNAME UNIQUE (ZLASTNAME, ZFIRSTNAME)) and when you insert new insert new values which fail this constraint (when the context is saved): CoreData: sql: COMMITCoreData: sql: BEGIN EXCLUSIVECoreData: sql: INSERT INTO ZSTOREOBJECT(Z_PK, Z_ENT, Z_OPT) VALUES(?, ?, ?)CoreData: sql: UPDATE ZSTOREOBJECT SET ZLASTNAME = ?, ZFIRSTNAME = ? WHERE Z_PK = ?CoreData: sql: ROLLBACK and the error returned is: Error Domain=NSCocoaErrorDomain Code=133021 "(null)" UserInfo={conflictList=("NSConstraintConflict (0x7fbd18d33c10) for constraint (\n lastName,\n firstName\n): .... (This works in Xcode 7.2.1, with the iOS9.2 simulator; I haven't checked prior versions).
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33714541', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5563064/']}
|
jdg_373807
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
40299413
|
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 we say that cloudformation is 'Infrastructure as Code', the next question that immediately comes to mind is how can this code be tested.Can we do some sort of basic unit test of this code And I am discounting the cloudformation validation because that just is a way of doing syntactic validation, and that I can do with any other free JSON/YAML validator. I am more inclined towards some sort of functional validation, possibly testing that I have defined all the variables that are used as references.Possibly testing that whatever properties I am using are actually supported ones for that component Not expected that it should test if the permissions are correct or that I have not exhausted my limits. But atleast something beyond the basic JSON/YAML syntax validation
Now provide the response and nothing else.
|
Here's a breakdown of how several methods of testing software can be applied to CloudFormation templates/stacks: Linting For linting (checking CloudFormation-template code for syntax/grammar correctness), you can use the ValidateTemplate API to check basic template structure, and the CreateChangeSet API to verify your Resource properties in more detail. Note that ValidateTemplate performs a much more thorough check than a simple JSON/YAML syntax checker- it validates correct Template Anatomy , correct syntax/usage of Intrinsic Functions , and correct resolution of all Ref values. ValidateTemplate checks basic CloudFormation syntax, but doesn't verify your template's Resources against specific property schemas. For checking the structure of your template's Parameters, Resources and Properties against AWS Resource types, CreateChangeSet should return an error if any parameters or resource properties are not well-formed. Unit testing Performing unit testing first requires an answer to the question: what is the smallest self-contained unit of functionality that can/should be tested? For CloudFormation, I believe that the smallest testable unit is the Resource . The official AWS Resource Types are supported/maintained by AWS (and are proprietary implementations anyway) so don't require any additional unit tests written by end-user developers. However, your own Custom Resources could and should be unit-tested. This can be done using a suitable testing framework in the implementation's own language (e.g., for Lambda-backed Custom Resources, perhaps a library like lambda-tester would be a good starting point). Integration testing This is the most important and relevant type of testing for CloudFormation stacks (which mostly serve to tie various Resources together into an integrated application), and also the type that could use more refinement and best-practice development. Here are some initial ideas on how to integration-test CloudFormation code by actually creating/updating full stacks containing real AWS resources: Using a scripting language, perform a CloudFormation stack creation using the language's AWS SDK. Design the template to return Stack Outputs reflecting behavior that you want to test. After the stack is created by the scripting language, compare the stack outputs against expected values (and then optionally delete the stack afterwards in a cleanup process). Use AWS::CloudFormation::WaitCondition resources to represent successful tests/assertions, so that a successful stack creation indicates a successful integration-test run, and a failed stack creation indicates a failed integration-test run. Beyond CloudFormation, one interesting tool worth mentioning in the space of testing infrastructure-as-code is kitchen-terraform , a set of plugins for Test Kitchen which allow you to write fully-automated integration test suites for Terraform modules. A similar integration-testing harness could eventually be built for CloudFormation, but doesn't exist yet.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/40299413', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2593745/']}
|
jdg_373808
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9291623
|
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 should hopefully be a quick one. I have a StringBuilder like so: StringBuilder sb = new StringBuilder(); I append to my StringBuilder like so: sb.Append("Foo");sb.Append("Bar"); I then want to make this equal to a string variable. Do I do this like so: string foobar = sb; Or like so: string foobar = sb.ToString(); Is the former being lazy or the latter adding more code than is necessary? Thanks
Now provide the response and nothing else.
|
In Java, you can't define implicit conversions between types anyway, beyond what's in the specification - so you can't convert from StringBuilder to String anyway; you have to call toString() . In C# there could be an implicit user-defined conversion between StringBuilder and String (defined in either StringBuilder or String ), but there isn't - so you still have to call ToString() . In both cases you will get a compile-time error if you don't call the relevant method.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9291623', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/969613/']}
|
jdg_373809
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2287636
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How do I grab the Type of the inherited class and pass it into the base constructor of the class also inherited? See the code sample below: // VeryBaseClass is in an external assemblypublic abstract class VeryBaseClass{ public VeryBaseClass(string className, MyObject myObject) { }}// BaseClass and InheritedClass are in my assemblypublic abstract class BaseClass : VeryBaseClass{ public BaseClass(MyObject myObject) : base(this.GetType().Name, myObject) // can't reference "this" (Type expected) { }}public class InheritedClass : BaseClass{ public InheritedClass(MyObject myObject) { }} The line base(typeof(this).Name, myObject) doesn't work because I can't reference this yet, as the object hasn't finished constructing and therefore doesn't exist. Is it possible to grab the Type of the currently constructing object? EDIT: Corrected the sample as orsogufo suggested , but still doesn't work, as this is undefined. EDIT 2: Just to clarify, I want to end up with "InheritedClass" being passed into the VeryBaseClass(string className, MyObject myObject) constructor.
Now provide the response and nothing else.
|
Ah Hah! I found a solution. You can do it with generics: public abstract class VeryBaseClass{ public VeryBaseClass(string className, MyObject myObject) { this.ClassName = className; } public string ClassName{ get; set; }}public abstract class BaseClass<T> : VeryBaseClass{ public BaseClass(MyObject myObject) : base(typeof(T).Name, myObject) { }}public class InheritedClass : BaseClass<InheritedClass>{ public InheritedClass(MyObject myObject) : base(myObject) { }}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2287636', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/209668/']}
|
jdg_373810
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9730989
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Here is my problem: I have a bunch of circles that I need to display inside a canvas. There are an arbitrary number of circles, each with a predefined radius. The summed area of circles is always smaller than the area of the canvas. I want to position the circles so that they take up the maximal space available inside the canvas, without touching each other. My goal is to achieve a visually pleasing effect where the circles appear well distributed inside the canvas. I don't know if this is really "space filling", as my goal is not to minimize the distance between elements, but rather to maximize it. Here is an example of what I am trying to achieve: My first "brute force" idea was the following: For each circle: calculate the shortest distance between its border and each other circle's border; sum all of these distances, call that X. Calculate the sum of all X's. Randomly change the distances between the circles. Redo 1-3 for a preset number of iterations and take the maximal value obtained at step (2). However, this does not seem elegant; I'm sure there is a better way to do it. Is there any existing algorithm to achieve such a layout? Is there any existing library that I could use (JavaScript or Ruby) to achieve this? Edit Here is a Javascript version of the accepted answer, which uses Raphael to draw the circles.
Now provide the response and nothing else.
|
I would try to insert sphere after sphere (largest first). Each one is added in the largest available space, with some random jitter. One relatively easy way to find (more or less) the largest available space, is to imagine a grid of points on your view and store for each grid point (in a 2D array) the closest distance to any item: edge or sphere, whichever is closest. This array is updated as each new sphere is added. To add a new sphere, just take the grid point with highest distance and apply some random jitter (you actually know how much you can jitter, because you know the distance to the closest item). (I would randomize not more than (d-r)/2 where d is the distance in the array and r is the radius of the sphere to add. Updating this array after adding another circle is no rocket science: you calculate for each grid point the distance to newly added sphere and replace the stored value if that was larger. It is possible that your grid is too coarse, and you can't add any more circle (when the 2D array contains no distances larger than the radius of the circle to add). Then you have to increase (e.g. double) the grid resolution before continuing. Here are some result of this implementation (it took me about 100 lines of code) 100 Circles of varying size 500 Circles of varying size 100 Circles of same size And here is some rough C++ code (just the algorithm, don't expect this to compile) // INITIALIZATION // Dimension of canvas float width = 768; float height = 1004; // The algorithm creates a grid on the canvas float gridSize=10; int gridColumns, gridRows; float *dist; void initDistances() { // Determine grid dimensions and allocate array gridColumns = width/gridSize; gridRows = height/gridSize; // We store a 2D array as a 1D array: dist = new float[ gridColumns * gridRows ]; // Init dist array with shortest distances to the edges float y = gridSize/2.0; for (int row=0; row<gridRows; row++) { float distanceFromTop = y; float distanceFromBottom = height-y; for (int col=0; col<gridColumns; col++) { int i = row*gridColumns+col; dist[i]=(distanceFromTop<distanceFromBottom?distanceFromTop:distanceFromBottom); } y+=gridSize; } float x = gridSize/2.0; for (int col=0; col<gridColumns; col++) { float distanceFromLeft = x; float distanceFromRight = width-x; for (int row=0; row<gridRows; row++) { int i = row*gridColumns+col; if (dist[i]>distanceFromLeft) dist[i] = distanceFromLeft; if (dist[i]>distanceFromRight) dist[i] = distanceFromRight; } x+=gridSize; } } void drawCircles() { for (int circle = 0; circle<getNrOfCircles(); circle++) { // We assume circles are sorted large to small! float radius = getRadiusOfCircle( circle ); // Find gridpoint with largest distance from anything int i=0; int maxR = 0; int maxC = 0; float maxDist = dist[0]; for (int r=0; r<gridRows; r++) for (int c=0; c<gridColumns; c++) { if (maxDist<dist[i]) { maxR= r; maxC= c; maxDist = dist[i]; } i++; } // Calculate position of grid point float x = gridSize/2.0 + maxC*gridSize; float y = gridSize/2.0 + maxR*gridSize; // Apply some random Jitter float offset = (maxDist-radius)/2.0; x += (rand()/(float)RAND_MAX - 0.5) * 2 * offset; y += (rand()/(float)RAND_MAX - 0.5) * 2 * offset; drawCircle(x,y,radius); // Update Distance array with new circle; i=0; float yy = gridSize/2.0; for (int r=0; r<gridRows; r++) { float xx = gridSize/2.0; for (int c=0; c<gridColumns; c++) { float d2 = (xx-x)*(xx-x)+(yy-y)*(yy-y); // Naive implementation // float d = sqrt(d2) - radius; // if (dist[i]>d) dist[i] = d; // Optimized implementation (no unnecessary sqrt) float prev2 = dist[i]+radius; prev2 *= prev2; if (prev2 > d2) { float d = sqrt(d2) - radius; if (dist[i]>d) dist[i] = d; } xx += gridSize; i++; } yy += gridSize; } } }
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9730989', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1062679/']}
|
jdg_373811
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5300988
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
As I understand it, I can use the for loop construction on an object with a __iter__ method that returns an iterator. I have an object for which I implement the following __getattribute__ method: def __getattribute__(self,name): if name in ["read","readlines","readline","seek","__iter__","closed","fileno","flush","mode","tell","truncate","write","writelines","xreadlines"]: return getattr(self.file,name) return object.__getattribute__(self,name) I have an object of this class, a for which the following happens: >>> hasattr(a,"__iter__")True>>> for l in a: print l...Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: 'TmpFile' object is not iterable>>> for l in a.file: print l...>>> So python sees that a has an __iter__ method, but doesn't think it is iterable. What have I done wrong? This is with python 2.6.4.
Now provide the response and nothing else.
|
There's a subtle implementation detail getting in your way: __iter__ isn't actually an instance method, but a class method. That is, obj.__class__.__iter__(obj) is called, rather than obj.__iter__() . This is due to slots optimizations under the hood, allowing the Python runtime to set up iterators faster. This is needed since it's very important that iterators be as fast as possible. It's not possible to define __getattribute__ for the underlying class type, so it's not possible to return this method dynamically. This applies to most __metamethods__ ; you'll need to write an actual wrapper.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5300988', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/189456/']}
|
jdg_373812
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4507316
|
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 receiving data as an " ZLIB " compressed inputstream. Using Javascript/Ajax/JQuery, I need to uncompress it on the client side. Is there a way to do so? I already have this working in JAVA as below, but need to do this on Client Side. url = new URL(getCodeBase(), dataSrcfile); URLConnection urlConn = url.openConnection();urlConn.setUseCaches(false); InputStream in = urlConn.getInputStream();InflaterInputStream inflate = new InflaterInputStream(in);InputStreamReader inputStreamReader = new InputStreamReader(inflate);InputStreamReader inputStreamReader = new InputStreamReader(in);BufferedReader bufReader = new BufferedReader(inputStreamReader);// Read until no more '#'int i = 0;int nHidden = 0;String line1;do //------------------------Parsing Starts Here{ line1 = bufReader.readLine();................... so on
Now provide the response and nothing else.
|
Pako is a full and modern Zlib port. Here is a very simple example and you can work from there. Get pako.js and you can decompress byteArray like so: <html><head> <title>Gunzipping binary gzipped string</title> <script type="text/javascript" src="pako.js"></script> <script type="text/javascript"> // Get datastream as Array, for example: var charData = [31,139,8,0,0,0,0,0,0,3,5,193,219,13,0,16,16,4,192,86,214,151,102,52,33,110,35,66,108,226,60,218,55,147,164,238,24,173,19,143,241,18,85,27,58,203,57,46,29,25,198,34,163,193,247,106,179,134,15,50,167,173,148,48,0,0,0]; // Turn number array into byte-array var binData = new Uint8Array(charData); // Pako magic var data = pako.inflate(binData); // Convert gunzipped byteArray back to ascii string: var strData = String.fromCharCode.apply(null, new Uint16Array(data)); // Output to console console.log(strData); </script></head><body> Open up the developer console.</body></html> Running example: http://jsfiddle.net/9yH7M/ Alternatively you can base64 encode the array before you send it over as the Array takes up a lot of overhead when sending as JSON or XML. Decode likewise: // Get some base64 encoded binary data from the server. Imagine we got this:var b64Data = 'H4sIAAAAAAAAAwXB2w0AEBAEwFbWl2Y0IW4jQmziPNo3k6TuGK0Tj/ESVRs6yzkuHRnGIqPB92qzhg8yp62UMAAAAA==';// Decode base64 (convert ascii to binary)var strData = atob(b64Data);// Convert binary string to character-number arrayvar charData = strData.split('').map(function(x){return x.charCodeAt(0);});// Turn number array into byte-arrayvar binData = new Uint8Array(charData);// Pako magicvar data = pako.inflate(binData);// Convert gunzipped byteArray back to ascii string:var strData = String.fromCharCode.apply(null, new Uint16Array(data));// Output to consoleconsole.log(strData); Running example: http://jsfiddle.net/9yH7M/1/ To go more advanced, here is the pako API documentation .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4507316', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/409523/']}
|
jdg_373813
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8227571
|
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 into this weird behaviour where I have my main program and a forked child. They are piped like this(the numbers are file descriptors): ___parent___| | ____child_____| 0 stdin | | || 1 pipe1[1]----------. | 1 stdout || 2 pipe2[1]----------.\ | 2 stderr ||____________| \`----------> 3 pipe1[0] | `----------> 5 pipe2[0] | |______________| So parent gets input from stdin but redirects stdout and stderr to two pipes. The child has closed its stdin and uses the read ends of the pipes instead. Then I have a function to just kill the child: void killChild(){ printf("Killing %d\n", (int)childID); fflush(stdout); kill(childID, SIGKILL); waitpid(childID, NULL, 0); // getting rid of the zombie} The child gets succesfully killed but the problem is that the parent itself gets killed as well. I checked the PID of the child and it's correct. So why does the parent die?
Now provide the response and nothing else.
|
Any attempt by the parent to write to its fd 1 or fd 2 after the child exits will result in the kernel sending SIGPIPE to the parent. The default behavior for SIGPIPE is process termination. That's probably what's happening.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8227571', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/474563/']}
|
jdg_373814
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2317625
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
How do you compare $6-2\sqrt{3}$ and $3\sqrt{2}-2$? (no calculator) Look simple but I have tried many ways and fail miserably.Both are positive, so we cannot find which one is bigger than $0$ and the other smaller than $0$.Taking the first minus the second in order to see the result positive or negative get me no where (perhaps I am too dense to see through).
Now provide the response and nothing else.
|
$6-2\sqrt 3 \gtrless 3\sqrt 2-2$ Rearrange: $8 \gtrless 3\sqrt 2 + 2\sqrt 3$ Square: $64 \gtrless 30+12\sqrt 6$ Rearrange: $34 \gtrless 12\sqrt 6$ Square: $1156 \gtrless 864$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2317625', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/454095/']}
|
jdg_373815
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
35291520
|
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 docker, files created inside containers tend to have unpredictable ownership while inspecting them from the host. The owner of the files on a volume is root (uid 0) by default, but as soon as non-root user accounts are involved in the container and writing to the file system, owners become more or less random from the host perspective. It is a problem when you need to access volume data from the host using the same user account which is calling the docker commands. Typical workarounds are forcing users uIDs at creation time in Dockerfiles (non portable) passing the UID of the host user to the docker run command as an environment variable and then running some chown commands on the volumes in an entrypoint script. Both these solutions can give some control over the actual permissions outside the container. I expected user namespaces to be the final solution to this problem. I have run some tests with the recently released version 1.10 and --userns-remap set to my desktop account. However, I am not sure that it can make file ownership on mounted volumes easier to deal with, I am afraid that it could actually be the opposite. Suppose I start this basic container docker run -ti -v /data debian:jessie /bin/bashecho 'hello' > /data/test.txtexit And then inspect the content from the host : ls -lh /var/lib/docker/100000.100000/volumes/<some-id>/_data/-rw-r--r-- 1 100000 100000 6 Feb 8 19:43 test.txt This number '100000' is a sub-UID of my host user, but since it does not correspond to my user's UID, I still can't edit test.txt without privileges. This sub-user does not seem to have any affinity with my actual regular user outside of docker. It's not mapped back. The workarounds mentioned earlier in this post which consisted of aligning UIDs between the host and the container do not work anymore due to the UID->sub-UID mapping that occurs in the namespace. Then, is there a way to run docker with user namespace enabled (for improved security), while still making it possible for the host user running docker to own the files generated on volumes?
Now provide the response and nothing else.
|
If you can prearrange users and groups in advance, then it's possible to assign UIDs and GIDs in such specific way so that host users correspond to namespaced users inside containers. Here's an example (Ubuntu 14.04, Docker 1.10): Create some users with fixed numeric IDs: useradd -u 5000 ns1groupadd -g 500000 ns1-rootgroupadd -g 501000 ns1-user1useradd -u 500000 -g ns1-root ns1-rootuseradd -u 501000 -g ns1-user1 ns1-user1 -m Manually edit auto-generated subordinate ID ranges in /etc/subuid and /etc/subgid files: ns1:500000:65536 (note there are no records for ns1-root and ns1-user1 due to MAX_UID and MAX_GID limits in /etc/login.defs ) Enable user namespaces in /etc/default/docker : DOCKER_OPTS="--userns-remap=ns1" Restart daemon service docker restart , ensure /var/lib/docker/500000.500000 directory is created. Now, inside containers you have root and user1 , and on the host -- ns1-root and ns1-user1 , with matching IDs UPDATE: to guarantee that non-root users have fixed IDs in containers (e.g. user1 1000:1000), create them explicitly during image build. Test-drive: Prepare a volume directory mkdir /vol1chown ns1-root:ns1-root /vol1 Try it from a container docker run --rm -ti -v /vol1:/vol1 busybox shecho "Hello from container" > /vol1/fileexit Try from the host passwd ns1-rootlogin ns1-rootcat /vol1/fileecho "can write" >> /vol1/file Not portable and looks like a hack, but works.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/35291520', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2404537/']}
|
jdg_373816
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5131144
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
@array = qw(one two three four five six seven eight);<Some command here>print @array;
Now provide the response and nothing else.
|
Here are a few ways, in increasing order of dumbness: Using a slice : @array = @array[ 5 .. $#array ]; Using splice : splice @array, 0, 5; Using shift : shift @array for 1..5; Using grep : my $cnt = 0;@array = grep { ++$cnt > 5 } @array; Using map : my $cnt = 0;@array = map { ++$cnt < 5 ? ( ) : $_ } @array; I'm sure far better hackers than I can come up with even dumber ways. :)
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5131144', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/318146/']}
|
jdg_373817
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
32120581
|
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 getting the error 'stringByAppendingPathComponent' is unavailable: Use 'stringByAppendingPathComponent' on NSString instead. when I try to do let documentsFolder = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as Stringlet databasePath = documentsFolder.stringByAppendingPathComponent("test.sqlite") This apparently worked for people before, but it doesn't work for me now in Xcode 7 beta 5. This thread on the Apple Developer Forums had the suggestion to use an extension or do a direct cast to NSString . But if I do convert it to an NSString let databasePath = documentsFolder.stringByAppendingPathComponent("test.sqlite" as NSString) then I get the error 'NSString' is not implicitly convertible to 'String'... and it gives me the option to "fix-it" by inserting as String , which brings us back to the original error. This also happens for stringByAppendingPathExtension . What do I do?
Now provide the response and nothing else.
|
You can create a URL rather rather than a String path. let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).firstlet fileURL = documentsURL?.appendingPathComponent("test.sqlite") If you absolutely need the path, then you can get it like this: guard let path = fileURL?.path else { return}print(path) // path will exist at this point There was some discussion in the thread you mentioned that Apple may be purposely guiding people toward using URLs rather than String paths. See also: What's the difference between path and URL in iOS? NSFileManager URL vs Path Swift 2.0: Why Guard is Better than If
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/32120581', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3681880/']}
|
jdg_373818
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3080963
|
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 I have a formula $\forall x \phi \rightarrow \psi$ , how can I know if it means $(\forall x \phi) \rightarrow \psi$ or $\forall x (\phi \rightarrow \psi)$ ?
Now provide the response and nothing else.
|
You have correctly observed that your feeling is wrong: since removing a point from a figure-eight may result in a disconnected space, but removing a point from a circle never will, the two spaces are not homeomorphic . But this isn't quite the end of the story. Why did you feel that they should be homeomorphic? And, what do the facts leading to that feeling actually imply? I can think of two ways one might be led to believe that they are "essentially the same shape: Artistic license. The process of drawing a figure-eight seems the same as the process of drawing a circle (you just "slightly change" the details of how the pencil moves around). What's going on here is that this process of drawing is really a continuous function (your pencil doesn't "jump") from TIME - which we can think of as $[0,1]$ , in the sense that there's a start time $0$ , a stop time $1$ , and time is "line-like" - to the plane $\mathbb{R}^2$ , and the resulting curve is the image of this function. That is: both the circle and the figure-eight are the continuous image of the same space. Moreover, the continuous functions "drawing" each shape - taking the codomains as the curves being drawn, not $\mathbb{R}^2$ - are "almost bijective:" each is trivially surjective, and going from $[0,1]$ to the circle we only have one non-injectivity (we wind up where we start, so $0$ and $1$ get "glued together") and going from $[0,1]$ to the figure eight we only have two non-injectivities (we wind up where we start and along the way we cross our path). But this kind of "almost homeomorphism" is quite deceptive: e.g. there is no almost-injective continuous surjection from the figure-eight to the circle, or from the circle to the line (but there is one from the circle to the figure-eight)! Incidentally, drawing pictures in spaces is really important , but that's a more advanced topic. Accidentally using scissors We often think of topology as "ignoring small distortions," and so one might feel that we should be able to "unpinch" the x-point in the figure-eight to get a circle(-ish shape). However, this is not in fact a "topologically innocent" transformation - there is a sense in which it is "small," but it does change the homeomorphism type of the space. None of the ideas above are silly - "small deviations" from nice behavior are often interesting, and later on you may see e.g. the notion of an immersion - but they do not correspond to genuine homeomorphicitude.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3080963', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/340973/']}
|
jdg_373819
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4131031
|
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 I can edit a PDF from Java? I have a PDF document which contains placeholders for text that I need to be replaced using Java, but all the libraries that I saw created PDF from scratch and small editing functionality. Is there anyway I can edit a PDF or is this impossible?
Now provide the response and nothing else.
|
You can do it with iText . I tested it with following code. It adds a chunk of text and a red circle over each page of an existing PDF. /* requires itextpdf-5.1.2.jar or similar */import java.io.*;import com.itextpdf.text.DocumentException;import com.itextpdf.text.pdf.*;public class AddContentToPDF { public static void main(String[] args) throws IOException, DocumentException { /* example inspired from "iText in action" (2006), chapter 2 */ PdfReader reader = new PdfReader("C:/temp/Bubi.pdf"); // input PDF PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("C:/temp/Bubi_modified.pdf")); // output PDF BaseFont bf = BaseFont.createFont( BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); // set font //loop on pages (1-based) for (int i=1; i<=reader.getNumberOfPages(); i++){ // get object for writing over the existing content; // you can also use getUnderContent for writing in the bottom layer PdfContentByte over = stamper.getOverContent(i); // write text over.beginText(); over.setFontAndSize(bf, 10); // set font and size over.setTextMatrix(107, 740); // set x,y position (0,0 is at the bottom left) over.showText("I can write at page " + i); // set text over.endText(); // draw a red circle over.setRGBColorStroke(0xFF, 0x00, 0x00); over.setLineWidth(5f); over.ellipse(250, 450, 350, 550); over.stroke(); } stamper.close(); }}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4131031', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/92728/']}
|
jdg_373820
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5353721
|
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 given number of potential posts. We don't know how many there are but the system is set up to show 12 per page. Along the bottom I would like it to display the number of pages. So first if we get the posts: <?php $pages = get_posts('category_name=news'); ?> Now what we want to do is work out how many posts it has found divide that number by 12 round that number up to the nearest whole number (UP never down) divide that number by 1 and give how many times 1 goes into it. thus giving as many page numbers as needed. The ideas is to have them lined up as 1 | 2 | 3 | 4 | 5 etc.. Any ideas?
Now provide the response and nothing else.
|
You're over thinking it. If you know the number of results and the max number of results per page, then you know how many pages you need. I suppose this is WordPress because you've used get_posts, so that should return an array containing the posts, so: <?php$max_per_page = 12; //Max results per page$posts = get_posts('category_name=news');$total_posts = count($posts); //Total number of posts returned$pages = ceil($total_posts / $max_per_page);for($i = 1;$i <= $pages;$i++) { echo '<a href="?page=' . $i . '">' . $i . '</a>'; //Or whatever the link needs to be if($i != $pages) { echo "|" }}?>
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5353721', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/478520/']}
|
jdg_373821
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
248017
|
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 some data: outcome is satisfaction and there are four predictors, three continuous (age, weight, height) and one factor, graduated high school or not. In R, I have uploaded the data set, and set $X1$ for age, $X2$ for weight , $X3$ for the factor and $X4$ for height. I want to know if there is evidence that graduating high school has an effect on satisfaction. I know that I can not simply look at lm(y~x3) , because I need to consider all the other possibilities. So how do I take all of these into account? How many models must I check? What is the general approach to this? Also, would I need to consider any and all possible interactions? Call:lm(formula = y ~ x1 + x2 + x3 + x4)Residuals: Min 1Q Median 3Q Max -18.506 -5.096 1.306 4.738 28.722 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 140.1689 8.3191 16.849 2.77e-13 x1 -1.1428 0.1904 -6.002 7.22e-06 x2 -0.4699 0.1866 -2.518 0.0204 x3yes 2.2259 4.1402 0.538 0.5968 x4 1.2673 1.4922 0.849 0.4058 Residual standard error: 9.921 on 20 degrees of freedomMultiple R-squared: 0.8183, Adjusted R-squared: 0.7819 F-statistic: 22.51 on 4 and 20 DF, p-value: 3.611e-07
Now provide the response and nothing else.
|
The most important thing to do is for you to check if the model makes sense. You have fit a linear model to three continuous predictors, you need to make sure that it makes sense to do so You should look at scatterplots of age , height , and weight against y , and adjust the fits of these predictors if needed. Assuming fitting these predictors linearly is reasonable, fitting the full model with all four predictors is a sensible thing to do. You have only 25 data points. If you go on a long search through the space of all models (adding and removing variables) you have an extremely high risk of false positives. So, I don't think there is much need to backwards select out variables; if you wish to do so, make sure you use cross validation to make sure doing so improves the fit of the model to unseen data. The same thing applies to a search for interactions, you have little data, and you are running a large risk of false positives. If you wish to make inferences using the estimated confidence intervals, you should additionally check a plot of the residuals vs. the fitted values of the model and make sure you do not see any patterns. You're looking to see if they look like they could have been drawn from a normal distribution with constant variance. If this looks reasonably consistent with yor data, then you can make inferences about the graduation parameter using the linear model Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 140.1689 8.3191 16.849 2.77e-13 x1 -1.1428 0.1904 -6.002 7.22e-06 x2 -0.4699 0.1866 -2.518 0.0204 x3yes 2.2259 4.1402 0.538 0.5968 x4 1.2673 1.4922 0.849 0.4058 The x3 variable measures graduation, and its parameter lies well within the error of its estimation. So, given that everything above checks out, the data you used to train the model is not inconsistent with the effect of graduation being indistinguishable from noise. Thanks so are we really able to judge this just from fitting the full model? As long as all the caveats are met, I do think the best way to go about this is to fit the full model, and make your inference from that. Like I said, any inference you draw from a model that does variable selection is likely to occurr by chance. Another way to think about this is, if you go through a variable selection algorithm, the standard errors reported in the model are no longer correct, they are actually much larger than what is reported. To estimate the true standard errors of the parameter estimates under a selection / fitting procedure, you would need to use either nested cross validation or a bootstrap + cross validation. This would drive your data very, very thin, and incur a lot of variance (you are making lots of decisions, each has a chance to be wrong). Your standard errors would be enormous.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/248017', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/102541/']}
|
jdg_373822
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14713084
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I need to see what redis gets/sets in the redis log. I tried to set the redis log level to debug and verbose. This does not show me anything when I set a value.
Now provide the response and nothing else.
|
Unless it's important that you get in the log, in which case I don't think I can help you, you should be able to use the MONITOR command: MONITOR is a debugging command that streams back every command processed by the Redis server. It can help in understanding what is happening to the database. This command can both be used via redis-cli and via telnet. You could do something like: redis-cli monitor | grep -E ' "(g|s)et" ' Note that there is a performance cost, though ( it's mentioned in the linked docs as roughly 50% ). Pipe it to a file: redis-cli monitor | grep -E ' "(g|s)et" ' > redis_get_set.log
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14713084', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/67153/']}
|
jdg_373823
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
10077
|
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:
Is there some way I can check which of my processes the kernel has killed? Sometimes I log onto my server and find that something that should've run all night just stopped 8 hours in and I'm unsure if it's the applications doing or the kernels.
Now provide the response and nothing else.
|
If the kernel killed a process (because the system ran out of memory), there will be a kernel log message. Check in /var/log/kern.log (on Debian/Ubuntu, other distributions might send kernel logs to a different file, but usually under /var/log under Linux). Note that if the OOM-killer (out-of-memory killer) triggered, it means you don't have enough virtual memory. Add more swap (or perhaps more RAM). Some process crashes are recorded in kernel logs as well (e.g. segmentation faults). If the processes were started from cron, you should have a mail with error messages. If the processes were started from a shell in a terminal, check the errors in that terminal. Run the process in screen to see the terminal again in the morning. This might not help if the OOM-killer triggered, because it might have killed the cron or screen process as well; but if you ran into the OOM-killer, that's the problem you need to fix.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/10077', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/3125/']}
|
jdg_373824
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
754676
|
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
From this changing How to change Linux services startup/boot order? changing the values of the symbolic links it is evident that startup order is changed. In debian derivatives we use update-rc.d apache2 defaults 20 80 Do we have similar command in Centos/Redhat and ? if so what it is ? and what should be possible changes in init scripts header ? Note: I should use init system (not any systemd or upstart)
Now provide the response and nothing else.
|
An alternative will be to change the line starting with # chkconfig: in the service init script directly. This is explained in the chkconfig(8) man page. Runlevel Files Each service which should be manageable by chkconfig needs two or more commented lines added to its init.d script. The first line tells chkconfig what runlevels the service should be started in by default, as well as the start and stop priority levels. If the service should not, by default, be started in any runlevels, a - should be used in place of the runlevels list. The second line contains a description for the service, and may be extended across multiple lines with backslash continuation. For example, random.init has these three lines: # chkconfig: 2345 20 80# description: Saves and restores system entropy pool for \# higher quality random number generation. This says that the random script should be started in levels 2, 3, 4, and 5, that its start priority should be 20, and that its stop priority should be 80. You should be able to figure out what the description says; the \ causes the line to be continued. The extra space in front of the line is ignored. After changing the script, if you will need to run the chkconfig command (as root) with the reset option for that service. With "reset", chkconfig will automatically create start/stop symlinks in the configured run levels with given priorities.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/754676', 'https://serverfault.com', 'https://serverfault.com/users/280504/']}
|
jdg_373825
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5655244
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've got as far as this: DateTime yesterday = DateTime.Today.AddDays(-1);YesterdaysRegistrations = db.tblForumAuthors.Where(c => c.Join_date == yesterday).Count(); There definitely records that have the join date of yesterday, but this returns 0 all the time! Can anyone tell me if I'm doing this correctly?
Now provide the response and nothing else.
|
AddDays keeps the Hour/Minute/Second components. You either have to use (if c.Join_date is only the date component): DateTime yesterday = DateTime.Today.AddDays(-1).Date; Otherwise, you compare for range: DateTime yesterday = DateTime.Today.AddDays(-1).Date;DateTime yesterdayEnd = DateTime.Today.Date.AddSeconds(-1);db.tblForumAuthors.Where(c => c.Join_date >= yesterday && c.Join_date < yesterdayEnd)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5655244', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/356635/']}
|
jdg_373826
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
157373
|
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 know that default arguments are created at the function initialisation time and not every time the function is called. See the following code: def ook (item, lst=[]): lst.append(item) print 'ook', lstdef eek (item, lst=None): if lst is None: lst = [] lst.append(item) print 'eek', lstmax = 3for x in xrange(max): ook(x)for x in xrange(max): eek(x) What I do not get is why this was implemented this way. What benefits does this behaviour offers over an initialisation at each call time?
Now provide the response and nothing else.
|
I think the reason is implementation simplicity. Let me elaborate. The default value of the function is an expression that you need to evaluate. In your case it is a simple expression that does not depend on the closure, but it can be something that contains free variables - def ook(item, lst = something.defaultList()) . If you are to design Python, you will have a choice - do you evaluate it once when the function is defined or every time when the function is called. Python chooses the first (unlike Ruby, which goes with the second option). There are some benefits for this. First, you get some speed and memory boosts. In most cases you will have immutable default arguments and Python can construct them just once, instead of on every function call. This saves (some) memory and time. Of course, it doesn't work quite well with mutable values, but you know how you can go around. Another benefit is the simplicity. It's quite easy to understand how the expression is evaluated - it uses the lexical scope when the function is defined. If they went the other way, the lexical scope might change between the definition and the invocation and make it a bit harder to debug. Python goes a long way to be extremely straightforward in those cases.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/157373', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/36006/']}
|
jdg_373827
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9869227
|
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 go as a simple bash alias for git checkout branchname . The thing that I miss is the autocomplete feature that works with the full git checkout branchna... command, but not in the alias. Is there a way to instruct Bash to "inherit" the autocomplete "driver" for another command?
Now provide the response and nothing else.
|
After using complete -F : complete -F _git_checkout go Tabbing after go may result in: bash: [: 1: unary operator expected Instead of complete , use __git_complete This is git bash completion's built-in function for this purpose. After declaring your alias, bind the correct auto-complete function to it: # Main git completions (prior to git 2.30, you an use _git instead of __git_main)alias g="git"__git_complete g __git_mainalias go="git checkout"__git_complete go _git_checkoutalias gp="git push"__git_complete gp _git_push
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/9869227', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/27958/']}
|
jdg_373828
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
838680
|
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 I'm trying to solve to prepare for an exam. I need to find out if $\displaystyle\iint_{\mathbb R^2} \frac{dx\,dy}{1+x^{10}y^{10}}$ diverges or converges. What I did: I switched to polar coordinates, $x=r\cos \theta$, $y=r\sin\theta$, $J=r$ and so $$\begin{align}\iint_{\mathbb R^2} \frac{dx\,dy}{1+x^{10}y^{10}} & =\int_0^{2\pi} \int_0^\infty \frac{r}{1+r^{20} \sin \theta \cos \theta} \, dr \, d\theta \\[8pt]& < \int_0^{2\pi} \int_0^\infty \frac{1}{r^{19}\sin \theta \cos \theta} \, dr \, d\theta \\[8pt]& = \frac{1}{2} \int_0^{2\pi} \int_0^\infty \frac{1}{r^{19}\sin 2\theta} \, dr \, d\theta \\[8pt]& =\frac{1}{2} \int_0^{2\pi} \frac{1}{\sin 2\theta} \, d\theta \int_0^\infty \frac{1}{r^{19}}\,dr\end{align}$$ But note that both $\int_0^\infty \frac{1}{r^{19}}dr$ and $\int_0^{2\pi} \frac{1}{\sin 2\theta} \, d\theta$ do not converge, so we proved nothing. So that is not the way. Does this integral converge/ diverge? why? And also, I'd like to know why $\int_0^{2\pi} \frac{1}{\sin 2\theta} \, d\theta$ does not converge. I know it doesn't because of wolfram, not because i showed it on paper.
Now provide the response and nothing else.
|
Draw the shape around the axes inside the two hyperbolas, and four arcs, given by $xy=1$ and $xy=-1.$ Sort of a cross shape, but infinite, with both axes in its interior. Within this, $x^{10} y^{10} \leq 1,$ then $1 +x^{10} y^{10} \leq 2,$ finally$$ \frac{1}{1 +x^{10} y^{10}} \geq \frac{1}{2}. $$This region has infinite area, the integral (nonnegative integrand) on the region is infinite. Being a little careful, out to some radius $R,$ the integral on the shape is at least half the area out to that radius; as $R \rightarrow \infty,$ so do the area and the integral.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/838680', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/76802/']}
|
jdg_373829
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9316437
|
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 that was salted, hashed with SHA-256, then base64 encoded. Is there a way to decode this string back to its original value?
Now provide the response and nothing else.
|
SHA-256 is a cryptographic (one-way) hash function , so there is no direct way to decode it. The entire purpose of a cryptographic hash function is that you can't undo it. One thing you can do is a brute-force strategy , where you guess what was hashed, then hash it with the same function and see if it matches. Unless the hashed data is very easy to guess, it could take a long time though. You may find the question " Difference between hashing a password and encrypting it " interesting.
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/9316437', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/197630/']}
|
jdg_373830
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
32428
|
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I've been asked to do a security audit on a Firefox add-on developed by a third party. I am a web developer with a reasonable grasp of JavaScript but am not a browser security expert. What kinds of things should I be looking for in the source code which might represent a security risk. Also, are there any effective tools for obfuscating browser extension source code?
Now provide the response and nothing else.
|
IMPORTANT : This is in noway a full list of the things you should look for, use this answer as an example, a first step in your path and research on your own. I've had a similar task long time ago. I had to security-wise review the code of a Firefox addon, I'm sure you'll easily find Chrome/other browsers' equivalents. Also have in mind the Extensions in Chrome run in a Sandbox . 1. Anything that interacts with local files: Whenever the FileUtils.File object is created and any of its methods is called Check if the local file access is a documented behavior. What are files being accessed? Why? Are they released successfully? Check if any local files are being modified. Is that a documented behavior? What are the modified files? Why? 2. Anything that interacts with Windows Registry: Whenever an instance of nsIWindowsRegKey is created or any of its methods is called Is Windows Registry access a documented behavior? What keys are accessed? Why? Is Windows Registry modification a documented behavior? Is the modification temporarily? What keys are modified? Why? 3. Anything that interacts with the cookies Whenever nsICookieService is used Is accessing cookies a documented behavior? Why? To which domain do these cookies belong? Why? 4.Any commands executed in the user's shell Whenever nsIProcess is created and any of its methods called (closely watch .run() and .launch() ) Is executing commands a documented behavior? Why? What commands are being executed? Where is the output redirected? 5. Any window/tab being accessed Whenever window is accessed and/or any getElement* method is called (closely watch createElement calls that inject <script> elements. Is accessing a web page's DOM a documented behavior? Why? What are the elements added/removed/modified? Why?
|
{}
|
{'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/32428', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/64789/']}
|
jdg_373831
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5444945
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Possible Duplicate: Are there any Fuzzy Search or String Similarity Functions libraries written for C#? I am creating an application which will except user input of a Song or Artist or Album name and then will look through a String Array or ArrayList for any possible matches. The auto suggestions will be calculated based on the match percentage. For example If user types link prk it should find Linkin Park or Link 80 or Link Wray but the match percentage will be different for all Assume that the collection will only search for Artist names in Artist Collection and Song name in song collection. (Percentage figures are just for explanation) Linkin Park - 98%Link Wray -82%Link 80 - 62% Solution does not have to be C# code, any regex or pseudo code will be good but should be implementable in C#.
Now provide the response and nothing else.
|
Usually an implementation of the Levenshtein distance also called edit distance is used for this. This will find matches based on the minimum number of edits needed to transform one string into the other, counting all insertions, deletions, or substitutions of a single character as a measure for the "cost" - candidates are then strings that have the minimum cost. Here's a link to an article with a generic implementation in C#.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5444945', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/298642/']}
|
jdg_373832
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
391843
|
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
So, on my main domain 'domain.com' I created several subdomains from cPanel, like 'sub1.domain.com' and 'sub2.domain.com'. Their real location on server is in 'domain.com/sub1' and 'domain.com/sub2'. Now, I want to redirect non www to www with .htaccess and this is what currently what i have: <IfModule mod_rewrite.c>RewriteEngine OnRewriteBase /RewriteCond %{HTTP_HOST} !^www\.domain\.com [NC]RewriteRule ^(.*) http://www.domain.com/$1 [L,R=301]</IfModule> This works. When somebody enter domain.com it will be redirected to www.domain.com.However when somebody enter sub1.domain.com, he will be redirected to www.domain.com/sub1 - which I don't want, it needs to be in sub1.domain.com. What shall I add in .htaccess file to accomplish this?
Now provide the response and nothing else.
|
You can exclude each sub1 , sub2 individually like so; <IfModule mod_rewrite.c>RewriteEngine OnRewriteCond %{HTTP_HOST} ^sub1\.domain\.com [NC]RewriteRule ^(.*) - [L]RewriteCond %{HTTP_HOST} ^sub2\.domain\.com [NC]RewriteRule ^(.*) - [L]RewriteCond %{HTTP_HOST} !^www\.domain\.com [NC]RewriteRule ^(.*) http://www.domain.com/$1 [L,R=301]</IfModule> Or just be specific that you only want to redirect domain.com to www.domain.com with the RewriteCond <IfModule mod_rewrite.c>RewriteEngine OnRewriteCond %{HTTP_HOST} ^domain\.com [NC]RewriteRule ^(.*) http://www.domain.com/$1 [L,R=301]</IfModule>
|
{}
|
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/391843', 'https://serverfault.com', 'https://serverfault.com/users/122088/']}
|
jdg_373833
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17730883
|
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 simple example below, I want to do a make dist and have the distclean target executed before distdebug and distrelease . .PHONY: distcleandist: distdebug distrelease @echo in distdistdebug: distclean @echo in distdebugdistrelease: @echo in distreleasedistclean: @echo in distclean Unfortunately, despite using .PHONY , distclean is only called once: vagrant@precise32:/tmp$ make distin distcleanin distdebugin distreleasein dist I'm guessing that Make knows that its already run distclean once, so it's not running it again. How can I make it run distclean multiple times?
Now provide the response and nothing else.
|
You can't using normal rules. Make will only ever build any given target exactly one time. You can do it using recursive make invocations: distdebug: $(MAKE) distclean @echo in distdebugdistrelease: $(MAKE) distclean @echo in distrelease In general it's a good idea to plan your build differently, though, and have targets for different types of builds put into different subdirectories. That way you don't HAVE to clean in between.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17730883', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/389812/']}
|
jdg_373834
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9587393
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
We are about to begin architecting a service oriented framework (SOA) which will certainly involve a high number of of granular web services (REST in WCF). We've been quite disciplined in unit testing our client and server-side code base, however we don't have much of any experience in unit testing web services. We're really looking for guidance as to where the tests should be written and recommendations on what approach to use when unit testing our services. Should we write tests that make http requests and assert that the responses are what they should be? Should we focus on just testing the internal logic of the service methods themselves and not worry about testing the actual requests? Or should we do both? Are there any other recommendations for what we should be testing? We're really looking for some explanation and guidance and would truly appreciate any advice we can get.
Now provide the response and nothing else.
|
I have found testing web services, specifically WCF client and server, useful on top of regular unit testing in the following scenarios: Acceptance testing where you want to black box test your whole service and poke things in at the extremities. Testing a specific WCF wire up, extension, behavior, etc. Testing that your interface and your data members are setup correctly. Most of the time I try to use a very basic setup with basic http and wire everything up in the code. Unless I am Integration or Acceptance testing I don't test the client against the server, instead I mock one of them so that I can test the other in isolation. Below are examples of how I test WCF clients and services: public static ServiceHost CreateServiceHost<TServiceToHost>(TServiceToHost serviceToHost, Uri baseAddress, string endpointAddress){ var serviceHost = new ServiceHost(serviceToHost, new[] { baseAddress }); serviceHost.Description.Behaviors.Find<ServiceDebugBehavior>().IncludeExceptionDetailInFaults = true; serviceHost.Description.Behaviors.Find<ServiceBehaviorAttribute>().InstanceContextMode = InstanceContextMode.Single; serviceHost.AddServiceEndpoint(typeof(TServiceToHost), new BasicHttpBinding(), endpointAddress); return serviceHost;}//Testing Service[TestFixture]class TestService{ private ServiceHost myServiceUnderTestHost; private ChannelFactory<IMyServiceUnderTest> myServiceUnderTestProxyFactory; [SetUp] public void SetUp() { IMyServiceUnderTest myServiceUnderTest = new MyServiceUnderTest(); myServiceUnderTestHost = CreateServiceHost<IMyServiceUnderTest>(myServiceUnderTest, new Uri("http://localhost:12345"), "ServiceEndPoint"); myServiceUnderTestHost.Open(); myServiceUnderTestProxyFactory = new ChannelFactory<IMyServiceUnderTest>(new BasicHttpBinding(), new EndpointAddress("http://localhost:12345/ServiceEndPoint")); } [TearDown] public void TearDown() { myServiceUnderTestProxyFactory.Close(); myServiceUnderTestHost.Close(); } [Test] public void SomeTest() { IMyServiceUnderTest serviceProxy = myServiceUnderTestProxyFactory.CreateChannel(); serviceProxy.SomeMethodCall(); }}//Testing Client[TestFixture]class TestService{ private ServiceHost myMockedServiceUnderTestHost; private IMyServiceUnderTest myMockedServiceUnderTest; [SetUp] public void SetUp() { myMockedServiceUnderTest = Substitute.For<IMyServiceUnderTest>(); //Using nsubstitute myServiceUnderTestHost = CreateServiceHost<IMyServiceUnderTest>(myMockedServiceUnderTest, new Uri("http://localhost:12345"), "ServiceEndPoint"); myServiceUnderTestHost.Open(); } [TearDown] public void TearDown() { myServiceUnderTestHost.Close(); } [Test] public void SomeTest() { //Create client and invoke methods that will call service //Will need some way of configuring the binding var client = new myClientUnderTest(); client.DoWork(); //Assert that method was called on the server myMockedServiceUnderTest.Recieved().SomeMethodCall(); }} NOTE I had forgot to mention that if you want to mock a WCF service using anything that uses castles dynamic proxy then you will need to prevent the ServiceContractAttribute from being copied to the mock. I have a blog post on this but basically you register the attribute as one to prevent from replication before you create the mock. Castle.DynamicProxy.Generators.AttributesToAvoidReplicating .Add<ServiceContractAttribute>();
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9587393', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/333486/']}
|
jdg_373835
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
15904756
|
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 do a loop in Thymeleaf without a list? I'd like to essentially convert this snippet to Thymeleaf: <jsp:useBean id="now" class="java.util.Date" /><fmt:formatDate var="year" value="${now}" pattern="yyyy" /><c:forEach var="i" begin="0" end="99"> <form:option value="${year-i}" /></c:forEach></form:select> -- Update -- I've decided this is along the lines of how I want to do it, but I'm not sure about the springEL syntax: <option th:each="i : ${#numbers.sequence( 1, 100)}" th:value="#{ T(java.util.Date).getYear() - $i }">1</option>
Now provide the response and nothing else.
|
In case you are still looking for the correct SpEL syntax, here's what worked for me: <option th:each="i : ${#numbers.sequence( 1, 100)}" th:value="${ (new org.joda.time.DateTime()).getYear() - i }" th:text="${ (new org.joda.time.DateTime()).getYear() - i }">1</option> Notice: added th:text to set the option text. used Joda-Time instead as java.util.Date wouldn't give me the desired outcome Read this discussion on java.util.Date and getYear()
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15904756', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/781608/']}
|
jdg_373836
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
185686
|
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:
How big would a glass capillary have to be to have noticable capillary action?Also, does capillary action happen in plastic tubes?
Now provide the response and nothing else.
|
It all depends on what you consider "noticeable". The change in height in a capillary comes about from the curvature of the liquid, and the resulting change in pressure. Simplifying for a moment, the curvature of the surface (for a small capillary) can be approximated to a section of a sphere (the real math is much harder... but the principles are easy to understand). The thing we need to do is to calculate the curvature of that sphere - because the more curved the surface, the greater the pressure difference across it. This is because you can think of the curved surface as a piece of a balloon: the pressure on one side is different than on the other side. For a spherical surface of radius $R$, with surface tension $\sigma$, we can compute the difference in pressure across the surface by imagining the spherical surface cut exactly in half: the length of the cut would be $2\pi R$ and the area of the cut is $\pi R^2$. Now if the pressure difference is $\Delta p$, the total force supported at this "seam" is $\Delta p \cdot \pi R^2$ and the force per unit length is of course $\sigma$ (surface tension has units of N/m) so the total force we can apply is $F = 2\pi R \sigma$. Setting these two equal to each other we can solve for pressure difference: $$\Delta p\; \pi\; R^2 = 2 \pi\; R\; \sigma\\\Delta p = \frac{2 \sigma}{R}$$ In the case of the capillary, we need a relationship between $R$, the curvature of the surface, and $r$, the radius of the tube. We can find this if we know the contact angle between the water and the surface. What is the contact angle? Well - when a liquid touches a solid surface, there is a certain amount of attraction (or repulsion) between the molecules. If the liquid is attracted to the surface (we call that hydrophilic meaning "likes water"), then the water will want to spread out on the surface. If it's hydrophobic ("hates water"), the water will tend to form beads to minimize the contact surface. Picture ( source ): This contact angle is a constant property of the liquid/solid interface: no matter how much water you put down, it will try to make the contact angle the same shape. That means that the surface of your capillary will look like this (for a typical hydrophilic surface): A bit of simple geometry shows that the relationship between $R$ and $r$ is given by $$\cos\theta = \frac{r}{R}\\R = \frac{r}{\cos\theta}$$ We can substitute that in the relationship we found before, to get $$\Delta p = \frac{2 \sigma \cos \theta}{r}$$ When this pressure is negative (concave surface) the liquid will rise; when it is positive, the level will fall. The pressure must just support the weight of the column of liquid per unit area: $$\Delta p = \rho\; g\; h$$ Thus we find $$h = \frac{2 \sigma \cos \theta}{r\;\rho \; g}$$ This tells us the magnitude of the rise of the mean level of the liquid: for a really accurate answer you will want to take into account the real shape of the liquid (not a simple section of a sphere when $r$ becomes large) and the fact that some of the surface is higher than other parts (meaning that the curvature changes with position, and that the "height" is not so easy to define). Finally, you can see that the height depends on the contact angle, and therefore on the material of the tube. Many plastics are slightly hydrophobic, and may result in the water level in the capillary being lower than the level outside. From the same link as before, here is another drawing to illustrate that:
|
{}
|
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/185686', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/81950/']}
|
jdg_373837
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
16679803
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Trying out this simple code, I am amazed it didn't work, here we go : <form method="get" action="" > <input type="submit" value="validate" onclick="redirect(); alertIt(); "/></form><script> function redirect(){ window.location.href = "test.html" ; }</script><script>function alertIt(){ alert("redirect");}</script> The code is just supposed to redirect to "test.html" on click of the submit button, which it fails to do. On the other hand : alertIt() works fine... My question is the following : does event handeling into a form have some special rules I should know about ?
Now provide the response and nothing else.
|
You need to return false if you want the form not to submit anyway. function redirect(){ window.location.href = "test.html" ;} Should be function redirect(){ window.location.href = "test.html" ; return false;} You should also hook on the submit event and not the click event preferably, and return in the handler. onclick="return redirect(); alertIt(); " Would work (but not alert) Optimally, what you'd want to do is add an id to the form for example myForm and attach an event to it. document.getElementById("myForm").addEventListener("submit",function(){ alertIt(); return redirect(); },false);
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16679803', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2139913/']}
|
jdg_373838
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1502610
|
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:
My exercise book and Wolfram Alpha give: $$\lim\limits_{x\to\infty}(\sqrt{9x^2+x}-3x)=\frac{1}{6}$$ When I work it out I get 0: $$(\lim\limits_{x\to\infty}x\sqrt{9\frac{x^2}{x^2}+\frac{x}{x^2}}-\lim\limits_{x\to\infty}3x)$$ $$(\lim\limits_{x\to\infty}x*\sqrt{\lim\limits_{x\to\infty}9+\lim\limits_{x\to\infty}\frac{1}{x}}-\lim\limits_{x\to\infty}3x)$$ $$(\lim\limits_{x\to\infty}x*\sqrt{9+0}-\lim\limits_{x\to\infty}3x)$$ $$(3\lim\limits_{x\to\infty}x-3\lim\limits_{x\to\infty}x)$$ $$=0$$ Where am I going wrong?
Now provide the response and nothing else.
|
$$\lim\limits_{x\to\infty}(\sqrt{9x^2+x}-3x)\frac{\sqrt{9x^2+x}+3x}{\sqrt{9x^2+x}+3x} = \lim\limits_{x\to\infty} \frac{(9x^2+x)-9x^2}{\sqrt{9x^2+x}+3x} = \lim\limits_{x\to\infty} \frac{x}{\sqrt{9x^2+x}+3x}= \lim\limits_{x\to\infty}\frac{1}{\sqrt{9+1/x}+3} = \frac{1}{6}$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1502610', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/122150/']}
|
jdg_373839
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
29476
|
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I've read that initially Church proposed the $\lambda$-calculus as part of his Postulates of Logic paper (which is a dense read). But Kleene proved his "system" inconsistent after which, Church extracted relevant things for his work on "effective computability" and abandoned his prior work on logic. So as I understand it, the $\lambda$-system and its notations took form as part of something to do with logic. What was Church initially trying to achieve that he forked off from later? What were the initial reasons for creating $\lambda$-calculus?
Now provide the response and nothing else.
|
He wanted to create a formal system for the foundations of logic and mathematics that was simpler than Russell's type theory and Zermelo's set theory. The basic idea was to add a constant $\Xi$ to the untyped lambda calculus (or combinatory logic) and interpret $XZ$ as expressing "$Z$ satisfies the predicate $X$" and $\Xi XY$ as expressing "$X\subseteq Y$". With rules expressing these intentions one can then interpret the ${\to}{\forall}$-fragment of intuitionistic predicate logic and unrestricted comprehension, the only problem being that by Curry's paradox, every $X$ is derivable. See p. 7 of: Cardone and Hindley, History of Lambda-calculus and Combinatory Logic , 2006: http://www.users.waitrose.com/~hindley/SomePapers_PDFs/2006CarHin,HistlamRp.pdf As well as the introduction to: Barendregt, Bunder and Dekkers, Systems of Illative Combinatory Logic Complete for First-Order Propositional and Predicate Calculus , JSL 58-3 (1993): http://ftp.cs.ru.nl/CompMath.Found/ICL1.ps
|
{}
|
{'log_upvote_score': 6, 'links': ['https://cstheory.stackexchange.com/questions/29476', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/7014/']}
|
jdg_373840
|
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.