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
25581183
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 having a problem with the following scenario I am developing a chatting application wish a user can send a link in to a specific page like Hey check out my link www.link1.com what i am doing is using a reg-expression to detect the link and replace it by <a href > this is the code i am using : public string ReplaceMsgHyperLinkIfExist(string msg) { Regex r= new Regex(@"((?:(?:https?|ftp|gopher|telnet|file|notes|ms-help):(?://|\\\\)(?:www\.)?|www\.)[\w\d:#@%/;$()~_?\+,\-=\\.&]+)"); Match m = r.Match(msg); while (m.Success) { string val="<a href='"+m.Value+"' title='"+m.Value+"' >"+m.Value+"</a>"; msg= msg.Replace(m.Value,val); m = m.NextMatch(); } return msg; } The problem is when the message is sent and the user click on it ,it's not redirecting properly,for example if the user send this message hi www.google.com in c# when the receiver click on it it redirect to localhost:2525/www.google.com (asp.net is considering the link as a subfolder and not as an actual path for another website what would be the solution for that ? Now provide the response and nothing else.
So you want to dispatch events to their handlers for the current state. To dispatch to the current state, subscribing each state as it becomes active, and unsubscribing it as it becomes inactive is rather cumbersome. It is easier to subscribe an object that knows the active state, and simply delegates all events to the active state. To distinguish events, you can use separate event objects, and then distinguish them with the visitor pattern , but that's quite a bit of boilerplate code. I'd only do this if I have other code that treats all events the same (for instance, if events must be buffered before delivery). Otherwise, I'd simply do something like interface StateEventListener { void onEventX(); void onEventY(int x, int y); void onEventZ(String s);}enum State implements StateEventListener { initialState { @Override public void onEventX() { // do whatever } // same for other events }, // same for other states}class StateMachine implements StateEventListener { State currentState; @Override public void onEventX() { currentState.onEventX(); } @Override public void onEventY(int x, int y) { currentState.onEventY(x, y); } @Override public void onEventZ(String s) { currentState.onEventZ(s); }} Edit If you have many event types, it might be better to generate the boring delegation code at runtime using a bytecode engineering library, or even a plain JDK proxy: class StateMachine2 { State currentState; final StateEventListener stateEventPublisher = buildStateEventForwarder(); StateEventListener buildStateEventForwarder() { Class<?>[] interfaces = {StateEventListener.class}; return (StateEventListener) Proxy.newProxyInstance(getClass().getClassLoader(), interfaces, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { return method.invoke(currentState, args); } catch (InvocationTargetException e) { throw e.getCause(); } } }); }} This makes the code less readable, but does eliminate the need to write delegation code for each event type.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25581183', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1428318/']}
jdg_72941
stackexchange
llm_judgeable_groundtruth_similarity
61353534
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 can I access to the data in this JSON from this website https://corona.lmao.ninja/v2/historical/usacounties/florida?lastdays=1 { "province": "florida", "county": "bay", "timeline": { "cases": { "4/20/20": 57 //How can I name this line inside of struct Cases }, "deaths": { "4/20/20": 2 } } } This is the Decodable JSON in SwiftUI struct Florida: Codable, Identifiable { let id = UUID() var county: String var timeline: Cases}struct Cases: Codable, Identifiable { let id = UUID() var cases: ?????} Now provide the response and nothing else.
Updated answer for newer versions of plotly: For recent plotly versions, a larger number of the attributes of a plotly figure object are readable through fig.data . Now you can retrive the color for a line without defining it or following a color cycle through: fig.data[0].line.color To make things a bit more flexible compared to my original answer, I've put together an example where you can have multiple markers on the same line. Markers are organized in a dict like so: markers = {'trace01':[[2,5], [4,9]], 'trace02':[[3,9]]} And the essence of my approach to getting the plot below is this snippet: for d in fig.data: if d.name in markers.keys(): for m in markers[d.name]: fig.add_traces(go.Scatter(x=[m[0]], y = [m[1]], mode='markers', name=None, showlegend=False, marker=dict(color=d.line.color,size=15) ) ) Here you can see that I'm not actually using fig.data[0].line.color , but rather color=d.line.color since I've matched the markers with the traces by name through : for d in fig.data: if d.name in markers.keys(): for m in markers[d.name]: Plot: Complete code: import plotly.graph_objects as gofig = go.Figure()fig.add_trace(go.Scatter( x=[0, 1, 2, 3, 4, 5], y=[0, 3, 5, 7, 9, 11], name='trace01', line=dict(color='blue'), mode='lines', ))fig.add_trace(go.Scatter( x=[0, 1, 2, 3, 4, 5], y=[3, 5, 7, 9, 11, 13], name='trace02', line=dict(color='red'), mode='lines' ))markers = {'trace01':[[2,5], [4,9]], 'trace02':[[3,9]]}for d in fig.data: if d.name in markers.keys(): for m in markers[d.name]: fig.add_traces(go.Scatter(x=[m[0]], y = [m[1]], mode='markers', name=None, showlegend=False, marker=dict(color=d.line.color,size=15) ) ) fig.show() Original answer for older versions You can retrieve the color of a trace using: fig['data'][0]['line']['color'] But you'll have to specify the color of the trace to be able to do so. Or you can make sure that the color of the markers follow the same sequence as the traces. But we can get to all the details if this is in fact what you're trying to accomplish: If you study the code snippet below, you'll see that I, unlike you, havent defined the markers in the same go as the lines. Rather, I've added the traces as pure lines with mode='lines' and then added separate traces for the markers with mode='markers' . When doing the latter, I've retrieved the colors of the corresponding lines using color=data['line']['color'] in a loop: import plotly.graph_objects as gofig = go.Figure()fig.add_trace(go.Scatter( x=[0, 1, 2, 3, 4, 5], y=[0, 3, 5, 7, 9, 11], name='trace01', line=dict(color='blue'), mode='lines', ))fig.add_trace(go.Scatter( x=[0, 1, 2, 3, 4, 5], y=[3, 5, 7, 9, 11, 13], name='trace02', line=dict(color='red'), mode='lines' ))markers = [[2,5], [3,9]]for i, data in enumerate(fig['data']): #print(data['line']['color']) fig.add_trace(go.Scatter(x=[markers[i][0]], y=[markers[i][1]], mode='markers', name=None, showlegend=False, marker=dict(color=data['line']['color'], size=15 )))fig.show() Edit 1: How to do the same by referencing the default color sequence By default, plotly follows a color sequence that can be found using px.colors.qualitative.Plotly : ['#636EFA', '#EF553B', '#00CC96', '#AB63FA', '#FFA15A', '#19D3F3', '#FF6692', '#B6E880', '#FF97FF', '#FECB52'] The following snippet will produce the exact same figure as before, but without having to define the colors for the traces. import plotly.graph_objects as goimport plotly.express as pxfig = go.Figure()fig.add_trace(go.Scatter( x=[0, 1, 2, 3, 4, 5], y=[0, 3, 5, 7, 9, 11], name='trace01', mode='lines',))fig.add_trace(go.Scatter( x=[0, 1, 2, 3, 4, 5], y=[3, 5, 7, 9, 11, 13], name='trace02', mode='lines'))colors = px.colors.qualitative.Plotlymarkers = [[2,5], [3,9]]for i, data in enumerate(fig['data']): #print(data['line']['color']) fig.add_trace(go.Scatter(x=[markers[i][0]], y=[markers[i][1]], mode='markers', name=None, showlegend=False, marker=dict(color=colors[i], size=15 )))fig.show()
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/61353534', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12928890/']}
jdg_72942
stackexchange
llm_judgeable_groundtruth_similarity
39380285
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 a newbie to Julia and still trying to figure out everything.I want to restrict input variable type to array that can contain int and floats.I would really appreciate any help. function foo(array::??) Now provide the response and nothing else.
As I mentioned in the comment, you don't want to mix them for performance reasons. However, if your array can be either Floats or Ints, but you don't know which it will be, then the best approach is to make it dispatch on the parametric type: function foo{T<:Number,N}(array::Array{T,N}) This will make it compile a separate function for arrays of each number type (only when needed), and since the type will be known for the compiler, it will run an optimized version of the function whether you give it foo([0.1,0.3,0.4]) , foo([1 2 3]) , foo([1//2 3//4]) , etc. Updated syntax in Julia 0.6+ function foo(array::Array{T,N}) where {T<:Number,N} For more generality, you can use Array{Union{Int64,Float64},N} as a type. This will allow Floats and Ints, and you can use its constructor like arr = Array{Union{Int64,Float64},2}(4,4) # The 2 is the dimension, (4,4) is the size and you can allow dispatching onto weird things like this as well by doing function foo{T,N}(array::Array{T,N}) i.e. just remove the restriction on T . However, since the compiler cannot know in advance whether any element of the array is an Int or a Float, it cannot optimize it very well. So in general you should not do this... But let me explain one way you can work with this and still get something with decent performance. It also works by multiple dispatch. Essentially, if you encase your inner loops with a function call which is a strictly typed dispatch, then when doing all of the hard calculations it can know exactly what type it is and optimize the code anyways. This is best explained by an example. Let's say we want to do: function foo{T,N}(array::Array{T,N}) for i in eachindex(array) val = array[i] # do algorithm X on val endend You can check using @code_warntype that val will not compile as an Int64 or Float64 because it won't know until runtime what type it will be for each i . If you check @code_llvm (or @code_native for the assembly) you see that there is a really long code that is generated in order to handle this. What we can instead do is define function inner_foo{T<:Number}(val::T) # Do algorithm X on valend and then instead define foo as function foo2{T,N}(array::Array{T,N}) for i in eachindex(array) inner_foo(array[i]) endend While this looks the same to you, it is very different to the compiler. Note that inner_foo(array[i]) dispatches a specially-compiled function for whatever number type it sees, so in foo2 algorithm X is calculated efficiently, and the only non-efficient part is the wrapping above inner_foo (so if all your time is spent in inner_foo, you will get basically maximal performance). This is why Julia is built around multiple-dispatch: it's a design which allows you to push things out to optimized functions whenever possible. Julia is fast because of it. Use it.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39380285', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4820838/']}
jdg_72943
stackexchange
llm_judgeable_groundtruth_similarity
57516373
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 only an issue in Safari and looks like a Safari bug to me. Here is a fiddle with a simplified version of the issue. When an image is in a nested flexbox element with a width set and height: auto it is being stretched... the auto height is not working. Does something extra need to be added for this to work in Safari? .container { display: flex; flex-direction: column;}.container section:first-child { display: flex; margin-bottom: 25px;}.container img { width: 125px; height: auto;} <div class="container"> <section> <img src="https://via.placeholder.com/250"> </section> <section> <img src="https://via.placeholder.com/150"> </section></div> I expect the height of the image to automatically be adjusted to maintain aspect ratio. This works in all browsers except Safari. In Safari the image is stretched and the auto height does not work. Now provide the response and nothing else.
It certainly appears to be a bug. The default setting for the align-items property is stretch . Most major browsers handle this sensibly, stretching the image within the confines of the container . For whatever reason, Safari stretches the image to its natural height, taking the container along for the ride. flex-direction: row To fix the problem, override the stretch default value with flex-start in the align-items property. .container { display: flex; flex-direction: column;}.container section:first-child { display: flex; align-items: flex-start; /* new */ margin-bottom: 25px;}.container img { width: 125px; height: auto;} <div class="container"> <section> <img src="http://i.imgur.com/60PVLis.png"> </section> <section> <img src="http://i.imgur.com/60PVLis.png"> </section></div> jsFiddle demo flex-direction: column Switching the direction of the flex container to column also fixes the problem. This works because align-items now applies to width and you've defined a width on the image. If you reverse the image dimensions from .container img { width: 125px; height: auto;} to .container img { width: auto; height: 125px;} ... you'll have the same problem in Safari as in flex-direction: row , and need align-items: flex-start for the correction. .container { display: flex; flex-direction: column;}.container section:first-child { display: flex; /* align-items: flex-start; */ margin-bottom: 25px;}.container img { width: auto; height: 125px;} <div class="container"> <section> <img src="http://i.imgur.com/60PVLis.png"> </section> <section> <img src="http://i.imgur.com/60PVLis.png"> </section></div> jsFiddle demo
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/57516373', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5651633/']}
jdg_72944
stackexchange
llm_judgeable_groundtruth_similarity
279190
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 can I extract the list of colors in the System.Drawing.Color struct into a collection or array? Is there a more efficient way of getting a collection of colors than using this struct as a base? Now provide the response and nothing else.
So you'd do: string[] colors = Enum.GetNames(typeof(System.Drawing.KnownColor)); ... to get an array of all the collors. Or... You could use reflection to just get the colors. KnownColors includes items like "Menu", the color of the system menus, etc. this might not be what you desired. So, to get just the names of the colors in System.Drawing.Color, you could use reflection: Type colorType = typeof(System.Drawing.Color);PropertyInfo[] propInfoList = colorType.GetProperties(BindingFlags.Static | BindingFlags.DeclaredOnly | BindingFlags.Public);foreach (System.Reflection.PropertyInfo c in propInfoList) { Console.WriteLine(c.Name);} This writes out all the colors, but you could easily tailor it to add the color names to a list. Check out this Code Project project on building a color chart .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/279190', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1583/']}
jdg_72945
stackexchange
llm_judgeable_groundtruth_similarity
727984
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 calculate this sum $$ \sum \limits_{k=1}^{n} \frac{k}{n^k}{n\choose k} \;?$$ Now provide the response and nothing else.
Let's consider $1$st problem. Problem: How many liters of a 70% alcohol solution must be added to 50 liters of a 40% alcohol solution to produce a 50% alcohol solution? "Easy and nice trick" :) Let's consider liquids separately: - alcohol; - water. Then image: Then one can write equation for each liquid: for alcohol: $$\qquad 0.7 \cdot x + 0.4 \cdot 50 = 0.5 \cdot (x+50);\tag{1}$$ or for water: $$\qquad 0.3 \cdot x + 0.6 \cdot 50 = 0.5 \cdot (x+50).\tag{2}$$ Then solve $(1)$ (or $(2)$ ) : $$0.2\cdot x=5;$$$$x=25 \mbox{ (liters)}.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/727984', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/118364/']}
jdg_72946
stackexchange
llm_judgeable_groundtruth_similarity
192603
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 wondering how to speed up the following code: Currently it takes more than two sec to be processed. Timing[For[i = 1;list = {}, i <= 11111, i++, l = AppendTo[list, i/Pi]]; Total@N@list] I am new to Wolfram languages and it's the only thing I could come up with.Any idea ? Thanks Now provide the response and nothing else.
You can see in @MarcoB's answer the enormous speed up possible. Even for your code, if you replace the AppendTo with a different structure, you can get orders of magnitude improvement. Your code here - note that we don't need l for anything. ( For[i = 1; list = {}, i <= 11111, i++, AppendTo[list, i/Pi]];Total@N@list ) //AbsoluteTiming {2.12476, 1.96501*10^7} Slight modification results in factor of 100 speed up. (For[i = 1; list = {}, i <= 11111, i++, list = {list, i/Pi}];Total@N@Flatten@list) // AbsoluteTiming {0.0287278, 1.96501*10^7}
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/192603', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/-1/']}
jdg_72947
stackexchange
llm_judgeable_groundtruth_similarity
366566
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: As the title explains the question, let's assume that we're using versioning as major.minor.revision.build . What should the initial version of a software build be? 0.0.0.1 or 0.0.0.0 or anything else? Now provide the response and nothing else.
First build ? 0.0.0.0. Because you are going to build and try your code many times before you reach the point you put a version on it. But now I'm going to stop nitpicking and assume you mean the first release . So - it depends: If the first release is a stable one - it should be 1.0.0.###. In the more likely case the first release is not a stable one - it should be 0.1.0.###. The build number is ### because it depends on how you do build numbers - there are several ways to do those buy they tend to be very simple without much room for decisions (like timestamp or incremented number) so just stick with the rules for build number. The revision/bugfix is 0 - because it's the first release. Incrementing a major version means you are breaking backward compatibility (at least according to SemVer ), so you usually want to start with 0 - which is special because it means you don't guarantee backward compatibility just yet. And you set the minor version to 1 so that your release won't be 0.0.0.###. This is good for the first releases, because once your software is tried out in the wild and you get some feedback, you may realize some of your design decisions were wrong (or even just "not right enough") and need to introduce some breaking changes - being at major version 0 will allow you to do so without much fuss. If you do decide to promise backward compatibility from the very first release, you set the major version to 1 and the minor version to 0 because that's the initial minor version for a new major version. You need to have a really good reason to do this though, because that means you'll have to increase a major version on each breaking change, and a month-old project with major version of 23 looks quite alarming.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/366566', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/297125/']}
jdg_72948
stackexchange
llm_judgeable_groundtruth_similarity
2567616
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$f^{''}$ is defined on $[a,b]$ and if $|f^{''}(x)| \leq M \forall x \in [a,b]$ then prove that $|f(b)-f(a)-\frac{b-a}{2}(f'(a)+f'(b)) | \leq \frac{(b-a)^2}{2}M$ My attemptBy taylor's theorem,$f(b)=f(a)+(b-a)f'(a)+\frac{(b-a)^2}{2} f^{''}(\zeta) , \forall\zeta \in (a,b),$ [as second derivative is bounded third and higher derivatives = 0, since $-M\leq{f^{''}(x)} \leq M$, Differentiating again $0 \leq {f^{'''}(x)} \leq 0$] Putting this in above given problem, $|\frac{b-a}{2}(f'(a)-f'(b))+\frac{(b-a)^2}{2} f^{''}(\zeta)| = |\frac{b-a}{2}(f'(a)-(f'(a)+(b-a)f^{''}(\eta))+\frac{(b-a)^2}{2} f^{''}(\zeta)|=|-\frac{(b-a)^2}{2} f^{''}(\eta)+\frac{(b-a)^2}{2} f^{''}(\zeta)|\leq (b-a)^2 M$ But in problem it is given as $\frac{M}{2}$. can you tell where i went wrong? On face of it, it looks ok to me Now provide the response and nothing else.
\begin{align*}\left|f(b)-f(a)-\dfrac{b-a}{2}(f'(a)+f'(b))\right|&=\left|f'(\xi)(b-a)-\dfrac{b-a}{2}(f'(a)+f'(b))\right|\\&=\left|\dfrac{b-a}{2}(f'(\xi)-f'(a))+\dfrac{b-a}{2}(f'(\xi)-f(b))\right|\\&\leq\dfrac{b-a}{2}|f''(\alpha)||\xi-a|+\dfrac{b-a}{2}|f''(\beta)||b-\xi|\\&\leq\dfrac{b-a}{2}\left(M(\xi-a)+M(b-\xi)\right)\\&=\dfrac{(b-a)^{2}}{2}\cdot M,\end{align*}where $\xi\in(a,b)$, $\alpha\in(a,\xi)$, $\beta\in(\xi,b)$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2567616', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/460436/']}
jdg_72949
stackexchange
llm_judgeable_groundtruth_similarity
9220
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: Assume you are given two objects whose exact locations are unknown, but are distributed according to normal distributions with known parameters (e.g. $a \sim N(m, s)$ and $b \sim N(v, t))$. We can assume these are both bivariate normals, such that the positions are described by a distribution over $(x,y)$ coordinates (i.e. $m$ and $v$ are vectors containing the expected $(x,y)$ coordinates for $a$ and $b$ respectively). We will also assume the objects are independent. Does anyone know if the distribution of the squared Euclidean distance between these two objects is a known parametric distribution? Or how to derive the PDF / CDF for this function analytically? Now provide the response and nothing else.
The answer to this question can be found in the book Quadratic forms in random variables by Mathai and Provost (1992, Marcel Dekker, Inc.). As the comments clarify, you need to find the distribution of $Q = z_1^2 + z_2^2$ where $z = a - b$ follows a bivariate normal distribution with mean $\mu$ and covariance matrix $\Sigma$. This is a quadratic form in the bivariate random variable $z$. Briefly, one nice general result for the $p$-dimensional case where $z \sim N_p(\mu, \Sigma)$ and $$Q = \sum_{j=1}^p z_j^2$$ is that the moment generating function is $$E(e^{tQ}) = e^{t \sum_{j=1}^p \frac{b_j^2 \lambda_j}{1-2t\lambda_j}}\prod_{j=1}^p (1-2t\lambda_j)^{-1/2}$$where $\lambda_1, \ldots, \lambda_p$ are the eigenvalues of $\Sigma$ and $b$ is a linear function of $\mu$. See Theorem 3.2a.2 (page 42) in the book cited above (we assume here that $\Sigma$ is non-singular). Another useful representation is 3.1a.1 (page 29) $$Q = \sum_{j=1}^p \lambda_j(u_j + b_j)^2$$where $u_1, \ldots, u_p$ are i.i.d. $N(0, 1)$. The entire Chapter 4 in the book is devoted to the representation and computation of densities and distribution functions, which is not at all trivial. I am only superficially familiar with the book, but my impression is that all the general representations are in terms of infinite series expansions. So in a certain way the answer to the question is, yes, the distribution of the squared euclidean distance between two bivariate normal vectors belongs to a known (and well studied) class of distributions parametrized by the four parameters $\lambda_1, \lambda_2 > 0$ and $b_1, b_2 \in \mathbb{R}$. However, I am pretty sure you won't find this distribution in your standard textbooks. Note, moreover, that $a$ and $b$ do not need to be independent. Joint normality is enough (which is automatic if they are independent and each normal), then the difference $a-b$ follows a normal distribution.
{}
{'log_upvote_score': 6, 'links': ['https://stats.stackexchange.com/questions/9220', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/1913/']}
jdg_72950
stackexchange
llm_judgeable_groundtruth_similarity
5984
Below is a question asked on the forum engineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In addition to power and performance, one of the reasons VW cheated their emissions results was to improve the fuel economy of their cars. Why exactly does this happen? I'm familiar with cars and how cars work so feel free to get technical. And a follow-up question: Where is the "sweet spot" between burning more gas per mile but having that burned gas release fewer emissions, and burning less gas per mile but releasing more emissions per gallon burned? Now provide the response and nothing else.
Not all of the pollutants come directly from the fuel. Some (e.g. NOx) come from the air itself, based on the combustion temperature in the cylinder. Running a cylinder at a higher temperature (by leaning the mixture) results in both greater efficiency and greater NOx emissions. On the other hand, running the cylinder at a lower temperature reduces NOx emissions, but at some point, CO and HC emissions go up because of incomplete combusion (which is why catalytic converters are used). The "sweet spot" you ask about in your followup question is very much dependent on the specific design of the engine, and it is, of course, the target of ongoing (and proprietary) research.
{}
{'log_upvote_score': 4, 'links': ['https://engineering.stackexchange.com/questions/5984', 'https://engineering.stackexchange.com', 'https://engineering.stackexchange.com/users/3579/']}
jdg_72951
stackexchange
llm_judgeable_groundtruth_similarity
530775
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: For $a$ and $b$ are integers greater than $1$, ${ a }^{ 2 }-{ b }^{ 2 }=8$ holds? Now provide the response and nothing else.
Hint : We have $8= a^2 - b^2 = (a+b)(a-b)$. As $a,b \ge 1$, we have $a+b > a-b$, that is either $a+b=8$ and $a-b = 1$, or $a+b=4$ and $a-b=2$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/530775', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/76526/']}
jdg_72952
stackexchange
llm_judgeable_groundtruth_similarity
29355613
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is it possible to run a chord callback even if the main tasks failed? I've created a chord which I added a bunch of tasks and registered a callback to it. My problem is that if one of the tasks fail, the callback is not triggered. But I would like the callback to be triggered either way. I've tried to register the callback with si() ( immutability ) callback = tasks.run_delete_rule.si([timestamp])header = [tasks.run_update_rule.s(i, timestamp) for i in item_ids]result = chord(header)(callback) I also tried to add the parameter ignore_result=True to both tasks decorator, but no success. Now provide the response and nothing else.
From the github issue #1881 if the callback has the link_error option set, which takes a list of tasks names, then when a task of the chord fails the link_error tasks are going to be executed. @task(name='super_task.good')def good(): return True@task(name='super_task.raise_exception')def raise_exception(): raise ValueError('error')@task(name='super_task.callback')def callback(*args, **kwargs): logger.info('callback') logger.info(args) logger.info(kwargs) return 'finished'@task(name='super_task.error_callback')def error_callback(*args, **kwargs): logger.info('error_callback') logger.info(args) logger.info(kwargs) return 'error'>>> c = chord( [raise_exception.s(), good.s(), raise_exception.s()], callback.s().set(link_error=['super_task.error_callback']) )>>> result = c() This will execute the chord and in your celery log, you'll see the raise_exception task fail, and the execution of error_callback which will receive in it's args the task_id of callback . At this point the value of result will contain the AsyncResult instance of callback , and because in a chord the errors propagate to the callback doing result.get() will raise the exception of the tasks and result.traceback gives you the traceback. If you want to have a single callback, just pass the name of the chord callback to link_error callback.s().set(link_error='super_task.callback') NOTE Another options it's to set CELERY_CHORD_PROPAGATES = False which will revert to the pre celery 3.1 behavior and always execute the callback. But this is not a recommended approach because as you can find in the github issue #1349 Celery 3.1 defines how chord errors are handled, the previous behavior was never documented and more of an accident since it was never the intention to work that way. We couldn't change the behavior in a bugfix release so a setting had to be used instead, but it was never the intention that someone would deliberately disable the new behavior. The new behavior is there to protect against this sort of issue happening, and the backward compatible setting may be removed. I suggest you find some other way to handle errors here (and I wouldn't mind a proposal if you can invent a nice api for it)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29355613', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/533938/']}
jdg_72953
stackexchange
llm_judgeable_groundtruth_similarity
25648155
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Does Windows have an executable that I can run in the command shell which returns the version number of an executable (.exe) file? I see a lot of questions that show how to do it from different languages, and references to third party software to write it, but I can't find a simple shell command to do it. Additional points if I don't need to install anything. It must be run as normal user. Not administrator. Now provide the response and nothing else.
wmic datafile where name="C:\\Windows\\System32\\msiexec.exe" get Version /value You can use wmic to do it. And you can wrap it into a batch file @echo off setlocal enableextensions set "file=%~1" if not defined file goto :eof if not exist "%file%" goto :eof set "vers=" FOR /F "tokens=2 delims==" %%a in (' wmic datafile where name^="%file:\=\\%" get Version /value ') do set "vers=%%a" echo(%file% = %vers% endlocal Save it as (example) getVersion.cmd and call as getVersion.cmd "c:\windows\system32\msiexec.exe" edited to adapt to comments and not require administrator rights. In this case, an hybrid cmd/javascript file is used to query wmi. Same usage @if (@this==@isBatch) @then@echo off setlocal enableextensions set "file=%~f1" if not exist "%file%" goto :eof cscript //nologo //e:jscript "%~f0" /file:"%file%" endlocal exit /b@end var file = WScript.Arguments.Named.Item('file').replace(/\\/g,'\\\\'); var wmi = GetObject('winmgmts:{impersonationLevel=impersonate}!\\\\.\\root\\cimv2') var files = new Enumerator(wmi.ExecQuery('Select Version from CIM_datafile where name=\''+file+'\'')) while (!files.atEnd()){ WScript.StdOut.WriteLine(files.item().Version); files.moveNext(); }; WScript.Quit(0)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/25648155', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10335/']}
jdg_72954
stackexchange
llm_judgeable_groundtruth_similarity
269649
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: A Catalan path of semilength $n$ is a path from $(0,0)$ to $(2n,0)$ that proceeds by taking northeast (1,1) or southeast (1,-1) steps, and never goes below the $x$-axis. The area of a path $P$ is the area beneath the path and above the $x$-axis. So, for example, the path of semilength 3 that goes $(0,0)-(1,1)-(2,2)-(3,1)-(4,0)-(5,1)-(6,0)$ has area $5$. The sum of the area of all Catalan paths of semilength $n$ is known to be $4^n - \binom{2n+1}{n}$, so that the average area of a path is on the order of $n^{3/2}$. In an application I'm working on, I've found that it would be useful to have upper bounds on how many paths have area significantly greater than $n^{3/2}$. The largest possible area is $n^2$, and from Markov's inequality I can say that a vanishing proportion of paths have area greater than $n^2/1000$, say; specifically, there are no more than $O\left(4^n/n^2\right)$ such paths (whereas there are $\Theta\left(4^n/n^{3/2}\right)$ paths in total). I suspect that there are far fewer paths with large area, and for my application I need a much lower upper bound. Are there quantitative results for this problem? I can translate the problem into that of estimating the number of partitions of the number $N$ into at most $c\sqrt{N}$ parts each of size at most $c\sqrt{N}$, which in turn becomes a problem of estimating a coefficient of a Gaussian polynomial, but I'm not aware of quantatitive results here, either. Now provide the response and nothing else.
Notice that the number of Catalan paths of area at least $cn^{\frac{3}{2}+\varepsilon}$ is less than the number of all paths that deviate from the horizontal axis by at least $n^{\frac{1}{2}+\varepsilon}$. Let $(S_k, k\geq 0)$ be the one-dimensional simple random walk starting from the origin. We need to find an upper bound for the following probability: $$P\big[\max_{k\leq 2n}S_k > n^{\frac{1}{2}+\varepsilon}\big].$$ Now, one may use e.g. a Chernoff's bound for the Binomial distribution (together with the Reflection Principle if you don't want an extra polynomial term in front, see e.g. Chapter III of the Feller's book) to obtain that the above probability is upper bounded by $\exp(-c'n^{\varepsilon})$. So, the total number of such paths is at most $4^n\exp(-c'n^{\varepsilon})$.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/269649', 'https://mathoverflow.net', 'https://mathoverflow.net/users/21690/']}
jdg_72955
stackexchange
llm_judgeable_groundtruth_similarity
16983343
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 a vector in a C++ program and I need to pass a part of that vector to a function. If it was C, I would need to do the following (with arrays): int arr[5] = {1, 2, 3, 4, 5};func(arr+2); // Pass the part of the array {3, 4, 5} Is there any other way than creating a new vector with the last part? Now provide the response and nothing else.
A common approach is to pass iterator ranges. This will work with all types of ranges, including those belonging to standard library containers and plain arrays: template <typename Iterator>void func(Iterator start, Iterator end) { for (Iterator it = start; it !=end; ++it) { // do something } } then std::vector<int> v = ...;func(v.begin()+2, v.end());int arr[5] = {1, 2, 3, 4, 5};func(arr+2, arr+5); Note : Although the function works for all kinds of ranges, not all iterator types support the increment via operator+ used in v.begin()+2 . For alternatives, have a look at std::advance and std::next .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16983343', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1246772/']}
jdg_72956
stackexchange
llm_judgeable_groundtruth_similarity
18695727
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 looking at matching glob-style patterns similar the what the Redis KEYS command accepts . Quoting: h?llo matches hello, hallo and hxllo h*llo matches hllo and heeeello h[ae]llo matches hello and hallo, but not hillo But I am not matching against a text string, but matching the pattern against another pattern with all operators being meaningful on both ends. For example these patterns should match against each other in the same row: prefix* prefix:extended**suffix *:extended:suffixleft*right left*middle*righta*b*c a*b*d*b*chello* *okpre[ab]fix* pre[bc]fix* And these should not match: prefix* wrong:prefix:**suffix *suffix:wrongleft*right right*middle*leftpre[ab]fix* pre[xy]fix*?*b*? bcb So I'm wondering ... if this is possible to do (implement a verification algorithm), if at all? if not possible, what subset of regex would be possible? (i.e. disallow * wildcard?) if it is indeed possible, what is an efficient algorithm? what are the time complexity required? EDIT: Found this other question on RegEx subset but this is not exactly the same as the words that hello* and *ok matches is not a subset/superset of each other but they do intersect. So I guess mathematically, this might be phrased as; is it possible to deterministically check that a set of words that one pattern match, intersecting with a set of words that another pattern matches, result in a non-empty set? EDIT: A friend @neizod drew up this elimination table which neatly visualize what might be a potential/partial solution: Elimination rule EDIT: Will adds extra bounty for those who can also provide working code (in any language) and test cases that proves it. EDIT: Added the ?*b*? test case discovered by @DanielGimenez in the comments. Now provide the response and nothing else.
Now witness the firepower of this fully ARMED and OPERATIONAL battle station! (I have worked too much on this answer and my brain has broken; There should be a badge for that.) In order to determine if two patterns intersect, I have created a recursive backtracking parser -- when Kleene stars are encountered a new stack is created so that if it fails in the future everything is rolled back and and the star consumes the next character. You can view the history of this answer to determine how arrived at all this and why it was necessary, but basically it wasn't sufficient to determine an intersection by looking ahead only one token, which was what I was doing before. This was the case that broke the old answer [abcd]d => *d . The set matches the d after the star , so the left side would still have tokens remaining, while the right side would be complete. However, these patterns two intersect on ad , bd , cd and dd , so that needed to be fixed. My almost O(N) answer was thrown out. Lexer The lexing process is trivial, except that is processes escape characters and removes redundant stars . Tokens are broken out into sets , stars , wild character (?) , and character . This is different than my previous versions where one token was a string of characters instead of a single character. As more cases come up, having strings as tokens was more of a hindrance than advantage. Parser Most of the functions of the parser are pretty trivial. A switch given the left side's type, calls a function that is a switch that determines the appropriate function to compare it with the right side's type. The result from the comparison bubbles up the two switches to the original callee, typically the main loop of the parser. Parsing Stars The simplicity ends with the star . When that is encountered it takes over everything. First it compares its side's next token with the other side's, advancing the other side until if finds a match. Once the match is found, it then checks if everything matches all the way up to the end of both patterns. If it does then the patterns intersect. Otherwise, it advances the other side's next token from the original one it was compared against and repeats the process. When two anys are encountered then the take off into their own alternative branches starting from each others' next token. function intersects(left, right) { var lt, rt, result = new CompareResult(null, null, true); lt = (!left || left instanceof Token) ? left : tokenize(left); rt = (!right || right instanceof Token) ? right : tokenize(right); while (result.isGood && (lt || rt)) { result = tokensCompare(lt, rt); lt = result.leftNext; rt = result.rightNext; } return result;}function tokensCompare(lt, rt) { if (!lt && rt) return tokensCompare(rt, lt).swapTokens(); switch (lt.type) { case TokenType.Char: return charCompare(lt, rt); case TokenType.Single: return singleCompare(lt, rt); case TokenType.Set: return setCompare(lt, rt); case TokenType.AnyString: return anyCompare(lt, rt); }}function anyCompare(tAny, tOther) { if (!tOther) return new CompareResult(tAny.next, null); var result = CompareResult.BadResult; while (tOther && !result.isGood) { while (tOther && !result.isGood) { switch (tOther.type) { case TokenType.Char: result = charCompare(tOther, tAny.next).swapTokens(); break; case TokenType.Single: result = singleCompare(tOther, tAny.next).swapTokens(); break; case TokenType.Set: result = setCompare(tOther, tAny.next).swapTokens(); break; case TokenType.AnyString: // the anyCompare from the intersects will take over the processing. result = intersects(tAny, tOther.next); if (result.isGood) return result; return intersects(tOther, tAny.next).swapTokens(); } if (!result.isGood) tOther = tOther.next; } if (result.isGood) { // we've found a starting point, but now we want to make sure this will always work. result = intersects(result.leftNext, result.rightNext); if (!result.isGood) tOther = tOther.next; } } // If we never got a good result that means we've eaten everything. if (!result.isGood) result = new CompareResult(tAny.next, null, true); return result;}function charCompare(tChar, tOther) { if (!tOther) return CompareResult.BadResult; switch (tOther.type) { case TokenType.Char: return charCharCompare(tChar, tOther); case TokenType.Single: return new CompareResult(tChar.next, tOther.next); case TokenType.Set: return setCharCompare(tOther, tChar).swapTokens(); case TokenType.AnyString: return anyCompare(tOther, tChar).swapTokens(); }}function singleCompare(tSingle, tOther) { if (!tOther) return CompareResult.BadResult; switch (tOther.type) { case TokenType.Char: return new CompareResult(tSingle.next, tOther.next); case TokenType.Single: return new CompareResult(tSingle.next, tOther.next); case TokenType.Set: return new CompareResult(tSingle.next, tOther.next); case TokenType.AnyString: return anyCompare(tOther, tSingle).swapTokens(); }}function setCompare(tSet, tOther) { if (!tOther) return CompareResult.BadResult; switch (tOther.type) { case TokenType.Char: return setCharCompare(tSet, tOther); case TokenType.Single: return new CompareResult(tSet.next, tOther.next); case TokenType.Set: return setSetCompare(tSet, tOther); case TokenType.AnyString: return anyCompare(tOther, tSet).swapTokens(); }}function anySingleCompare(tAny, tSingle) { var nextResult = (tAny.next) ? singleCompare(tSingle, tAny.next).swapTokens() : new CompareResult(tAny, tSingle.next); return (nextResult.isGood) ? nextResult: new CompareResult(tAny, tSingle.next);}function anyCharCompare(tAny, tChar) { var nextResult = (tAny.next) ? charCompare(tChar, tAny.next).swapTokens() : new CompareResult(tAny, tChar.next); return (nextResult.isGood) ? nextResult : new CompareResult(tAny, tChar.next);}function charCharCompare(litA, litB) { return (litA.val === litB.val) ? new CompareResult(litA.next, litB.next) : CompareResult.BadResult;}function setCharCompare(tSet, tChar) { return (tSet.val.indexOf(tChar.val) > -1) ? new CompareResult(tSet.next, tChar.next) : CompareResult.BadResult;}function setSetCompare(tSetA, tSetB) { var setA = tSetA.val, setB = tSetB.val; for (var i = 0, il = setA.length; i < il; i++) { if (setB.indexOf(setA.charAt(i)) > -1) return new CompareResult(tSetA.next, tSetB.next); } return CompareResult.BadResult;} jsFiddle Time Complexity Anything with the words "recursive backtracking" in it is at least O(N 2 ). Maintainability and Readability I purposely broke out any branches into there own functions with a singular switch. Assitionally I used named constants when a one character string would suffice. Doing this made the code longer and more verbose, but I think it makes it easier to follow. Tests You can view all the tests in the Fiddle. You can view the comments in the Fiddle output to glean their purposes. Each token type was tested against each token type, but I haven't made one that tried all possible comparisons in a single test. I also came up with a few random tough ones like the one below. abc[def]?fghi?*nop*[tuv]uv[wxy]?yz => a?[cde]defg*?ilmn[opq]*tu*[xyz]* I added an interface on the jsFiddle if anybody wants to test this out themselves. The logging is broken once I added the recursion. I don't think I tried enough negative tests, especially with the last version I created. Optimization Currently the solution is a brute force one, but is sufficient to handle any case. I would like to come back to this at some point to improve the time complexity with some simple optimizations. Checks at the start to reduce comparisons could increase processing time for certain common scenarios. For example, if one pattern starts with a star and one ends with one then we already know they will intersect. I can also check all the characters from the start and end of the patterns and remove them if the match on both patterns. This way they are excluded from any future recursion. Acknowledgements I used @m.buettner's tests initially to test my code before I came up with my own. Also I walked through his code to help me understand the problem better.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18695727', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3055/']}
jdg_72957
stackexchange
llm_judgeable_groundtruth_similarity
17997214
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So, I have always had doubts about how redirection works in the following situations: I type "ls" and all the filenames are separated by white spaces: test$ touch a b ctest$ lsa b c I use a ">" to redirect STDOUT to a file: test$ ls > ls.txttest$ cat ls.txt abcls.txt It is interesting to see that the format changes, with the filenames separated by newline characters. It seems that the output is generated by ls -1 . Why is the output in the latter case different from that in the former case? Can ls actually see the ">" symbol so it changes its behavior? Now provide the response and nothing else.
ls tests its output stream to see whether it is a terminal, and it modifies its behavior depending on that. This is documented; the man page for ls documents several things that depend on whether the output is a terminal: If the output is a terminal, -C (for multi-column output) is a default, otherwise -1 (one-column) is a default. If -l or -s is used and the output is a terminal, a sum for all file sizes or blocks, respectively, is printed on a line before the listing. If the output is a terminal, -q is a default. This prints non-graphic characters as “?”. Otherwise, -v and -w are defaults. I am a bit unclear on the difference between -v and -w . The documentation I have says -v forces “unedited printing of non-graphic characters” and -w forces “raw printing of non-printable characters.”
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17997214', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1337629/']}
jdg_72958
stackexchange
llm_judgeable_groundtruth_similarity
51685490
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 currently using react-google-map for getting Google Map to run in my React project, here is my Map component: import React from 'react'import { compose, withProps, lifecycle } from 'recompose'import { withScriptjs, withGoogleMap, GoogleMap } from 'react-google-maps'import MapStyle from '../../../api/mapStyle'const Map = ({ children }) => { return ( <GoogleMap defaultZoom={15} defaultCenter={{ lat: 35.6840299, lng: 51.3861187 }} > {children} </GoogleMap> )}export default compose( withProps({ googleMapURL: "https://maps.googleapis.com/maps/api/js?key=MY_KEY_HERE", loadingElement: <div style={{ height: `100%` }} />, containerElement: <div className='map' style={{ height: `100vh` }} />, mapElement: <div style={{ height: `100%` }} /> }), withScriptjs, withGoogleMap,)(Map) As you can see this is as what react-google-map DOC says , nothing so fancy here! Yesterday I just started to build map, and as normal I went to my Google console and got a key, then I put it on MY_KEY_HERE section of link , and it worked fine until this morning, today i am struggling with: You have exceeded your request quota for this API Not: You have exceeded your daily request quota for this API as below: I searched Google and I found this and this and this and many many others, but I could not find any proper answer to this problem. What did I try? I created a couple of other keys in my console to remove this problem , but it is not solved, I got the same You have exceeded your request quota for this API error I used another account of mine on Google to resolve this issue and I just logged in and went to console platform and again generated a key, but I still getting that error? even by trying it in codeSandBox.io, I still got the same error I'm really confused about this issue, how should I solve it? Now provide the response and nothing else.
Edit: The link below seems to be dead. You can read Google Maps Platform Billing 's documentation here https://developers.google.com/maps/billing-and-pricing/billing#billing-in-the-console Check if your project has a billing account associated to it. You can use this Google tool: https://mapsplatformtransition.withgoogle.com/ "This project does not have a billing account. You will need to addbilling information for this project to continue to use Google MapsPlatform. The first $200 of monthly usage is free. You only pay forwhat you use. You can review rates and access your spending any timein your Google Cloud Platform Console, where you can also set dailyquotas to protect against unexpected increases. You can also setbilling alerts to receive email notifications when charges reach apreset threshold determined by you." It will list all your projects using Google Maps and tell you to "Add Billing" if the project status is not "in good shape".
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/51685490', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5354341/']}
jdg_72959
stackexchange
llm_judgeable_groundtruth_similarity
36286
Below is a question asked on the forum mechanics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: My car will not start. A month ago it wouldn't start. At that time it was still cranking (weakly) but not starting. I bought a new battery and installed it. It still wouldn't start until I jumped it (which doesn't make sense since it's a new battery) and then it started. I took the old battery back and the worker said that the battery was fine. Keep in mind this was all a month ago and it was running fine until now. It stopped starting up again. I did notice that the starts were getting weaker just before it stopped starting again. This time I had to get it towed. Now it will not crank at all and makes a single click and nothing more. Is this indicative of a bad starter or a bad alternator or is there something else I'm missing? All my electronics still seem to work fine, it just won't start so I'm leaning more towards the starter. Vehicle is: 2006 Honda Civic EX 1.8L 4 Cylinder (though it shouldn't matter). I did do a search and could not find any questions with this specific case. UPDATE: I put in a fully charged battery (battery tested good and was charged using a battery charger) and it would not start. Like I mentioned before, a month ago it did crank (weakly) and wouldn't start. Now it doesn't crank at all and just clicks. Is this solely a problem with the starter or could this be indicative of an underlying problem? UPDATE 2: It was the starter. It was going bad and would fail when it got hot. Now provide the response and nothing else.
To differentiate between the starter and the alternator you can check the battery voltage – should be about 12.6 with the engine off and 13.5-14.2 with the engine running if the alternator is doing its job. You may have a failing starter. You can get a good take on this by taking a current reading while trying to start. Usually this is done with a specialized meter, so you may want to take it to a motor shop or a car parts store and ask them to test it. A failing motor will usually have a very high draw (or none). However, if the car won't move… The starter should cause a large drop in battery voltage when it runs (and even more if it doesn't run, but is trying to). So if you have access to a volt meter you could also try reading the voltage before and during an attempt to start. Any significant drop in voltage indicates that the motor is trying to run. If it isn't then I'd say it's time to take the motor in for repair/replacement.
{}
{'log_upvote_score': 4, 'links': ['https://mechanics.stackexchange.com/questions/36286', 'https://mechanics.stackexchange.com', 'https://mechanics.stackexchange.com/users/22374/']}
jdg_72960
stackexchange
llm_judgeable_groundtruth_similarity
11746769
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 in perl you can interpolate scalars by simply doing this: "This is my $string" However, I'm wondering if there is a way where I can interpolate actual perl code to be evaluated? An idea of what I want can be seen with ruby strings: "5 + 4 = #{5 + 4}" And it will evaluate whatever is in between the {} . Does anyone know of a way to do this in perl? Thanks! Now provide the response and nothing else.
You can use the following trick: "5 + 4 = @{[ 5 + 4 ]}" Alternatively, you can use sprintf : sprintf("5 + 4 = %d", 5 + 4); Either of these yields the desired string. Arguably, sprintf is safer than the first one, as you can restrict the type of the interpolated value somewhat. The first one is closer in spirit to what you desire, however. Further reading: Why does Perl evaluate code in ${…} during string interpolation?
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11746769', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/834140/']}
jdg_72961
stackexchange
llm_judgeable_groundtruth_similarity
42101
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 am reading the book Electronic Principles by Malvino and I found the circuit shown below.It asks to find the A(gain) when the switch is in position 1 and in position 2. I am not sure about this but in position 1 I found that A = 10k/10k + 1 = 2. What about position 2? Now provide the response and nothing else.
Adding on to Dave's answer, An ideal op-amp follows two basic rules when operating under closed-loop feedback conditions: The voltage at the two inputs are equal There is no current flowing into or out of the op-amp inputs Position 1: In position 1, the voltage at the bottom input is Vin . Using rule 1, the voltage at node A is also Vin . Since there's no voltage difference across the left resistor, there's no current flowing in. Using Kirchoff's current law, \begin{equation}\sum{I_A} = 0\end{equation} Since there is no current from Vin to node A and since the op-amp input can't source/sink any current, that must mean there is also no current flowing from node A to Vout , thus Vout = VA = Vin . This means the gain is 1 . Position 2: Here, the two op-amp inputs are set to 0V (due to rule 1). The current flowing from Vin to node A is thus: \begin{equation}I = \frac{Vin}{R}\end{equation} Again, the op-amp input sources/sinks no current so that means the current flowing from node A to Vout is: \begin{equation}I = \frac{0 - Vout}{R} = \frac{Vin}{R}\end{equation} Solving for Vout , we get\begin{equation}Vout = -Vin\end{equation} Thus getting the output gain of -1 .
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/42101', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/13551/']}
jdg_72962
stackexchange
llm_judgeable_groundtruth_similarity
13020103
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 working with ASP.NET MVC 4 WebApi and am having a lot of fun with it running it on my local computer on IIS Express. I've configured IIS Express to serve remote machines too, and so other's in my company are using my computer as our webserver. After deciding this was a less-than-optimal solution, we decided to put the WebApi on a remote server after installing .NET 4.5. When I use fiddler and sent a POST to a controller on my local machine it returns the correct response, yet when I change the domain to the webserver running IIS7 the same POST returns a cryptic {"message":"an error has occurred"} message. Anyone have any idea what could be going on? Now provide the response and nothing else.
The problem was a missing dependency that wasn't on the server but was on my local machine. In our case, it was a Devart.Data.Linq dll. To get to that answer, I turned on IIS tracing for 500 errors. That gave a little bit of information, but the really helpful thing was in the web.config setting the <system.web><customErrors mode="Off"/></system.web> This pointed to a missing dynamically-loaded dependency. After adding this dependency and telling it to be copied locally, the server started working.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/13020103', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1087161/']}
jdg_72963
stackexchange
llm_judgeable_groundtruth_similarity
19697110
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 a new user in GWT and I want to deploy one of existed samples in my localhost. I could run the example by eclipse and get the result. But I need to deploy that example in my localhost (IIS). How can I do this? Now provide the response and nothing else.
For your case best way used MVVM pattern XAML: <Window> <Window.InputBindings> <KeyBinding Command="{Binding SomeCommand}" Key="F5"/> </Window.InputBindings></Window> Code behind: public partial class MainWindow : Window{ public MainWindow() { InitializeComponent(); }} In your view-model: public class MyViewModel{ private ICommand someCommand; public ICommand SomeCommand { get { return someCommand ?? (someCommand = new ActionCommand(() => { MessageBox.Show("SomeCommand"); })); } }} Then you'll need an implementation of ICommand .This simple helpful class. public class ActionCommand : ICommand{ private readonly Action _action; public ActionCommand(Action action) { _action = action; } public void Execute(object parameter) { _action(); } public bool CanExecute(object parameter) { return true; } public event EventHandler CanExecuteChanged;}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/19697110', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2939725/']}
jdg_72964
stackexchange
llm_judgeable_groundtruth_similarity
1292449
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 reason (safety?) why someone should rename the ASP.NET Session Cookie Name or is it just a senseless option of ASP.NET? Now provide the response and nothing else.
If you have several applications running under the same domain on the same server, you may well want to have seperate session cookie names for each one, so that they aren't sharing the same session state or worse still overwriting each other. See also the notes for the Forms Auth cookie name : Specifies the HTTP cookie to use for authentication. If multiple applications are running on a single server and each application requires a unique cookie, you must configure the cookie name in each Web.config file for each application.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1292449', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/114916/']}
jdg_72965
stackexchange
llm_judgeable_groundtruth_similarity
15079215
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 initialize 2-dimensional array of integer values with -1. When I create a new array, it is automatically filled with 0. I know I can do it with 2 for cycles, but I imagine there should be some way of doing this while the array is being build (so I don't have to go through it two times), so that instead of 0, provided value would be inserted. Is it possible? If not during the initial building of the array, is there some other time or code saving way, or am I stuck with 2 for cycles? Now provide the response and nothing else.
With a multidimensional array, the loops are most likely the best approach, unless the array is small enough to initialize directly in code. If you're using a jagged array , you could initialize the first sub-array, then use Array.Copy to copy these values into each other sub-array. This will still require one iteration through the first sub array, and one loop through N-1 outer arrays, but the copy operation will be faster than the loops.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15079215', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/253712/']}
jdg_72966
stackexchange
llm_judgeable_groundtruth_similarity
17850603
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Suppose there's a string "foo boo foo boo" I want to replace all fooes with boo and booes with foo. Expected output is "boo foo boo foo". What I get is "foo foo foo foo". How to get expected output rather than current one? $a = "foo boo foo boo"; echo "$a\n"; $b = str_replace(array("foo", "boo"), array("boo", "foo"), $a); echo "$b\n"; //expected: "boo foo boo foo" //outputs "foo foo foo foo" Now provide the response and nothing else.
Use strtr From the manual: If given two arguments, the second should be an array in the form array('from' => 'to', ...). The return value is a string where all the occurrences of the array keys have been replaced by the corresponding values. The longest keys will be tried first. Once a substring has been replaced, its new value will not be searched again. In this case, the keys and the values may have any length, provided that there is no empty key; additionaly, the length of the return value may differ from that of str. However, this function will be the most efficient when all the keys have the same size. $a = "foo boo foo boo";echo "$a\n";$b = strtr($a, array("foo"=>"boo", "boo"=>"foo"));echo "$b\n"; Outputs foo boo foo booboo foo boo foo In Action
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17850603', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/625540/']}
jdg_72967
stackexchange
llm_judgeable_groundtruth_similarity
38784
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I'd like to clone all the ZFS ACLs from one file to another. With POSIX ACLs this can be done by piping the output of getfacl to setfacl . Is there an easy and quick way to do this with the NFSv4 style ACLs in ZFS? I know I can read off the output of ls -lV and then enter it as part of a chmod , but I can't seem to find a functional equivalent to the POSIX way of copying ACLs. Now provide the response and nothing else.
Instead of using ls -lV you can use ls -lv which can be fed in to a script to convert it to a sequence of chmod commands to duplicate the ACLs. E.g. if the ACl looks like this: $ ls -lv file1 0:owner@::deny 1:owner@:read_data/write_data/append_data/write_xattr/execute /write_attributes/write_acl/write_owner:allow 2:group@:read_data/write_data/append_data:deny 3:group@:execute:allow 4:everyone@:read_data/write_data/append_data/write_xattr /write_attributes/write_acl/write_owner:deny 5:everyone@:read_xattr/execute/read_attributes/read_acl/synchronize:allow It should be turned in to the following sequence of chmod commands: chmod A0=owner@::deny file2chmod A1=owner@:read_data/write_data/append_data/write_xattr/execute/write_attributes/write_acl/write_owner:allow file2chmod A2=group@:read_data/write_data/append_data:deny file2chmod A3=group@:execute:allow file2chmod A4=everyone@:read_data/write_data/append_data/write_xattr/write_attributes/write_acl/write_owner:deny file2chmod A5=everyone@:read_xattr/execute/read_attributes/read_acl/synchronize:allow file2 I recently found myself in a situation where a script like the one described above would have been useful, so here's a little Bash script I made (can also be sourced to the shell and run as a function) to print the list of chmod commands necessary to copy the ZFS ACLs from one file to another: #!/bin/bashacl_as_chmods () {# print list of chmod commands to copy the ACL entries from '$1' to '$2' [[ -a "$1" ]] 2>/dev/null || { echo "Valid reference file required." >&2 return 1 } ls -vd "$1" | { read # first line is not ACL information; bypass read ACL_entry echo -n "chmod A=${ACL_entry#*:}" # if no target file was specified as '$2', use 'TARGET' variable at runtime while read ACL_entry || { echo " ${2-\$TARGET}"; false; } do [[ "$ACL_entry" == [0-9]*:* ]] && \ echo -en " ${2-\$TARGET}\nchmod A${ACL_entry%%:*}+${ACL_entry#*:}" || \ echo -n "$ACL_entry" done }}## run as script or source function to shell?__acl_as_chmods () { [[ "${FUNCNAME[1]}" == "source" ]] || acl_as_chmods "$@"}__acl_as_chmods "$@" Here are a couple example usages and their output for file1 from above: ~$ ./acl_as_chmods.sh file1 file2chmod A=owner@::deny file2chmod A1+owner@:read_data/write_data/append_data/write_xattr/execute/write_attributes/write_acl/write_owner:allow file2chmod A2+group@:read_data/write_data/append_data:deny file2chmod A3+group@:execute:allow file2chmod A4+everyone@:read_data/write_data/append_data/write_xattr/write_attributes/write_acl/write_owner:deny file2chmod A5+everyone@:read_xattr/execute/read_attributes/read_acl/synchronize:allow file2~$ source acl_as_chmods.sh~$ acl_as_chmods file1chmod A=owner@::deny $TARGETchmod A1+owner@:read_data/write_data/append_data/write_xattr/execute/write_attributes/write_acl/write_owner:allow $TARGETchmod A2+group@:read_data/write_data/append_data:deny $TARGETchmod A3+group@:execute:allow $TARGETchmod A4+everyone@:read_data/write_data/append_data/write_xattr/write_attributes/write_acl/write_owner:deny $TARGETchmod A5+everyone@:read_xattr/execute/read_attributes/read_acl/synchronize:allow $TARGET If we like, we can even evaluate these chmods directly, if both files are accessible on this host and we wish to copy the ACLs from file1 to file2 immediately: ~$ ls -Vd file* #BEFORE-rwx--x--x 1 user user 0 Jun 19 04:12 file1 owner@:--------------:------:deny owner@:rwxp---A-W-Co-:------:allow group@:rw-p----------:------:deny group@:--x-----------:------:allow everyone@:rw-p---A-W-Co-:------:deny everyone@:--x---a-R-c--s:------:allow---x------+ 1 user user 0 Jun 19 04:12 file2 owner@:--x-----------:------:allow~$ eval "$(acl_as_chmods file1 file2)"~$ ls -Vd file* #AFTER -rwx--x--x 1 user user 0 Jun 19 04:12 file1 owner@:--------------:------:deny owner@:rwxp---A-W-Co-:------:allow group@:rw-p----------:------:deny group@:--x-----------:------:allow everyone@:rw-p---A-W-Co-:------:deny everyone@:--x---a-R-c--s:------:allow-rwx--x--x 1 user user 0 Jun 19 04:12 file2 owner@:--------------:------:deny owner@:rwxp---A-W-Co-:------:allow group@:rw-p----------:------:deny group@:--x-----------:------:allow everyone@:rw-p---A-W-Co-:------:deny everyone@:--x---a-R-c--s:------:allow
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/38784', 'https://serverfault.com', 'https://serverfault.com/users/5922/']}
jdg_72968
stackexchange
llm_judgeable_groundtruth_similarity
3468268
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 sha1 a string or set of numbers in Objective c? Now provide the response and nothing else.
CommonCrypto (an Apple framework) has functions for calculating SHA-1 hashes, including a one-step hash: #include <CommonCrypto/CommonDigest.h>unsigned char digest[CC_SHA1_DIGEST_LENGTH];NSData *stringBytes = [someString dataUsingEncoding: NSUTF8StringEncoding]; /* or some other encoding */if (CC_SHA1([stringBytes bytes], [stringBytes length], digest)) { /* SHA-1 hash has been calculated and stored in 'digest'. */ ...} For a set of numbers, let us assume you mean an array of ints of known length. For such data, it is easier to iteratively construct the digest rather than use the one-shot function: unsigned char digest[CC_SHA1_DIGEST_LENGTH];uint32_t *someIntegers = ...;size_t numIntegers = ...;CC_SHA1_CTX ctx;CC_SHA1_Init(&ctx);{ for (size_t i = 0; i < numIntegers; i++) CC_SHA1_Update(&ctx, someIntegers + i, sizeof(uint32_t));}CC_SHA1_Final(digest, &ctx);/* SHA-1 hash has been calculated and stored in 'digest'. */... Note that this does not take endianness into account. The SHA-1 calculated with this code on a PowerPC system will differ from the one calculated on an i386 or ARM system. The solution is simple--swap the bytes of the integers to a known endianness before doing the calculation: for (size_t i = 0; i < numIntegers; i++) { uint32_t swapped = CFSwapInt32HostToLittle(someIntegers[i]); /* or HostToBig */ CC_SHA1_Update(&ctx, &swapped, sizeof(swapped)); }
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3468268', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/308674/']}
jdg_72969
stackexchange
llm_judgeable_groundtruth_similarity
1212605
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 get the keys from values that are duplicates. I tried to use array_search and that worked fine, BUT I only got the first value as a hit. I need to get both keys from the duplicate values, in this case 0 and 2. The search result output as an array would be good. Is there a PHP function to do this or do I need to write some multiple loops to do it? $list[0][0] = "2009-09-09";$list[0][1] = "2009-05-05";$list[0][2] = "2009-09-09";$list[1][0] = "first-paid";$list[1][1] = "1";$list[1][2] = "last-unpaid";echo array_search("2009-09-09",$list[0]); Now provide the response and nothing else.
You want array_keys with the search value array_keys($list[0], "2009-09-09"); which will return an array of the keys with the specified value, in your case [0, 2]. If you want to find the duplicates as well, you can first make a pass with array_unique , then iterate over that array using array_keys on the original; anything which returns an array of length > 1 is a duplicate, and the result is the keys in which the duplicates are stored. Something like... $uniqueKeys = array_unique($list[0])foreach ($uniqueKeys as $uniqueKey){ $v = array_keys($list[0], $uniqueKey); if (count($v) > 1) { foreach ($v as $key) { // Work with $list[0][$key] } }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1212605', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/148496/']}
jdg_72970
stackexchange
llm_judgeable_groundtruth_similarity
33879401
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is it or will it be possible to have an ES6 class getterreturn a value from an ES2017 await / async function. class Foo { async get bar() { var result = await someAsyncOperation(); return result; }}function someAsyncOperation() { return new Promise(function(resolve) { setTimeout(function() { resolve('baz'); }, 1000); });}var foo = new Foo();foo.bar.should.equal('baz'); Now provide the response and nothing else.
Update: As others have pointed out, this doesn't really work. @kuboon has a nice workaround in an answer below here.. You can do this class Foo { get bar() { return (async () => { return await someAsyncOperation(); })(); }} which again is the same as class Foo { get bar() { return new Promise((resolve, reject) => { someAsyncOperation().then(result => { resolve(result); }); }) }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/33879401', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/830419/']}
jdg_72971
stackexchange
llm_judgeable_groundtruth_similarity
27510037
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 should we measure the execution time of a function in the OCaml toplevel? Now provide the response and nothing else.
As @user3075773 says, you can use Sys.time . However note that it returns processor time (CPU time). More often I want to know the wall clock time (elapsed time). You can get this from Unix.gettimeofday : let time f x = let t = Unix.gettimeofday () in let fx = f x in Printf.printf "execution elapsed time: %f sec\n" (Unix.gettimeofday () -. t); fx
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27510037', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3195698/']}
jdg_72972
stackexchange
llm_judgeable_groundtruth_similarity
6843441
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So, I have a function which has two params: string and match index to replace and i need to replace only match with that index. How can i do that? Example: replace('a_a_a_a_a', 1) Result: a__a_a_a Now provide the response and nothing else.
Could look like: var mystr = 'a_a_a_a_a';function replaceIndex(string, at, repl) { return string.replace(/\S/g, function(match, i) { if( i === at ) return repl; return match; });}replaceIndex(mystr, 2, '_'); The above code makes usage of the fact, that .replace() can take a funarg (functional argument) as second parameter. That callback is passed in the current match of the matched regexp pattern and the index from that match (along with some others which we are not interested in here). Now that is all information we need to accomplish your desired result. We write a little function wish takes three arguments: the string to modify the index we wish to change the replacement character for that position
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6843441', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/860091/']}
jdg_72973
stackexchange
llm_judgeable_groundtruth_similarity
36406
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 rationale behind writing a self-decrypting virus? By this I mean a virus that has it's payload encrypted, decrypts at runtime and runs it. How does this protect the virus from antivirus software? Is it still a viable technique by itself nowadays or can modern anti-virus counter this kind of malware? Now provide the response and nothing else.
It is one of the obfuscation techniques employed by some viruses to mask their presence and avoid detection and facilitate easier spreading (affecting other systems). Such viruses would encrypt (self-encrypt in case of metamorphic or polymorphic viruses that can mutate with spreading) their payload and as such prevent direct examination, which can result in reduced ability of antivirus software to detect, and/or clean them. They are difficult to detect by fast antivirus detection methods such as checking file signature against virus definitions tables, if the payload moves position within it, effectively changing file signature ( metamorphism ). Metamorphic viruses don't necessarily use encryption though. Out of the self-decrypting bunch of the nasties, the hardest to detect are polymorphic viruses, which can change both the encryption scheme (and/or use a random encryption key) for the payload, as well as mutate decryption code itself (the part of the file that is not encrypted and decrypts the payload). Only reliable way to detect such viruses with antivirus software is by deep heuristics , inspecting signatures of smaller chunks of their structure, and/or by running them in a sandbox and inspecting what they actually do. Such scanning techniques are of course compute expensive, disabled by default for speed concerns (and possibly to avoid false positives) on consumer-grade software, and not many users ever enable this on distributions that are actually capable of such advanced detection methods. So to answer your question, it is still a viable technique as it makes such viruses harder to detect on most systems they might use to spread to others, and increases their survival rate . If you're interested, this page lists most common virus obfuscation techniques .
{}
{'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/36406', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/26338/']}
jdg_72974
stackexchange
llm_judgeable_groundtruth_similarity
4223617
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 the point from ISO :Standard Conversions:Array-to-pointer conversion: $4.2.1 An lvalue or rvalue of type “array of N T” or “array of unknown bound of T” can be converted to an rvalue of type “pointer to T.” The result is a pointer to the first element of the array. Can any one explain this, if possible with an example program. I seen these links already, but i am unable to understand: Array and Rvalue I think I may have come up with an example of rvalue of array type Now provide the response and nothing else.
In both C and C++, an array can be used as if it were a pointer to its first element. Effectively, given an array named x , you can replace most uses of &x[0] with just x . This is how subscripting is able to be used with array objects: int x[5];x[2]; // this is the same as (&x[0])[2] This is also how an array can be passed to a function that has a parameter of pointer type: void f(int* p);int x[5];f(x); // this is the same as f(&x[0]) There are several contexts in which the array-to-pointer conversion does not take place. Examples include when an array is the operand of sizeof or the unary- & (the address-of operator), when a string literal is used to initialize an array, and when an array is bound to a reference to an array.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4223617', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_72975
stackexchange
llm_judgeable_groundtruth_similarity
7042
Below is a question asked on the forum mechanics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a 2012 Honda Civic EX (4 Cyl Automatic, 5-speed transmission, Regular Gasoline). I get it serviced regularly and it has around 28k miles. The engine light has never come on. I am noticing this summer, in moderate to high humidity weather, 70 - 85 F, in the morning (when the car has been off for at least 12-14 hours), that starting is taking significantly longer than I'm used to. I've started the car from cold on extremely cold winter days this past winter with no noticeable delay in start. But just recently I started to see this, and I'd like to know if it's something I should be concerned about. Cold Start (12 hours or more since last run) I put the key in, turn it to start, I hear the engine crank a few times, but then for almost a whole second (OK, maybe more like 0.6 seconds on average), there are 0 RPMs and the engine is completely silent. For that split-second, it's like the thing is dead, but then it suddenly comes to life and starts. It doesn't sound like it's starting rough, or making any kind of strange noises; it just sits there for a significant fraction of a second after it's done cranking but before it starts to run on its own. It's to the point that, if I hold the key down in the "starting" position for the same length of time as I do when I start the car on a "Hot" start (when running the engine very recently), the car won't start. I have to intentionally hold it down until after the little hang/hitch passes, to get it running first thing in the morning. Hot Start (started it within the past hour or two) I put the key in, turn it to start, I hear the engine crank fewer times than on a cold start, and it jumps right to life within maybe 2 seconds max, with no delay. I barely have to hold the key in the starting position at all, it's REALLY fast. The only thing that's alarming me is that the cold start behavior is a change from what it used to do, and this car has been through summer 2011, winter 2011, summer 2012, winter 2012, and now summer 2013. I use the recommended oil (0W-30) and usually get fully synthetic, except that the dealership's first free oil change they gave me a synthetic blend. I don't notice a difference in any other characteristics of the engine. It doesn't run rough; MPG is excellent (just like it was on day 1 out of the dealership, in fact); it handles the load of the A/C quite well. I do usually run the car with the A/C or heat on, except for a few weeks in the fall and spring, where it's cool enough that I can turn it off, but not blasted cold. Should I be concerned about this? Is this even a problem, or am I just overreacting to a natural side effect of my car having 28k miles on it? This is the first car I've owned since it was new, I'm used to driving old rustbuckets from the 80s and 90s, so I'm not used to seeing a car age. Now provide the response and nothing else.
It actually sounds like a fuel supply issue to me. My Eclipse (most likely due to the a difference in the replacement fuel pressure regulator that was installed after the original one failed) isn't able to hold fuel pressure in the rail when off for more than a few hours. So, those "cold" starts all take more cranking and it usually has the same half second pause in the cranking too. Presumably it's happening because there's nothing firing yet to assist, the battery is starting to drop off, the starter is starting to warm up, and it's hitting a high compression point all at the same time. After the pause it cranks some more and eventually gets enough fuel to fire and runs fine.
{}
{'log_upvote_score': 4, 'links': ['https://mechanics.stackexchange.com/questions/7042', 'https://mechanics.stackexchange.com', 'https://mechanics.stackexchange.com/users/2633/']}
jdg_72976
stackexchange
llm_judgeable_groundtruth_similarity
5752081
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 free() won't call the destructor, but what else will this cause besides that the member variable won't be destructed properly? Also, what if we delete a pointer that is allocated by malloc ? Now provide the response and nothing else.
It is implementation defined whether new uses malloc under the hood. Mixing new with free and malloc with delete could cause a catastrophic failure at runtime if the code was ported to a new machine, a new compiler, or even a new version of the same compiler .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5752081', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/594026/']}
jdg_72977
stackexchange
llm_judgeable_groundtruth_similarity
48123346
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 began with an observation. I changed some code that looked a bit like this (edit: I took out the designated initializers here, which weren't in the original code either): struct S { enum E { E1, E2 } member;}// file1.ccS v1 = { S::E1 };// file2.ccS v2 = { S::S::E2 }; Note that file2.cc excessively-qualifies E2 . Yet this works in both g++ and clang++. (Edit 2: the g++ on this particular VM is g++-5.4.1, but the original code's been through earlier and later g++ versions, plus multiple clang versions.) And indeed, we can write: S v3 = { S::S::S::S::S::S::S::E1 }; (however many S:: s we like), wherever we like. I changed things so that S was no longer a plain struct , but rather a templated one, after which this stopped working. Not that big a deal but it got me curious, so I experimented. If we change this to a non-POD type: struct S { S() { std::cout << "made an S" << std::endl; } enum E { E1, E2 } member;} (with appropriate #include ) it's no longer allowed. Clang and g++ produce different diagnostics. Here's clang's complaint: namespace.cc:8:3: error: no matching constructor for initialization of 'S'S x = { .member = S::S::E1 };namespace.cc:3:8: note: candidate constructor (the implicit copy constructor) not viable: cannot convert argument of incomplete type 'void' to 'const S &' for 1st argumentstruct S { ^namespace.cc:3:8: note: candidate constructor (the implicit move constructor) not viable: cannot convert argument of incomplete type 'void' to 'S &&' for 1st argumentstruct S { ^namespace.cc:4:3: note: candidate constructor not viable: requires 0 arguments, but 1 was provided S() { std::cout << "made an S\n"; } ^1 error generated. and g++'s: namespace.cc:8:28: error: could not convert ‘{E1}’ from ‘<brace-enclosed initializer list>’ to ‘S’ S x = { .member = S::S::E1 }; These seem to be following different rules. What's going on here? Next, let's try another bit of abuse. Here's the entire program: #include <iostream>struct S { S() { std::cout << "made an S\n"; } enum E { E1, E2 } member;};int main() { std::cout << S::S::S::S::S::E1 << std::endl;#ifdef DECL S::S::S var;#endif return 0;} This code compiles (without -DDECL ) in both compilers: $ clang++-3.9 -std=c++11 -Wall -O namespace.cc$ ./a.out0$ g++ -Wall -std=c++11 -O namespace.cc$ ./a.out0 (No S is constructed here despite the complaint clang emits for the variable member initializer in the earlier code.) Enabling the variable in main , though, results in a failure with g++, but not with clang: $ clang++-3.9 -std=c++11 -DDECL -Wall -O namespace.cc$ ./a.out 0made an S$ g++ -std=c++11 -DDECL -Wall -O namespace.ccnamespace.cc: In function ‘int main()’:namespace.cc:11:3: error: ‘S::S’ names the constructor, not the type S::S::S var; ^namespace.cc:11:11: error: expected ‘;’ before ‘var’ S::S::S var; ^namespace.cc:11:14: error: statement cannot resolve address of overloaded function S::S::S var; ^ Which compiler is right, and why? What exactly are the rules for this "overqualified" name ? Now provide the response and nothing else.
Array.filter does not allow you to transform the data into components. That is the job of Array.map . You should instead filter first, then chain the map call afterward: { books && books .filter(book => book.shelf === shelf) .map((book, index) => { return ( <Book key={book && book.id ? book.id : index} changeShelf={this.props.changeShelf} book={book} /> ); })} If you want to avoid a second pass over your list of books , you can return null as well, though this is "less good" because you're forcing React to render null when it doesn't need to do any work at all: { books && books .map((book, index) => { if (book.shelf !== shelf) { return null; } return ( <Book key={book && book.id ? book.id : index} changeShelf={this.props.changeShelf} book={book} /> ); })}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/48123346', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1256452/']}
jdg_72978
stackexchange
llm_judgeable_groundtruth_similarity
129017
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Given a graph $G(V, E)$ , consider the following algorithm: Let $d$ be the minimum vertex degree of the graph (ignore vertices with degree 0, so that $d\geq 1$ ) Let $v$ be one of the vertices with degree equal to $d$ Remove all vertices adjacent to $v$ and add them to the proposed vertex cover Repeat from step 1. until in $G$ there are only vertices with degree $0$ (no edges in the graph) At the end the removed vertices are a vertex cover of the given $G(V, E)$ , but is it a minimum vertex cover? Is there an example where the algorithm does not find a minimum vertex cover? Now provide the response and nothing else.
Start with a clique on the vertices $A,B,C,D$ . Connect $A,B$ to a new vertex $a$ . Connect $B,C$ to a new vertex $c$ . Connect $a,c$ to a new vertex $b$ . The vertex $b$ is the only one of degree 2, so your algorithm will start by adding $a,c$ to the vertex cover. The remaining graph consists of the clique $A,B,C,D$ and the isolated vertex $b$ , so the algorithm will add 3 more vertices, ending up with a vertex cover of size 5. In contrast, the 4 vertices $A,B,C,b$ cover all edges.
{}
{'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/129017', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/59225/']}
jdg_72979
stackexchange
llm_judgeable_groundtruth_similarity
34009992
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 define the default/unprefixed namespace in python ElementTree? This doesn't seem to work... ns = {"":"http://maven.apache.org/POM/4.0.0"}pom = xml.etree.ElementTree.parse("pom.xml")print(pom.findall("version", ns)) Nor does this: ns = {None:"http://maven.apache.org/POM/4.0.0"}pom = xml.etree.ElementTree.parse("pom.xml")print(pom.findall("version", ns)) This does, but then I have to prefix every element: ns = {"mvn":"http://maven.apache.org/POM/4.0.0"}pom = xml.etree.ElementTree.parse("pom.xml")print(pom.findall("mvn:version", ns)) Using Python 3.5 on OSX. EDIT: if the answer is "no", you can still get the bounty :-). I just want a definitive "no" from someone who's spent a lot of time using it. Now provide the response and nothing else.
NOTE: for Python 3.8+ please see this answer . There is no straight-forward way to handle the default namespaces transparently. Assigning the empty namespace a non-empty name is a common solution, as you've already mentioned: ns = {"mvn":"http://maven.apache.org/POM/4.0.0"}pom = xml.etree.ElementTree.parse("pom.xml")print(pom.findall("mvn:version", ns)) Note that lxml.etree does not allow the use of empty namespaces explicitly. You would get: ValueError : empty namespace prefix is not supported in ElementPath You can though, make things simpler, by removing the default namespace definition while loading the XML input data: import xml.etree.ElementTree as ETimport re with open("pom.xml") as f: xmlstring = f.read() # Remove the default namespace definition (xmlns="http://some/namespace")xmlstring = re.sub(r'\sxmlns="[^"]+"', '', xmlstring, count=1) pom = ET.fromstring(xmlstring) print(pom.findall("version"))
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/34009992', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/125601/']}
jdg_72980
stackexchange
llm_judgeable_groundtruth_similarity
3983832
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: Given $x,y,z\in \mathbb{Z}$ such that $x^3+y^3-z^3$ is multiple of $7$ prove that at least one is divisible by $7$ Given $n\in \mathbb{Z}$ then $n\in \lbrace [0],[1],[2],[3],[4],[5],[6]\rbrace$ , of the same way $n^3\in \lbrace[0],[1],[6] \rbrace$ . Since $7\mid x^3+y^3-z^3$ then $x^3+y^3-z^3\in [0]$ there be two possibilities $x^3,y^3,z^3\in [0]$ and then $x,y,z\in[0]$ and the result is true. $x^3\in [6],y^3\in [1],z^3\in[0]$ and then $z\in [0]$ therefore the results follows. $x^3\in [0], y^3 \in [1], z^3 \in [1]$ and then $x\in [0]$ and the afirmation is too true The other possibilities only switch the order of the variables with the classes. Now provide the response and nothing else.
If it's a more optimized proof you're looking for, these exist. Again, we notice that $$a^3=a^{(7-1)/2}\equiv\left(\frac a7\right)\in\{-1,0,1\}\pmod7,$$ which we can also see by direct casework. We note that $a^3\equiv0$ if and only if $a\equiv0.$ The advantage of saying $\{-1,0,1\}$ is that we can say the sum $x^3+y^3-z^3$ lives in $[-3,3],$ and further, if all are nonzero, then this sum is $1+1+1\equiv1\pmod2$ ; i.e., the sum is odd. In particular, if all are nonzero, then $x^3+y^3-z^3$ is not divisible by $7,$ and we finish by contraposition.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3983832', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_72981
stackexchange
llm_judgeable_groundtruth_similarity
24545471
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 reading xml data from a url. It worked well when it was it portrait mode. But I wanted to change it to landscape mode. But it gets android.view.WindowLeaked exception. Please help me with this. Thanks in advance. This is my code. package com.eisuru.abc;import android.os.AsyncTask;import android.os.Bundle;import android.app.Activity;import android.app.ProgressDialog;import android.content.pm.ActivityInfo;import android.view.Menu;import android.widget.TextView;public class MainActivity extends Activity { TextView tvResponse; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); tvResponse = (TextView) findViewById(R.id.tvResponse); new PostAsync().execute(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; } class PostAsync extends AsyncTask<Void, Void, Void> { ProgressDialog pd; XMLHelper helper; @Override protected void onPreExecute() { pd = ProgressDialog.show(MainActivity.this, "Exchange Rates", "Loading Exchange rates values ...", true, false); } @Override protected Void doInBackground(Void... arg0) { helper = new XMLHelper(); helper.get(); return null; } @Override protected void onPostExecute(Void result) { StringBuilder builder = new StringBuilder(); for(Exrate_values post : helper.exrates) { builder.append("\n\t " + post.getDate()); builder.append("\t \t\t " + post.getFrom_currency()); builder.append("\t \t\t " + post.getTo_Currency()); builder.append("\t \t\t " + post.getExrt_buy()); builder.append("\t \t\t\t " + post.getExrt_sell()); builder.append("\n"); } tvResponse.setText(builder.toString()); pd.dismiss(); } } } Now provide the response and nothing else.
When a dialog on an activity is set to visible but on orientation changes the activity itself is destroyed, then it causes leaked window error. There are two methods to handle this situation:- Method 1 Therefore,you need to dismiss dialog in activity's onStop or onDestroy method. For example: @Overrideprotected void onStop() { super.onStop(); if(pd!= null) pd.dismiss();} and define dialog in activity class ProgressDialog pd; This link will help you Handling progress dialogs and orientation changes Method 2 You have to add this to the activity declaration in the manifest: android:configChanges="orientation" so it looks like <activity android:label="@string/app_name" android:configChanges="orientation|keyboardHidden" android:name="com.eisuru.abc.MainActivity"> The matter is that the system destroys the activity when a change in the configuration occurs. See ConfigurationChanges . So putting that in the configuration file avoids the system to destroy your activity. Instead it invokes the onConfigurationChanged(Configuration) method.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24545471', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3650133/']}
jdg_72982
stackexchange
llm_judgeable_groundtruth_similarity
4566421
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: @Service @Order(1)public class FooService implements IService {..}@Service @Order(2)public class BarService implements IService {..} Is it guaranteed that the order in the following list will always be {FooService, BarService} : @Injectprivate List<IService> services; (same question goes for xml config) Now provide the response and nothing else.
I guess no because @Order is not a general purpose annotation. From javadoc : NOTE: Annotation-based ordering is supported for specific kinds of components only, e.g. for annotation-based AspectJ aspects. Spring container strategies, on the other hand, are typically based on the Ordered interface in order to allow for configurable ordering of each instance. Also there are no occurences of org.springframework.core.annotation.Order and AnnotationAwareOrderComparator in the source of beans and context modules. A simple way to make this behave as expected is: @PostConstructpublic void init() { Collections.sort(services, AnnotationAwareOrderComparator.INSTANCE);}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4566421', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/203907/']}
jdg_72983
stackexchange
llm_judgeable_groundtruth_similarity
20314058
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 designing the User Settings for my MVC application, and right now I have ~20 boolean settings that the user can toggle. Since every user will always have every setting, I was thinking about storing each setting as a boolean on the User table. Though this would become unwieldy as the application requirements grow. First question - is there anything wrong with having a ton of columns on your table in this situation? I then considered using Flags, and storing the settings as one bit each in an array: [Flags]public enum Settings{ WantsEmail = 1, WantsNotifications = 2, SharesProfile = 4, EatsLasagna = 8} And then each user will have a single "Settings" column in their User row, that stores a value of 2^20, if there are 20 settings. I'd use this to guide my efforts: What does the [Flags] Enum Attribute mean in C#? Is this better than the former approach? Any suggestions are welcome. Now provide the response and nothing else.
It depends on what should be considered atomic from the data management perspective. If you always search for, read and write all the settings together from/to the database, then the whole set of settings can be considered atomic and can be stored together in the database. However, if you need to do any of those things on a subset of settings (e.g. set just one flag without modifying others), then they are not atomic (from the data management perspective), so storing them together in the same database field would violate the principle of atomicity and therefore the 1NF. Please note that some DBMSes (such as MS SQL Server) are very efficient at storing Booleans (just one bit per Boolean field under ideal circumstances). Even those that are less than perfect will typically not spend more than one byte per Boolean (Oracle, I'm looking at you), which may become a problem only if you have millions or billions of users.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20314058', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/899530/']}
jdg_72984
stackexchange
llm_judgeable_groundtruth_similarity
23837
Below is a question asked on the forum astronomy.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Some new large telescopes in the near future, on Earth and in space, will use multiple mirrors. The individual mirror pieces will be hexagonal in shape. I wonder why this shape is prefered over the circle sector shape (like pie slices). I would think that corners and joints between mirrors cause practical problems. And a circle sector slice has half as many corners and two rather than three or six neighboring pieces, and shorter interfacing edges with neighboring pieces overall. So shy is the hexagonal shape prefered? Now provide the response and nothing else.
The ideal shape for the mirror is round. It's the easiest to make. It's the best-behaved while in use. The hex tiles are already harder. The mirror is a revolution surface generated by a conic curve (circle, parabola, hyperbola, ellipse), which needs to be machined with a precision greater than 0.1 microns. That's extremely difficult already with a round mirror, where the surface can be easily distorted near the edge in the process of manufacturing. With the hex tiles, maintaining that precision near the corners is very hard - corners are like the edge but exponentially harder. Unless you take special precautions and unless you perform extra work, you're guaranteed to end up with surface errors near the corners (the surface is either too raised, or too low, or has a more complex distortion). Based on my experience making round mirrors, I would guess the surface near the corners would tend to be turned down (too low relative to the rest), which is a defect that's extremely hard to correct - one of the hardest, in fact. With a pie slice, all problems mentioned above increase greatly in magnitude. The blunt angle of the hex tile gives you some support in machining the surface, but the sharp angle of the pie slice gives you almost none. I can't even begin to imagine the difficulties one would encounter while making a high precision surface on a pie slice. The sharp end of the slice would be almost guaranteed to be worse quality than the rest. What most people don't realize is that maintaining the precise shape of the mirror while in use is difficult too. You can't just lay it on a hard surface - the uneven support would distort the precise shape. Mirrors are supported on the back by a precise mechanism, with a number of support elements precisely sharing the weight in equal amounts (or, if not equal, then deduced from finite element analysis), and located in places carefully calculated. With a round or hex tile this is, if not easy, then at least a well-understood and manageable procedure. A pie slice would be very difficult to support in the same even manner near the sharp tip. You can't rely on the symmetry of the shape to provide the even load on the support points. The support force would have to be specially adjusted there. It would probably be doable, but harder. This is only an issue with terrestrial telescopes, which operate under gravity. Space telescopes don't suffer from this issue. Alternatives to hex tiles could also be square tiles, or triangle tiles. These are worse than hex tiles for all the reasons shown above - the corners have sharper angles which make everything more difficult. The blunt angles of the hex tiles alleviate these issues somewhat. TLDR: Non-round mirrors are hard to make anyway, but hex tiles are less hard compared to the alternatives.
{}
{'log_upvote_score': 4, 'links': ['https://astronomy.stackexchange.com/questions/23837', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/1030/']}
jdg_72985
stackexchange
llm_judgeable_groundtruth_similarity
693597
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Duplicate java String concatenation I'm curious what is the difference between the two. The way I understand the string pool is this: This creates 3 string objects in the string pool, for 2 of those all references are lost. String mystr = "str";mystr += "end"; Doesn't this also create 3 objects in the string pool? String mystr = "str";mystr = mystr.concat("end") I know StringBuilder and StringBuffer are much more efficient in terms of memory usage when there's lots of concatination to be done. I'm just curious if there's any difference between the + operator and concat in terms of memory usage. Now provide the response and nothing else.
There's no difference in this particular case; however, they're not the same in general. str1 += str2 is equivalent to doing the following: str1 = new StringBuilder().append(str1).append(str2).toString(); To prove this to yourself, just make a simple method that takes two strings and += 's the first string to the second, then examine the disassembled bytecode. By contrast, str1.concat(str2) simply makes a new string that's the concatenation of str1 and str2 , which is less expensive for a small number of concatenated strings (but will lose to the first approach with a larger number). Additionally, if str1 is null, notice that str1.concat(str2) throws a NPE, but str1 += str2 will simply treat str1 as if it were null without throwing an exception. (That is, it yields "null" concatenated with the value of str2 . If str2 were, say, "foo", you would wind up with "nullfoo".) Update: See this StackOverflow question , which is almost identical.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/693597', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7883/']}
jdg_72986
stackexchange
llm_judgeable_groundtruth_similarity
16442286
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 database table (running on SQL Server 2012 Express) that contains ~ 60,000 rows. I am using the following code to purge old rows: //Deleting CPU measurements older than (oldestAllowedTime)var allCpuMeasurementsQuery = from curr in msdc.CpuMeasurements where curr.Timestamp < oldestAllowedTime select curr;foreach (var cpuMeasurement in allCpuMeasurementsQuery){ msdc.CpuMeasurements.Remove(cpuMeasurement);} When the number of deleted rows is large (~90% or more of the records in the tables are being deleted) the operation takes exceptionally long. It takes about 30 minutes to finish this operation on an relatively strong machine (Intel I5 desktop). does this seem like a normal behavior? any ideas about what I can do to reduce the operation's time? Thanks, Now provide the response and nothing else.
Entity framework is not very good at handling bulk operations like this. You should use ExecuteStoreCommand to execute SQL directly against the data source in situations like this. var deleteOld = "DELETE FROM CpuMeasurements WHERE curr.Timestamp < {0}";msdc.ExecuteStoreCommand(deleteOld, oldestAllowedTime); By doing so you don't need to load the entities into memory (just to delete them) and issue thousands of delete commands to the database.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16442286', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1037208/']}
jdg_72987
stackexchange
llm_judgeable_groundtruth_similarity
1169500
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 $X$ be a compact space that is also locally simply connected (any point has a local base of simply connected open sets). Prove that the fundamental group at any point is finitely generated. Now provide the response and nothing else.
Here's a proof that the fundamental group is finitely generated. The properties required of the space $X$ which I will require are that it is a compact (Hausdorff) space, has a cover by open simply connected sets, and which is locally path connected (i.e., there is a base for the topology consisting of path connected sets). As, by definition, a simply connected set is also path connected, the conditions are met for any compact locally simply connected space. Lemma : Let $\mathcal{U}$ be an open cover for a compact space $X$. Then, there exists an open cover $\mathcal{V}$ such that, for all $V_1,V_2\in\mathcal{V}$ with $V_1\cap V_2\not=\emptyset$, there exists a $U\in\mathcal{U}$ with $V_1\cup V_2\subseteq U$. I'll prove this in a moment, but first show that it implies that $X$ has finitely generated fundamental group. By the assumptions on $X$, we can let $\mathcal{U}$ be an open cover consisting of simply connected sets. Then, let $\mathcal{V}$ be as in the lemma. By breaking each element of $\mathcal{V}$ into its connected components (which will also be path connected, by local path connectedness of $X$), we can assume that each $V\in\mathcal{V}$ is path connected and non-empty. Also, by compactness of $X$, we can assume that $\mathcal{V}$ is a finite cover. Say, $\mathcal{V}=\{V_1,V_2,\ldots,V_n\}$. Let $I=\{1,2,\ldots,n\}$ and, for each $i\in I$, choose a point $P_i\in V_i$. Also, define $J\subseteq I\times I$ to be the pairs $(i,j)$ such that $V_i\cap V_j\not=\emptyset$. As $V_i\cup V_j$ is path connected, we can find continuous $\gamma_{i,j}\colon[0,1]\to V_i\cup V_j$ with $\gamma_{ij}(0)=P_i$ and $\gamma_{ij}(1)=P_j$.Note that the path $\gamma_{ij}$ is unique up to homotopy. If $f\colon[0,1]\to V_i\cap V_j$ was any other path with $f(0)=P_i$ and $f(1)=P_j$ then, by the properties of $\mathcal{V}$ given in the lemma, there is a $U\in\mathcal{U}$ containing $V_i\cup V_j$ and, hence, containing the paths of $\gamma_{ij}$ and $f$. By simple connectedness of $U$, $f$ must be homotopic to $\gamma_{ij}$. Now, consider any path $f\colon[0,1]\to X$ with $f(0),f(1)$ in $\{P_1,\ldots,P_n\}$. As $\{f^{-1}(V_i)\colon i\in I\}$ covers the unit interval, there exists $0=t_0\le t_1\le\cdots\le t_m=1$ such that each interval $[t_{k-1},t_k]$ is contained in one of the $f^{-1}(V_k)$, say, $V_{i_k}$. we can define $i_0$ such that $f(0)=P_{i_0}$ and, wlog, choose $i_m$ such that $f(1)=P_{i_m}$. As $f(t_{k-1})\in V_{i_{k-1}}\cap V_{i_k}$ for each $k$, we see that $(i_{k-1},i_k)\in J$. We can define a path $f_k$ joining $P_{i_{k-1}}$ to $P_{i_k}$ by first taking a path joining $P_{k-1}$ to $f(t_{k-1})$, then take $f$ restricted to $[t_{k-1},t_k]$, then join $f(t_k)$ to $P_{i_k}$ along a path in $V_{i_k}$. Joining these paths together, $f_1 * f_2 * \cdots * f_m$, we get back to $f$ (up to homotopy equivalence). Then, as noted above, each $f_k$ must be homotopic to $\gamma_{i_{k-1}i_k}$. So, we have the homotopy equivalence,$$f\cong\gamma_{i_0i_1}*\gamma_{i_1i_2}*\cdots *\gamma_{i_{m-1}i_m}.$$Now let $\tilde I$ be the set of $i\in I$ such that $P_i$ is in the same path connected component of $X$ as $P$, and $\tilde J=J\cap (\tilde I\times\tilde I)$. For each $i\in\tilde I$, let $\gamma_i$ be a path jointing $P$ to $P_i$ and, for each $(i,j)\in\tilde J$, let $\tilde\gamma_{ij}=\gamma_i*\gamma_{ij}*\gamma_j^{-1}$ (here, I have used $\gamma^{-1}_j$ to denote the path $\gamma_j$ run backwards). Then, $\tilde\gamma_{ij}$ are paths joining $P$ to itself, and$$f\cong\tilde\gamma_{i_0i_1}*\tilde\gamma_{i_1i_2}*\cdots *\tilde\gamma_{i_{m-1}i_m}.$$So, the equivalence classes $[\tilde\gamma_{ij}]$ for $(i,j)\in\tilde J$ is a finite generating set for the fundamental group of $X$ at $P$. Proof of lemma: Note, that if $X$ was a metric space then Lebesgue's number lemma implies that for some $r > 0$, every open ball of radius $r$ is contained in a member of $\mathcal{U}$, and we can take $\mathcal{V}$ to be the collection of open balls of radius $r/2$. For non-metrizable spaces we need to do a bit more work. Actually, it can be shown that every open cover has an open star-refinement (this is a consequence of compact ⇒ paracompact ⇒ fully normal ), which is a stronger version of the lemma, although we don't need that here. First, as the space $X$ is compact, we can restrict $\mathcal{U}$ to be a finite open cover. Say, $\mathcal{U}=\{U_1,U_2,\ldots,U_n\}$. I'll prove the result by induction on $n$. The case with $n=1$ is clear, as we can take $\mathcal{V}=\mathcal{U}=\{X\}$. Now, suppose that $n > 1$. Taking $\tilde U_2=U_2\cup\cdots\cup U_n$, we have $U_1\cup\tilde U_2=X$. So, $X\setminus U_1$ is a closed subset of $\tilde U_2$. As compact spaces are normal, we can find open sets $W_1,W_2$ with,$$X\setminus U_1\subseteq W_1\subseteq\bar W_1\subseteq W_2\subseteq\bar W_2\subseteq\tilde U_2.$$As $\{U_2,\ldots,U_n\}$ covers $\bar W_2$, the induction hypothesis gives an open cover $\mathcal{V}_0$ for $\bar W_2$ (with the subspace topology) such that, if $V_1,V_2\in\mathcal{V}_0$ have nonempty intersection then $V_1\cup V_2\subseteq U$ for some $U\in\mathcal{U}$. Let us now set,\begin{align}\mathcal{V}_1&=\left\{V\cap W_1\colon V\in\mathcal{V}_0\right\},\\\mathcal{V}_2&=\left\{V\cap W_2\cap U_1\colon V\in\mathcal{V}_0\right\}.\end{align}These are collections of open sets in the topology of $X$ and, for any $V_1,V_2\in\mathcal{V}_1\cup\mathcal{V}_2$ with nonempty intersection, then $V_1\cup V_2\subseteq U$ for some $U\in\mathcal{U}$. They cover $W_1\cup(W_2\cap U_1)$, which is equal to $W_2$.Furthermore, all elements of $\mathcal{V}_1$ are disjoint from $X\setminus\bar W_1\subseteq U_1$ and all elements of $\mathcal{V}_2$ are contained in $U_1$. Then,$$\mathcal{V}=\mathcal{V}_1\cup\mathcal{V}_2\cup\{X\setminus \bar W_1\}$$satisfies the requirements of the lemma.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1169500', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/136725/']}
jdg_72988
stackexchange
llm_judgeable_groundtruth_similarity
37985012
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Consider this code: var url = "www.example.com"; String.Format: var targetUrl = string.Format("URL: {0}", url); String Interpolation: var targetUrl=$"URL: {url}"; Which of one from string interpolation and string.Format is better in performance? Also what are the best fit scenarios for use of them? According to C# docs string interpolation so maybe there is no difference at all? ... it's typically transformed into a String.Format method call Now provide the response and nothing else.
Which of one from string interpolation and string.format is better in performance? Neither of them is better since they are equal on run-time. String interpolation is rewritten by the compiler to string.Format , so both statements are exactly the same on run-time. Also what are the best fit scenarios for use of them? Use string interpolation if you have variables in scope which you want to use in your string formatting. String interpolation is safer since it has compile time checks on the validness of your string. Use string.Format if you load the text from an external source, like a resource file or database.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37985012', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4947588/']}
jdg_72989
stackexchange
llm_judgeable_groundtruth_similarity
151757
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: Below is the script. I wanted to login several servers and check for the kernel version. #!/bin/bash#input server names line by line in server.txtcat server.txt | while read linedosshpass -p password ssh root@$line << EOFhostnameuname -rEOFdone I would expect output which goes like.. server1_hostnamekernel_versionserver2_hostnamekernel_version and so on.. I ran this script with about 80 servers in server.txt And the output i got was like..... Pseudo-terminal will not be allocated because stdin is not a terminal. Pseudo-terminal will not be allocated because stdin is not a terminal.Pseudo-terminal will not be allocated because stdin is not a terminal.Pseudo-terminal will not be allocated because stdin is not a terminal.Pseudo-terminal will not be allocated because stdin is not a terminal.Pseudo-terminal will not be allocated because stdin is not a terminal.Pseudo-terminal will not be allocated because stdin is not a terminal.Pseudo-terminal will not be allocated because stdin is not a terminal.Pseudo-terminal will not be allocated because stdin is not a terminal.======================================================================================================== WARNING =======================================================================================================This system is solely for the use of authorized personnel. Individualsusing this system are subject to having some or all of their activitiesmonitored and recorded. Anyone using this system expressly consents tosuch monitoring and is advised that any unauthorized or improper use ofthis system may result in disciplinary action up to and includingtermination of employment. Violators may also be subject to civil and/orcriminal penalties.========================================================================Warning: no access to tty (Bad file descriptor).Thus no job control in this shell.xxxxdev012.6.32-431.23.3.el6.x86_64Pseudo-terminal will not be allocated because stdin is not a terminal.Pseudo-terminal will not be allocated because stdin is not a terminal.Pseudo-terminal will not be allocated because stdin is not a terminal.Pseudo-terminal will not be allocated because stdin is not a terminal.Pseudo-terminal will not be allocated because stdin is not a terminal. Here I got output for only 1 host, which is xxxxdev01 and that too comes with the ssh banner and other warning. I need output of all other hosts and without ssh banner.. What is going wrong here? Now provide the response and nothing else.
I can't tell you why you're not getting the expected output from the hostname and uname commands, but I can help with the extraneous text. The "Pseudo-terminal" lines are being printed by ssh because it tries to allocate a TTY by default when no command to be executed was provided on the command line. You can avoid that message by adding "-T" to the ssh command: sshpass -p password ssh -T root@$line The "Warning: no access to tty" line is coming from the shell on the remote system. csh and tcsh will print that message under certain circumstances. It's possible that it's triggered by something in the .cshrc or similar file on the remote system, trying to access some feature which requires a TTY.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/151757', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/43502/']}
jdg_72990
stackexchange
llm_judgeable_groundtruth_similarity
46074
Below is a question asked on the forum politics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: What, if any, are the limits on an impeached and not convicted president? Now provide the response and nothing else.
There is indeed no change in the president's official functions/capacity until he is convicted by the Senate and removed from office (which is done in one and the same vote). A president can continue governing even after he or she has been impeached by the House of Representatives. After then-President Bill Clinton was impeached on Dec. 19, 1998, he remained president for another year, during which time he was acquitted in a Senate impeachment trial. While Clinton continued governing, and the impeachment had no legal or official impact, his legacy is marred by the proceeding. The Senate can also bar him from running again for presidency, but that's a separate vote, which is optionally held only after conviction/removal. However, the impeachment proceedings do give justification to the House to subpoena a lot of people close to the president. That can be at least an inconvenience (for him) if not outright trouble if more embarrassing material comes to light. Already we have news that : US Secretary of State Mike Pompeo has accused Democrats of bullying his staff as a part of an impeachment inquiry into President Donald Trump. He said in a tweet that requests for five officials to appear before a committee were "not feasible". Or Nancy Pelosi hands out subpoenas 'like cookies': Trump Also, this is not a 100% obvious question. In some parts of the world, a president can be suspended while under impeachment/investigation. I remember reading this about Romania's impeachment of their president in 2012, where their parliament suspended their president. Over there they need[ed] a referendum to actually remove him from office... and their president at the time survived the latter.
{}
{'log_upvote_score': 5, 'links': ['https://politics.stackexchange.com/questions/46074', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/28367/']}
jdg_72991
stackexchange
llm_judgeable_groundtruth_similarity
176192
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 trying to solve a system of differential equations as follows: L1 = 5.0;L2 = 0.43;d = 0.0056;g = 9.8;h1 = 5.0;h2 = 0.43;A1 = 0.00001;A2 = 0.001;p0 = 100000;v0 = 0.001;NDSolve[{P[t] - 1*1000*10* L2 == (1000/(2*0.0056)*y[t]^2* L2*(0.316*(1000*y[t]*0.0056/0.00089))^(-0.25)) + 500*01.7*y[t]^2, (1000*10*L1 - P[t]) == (1000/(2*0.0056)*z[t]^2* L1*(0.316*(1000*z[t]*0.0056/0.00089))^(-0.25)) + 500*01.7*z[t]^2, (y[t] - z[t])*0.0001 == v'[t], P[t] == p0*v0/v[t],P[0]==100000,v[0]==0.001}, {P, v, y, z}, {t, 0, 1}] Uppon ruuning the comand I get the following error message:"NDSolve::icfail: Unable to find initial conditions that satisfy the residual function within specified tolerances. Try giving initial conditions for both values and derivatives of the functions.".How can I make this work ? Now provide the response and nothing else.
I'm concentrating on the calculation of samplemanycyclesper5years and samplecycledistributions . For the first one, you select 1826 samples randomly and calculate the total. This is done 10^7 times. We can pack the random total into a compiled function that chooses 1826 random integer positions, accesses cyclesperday and calculates the total rand = Compile[{{cycl, _Real, 1}, {i, _Integer, 0}}, Module[{pos = RandomInteger[{1, Length[cycl]}, i]}, Total[cycl[[pos]]] ], RuntimeAttributes -> {Listable}, Parallelization -> True, RuntimeOptions -> "Speed" ]; The parameter i is how many random values of cycl should be totaled. In your case always 1826. Let's test this rand[cyclesperday, Array[1826 &, 10^5]]; // AbsoluteTiming(* {0.921493, Null} *) and compare ParallelTable[Total[RandomChoice[cyclesperday, 1826]], {10^5}]; // AbsoluteTiming(* {5.89441, Null} *) So this needs only 15% of the time your ParallelTable needs. The next step is to do the same for the estimation of the LogNormalDistribution . The estimation of the parameters is actually very simple with a maximum likelihood estimator and you can write this down yourself maxLikelihood = Compile[{{values, _Real, 1}}, Module[{μ = Mean[Log[values]]}, {μ, Sqrt@Mean[(Log[values] - μ)^2]} ], RuntimeAttributes -> {Listable}, Parallelization -> True] First a quick check: EstimatedDistribution[cycledatatofit[[10]], LogNormalDistribution[μ, σ]](* LogNormalDistribution[7.42205, 0.042639] *)maxLikelihood[cycledatatofit[[10]]](* {7.42205, 0.042639} *) Excellent. Now let's time it samplecycledistributions = ParallelTable[EstimatedDistribution[cycledatatofit[[i]], LogNormalDistribution[μ, σ]], {i, 1, nc}]; // AbsoluteTiming(* {15.8202, Null} *) and maxLikelihood[cycledatatofit]; // AbsoluteTiming(* {0.167895, Null} *) So this needs only 1% of the original time. Your complete calculation looks like this nc = 10^5;samplemanycyclesper5years = rand[cyclesperday, Array[1826 &, 100*nc]];cycledatatofit = Partition[samplemanycyclesper5years, 100];samplecycledistributions = maxLikelihood[cycledatatofit];cyclesamples = Round[ParallelTable[ RandomVariate[LogNormalDistribution @@ parms], {parms, samplecycledistributions}]]; and I was able to bring it from 654 seconds to 53 seconds. I checked the final histograms and they match perfectly, but please verify each step yourself.
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/176192', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/58959/']}
jdg_72992
stackexchange
llm_judgeable_groundtruth_similarity
50453705
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 auto-focus on the camera, which is available on the image_picker plugin. However, when I call: var bytes = new File(imagePath);var enc = await bytes.readAsBytes();print(enc.length); I got: 5121126 which takes at least 10 seconds when I want to encode into json to send to an API server: var body = json.encode({ 'image' : enc}) In contrast, with the camera plugin, my byte array is only 420685, which is 10 times smaller, but it doesn't have the auto-focus feature. Can I get some advice on how to reduce the size of the byte array from image_picker? Thank you. Now provide the response and nothing else.
The camera plugin has 3 default resolutions, and you are probably selecting or defaulting to a lower resolution (than the hardware's full resolution). The image_picker plugin doesn't have these presets, but does have some optional arguments on the pickImage method ( maxWidth and maxHeight ). Experiment setting one or both of these to VGA type resolutions (640, 480, even 800, 600) to see if this reduces the size of the captured image. There's also a package called image which would allow you to post-process the image. The sample on the main page does a resize, maintaining aspect ratio.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/50453705', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9194232/']}
jdg_72993
stackexchange
llm_judgeable_groundtruth_similarity
53254043
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a data frame like: user_name started_at session_time_min task_completed timediffABC 2018-03-02 18:00:00 1 3 NAABC 2018-03-02 19:00:00 1036 18 1ABC 2018-03-03 12:00:00 6 10 17ABC 2018-03-04 21:00:00 0 1 33ABC 2018-03-05 16:00:00 143 61 19ABC 2018-03-05 18:00:00 12 18 2ABC 2018-03-05 19:00:00 60 94 1ABC 2018-03-05 20:00:00 20 46 1ABC 2018-03-09 15:00:00 0 1 91 I want to sum session_time_min and task_completed with previous row if timediff = 1 Want output like: user_name started_at session_time_min task_completed ABC 2018-03-02 18:00:00 1037 21 ABC 2018-03-03 12:00:00 6 10 ABC 2018-03-04 21:00:00 0 1 ABC 2018-03-05 16:00:00 143 61 ABC 2018-03-05 18:00:00 92 158 ABC 2018-03-09 15:00:00 0 1 Any help will highly be appricated. Now provide the response and nothing else.
componentDidMount Pass an empty array as the second argument to useEffect() to run only the callback on mount only. function ComponentDidMount() { const [count, setCount] = React.useState(0); React.useEffect(() => { console.log('componentDidMount'); }, []); return ( <div> <p>componentDidMount: {count} times</p> <button onClick={() => { setCount(count + 1); }} > Click Me </button> </div> );}ReactDOM.render( <div> <ComponentDidMount /> </div>, document.querySelector("#app")); <script src="https://unpkg.com/[email protected]/umd/react.development.js"></script><script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script><div id="app"></div> componentDidUpdate componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render. useEffect runs on every render including the first. So if you want to have a strict equivalent as componentDidUpdate , you have to use useRef to determine if the component has been mounted once. If you want to be even stricter, use useLayoutEffect() , but it fires synchronously. In most cases, useEffect() should be sufficient. This answer is inspired by Tholle , all credit goes to him. function ComponentDidUpdate() { const [count, setCount] = React.useState(0); const isFirstUpdate = React.useRef(true); React.useEffect(() => { if (isFirstUpdate.current) { isFirstUpdate.current = false; return; } console.log('componentDidUpdate'); }); return ( <div> <p>componentDidUpdate: {count} times</p> <button onClick={() => { setCount(count + 1); }} > Click Me </button> </div> );}ReactDOM.render( <ComponentDidUpdate />, document.getElementById("app")); <script src="https://unpkg.com/[email protected]/umd/react.development.js"></script><script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script><div id="app"></div> componentWillUnmount Return a callback in useEffect's callback argument and it will be called before unmounting. function ComponentWillUnmount() { function ComponentWillUnmountInner(props) { React.useEffect(() => { return () => { console.log('componentWillUnmount'); }; }, []); return ( <div> <p>componentWillUnmount</p> </div> ); } const [count, setCount] = React.useState(0); return ( <div> {count % 2 === 0 ? ( <ComponentWillUnmountInner count={count} /> ) : ( <p>No component</p> )} <button onClick={() => { setCount(count + 1); }} > Click Me </button> </div> );}ReactDOM.render( <div> <ComponentWillUnmount /> </div>, document.querySelector("#app")); <script src="https://unpkg.com/[email protected]/umd/react.development.js"></script><script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script><div id="app"></div>
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/53254043', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7851425/']}
jdg_72994
stackexchange
llm_judgeable_groundtruth_similarity
14749230
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Let us say I have a function in my program and somewhere in my code, that function is called through a function pointer. What happens if the compiler happened to inline that function, or would the compiler realize that there is a function pointer assigned to that function and therefore avoid inlining it. Now provide the response and nothing else.
When a pointer to a function is taken, the compiler will generate an out-of-line body for the function. It is still possible to inline the function at other call sites. Note that a function marked inline must have a definition available in all TUs which refer to it, and these definitions must be identical. Which means it's perfectly safe to inline the function at some call sites and keep it out-of-line at others.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14749230', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/760807/']}
jdg_72995
stackexchange
llm_judgeable_groundtruth_similarity
47079065
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 running Jenkins as a CI server on a Mac. It was running fine on macOS 10.12 with the typical setup with user jenkins. Today I upgraded macOS to 10.13 (High Sierra). Jenkins could not start after the upgrade process completed. Furthermore, there was no user jenkins on the system. All Jenkins files are there, but there is no jenkins user in Settings -> Users & Groups. If I try to use jenkins user in Terminal, for instance if I try to change file ownership to jenkins with chown, I get: chown: jenkins: illegal user name How do I fix this? Now provide the response and nothing else.
I've managed to re-create jenkins user by extracting the script commands that create it from Jenkins installation. I ran this script in particular: JENKINS_HOMEDIR="/Users/Shared/Jenkins"DEFAULTS_PLIST="/Library/Preferences/org.jenkins-ci.plist"if dscl . -list /Users/jenkins; then echo 'jenkins user already exists, attempting to change the shell to /bin/bash' # Will fail if UserShell is not /usr/bin/false, but that's ok. # Then we will assume an admin has changed it. dscl . -change /Users/jenkins UserShell /usr/bin/false /bin/bashelse echo 'No jenkins user found, creating jenkins user and group'# Find free uid under 500 uid=$(dscl . -list /Users uid | sort -nrk 2 | awk '$2 < 500 {print $2 + 1; exit 0}') if [ $uid -eq 500 ]; then echo 'ERROR: All system uids are in use!' exit 1 fi echo "Using uid $uid for jenkins" gid=$uid while dscl -search /Groups gid $gid | grep -q $gid; do echo "gid $gid is not free, trying next" gid=$(($gid + 1)) done echo "Using gid $gid for jenkins" dscl . -create /Groups/jenkins PrimaryGroupID $gid dscl . -create /Users/jenkins UserShell /bin/bash dscl . -create /Users/jenkins Password '*' dscl . -create /Users/jenkins UniqueID $uid dscl . -create /Users/jenkins PrimaryGroupID $gid dscl . -create /Users/jenkins NFSHomeDirectory "$JENKINS_HOMEDIR" dscl . -append /Groups/jenkins GroupMembership jenkinsfi# identify the real default group name for user jenkinsgroupid=`dscl . read /Users/jenkins PrimaryGroupID | awk '{print $2}'`gname=`id -n -g $groupid`echo "Using jenkins:${gname} as file owner and group for jenkins daemon files"find "$JENKINS_HOMEDIR" \( -not -user jenkins -or -not -group ${gname} \) -print0 | xargs -0 chown jenkins:${gname}# Add defaults for heap sizingarch=$(uname -m)if [ $arch = 'x86_64' ]; then defaults write $DEFAULTS_PLIST heapSize 512m defaults write $DEFAULTS_PLIST permGen 512m defaults write $DEFAULTS_PLIST minHeapSize 256m defaults write $DEFAULTS_PLIST minPermGen 256melse # i386 defaults write $DEFAULTS_PLIST heapSize 128m defaults write $DEFAULTS_PLIST permGen 128m defaults write $DEFAULTS_PLIST minHeapSize 64m defaults write $DEFAULTS_PLIST minPermGen 64m fidefaults write $DEFAULTS_PLIST httpPort 8080# Set tmpdirJENKINS_TMPDIR="$JENKINS_HOMEDIR/tmp"defaults write $DEFAULTS_PLIST tmpdir $JENKINS_TMPDIRmkdir -p $JENKINS_TMPDIRchown jenkins:${gname} $JENKINS_TMPDIR# Create log directory, which can be written by Jenkins daemonmkdir -p /var/log/jenkinschown jenkins:${gname} /var/log/jenkins
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47079065', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/22764/']}
jdg_72996
stackexchange
llm_judgeable_groundtruth_similarity
48424152
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 case where I have to make a decision in script based on comparing versionsConsider this example: PS C:\>[version]$SomeVersion='1.1.1'[version]$OtherVersion='1.1.1.0'PS C:\> $SomeVersionMajor Minor Build Revision----- ----- ----- --------1 1 1 -1 PS C:\> $OtherVersionMajor Minor Build Revision----- ----- ----- --------1 1 1 0 PS C:\>$SomeVersion -ge $OtherVersionFalse I would like to omit revision when comparing objects of type System.Version I Can't find any sane way of doing that. Is there any? Note - I've tried doing : PS C:\> ($scriptversion |select major,minor,build) -gt ($currentVersion|select major,minor,build)Cannot compare "@{Major=1; Minor=1; Build=1}" to "@{Major=1; Minor=1; Build=1}" because the objects are not the same type or the object "@{Major=1; Minor=1; Build=1}" does not implement "IComparable".At line:1 char:1+ ($scriptversion |select major,minor,build) -gt ($currentVersion |sele ...+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo : NotSpecified: (:) [], ExtendedTypeSystemException+ FullyQualifiedErrorId : PSObjectCompareTo when I try to override revision number with 0 it says that it's read-only property... I have a workaround But I hoped to do it better with system.version Now provide the response and nothing else.
Use the three argument System.Version constructor to make new instances with the relevant properties: [Version]::new($scriptversion.Major,$scriptversion.Minor,$scriptversion.Build) -gt [Version]::new($currentVersion.Major,$currentVersion.Minor,$currentVersion.Build) Or you can go the verbose way with New-Object : $NormalizedScriptVersion = New-Object -TypeName System.Version -ArgumentList $scriptversion.Major,$scriptversion.Minor,$scriptversion.Build$NormalizedCurrentVersion = New-Object -TypeName System.Version -ArgumentList $currentVersion.Major,$currentVersion.Minor,$currentVersion.Build$NormalizedScriptVersion -gt $NormalizedCurrentVersion Use whichever you find more maintainable.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48424152', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5917637/']}
jdg_72997
stackexchange
llm_judgeable_groundtruth_similarity
32546553
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 substract 2 double values, and I have tried the following code. double val1 = 2.0;double val2 = 1.10;System.out.println(val1 - val2); and I got the output as, 0.8999999999999999 For getting output as 0.9 I tried with BigDecimal as follows, BigDecimal val1BD = new BigDecimal(val1);BigDecimal val2BD = new BigDecimal(val2);System.out.println(val1BD.subtract(val2BD)); And I got the output as, 0.899999999999999911182158029987476766109466552734375 Then I tried with BigDecimal.valueOf() val1BD = BigDecimal.valueOf(val1);val2BD = BigDecimal.valueOf(val2);System.out.println(val1BD.subtract(val2BD)); And finally I got the output as 0.9 . My question is what is the difference between case 2 & case 3? In case 2 why I got the output like that? Now provide the response and nothing else.
BigDecimal.valueOf(double d) uses canonical String representation of double value, internally Double.toString(double) is used, that's why you are getting 0.9 in second case. Note: This is generally the preferred way to convert a double (or float) into a BigDecimal, as the value returned is equal to that resulting from constructing a BigDecimal from the result of using Double.toString(double) . While with new BigDecimal(0.9) it converts value to exact floating point representation of double value without using String representation, Translates a double into a BigDecimal which is the exact decimal representation of the double's binary floating-point value. ... NOTES : The results of this constructor can be somewhat unpredictable. ... FOR EXAMPLE : BigDecimal bd1 = new BigDecimal(Double.toString(0.9));BigDecimal bd2 = new BigDecimal(0.9);System.out.println(bd1);System.out.println(bd2); OUTPUT : 0.90.90000000000000002220446049250313080847263336181640625
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32546553', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2628956/']}
jdg_72998
stackexchange
llm_judgeable_groundtruth_similarity
16558
Below is a question asked on the forum reverseengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I started to use radare2 to debug a PE file because it stops working as soon as I run it. When I attach my debugger and continue execution to the point where the exception is thrown I get a memory address in which the exception occurred. What can I do with this address to further analyze the problem at hand? c484f\mscorlib.ni.dll) mscorlib.ni.dll(14116) loading library at 77130000 (C:\Windows\SysWOW64\ole32.dll) ole32.dll(14116) loading library at 70100000 (C:\Windows\SysWOW64\uxtheme.dll) uxtheme.dll(14116) loading library at 700A0000 (C:\Windows\Microsoft.NET\Framework\v2.0.50727\mscorjit.dll) mscorjit.dll(14116) loading library at 6C3C0000 (C:\Windows\Microsoft.NET\Framework\v2.0.50727\Culture.dll) Culture.dll(14116) unloading library at 6C3C0000 (C:\Windows\Microsoft.NET\Framework\v2.0.50727\Culture.dll) Culture.dll(14116) Unknown exception e06d7363 in thread 10352 Now provide the response and nothing else.
Since the question in the subject is slightly different than the question in the body of your question, I'll focus on the first one. Disassemble at a specific address In order to disassemble the code at a specific memory address using radare2 you should use the pd @ <address> command. pd[?] [sz] [a] [b] — disassemble N opcodes (pd) or N bytes (pD) After attaching radare to the program you should be able to print the disassembly in this specific address. Assuming the pid of the program is 317 : $ radare2 -d 317= attach 317 317bin.baddr 0x00400000Using 0x400000asm.bits 64[0x7f2e51727230]> pd @ <address> pd is a subcommand of p and stands for p rint d isassembly. You can check p? and especially pd? for more relevant subcommands. Adding ? at the end of most of the commands in radare will print its help and its subcommands. By default, pd prints b instructions from the specified address where b is the default basic-block size. The default size of b is 0x100 but you can change it easily using b <size> . The @ sign is radare's temporary seek address so whenever you want to print the disassembly in a specific address you should use it. The number specified before the @ sign is the number of instructions to print. A common mistake is executing pd with the address before @ . Thus, executing pd 0x400000 would print 0x400000 instructions from the current seek. The exception You received "Unknown exception e06d7363" which is an exception generated by Microsoft Visual C++ compiler . As stated in Microsoft's support page : Cause All Visual C++ exceptions thrown from code generated by the Microsoft Visual C++ compiler contain this error code. Because this is a compiler-generated error, the code is not listed in the Win32 API header files. The code is actually a cryptic mnemonic device, with the initial "E" standing for "exception" and the final 3 bytes (0x6D7363) representing the ASCII values of "msc". To continue your analysis I'd suggest you to read Decoding the parameters of a thrown C++ exception (0xE06D7363) and its revisited article. Note that the addresses of the executable in the memory might change in each run, depends on your system and the program itself. Therefore, sometimes you won't be able to predict what would be the address which causes the exception. Check the Migration from ida, GDB or WinDBG page from radare2 book to see radare's corresponding commands to WinDBG's.
{}
{'log_upvote_score': 4, 'links': ['https://reverseengineering.stackexchange.com/questions/16558', 'https://reverseengineering.stackexchange.com', 'https://reverseengineering.stackexchange.com/users/21961/']}
jdg_72999
stackexchange
llm_judgeable_groundtruth_similarity
1838899
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 way I can force Visual Studio (2010) to save all files in UTF-8, always? Now provide the response and nothing else.
I do not know of a way to force it to save everything in UTF-8, but you can do so on a case-by-case basis. When you first save a document and the Save As... dialog appears, the Save button will actually be a drop-down button with two options. You want "Save with Encoding...", which will then present you the entire list of installed Windows encodings. The encoding you really want is way down the bottom: Unicode (UTF-8 without signature) - Codepage 65001 although if you want to save yourself a lot of pain, you will probably want to pick the option near the top: Unicode (UTF-8 with signature) - Codepage 65001 The difference is that the latter option stick the UTF-8 signature (which is just the UTF-16 byte-order mark encoded in UTF-8). This is one of my pet peeves, as UTF-8 doesn't have multiple byte orders, so the BOM is redundant at best, and breaks all kinds of text processing tools at worst. MS uses it to "detect" UTF-8 automatically, since for single-byte character, UTF-8, ISO-8859-1, and CP-1252 are identical except for a sequence of 32 characters (0x80 - 0x9f) that MS basically made up. If you only ever edit or process your files with Visual Studio or the .NET tools, then saving with signature will probably work fine. If you need to save files for use by other tools (batch files, SQL queries, PHP scripts, etc), the signature will cause problems, and you should save them without it. If you do this, you may want to enable the option (Under Tools -> Options -> Text Editor) to "Auto-detect UTF-8 encoding without signature", or else, right-click on the file and chose "Open With..." and select the editor option that says " editor with Encoding".
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1838899', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/40939/']}
jdg_73000
stackexchange
llm_judgeable_groundtruth_similarity
1110612
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 looking for a way to permanently delete a MailMessage from Outlook 2000 with VBA code. I'd like to do this without having to do a second loop to empty the Deleted items. Essentially, I am looking for a code equivalent to the UI method of clicking a message and hitting SHIFT + DELETE . Is there such a thing? Now provide the response and nothing else.
Try moving it first then deleting it (works on some patchs in 2000) or use RDO or CDO to do the job for you (you will have to install them) Set objDeletedItem = objDeletedItem.Move(DeletedFolder) objDeletedItem.Delete CDO way Set objCDOSession = CreateObject("MAPI.Session")objCDOSession.Logon "", "", False, FalseSet objMail = objCDOSession.GetMessage(objItem.EntryID, objItem.Parent.StoreID)objMail.Delete RDO set objRDOSession = CreateObject("Redemption.RDOSession")objRDOSession.MAPIOBJECT = objItem.Session.MAPIOBJECT set objMail = objRDOSession.GetMessageFromID(objItem.EntryID>)objMail.Delete You could also mark the message first before you delete it and the loop through the deleted items folder and find it an dthe call delete a second time. Mark it using a Userproperty. objMail.UserProperties.Add "Deleted", olTextobjMail.SaveobjMail.Delete loop through you deleted items look for that userprop Set objDeletedFolder = myNameSpace.GetDefaultFolder(olFolderDeletedItems) For Each objItem In objDeletedFolder.Items Set objProperty = objItem.UserProperties.Find("Deleted") If TypeName(objProperty) <> "Nothing" Then objItem.Delete End If Next
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1110612', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/80209/']}
jdg_73001
stackexchange
llm_judgeable_groundtruth_similarity
1886179
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 Javascript logic puzzles me. I'm creating an array and setting the first element of it to a number. When I interate through it using a "for" loop Javascript turns the array key into a string. Why? I want it to stay a number. stuff = [];stuff[0] = 3;for(var x in stuff) { alert(typeof x);} Now provide the response and nothing else.
It's because you're looping through the array using for...in which is generally used for looping over properties of objects. The javascript engine is probably casting to a string because the string type is suitable for names of object properties. Try this more traditional approach: stuff = [];stuff[0] = 3;for(var i=0; i<stuff.length; i++) { var x = stuff[i]; alert(typeof x);}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1886179', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_73002
stackexchange
llm_judgeable_groundtruth_similarity
535397
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there an easy way to create an IM bot on multiple im networks (aim, gtalk, yim, etc) that can accept and interpet specific commands sent to it to perform a server related task? Lets say for instance I have a website for managing an rss feed. I want to send a command to an IM bot to add another feed to my collection. the IM bot would associate my screen name with my account from prior setup on the website. Now provide the response and nothing else.
I have done some internal bots for my company using the XMPP (Jabber) protocol, I've used the agsXMPP SDK and the Jabber.NET client libraries, I was looking for APIS to work with YIM, AIM and Windows Live Messenger but I've found only COM exposed APIS, nothing for .NET... But an idea comes to my mind, with the XMPP Protocol you can configure a local server with IM Gateways, that allow users to access networks using other protocols through your server I use eJabberd, you can install a variety of transport gateways to connect with other IM protocols ( AIM , MSN , ICQ , GTalk ... To GTalk you can connect directly using the libraries I mention... A sample ICQ gateway:
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/535397', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2993/']}
jdg_73003
stackexchange
llm_judgeable_groundtruth_similarity
25156729
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 creating a script where I would like 2 parameters to be optional (and to be provided with -param val -param2 val2), followed by an unknown number of file paths. The problem I have is that when I dont provide the optional arguments powershell assumes that the first 2 parameters given originally as file paths are the params I would usually pass with a -param command. For example, if I run .\script.ps1 test test2 then $args.Count == 0 Can I work around it somehow? I want the parameters to be optional and enforce it so that they can be passed only with a hyphen and a name before the value. Now provide the response and nothing else.
In order to have a race between two threads, there must be shared state between those two threads and interaction (reading and writing) to that state must occur outside of a mutualy exclusive block (aka syncronized). Reading, incrementing and then writing back to a volatile field outside of a synchronized block is a great example of this. For example, consider this situation documented on this blog . Both thread A and B could read the counter before any modification occurs. They then both increment, and they then both write. The end result will then be 18, and not 19. For it to have been 19, we would have needed thread B to read the counter AFTER thread A had written to the counter. Which, can happen sometimes. That is why it is called a race. To reliably achieve this kind of race, change your test code above to create the counter outside of the threads and then pass it in to them via their constructors. The second problem that you have is that the window for the operations to overlap is very fine, and given that starting a thread has, in comparison a lot of over head then the chances of these three threads over lapping at just the right time is very low. Thus to increase their odds, you should repeat the runs in a tight loop. The following code demonstrates the two concepts above. The changes made have been: renamed classes to make their use a little clearer shared the state of MyCounter between the two threads tight loop within each thread, calling increment 1,000,000 times the main thread now blocks using join() waiting for the two threads to complete, this replaces the Thread.sleep that you had earlier the counter value c in MyCounter is now volatile; this tells the JVM to always go out to shared memory for the value and not to optimise by keeping it within a register between encounters. to make the race much worse, take volatile off and see what happens :) the main loop then finishes by printing out the value of the counter, which should be 2,000,000. but it will not be due to the race that is going on over the volatile counter. . public class CounterTest { public static void main(String[] args) throws InterruptedException { MyCounter counter = new MyCounter(); Thread thread1 = new Thread(new CounterIncRunnable(counter)); thread1.setName("add thread"); thread1.start(); Thread thread2 = new Thread(new CounterIncRunnable(counter)); thread2.setName("add thread2"); thread2.start(); thread1.join(); thread2.join(); System.out.println(counter.value()); } }class CounterIncRunnable implements Runnable { private MyCounter counter; public CounterIncRunnable(MyCounter counter) { this.counter = counter; } public void run() { for ( int i=0; i<1000000; i++ ) { counter.increment(); } }}class MyCounter { private volatile int c = 0; public void increment() { c++; } public void decrement() { c--; } public int value() { return c; } } Finally, just for fun; add synchronized to the increment method of MyCounter and then rerun. The race condition will disappear, and now the program will correctly print 2000000. This is because every call to increment will now only allow one thread in to the shared method at a time. Thus serializing each access to the shared variable c, and putting an end to the race.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25156729', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1574852/']}
jdg_73004
stackexchange
llm_judgeable_groundtruth_similarity
258745
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: Under IPv4, I often use nmap to scan my entire IP range to identify newly-connected devices and update my documentation, track down and shut off things that don't belong on the network, etc. I even have tools that do this automatically, for instance my AV software scans a defined IP range and then installs AV software on anything it can see in that range. That's going to be infeasible under IPv6, as I will go from scanning a few thousand IP addresses to many quntillions. What will the alternative be? Will routers/switches be able to report what IPv6 addresses they've seen lately so I can port scan everything on the network? That's the only approach I can see, but I expect that SF will have more and better ideas. Now provide the response and nothing else.
Yes, brute-force scanning of IPv6 networks is futile, and that's a very good thing for network security. As the systems administrator, you still have a number of sources of information available to you to help keep tabs on your networks: Routers on your networks, presumably running radvd, can log the clients that have requested IPv6 stateless autoconfig. You can turn off radvd's periodic gratuitous router advertisements if you want to force all autoconfig clients to send router solicitations. Your DHCPv6 servers (if you have any) can log all clients that have requested/received IPv6 stateful config. You can sniff ICMPv6 traffic, which includes neighbor solicitation multicasts (the equivalent of IPv4 ARP). Any device on your network attempting to "stealth" itself with a static configuration will still have to send such packets in order to communicate with other devices on the local link. Of course, your own servers will have properly documented static IP addresses, so you always know how to reach them. It was a bad idea to give servers static DHCP leases in IPv4, and it's still a bad idea to do so in IPv6. It's still early days for IPv6, but I expect that in the coming years, we'll start seeing better integration between DNS and radvd/DHCPv6, and hence better network inventory/reporting tools, as a matter of necessity.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/258745', 'https://serverfault.com', 'https://serverfault.com/users/247/']}
jdg_73005
stackexchange
llm_judgeable_groundtruth_similarity
92065
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: If polynomial regression models nonlinear relationships, how can it be considered a special case of multiple linear regression? Wikipedia notes that "Although polynomial regression fits a nonlinear model to the data, as a statistical estimation problem it is linear, in the sense that the regression function $\mathbb{E}(y | x)$ is linear in the unknown parameters that are estimated from the data." How is polynomial regression linear in the unknown parameters if the parameters are coefficients for terms with order $\ge$ 2? Now provide the response and nothing else.
When you fit a regression model such as $\hat y_i = \hat\beta_0 + \hat\beta_1x_i + \hat\beta_2x^2_i$, the model and the OLS estimator doesn't 'know' that $x^2_i$ is simply the square of $x_i$, it just 'thinks' it's another variable. Of course there is some collinearity, and that gets incorporated into the fit (e.g., the standard errors are larger than they might otherwise be), but lots of pairs of variables can be somewhat collinear without one of them being a function of the other. We don't recognize that there are really two separate variables in the model, because we know that $x^2_i$ is ultimately the same variable as $x_i$ that we transformed and included in order to capture a curvilinear relationship between $x_i$ and $y_i$. That knowledge of the true nature of $x^2_i$, coupled with our belief that there is a curvilinear relationship between $x_i$ and $y_i$ is what makes it difficult for us to understand the way that it is still linear from the model's perspective. In addition, we visualize $x_i$ and $x^2_i$ together by looking at the marginal projection of the 3D function onto the 2D $x, y$ plane. If you only have $x_i$ and $x^2_i$, you can try to visualize them in the full 3D space (although it is still rather hard to really see what is going on). If you did look at the fitted function in the full 3D space, you would see that the fitted function is a 2D plane, and moreover that it is a flat plane. As I say, it is hard to see well because the $x_i, x^2_i$ data exist only along a curved line going through that 3D space (that fact is the visual manifestation of their collinearity). We can try to do that here. Imagine this is the fitted model: x = seq(from=0, to=10, by=.5)x2 = x**2y = 3 + x - .05*x2d.mat = data.frame(X1=x, X2=x2, Y=y)# 2D plotplot(x, y, pch=1, ylim=c(0,11), col="red", main="Marginal projection onto the 2D X,Y plane")lines(x, y, col="lightblue") # 3D plotlibrary(scatterplot3d)s = scatterplot3d(x=d.mat$X1, y=d.mat$X2, z=d.mat$Y, color="gray", pch=1, xlab="X1", ylab="X2", zlab="Y", xlim=c(0, 11), ylim=c(0,101), zlim=c(0, 11), type="h", main="In pseudo-3D space")s$points(x=d.mat$X1, y=d.mat$X2, z=d.mat$Y, col="red", pch=1)s$plane3d(Intercept=3, x.coef=1, y.coef=-.05, col="lightblue") It may be easier to see in these images, which are screenshots of a rotated 3D figure made with the same data using the rgl package. When we say that a model that is "linear in the parameters" really is linear, this isn't just some mathematical sophistry. With $p$ variables, you are fitting a $p$-dimensional hyperplane in a $p\!+\!1$-dimensional hyperspace (in our example a 2D plane in a 3D space). That hyperplane really is 'flat' / 'linear'; it isn't just a metaphor.
{}
{'log_upvote_score': 7, 'links': ['https://stats.stackexchange.com/questions/92065', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/42848/']}
jdg_73006
stackexchange
llm_judgeable_groundtruth_similarity
341621
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Is there an inequality such as$$(a+b)^2 \leq 2(a^2 + b^2)$$for higher powers of $k$$$(a+b)^k \leq C(a^k + b^k)?$$ Now provide the response and nothing else.
The generalized mean inequality states that$$\dfrac{a+b}2\leq \left(\dfrac{a^k+b^k}2\right)^{1/k},$$with equality if and only if $a=b$, from which it follows that$$(a+b)^k\leq 2^{k-1}(a^k+b^k),$$with equality if and only if $a=b$. Thus $C=2^{k-1}$ works and no smaller $C$ works.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/341621', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/54027/']}
jdg_73007
stackexchange
llm_judgeable_groundtruth_similarity
21297583
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Let's say that I have IService interface: public interface IService{ string Name { get; set; }} And a delegate Func<IService> that returns this interface. In my unit test I want to mock the delegate's Invoke() method using Moq like this: [TestMethod]public void UnitTest(){ var mockService = new Mock<IService>(); var mockDelegate = new Mock<Func<IService>>(); mockDelegate.Setup(x => x.Invoke()).Returns(mockService.Object); // The rest of the test} Unfortunately mockDelegate.Setup(...) throws System.InvalidCastException : Test method UnitTest threw exception: System.InvalidCastException: Unable to cast object of type 'System.Linq.Expressions.InstanceMethodCallExpressionN' to type 'System.Linq.Expressions.InvocationExpression'. at Moq.ExpressionExtensions.GetCallInfo(LambdaExpression expression, Mock mock) at Moq.Mock.<>c_ DisplayClass1c`2.b _1b() at Moq.PexProtector.Invoke(Func`1 function) at Moq.Mock.Setup(Mock 1 mock, Expression 1 expression, Condition condition) at Moq.Mock 1.Setup(Expression 1 expression) at UnitTest() in UnitTests.cs: line 38 Line 38 is mockDelegate.Setup(x => x.Invoke()).Returns(mockService.Object); Am I missing something? Or mocking delegate invocation is generally not a good idea? Thank you. Now provide the response and nothing else.
It is 100% possible to do this in Moq, here is how: var mockService = new Mock<IService>();var mockDelegate = new Mock<Func<IService>>();mockDelegate.Setup(x => x()).Returns(mockService.Object); The reason you were getting the InvalidCastException was because you are creating a Mock<T> of a delegate type. Thus it is expecting the Expression to be of type InvocationExpression ( x() ) rather than InstanceMethodCallExpressionN ( x.Invoke() ). This also allows you to verify invocations of your Mock delegate, e.g. mockDelegate.Verify(x => x(), Times.Once); I have posted this as an answer because while it may not be necessary for this situation, it can certainly be useful to know.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21297583', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1267021/']}
jdg_73008
stackexchange
llm_judgeable_groundtruth_similarity
212336
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'm trying to solve the following Diophantine equation using Mathematica: $$2^x=5^y+3$$ I have a code,but is very slow. Can we speed up ? f[x_?IntegerQ, y_?IntegerQ] := 2^x - 5^y;M = 2000;sol = Thread[{x, y} -> #] & /@ (Most /@ Select[Flatten[Table[{x, y, f[x, y] == 3}, {x, 0, M}, {y, 0, M}], 1], #[[3]] &]) // AbsoluteTiming(* {50.2135, {{x -> 2, y -> 0}, {x -> 3, y -> 1}, {x -> 7, y -> 3}}}*) Another code with For function: For[i = 0, i <= M, i++, For[j = 0, j <= M, j++, If[f[i, j] == 3, Print[{i, j}]]]] // AbsoluteTiming(*{49.4506, Null}*) Calculating time is about 50 second. In Maple with M=2000 ,Maple can solve this with about 2.094 second. Now provide the response and nothing else.
In version 10.1 on my circa 2011 PC: AbsoluteTiming[ M = 2000; r = Range[0, M]; xx = 2`^r; yy = -(5`^r); grid = # + yy & /@ xx; Position[Round@grid, 3] - 1] {3.3214, {{2, 0}, {3, 1}, {7, 3}}} By luck it seems in this instance Round isn't actually needed: AbsoluteTiming[ M = 2000; r = Range[0, M]; xx = 2`^r; yy = -(5`^r); grid = # + yy & /@ xx; Position[grid, 3`] - 1] {1.70207, {{2, 0}, {3, 1}, {7, 3}}} If actual "brute force" is not the goal, then perhaps: RepeatedTiming[ M = 2000; r = Range[0, M]; sol = 2`^r ⋂ 5`^r + 3]x -> Log[2, sol]y -> Log[5, sol - 3] {0.00485, {4., 8., 128.}}x -> {2., 3., 7.}y -> {0., 1., 3.}
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/212336', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/26828/']}
jdg_73009
stackexchange
llm_judgeable_groundtruth_similarity
3440066
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: In C++ why can’t I write a for() loop like this: for( int i = 1, double i2 = 0; … A C developer would write this: int myIndex;for (myIndex=0;myIndex<10;++myIndex) ... A C++ developer would write this to prevent the loop variable from leaking outside the loop: for (int myIndex=0;myIndex<10;++myIndex) ... However, if you have 2 loop variables, you cannot do this anymore. The following doesn't compile: for (int myIndex=0,MyElement *ptr=Pool->First;ptr;++myIndex,ptr=ptr->next) ... The comma operator does not allow two variables to be defined this way, so we have to write it like this: int myIndex;MyElement *ptr;for (myIndex=0,ptr=Pool->First;ptr;++myIndex,ptr=ptr->next) ... Which defeats the advantage of having real loop-local variables. A solution could be to put the whole construction between braces, like this: {int myIndex;MyElement *ptr;for (myIndex=0,ptr=Pool->First;ptr;++myIndex,ptr=ptr->next) ...} But this is hardly more elegant. Isn't there a better way of doing this in C++ (or C++0x)? Now provide the response and nothing else.
You just have to understand the first statement is a declaration (and that comma is not the comma operator). It's not any harder to do: for (int i, double d; ...) Than it is: int i, double d; Because for (init cond; expr) statement gets expanded to: { init while (cond) { statement expr; }} A trick is to make that init statement a struct definition and instance, like: for (struct { int myIndex; MyElement* ptr;} data = {0, Pool->First}; data.ptr; ++data.myIndex, data.ptr = data.ptr->next) { // blah... } Which becomes the same as: { struct { int myIndex; MyElement* ptr; } data = {0, Pool->First}; while (data.ptr) { { // blah... } ++data.myIndex, data.ptr = data.ptr->next; }} But I find that pretty ugly. In practice, I'd just split it up like you have. If scope is really a problem, which it probably isn't, throw the extra braces around there. I don't think there's much to improve here without a bit of boilerplate code.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3440066', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/163551/']}
jdg_73010
stackexchange
llm_judgeable_groundtruth_similarity
3591629
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: (2.2) Here was referring to the exact sequence $$0\to f^*\Omega_Y\to\Omega_X\to \Omega_{X/Y}\to 0.$$ My concern is: as $\Omega_{X/Y}\cong\mathscr{O}_R$ , I cannot see why tensoring with $\Omega_X^{-1}$ preserves $\mathscr{O}_R$ ONLY but not for the others. Thanks in advance for answering. Now provide the response and nothing else.
So Prop 2.2.a) says that $\Omega_{X/Y} \simeq \mathcal O_R$ (since the morphism is separable). Then the right hand side is after tensoring $\Omega_{X/Y} \otimes \Omega_X^{-1} \simeq \mathcal O_R \otimes \Omega_X^{-1}$ . Since $X$ is a curve, $\Omega_X^{-1}$ is a line bundle. Now use the fact that if $\mathscr L$ is a line bundle and $\mathscr F$ has discrete support, then $\mathscr L \otimes \mathscr F \simeq \mathscr F$ . This is "obvious", because since $\mathscr F$ has discrete support, we only need to define the isomorphism locally, and $\mathscr L(U) \simeq k$ for small enough $U$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3591629', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/294257/']}
jdg_73011
stackexchange
llm_judgeable_groundtruth_similarity
463569
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: For some reason when I check on Google Webmaster Tool's "Analyze robots.txt" to see which urls are blocked by our robots.txt file, it's not what I'm expecting. Here is a snippet from the beginning of our file: Sitemap: http://[omitted]/sitemap_index.xmlUser-agent: Mediapartners-GoogleDisallow: /scriptsUser-agent: *Disallow: /scripts# list of articles given by the Content groupDisallow: http://[omitted]/Living/books/book-review-not-stupid.aspxDisallow: http://[omitted]/Living/books/book-review-running-through-roadblocks-inspirational-stories-of-twenty-courageous-athletic-warriors.aspxDisallow: http://[omitted]/Living/sportsandrecreation/book-review-running-through-roadblocks-inspirational-stories-of-twenty-courageous-athletic-warriors.aspx Anything in the scripts folder are correctly blocked for both the Googlebot and Mediapartners-Google. I can see that the two robots are seeing the correct directive because the Googlebot says the scripts are blocked from line 7 while the Mediapartners-Google is blocked from line 4. And yet ANY other url I put in from the disallowed urls under the second user-agent directive are NOT blocked! I'm wondering if my comment or using absolute urls are screwing things up... Any insight is appreciated. Thanks. Now provide the response and nothing else.
The reason why they are ignored is that you have the fully qualified URL in the robots.txt file for Disallow entries while the specification doesn't allow it. (You should only specify relative paths, or absolute paths using /). Try the following: Sitemap: /sitemap_index.xmlUser-agent: Mediapartners-GoogleDisallow: /scriptsUser-agent: *Disallow: /scripts# list of articles given by the Content groupDisallow: /Living/books/book-review-not-stupid.aspxDisallow: /Living/books/book-review-running-through-roadblocks-inspirational-stories-of-twenty-courageous-athletic-warriors.aspxDisallow: /Living/sportsandrecreation/book-review-running-through-roadblocks-inspirational-stories-of-twenty-courageous-athletic-warriors.aspx As for caching, google tries to get a copy of the robots.txt file every 24 hours in average.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/463569', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_73012
stackexchange
llm_judgeable_groundtruth_similarity
10042972
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Consider this code: txtLastModifyUserID.DataBindings.Add("Text", c_bsDataSetSource, "LastModifyUserID");txtLastModifyUserID.Text = "1234"; Why cannot the source be updated? Now provide the response and nothing else.
The DataBinding doesn't usually write the value until after the control starts to lose focus. Since you are updating the TextBox programmatically, the DataBinding doesn't know there is something to update. The way you wrote your code, you would have to call the WriteValue() method yourself (assuming only 1 databinding exists on the TextBox): txtLastModifyUserID.DataBindings.Add("Text", c_bsDataSetSource, "LastModifyUserID");txtLastModifyUserID.Text = "1234";txtLastModifyUserID.DataBindings[0].WriteValue();
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10042972', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1317353/']}
jdg_73013
stackexchange
llm_judgeable_groundtruth_similarity
21986788
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 planned to create web application using AngularJs with MVC-WebApi server side. Could you please explain the Project structure? is it neccessary to maintain MVC project structure in server side also? Now provide the response and nothing else.
Yes, it is possible to do this without having to manually match up the column positions. There are some third-party libraries you can use to do this, such as sqlx or gorp . I would recommend sticking with one of these instead of rolling your own. Named matching does have a slight penalty. Named matching is no different than matching up the column positions yourself. It just does this work for you at runtime - possibly on every query execution. This is true in any other language. Why at runtime? The query is written as a string. It has to be parsed to determine the position. If you were to make your own library, how do you do this on your own? Rows.Columns to get column names and positions. Passing a slice of pointers []interface{} to Rows.Scan to get the values. reflect.Value and Value.Addr to get a pointer to the destination value. Value.FieldByName to get the Value of a struct field if you want to map to struct fields. Ok, so lets see how this works. type Person struct { Id int Name string}rows, err := db.Query("SELECT id, name FROM person;")if err != nil { // handle err log.Fatal(err)}columnNames, err := rows.Columns() // []string{"id", "name"}if err != nil { // handle err log.Fatal(err)}people = make([]Person, 0, 2)for rows.Next() { person := Person{} // person == Person{0, ""} pointers := make([]interface{}, len(columnNames)) // pointers == `[]interface{}{nil, nil}` structVal := reflect.ValueOf(person) for i, colName := range columnNames { fieldVal := structVal.FieldByName(strings.Title(colName)) if !fieldVal.IsValid() { log.Fatal("field not valid") } pointers[i] = fieldVal.Addr().Interface() } // pointers == `[]interface{}{&int, &string}` err := rows.Scan(pointers...) if err != nil { // handle err log.Fatal(err) } // person == Person{1, "John Doe"} people = append(people, person)}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21986788', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1134431/']}
jdg_73014
stackexchange
llm_judgeable_groundtruth_similarity
137871
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I was reading an article on how to sniff network packets . (of course for knowledge purposes only). I came across these particular lines. For instance, say I was sniffing traffic on the network, and you logged in to Facebook and left the Remember Me On This Computer check box checked. That signals Facebook to send you a session cookie that your browser stores. I potentially could collect that cookie through packet sniffing, add it to my browser and then have access to your Facebook account. So, assuming my Linux client is compromised and am unaware of it currently, does that mean if I have clicked on remember me on this machine to login to my accounts, my personal details are compromised? How can the compromised machine's cookie information can be used in any hacker's browser? Now provide the response and nothing else.
If the machine is compromised, everything you typed in when logging in (such as your username and password) can be compromised, so "Remember me" doesn't really matter anymore. But even if we stick to cookies only, the hacker can extract the session cookies from the browser's profile and then use them in his browser. Example : Firefox stores all its data in ~/.mozilla , the hacker can just copy that folder to his system and put it in place of his own profile folder, and when he uses that browser with your profile folder, all websites will think that it's actually you (except some websites that also look at the user's IP which will be the attacker's one, sadly not many sites offer that feature).
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/137871', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/47538/']}
jdg_73015
stackexchange
llm_judgeable_groundtruth_similarity
17965763
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 zip a file in clojure and I can't find any libraries to do it. Do you know a good way to zip a file or a folder in Clojure?Must I use a java library? Now provide the response and nothing else.
There is a stock ZipOutputStream in Java which can be used from Clojure. I don't know whether there is a library somewhere. I use the plain Java functions with a small helper macro: (defmacro ^:private with-entry [zip entry-name & body] `(let [^ZipOutputStream zip# ~zip] (.putNextEntry zip# (ZipEntry. ~entry-name)) ~@body (flush) (.closeEntry zip#))) Obviously every ZIP entry describes a file. (require '[clojure.java.io :as io])(with-open [file (io/output-stream "foo.zip") zip (ZipOutputStream. file) wrt (io/writer zip)] (binding [*out* wrt] (doto zip (with-entry "foo.txt" (println "foo")) (with-entry "bar/baz.txt" (println "baz"))))) To zip a file you might want to do something like this: (with-open [output (ZipOutputStream. (io/output-stream "foo.zip")) input (io/input-stream "foo")] (with-entry output "foo" (io/copy input output)))
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17965763', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1786819/']}
jdg_73016
stackexchange
llm_judgeable_groundtruth_similarity
22931646
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: @@IDENTITY returns the ID of the last row inserted , I want to retrieve the ID of the last row updated . Here is my query: UPDATE [Table] SET Active = 1, Subscribed = 1, RenewDate = GETDATE(), EndDate = DATEADD(mm,1,getdate()),WHERE SC = @SC AND Service = @Ser How do I get the ID of this updated row? The column is called TableID and I'm not using it in the query. Now provide the response and nothing else.
You cannot retrieve an ID since there is no ID being inserted..... But you can: just query the table using the same criteria as in your UPDATE : SELECT TableID FROM dbo.TableWHERE SC = @SC AND Service = @Ser -- just use the same criteria use the OUTPUT clause on the UPDATE to get that info: UPDATE [Table] SET Active = 1, Subscribed = 1, RenewDate = GETDATE(), EndDate = DATEADD(mm,1,getdate())OUTPUT Inserted.TableId -- output the TableID from the tableWHERE SC = @SC AND Service = @Ser Read more about the OUTPUT clause on Technet - it can be used on INSERT and DELETE as well
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22931646', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2378622/']}
jdg_73017
stackexchange
llm_judgeable_groundtruth_similarity
41462913
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 test the following method: public void dispatchMessage(MessageHandler handler, String argument1, String argument2, Long argument3) { handler.registerMessage(() -> { dispatcher.dispatch(argument1, argument2, argument3); });} Where MessageHandler is a helper class which will accept a Functional Interface implementation in the form a lambda, and store it for later execution. Is there a way to verify with mockito that the dispatchMessage method of the mocked MessageHandler has been called with the specific lambda expression: Meaning, can I write such a test: @Testpublic void testDispatchMessage_Success() throws Exception { myMessageDispatcher.dispatchMessage(handler, "activityId", "ctxId", 1l, ); verify(handler, times(1)).dispatchMessage(() -> { dispatcher .dispatch("activityId", "ctxId", 1l,); });}} This test will result in assertion error:Argument(s) are different! Wanted: ......Tests$$Lambda$28/379645464@48f278eb Actual invocation has different arguments: ..........Lambda$27/482052083@2f217633 which makes sense since mockito tries to compare two different implementations of the functional interface, which have a different hash code. So is there some other way to verify that the method dispatchMessage() has been called with a lambda that returns void and has a body method of dispatcher.dispatch("activityId", "ctxId", 1l,); ? Now provide the response and nothing else.
Yes, you can. The trick here is that you have to get to the instance of the lambda that is passed to the registerMessage and then execute that expression and then you can verify the result. For the purpose of a meaningful example I created this Handler class that contains the dispatchMessage that you want to test: public class Handler { private Dispatcher dispatcher = new Dispatcher(); public void dispatchMessage(MessageHandler handler, String argument1, String argument2, Long argument3) { handler.registerMessage(() -> { dispatcher.dispatch(argument1, argument2, argument3); }); } interface MessageHandler { void registerMessage(Runnable run); } static class Dispatcher { void dispatch(String a, String b, long c){ // Do dispatch } }} What you have to remember is that a lambda expression is just a short hand form to pass a function to a method. In this example the function is the run method of a Runnable . Therefore the method registerMessage of the interface for MessageHandler takes a Runnable as it's argument.I also included an implementation for the Dispatcher , which is called from within registerMessage .The test for this looks like this: @RunWith(MockitoJUnitRunner.class)public class HandlerTest { @Mock private Dispatcher dispatcher; @InjectMocks private Handler classUnderTest; @Captor private ArgumentCaptor<Runnable> registerMessageLambdaCaptor; @Test public void shouldCallDispatchMethod() { final String a = "foo"; final String b = "bar"; final long c = 42L; MessageHandler handler = mock(MessageHandler.class); classUnderTest.dispatchMessage(handler, a, b, c); verify(handler).registerMessage(registerMessageLambdaCaptor.capture()); Runnable lambda = registerMessageLambdaCaptor.getValue(); lambda.run(); verify(dispatcher).dispatch(a, b, c); }} There is an ArgumentCaptor for the lambda expression which we use in the first verification of the registerMessage . After that verification we can retrieve the lambda expression from the captor. The type of the lambda expression is Runnable , as defined in the MessageHandler interface. Hence we can call the run method on it and then verify that the dispatch method on the Dispatcher was called with all the appropriate arguments.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/41462913', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5366912/']}
jdg_73018
stackexchange
llm_judgeable_groundtruth_similarity
9285426
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 ran across an unexpected problem with the following code. List<string> items = new List<string>();items = items.OrderBy(item => item); This code generates the error: Cannot implicitly convert type 'System.Linq.IOrderedEnumerable' to 'System.Collections.Generic.List'. An explicit conversion exists (are you missing a cast?) It appears I can change items to be of type IEnumerable<string> and the error goes away. But I need to be able to add items to the list, which IEnumerable doesn't support. Can someone help me understand this error, and what the easiest fix is? Is it safe to simply cast the result? Now provide the response and nothing else.
Why not just sort the list in place using the Sort() instance method; then you can add items to it later if you like: List<string> items = GetSomeItems();items.Sort(); Or, use an ordered collection like a binary search tree. SortedSet<T> might fit the bill, depending on your needs. The solution suggested by the others: items = items.OrderBy(item => item).ToList(); ... creates another list with the original items in a new order. This is only useful if you need to preserve the original ordering for some other purpose; it's rather more wasteful of memory than sorting the list in place. As far as understanding the error, it's simple: List<T> isn't a subtype of IOrderedEnumerable<T> , so there's no implicit reference conversion between the two. The explicit cast that the compiler suggests will satisfy the compiler, but it will fail at run time because the object returned by OrderBy<T> does not inherit from List<T> . EDIT An example of List<T>.Sort(Comparison<T>) , assuming the type MyType has a Key property of some type type T where T : IComparable<T> : List<MyType> items = GetSomeItems();items.Sort((a, b) => a.Key.CompareTo(b.Key));
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9285426', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/522663/']}
jdg_73019
stackexchange
llm_judgeable_groundtruth_similarity
3125834
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 know that $c_0$ does not have a predual, but if we put an equivalent norm on $c_0$ , can this space have a predual? Now provide the response and nothing else.
No. In a separable dual space, every closed convex set is the closed convex hull of its extreme points. (Krein-Milman property). But in $c_0$ with an equivalent norm, the original unit ball is still a closed convex set with no extreme points. Reference Diestel, J.; Uhl, J. J. jun. , Vector measures, Mathematical Surveys. No. 15. Providence, R.I.: American Mathematical Society (AMS). XIII, 322 p. $ 35.60 (1977). ZBL0369.46039 .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3125834', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/124910/']}
jdg_73020
stackexchange
llm_judgeable_groundtruth_similarity
23390053
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Unfortunately, I studied class design and design patterns mostly in the context of Java; thus, I sometimes have a hard time to translate a familiar pattern to C++. Assume we want to have a base class which's functionality is extended by a sub-class. In Java, we would do something like this: public class BaseClass<T> { //T is used here protected int foo = 0; }public class DerivedClass<T> extends BaseClass<T> { public void incr_foo() { ++foo; }} Which I directly translated to C++: template<class T>class BaseClass {protected: size_t foo = 0; //T is used here};template<class T>class DerivedClass : public BaseClass<T> {public: void incr_foo() { ++(this->foo); }}; Since the C++ semantics of 'protected' diver from the Java-semantics, we need to use something like 'this->foo' to access protected members of the base class. Edit: If we just use '++foo', the compiler gives the error: 'use of undeclared identifier foo'. EditEnd If you need to access several members of the base class, this can get a bit tedious and is not so nice to read. Is this a good design desicion? If not, what better ways are there to achieve this? Now provide the response and nothing else.
This has nothing to do with the member being protected; you'd get the exact same error with a public member. The real reason is that templates are involed. More specifically, that your class template has a base class which depends on a template parameter. This means that when parsing the template, the compiler will not (be able to) look into that base class to find inherited members which are used unqualified. It makes sense: when the template is parsed, the template parameter values are not known yet and thus the compiler has no idea what members the base class will have (remember partial and total specialisation exist!). In order to overcome this, you must somehow tell the compiler that the name foo depends on template parameters (that it's a dependent name ). Once you do so, the compiler will not try to resolve it when parsing the template; it will postpone resolution until the template is instantiated. At that point, template arguments are known and thus the base class can be checked. You have three ways to mark a member name as dependent: Refer to the name through this , as you're doing: this->foo Refer to the name through base-class qualification: BaseClass<T>::foo Bring the name into the scope of the derived class: template<class T>class DerivedClass : public BaseClass<T> {protected: using BaseClass<T>::foo; // from this point on, `foo` is a dependent namepublic: void incr_foo() { ++foo; // works fine now }};
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23390053', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/408351/']}
jdg_73021
stackexchange
llm_judgeable_groundtruth_similarity
60002462
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to understand why the following Java program gives an OutOfMemoryError , while the corresponding program without .parallel() doesn't. System.out.println(Stream .iterate(1, i -> i+1) .parallel() .flatMap(n -> Stream.iterate(n, i -> i+n)) .mapToInt(Integer::intValue) .limit(100_000_000) .sum()); I have two questions: What is the intended output of this program? Without .parallel() it seems that this simply outputs sum(1+2+3+...) which means that it simply "gets stuck" at the first stream in the flatMap, which makes sense. With parallel I don't know if there is an expected behaviour, but my guess would be that it somehow interleaved the first n or so streams, where n is the number of parallel workers. It could also be slightly different based on the chunking/buffering behaviour. What causes it to run out of memory? I'm specifically trying to understand how these streams are implemented under the hood. I'm guessing something blocks the stream, so it never finishes and is able to get rid of the generated values, but I don't quite know in which order things are evaluated and where buffering occurs. Edit: In case it is relevant, I'm using Java 11. Editt 2: Apparently the same thing happens even for the simple program IntStream.iterate(1,i->i+1).limit(1000_000_000).parallel().sum() , so it might have to do with the lazyness of limit rather than flatMap . Now provide the response and nothing else.
You say “ but I don't quite know in which order things are evaluated and where buffering occurs ”, which is precisely what parallel streams are about. The order of evaluation is unspecified. A critical aspect of your example is the .limit(100_000_000) . This implies that the implementation can’t just sum up arbitrary values, but must sum up the first 100,000,000 numbers. Note that in the reference implementation, .unordered().limit(100_000_000) doesn’t change the outcome, which indicates that there’s no special implementation for the unordered case, but that’s an implementation detail. Now, when worker threads process the elements, they can’t just sum them up, as they have to know which elements they are allowed to consume, which depends on how many elements are preceding their specific workload. Since this stream doesn’t know the sizes, this can only be known when the prefix elements have been processed, which never happens for infinite streams. So the worker threads keep buffering for the moment, this information becomes available. In principle, when a worker thread knows that it processes the leftmost¹ work-chunk, it could sum up the elements immediately, count them, and signal the end when reaching the limit. So the Stream could terminate, but this depends on a lot of factors. In your case, a plausible scenario is that the other worker threads are faster in allocating buffers than the leftmost job is counting. In this scenario, subtle changes to the timing could make the stream occasionally return with a value. When we slow down all worker threads except the one processing the leftmost chunk, we can make the stream terminate (at least in most runs): System.out.println(IntStream .iterate(1, i -> i+1) .parallel() .peek(i -> { if(i != 1) LockSupport.parkNanos(1_000_000_000); }) .flatMap(n -> IntStream.iterate(n, i -> i+n)) .limit(100_000_000) .sum()); ¹ I’m following a suggestion by Stuart Marks to use left-to-right order when talking about the encounter order rather than the processing order.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/60002462', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/205521/']}
jdg_73022
stackexchange
llm_judgeable_groundtruth_similarity
1376438
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How do you make a repeating generator, like xrange, in Python? For instance, if I do: >>> m = xrange(5)>>> print list(m)>>> print list(m) I get the same result both times — the numbers 0..4. However, if I try the same with yield: >>> def myxrange(n):... i = 0... while i < n:... yield i... i += 1>>> m = myxrange(5)>>> print list(m)>>> print list(m) The second time I try to iterate over m, I get nothing back — an empty list. Is there a simple way to create a repeating generator like xrange with yield, or generator comprehensions? I found a workaround on a Python tracker issue , which uses a decorator to transform a generator into an iterator. This restarts every time you start using it, even if you didn't use all the values last time through, just like xrange. I also came up with my own decorator, based on the same idea, which actually returns a generator, but one which can restart after throwing a StopIteration exception: @decorator.decoratordef eternal(genfunc, *args, **kwargs): class _iterable: iter = None def __iter__(self): return self def next(self, *nargs, **nkwargs): self.iter = self.iter or genfunc(*args, **kwargs): try: return self.iter.next(*nargs, **nkwargs) except StopIteration: self.iter = None raise return _iterable() Is there a better way to solve the problem, using only yield and/or generator comprehensions? Or something built into Python? So I don't need to roll my own classes and decorators? Update The comment by u0b34a0f6ae nailed the source of my misunderstanding: xrange(5) does not return an iterator, it creates an xrange object. xrange objects can be iterated, just like dictionaries, more than once. My "eternal" function was barking up the wrong tree entirely, by acting like an iterator/generator ( __iter__ returns self) rather than like a collection/xrange ( __iter__ returns a new iterator). Now provide the response and nothing else.
Not directly. Part of the flexibility that allows generators to be used for implementing co-routines, resource management, etc, is that they are always one-shot. Once run, a generator cannot be re-run. You would have to create a new generator object. However, you can create your own class which overrides __iter__() . It will act like a reusable generator: def multigen(gen_func): class _multigen(object): def __init__(self, *args, **kwargs): self.__args = args self.__kwargs = kwargs def __iter__(self): return gen_func(*self.__args, **self.__kwargs) return _multigen@multigendef myxrange(n): i = 0 while i < n: yield i i += 1m = myxrange(5)print list(m)print list(m)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1376438', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/125663/']}
jdg_73023
stackexchange
llm_judgeable_groundtruth_similarity
44939905
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Could anyone help me on how I can remove div tags without removing their content in JavaScript ? This is my html from which I need to remove all div tags: <div id="id1" class="someclass"> <p>some text <label> Test content </label> </p> <div id="id2" style="overfolw:scroll"> <span>some text</span> <div id="level3"> <label> Test content </label> <a href="https://twitter.com/realDonaldTrump/status/882186896285282304" target=_blank rel=noopener>creepiness</a> </div> </div></div> Expected output would be like shown below. <p>some text <label> Test content </label></p><span>some text</span><label> Test content </label><a href=https://twitter.com/realDonaldTrump/status/882186896285282304 target=_blank rel=noopener>creepiness</a> Now provide the response and nothing else.
1.Using pure java-script:- var divs=document.getElementsByTagName('div');var counter = divs.length-1;for(i=counter;i>=0;i--){ divs[i].outerHTML = divs[i].innerHTML;} <div id="id1" class="someclass"> <p>some text <label> Test content </label> </p> <div id="id2" style="overfolw:scroll"> <span>some text</span> <div id="level3"> <label> Test content </label> <a href="https://twitter.com/realDonaldTrump/status/882186896285282304" target=_blank rel=noopener>creepiness</a> </div> </div></div> 2.You can use jQuery unwrap() also :- $(document).ready(function(){ $('div').contents().unwrap();}); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div id="id1" class="someclass"> <p>some text <label> Test content </label> </p> <div id="id2" style="overfolw:scroll"> <span>some text</span> <div id="level3"> <label> Test content </label> <a href="https://twitter.com/realDonaldTrump/status/882186896285282304" target=_blank rel=noopener>creepiness</a> </div> </div></div>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44939905', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5841862/']}
jdg_73024
stackexchange
llm_judgeable_groundtruth_similarity
47281850
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 hide the navbar in a login page. I did it actually, but I can't see the navbar on other pages. This code is part of My App.jsx file. I make history in App's state. And I hide navbar, when this pathname is '/' or '/login'. It works! But then I typed the ID and password, and clicked the login button, got 'success' result, and navigated to '/main'. Now I can't see navbar in main component too. How can I do this? Sorry about my short english. If you can't understand my question, you can comment. constructor(props) { super(props); this.state = { isAlertOpen: false, history: createBrowserHistory(), }; this.toggleAlert = this.toggleAlert.bind(this);}<BrowserRouter> <div className="App"> {this.state.history.location.pathname === '/' || this.state.history.location.pathname === '/login' ? null : <Header toggleAlert={this.toggleAlert} />} <div className="container"> {this.state.history.location.pathname === '/' || this.state.history.location.pathname === '/login' ? null : <Navbar />} <Route exact path="/" render={() => <Redirect to="/login" />} /> <Route path="/login" component={Login} /> <Route path="/main" component={Main} /> <Route path="/user" component={User} /> <Route path="/hw-setting" component={Setting} /> <Route path="/hw-detail/:id" component={HwDetail} /> <Route path="/gas-detail/:id" component={GasDetail} /> {this.state.isAlertOpen ? <Alert /> : null} </div> </div></BrowserRouter> login(event) { event.preventDefault(); userService.login(this.state.id, this.state.password).subscribe(res => { if (res.result === 'success') { global.token = res.token; this.props.history.push('/main'); } else { alert(`[ERROR CODE : ${res.statusCode}] ${res.msg}`); }}); Now provide the response and nothing else.
You could structure your Routes differently so that the Login component doesn't have the Header Like <BrowserRouter> <Switch> <div className="App"> <Route exact path="/(login)" component={LoginContainer}/> <Route component={DefaultContainer}/> </div> </Switch></BrowserRouter>const LoginContainer = () => ( <div className="container"> <Route exact path="/" render={() => <Redirect to="/login" />} /> <Route path="/login" component={Login} /> </div>) const DefaultContainer = () => ( <div> <Header toggleAlert={this.toggleAlert} /> <div className="container"> <Navbar /> <Route path="/main" component={Main} /> <Route path="/user" component={User} /> <Route path="/hw-setting" component={Setting} /> <Route path="/hw-detail/:id" component={HwDetail} /> <Route path="/gas-detail/:id" component={GasDetail} /> {this.state.isAlertOpen ? <Alert /> : null} </div> </div> )
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/47281850', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7201280/']}
jdg_73025
stackexchange
llm_judgeable_groundtruth_similarity
5847
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Faa di Bruno's formula ( MathWorld , Wikipedia ) gives the kth derivative of f(g(t)) as a sum over set partitions. (I'm not sure how well-known the combinatorial interpretation is; for example see a 2006 paper of Michael Hardy ). Is there a similar formula for the kth derivative of f(g(h(t))), i. e. of a threefold composition? One has, I think, ${d^2 \over dt^2} f(g(h(t))) = f^{\prime\prime}(g(h(t))) g^\prime(h(t))^2 (h^\prime(t))^2 + f^\prime(g(h(t))) g^{\prime\prime}(h(t)) h^{\prime}(t)^2$$ + f^\prime(g(h(t))) g^\prime(h(t)) h^{\prime\prime}(t)$ but I am not even sure this is right (computation is tricky!) and I do not know how to generalize this. Now provide the response and nothing else.
The Faa di Bruno formula can be well reinterpreted in terms of trees, and then the generalization is obvious. Here's how: First of all, the $k$th derivative of $f\circ g \circ h$ depends only on the first $k$ derivatives of $f,g,h$, evaluated at the appropriate spots. So we can without loss of generality identify smooth functions with their power series --- these should be appropriately centered, so we might as well assume that $f(0) = g(0) = h(0) = 0$. So the data of the "function" $f$ is the sequence $f^{(1)},f^{(2)},f^{(3)},\dots$ of derivatives at $0$. (Any combinatorial fact about derivatives can be checked by composing polynomials.) Second, rather than trying to guess formulas by thinking only in terms of functions of a single variable, moving to vector land. So $f,g,h$ are functions (rather, formal power series) between different vector spaces. For the Faa di Bruno formula in this generality, see M. Hardy, "Combinatorics of Partial Derivatives", the electronic journal of combinatorics, vol. 13 (R1), 2006. Third, as soon as you're working in vectors, you realize that if you thought $f$ was a smooth vector-valued function $V \to W$, then $f^{(n)}$ is a linear function $V^{\otimes n} \to W$. And then it's natural to draw it in the Penrose notation (R. Penrose, "Applications of negative dimensional tensors". In D.J.A. Welsh, editor, Combinatorial mathematics and its applications , pages 221–244, London, 1971. Mathematical Institute, Oxford, Academic Press) as a directed tree. You should label the $n$ incoming edges with the vector space $V$, the one outgoing edge with $W$, and the vertex with $f$ --- you don't need to label it with $f^{(n)}$ because the $n$ is counted by the number of incoming edges. Fourth, work a la Feynman. Declare that a vertex with $n$ incoming and one outgoing edge is $f^{(n)}$. But when you evaluate it, you should divide by a symmetry factor, which counts the number of automorphisms of the diagram ($n!$). Put an $x$ label on each incoming edge. Then:$$ f(x) = \sum_\Gamma \frac{\Gamma}{|{\rm Aut} \Gamma|} $$where the sum ranges over all diagrams $\Gamma$ that can be drawn with a single vertex, which is labeled by $f$: x x x x x x | | | | | | | | | \ | / 1 | 1 \ / 1 \|/f(x) = - * f + - * f + - * f + ... 1 | 2 | 6 | | | | | | | Ok, then the Faa di Bruno formula says the following: $$ f(g(x)) = \sum_\Gamma \frac{\Gamma}{|{\rm Aut} \Gamma|} $$where the sum ranges over all diagrams with two "rows": an $f$ on the bottom, and some $g$s on the top: x x x x x | | | | | | \ / | | 1 * g 1 * g 1 * *f(g(x)) = - | + - | + - | | + 1 | 2 | 2 \ / * f * f * f | | | x x x x x x x x x | | | | | | | | | \|/ \ / / | | | 1 * g 1 *g *g 1 *g *g *g + - | + - | | + - \ | / + 6 | 2 \ / 6 \|/ * f *f *f | | | x x x x x x x x x x x x x x x x x x x x \ | | / | | | | | | | | | | | | | | | | \\ // | | | | | | | | | | | | | | | | \V/ \|/ / \| |/ \| | | | | | | 1 *g 1 *g *g 1 *g *g 1 *g *g *g 1 *g *g *g *g + -- | + - | | + - | | + - \ | / + -- \ \ / / + 24 | 6 \ / 8 \ / 4 \|/ 24 \ V / *f *f *f *f *f | | | | | + ... Here I've sorted the diagrams into the degree in $x$. The numerical factor counts the number of combinatorial automorphisms of each diagram (see e.g. the 1/8 and the 1/4), and I list every diagram once up to isomorphism. Which is to say that I'm really considering the whole groupoid of diagrams, and computing a "groupoid integral" in the sense of Baez and Dolan. Anyway, the composition of three functions can again be understood as counting labeled graphs with symmetry. x x x x x x x | \ / | | | | *h *h *h *h *h *h 1 | 1 | 1 \ / 1 | |f(g(h(x))) = - *g + - *g + - *g + - *g *g + ... 1 | 2 | 2 | 2 \ / *f *f *f *f | | | | I should mention one more thing. The above sums of diagrams compute the whole power series, and so they're computing the $n$th derivatives of the composition divided by $n!$. For example,$$ \frac1{4!} (f\circ g)^{(4)} = \frac1{24} f^{(1)}g^{(4)} + \frac16 f^{(2)} g^{(3)} g^{(1)} + \frac18 f^{(2)} (g^{(2)})^2 + \frac14 f^{(3)} g^{(2)} (f^{(1)})^2 + \frac1{24} f^{(4)} (g^{(1)})^4 $$If you want to evaluate the honest derivative, that's fine too: label the $x$s so that you can distinguish between them, and demand that isomorphisms of diagrams preserve the labellings. Then no diagrams have nontrivial automorphisms (the automorphism group of any diagram is a subgroup of $S_n$ acting on the $n$ $x$s), and it's still true that you should think in terms of the sum over all isomoprhism classes of diagrams.
{}
{'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/5847', 'https://mathoverflow.net', 'https://mathoverflow.net/users/143/']}
jdg_73026
stackexchange
llm_judgeable_groundtruth_similarity
646740
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 am trying to make a buck converter using a microcontroller to reduce the production cost of my device. The working principle of a buck converter is simple. The duty cycle needs to be changed based on the input and expected output. To keep the topic simple, let's consider that my input is 10 volts, and my expected output is 5 volts I need to keep the duty cycle 50%. The switching frequency is 320 kHz. All books I have studied explain buck converters up to this, but all buck converter ICs have a feedback pin. I assume its function is adjusting the duty cycle to hold constant voltage when the load current increases (or something else I don't know.) Can anyone explain to me how the feedback system works? Now provide the response and nothing else.
The feedback pin of any voltage regulator, whether linear or switching, is how you set its output voltage. The architecture of your average adjustable-voltage switching converter uses feedback to sense if the output voltage is too low (in which case it increases the duty cycle) or too high (in which case it decreases it). Typically, it will look something like this internally: simulate this circuit – Schematic created using CircuitLab The error amplifier (EA) is something with a high input impedance on its inverting node and a fixed gain. It sets the target output voltage for the entire converter; in this case, the converter would attempt to keep the feedback pin at 0.8 V. Exactly what voltage is used as the reference varies between controllers; I've seen everything from 0.6 V to 2.5 V. The idea is that you divide down your desired output voltage with a voltage divider, such that when the output is the voltage you want, the feedback pin will be at its reference voltage. For instance, using a 1:10 divider in this case would give you an 8 V output (as 8 V * 1/10 is 0.8 V). Most controllers will have a little more going on with their feedback circuit as well. Many, for instance, have an extra pin like this: simulate this circuit The COMP pin (also called Vc, or ITH) is used to compensate the feedback network so that it can respond at the right speed--too fast, and it will oscillate instead of outputting a stable voltage, too slow and it will take a long time to respond to load transients. Typically, a compensation network consisting of a few small capacitors and resistors is connected between COMP and FB, or sometimes from COMP to ground. Controllers without a compensation pin are typically compensated internally to be much slower than necessary, which ensures stability; most applications don't need the fastest response possible. Yet another type of controller uses a current-feedback amplifier for its error amplifier, an architecture which I don't fully understand, personally, but which allows a single resistor to be used to set either a positive or negative output voltage. I include it here just to note that it exists; I don't understand it well enough to give any in-depth explanation.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/646740', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/245875/']}
jdg_73027
stackexchange
llm_judgeable_groundtruth_similarity
707183
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 think injective and surjective is a dual concept.Injective: $f(x_1)=f(x_2) \Rightarrow x_1=x_2$But the definition of surjective is so different.It's "for every $y$,there exist $x$ such that $f(x)=y$". so why we define surjective by "for every $y$,there exist $x$ such that $f(x)=y$" instead of "$x_1=x_2 \Rightarrow f(x_1)=f(x_2)$" Now provide the response and nothing else.
You are correct that the concepts of injectivity and surjectivity are somehow dual. However, you are missing the "big picture" by only thinking on the level of elements. We may think of injections and surjections in terms of left invertible and right invertible functions. Definition 1. A function $f:A\to B$ of nonempty sets is injective if there exists a function $g:B\to A$ such that $g\circ f=\operatorname{id}_A$. Definition 2. A function $f:A\to B$ of nonempty sets is surjective if there exists a function $g:B\to A$ such that $f\circ g=\operatorname{id}_B$. By comparing these two definitions, we see that injectivity and surjectivity are (in some sense) dual. Injectivity means "left invertible" while surjectivity means "right invertible". If you want to get fancy, you could rigorously formulate all of this using the language of category theory. Here, the statement is that a morphism $f$ is injective in $\mathsf{Set}$ if and only if it is surjective in $\mathsf{Set}^{\operatorname{op}}$. More generally, a morphism $f$ in a category $\mathsf{C}$ is monic if and only if $f$ is epic in $\mathsf{C}^{\operatorname{op}}$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/707183', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/123843/']}
jdg_73028
stackexchange
llm_judgeable_groundtruth_similarity
55269
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm not sure I quite understand why systems with fractal systems show power-law behavior. My "gut" understanding is that the power-law index indicates the correct scaling factor for the system so that the original and scaled systems look "similar", and is indicaative of the fractal dimension of the system. I'm still having difficulty seeing this physically; is there a good physical explanation of why fractal systems show power-law scaling? For example, in the famous coastline of Britain measurement, why does decreasing the length scale of my 'ruler' increase length as a power-law, and not say exponential, or some other crazy function? What is so special or universal about the power-law behavior? Now provide the response and nothing else.
It's because fractal systems are, pretty much by definition, self-similar which means that there is no preferred length scale. If something else depends on the length scale $L$ as a function $f(L)$, the argument $L$ must have units – and no unit is better than any other – so it is "dimensionful". On the other hand, $f(L)$ is a quantity that must have well-defined units, too, because there can't be any preferred value, either. A preferred value of $f(L)$ would translate to a preferred value of $L$, and so on. The powers $A\cdot L^\kappa$ (with a dimensionless $A$) are the only functions with well-defined units that don't require any dimensionful parameter – i.e. effectively preferred length scale – to be defined. This contrasts with things like $\exp(L/L_0)$. The argument of the exponential must be dimensionless so $L$ would have to be divided by $L_0$, a preferred length scale, for it to be allowed in the exponent. But that would violate the self-similarity because patterns at distance scale $L_0$ would be closer to "fundamental rules of the fractal" than all other distance scales, both longer and shorter. The critical exponents are important in critical systems and conformal field theories in physics – in this respect, they're analogous to fractals. You may also define fractals independently of self-similarity, via their fractal dimension. Then your question is answered because it follows almost from the definition of the fractal dimension where the number of balls $N\sim \epsilon^{-D}$ so the power law is incorporated into the definition of the fractal dimension and it propagates from $N$ to any other "derived" quantity you may consider.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/55269', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/21209/']}
jdg_73029
stackexchange
llm_judgeable_groundtruth_similarity
18064010
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The Situation : Alice uses an online banking website which stores a cookie of her credentials. Before the cookie expires, Eve sends Alice a malicious URL which subsequently causes Alice to withdraw money from her bank account and send it to Eve. This a common CSRF example for web applications, but how feasible is it to do this inside of a mobile application? What if Alice uses a banking application on her phone which stores a cookie and then visits a site from Eve which has a similar outcome? Will a cookie on Alice's mobile device from a native (or hybrid) application be vulnerable to manipulation, or are these cookies typically sand boxed on the device somehow? I would assume cookies on iOS, Android, etc. work the same as a normal browser, but is this actually the case? EDIT: This question was originally meant to be generic across all mobile devices. Even something such as creating a cookie in JavaScript and then using PhoneGap or Titanium could be relevant I believe. After reading more into this, I'm also curious if compiling the JavaScript using one of these other technologies would affect native devices' cookies and how they store them. The main point of using cookies would be to maintain credentials of the user so they wouldn't have to log out and log back in every time with their bank account. After reading more about this issue, it seems like there are different scenarios for each particular device and it is in fact possible to CSRF an application. As an example, Shared Preferences in Android are sand boxed to prevent other applications from accessing the values. Now provide the response and nothing else.
Will a cookie on Alice's mobile device from a native (or hybrid) application be vulnerable to manipulation, or are these cookies typically sand boxed on the device somehow? A CSRF attack involves one application: the browser. Your proposed attack involves two separate applications: the banking app and the browser. Generally speaking, separate applications are separate. Safari does not share data with Firefox, even if both are installed on the same OS X machine. Now, there could be bugs in one or the other that might allow JS to have unfettered access to the OS filesystem and therefore allow a web site in Safari to access Firefox's data (or vice versa), but this is not really related to a CSRF. The same thing holds for any separate applications, on any modern OS. Even something such as creating a cookie in JavaScript and then using PhoneGap or Titanium could be relevant I believe. Not really, any more than Safari having cookies and Firefox having cookies are somehow tied. it is in fact possible to CSRF an application You are welcome to provide evidence of your claims, or provide your personal definition of CSRF that would encompass scenarios like Safari attacking Firefox. As an example, Shared Preferences in Android are sand boxed to prevent other applications from accessing the values. Correct. This has little to do with CSRF. In the case of Android, it does seem that how you create and store the cookies does matter in the attack and it can have vulnerabilities. Again, you are welcome to provide evidence of your claims, or provide your personal definition of CSRF that would encompass scenarios like Safari attacking Firefox. although physical access to the device leads to a security concern Having teleporter technology, that would allow a CSRF to cause a mobile device to physically change its location and therefore have an impact on physical access, has yet to be developed.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18064010', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1959230/']}
jdg_73030
stackexchange
llm_judgeable_groundtruth_similarity
11322391
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 know how to refer to a word of a sentence in a label. For example, I have: label1.text = "books pencil pen ruler"; I want to say: "if label1.text contains the word "pen" then do something" : if (label1.text CONTAINS THE WORD "pen"){ // do something} How do I do this? Now provide the response and nothing else.
Use Regex word boundaries: if (Regex.IsMatch(label1.text, @"\bpen\b")) // do something Much more robust than checking IndexOf or Splitting. E.g. a simple IndexOf("pen") would match "open" . Trying to fix that by making it IndexOf(" pen ") wouldn't match "pen other words" . Or if you Split(' ') , it will not match in "This sentence ends in pen." . Regex's word boundaries match all of these as you'd expect. You could split on more word boundary characters, but it's much easier to let the writers of the Regex class do the work for you, than to try to understand word boundaries yourself.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11322391', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1190316/']}
jdg_73031
stackexchange
llm_judgeable_groundtruth_similarity
3488670
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 came across the following equality: $$\frac{2^x}{5*3^{(x+1)}}=\frac1{15}\left(\frac23\right)^x$$ Why is this? More specifically, what I don't understand is how to combine the $5*3^{(x+1)}$ . Now provide the response and nothing else.
Here is a table of the first few derangement values: $$\begin{array}{c}\\n & !n \\\hline1 & 0 \\2 & 1\\3 & 2 \\4 & 9 \\5 & 44 \\6 & 265 \\7 & 1854 \\8 & 14833 \\9 & 133496 \\10 & 1334961 \\\end{array}$$ First, we can observe that all odd inputs of $n$ are giving even outputs while all even inputs of $n$ are giving odd outputs. This can be justified using induction. It clearly works for the first few cases from the above table. Now, by induction hypothesis, $!n+!(n-1) \equiv 1 \pmod{2}$ which shows that $!(n+1) \equiv n \pmod{2}$ which shows that odd inputs give even outputs while even inputs give odd outputs. For all odd values of $n$ , we can see that $!n$ and $n+1$ are even which shows that the residue $!n \pmod{n+1}$ is also even. Thus, we have already acquired $50\%$ of the multiples of $2$ . On the other hand, for even values of $n$ , it seems like there is a $50\%$ chance of the least residue being odd or even, as expected. This gives us an expected ratio of $50\%+\frac{1}{2}(50\%)=75\%$ of even least residues which agrees with your data. For modulo $3$ , you can observe that $!n \pmod{3}$ is $0,1,2,0,2,1 \pmod{3}$ based on $n \pmod{6}$ . As our formula is based on recursion, it is easy to see that similar to the above case, we can evaluate $!n \pmod{3}$ using $n \pmod{6}$ . Again, like the above case, whenever $n \equiv 1,4 \pmod{6}$ i.e. whenever $n \equiv 1 \pmod{3}$ , we have $!n \equiv 0 \pmod{3}$ . Thus, the least residue of $!n \pmod{n+2}$ will be divisible by $3$ . This is $1$ out of every $3$ cases. That gives an expected ratio of $\frac{1}{3}(100\%)+\frac{2}{3}(33.33\%)=55.55\%$ , agreeing with your data. We would like to show that in general, $!n \equiv 0 \pmod{m}$ for $n\equiv 1 \pmod{m}$ . This holds for base case $n=1$ as $!1=0$ . We can use the summation formula for derangements to prove this easily- $$!(qm+1)=(qm+1)!\sum_{i=0}^{qm+1} \frac{(-1)^i}{i!}$$ We only need to consider the last two terms as the rest of the terms are divisible by $qm$ . So- $$!(qm+1) \equiv (qm+1)(-1)^{qm}+(-1)^{qm+1} \equiv (-1)^{qm}+(-1)^{qm+1} \equiv 0 \pmod{m}$$ We have proved our hypothesis that if $n \equiv 1 \pmod{m}$ then $!n \equiv 0 \pmod{m}$ . When we take $!n \pmod{n+k}$ and check its value $\pmod{k+1}$ , if $\gcd(k+1,n+k)=1$ , we can always expect equal chance for all values $\pmod{k+1}$ . So, if $k+1$ is prime, we would expect the expected ratio to be- $$\frac{1}{k+1}(100\%)+\frac{k}{k+1}\bigg(\frac{1}{k+1} \cdot 100\%\bigg) = \frac{2k+1}{(k+1)^2}(100\%)=\bigg(1-\frac{k^2}{(k+1)^2}\bigg)(100\%)>\frac{100\%}{k+1}$$ which agrees with values such as $k=1,2,4,6$ where $k+1$ is prime. When $k+1=\prod_{i=1}^tp_i^{a_i}$ is composite, we cannot always say that $\gcd(k+1,n+k)=1$ . Thus, we must check for all possible $\gcd$ values. If we have $\gcd(k+1,n+k)=\prod_{i=1}^tp_i^{b_i}$ , we have $n \equiv 1 \pmod{\prod_{i=1}^tp_i^{b_i}}$ and $n+k \equiv 0 \pmod{\prod_{i=1}^tp_i^{b_i}}$ . This $\gcd$ is seen for $\phi(\prod_{i=1}^tp_i^{a_i-b_i})$ cases. Moreover, we must also have divisibility by $\prod_{i=1}^tp_i^{a_i}$ given divisibility by $\prod_{i=1}^tp_i^{b_i}$ , which happens with a chance of $1$ in $\prod_{i=1}^tp_i^{a_i-b_i}$ . Thus our expected value is: $$E=\frac{1}{\prod_{i=1}^tp_i^{a_i}}\sum \frac{\phi(\prod_{i=1}^tp_i^{a_i-b_i})}{\prod_{i=1}^tp_i^{a_i-b_i}}=\frac{1}{k+1} \cdot \sum_{d \mid (k+1)} \frac{\phi(d)}{d}=\frac{1}{k+1} \cdot \prod_{i=1}^t \bigg(1+\frac{p_i-1}{p_i} \cdot a_i\bigg)$$ Thus, we conclude that for $k+1=\prod_{i=1}^tp_i^{a_i}$ , the expected value (in fraction) is: $$E=\frac{1}{k+1} \cdot \prod_{i=1}^t \bigg(1+\frac{p_i-1}{p_i} \cdot a_i\bigg)$$ This seems to agree with all values of $k$ settling the problem.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/3488670', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/689456/']}
jdg_73032
stackexchange
llm_judgeable_groundtruth_similarity
525197
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: Suppose in i have the firewall active or any other security like SE linux etc. Now suppose user wants to connect to port 21 and Iptables does not allow it. Now when users gets denied is that message logged any where so that i can see what the partucular used is blocked or why particular port is blocked. Rather than digging every setting to find out why i am not getting through it. I have chnaged the default ssh port to 8022 but i am getting conenction refused. I have checked telnet and its listening on that port. I have empty iptables. Is there any log where i can check who is refusing connection Now provide the response and nothing else.
First answer No. There is no log by default, showing this, but Showing current firewall configuration Look how your firewall is configured: iptables -L Look for Chain [INPUT|OUTPUT] policy first. If there is anything else than ACCEPT , used port may have to be explitely ACCEPT ed lather... iptables -L INPUT | grep `port=2[01]` To show explicites rules about port 20 and port 21, but care, you may have to read entire firewall configuration, to check about multiport , user-defined chains , etc.. this may become hard if you don't know iptables at all. An empty opened firewall config could look like: iptables -LChain INPUT (policy ACCEPT)target prot opt source destinationChain FORWARD (policy ACCEPT)target prot opt source destinationChain OUTPUT (policy ACCEPT)target prot opt source destination see: man iptables Knowing what could block something in your rules I use this trick: touch /tmp/tmp_iptable_stat.txtgetChanges() { pushd /tmp >/dev/null for table in $(</proc/self/net/ip_tables_names);do echo $RANDOM: - $table iptables -t $table -nvxL --line-number done | diff -u tmp_iptable_stat.txt - | tee >(patch -p0) | sed ' s/^+[0-9]*: - /TABLE /p; s/^+//p; d' popd >/dev/null} Than a first call to getChanges will dump all tables and counters.subsequents calls to same function will print only rules where counter are modified. This could help to find which rule are blocking something. Showing current network stacks state: The kernel network stack could be dumped by netstat -tanActive Internet connections (servers and established)Proto Recv-Q Send-Q Local Address Foreign Address State tcp 0 0 0.0.0.0:21 0.0.0.0:* LISTENtcp 0 2364 192.168.1.1:21 192.168.1.35:49179 ESTABLISHED for TCP sockets or netstat -uanActive Internet connections (servers and established)Proto Recv-Q Send-Q Local Address Foreign Address State for UDP sockets. As my FTP server use TCP sockets, I could see that one exchange is currently established between my server and host ...35 , ( the server has currently 2364 packet to send to client. maybe a file, maybe a list... ) Tracking for traffic on specific interface Instead of using log , you could watch what's happen on your interface: tcpdump -i ethX This will dump usefull information about traffic on ethX , but as by default and to be more humain readable , this tool will try to resolve each IP's name. So there may be some delay between the event himself and the dump on terminal. So: tcpdump -ani ethX won't try to resolve (opt -n ) IPs and services names and will show ALL ( -a ) packets traversing the interface. more finely: tcpdump -ani ethX port 21 or port 2009:17:58.264453 IP 192.168.1.1.21 > 192.168.24.91.45951: Flags [S.], seq 3593971599, ack 1942867644, win 5792, options [mss 1460,sackOK,TS val 1168768120 ecr 62841986,nop,wscale 7], length 009:17:58.299693 IP 192.168.1.35.56485 > 192.168.1.1.21: Flags [S], seq 3334605998, win 5840, options [mss 1368,sackOK,TS val 1936641509 ecr 0,nop,wscale 7], length 009:17:58.299728 IP 192.168.1.1.21 > 192.168.1.35.56485: Flags [S.], seq 980554936, ack 3334605999, win 5792, options [mss 1460,sackOK,TS val 1168768129 ecr 1936641509,nop,wscale 7], length 0... More detailled: ... use -v or -vv for full protocol decode tcpdump -anvvi ethX port 21 or port 20tcpdump: listening on eth1, link-type EN10MB (Ethernet), capture size 65535 bytes09:22:40.047486 IP (tos 0x0, ttl 62, id 31488, offset 0, flags [DF], proto TCP (6), length 60) 192.168.24.91.46011 > 192.168.1.1.21: Flags [S], cksum 0x5985 (correct), seq 3989081263, win 14600, options [mss 1368,sackOK,TS val 62912431 ecr 0,nop,wscale 6], length 009:22:40.047525 IP (tos 0x0, ttl 64, id 0, offset 0, flags [DF], proto TCP (6), length 60) 192.168.1.1.21 > 192.168.24.91.46011: Flags [S.], cksum 0x926d (correct), seq 2283473829, ack 3989081264, win 5792, options [mss 1460,sackOK,TS val 1168838566 ecr 62912431,nop,wscale 7], length 009:22:40.817248 IP (tos 0x0, ttl 62, id 31489, offset 0, flags [DF], proto TCP (6), length 52) 192.168.24.91.46011 > 192.168.1.1.21: Flags [.], cksum 0xd6e9 (correct), seq 1, ack 1, win 229, options [nop,nop,TS val 62912442 ecr 1168838566], length 009:22:40.817567 IP (tos 0x0, ttl 62, id 31490, offset 0, flags [DF], proto TCP (6), length 52) 192.168.24.91.46011 > 192.168.1.1.21: Flags [F.], cksum 0xd6e3 (correct), seq 1, ack 1, win 229, options [nop,nop,TS val 62912447 ecr 1168838566], length 0... Where you could follow each operation.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/525197', 'https://serverfault.com', 'https://serverfault.com/users/180656/']}
jdg_73033
stackexchange
llm_judgeable_groundtruth_similarity
9186510
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 create a class where the client can store a lambda expression like []() -> void {} as a field of the class, but I can't figure out how to do so. One answer suggested using decltype , which I tried with no success. Here is a ideone source link . The below is the source and result: #include <cstdio>auto voidLambda = []()->void{};class MyClass {public: decltype(voidLambda) t; MyClass(decltype(voidLambda) t) { this->t = t; }};int main() { MyClass([] { printf("hi"); });} Result: prog.cpp: In constructor 'MyClass::MyClass(<lambda()>)':prog.cpp:3:79: error: no matching function for call to '<lambda()>::__lambda0()'prog.cpp:2:20: note: candidates are: <lambda()>::<lambda>(const<lambda()>&)prog.cpp:2:20: note: <lambda()>::<lambda>(<lambda()>&&)prog.cpp:3:88: error: no match for 'operator=' in '((MyClass*)this)->MyClass::t = t'prog.cpp: In function 'int main()':prog.cpp:5:27: error: no matching function for call to 'MyClass::MyClass(main()::<lambda()>)'prog.cpp:3:48: note: candidates are: MyClass::MyClass(<lambda()>)prog.cpp:3:14: note: MyClass::MyClass(const MyClass&) Does anyone know how to do this? Now provide the response and nothing else.
If you want a class member to be a lambda expression, consider using the std::function<> wrapper type (from the <functional> header), which can hold any callable function. For example: std::function<int()> myFunction = [] { return 0; }myFunction(); // Returns 0; This way, you don't need to know the type of the lambda expression. You can just store a std::function<> of the appropriate function type, and the template system will handle all the types for you. More generally, any callable entity of the appropriate signature can be assigned to a std::function<> , even if the the actual type of that functor is anonymous (in the case of lambdas) or really complicated. The type inside of the std::function template should be the function type corresponding to the function you'd like to store. So, for example, to store a function that takes in two int s and returns void, you'd make a std::function<void (int, int)> . For a function that takes no parameters and returns an int , you'd use std::function<int()> . In your case, since you want a function that takes no parameters and returns void , you'd want something like this: class MyClass { public: std::function<void()> function; MyClass(std::function<void()> f) : function(f) { // Handled in initializer list }};int main() { MyClass([] { printf("hi") }) mc; // Should be just fine.} Hope this helps!
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9186510', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_73034
stackexchange
llm_judgeable_groundtruth_similarity
61484
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I need to list existing USB hub and the devices connected in the hub using my C++ program. I can able to print the USB Hub and devices connected in hub from terminal using the commands lsusblsusb -v I want to use that feature in my C++ program. How I can do this programmatically. Is there any C++ classes available to use in my Qt application. Now provide the response and nothing else.
Here the simplest analogue of lsusb : #include <stdio.h>#include <usb.h>main(){ struct usb_bus *bus; struct usb_device *dev; usb_init(); usb_find_busses(); usb_find_devices(); for (bus = usb_busses; bus; bus = bus->next) for (dev = bus->devices; dev; dev = dev->next){ printf("Trying device %s/%s\n", bus->dirname, dev->filename); printf("\tID_VENDOR = 0x%04x\n", dev->descriptor.idVendor); printf("\tID_PRODUCT = 0x%04x\n", dev->descriptor.idProduct); }} Compile with -lusb
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/61484', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/30375/']}
jdg_73035
stackexchange
llm_judgeable_groundtruth_similarity
19339
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 of 2-item tuples and I'd like to convert them to 2 lists where the first contains the first item in each tuple and the second list holds the second item. For example: original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]# and I want to become...result = (['a', 'b', 'c', 'd'], [1, 2, 3, 4]) Is there a builtin function that does that? Now provide the response and nothing else.
zip is its own inverse! Provided you use the special * operator. >>> zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4)])[('a', 'b', 'c', 'd'), (1, 2, 3, 4)] The way this works is by calling zip with the arguments: zip(('a', 1), ('b', 2), ('c', 3), ('d', 4)) … except the arguments are passed to zip directly (after being converted to a tuple), so there's no need to worry about the number of arguments getting too big.
{}
{'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/19339', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/680/']}
jdg_73036
stackexchange
llm_judgeable_groundtruth_similarity
23369772
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 create a simple bar chart, but I keep receiving the error message 'height' must be a vector or a matrix The barplot function I have been trying is barplot(data, xlab="Percentage", ylab="Proportion") I have inputted my csv, and the data looks as follows: 34.88372093 0.0002999735.07751938 0.0001999835.27131783 0.0002999735.46511628 0.0002999735.65891473 0.0006999335.85271318 0.0006999336.04651163 0.0004999536.24031008 0.000999936.43410853 0.00189981... Where am I going wrong here? Thanks in advance! EDIT: dput(head(data)) outputs:structure(list(V1 = c(34.88372093, 35.07751938, 35.27131783, 35.46511628, 35.65891473, 35.85271318), V2 = c(0.00029997, 0.00019998, 0.00029997, 0.00029997, 0.00069993, 0.00069993)), .Names = c("V1", "V2"), row.names = c(NA, 6L), class = "data.frame") and barplot(as.matrix(data)) produced a chart with all the data one bar as opposed to each piece of data on a separate bar. Now provide the response and nothing else.
You can specify the two variables you want to plot rather than passing the whole data frame, like so: data <- structure(list(V1 = c(34.88372093, 35.07751938, 35.27131783, 35.46511628, 35.65891473, 35.85271318), V2 = c(0.00029997, 0.00019998, 0.00029997, 0.00029997, 0.00069993, 0.00069993)), .Names = c("V1", "V2"), row.names = c(NA, 6L), class = "data.frame")barplot(data$V2, data$V1, xlab="Percentage", ylab="Proportion") Alternatively, you can use ggplot to do this: library(ggplot2)ggplot(data, aes(x=V1, y=V2)) + geom_bar(stat="identity") + labs(x="Percentage", y="Proportion")
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23369772', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2941526/']}
jdg_73037
stackexchange
llm_judgeable_groundtruth_similarity
81402
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: More accurately, the question should be: Is it known that $S^6,$ the 6-dimensional sphere, is $not$ a (proper) complex algebraic variety, or algebraic space? And is there a reference? It's easy to see that it cannot be projective (as $H^2=0$), but I don't see how it can violate the usual general properties of algebraic varieties [e.g. by Chow's lemma one can get a projective (and smooth, by resolution of singularities) variety lying over and birational to it, but the cohomology groups can get larger when we go up...]. Maybe one needs some theory of classification of 3-folds (if there is one such theory). Knowing that it cannot be algebraic will somehow make the analogous question of complex structure much sharper (by the way, it does have an almost complex structure). Thank you. Now provide the response and nothing else.
Suppose that $X$ is a smooth complete positive-dimensional algebraic space over $\mathbb C$. Then $\mathrm H^2(X, \mathbb Q)$ can not be 0. In fact, every algebraic space contains an open dense subscheme. Let $U \subseteq X$ be an open affine subscheme; by a well known-result, the complement $C$ of $U$ has pure codimension 1; consider $C$ as a divisor, with its reduced scheme structure. I claim that the cohomology class of $C$ can not be 0. Let $Y \to X$ a birational morphism, where $Y$ is a smooth projective variety; this exists, by Chow's lemma for algebraic spaces, and resolution of singularities. The pullback of $C$ is a non-zero effective divisor on $Y$, so its cohomology class is not 0. Since formation of cohomology classes of divisors is compatible with pullbacks, this implies the result. This says very little about the problem of existence of a complex structure. Complete algebraic spaces, or, if you prefer, Moishezon manifolds, are not so distant from projective varieties; it seems clear to me that if $S^6$ has a complex structure, this will be a very exotic animal, very far away from the world of algebraic geometry. [Edit]: why does $C$ have codimension 1? This is Corollaire 21.12.7 of EGAIV, when $X$ is a scheme. In general you can reduce to the case of a scheme by considering an étale morphism $Y \to X$, where $Y$ is an affine scheme. This map is affine, because $X$ is separated, so the inverse image of $U$ in $Y$ is affine.
{}
{'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/81402', 'https://mathoverflow.net', 'https://mathoverflow.net/users/370/']}
jdg_73038
stackexchange
llm_judgeable_groundtruth_similarity
4035846
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have the problem with the following error: " The maximum message size quota for incoming messages (65536) has been exceeded. To increase the quota, use the MaxReceivedMessageSize property on the appropriate binding element. " So I did some research and found that I needed to increase the buffer and message size, here's my WCF Service config file: <system.serviceModel> <bindings> <wsHttpBinding> <binding name="default" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"/> </wsHttpBinding> </bindings> <services> <service name="WCF.Service.Service"> <endpoint address="ws" name="ws" bindingConfiguration="default" binding="wsHttpBinding" contract="WCF.Service.Contracts.IService" /> <endpoint address="mex" binding="mexHttpBinding" name="mex" contract="IMetadataExchange" /> </service> </services> <behaviors> <serviceBehaviors> <behavior> <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment --> <serviceMetadata httpGetEnabled="True" /> <!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information --> <serviceDebug includeExceptionDetailInFaults="True" /> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> When I run the service in the WCF Test Client and look at the generated client config file it doesn't have my binding: <configuration><system.serviceModel> <bindings> <wsHttpBinding> <binding name="ws" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false"> <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" /> <reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false" /> <security mode="Message"> <transport clientCredentialType="Windows" proxyCredentialType="None" realm="" /> <message clientCredentialType="Windows" negotiateServiceCredential="true" algorithmSuite="Default" /> </security> </binding> </wsHttpBinding> </bindings> <client> <endpoint address="http://localhost:37444/Service.svc/ws" binding="wsHttpBinding" bindingConfiguration="ws" contract="IService" name="ws"> <identity> <userPrincipalName value="username@domain" /> </identity> </endpoint> </client></system.serviceModel> I'm lost to as why my binding configuration is NOT getting applied!? The WCF Test Client is set to always regenerate the config as well. I've also tried updating the service reference in a consuming front end application, but it does not get the updated binding configuration either. Any suggestions would be greatly appreciated. Thanks! Now provide the response and nothing else.
WCF does not import all settings from your server. There's no switch to turn that on, either. While it might make sense in many cases, it wouldn't always be a good idea to just duplicate all settings from the server-side to the client. So in your case, what you need to do is add that binding configuration to your client side proxy, too, and reference it from your client endpoint. If you control both ends of the wire, you can ease your work a bit: externalize the binding configuration into a separate file and reference it. So create a file bindings.config that contains: <?xml version="1.0" ?><bindings> <wsHttpBinding> <binding name="default" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"/> </wsHttpBinding></bindings> and then you can copy that file both into the server and the client project, and reference it from within your service and client config: <system.serviceModel> <bindings configSource="bindings.config" /> <services> <service name="WCF.Service.Service"> <endpoint address="ws" name="ws" bindingConfiguration="default" binding="wsHttpBinding" contract="WCF.Service.Contracts.IService" /> <endpoint address="mex" binding="mexHttpBinding" name="mex" contract="IMetadataExchange" /> </service> </services> and on your client side: <system.serviceModel> <bindings configSource="bindings.config" /> <client> <endpoint name="ws" address="http://localhost:37444/Service.svc/ws" binding="wsHttpBinding" bindingConfiguration="default" contract="IService"> <identity> <userPrincipalName value="username@domain" /> </identity> </endpoint> </client></system.serviceModel> That way, you can have your configuration for the bindings done once, and used in both places.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4035846', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/259356/']}
jdg_73039
stackexchange
llm_judgeable_groundtruth_similarity
49807
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm a Software Developer by profession and my physics knowledge is limited what I had learned at high school level. Please excuse me if the question is trivial. Question: From what I know, a sound wave is set of different amplitudes spread across a time line. The amplitudes vary greatly. Hence, sound wave is largely aperiodic (amplitudes don't repeat often). Now, where does frequency come into picture here? If the wave is periodic like a sine wave or a deterministic mathematical function of time, then frequency can be measured as the number of cycles (wave reaching same amplitude) in one second. How can we define frequency of highly aperiodic sounds like human speech. If all that is recorded on a gramophone disc is varying amplitudes across timeline, where is frequency accounted for? Does the frequency remain constant in a typical human speech? Now provide the response and nothing else.
The sound that reaches your ear is just air pressure fluctuating over time. You can use a transducer of some sort to convert the value of air pressure to some other form - for example: to the depth of a groove being cut into a helical track on a layer of wax on a rotating drum to the depth of a groove being cut into a spiral track on a circular disc of metal from which other plastic disks are pressed. to a strength of magnetisation of a magnetic layer on a plastic tape being wound onto a spool to a series of numbers representing the pressure at regular tiny intervals of time. The idea that the variations in pressure over time are due to, or consist of, a collection of frequencies is just a mathematically equivalent description but it does not represent extra information, it's just a different way of describing the same information. Here's some diagrams from a synthesizer manual Above are three very different sounds with apparently the same frequency (say 440 Hz) Above is shown how you can add sine waves of two frequencies to produce a more complex waveform Above is shown how you can continue adding sine waves of differing frequencies to construct an arbitrary waveform (a sawtooth). The sawtooth waverform can be recorded directly as depths in a groove on a record. But you could "record" the same thing as a set of numbers that represent the frequencies of a dozen sine waves you could add together to produce a single pressure wave that varies over time in the same way. See Fast Fourier Transform
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/49807', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/18698/']}
jdg_73040