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
3211538
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $f(x,y)$ be multi variable function that is defined when $\frac{x}{2}<y <x $ , and I want to know if there is such a function that satisfies : 1 ) $f(x-1,y) > f(x,y)$ 2 ) $f(x-1,y-\ln x) > f(x,y)(1-\frac{1}{x})$ 3 ) $|f(x,y) - \ln x| < \frac{1}{\sqrt{x}}$ when $|y- x| < 3\ln x$ , this condition can be loosened to say $\frac{1}{x^{\frac{1}{3}}}$ or more (but for a fixed constant power). I think such function do not exist, I just don't have a proof. Please give a proof that such function does not exist or an example for such a function Edit : I am interested as $x \to \infty$ how the function behave, also i am assuming that $f(x-1,y),f(x-1,y-\ln x),f(x,y)$ are all defined. For example the function $f(x,y) = \ln (x) +1-\frac{x}{y}$ does satisfy the conditions $1,3$ but does not satisfy $2$ . Now provide the response and nothing else.
HINT $\color{brown}{\textbf{Domains and unknowns.}}$ Taking in account condition $$\frac x2 < y < x$$ expressions $f(x,y)$ and $f(x-1)$ exists in the same time if $$\frac x2 < y < x-1,\quad x \in [2,\infty).\tag1$$ Since $$\dfrac x2-n\ln x = \dfrac t2-n\ln t + \left(\dfrac12 -\dfrac nt\right)(x-t) +\dfrac n{2t^2}(x-t)^2 - \dfrac n{3t^3}(x-t)^3+\dots,$$ then $y-n\ln x > g_n(x,t),$ where $$g_n(x,t) = \dfrac t2-n\ln t + \left(\dfrac12 -\dfrac nt\right)(x-t) +\dfrac {3n}{2t}\dfrac{(x-t)^2}{2x+t}.\tag2$$ In particular, $y-\ln x > g_1(x,2),$ or $$y-\ln x > \ln\frac e2 + \frac38\,\frac{(x-2)^2}{x+1},\quad\text{where}\quad x>2,\tag{3a}$$ with the angular coefficient from zero to ${\large\frac38}$ (see also Wolfram Alpha plot ). The slope $k=g'_2(t) = {\large \frac38 \frac{(t-2)(t+4)}{(t+1)^2}}$ of the tangent line $AB,$ where $A=(0,2)$ and $B=(t,g(t)),$ can be obtained from the condition $g(t) = k(t-2),\phantom{\Big|}$ or $$\ln\frac e2 +\dfrac38 \left(\dfrac{t-2}{t+1}\right)^2(t+1-(t+4)) = 0,$$ with the solution $$t = \frac{q+2}{1-q},\quad k = \frac38 \frac{(t-2)(t+4)}{(t+1)^2},\quad\text{where}\quad q=\frac{2\sqrt{2\ln{\Large\frac e2}\phantom{\bigg|}}}3,\quad \dbinom tk \approx \dbinom{5.279}{0.289\,412}.$$ Then $$\dfrac{y-\ln x}{x-2}\in \begin{cases}\left(\dfrac27,\infty\right),\quad\text{if}\quad x\in(2,\infty)\\\left(\dfrac27,\dfrac12\right),\quad\text{if}\quad x\in(3,\infty).\end{cases}\tag{3b}$$ Domain of the third condition $$y>x-3\ln x$$ is actual if $x> 3\ln x,$ or $x>u,$ where $$u = e^{-\large W_{\large-1}\left({\large-\frac13}\right)}\approx 4.536\,403\,655,\tag4$$ where $W_{-1}(x)$ is the analytic continuation of Lambert $W$ function (see also Wolfram Alpha solution and calculations ). Then $x-3\ln x > 2g_{3/2}(x,u),$ or $$x-3\ln x>\frac{x-u}{2u}\,\frac{(4u-3)(x-u)+6u(u-3)}{2x+u},\quad\text{if}\quad x\in(u,\infty),\tag{5a}$$ with the angular coefficient changing ${\large\frac{u-3}{u}}\approx0.339$ to ${\large\frac{4u-3}{4u}}\approx0.835$ (see also Wolfram Alpha plot ). Then $$\dfrac{x-3\ln x}{x-u}\in \left(\dfrac{1}{3},1\right), \quad\text{if}\quad x\in(u,\infty).\tag{5b}$$ $\color{brown}{\textbf{Mltiplicative model.}}$ Let us try to search function $f$ in the multiplicative form of $$f(x,y) = X(x)Y(y).\tag6$$ Taking in account $(1)-(5),$ let us consider the system of conditions in the form of $$\begin{cases}X(x-1)\,Y(y) > X(x)\,Y(y),\quad\text{if}\quad x>2\\[4pt]X(x-1)\,Y\left(y-\ln x\right)> \dfrac{x-1}x\,X(x)\,Y(y),\quad\text{if}\quad x>2\\[4pt]|X(x) Y(x-3\ln x) - \ln x| < \dfrac1{\sqrt x},\quad\text{if}\quad x>u\\[4pt]|X(x) Y(x-1) -\ln x| < \dfrac1{\sqrt x},\quad\text{if}\quad x>u\\y\in\left(\dfrac x2,x-1\right)\\y-\ln x \in\left(\dfrac{2(x-2)}7, \dfrac{x-2}2\right)\\x-3\ln x \in \left(\dfrac{x-u}3, \dfrac{x-u}2\right),\end{cases}\tag7$$ where $u$ is given by $(4).$ Assume $X(x)$ and $Y(y)$ monotonic positive functions. Easily to see that the first condition is satisfied if the function $X(x)$ decreases in the interval $(2,\infty).$ Taking in account $(1),$ the third condition in the form $(7.4)$ means that the production $X(x)Y(y)$ infinitely increases when $x\to\infty.$ Thus, function $Y(y)$ increases in the interval $(1,\infty).$ Taking in account increasing factor $\frac{x-1}x$ in the $\textbf{second condition},$ function $X(x)$ should contain decreasing factor ${\large\frac1x}.$ Taking in account $(7.4),$ it should contain logarithmic factor. It is possible, because the production $x^{-1}\ln^p(x+1)$ decreases in the interval $x\in(1,\infty)$ if $p\in(0,1].$ Taking in account $(3a),$ looks that the functions $$X(x) = \left(\ln(x+1)\right)^p x^{-q},\quad Y(y)= C\, \left(\ln(x+1)\right)^r(2y)^{-s}\tag8$$ can be solution for certain positive values of $p,q,r,s,$ Also, can be useful function $\dfrac{\ln^p\left(x+q\right)}{x},$ which decreases if $p\in[0,2],\,q\ge \dfrac{223}{168}\, \left(q=\dfrac43\right).$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3211538', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/411780/']}
jdg_371741
stackexchange
llm_judgeable_groundtruth_similarity
4318196
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Before you mention it I am aware that this question has been asked before but not since the launch of WCF4! So, after a lot of reading I've decided that a RESTful architecture is the way forward to begin a data providing API. Considering the release WCF 4, ASP.NET MVC 2 and WCF REST starter kit, what is the best way to begin implementing a RESTful architecture NOW? Me:I am very familiar with ASP.NET MVC so I'd feel quite comfortable there. My knowledge of WCF, however, is lacking. So WCF4 or ASP.NET MVC? (or something else like the wcf rest starter kit)? Specifically I'm looking for: Ease of implementation I know ASP.NET MVC, not WCF. Is WCF worth the learning curve? Is WCF4 overkill for REST or will ASP.NET MVC falls short at some point? Now provide the response and nothing else.
I've actually implemented or am currently using all 3 of the posted options so I'll give my take. Now that you've clarified what your looking for a little its easier to answer. OData OData is great for internal applications when: You are both the server and the client. You are using Entity Framework. You do not use inheritance in your models and are not expecting to query sub-collections. Odata is awesome because you can use IQueryable on the client side. This comes with some limitations though. The two off the top of my head include that you working with inherited models is a little awkward and you can't do nested collections . There is also an issue with not really knowing what the supported LINQ capabilities are . I'd recommend OData is you absolutely need a service layer and only expect to do simple CRUD operations with them. The main problem with every OData problem results in a hard wall you just can't get around sometimes. The client consumer code is really the best part and if you aren't using C# to consume its probably not worth it. Also without using EFs auto metadata support you'll be writing just the same amount of code to conform to a schema your consumers may or may not enjoy writing against. While there is a Rails wrapper for OData all of this is relatively new. I don't see OData in the wild yet besides really big MS partners. OData authentication and filtering is also pretty bare bones ATM. You'll be writing a lot of permission related code by yourself if you need to limit data. If you ever want SELECT * FROM TABLE to be limited by permissions be prepared to write some awkward code. MVC 2 MVC is pretty good for making a RESTful service. You have verb support and return JSONResult is as easy at it can be. The only potential downside is your coding a lot of the error handling yourself and all of your view models should inherit from a base class that shows status codes and error messages. You also may want to tweak the view engine a little depending on how fancy or convention driven you want your message replies to be. The HUGE benefit to MVC is its very extensible and you can do almost whatever you want. I'm big into combining forms/ajax calls/and rest services into the same controller action. Implement once, get three flavors of the same operation. It would be hard to make MVC fall short because it can be twisted to do almost anything you'd need. A big benefit to an MVC service is you can sneak a little admin UI in a the application that gets deployed along with the service. Very handy to not have two sites to deploy. WCF REST So I'm only using WCF rest in a very limited capacity and it seems... ok... I've used WCF for 3 years and I'm always unhappy with how frustratingly complex it is to extend it. Just like ODATA you'll run into sealed classes and unextensible caverns of functionality pretty quick if you go off the beaten path. This is in direct contrast to MVC's amount of extensibility. The other problem is your building on top of WCF and all the insanity that goes along with it. I've always said it requires a PhD to use WCF effectively. Rick Strahl had a good article about the pain points of WCF REST . Not sure if things have changed but its worth a read. WCF REST looks really promising and I'm using it right now I just don't know enough about it to recommend. Main Points If you don't know your consumers then I'd assume you don't know your API. Don't build a service until you have a use case and and can code against it. MVC is the most extensible and if you are familiar with how things work under the covers you'll probably be better off than implementing a hard to extend MS thing like OData and WCF. All of the "big boys" like Facebook, Amazon, PayPal, Ebay have APIs that don't really conform to any known pattern or schema like OData. Your REST service is really what you make of it. This relates to #1. Concentrate on making it easy for a consumer to work with first.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4318196', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/305955/']}
jdg_371742
stackexchange
llm_judgeable_groundtruth_similarity
3089616
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 $G$ be a non-abelian group of order $20$ . What will be the order of $\operatorname{Aut}(G)$ ? $(a)$ $1$ . $(b)$ $10$ . $(c)$ $30$ . $(d)$ $40$ . If I take $G = D_{10}$ then I find that the order of $\operatorname{Aut}(G)$ is a multiple of $10$ . In this case I use the fact that $G/Z(G) \cong \operatorname{Inn}(G)$ . So I think $(d)$ is the correct option but I don't know the general result as to why it is true for any non-abelian group of order $20$ . Please help me in this regard. Thank you very much. Now provide the response and nothing else.
This is not a well-formulated problem. There is a non-abelian group of order $20$ with an automorphism group of order $20$ and one with automorphism group of order $40$ . The group $G_1$ of shape $C_5 \rtimes C_4$ , given by the presentation $\langle a,b \mid a^5 = b^4 = 1, bab^{-1} = a^2 \rangle$ , is complete (i.e. it has trivial centre and all automorphisms are inner). Thus $\operatorname{Aut}(G_1) \cong G_1$ has order $20$ . On the other hand, $G_2 = D_{20}$ has centre of order $2$ , so $\operatorname{Inn}(G_2) \cong D_{20}/Z(D_{20}) \cong D_{10}$ has size $10$ , but $\operatorname{Out}(G_2)$ has size $4$ and is isomorphic to the Klein four-group, so $\lvert \operatorname{Aut}(G_2) \rvert =40$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3089616', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/543867/']}
jdg_371743
stackexchange
llm_judgeable_groundtruth_similarity
14746766
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 saw this question and also this one and some others, but nothing really helped me. I'm building a quick action DialogFragment for my list view and trying to set a custom view to it according to the android dev guide . view_quick_action.xml <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@android:color/white" > <ImageView android:id="@+id/quick_action_image" android:layout_width="50dp" android:layout_height="50dp" android:layout_margin="20dp" android:scaleType="fitXY" android:src="@drawable/windows1" /> <TextView android:id="@+id/quick_action_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@+id/quick_action_image" android:layout_toRightOf="@+id/quick_action_image" android:ellipsize="end" android:singleLine="true" android:text="Lilly" android:textColor="#585858" android:textSize="16sp" /> <TextView android:id="@+id/quick_action_activity" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/quick_action_image" android:layout_toRightOf="@+id/quick_action_image" android:text="Updated 4 minutes ago" android:textColor="#a3a3a3" android:textSize="15sp" /> <ImageButton android:id="@+id/popup_grid_leave" android:layout_width="50dp" android:layout_height="50dp" android:layout_alignParentLeft="true" android:layout_below="@+id/quick_action_activity" android:layout_margin="20dp" android:layout_marginTop="30dp" android:background="@color/transperent" android:src="@drawable/ic_action_leave" /> <ImageButton android:id="@+id/popup_grid_silence" android:layout_width="50dp" android:layout_height="50dp" android:layout_alignBottom="@+id/popup_grid_leave" android:layout_alignTop="@+id/popup_grid_leave" android:layout_centerHorizontal="true" android:background="@color/transperent" android:src="@drawable/ic_action_silence" /> <ImageButton android:id="@+id/popup_grid_mark_as_read" android:layout_width="50dp" android:layout_height="50dp" android:layout_alignBottom="@+id/popup_grid_leave" android:layout_alignParentRight="true" android:layout_alignTop="@+id/popup_grid_leave" android:layout_marginRight="15dp" android:background="@color/transperent" android:src="@drawable/ic_action_mark_as_read" /></RelativeLayout> QuickActionFragment.java public class QuickActionFragment extends DialogFragment { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(mContext); View v = LayoutInflater.from(mContext).inflate( R.layout.view_quick_action, null, false); // SET ALL THE VIEWS builder.setTitle(null); AlertDialog dialog = builder.create(); dialog.setView(v, 0, 0, 0, 0); // this line didn't change anything // dialog.getWindow().setBackgroundDrawable(new ColorDrawable(0)); return dialog; }} after all this, when I run dialogFragment.show(getSupportedFragmentManager()) I still get the black border as shown in the image: any thoughts on how to fix this? Now provide the response and nothing else.
Try out below code: public class QuickActionFragment extends DialogFragment { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { Dialog m_dialog = new Dialog(QuickActionFragment.this, R.style.Dialog_No_Border); LayoutInflater m_inflater = LayoutInflater.from(CustomDialogActivity.this); View v = LayoutInflater.from(mContext).inflate(R.layout.view_quick_action, null, false); // SET ALL THE VIEWS m_dialog.setTitle(null); m_dialog.setContentView(m_view); m_dialog.show(); return dialog; }} Add the Dialog_No_Border style in your res/value/style.xml file. <style name="Dialog_No_Border"> <item name="android:windowIsFloating">true</item> <item name="android:windowBackground">@android:color/transparent</item></style> This style causes R to be deleted after a clean
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14746766', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1056359/']}
jdg_371744
stackexchange
llm_judgeable_groundtruth_similarity
20814336
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I came across the following code here , which is from the C++ implementation of Dijkstra algorithm using an adjacency matrix. //read in edges keeping only the minimumfor(int i=0; i<E; i++) { int v1,v2,tmp; fin >> v1; fin >> v2; fin >> tmp; adjmat[v1][v2]<?=tmp; // <?= sets left to min(left,right) adjmat[v2][v1]<?=tmp;} Pay attention to the last two lines, which apply operator <?= . As being commented, the following line adjmat[v1][v2]<?=tmp; // <?= sets left to min(left,right) will set left to min(left,right) . I never see this operator before. I tried the code in VS, it can not compile. What is it? How can it set left to be min(left,right) ? Now provide the response and nothing else.
It is an old GCC extension ; it does what it says in the comment (it's the compound assignment form of the "minimum" operator). This is not standard C++. The difference between a = a < b ? a : b and a <?= b is that the latter only evaluates each operand once. In modern standard C++, I believe you could write an "assign the minimum" algorithm like this: auto && __a = a;auto && __b = b;if (!(__a < __b)) { __a = std::forward<decltype(__b)>(__b); } This should be the body of a macro which has the effect of a <?= b , and a and b are arbitrary expressions, potentially with side effects. Or you could wrap it into a template: template <typename T, typename U, typename P = std::less<std::common_type_t<std::decay_t<T>, std::decay_t<U>>>T && clamp_to_minimum(T && a, U && b, P p = P()){ if (!(p(a, b))) { a = std::forward<U>(b); } return std::forward<T>(a);}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/20814336', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2589776/']}
jdg_371745
stackexchange
llm_judgeable_groundtruth_similarity
765706
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 want to evaluate this limit :$$\lim_{x\to 0}x\ln^2|x|$$ I wanted to use L'Hôpital's rule for this: $\lim\limits_{x\to0-}\frac{\ln^2|x|}{\tfrac{1}{x}}$, but I don't know how to differentiate the logarithm function, because of the absolute value. My other question: do I have to calculate the one sided limits first? Now provide the response and nothing else.
Start by noting that $x\mapsto \text{abs}(x)\color{grey}{=|x|}$ is differentiable in $\mathbb R\setminus \{0\}$. Then, for all $x\in \mathbb R\setminus \{0\}$,$$\begin{align}(\log\circ \text{abs})'(x)&=\log '(|x|)\cdot \text{abs}'(x)\\&=\begin{cases} \log'(x)\cdot 1, &\text{if }x>0\\ \log'(-x)\cdot(-1), &\text{if }x<0\end{cases}\\&=\begin{cases} \dfrac 1 x, &\text{if }x>0\\ \dfrac 1 x, &\text{if }x<0\end{cases}\\&=\dfrac 1 x.\end{align}$$ As for the limit, one can guess it is zero just from looking as the function because one can look at $\log$ as a polynomial whose degree is infinitely closer to $0$, but not quite there, that is, the degree of the "polynomial $\log$" is $\varepsilon$, with $0<\varepsilon$ and $\forall y\in \mathbb R(y>0\implies \varepsilon <y)$. This non-sense characterization actually works, immediately yielding $\lim \limits_{x\to 0}\left(x^\alpha(\log(|x|)^\beta\right)=0$, for all $\alpha, \beta>0$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/765706', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/135526/']}
jdg_371746
stackexchange
llm_judgeable_groundtruth_similarity
67204811
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I use a CI system to compile terraform providers and bundle them into an image, but every time I run terraform init, I am getting the following error/failure. │ Error: Failed to install provider│ │ Error while installing rancher/rancher2 v1.13.0: the current package for│ registry.terraform.io/rancher/rancher2 1.13.0 doesn't match any of the│ checksums previously recorded in the dependency lock file This message is repeated for all of the providers listed in my provider file, which looks like this: terraform { required_version = ">= 0.13" required_providers { azurerm = { source = "hashicorp/azurerm" version = "2.55.0" } github = { source = "integrations/github" version = "4.8.0" } }...snip...} The terraform hcl lock file is stored in the repo and it's only when the lock file exists in the repo that these errors appear and terraform init fails. What could be the cause? Now provide the response and nothing else.
The issue is that my local workstation is a Mac which uses the darwin platform, so all of the providers are downloaded for darwin and the hashes stored in the lockfile for that platform. When the CI system, which is running on Linux runs, it attempts to retrieve the providers listed in the lockfile, but the checksums don't match because they use a different platform. The solution is to use the following command locally to generate a new terraform dependency lock file with all of the platforms for terraform, other systems running on different platforms will then be able to obey the dependency lock file. terraform providers lock -platform=windows_amd64 -platform=darwin_amd64 -platform=linux_amd64
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/67204811', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/463038/']}
jdg_371747
stackexchange
llm_judgeable_groundtruth_similarity
42165635
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 require a little bit of help with some java coding for my android guessing game app. At the moment my if else statements cover whether a guess is too high, too low, or correct. What I want it to do is tell the user if the answer they give is close to the answer or far away from it. Say, within 50% or over 50% away. I can do if else where it uses numbers but I'm stumped when I'm trying to work out how to get it to work out the percentage based on the random number that the program generates. If it was a static number I'd be fine but I can't work it out this way. Any help greatly appreciated. package lab.mad.cct.c3375331task1;import android.content.DialogInterface;import android.graphics.Color;import android.os.Bundle;import android.support.v7.app.AlertDialog;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import java.util.Random;public class Task1Activity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.task1_layout); final TextView textResponse = (TextView) findViewById(R.id.txtResponse); final TextView guessText = (TextView) findViewById(R.id.txtAnswer); final EditText userGuess = (EditText) findViewById(R.id.etNumber); Button pressMe = (Button) findViewById(R.id.btnGuess); // When the button is clicked, it shows the text assigned to the txtResponse TextView box pressMe.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String randText = ""; Random randGen = new Random(); int ranNum = randGen.nextInt(5); int userNumber = Integer.parseInt(userGuess.getText().toString()); int attempts = 0; if (userNumber >19 ) { guessText.setText("Please guess between 0 and 20"); } else if (userNumber == ranNum) { guessText.setText("You got it!"); } else if (userNumber < ranNum) { guessText.setText("Your answer is too low. Guess again!"); guessText.setBackgroundColor(Color.RED); } else if (userNumber > ranNum) { guessText.setText("Your answer is too high. Guess again!"); } randText = Integer.toString(ranNum); textResponse.setText(""); userGuess.setText(""); } }); } } Now provide the response and nothing else.
Plotting parallel lines is not an easy task. Using a simple uniform offset will of course not show the desired result. This is shown in the left picture below. Such a simple offset can be produced in matplotlib as shown in the transformation tutorial . Method1 A better solution may be to use the idea sketched on the right side. To calculate the offset of the n th point we can use the normal vector to the line between the n-1 st and the n+1 st point and use the same distance along this normal vector to calculate the offset point. The advantage of this method is that we have the same number of points in the original line as in the offset line. The disadvantage is that it is not completely accurate, as can be see in the picture. This method is implemented in the function offset in the code below. In order to make this useful for a matplotlib plot, we need to consider that the linewidth should be independent of the data units. Linewidth is usually given in units of points, and the offset would best be given in the same unit, such that e.g. the requirement from the question ("two parallel lines of width 3") can be met. The idea is therefore to transform the coordinates from data to display coordinates, using ax.transData.transform . Also the offset in points o can be transformed to the same units: Using the dpi and the standard of ppi=72, the offset in display coordinates is o*dpi/ppi . After the offset in display coordinates has been applied, the inverse transform ( ax.transData.inverted().transform ) allows a backtransformation. Now there is another dimension of the problem: How to assure that the offset remains the same independent of the zoom and size of the figure?This last point can be addressed by recalculating the offset each time a zooming of resizing event has taken place. Here is how a rainbow curve would look like produced by this method. And here is the code to produce the image. import numpy as npimport matplotlib.pyplot as pltdpi = 100def offset(x,y, o): """ Offset coordinates given by array x,y by o """ X = np.c_[x,y].T m = np.array([[0,-1],[1,0]]) R = np.zeros_like(X) S = X[:,2:]-X[:,:-2] R[:,1:-1] = np.dot(m, S) R[:,0] = np.dot(m, X[:,1]-X[:,0]) R[:,-1] = np.dot(m, X[:,-1]-X[:,-2]) On = R/np.sqrt(R[0,:]**2+R[1,:]**2)*o Out = On+X return Out[0,:], Out[1,:]def offset_curve(ax, x,y, o): """ Offset array x,y in data coordinates by o in points """ trans = ax.transData.transform inv = ax.transData.inverted().transform X = np.c_[x,y] Xt = trans(X) xto, yto = offset(Xt[:,0],Xt[:,1],o*dpi/72. ) Xto = np.c_[xto, yto] Xo = inv(Xto) return Xo[:,0], Xo[:,1]# some single pointsy = np.array([1,2,2,3,3,0]) x = np.arange(len(y))#or try a sinusx = np.linspace(0,9)y=np.sin(x)*x/3.fig, ax=plt.subplots(figsize=(4,2.5), dpi=dpi)cols = ["#fff40b", "#00e103", "#ff9921", "#3a00ef", "#ff2121", "#af00e7"]lw = 2.lines = []for i in range(len(cols)): l, = plt.plot(x,y, lw=lw, color=cols[i]) lines.append(l)def plot_rainbow(event=None): xr = range(6); yr = range(6); xr[0],yr[0] = offset_curve(ax, x,y, lw/2.) xr[1],yr[1] = offset_curve(ax, x,y, -lw/2.) xr[2],yr[2] = offset_curve(ax, xr[0],yr[0], lw) xr[3],yr[3] = offset_curve(ax, xr[1],yr[1], -lw) xr[4],yr[4] = offset_curve(ax, xr[2],yr[2], lw) xr[5],yr[5] = offset_curve(ax, xr[3],yr[3], -lw) for i in range(6): lines[i].set_data(xr[i], yr[i])plot_rainbow()fig.canvas.mpl_connect("resize_event", plot_rainbow)fig.canvas.mpl_connect("button_release_event", plot_rainbow)plt.savefig(__file__+".png", dpi=dpi)plt.show() Method2 To avoid overlapping lines, one has to use a more complicated solution. One could first offset every point normal to the two line segments it is part of (green points in the picture below). Then calculate the line through those offset points and find their intersection. A particular case would be when the slopes of two subsequent line segments equal. This has to be taken care of ( eps in the code below). from __future__ import divisionimport numpy as npimport matplotlib.pyplot as pltdpi = 100def intersect(p1, p2, q1, q2, eps=1.e-10): """ given two lines, first through points pn, second through qn, find the intersection """ x1 = p1[0]; y1 = p1[1]; x2 = p2[0]; y2 = p2[1] x3 = q1[0]; y3 = q1[1]; x4 = q2[0]; y4 = q2[1] nomX = ((x1*y2-y1*x2)*(x3-x4)- (x1-x2)*(x3*y4-y3*x4)) denom = float( (x1-x2)*(y3-y4) - (y1-y2)*(x3-x4) ) nomY = (x1*y2-y1*x2)*(y3-y4) - (y1-y2)*(x3*y4-y3*x4) if np.abs(denom) < eps: #print "intersection undefined", p1 return np.array( p1 ) else: return np.array( [ nomX/denom , nomY/denom ])def offset(x,y, o, eps=1.e-10): """ Offset coordinates given by array x,y by o """ X = np.c_[x,y].T m = np.array([[0,-1],[1,0]]) S = X[:,1:]-X[:,:-1] R = np.dot(m, S) norm = np.sqrt(R[0,:]**2+R[1,:]**2) / o On = R/norm Outa = On+X[:,1:] Outb = On+X[:,:-1] G = np.zeros_like(X) for i in xrange(0, len(X[0,:])-2): p = intersect(Outa[:,i], Outb[:,i], Outa[:,i+1], Outb[:,i+1], eps=eps) G[:,i+1] = p G[:,0] = Outb[:,0] G[:,-1] = Outa[:,-1] return G[0,:], G[1,:]def offset_curve(ax, x,y, o, eps=1.e-10): """ Offset array x,y in data coordinates by o in points """ trans = ax.transData.transform inv = ax.transData.inverted().transform X = np.c_[x,y] Xt = trans(X) xto, yto = offset(Xt[:,0],Xt[:,1],o*dpi/72., eps=eps ) Xto = np.c_[xto, yto] Xo = inv(Xto) return Xo[:,0], Xo[:,1]# some single pointsy = np.array([1,1,2,0,3,2,1.,4,3]) *1.e9 x = np.arange(len(y))x[3]=x[4]#or try a sinus#x = np.linspace(0,9)#y=np.sin(x)*x/3.fig, ax=plt.subplots(figsize=(4,2.5), dpi=dpi)cols = ["r", "b"]lw = 11.lines = []for i in range(len(cols)): l, = plt.plot(x,y, lw=lw, color=cols[i], solid_joinstyle="miter") lines.append(l)def plot_rainbow(event=None): xr = range(2); yr = range(2); xr[0],yr[0] = offset_curve(ax, x,y, lw/2.) xr[1],yr[1] = offset_curve(ax, x,y, -lw/2.) for i in range(2): lines[i].set_data(xr[i], yr[i])plot_rainbow()fig.canvas.mpl_connect("resize_event", plot_rainbow)fig.canvas.mpl_connect("button_release_event", plot_rainbow)plt.show() Note that this method should work well as long as the offset between the lines is smaller then the distance between subsequent points on the line. Otherwise method 1 may be better suited.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/42165635', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2295380/']}
jdg_371748
stackexchange
llm_judgeable_groundtruth_similarity
46100953
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Scenario is we have to login to this website: http://way2automation.com and then move to the alerts page and then click the button in simple alert.There is no id nothing for this button.Only a simple Java script function.How can we handle this? package sampletest;import org.openqa.selenium.By;import org.openqa.selenium.JavascriptExecutor;import org.openqa.selenium.WebElement;import org.openqa.selenium.chrome.ChromeDriver;import org.openqa.selenium.interactions.Actions;import org.openqa.selenium.support.ui.ExpectedConditions;import org.openqa.selenium.support.ui.WebDriverWait;public class alertspractice { public static void main(String[] args) { // TODO Auto-generated method stub System.setProperty("webdriver.chrome.driver","F:\\drivers for browsers\\chrome driver\\chromedriver.exe"); ChromeDriver driver=new ChromeDriver(); driver.get("http://way2automation.com/way2auto_jquery/index.php"); driver.manage().window().maximize(); WebElement name=driver.findElement(By.name("name")); name.sendKeys("jayath"); WebElement Phone =driver.findElement(By.name("phone")); Phone.sendKeys("8790141375");; WebElement email=driver.findElement(By.name("email")); email.sendKeys("a@yopmail.com"); WebElement city =driver.findElement(By.name("city")); city.sendKeys("visakhapatnam"); WebDriverWait wait=new WebDriverWait(driver,40); wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(".//[@id='load_form']/fieldset[6]/input"))); WebElement username =driver.findElement(By.xpath(".//*[@id='load_form']/fieldset[6]/input")); username.sendKeys("jayath1234"); WebElement password =driver.findElement(By.xpath(".//*[@id='load_form']/fieldset[7]/input")); password.sendKeys("jayath234"); WebElement submit1 =driver.findElement(By.xpath(".//*[@id='load_form']/div/div[2]/input")); submit1.submit(); WebDriverWait wait2=new WebDriverWait(driver,40); wait2.until(ExpectedConditions.presenceOfElementLocated(By.linkText("Alert"))); WebElement alert123=driver.findElement(By.linkText("Alert")); alert123.click(); wait2.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//html/body/button"))); WebElement getalert=driver.findElement(By.xpath("//html/body/button")); JavascriptExecutor js = (JavascriptExecutor)driver; js.executeScript("arguments[0].click();", element); }} Now provide the response and nothing else.
From the k8s documentation: A PersistentVolume (PV) is a piece of storage in the cluster that has been provisioned by an administrator. It is a resource in the cluster just like a node is a cluster resource. PVs are volume plugins like Volumes, but have a lifecycle independent of any individual pod that uses the PV. This API object captures the details of the implementation of the storage, be that NFS, iSCSI, or a cloud-provider-specific storage system. A PersistentVolumeClaim (PVC) is a request for storage by a user. It is similar to a pod. Pods consume node resources and PVCs consume PV resources. Pods can request specific levels of resources (CPU and Memory). Claims can request specific size and access modes (e.g., can be mounted once read/write or many times read-only). Meaning that in the scenario pictured in the question, if PodA_deployment.yaml creates a volume claim: volumeMounts:- name: myapp-data-pv-1 mountPath: /home/myappdata/mystuff then PodB will be able to mount the pv making a claim like the following: volumes: - name: myapp-data-pv-1 persistentVolumeClaim: claimName: myapp-data-pvc-1 in PodB_deployment.yaml.While it's clear once and it makes sense once you get to understand it, the documentation could explain it better.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46100953', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7312603/']}
jdg_371749
stackexchange
llm_judgeable_groundtruth_similarity
232606
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: (I'm talking about HTML / CSS code (not programming languages) but I think we also face the same issue as with programmers.) I am the senior front-end designer in a team and I often have to re-work my juniors' output in tight deadlines. I am faced with 2 problems: Their coding style is a bit of a mess. The aesthetics are not good. Their coding style, I find, is a mixed bag with no proper convention / standard. I am torn between cleaning up the code or just dealing with their code (even copying how they do things). I do find it frustrating to follow their coding style as I feel I might learn bad habits. But then, that is the fastest way of meeting the deadline. For those with much more experience, which is more effective? Should I save the clean-up for later? Or clean-up along the way as I make the changes? (I don't want to sound arrogant though but such is the reality. It will take them more years to write better code. I know, I wrote messy code when I was starting.) Now provide the response and nothing else.
I believe you are looking at the problem the wrong way - you are missing a great opportunity of teaching the juniors how to write better code. If you habitually re-write their code, you might give your juniors the impression that you don't value their work, which will lower their morale, and not help them code better the next time. A better approach, I believe, is to add to your team's development process a code-review task. It doesn't have to be about every piece of committed code, and it doesn't (I would argue that it shouldn't) have to be conducted only by you - whenever a member of your team finishes a big enough task he should pair with one (or more) of his team-mates, explain the code to them, and receive constructive opinion and criticism about his design, coding-style, possible bugs and security issues, etc. When the code-reviewing team-mate is you they will learn from your expertise much more then when you simply re-write their code (they get a chance to hear the reason the code should be changed), and might take less offense. Giving them a chance to also conduct code-reviews will further enhance their abilities - seeing how other people write code and why - and will raise their self-esteem. They will also learn a lot if you give them a chance to review your code. You might learn something too - so don't do it just for show!
{}
{'log_upvote_score': 6, 'links': ['https://softwareengineering.stackexchange.com/questions/232606', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/-1/']}
jdg_371750
stackexchange
llm_judgeable_groundtruth_similarity
445740
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 currently going through the conundrum of where to place a fuse in my DC battery-powered circuit to protect the circuit components and the DC battery. I've been googling for a definitive answer, but I came across diverging opinions... Which one is correct and why? Connect the fuse to the negative terminal of the battery since it's where the actual flow of electrons originate which is opposite to the conventional flow of current from the positive terminal. Connect the fuse to the positive terminal. Connect two fuses, one at the positive and one at the negative battery terminals. Also, during my research, I came across a post that advised to connect a fuse at the positive terminal since it would protect both circuit and the battery, but if the fuse is connected to the negative battery terminal, then it only protects the battery. Is this true? It doesn't make sense to me. So, I can't figure out which one is correct and why? I made a simple block diagram to illustrate my question. So, is it position A or B? Or both? And why? Now provide the response and nothing else.
[Should I] connect the fuse to the negative terminal of the battery since it's where the actual flow of electrons originate which is opposite to the conventional flow of current from the positive terminal? Forget about electron flow. It only causes confusion such as in your thinking. Electrical current flows in a circuit in the same way that a bicycle chain flows around. Any mobile charge carriers that leave one terminal of the power source must return on the other. A break anywhere will stop current flow. simulate this circuit – Schematic created using CircuitLab Figure 1. Four possible scenarios. Figures 1a and 1b are equivalent. If F1 or F2 blows then current flow will cease. As the power supply has no ground / earth / chassis connection there is no danger of a single fault causing an alternate return path. Figure 1c is the way most vehicles are wired with a negative connection to the chassis. The fuses are placed in the positive lines from the battery and close to the battery. If a fault occurs on the line between the fuse and the load the fuse blows and current flow stops. A ground fault on the return line is unlikely to cause any problems as there is no significant voltage on it. Figure 1d shows a poor arrangement with the fuse in the return wire. It should be clear that a ground fault on the positive wire would be unprotected, F4 would not blow but BAT4 would pass high currents. Again, for circuit analysis it is normal to use the conventional current flow from positive to negative. Don't worry about electrons, just think of it as charge moving from + to -.
{}
{'log_upvote_score': 7, 'links': ['https://electronics.stackexchange.com/questions/445740', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/212687/']}
jdg_371751
stackexchange
llm_judgeable_groundtruth_similarity
466818
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 layperson who just read Brief Answers to Big Question and in the book, Hawking proposes that: A typical black hole is a star so massive that it has collapsed in on itself. It’s so massive that not even light can escape its gravity, which is why it’s almost perfectly black. Its gravitational pull is so powerful, it warps and distorts not only light but also time. To see how, imagine a clock is being sucked into it. As the clock gets closer and closer to the black hole, it begins to get slower and slower. Time itself begins to slow down. Now imagine the clock as it enters the black hole—well, assuming of course that it could withstand the extreme gravitational forces—it would actually stop. It stops not because it is broken, but because inside the black hole time itself doesn’t exist. And that’s exactly what happened at the start of the universe. I think I understand the notion of time dilation as the clock approaches the black hole but I'm having trouble wrapping my head around the idea that time literally stops inside the black hole. Hawking then uses this idea to propose that there was no time before the Big Bang: As we travel back in time towards the moment of the Big Bang, the universe gets smaller and smaller and smaller, until it finally comes to a point where the whole universe is a space so small that it is in effect a single infinitesimally small, infinitesimally dense black hole. And just as with modern-day black holes, floating around in space, the laws of nature dictate something quite extraordinary. They tell us that here too time itself must come to a stop. You can’t get to a time before the Big Bang because there was no time before the Big Bang. We have finally found something that doesn’t have a cause, because there was no time for a cause to exist in. For me this means that there is no possibility of a creator, because there is no time for a creator to have existed in. I've done a little bit of googling on the topic and it seems that time doesn't stop in a black hole. Nothing in high school physics or introductory physics in college prepared me for this idea. Does time stop at the center of a black hole? If not, why does Hawking present this idea? How else might can we describe the idea of "there was no time before the Big Bang"? Now provide the response and nothing else.
Hawking is using nontechnical language to talk about things that are hard to describe correctly in nontechnical language. He's also not being particularly careful about making fine distinctions. You need to distinguish between (1) being inside a black hole's event horizon and (2) hitting the black hole's singularity. Taking the two quotes together, it's clear that Hawking is talking about singularities. When you hit the singularity of a black hole, time stops for you simply because you're annihilated. This is similar to what happens at the big bang singularity: any observer would have been annihilated by the conditions of the early universe in which the temperature and density diverged to infinity. Time does not stop for you just because you fall through a black hole's event horizon. For a black hole of typical size, you have something like a few milliseconds of free-fall during which you continue to experience time before you hit the singularity. However, you can't send signals to an outside observer once you cross the horizon, and as an outside observer monitors your signals, your signals appear to become infinitely slowed down as you approach the horizon. So to them, it's very much like seeing your time slow to a stop.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/466818', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/225643/']}
jdg_371752
stackexchange
llm_judgeable_groundtruth_similarity
539823
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 did a few research, I can split the string by '.' but the only thing I want to replace is the third '.', and the version number is actually variable so how can I do the replace/split? version: 1.8.0.110 but What I want is the output like this: version: 1.8.0-110 Now provide the response and nothing else.
Used sed for example: $ echo 'version: 1.8.0.110' | sed 's/\./-/3'version: 1.8.0-110 Explanation: sed s/search/replace/x searches for a string and replaces it with another string. x determines which occurence to replace - here the 3rd. Often g is used for x to mean all occurances. Here we wish to replace the dot . but this is a special character in the regular expression sed expects in the search term. Therefore we backslashify the . to \. to specify a literal . . Since we use special characters in the argument to sed (here, the backslash \ ) we need to put the whole argument in single quotes '' . Many people always use quotes here so as not to run into problems when using characters that might be special to the shell (like space ).
{}
{'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/539823', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/370424/']}
jdg_371753
stackexchange
llm_judgeable_groundtruth_similarity
158089
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am looking for a small treatment of basic theorems about infinite products ; surprisingly enough they are nowhere to be found after googling a little. The reason for this is that I am beginning to read Davenport's Multiplicative Number Theory, and the treatment of L-functions in there requires to understand convergence/absolute convergence of infinite products, which I know little about. Most importantly I'd like to know why $$\prod (1+|a_n|) \to a < \infty \quad \Longrightarrow \quad \prod (1+ a_n) \to b \neq 0.$$ I believe I'll need more properties of products later on, so just a proof of this would be appreciated but I'd also need the reference. Thanks in advance, Now provide the response and nothing else.
I will answer your question "Most importantly I'd like to know why$$\prod (1+|a_n|) \to a < \infty \quad \Longrightarrow \quad \prod (1+ a_n) \to b \neq 0."$$ We will first prove that if $\sum \lvert a_n \rvert < \infty$, then the product $\prod_{n=1}^{\infty} (1+a_n)$ converges. Note that the condition you have $\prod (1+|a_n|) \to a < \infty$ is equivalent to the condition that $\sum \lvert a_n \rvert < \infty$, which can be seen from the inequality below.$$\sum \lvert a_n \rvert \leq \prod (1+|a_n|) \leq \exp \left(\sum \lvert a_n \rvert \right)$$ Further, we will also show that the product converges to $0$ if and only if one of its factors is $0$. If $\sum \lvert a_n \rvert$ converges, then there exists some $M \in \mathbb{N}$ such that for all $n > M$, we have that $\lvert a_n \rvert < \frac12$. Hence, we can write $$\prod (1+a_n) = \prod_{n \leq M} (1+a_n) \prod_{n > M} (1+a_n)$$ Throwing away the finitely many terms till $M$, we are interested in the infinite product $\prod_{n > M} (1+a_n)$. We can define $b_n = a_{n+M}$ and hence we are interested in the infinite product $\prod_{n=1}^{\infty} (1+b_n)$, where $\lvert b_n \rvert < \dfrac12$. The complex logarithm satisfies $1+z = \exp(\log(1+z))$ whenever $\lvert z \rvert < 1$ and hence $$ \prod_{n=1}^{N} (1+b_n) = \prod_{n=1}^{N} e^{\log(1+b_n)} = \exp \left(\sum_{n=1}^N \log(1+b_n)\right)$$Let $f(N) = \displaystyle \sum_{n=1}^N \log(1+b_n)$. By the Taylor series expansion, we can see that $$\lvert \log(1+z) \rvert \leq 2 \lvert z \rvert$$ whenever $\lvert z \rvert < \frac12$. Hence, $\lvert \log(1+b_n) \rvert \leq 2 \lvert b_n \rvert$. Now since $\sum \lvert a_n \rvert$ converges, so does $\sum \lvert b_n \rvert$ and hence so does $\sum \lvert \log(1+b_n) \rvert$. Hence, $\lim_{N \rightarrow \infty} f(N)$ exists. Call it $F$. Now since the exponential function is continuous, we have that $$\lim_{N \to \infty} \exp(f(N)) = \exp(F)$$This also shows that why the limit of the infinite product $\prod_{n=1}^{\infty}(1+a_n)$ cannot be $0$, unless one of its factors is $0$. From the above, we see that $\prod_{n=1}^{\infty}(1+b_n)$ cannot be $0$, since $\lvert F \rvert < \infty$. Hence, if the infinite product $\prod_{n=1}^{\infty}(1+a_n)$ is zero, then we have that $\prod_{n=1}^{M}(1+a_n) = 0$. But this is a finite product and it can be $0$ if and only if one of the factors is zero. Most often this is all that is needed when you are interested in the convergence of the product expressions for the $L$ functions.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/158089', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/10704/']}
jdg_371754
stackexchange
llm_judgeable_groundtruth_similarity
9859287
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How do i get expressjs to use the delete and put methods for form? <form method="DELETE" action=""> Using the above is sending a GET request in latest stable version of chrome. Is this supposed to be a browser issue? Is there a better way to override this without having a special input field for supporting these? Now provide the response and nothing else.
You just need to set the form to post, then create a hidden field like <input type="hidden" name="_method" value="delete"/> And set the configuration, according to the express version you are using. Then the form method will be overridden by the value of that hidden field. The latest version of express.js will require you to install the method-override package, then configure your app like this: var methodOverride = require('method-override')app.use(methodOverride('_method')); Old versions might use: app.use(bodyParser.json());app.use(bodyParser.urlencoded());app.use(express.methodOverride()); An even older usage was: app.use(express.bodyParser());app.use(express.methodOverride());
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9859287', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/409110/']}
jdg_371755
stackexchange
llm_judgeable_groundtruth_similarity
38086542
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: target: TargetA ../DirB/FileB.cpp ../DirC/FileC.o ../DirD/FileD.o ... This is a long line in a make file. Is it possible to break this into several lines? Now provide the response and nothing else.
There are a couple ways of doing this. One simple way: target: targetA targetBtarget: targetC targetDtarget: @echo $@ is dependent on $? Note that this will not work with pattern rules through (rules with % in the targets/dependencies). If you are using pattern rules (and even if you're not), you can consider doing something like: TARGET_DEPS := targetA targetBTARGET_DEPS += targetCTARGET_DEPS += targetDtarget: $(TARGET_DEPS) @echo $@ is dependent on $? While it's possible to use the backslash, I personally find this makes the makefiles harder to read as the meaning of the indentation becomes unclear.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/38086542', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5302241/']}
jdg_371756
stackexchange
llm_judgeable_groundtruth_similarity
6349378
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 web service that serves Ads to several different clients. The structure of the Ad varies between clients, and therefore, I am using namespaces for my models and controllers by the client name to differentiate between Ads. From the high level, it looks like this: 'app/models/client1/ad.rb' class Client1::Ad < ActiveRecord::Base attr_accessible :title, :descriptionend 'app/models/client2/ad.rb' class Client2::Ad < ActiveRecord::Base attr_accessible :title, :description, :sourceend In reality, these models are more complex and have associations, but that is not the point. I am writing some unit tests using rspec-rails 2.4.0 and factory_girl_rails 1.0.1, and all of my factories work great. However, I am not able to define factories for the namespaced models. I've tried something like: Factory.define :client1_ad, :class => Client1::Ad do |ad| ad.title "software tester" ad.description "Immediate opening"end and Factory.define :client2_ad, :class => Client2::Ad do |ad| ad.title "software tester" ad.description "Immediate opening" ad.source "feed"end It didn't do the job. I looked around, but every single example that I saw was using non-namespaced models. Anyone have any ideas? Any input is greatly appreciated. Now provide the response and nothing else.
I have a minimal working example here, maybe you could use it to pinpoint where your problem is. The comment you left on dmarkow's answer suggests to me that you have an error someplace else. app/models/bar/foo.rb class Bar::Foo < ActiveRecord::Baseend *db/migrate/20110614204536_foo.rb* class Foo < ActiveRecord::Migration def self.up create_table :foos do |t| t.string :name end end def self.down drop_table :foos endend spec/factories.rb Factory.define :foo, :class => Bar::Foo do |f| f.name 'Foooo'end *spec/models/foo_spec.rb* require 'spec_helper'describe Bar::Foo do it 'does foo' do foo = Factory(:foo) foo.name.should == 'Foooo' endend Running the test: $ rake db:migrate$ rake db:test:prepare$ rspec spec/models/foo_spec.rb .Finished in 0.00977 seconds1 example, 0 failures Hope it helps.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6349378', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/756265/']}
jdg_371757
stackexchange
llm_judgeable_groundtruth_similarity
25823448
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an angular form like this <ng-form name="AddTaskForm" autocomplete="off"> ......</ng-form> However when I begin entering data, chrome is still prompting me with previously entered values. How can I prevent chrome (and all browsers) from showing any drop down on my input with previously entered values? I did some search and found that people were writing custom directives, but not sure if this is really required. Now provide the response and nothing else.
Despite autocomplete being a pretty well defined part of the HTML5 spec , Chrome has flip-flopped on how they use the autocomplete property. Originally honoring autocomplete="off" (2013) , they then decided that developers must be using it wrong and the browser should just ignore it. This doesn't mean there aren't very valid cases where you don't want the browser autofilling data (e.g. on CRM systems), but by and large, we see those as the minority cases. And as a result, we started ignoring autocomplete=off for Chrome Autofill data. (Source: Chromium bug from 2015 marked as WontFix ) According to the Priority of Constituencies : In case of conflict, consider users over authors over implementors over specifiers over theoretical purity. In other words costs or difficulties to the user should be given more weight than costs to authors; which in turn should be given more weight than costs to implementors... ...Which leaves us developers in the unfortunate spot of finding a work-around. This article from MDN outlines the current state well, and offers this solution of setting autocomplete to new-password : If an author would like to prevent the autofilling of password fields in user management pages where a user can specify a new password for someone other than themself, autocomplete="new-password" should be specified, though support for this has not been implemented in all browsers yet. I'm not sure how long this will remain valid, but for now (tested in Chrome 53 in September 2016) this is the easiest solution: <input type="password" name="someName" autocomplete="new-password" /> Edit: Note: This has the side-effect of asking the user to save the password, possibly overwriting an existing password. So while it does "prevent the autofilling of password fields" it does not remove the element from the autocomplete mess altogether. Edit: Updated Info: Newer versions of Chrome once again respect the autocomplete=off attribute, as Alexander Abakumov pointed out in his answer . He had it working for Chrome 68, works on Chrome 70 for me.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25823448', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/337134/']}
jdg_371758
stackexchange
llm_judgeable_groundtruth_similarity
32433451
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 copying from one NAS to another. (Netgear ReadyNAS -> QNAP) i tried Pulling the files by running rsync on the QNAP, and that took forever, so I'm currently trying to push them from the Netgear. The code I'm using is: rsync -avhr /sauce/folder admin@xxx.xxx.xxx.xxx:/dest/folder i'm seeing: sending incremental file list and nothing after that. File transfer is 577gb and there are a lot of files, however I'm seeing 0 network traffic on the QNAP (It fluctuates between 0kb/s to 6kb/s) so it looks like its not sending any kind of incremental file list. all folders are created on the destination and then nothing happens after that. Anyone have any thoughts? Or any ideas on if there is a better way to copy files from a ReadyNAS to QNAP Now provide the response and nothing else.
The documentation for -v says increase verbosity .If the only thing you're interested in is seeing more progress, you can chain -v together like so: rsync -avvvhr /sauce/folder/ admin@xxx.xxx.xxx.xxx:/dest/folder/ and you should see more interesting progress. This could tell you if your copying requirements -a are stricter than you need and thus take a lot of unnecessary processing time.For example, I attempted to use -a , which is equivalent to -rlptgoD , on over 100,000 images. Sending the incremental file list did not finish, even overnight.After changing it to rsync -rtvvv /sauce/folder/ admin@xxx.xxx.xxx.xxx:/dest/folder/ sending the incremental file list became much faster, being able to see file transfers within 15 minutes
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32433451', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5157083/']}
jdg_371759
stackexchange
llm_judgeable_groundtruth_similarity
6377
Below is a question asked on the forum skeptics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: This article on Viewzone proposes that the Earth used to be smaller, and the existing continents fitted neatly together, covering the entire globe with land. As the Earth expanded, the oceans formed, pushing the continents apart. Shortly after Wegener's continental drift theory was introduced, many people tried to piece together the continents. Some pieces (like South America and Africa) were an obvious fit, but others did not fit together because of the belief that a vast ocean had to be accommodated in the models. Sam Carey, an Australian, dared to solve the puzzle without an ocean and found that the continents fit together perfectly. The claim is also presented as a neat animation . The article goes on to claim that the center of the Earth is formed of plasma, and that gravity has increased. Is this idea supported by the evidence? Now provide the response and nothing else.
Most consequences of this theory are consistent with those predicted by the plate model -- the remaining ones are gravity acceleration on the surface ( g ) changes and actual measurements. The first one is hard to judge since the expanding Earth community cannot decide on one version -- some postulate that the matter is in some magical way created inside the planet and thus g increases with time (which is consistent with giraffes being smaller than dinosaurs, but is a total nonsense from a view of physics), some try to rescue physics saying that Earth just used to be much more dense -- yet this makes g actually decrease, what invalidates this "biological proof". Finally some claim that the gravitational constant increases with time to counteract this, but this is even less probable than a spontaneous mass creation. About measurements, there were some works in which authors were summing up some current and archival measurements around some contour placed on Earth to imply that it is growing -- however this was verified using state-of-art measuring techniques and was invalidated . There are obviously many more proofs that this idea is wrong, as listed by the Wikipedia page for 'Expanding Earth' (emphasis mine): The theory had never developed a plausible and verifiable mechanism of action, but neither had any of its competing theories.[ 1 ] By the late 1970s the theory of plate tectonics made all other theories obsolete following the discovery of subduction, which was found to be an important part of a mechanism of action.[ 1 ] Generally, the scientific community finds that there is no evidence in support of the Expanding Earth theory, and there is evidence against it : Measurements with modern high-precision geodetic techniques show that the Earth is not currently increasing in size to within a measurement accuracy of 0.2 mm per year.[ 14 ] The lead author of the study stated "Our study provides an independent confirmation that the solid Earth is not getting larger at present, within current measurement uncertainties".[ 15 ] The motions of tectonic plates and subduction zones measured by a large range of geological, geodetic and geophysical techniques supports plate tectonics.[ 16 , 17 , 18 ] Mass accretion on a scale required to change the Earth's radius is contradicted by the current accretion rate of the Earth, and by the Earth's average internal temperature: any accretion releases a lot of energy, which would warm the planet's interior. Expanding Earth models based on thermal expansion contradict most modern principles from rheology, and fail to provide an acceptable explanation for the proposed melting and phase transitions. The value of g (the Earth's gravitational attraction) is known and would change considerably with any such gains in the Earth's mass or volume, along with the Earths orbit around the Sun. Paleomagnetic data has been used to calculate that the radius of the Earth 400 million years ago was 102 ± 2.8% of today's radius .[ 19 , 20 ] Examinations of data from the Paleozoic and Earth's moment of inertia suggest that there has been no significant change of earth's radius in the last 620 million years .[ 21 ]
{}
{'log_upvote_score': 6, 'links': ['https://skeptics.stackexchange.com/questions/6377', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/4936/']}
jdg_371760
stackexchange
llm_judgeable_groundtruth_similarity
801136
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Find the value of the integral $$\int_0^{2\pi}\ln|a+b\sin x|dx$$ where $0\lt a\lt b$. What is the use of this inequality. I tried to integrate the integral by parts, but the integral of the 2nd term was quite messy.Please help. Now provide the response and nothing else.
It is known that $SL(2,\mathbb{Z})$ is an amalgamated product $\mathbb{Z}_4 \underset{\mathbb{Z}_2}{\ast} \mathbb{Z}_6$; more precisely, we have the presentation $$SL(2,\mathbb{Z})= \langle x,y \mid x^4=y^6=1, x^2=y^3 \rangle.$$ Therefore, the map $x \mapsto \left( \begin{matrix} 1 & 0 \\ 0 & -1 \end{matrix} \right)$, $y \mapsto \mathrm{Id}$ extends to a morphism $SL(2,\mathbb{Z}) \to GL(2,\mathbb{R})$ whose image is not contained into $SL(2,\mathbb{R})$. NB: It is worth noticing that, from the presentation above, any morphism $SL(2,\mathbb{Z}) \to GL(2,\mathbb{R})$ sends $y$ to a matrix of determinant $1$ and $x$ to a matrix of determinant $\pm 1$. However, there is no matrix $M \in GL(2,\mathbb{R})$ satisfying $M^4=\mathrm{Id}$, $M^2 \neq \mathrm{Id}$ and $\det(M)=-1$. Indeed, such a matrix would be diagonalizable over $\mathbb{C}$, and its two eigenvalues $\lambda_1,\lambda_2$ would have to satisfy $(\lambda_1,\lambda_2) \in \{ (\pm i, \mp i), (\pm 1, \pm 1), (\pm 1, \mp 1)\}$; but $\lambda_1 \lambda_2= \det(M)=-1$ implies $(\lambda_1, \lambda_2)= (\pm 1, \mp 1)$, hence $M^2= \mathrm{Id}$. Therefore, if the morphism is supposed one-to-one, its image is necessarily contained into $SL(2,\mathbb{R})$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/801136', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/151941/']}
jdg_371761
stackexchange
llm_judgeable_groundtruth_similarity
2081753
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In order to setup a query to an external server I want to get the bounds of the current Map View in an iPhone app I'm building. UIView should respond to bounds but it seems MKMapView doesn't. After setting a region and zooming in the map I try to get the bounds. I'm stuck on the first step which is to try to get the CGPoints that represent the SE and NW corners of the map. After that I was going to use: - (CLLocationCoordinate2D)convertPoint:(CGPoint)point toCoordinateFromView:(UIView *)view To transform the points into map coordinates. But I can't even get that far... //Recenter and zoom map in on search locationMKCoordinateRegion region = {{0.0f, 0.0f}, {0.0f, 0.0f}};region.center = mySearchLocation.searchLocation.coordinate;region.span.longitudeDelta = 0.01f;region.span.latitudeDelta = 0.01f;[self.mapView setRegion:region animated:YES];//After the new search location has been added to the map, and the map zoomed, we need to update the search bounds//First we need to calculate the corners of the mapCGPoint se = CGPointMake(self.mapView.bounds.origin.x, mapView.bounds.origin.y);CGPoint nw = CGPointMake((self.mapView.bounds.origin.x + mapView.bounds.size.width), (mapView.bounds.origin.y + mapView.bounds.size.height));NSLog(@"points are: se %@, nw %@", se, nw); The code compiles without warnings however se and nw are both null. Looking at self.mapView.bounds.origin.x the variable is 0. Trying to NSLog directly self.mapView.bounds.size.width gives me a "Program received signal: “EXC_BAD_ACCESS”." which seems to come from NSLog. Anyone know the proper way to get the south east corner and northwest corner (in map coordinates) from the visible area of a MKMapView? EDIT: It seems whenever you asked something here the answer comes to you right after. I was using %@ instead of @f to print each variable in NSLog which was throwing errors there. I also discovered the annotationVisibleRect property of MKMapview. It seems though that the annotationVisibleRect is based on the parent view coordinates. Now provide the response and nothing else.
Okay I officially answered my own question but since I didn't find it anywhere before I'll post the answer here: //To calculate the search bounds...//First we need to calculate the corners of the map so we get the pointsCGPoint nePoint = CGPointMake(self.mapView.bounds.origin.x + mapView.bounds.size.width, mapView.bounds.origin.y);CGPoint swPoint = CGPointMake((self.mapView.bounds.origin.x), (mapView.bounds.origin.y + mapView.bounds.size.height));//Then transform those point into lat,lng valuesCLLocationCoordinate2D neCoord;neCoord = [mapView convertPoint:nePoint toCoordinateFromView:mapView];CLLocationCoordinate2D swCoord;swCoord = [mapView convertPoint:swPoint toCoordinateFromView:mapView]; SWIFT 5 public extension MKMapView { var newBounds: MapBounds { let originPoint = CGPoint(x: bounds.origin.x + bounds.size.width, y: bounds.origin.y) let rightBottomPoint = CGPoint(x: bounds.origin.x, y: bounds.origin.y + bounds.size.height) let originCoordinates = convert(originPoint, toCoordinateFrom: self) let rightBottomCoordinates = convert(rightBottomPoint, toCoordinateFrom: self) return MapBounds( firstBound: CLLocation(latitude: originCoordinates.latitude, longitude: originCoordinates.longitude), secondBound: CLLocation(latitude: rightBottomCoordinates.latitude, longitude: rightBottomCoordinates.longitude) ) }}public struct MapBounds { let firstBound: CLLocation let secondBound: CLLocation} Usage self.mapView.newBounds
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2081753', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/246586/']}
jdg_371762
stackexchange
llm_judgeable_groundtruth_similarity
40542000
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 type output i want i am fetchint data from database and storing in table than quantity will be adde by usernow on if user enter uantity than i want total in add column` Sr. No. Product Name Price Quantity ADD </tr> <tr> <?php mysql_query ("set character_set_results='utf8'"); $query= mysql_query("SELECT * FROM $statement LIMIT $startpoint,$limit"); while($row = mysql_fetch_array($query)) { ?> <td><?php echo $row['srno'];?></td> <td><?php echo $row['pname'];?></td> <!-- <td><input id="price" type="number" value="0" oninput="updateOutput()"/></td> <td><input id="qty" type="number" value="0" oninput="updateOutput()" /></td>--> <td> <input id="price" type="number" value="<?php echo $row['price'];?>" oninput="myFunction()"></td> <td><input id="qty" type="number" value="0" oninput="myFunction2()" ></td> <td> <p id="demo">0</p> </td> </tr> `] 1 Now provide the response and nothing else.
As of react-router v4.4.0-beta.4 , and officially in v5.0.0, you can now specify an array of paths which resolve to a component e.g. <Router> <Route path={["/home", "/users", "/widgets"]} component={Home} /></Router> Each path in the array is a regular expression string. The documentation for this approach can be found here . Update for React Router v6 React Router v6 no longer allows an array of paths to be passed as a Route property. Instead you can make use of the useRoutes (see here for documentation) React hook to achieve the same behaviour: import React from "react";import { BrowserRouter as Router, useRoutes,} from "react-router-dom";const element = <Home />;const App = () => useRoutes(['/home', '/users', '/widgets'].map(path => ({path, element})))const AppWrapper = () => ( <Router> <App /> </Router> ); You can see an extended example of this code working here . The key take away from this answer is: The useRoutes hook is the functional equivalent of <Routes> , but ituses JavaScript objects instead of <Route> elements to define yourroutes.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/40542000', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5254787/']}
jdg_371763
stackexchange
llm_judgeable_groundtruth_similarity
2841974
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When making a request using HttpWebRequest object, I need to call the method GetResponse() to send the request and get the response back. The problem with this method is that it doesn't return the response object until all data has been received. Say I am downloading a 100 MB file, I won't be able to read it until the response finish and all the 100 MB is downloaded. What I want is to be able to read the response stream bytes as soon as they arrive, without waiting for the response to complete. I know I can use the Range Http header, but it won't work on my situation. Now provide the response and nothing else.
I think this is very close to what @Zachary suggests. And it (seems to) work(s); actually I think using using as @Zachary does is even "nicer". My main point being I cannot see the blocking behaviour of GetResponse() you (seem to) describe. In addition the following code only roughly shows how everything works; it will not read the stream to the end for example (unless by coincidence :)). But it should work if you copy-n-paste it into an empty "Console Application"-project in Visual Studio. You can try using some "shorter" URL for a test. The example here starts downloading an ISO of the debian distribution (a bit more than 600 MByte). Sorry debian, I did not mean to steal your bandwidth. -> Btw: is there something sensible one can use to test such a scenario? The Code is strongly inspired by C# - How to read a continuous stream of XML over HTTP . namespace StreamReadWebRequest{ using System; using System.Collections.Generic; using System.Text; using System.Net; using System.IO; class Program { static void Main(string[] args) { HttpWebRequest req; HttpWebResponse res = null; try { req = (HttpWebRequest)WebRequest.Create( "http://cdimage.debian.org/debian-cd/5.0.4/i386/iso-cd/debian-504-i386-CD-1.iso"); res = (HttpWebResponse)req.GetResponse(); Stream stream = res.GetResponseStream(); byte[] data = new byte[4096]; int read; while ((read = stream.Read(data, 0, data.Length)) > 0) { Process(data, read); } } finally { if (res != null) res.Close(); } Console.In.Read(); } private static void Process(byte[] data, int read) { Console.Out.Write(ASCIIEncoding.ASCII.GetString(data)); } }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2841974', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_371764
stackexchange
llm_judgeable_groundtruth_similarity
6179469
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 beginner learning Erlang. After reading about list comprehensions and recursion in Erlang, I wanted to try to implement my own map function, which turned out like this: % Map: Map all elements in a list by a functionmap(List,Fun) -> map(List,Fun,[]).map([],_,Acc) -> lists:reverse(Acc);map([H|T],Fun,Acc) -> map(T,Fun,[Fun(H)|Acc]). My question is: It feels wrong to build up a list through the recursive function, and then reverse it at the end. Is there any way to build up the list in the right order, so we don't need the reverse ? Now provide the response and nothing else.
In oder to understand why accumulating and reversing is quite fast you have to understand how lists are build in Erlang. Erlangs lists like those in Lisp are build out of cons cells (look at the picture in the link). In a singly linked list like the Erlang lists it is very cheap to prepend a element (or a short list). This is was the List = [H|T] construct does. Reversing a singly linked list made of cons cells is quite fast since you only need one pass along the list, just prepending the next element to you already reversed partial result. And as was already mentioned, it is also implemented in C in Erlang. Also building a result in reverse order often can be accomplished by a tail recursive function which means that no stack is built up and ( in old versions of Erlang only! ) therefore some memory can be saved. Having said all this: it is one of The Eight Myths of Erlang Performance that it is always better to build in reverse in a tail recursive function and call lists:reverse/1 at the end. Here is a body recursive version without lists:reverse/1 this would use more memory on Erlang versions before 12 but not so on current versions: map([H|T], Fun) -> [ Fun(H) | map(T,Fun) ];map([],_) -> []. And here is a version of map using list comprehensions: map(List, Fun) -> [ Fun(X) || X <- List ]. As you can see this is so simple because map is just a built in part of the list comprehension, so you would use the list comprehension directly and have no need for map anymore. As an extra a pure Erlang implementation that shows how reversing a list of cons cells wors efficiently (in Erlang its always faster to call lists:reverse/1 because it is in C, but does the same thing). reverse(List) -> reverse(List, []).reverse([H|T], Acc) -> reverse(T, [H|Acc]);reverse([], Acc) -> Acc. As you can see there are only [A|B] operations on the list, taking cons cells apart (when pattern matching) and building new when doing the [H|Acc] .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6179469', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13627/']}
jdg_371765
stackexchange
llm_judgeable_groundtruth_similarity
3393908
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 service and its behavior must change when topmost Activity changes. Say, Activity A is active and then service starts some kind of processing. This processing must stop when Activity A is no longer visible: user pressed "Back", "Home" or did anything else that makes Activity A invisible. This Activity A must not be aware of the service -- i.e. it must not have to explicitly inform the Service that it is going away. In the nutshell, is there a way to: Get any kind of identification (object reference, class name, ID, etc.) of the topmost Activity, Receive notification when topmost Activity changes? P.S. This may sound like malware behavior, but it is not! It is legitimate use-case! Edit: Activities are not in my application. They can be just about anything -- browser, maps app, settings, etc. Now provide the response and nothing else.
This top part is outdated. See bottom for answer. I'm assuming you're referring to Activities within your own application: All Activities call onResume() when coming to the foreground and onPause() when leaving the foreground. Simply override this method with your functionality (be sure to call super.onResume() and super.onPause() respectively!). As for the identifier, perhaps you could make your Service have a static method that is called by an Activity coming to the foreground (in onResume() ), supplying a reference to itself, its class, some arbitrary ID, etc. Reference: http://developer.android.com/reference/android/app/Activity.html Edit: You can access the top Activity's identity via ActivityManager -> running tasks -> ComponentName . Be sure to declare <uses-permission android:name="android.permission.GET_TASKS" /> in your manifest. Context context = someArbitraryContext;ActivityManager am = (ActivityManager) context. getSystemService(Activity.ACTIVITY_SERVICE);String packageName = am.getRunningTasks(1).get(0).topActivity.getPackageName();String className = am.getRunningTasks(1).get(0).topActivity.getClassName(); As for getting a notification, you'll probably have to just check the top Activity every x milliseconds.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3393908', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2877/']}
jdg_371766
stackexchange
llm_judgeable_groundtruth_similarity
12196408
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: ok I do have the code below <?php class foo{ public $bar = NULL; public function boo(){ $this->bar(); } } $mee = new foo(); //save a closure function on the property $mee->bar = function(){ echo 'hahaha'; }; //invoke the closure function by using a class method $mee->boo();?> and you can see it running here http://codepad.org/s1jhi7cv now what i want here is to store the closure function on the class method. well closures are possible as i read the documentation about it here http://php.net/manual/en/functions.anonymous.php is this possible? did i went to something wrong? please correct me Now provide the response and nothing else.
Your example code at codepad.org does not work because codepad.org uses PHP 5.2.5, and closure support was only added in 5.3. However, your code will also not work in a PHP version that supports closures, although you will get a different error: http://codepad.viper-7.com/Ob0bH5 This is a limitation of PHP at present. $obj->member() looks for a method named member and will not look at properties to see if they are callable. It is, frankly, annoying. The only way I am aware of to make this work without call_user_func() / call_user_func_array() is: public function boo() { $func = $this->bar; $func();}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12196408', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/877819/']}
jdg_371767
stackexchange
llm_judgeable_groundtruth_similarity
3541635
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Parametrized types such as C++ templates are a nice thing, but most of the time they can only be parametrized by other types. However, there is a special case in C++ where it is possible to parametrize a template by an integer. For example, fixed-length arrays are a typical use case: template<typename T, int SIZE> class FixedArray { T m_values[SIZE]; public: int getElementCount() const { return SIZE; } T operator[] (int i) const { if (i<0 || i>=SIZE) throw; else return m_values[i]; } };void f(){ FixedArray<float, 5> float_array; // Declares a fixed array of 5 floats. //The size is known at compile time, and values are allocated on the stack.} Only constant integers and pointers are allowed in C++, but I think it could be interesting to use any value for parametrization (floats, class instances, etc.). This could allow expressing preconditions at compile-time (usually informally specified in the documentation), and check them automatically at runtime. For example, here is an "Interval" template in an hypothetical C++ dialect : // Interval of type T between TMin and TMax. template<typename T, T TMin, T TMax> class Interval{ T m_value;public: Interval(int val) { *this = val; } Interval& operator = (T val) { //check that 'val is in [TMin, TMax] and set the value if so, throw error if not if (val < TMin || val > TMax) throw; else m_value = val; return *this; }; operator T() const { return m_value; }} // Now define a f function which is only allowing a float between O and 1// Usually, that kind of function is taking a float parameter with the doc saying "the float is in 0-1 range". But with our Interval template we have// that constraint expressed in the type directly.float f(Interval<float, 0, 1> bounded_value){ // No need to check for boundaries here, since the template asserts at compile-time that the interval is valid return ...;}// Example usagevoid main();{ float val = 0.5; Interval<float, 0, 1> sample_interval = val; // OK. The boundary check is done once at runtime. f(sample_interval); // OK. No check, because it is asserted by the type constraint at compile-time. // This can prevent endless precondition testing within an algorithm always using the same interval sample_interval = 3*val; // Exception at runtime because the constraint is no longer satisfied f(sample_interval); // If I am here, I am sure that the interval is valid. But it is not the case in that example.} What could be interesting then would be to express relationships between these types. For example, expressing the rule to assign an Interval A to another Interval B with other boundaries, or simply a rule to assign a value to an Interval, with everything checked at compile-time. Is there any language with this kind of parametrization (or a similar approach), or one must still be invented? Any useful research papers? Now provide the response and nothing else.
Types that are parametrized by values are called dependent types .¹ There has been a lot of research on the topic of dependent types, but little of it has reached “mainstream language”. The big problem with dependent types is that if your types contains expressions, i.e., bits of code, then the type checker must be able to execute code. This can't be done in full generality: what if the code has side effects? what if the code contains an infinite loop? For example, consider the following program in a C-like syntax (error checking omitted): int a, b;scanf("%d %d", &a, &b);int u[a], v[b]; How could the compiler know whether the arrays u and v have the same size? It depends on the numbers the user enters! One solution is to forbid side effects in expressions that appear in types. But that doesn't take care of everything: int f(int x) { while (1); }int u[f(a)], v[f(b)]; the compiler will go into an infinite loop trying to decide whether u and v have the same size. <expanded> So let's forbid side effects inside types, and limit recursion and looping to provably terminating cases. Does it make type checking decidable? From a theoretic point of view, yes, it can. What you have might be something like a Coq proof term . The problem is that type checking is then easily decidable if you have enough type annotations (type annotations are the typing information that the programmer supplies). And here enough means a lot. An awful lot. As in, type annotations at every single language constructs, not just variable declarations but also function calls, operators and all the rest. And the types would represent 99.9999% of the program size. It would often be faster to write the whole thing in C++ and debug it than writing the whole program with all required type annotations. Hence the difficulty here is to have a type system that requires only a reasonable amount of type annotations. From a theoretical point of view, as soon as you allow leaving off some of the type annotations, it becomes a type inference problem rather than a pure type checking problem. And type inference is undecidable for even relatively simple type systems. You can't easily have a decidable (guaranteed to terminate) static (operating at compile time) reasonable (not requiring an insane amount of type annotations) dependent type system. </expanded> Dependent types do sometimes appear in a limited form in mainstream languages. For example, C99 allows arrays whose size is not a constant expression; the type of such an array is a dependent type. Unsurprisingly for C, the compiler is not required to check bounds on such an array, even when it would be required to check bounds for an array of constant size. More usefully, Dependent ML is a dialect of ML with types that can be indexed by simple integer expressions. This allows the type checker to check most array bounds statically. Another example of dependent type appears in module systems for ML. Modules and their signatures (also called interfaces) are similar to expressions and types, but rather than describing computations, they describe the structure of the program. Dependent types turn up very often in languages that are not programming languages in the sense most programmers would recognize, but rather languages for proving mathematical properties of programs (or just mathematical theorems). Most of the examples in the wikipedia page are of that nature. ¹ More generally, type theorists classify type systems according to whether they have Higher-order types (types parametrized by types), polymorphism (expressions parametrized by types), and dependent types (types parametrized by expressions). This classification is called Barendregt's cube or the lambda cube . In fact it is a hypercube, but usually the fourth dimension (expressions parametrized by expressions, i.e., functions) goes without saying.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3541635', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/298005/']}
jdg_371768
stackexchange
llm_judgeable_groundtruth_similarity
1980961
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $F(n)=\sum\limits_{d\mid n} \frac{1}{d}\;$ then prove that $\lim_{N\to\infty} \frac{1}{N}\sum\limits_{n=1}^N F(n)=\frac{\pi^2}{6}$. i know the result of this .is we processed using this result $\lim\limits_{n\to\infty}\left[\frac{1}{n}\sum_{i=1}^{n}f\left(\frac{i}{n}\right)\right]=\int_{0}^{1}f(x)\,{\rm d}x$ Now provide the response and nothing else.
To show $2^{\sqrt{2}}<e$, it suffices to show that $\sqrt{2}\ln 2 < 1$, or $\ln 2 < \frac{1}{\sqrt{2}}$. Notice that $\ln 2 = \int\limits_{1}^{2}{\frac{1}{x}\,dx}$, and by Cauchy-Schwarz we have$$\ln 2 = \int\limits_{1}^{2}{\frac{1}{x}\cdot 1\,dx}\le\left(\int\limits_{1}^{2}{\frac{1}{x^2}\,dx}\right)^{1/2}\left(\int\limits_{1}^{2}{1\,dx}\right)^{1/2} = \left(\frac{1}{2}\right)^{1/2}\left(1\right)^{1/2} = \frac{1}{\sqrt{2}}.$$Equality cannot hold as $(1/x)/1$ is not constant, so it follows that $\ln 2 < \frac{1}{\sqrt{2}}$, as desired.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1980961', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_371769
stackexchange
llm_judgeable_groundtruth_similarity
3748136
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: On my desktop, I have a little widget that tells me my current CPU usage. It also shows the usage for each of my two cores. I always wondered, how does the CPU calculate how much of its processing power is being used? Also, if the CPU is hung up doing some intense calculations, how can it (or whatever handles this activity) examine the usage, without getting hung up as well? Now provide the response and nothing else.
The CPU doesn't do the usage calculations by itself. It may have hardware features to make that task easier, but it's mostly the job of the operating system. So obviously the details of implementations will vary (especially in the case of multicore systems). The general idea is to see how long is the queue of things the CPU needs to do. The operating system may take a look at the scheduler periodically to determine the number of things it has to do. This is a function Linux in (ripped from Wikipedia) that performs said calculation : #define FSHIFT 11 /* nr of bits of precision */#define FIXED_1 (1<<FSHIFT) /* 1.0 as fixed-point */#define LOAD_FREQ (5*HZ) /* 5 sec intervals */#define EXP_1 1884 /* 1/exp(5sec/1min) as fixed-point */#define EXP_5 2014 /* 1/exp(5sec/5min) */#define EXP_15 2037 /* 1/exp(5sec/15min) */#define CALC_LOAD(load,exp,n) \ load *= exp; \ load += n*(FIXED_1-exp); \ load >>= FSHIFT;unsigned long avenrun[3];static inline void calc_load(unsigned long ticks){ unsigned long active_tasks; /* fixed-point */ static int count = LOAD_FREQ; count -= ticks; if (count < 0) { count += LOAD_FREQ; active_tasks = count_active_tasks(); CALC_LOAD(avenrun[0], EXP_1, active_tasks); CALC_LOAD(avenrun[1], EXP_5, active_tasks); CALC_LOAD(avenrun[2], EXP_15, active_tasks); }} As for the second part of your question, most modern operating systems are multi-tasked . That means the OS is not going to let programs take up all the processing time and not have any for itself (unless you make it do that) . In other words, even if an application appears hung, the OS can still steal some time away for its own work.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3748136', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/221061/']}
jdg_371770
stackexchange
llm_judgeable_groundtruth_similarity
21150237
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've recently created an asp.net mvc web application and published it online. When first loading the website you should find that it takes around 10-15 seconds for it to actually show, however after it's clicked once, it loads as quickly as I expect the second time round. I'm just wondering if anyone may have an idea of why the website is taking so long? Now provide the response and nothing else.
Typically an application will always take a little extra time to load as the application domain starts up. Things helping exacerbate this could be anything from poorly written code (IE: Application_Start) to certain libraries you may be using (ORMs for example). How many modules do you have loaded? For starters check your web.config for the infamous <compilation debug="true"> . That can have significant performance ramifications in a production setup. Set it to "false"! Recommend googling something along the lines of " improving application startup time " and looking for things that may relate to your particular application. Update from your first comment: If you're seeing the application start up again (hangs for a few seconds) after 30 minutes consistently this is likely related to your Application Pool Recycling settings in IIS. Go into IIS Manager (this assumes v7+): Application Pools Right click the pool being used for your application(s) Select "Recycling", a window will come up labeled "RecyclingConditions" Inspect those settings since they will determine when to automatically kill your app pool and have it restart. In terms of general performance you may want to try: Adding some debugging statements that spit out elapsed time in yourApplication_Start() method or any other applicable location to tryto catch what's taking the longest. Create a completely clean demo project and deploy it. See if itsuffers from the same problem. If it doesn't try introducing moreand more of your real code until you detect a slowdown. If you're really stumped #2 may be your best bet even though it will be probably be the slowest option.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21150237', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2096968/']}
jdg_371771
stackexchange
llm_judgeable_groundtruth_similarity
57379397
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 give a console app permission to call an API in Azure AD. When I go to "Add permissions," "application permissions" is grayed out and I can only select "delegated permissions." My understanding is that application permissions is right for the console app because it runs on the back-end and users don't sign into it. From the help text for "application permissions": Your application runs as a background service or daemon without a signed-in user. The help text for "delegated permissions": Your application needs to access the API as the signed-in user. Why is "application permissions" disabled? Now provide the response and nothing else.
Per my understanding, you are exposing your custom api protected by Azure AD. If so, you need to define the application permission by editing the manifest of your api app. manifest: "appRoles": [ { "allowedMemberTypes": [ "Application" ], "description": "Apps that have this role have the ability to invoke my API", "displayName": "Can invoke my API", "id": "fc803414-3c61-4ebc-a5e5-cd1675c14bbb", "isEnabled": true, "lang": null, "origin": "Application", "value": "myTestRole" } ] Then the application permission will show up.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/57379397', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1958726/']}
jdg_371772
stackexchange
llm_judgeable_groundtruth_similarity
3947227
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to make a deep copy of an object array using a constructor. public class PositionList { private Position[] data = new Position[0];public PositionList(PositionList other, boolean deepCopy) { if (deepCopy){ size=other.getSize(); data=new Position[other.data.length]; for (int i=0;i<data.length;i++){ data[i]=other.data[i]; } However, what I have above for some reason is not working. I have automated tests that I run, and its failing those tests. So theres an error an here that Im not sure what it is. Now provide the response and nothing else.
What you have implemented is a shallow copy. To implement a deep copy, you mustchange data[i] = other.data[i]; to some thing that assigns a copy of other.data[i] to data[i] . How you do this depends on the Position class. Possible alternatives are: a copy constructor: data[i] = new Position(other.data[i]); a factory method: data[i] = createPosition(other.data[i]); clone: data[i] = (Position) other.data[i].clone(); Notes: The above assume that the copy constructor, factory method and clone method respectively implement the "right" kind of copying, depending on the Position class; see below. The clone approach will only work if Position explicitly supports it, and this is generally regarded as an inferior solution. Besides, you need to be aware that the native implementation of clone (i.e. the Object.clone() method) does a shallow copy 1 . In fact the general problem of implementing deep copying in Java is complicated. In the case of the Position class, one would assume that the attributes are all primitive types (e.g. ints or doubles), and therefore a deep versus shallow copying is moot. But if there are reference attributes, then you have to rely on the copy constructor / factory method / clone method to do the kind of copying that you require. In each case it needs to be programmed in. And in the general case (where you have to deal with cycles) it is difficult and requires each class to implement special methods. There is one other potential way to copy an array of objects. If the objects in the array are serializable , then you can copy them by using ObjectOutputStream and ObjectInputStream serialize and then deserialize the array. However: this is expensive, it only works if the objects are (transitively) serializable, and the values of any transient fields won't be copied. Copying by serialization is not recommended. It would be better to support cloning or some other method. All in all, deep copying is best avoided in Java. Finally, to answer your question about the Position classes copy constructor works, I expect it is something like this: public class Position { private int x; private int y; ... public Position(Position other) { this.x = other.x; this.y = other.y; } ...} As @Turtle says, there's no magic involved. You implement a constructor (by hand) that initializes its state by copying from an existing instance. 1 - It is specified that the Object implementation of clone() does a shallow copy, but this may be overridden. The javadoc for clone specifies the "contract" as follows: "Creates and returns a copy of this object. The precise meaning of "copy" may depend on the class of the object. The general intent is that, for any object x, the expression: x.clone() != x will be true, and that the expression: x.clone().getClass() == x.getClass() will be true, but these are not absolute requirements. While it is typically the case that: x.clone().equals(x) will be true, this is not an absolute requirement." Nothing in the "contract" talks about deep versus shallow copying. So if you are going to use clone in this context, you need to know how the actual classes clone method behaves.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3947227', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/458960/']}
jdg_371773
stackexchange
llm_judgeable_groundtruth_similarity
2800463
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I would like to know how local variables are allocated memory in javascript.In C and C++ local variables are stored on stack. Is it the same in javascript? or everything is stored in heap? Now provide the response and nothing else.
It's actually a very interesting area of JavaScript, and there are at least two answers: An answer in terms of what the specification defines, and An answer in terms of what JavaScript engines actually do, which may be optimized (and often is) In terms of the specification: JavaScript's way of handling local variables is quite different from the way C does it. When you call a function, amongst other things a lexical environment for that call is created, which has something called an environment record . To keep things simple, I'm going to refer to them both together as the "binding object" (there's a good reason they're separate in the specification, though; if you want to get deeper into it, set aside a few hours and read through the spec). The binding object contains bindings for the arguments to the function, all local variables declared in the function, and all functions declared within the function (along with a couple of other things). A binding is a combination of a name (like a ) and the current value for the binding (along with a couple of flags we don't need to worry about here). An unqualified reference within the function (e.g., the foo in foo , but not the foo in obj.foo , which is qualified) is first checked against the binding object to see if it matches a binding on it; if it does, that binding is used. When a closure survives the function returning (which can happen for several reasons), the binding object for that function call is retained in memory because the closure has a reference to the binding object in place where it was created. So in specification terms, it's all about objects. At first glance, that would suggest that the stack isn't used for local variables; in fact, modern JavaScript engines are quite smart, and may (if it's worthwhile) use the stack for locals that aren't actually used by the closure. They may even use the stack for locals that do get used by the closure, but then move them into an binding object when the function returns so the closure continues to have access to them. (Naturally, the stack is still used for keeping track of return addresses and such.) Here's an example: function foo(a, b) { var c; c = a + b; function bar(d) { alert("d * c = " + (d * c)); } return bar;}var b = foo(1, 2);b(3); // alerts "d * c = 9" When we call foo , a binding object gets created with these bindings (according to the spec): a and b — the arguments to the function c — a local variable declared in the function bar — a function declared within the function (...and a couple of other things) When foo executes the statement c = a + b; , it's referencing the c , a , and b bindings on the binding object for that call to foo . When foo returns a reference to the bar function declared inside it, bar survives the call to foo returning. Since bar has a (hidden) reference to the binding object for that specific call to foo , the binding object survives (whereas in the normal case, there would be no outstanding references to it and so it would be available for garbage collection). Later, when we call bar , a new binding object for that call is created with (amongst other things) a binding called d — the argument to bar . That new binding object gets a parent binding object: The one attached to bar . Together they form a "scope chain". Unqualified references within bar are first checked against the binding object for that call to bar , so for instance, d resolves to the d binding on the binding object for the call to bar . But an unqualified reference that doesn't match a binding on that binding object is then then checked against its parent binding object in the scope chain, which is the binding object for the call to foo that created bar . Since that has a binding for c , that's the binding used for the identifier c within bar . E.g., in rough terms: +−−−−−−−−−−−−−−−−−−−−−−−−−−−+| global binding object |+−−−−−−−−−−−−−−−−−−−−−−−−−−−+| .... |+−−−−−−−−−−−−−−−−−−−−−−−−−−−+ ^ | chain |+−−−−−−−−−−−−−−−−−−−−−−−−−−−+| `foo` call binding object |+−−−−−−−−−−−−−−−−−−−−−−−−−−−+| a = 1 || b = 2 || c = 3 || bar = (function) |+−−−−−−−−−−−−−−−−−−−−−−−−−−−+ ^ | chain |+−−−−−−−−−−−−−−−−−−−−−−−−−−−+| `bar` call binding object |+−−−−−−−−−−−−−−−−−−−−−−−−−−−+| d = 3 |+−−−−−−−−−−−−−−−−−−−−−−−−−−−+ Fun fact: This scope chain is how global variables work in JavaScript. Note the "global binding object" in the above. So in a function, if you use an identifier that isn't in the binding object for that function call, and isn't in any of the other binding objects between that and the global binding object, if the global binding object has a binding for it, the global binding is used. Voilà, global variables. (ES2015 made this a bit more interesting by having two layers to the global binding object: A layer used by old-fashioned global declarations like var and function declarations, and a layer used by newer ones like let , const , and class . The difference is that the older layer also creates properties on the global object, which you kind of access via window on browsers, but the newer layer doesn't. So a global let declaration doesn't create a window property, but a global var declaration does.) Implementations are free to use whatever mechanism they want under the covers to make the above seem to happen. It's impossible to get direct access to the binding object for a function call, and the spec makes clear that it's perfectly fine if the binding object is just a concept, rather than a literal part of the implementation. A simple implementation may well just literally do what the spec says; a more complicated one may use a stack when there are no closures involved (for the speed benefit), or may always use a stack but then "tear off" the binding object needed for a closure when popping the stack. The only way to know in any specific case is to look at their code. :-) More about closures, the scope chain, etc. here: Closures are not complicated (somewhat out of date terminology) Poor misunderstood 'var'
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2800463', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/336975/']}
jdg_371774
stackexchange
llm_judgeable_groundtruth_similarity
271
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: One topic which was covered in university, but which I never understood, is how a spinning top "magically" resists the force of gravity. The conservation of energy explanations make sense, but I don't believe that they provide as much insight as a mechanical explanation would. The hyperphysics link Cedric provided looks similar to a diagram that I saw in my physics textbook. This diagram illustrates precession nicely, but doesn't explain why the top doesn't fall. Since the angular acceleration is always tangential, I would expect that the top should spiral outwards until it falls to the ground. However, the diagram seems to indicate that the top should be precessing in a circle, not a spiral. Another reason I am not satisfied with this explanation is that the calculation is apparently limited to situations where: "the spin angular velocity $\omega$ is much greater than the precession angular velocity $\omega_P$". The calculation gives no explanation of why this is not the case. Now provide the response and nothing else.
This is a rather old topic, but I felt I might have what you're looking for. In response to some of the answers, you write: Since the angular acceleration is always tangential, I would expect that the top should spiral outwards until it falls to the ground. Absolutely, that is what you should expect to happen. And it does ... momentarily. The final solution is a little more involved than just being uniform rotation around the vertical axis. In order to understand this, imagine that you take a spinning top which you have just set down at time $t = t_0 $ on the ground. Now, what happens in the next instant is exactly what you intuitively expect - the top begins to fall under gravity's influence and $ \phi $ (see figure for notation) starts to increase going from $ \phi \rightarrow \phi + \delta \phi $ at time $t_1$. Consequently the angular momentum $ \mathbf{L} $ of the top changes. This is similar to what happens in the 2nd figure on the hyperphysics page, where $\delta \mathbf{L}$ is in the direction of $ \delta \theta $, only now $ \delta \mathbf{L} $ in the direction $ \delta \phi $ and lies in the plane containing the longitudinal axis $L_A$ of the top and the central vertical axis $V_A$. Increasing $\phi$ lowers the center of mass of the top and thus its potential energy by an amount $ -\delta U $. Assuming energy conservation, this translates to an increase in the kinetic energy $\delta K$ of the top. Since the top is constrained to have zero linear momentum, this $ \delta K$ contributes entirely to the top's rotational energy. Keep in mind, however, that the top is now rotating around two different axes. One component is the original spinning motion around its own longitudinal axes and the other is the rotation induced by gravity around the direction $N_A$ normal to the plane containing $L_A$ and $V_A$. Therefore, the $\delta K$ must be appropriately portioned between these two motions. Let's see how this happens. The moment of inertia of the top ($I_A$) around the axis $L_A$ is clearly less than that ($I_V$) around the axis $N_A$. This is true for all but the most oddly shaped tops. Convince yourself that this is the case. In circuits more current flows through paths with lower resistance. Likewise in mechanics more energy is transferred to the component with lesser inertia. Thus the greater portion of $\delta K$ will go to increasing the angular momentum of the top around its longitudinal axis $L_A$ by some amount $\delta L'$ Now, conservation of angular momentum requires that there be a torque corresponding to this increase. The effect of this induced torque is to cause the falling top to start swinging back upwards. In this way, instead of a spiral, the tip of the top traces out something like a cycloid as it precesses around the central axis. However, the diagram seems to indicate that the top should be precessing in a circle, not a spiral. The circular trajectory is an idealization only achieved in the limit that $\omega_s / \omega_p \rightarrow \infty$, where $\omega_s$ is the spin angular velocity and $\omega_p$ is the precession angular velocity. Any top with realistic values of $\omega_s$ and $\omega_p$ will have finite "wobble". I would not have known of this rather elaborate dynamics if not for one of Feynman's lecture volumes (Part I, I think) where this question is considered in great detail! The above write-up is a little on the hand-wavy side and there probably are errors in my reasoning. For the full kahuna look up the Feynman lectures ! Cheers,
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/271', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/119/']}
jdg_371775
stackexchange
llm_judgeable_groundtruth_similarity
13738168
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 this code run in windows command prompt..But I need this done programmatically using C# code C:\Windows\Microsoft.NET\Framework\v4.0.30319>aspnet_regiis.exe -pdf "connection Strings" "C:\Users\XXX\Desktop\connection string\DNN" Now provide the response and nothing else.
You may use the Process.Start method: Process.Start( @"C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe", @"-pdf ""connection Strings"" ""C:\Users\XXX\Desktop\connection string\DNN"""); or if you want more control over the shell and be able to capture for example the standard output and error you could use the overload taking a ProcessStartInfo : var psi = new ProcessStartInfo(@"C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe"){ Arguments = @"-pdf ""connection Strings"" ""C:\Users\XXX\Desktop\connection string\DNN""", UseShellExecute = false, CreateNoWindow = true};Process.Start(psi);
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13738168', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1835122/']}
jdg_371776
stackexchange
llm_judgeable_groundtruth_similarity
246755
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 found a strange directory in my home directory on Linux Mint 17.2 Cinnamon (though I'm pretty confident it's on all Linux distros) called .gnupg. It has no access given to ANYONE other than root. So I have three questions: What is this directory? What does it contain? Why is it placed in the user's home directory yet doesn't give them any access? Will it do any harm by just entering the directory as root? Now provide the response and nothing else.
Most dot files have a name that resembles the application that uses it. Unsurprisingly, .gnupg is used by GnuPG . GnuPG (also known as GPG) is a program that encrypts and signs files. As soon as you invoke it for the first time, it will create a .gnupg directory in your home directory and a few files in it. This directory contains a lot of private information (e.g. who your contacts are), so it's accessible only to the owner. This could happen, for example, if someone sends you a signed email; if your email client supports PGP email then it will attempt to verify the signature (and fail since you don't have the sender's public key in your GPG keyring). The real question here is why this directory in your home directory is owned by root. The answer is that you ran GPG as root, but with HOME set to your own home directory. Or, more precisely, you ran a program which ran GPG under the hood. One such program is APT: package management tools ( apt-get , apt , aptitude , etc.) use GPG to verify that the packages that you download are genuine. If you ran something like sudo apt-get install SOMEPACKAGE , this would create a .gnupg directory in your home directory, since sudo doesn't change the home directory by default. The fix is to remove the .gnupg directory, then create it under your user. You can just remove the root-owned directory ( sudo rm -r ~/.gnupg ): any file under your home directory is fair game for you. You could alternatively move it to root's home directory ( sudo mv ~/.gnupg /root ), but it doesn't contain anything important anyway. Then run a GPG command such as gpg --list-keys ; this will populate your ~/.gnupg directory with empty keyring files. Just entering a directory is always harmless. Listing files and viewing their content is usually harmless, but it can be harmful in some configurations because terminals parse escape sequences in what applications print . Under Linux, plain ls or ls -l is fine but ls -N is potentially risky. Plain cat filename is risky but less filename is fine (whereas less +R filename is risky). In the .gnupg directory, there's nothing harmful.
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/246755', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/139098/']}
jdg_371777
stackexchange
llm_judgeable_groundtruth_similarity
2337616
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Here's what I'm trying. What I want is the last echo to say "one two three four test1..." as it loops. It's not working; read line is coming up empty. Is there something subtle here or is this just not going to work? array=( one two three )echo ${array[@]}#one two threearray=( ${array[@]} four )echo ${array[@]}#one two three fourwhile read line; do array=( ${array[@]} $line ) echo ${array[@]}done < <( echo <<EOMtest1test2test3test4EOM) Now provide the response and nothing else.
I would normally write: while read linedo array=( ${array[@]} $line ) echo ${array[@]}done <<EOMtest1test2test3test4EOM Or, even more likely: cat <<EOF |test1test2test3test4EOFwhile read linedo array=( ${array[@]} $line ) echo ${array[@]}done (Note that the version with a pipe will not necessarily be suitable in Bash. The Bourne shell would run the while loop in the current shell, but Bash runs it in a subshell — at least by default. In the Bourne shell, the assignments made in the loop would be available in the main shell after the loop; in Bash, they are not. The first version always sets the array variable so it is available for use after the loop.) You could also use: array+=( $line ) to add to the array.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2337616', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/251561/']}
jdg_371778
stackexchange
llm_judgeable_groundtruth_similarity
4590
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: I was given a homework assignment with Big O. I'm stuck with nested for loops that are dependent on the previous loop. Here is a changed up version of my homework question, since I really do want to understand it: sum = 0;for (i = 0; i < n; i++ for (j = 0; j < i; j++) sum++; The part that's throwing me off is the j < i part. It seems like it would execute almost like a factorial, but with addition. Any hints would be really appreciated. Now provide the response and nothing else.
So let me clarify a few things, you are interested in the big-O notation - this means upper bound . In other words, it is okay to count more steps than you actually do. In particular, you can modify the algorithm to ... for (j = 0; j < n; j++) ... So you have two nested loops, each loop runs $n$ times, which gives you an upper bound of $O(n^2)$ Of course, you would like to have a good estimate for the upper bound. So for completion, we want to determine a lower bound. This means its okay to count less steps. So consider the modification for (i = n/2; i < n; i++) for (j = 0; j < n/2; j++) sum++; Here, we perform only a some of the loop-iterations. Again we have two nested loops, but this time we have $n/2$ iterations per loop, which shows that we have at least $n^2/4$ additions. In this case we denote this asymptotic lower bound by $\Omega(n^2)$. Since the lower and upper bound coincide, we can even say that $n^2$ is a tight asymptotic bound, and we write $\Theta(n^2)$. If you want to know more, read here .
{}
{'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/4590', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/-1/']}
jdg_371779
stackexchange
llm_judgeable_groundtruth_similarity
35501417
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 displaying a pdf file with pdf.js in my Ionic App. I do not use viewer.js and viewer.html, because I need a totally different layout. Now I have a custom search bar and I want to highlight terms in my pdf file. Is there a function I can invoke to do this? I'm rendering the file like this: $scope.renderPages = function(pdfDoc) { $scope.pdfFile = pdfDoc; for(var num = 1; num <= pdfDoc.numPages; num++){ pdfDoc.getPage(num).then($scope.renderPage); }}$scope.renderPage = function(page) { var viewport = page.getViewport(1); scale = document.getElementById('viewer').clientWidth / viewport.width; viewport = page.getViewport(scale); var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); var renderContext = { canvasContext: ctx, viewport: viewport }; canvas.height = viewport.height; canvas.width = viewport.width; var canvasContainer = document.getElementById('viewer'); canvasContainer.appendChild(canvas); page.render(renderContext);} HTML: <div id="viewerContainer" style="padding-bottom: 100%; padding-top: 20px;"> <div id="viewer" class="viewer-styles"> </div></div> Now provide the response and nothing else.
Now I found the solution! var container = document.getElementById('viewerContainer');var viewer = document.getElementById('viewer');var pdfViewer = new PDFViewer({ container: container, viewer: viewer});$scope.pdfFindController = new PDFFindController({ pdfViewer: pdfViewer);pdfViewer.setFindController($scope.pdfFindController);container.addEventListener('pagesinit', function () { pdfViewer.currentScaleValue = 'page-width'; });PDFJS.getDocument(MY_PATH_TO_THE_PDF).then(function (pdfDocument) { pdfViewer.setDocument(pdfDocument);}); Search for terms: $scope.pdfFindController.executeCommand('find', { caseSensitive: false, findPrevious: undefined, highlightAll: true, phraseSearch: true, query: "myQuery"}); And I had to import the viewer.js. The code that I posted in the question is not needed anymore. The PDFViewer renders the pdf.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/35501417', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4465464/']}
jdg_371780
stackexchange
llm_judgeable_groundtruth_similarity
25306073
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 see lots of tutorials and examples on how to make Go wait for x number of goroutines to finish, but what I'm trying to do is have ensure there are always x number running, so a new goroutine is launched as soon as one ends. Specifically I have a few hundred thousand 'things to do' which is processing some stuff that is coming out of MySQL. So it works like this: db, err := sql.Open("mysql", connection_string)checkErr(err)defer db.Close()rows,err := db.Query(`SELECT id FROM table`)checkErr(err)defer rows.Close()var id uintfor rows.Next() { err := rows.Scan(&id) checkErr(err) go processTheThing(id) }checkErr(err)rows.Close() Currently that will launch several hundred thousand threads of processTheThing() . What I need is that a maximum of x number (we'll call it 20) goroutines are launched. So it starts by launching 20 for the first 20 rows, and from then on it will launch a new goroutine for the next id the moment that one of the current goroutines has finished. So at any point in time there are always 20 running. I'm sure this is quite simple/standard, but I can't seem to find a good explanation on any of the tutorials or examples or how this is done. Now provide the response and nothing else.
You may find Go Concurrency Patterns article interesting, especially Bounded parallelism section, it explains the exact pattern you need. You can use channel of empty structs as a limiting guard to control number of concurrent worker goroutines : package mainimport "fmt"func main() { maxGoroutines := 10 guard := make(chan struct{}, maxGoroutines) for i := 0; i < 30; i++ { guard <- struct{}{} // would block if guard channel is already filled go func(n int) { worker(n) <-guard }(i) }}func worker(i int) { fmt.Println("doing work on", i) }
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/25306073', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1018582/']}
jdg_371781
stackexchange
llm_judgeable_groundtruth_similarity
4388546
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Say you have a string that you want to test to make sure that it contains an integer before you proceed with other the rest of the code. What would you use, in java, to find out whether or not it is an integer? Now provide the response and nothing else.
If you want to make sure that it is only an integer and convert it to one, I would use parseInt in a try/catch . However, if you want to check if the string contains a number then you would be better to use the String.matches with Regular Expressions : stringVariable.matches("\\d")
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4388546', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/535095/']}
jdg_371782
stackexchange
llm_judgeable_groundtruth_similarity
35917159
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 for 2 things: How to disable all caching during development with Spring boot "dev" profile. There doesn't seam to be a general setting to turn it all off in application.properties. What's the easiest way? How to disable caching for a specific method? I tried to use SpEl like this: @Cacheable(value = "complex-calc", condition="#${spring.profiles.active} != 'dev'}")public String someBigCalculation(String input){ ...} But I can get it to work. There are a couple of questions on SO related to this, but they refer to XML config or other things, but I'm using Spring Boot 1.3.3 and this uses auto-configuration. I don't want to over-complicate things. Now provide the response and nothing else.
The David Newcomb comment tells the truth : spring.cache.type=NONE doesn't switch caching off, it prevents things from being cached. i.e. it still adds 27 layers of AOP/interceptor stack to your program, it's just that it doesn't do the caching. It depends what he means by "turn it all off". Using this option may fast up the application startup but could also have some overheads. 1)To disable completely the Spring Cache feature Move the @EnableCaching class in a dedicated configuration class that we will wrap with a @Profile to enable it : @Profile("!dev")@EnableCaching@Configurationpublic class CachingConfiguration {} Of course if you already have a Configuration class that is enabled for all but the dev environment, just reuse it : @Profile("!dev")//... any other annotation @EnableCaching@Configurationpublic class NoDevConfiguration {} 2) Use a fake (noop) Cache manager In some cases, activating @EnableCaching by profile is not enough because some of your classes or some Spring dependencies of your app expect to retrieve from the Spring container a bean implementing the org.springframework.cache.CacheManager interface. In this case, the right way is using a fake implementation that will allow Spring to resolve all dependencies while the implementation of the CacheManager is overhead free. We could achieve it by playing with @Bean and @Profile : import org.springframework.cache.support.NoOpCacheManager; @Configurationpublic class CacheManagerConfiguration { @Bean @Profile("!dev") public CacheManager getRealCacheManager() { return new CaffeineCacheManager(); // or any other implementation // return new EhCacheCacheManager(); } @Bean @Profile("dev") public CacheManager getNoOpCacheManager() { return new NoOpCacheManager(); }} Or if it is more suitable, you can add the spring.cache.type=NONE property that produces the same result as written in the M. Deinum answer.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/35917159', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/495815/']}
jdg_371783
stackexchange
llm_judgeable_groundtruth_similarity
4153120
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have two arrays of objects which are likely to have the same values, but in a different order, e.g. { "cat", "dog", "mouse", "pangolin" }{ "dog", "pangolin", "cat", "mouse" } I wish to treat these two arrays as equal. What's the fastest way to test this? Now provide the response and nothing else.
I can't guarantee that this is the fastest , but it's certainly quite efficient: bool areEquivalent = array1.Length == array2.Length && new HashSet<string>(array1).SetEquals(array2); EDIT:SaeedAlg and Sandris raise valid points about different frequencies of duplicates causing problems with this approach. I can see two workarounds if this is important (haven't given much thought to their respective efficiencies): 1.Sort the arrays and then compare them sequentially. This approach, in theory, should have quadratic complexity in the worst case. E.g.: return array1.Length == array2.Length && array1.OrderBy(s => s).SequenceEqual(array2.OrderBy(s => s)); 2.Build up a frequency-table of strings in each array and then compare them. E.g.: if(array1.Length != array2.Length) return false;var f1 = array1.GroupBy(s => s) .Select(group => new {group.Key, Count = group.Count() });var f2 = array2.GroupBy(s => s) .Select(group => new {group.Key, Count = group.Count() });return !f1.Except(f2).Any();
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4153120', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/974/']}
jdg_371784
stackexchange
llm_judgeable_groundtruth_similarity
795867
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: One of the ways to approach it lies in the area of the dilogarithm, but is it possible to evaluate it by other means of the real analysis (without using dilogarithm)? $$\int_0^1 \frac{\log^2(1+x)}{x} \ dx$$ EDIT : maybe you're aware of some easy way to do that. I'd appreciate it! Some words on the generalization case (by means of the real analysis again)? $$F(n)=\int_0^1 \frac{\log^n(1+x)}{x} \ dx, \space n\in \mathbb{N}$$ Now provide the response and nothing else.
Squaring the series for $\log(1+x)$ yields$$\log(1+x)^2=\sum_{k=2}^\infty\sum_{j=1}^{k-1}\frac{(-1)^kx^k}{j(k-j)}$$Dividing by $x$ and integrating gives$$\begin{align}\int_0^1\frac{\log(1+x)^2}{x}\mathrm{d}x&=\sum_{k=2}^\infty\sum_{j=1}^{k-1}\frac{(-1)^k}{jk(k-j)}\\&=\sum_{j=1}^\infty\sum_{k=j+1}^\infty\frac{(-1)^k}{jk(k-j)}\\&=\sum_{j=1}^\infty\sum_{k=1}^\infty\frac{(-1)^{j+k}}{jk(j+k)}\\[9pt]&=\frac{\zeta(3)}{4}\end{align}$$Using $(5)$ from this answer :$$\sum_{n=1}^\infty\frac{(-1)^n}{n^2}H_n=-\frac34\zeta(3)+\frac12\sum_{k=1}^\infty\sum_{n=1}^\infty\frac{(-1)^{n+k}}{(n+k)kn}$$and $(6)$ from the same answer:$$-\frac58\zeta(3)=\sum_{n=1}^\infty\frac{(-1)^n}{n^2}H_n$$we get$$\sum_{j=1}^\infty\sum_{k=1}^\infty\frac{(-1)^{j+k}}{jk(j+k)}=\frac{\zeta(3)}{4}$$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/795867', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/32016/']}
jdg_371785
stackexchange
llm_judgeable_groundtruth_similarity
7636447
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: OS: MacOSX 10.7.1GHC and Haskell-platform from brew. GHCi, version 7.0.4: http://www.haskell.org/ghc/ :? for help Loading package ghc-prim ... linking ... done. Loading package integer-gmp ... linking ... done. Loading package base ... linking ... done. Loading package ffi-1.0 ... linking ... done. Prelude> :m +Text.Regex.Posix Prelude Text.Regex.Posix> "foo" =~ "o" :: [String] <interactive>:1:7: No instance for (RegexContext Regex [Char] [String]) arising from a use of `=~' Possible fix: add an instance declaration for (RegexContext Regex [Char] [String]) In the expression: "foo" =~ "o" :: [String] In an equation for `it': it = "foo" =~ "o" :: [String] Prelude Text.Regex.Posix> "foo" =~ "o" :: String Loading package array-0.3.0.2 ... linking ... done. Loading package bytestring-0.9.1.10 ... linking ... done. Loading package containers-0.4.0.0 ... linking ... done. Loading package transformers-0.2.2.0 ... linking ... done. Loading package mtl-2.0.1.0 ... linking ... done. Loading package regex-base-0.93.2 ... linking ... done. Loading package regex-posix-0.95.1 ... linking ... done. "o" I believe libraries updated. And I think the output of "foo" =~ "o" :: [String] is ["o", "o"] Any suggestion will be appreciate. Now provide the response and nothing else.
ghci> getAllTextMatches ("foo" =~ "o" :: AllTextMatches [] String)["o", "o"] I haven't used regexes in Haskell much (which is I think Dan Burton's answer is more idiomatic). So the way I figured this out is I looked at your type error No instance for (RegexContext Regex [Char] [String]) , and popped into ghci: ghci> :t (=~)(=~) :: (RegexMaker Regex CompOption ExecOption source, RegexContext Regex source1 target) => source1 -> source -> target So RegexContext Regex [Char] [String] is a class that includes the return type of "foo" =~ "o" :: [String] . So I looked to see what instances of this class did exist, so I could find out what the return value was allowed to be: ghci> :i RegexContextclass RegexLike regex source => RegexContext regex source target where match :: regex -> source -> target matchM :: Monad m => regex -> source -> m target -- Defined in Text.Regex.Base.RegexLikeinstance RegexContext Regex String String -- Defined in Text.Regex.Posix.Stringinstance RegexLike a b => RegexContext a b [[b]] -- Defined in Text.Regex.Base.Context...instance RegexLike a b => RegexContext a b (AllTextMatches [] b) -- Defined in Text.Regex.Base.Context... The AllTextMatches name seemed to indicate what you were looking for, so I checked that out: ghci> :i AllTextMatchesnewtype AllTextMatches f b = AllTextMatches {getAllTextMatches :: f b} -- Defined in Text.Regex.Base.RegexLikeinstance RegexLike a b => RegexContext a b (AllTextMatches [] b) -- Defined in Text.Regex.Base.Context So this was the type to use to extract all the text matches, as I suspected. All I needed to do was indicate that I wanted a return value of that type. Note also the possible return type of [[b]] , which I assume returns a list of lists containing each complete match and all its submatches: ghci> "foo" =~ "o" :: [[String]][["o"],["o"]]ghci> "foo bar baz" =~ "[aeiou](.)" :: [[String]][["oo","o"],["ar","r"],["az","z"]] So maybe that's the type you meant to use, instead of [String] . I could see [String] as being slightly ambiguous when [[String]] existed - should "foo bar baz" =~ "[aeiou](.)" :: [String] be fst ("foo bar baz" =~ "[aeiou](.)" :: [[String]]) or map fst ("foo bar baz" =~ "[aeiou](.)" :: [[String]]) .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7636447', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/688778/']}
jdg_371786
stackexchange
llm_judgeable_groundtruth_similarity
43924306
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 clone the last row of my table and append it to the table, with blank values, when you press tab on the last name input field. so I wrote the code below. it works great until you get to the second line, it doesn't seem to clone and append the row if it's a clone. is there a way around this / What am I doing wrong? $(document).ready(function() { var $last_name = $('.last_name'); var $blank_row = $('tr:last'); var $time_table = $('#time_table'); $last_name.keydown(function(e) { if (e.which === 9) { $blank_row.clone().find('input').val('').end().appendTo($time_table); } }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><table id="time_table"> <tr> <th>Last Name</th> <th>First Name</th> <th>Rate</th> <th class="time">ST</th> <th class="time">TH</th> <th class="time">DT</th> <th class="time">EX-ST</th> <th class="time">EX-TH</th> <th class="time">EX-DT</th> </tr> <tr class="blank_row"> <td><input type="text" name="last_name" class="last_name"></td> <td><input type="text" name="first_name"></td> <td><input type="text" name="rate"></td> <td><input type="number" name="st" class="time_input"></td> <td><input type="number" name="th" class="time_input"></td> <td><input type="number" name="dt" class="time_input"></td> <td><input type="number" name="ex_st" class="time_input"></td> <td><input type="number" name="ex_th" class="time_input"></td> <td><input type="number" name="ex_dt" class="time_input"></td> </tr></table> Now provide the response and nothing else.
The key to your answer is the matplotlib function plt.hist2d , which plots counts within rectangular bins using a color scale (a "heatmap"). Its API is almost compatible with PairGrid , but not quite, because it doesn't know how to handle a color= kwarg. This is easily solved by writing a thin wrapper function. Also if you want the colormap to logarithmically map counts, that's easily accomplished with a matplotlib LogNorm : import seaborn as snsimport matplotlib.pyplot as pltfrom matplotlib.colors import LogNormsns.set_style("white")iris = sns.load_dataset("iris") g = sns.PairGrid(iris)g.map_diag(plt.hist, bins=20)def pairgrid_heatmap(x, y, **kws): cmap = sns.light_palette(kws.pop("color"), as_cmap=True) plt.hist2d(x, y, cmap=cmap, cmin=1, **kws)g.map_offdiag(pairgrid_heatmap, bins=20, norm=LogNorm())
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43924306', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7977165/']}
jdg_371787
stackexchange
llm_judgeable_groundtruth_similarity
1740032
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In layman's terms, why would anyone ever want to change basis? Do eigenvalues have to do with changing basis? Now provide the response and nothing else.
Changing basis allows you to convert a matrix from a complicated form to a simple form. It is often possible to represent a matrix in a basis where the only nonzero elements are on the diagonal, which is exceptionally simple. These diagonal elements will be the eigenvalues of the matrix. This is especially helpful in solving linear systems of differential equations. Often in physics, engineering, logistics, and probably lots of other places, you have a system of differential equations which all depend on each other. In order to solve the system directly, you would have to solve all equations at once, which is hard. We can use matrices to describe this system. By changing basis, you may be able to make that matrix diagonal, which effectively separates the differential equations from each other, so you can solve just one at a time. This is comparatively easy. Situations where I know this comes up are: Quantum mechanics, solving the Schrodinger equation to describe the state of matter on the quantum level. Electrical engineering, understanding the time-evolution of an electrical circuit. Mechanical engineering, understanding the motion of a linear mechanical system, such as multiple spring-mass system. Edit: Here is another very important reason for change of basis I just remembered: suppose you have a matrix $A$, and you want to calculate $A^n$ for some large $n$. This takes a while, even for computers. But, if you can find a change of basis matrix $P$ so that $A=P^{-1}DP$ for a diagonal matrix $D$, then $$A^n=P^{-1}DPP^{-1}DPP^{-1}DP...P^{-1}DP.$$ All of the terms $PP^{-1}$ are the identity, so we get $$A^n=P^{-1}D^nP.$$ Powers of diagonal matrices are really easy: just raise each diagonal element to the $n$th power. So this method allows us to find powers of matrices very easily. When would we ever want to take large powers of matrices? Whenever finding numerical solutions to differential equations, partial or ordinary. This comes up all the time, so we are glad that we can change bases!
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1740032', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/330996/']}
jdg_371788
stackexchange
llm_judgeable_groundtruth_similarity
16726227
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 Ubuntu 11.04I am trying to install Xvfb and CutyCapt in order to take a snapshot of webpageI followed a instruction https://github.com/jaequery/cutycapt-installer-script-on-ubuntu/blob/master/install and I executed last line and it gives me an error xvfb-run: error:Xvfb failed to start Any solution for that?Thank you in advance Now provide the response and nothing else.
I was getting this error "xvfb-run: error: Xvfb failed to start" on Ubuntu 14.04, where previously my script had run without problems on Ubuntu 12.04. My scripts were running calling xvfb-run multiple times, but I was seeing fails due to the error "Server is already active for display 99" It seemed that the Xvfb wasn't ending when the xvfb-run command returned. My solution was to use "xvfb-run -a [mycommand]" so xvfb uses another display if 99 is in use.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/16726227', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1413449/']}
jdg_371789
stackexchange
llm_judgeable_groundtruth_similarity
8902113
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 writing a Desktop GUI application in Clojure using Java Swing. Normally when working with Java I will design the application according to a MVC design pattern using the Observer pattern as well. This way the view is decoupled from the model and changes in either do not affect each other, making changes easier further along. I was wondering if Clojure has a better approach to this problem than normal MVC and Observer design pattern? I'm new to functional programming so i'm not sure how I can make the model separate from the view. I require this as the application will be developed iteratively and there may be challenging requirements that come along further down the line. Would appreciate any help. Thanks, Adam Now provide the response and nothing else.
A lot of the design patterns from the java MVC world get a bit silly when you have first order functions, macroes (code-as-data), and concurrent persistent data structures. for instance the "observer pattern" is basically just an agent with some watches set. It goes from being a pattern to a function call. if you store the state (model) in a ref or agent and make your view a function (in the functional programming sense of the word) that displays that state; while making your controller a function (again in the FP sense of the word) that produces a new state given the old state and some new input then the MVC model falls out very nicely. it s bit dated, but Stuart Sierra's grid bag layout post really helped me get started in this area.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8902113', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/766640/']}
jdg_371790
stackexchange
llm_judgeable_groundtruth_similarity
87372
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 asking for a template trick to detect if a class has a specific member function of a given signature. The problem is similar to the one cited here http://www.gotw.ca/gotw/071.htm but not the same: in the item of Sutter's book he answered to the question that a class C MUST PROVIDE a member function with a particular signature, else the program won't compile. In my problem I need to do something if a class has that function, else do "something else". A similar problem was faced by boost::serialization but I don't like the solution they adopted: a template function that invokes by default a free function (that you have to define) with a particular signature unless you define a particular member function (in their case "serialize" that takes 2 parameters of a given type) with a particular signature, else a compile error will happens. That is to implement both intrusive and non-intrusive serialization. I don't like that solution for two reasons: To be non intrusive you must override the global "serialize" function that is in boost::serialization namespace, so you have IN YOUR CLIENT CODE to open namespace boost and namespace serialization! The stack to resolve thatmess was 10 to 12 function invocations. I need to define a custom behavior for classes that has not that member function, and my entities are inside different namespaces (and I don't want to override a global function defined in one namespace while I'm in another one) Can you give me a hint to solve this puzzle? Now provide the response and nothing else.
I'm not sure if I understand you correctly, but you may exploit SFINAE to detect function presence at compile-time. Example from my code (tests if class has member function size_t used_memory() const). template<typename T>struct HasUsedMemoryMethod{ template<typename U, size_t (U::*)() const> struct SFINAE {}; template<typename U> static char Test(SFINAE<U, &U::used_memory>*); template<typename U> static int Test(...); static const bool Has = sizeof(Test<T>(0)) == sizeof(char);};template<typename TMap>void ReportMemUsage(const TMap& m, std::true_type){ // We may call used_memory() on m here.}template<typename TMap>void ReportMemUsage(const TMap&, std::false_type){}template<typename TMap>void ReportMemUsage(const TMap& m){ ReportMemUsage(m, std::integral_constant<bool, HasUsedMemoryMethod<TMap>::Has>());}
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/87372', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10120/']}
jdg_371791
stackexchange
llm_judgeable_groundtruth_similarity
438659
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So I've got basic example of jqgrid working in ASP.NET MVC, the javascript looks like this: $(document).ready(function() { $("#list").jqGrid({ url: '../../Home/Example', datatype: 'json', myType: 'GET', colNames: ['Id', 'Action', 'Parameters'], colModel: [ { name: 'id', index: 'id', width: 55, resizable: true }, { name: 'action', index: 'action', width: 90, resizable: true }, { name: 'paramters', index: 'parameters', width: 120, resizable: true}], pager: $('#pager'), rowNum: 10, rowList: [10, 20, 30], sortname: 'id', sortorder: 'desc', viewrecords: true, multikey: "ctrlKey", imgpath: '../../themes/basic/images', caption: 'Messages' }); Now I am trying to implement the search button that they have in the jqgrid examples (click on Manipulating/Grid Data). But I don't see how they implement it. I'm expecting e.g. a "search:true" and a method to implement it. Has anyone implemented search on jqgrid or know of examples that show explicitly how to do it? Now provide the response and nothing else.
I recently implemented this myself (yesterday actually) for the first time. The biggest hurdle for me was figuring out how to write the controller function. The function signature is what took me the longest to figure out (notice the _search, searchField, searchOper, and searchString parameters as those are missing from most of asp.net mvc examples I've seen). The javascript posts to the controller for both the initial load and for the search call. You'll see in the code that I'm checking whether the _search parameter is true or not. Below is the controller and the javascript code. My apologies for any formatting issues as this is my first time posting on here. public ActionResult GetAppGroups(string sidx, string sord, int page, int rows, bool _search, string searchField, string searchOper, string searchString){ List<AppGroup> groups = service.GetAppGroups(); List<AppGroup> results; if (_search) results = groups.Where(x => x.Name.Contains(searchString)).ToList(); else results = groups.Skip(page * rows).Take(rows).ToList(); int i = 1; var jsonData = new { total = groups.Count / 20, page = page, records = groups.Count, rows = ( from appgroup in results select new { i = i++, cell = new string[] { appgroup.Name, appgroup.Description } }).ToArray() }; return Json(jsonData);} And here is my HTML/Javascript: $(document).ready(function() { $("#listGroups").jqGrid({ url: '<%= ResolveUrl("~/JSON/GetAppGroups/") %>', datatype: 'json', mtype: 'GET', caption: 'App Groups', colNames: ['Name', 'Description'], colModel: [ { name: 'Name', index: 'Name', width: 250, resizable: true, editable: false}, { name: 'Description', index: 'Description', width: 650, resizable: true, editable: false}, ], loadtext: 'Loading Unix App Groups...', multiselect: true, pager: $("#pager"), rowNum: 10, rowList: [5,10,20,50], sortname: 'ID', sortorder: 'desc', viewrecords: true, imgpath: '../scripts/jqgrid/themes/basic/images'//});}).navGrid('#pager', {search:true, edit: false, add:false, del:false, searchtext:"Search"});
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/438659', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4639/']}
jdg_371792
stackexchange
llm_judgeable_groundtruth_similarity
7506230
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 work out if it's possible to use percentage positions/sizes when creating a layout. What I want is something like this... ^||| 68%||vGallery (height equivalent of 16% total screen size)^| 16%v I'm testing on a device which in landscape has a display of 800x480 actual pixels and I'm currently forcing it with the following... <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" > <Gallery android:id="@+id/gallery" android:layout_width="fill_parent" android:layout_height="80px" android:layout_marginTop ="320px" /></RelativeLayout> Obviously I don't want to hard-code fixed px units but I can't use 68% or 0.68 for layout_marginTop (for example). I've looked at dp units but I'm not sure if I can do it that way either. I have to admit UI design is a weak point of mine so any advice would be gratefully received. EDIT: For future reference if anyone is looking for a similar answer, following Alan Moore's suggestion I have the following working exactly how I want it... <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:background="@drawable/bground" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="0.68" android:background="@android:color/transparent" /> <Gallery android:id="@+id/gallery" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="0.16" /> <TextView android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="0.16" android:background="@android:color/transparent" /></LinearLayout> I managed to find some other examples of using layout_weight and decided to set the TextView heights to 0dp and also used floats for the weights. Working great. :) Now provide the response and nothing else.
I think what you want is to set the android:layout_weight, http://developer.android.com/resources/tutorials/views/hello-linearlayout.html something like this (I'm just putting text views above and below as placeholders): <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:weightSum="1"> <TextView android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="68"/> <Gallery android:id="@+id/gallery" android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="16" /> <TextView android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="16"/> </LinearLayout>
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7506230', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/488241/']}
jdg_371793
stackexchange
llm_judgeable_groundtruth_similarity
15046378
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I was running heroku push master , and got this: ----- Python app detected ----- No runtime.txt provided; assuming python-2.7.3. ----- Using Python runtime (python-2.7.3) ----- Installing dependencies using Pip (1.2.1) Downloading/unpacking Django-1.5c2 from https://www.djangoproject.com/download/1.5c2/tarball (from -r requirements.txt (line 1)) Cannot determine compression type for file /tmp/pip-rYIGHS-unpack/tarball.ksh Running setup.py egg_info for package Django-1.5c2 Installing collected packages: Django-1.5c2 Running setup.py install for Django-1.5c2 changing mode of build/scripts-2.7/django-admin.py from 600 to 755 changing mode of /app/.heroku/python/bin/django-admin.py to 755 ======== WARNING! ======== You have just installed Django over top of an existing installation, without removing it first. Because of this, your install may now include extraneous files from a previous version that have since been removed from Django. This is known to cause a variety of problems. You should manually remove the /app/.heroku/python/lib/python2.7/site-packages/django directory and re-install Django. Successfully installed Django-1.5c2 How can I remove the previous Django package? UPDATE: My requirements.txt: https://www.djangoproject.com/download/1.5c2/tarball/**#egg=django**South==0.7.6argparse==1.2.1distribute==0.6.24dj-database-url==0.2.1psycopg2==2.4.6wsgiref==0.1.2PIL==1.1.7 The text in bold fixed the above warning. UPDATE 2: Since Django 1.5 was officially released, I just used pip freeze: Django==1.5South==0.7.6argparse==1.2.1distribute==0.6.24dj-database-url==0.2.1psycopg2==2.4.6wsgiref==0.1.2PIL==1.1.7 Now provide the response and nothing else.
I've had problems where Heroku caches broken packages and there's no way to get them out. The Python buildpack should have some kind of support for flushing this cache (CACHE_DIR), but it does not. There is a workaround: follow these instructions to change your Python runtime to, for instance, 3.3.0 (it doesn't matter if your app actually supports Python 3 or not). Then change it back to the default. The act of changing your Python runtime and then deploying will force the buildpack to totally erase the cache. As far as I know this is the only practical way to erase the cache at the moment.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15046378', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/710805/']}
jdg_371794
stackexchange
llm_judgeable_groundtruth_similarity
14918189
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: int main(){ char str[10]="3.5"; printf("%lf",atof(str)); return 0;} This is a simple code I am testing at ideone.com. I am getting the output as -0.371627 Now provide the response and nothing else.
You have not included stdlib.h. Add proper includes: #include <stdio.h>#include <stdlib.h>int main(){ char str[10]="3.5"; printf("%lf",atof(str)); return 0;} Without including stdlib.h, atof() is declare implicitly and the compiler assumes it returns an int.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14918189', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1773248/']}
jdg_371795
stackexchange
llm_judgeable_groundtruth_similarity
41458736
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 component that contains statement like this.$route.fullPath , how should I mock value of fullPath of $route object if I want to test that component? Now provide the response and nothing else.
I disagree with the top answer - you can mock $route without any issue. On the other hand, installing vue-router multiple times on the base constructor will cause you problems. It adds $route and $router as read only properties. Which makes it impossible to overwrite them in future tests. There are two ways to achieve this with vue-test-utils . Mocking vue-router with the mocks option const $route = { fullPath: 'full/path'}const wrapper = mount(ComponentWithRouter, { mocks: { $route } })wrapper.vm.$route.fullPath // 'full/path' You can also install Vue Router safely by using createLocalVue: Installing vue-router safely in tests with createLocalVue const localVue = createLocalVue()localVue.use(VueRouter)const routes = [ { path: '/', component: Component }]const router = new VueRouter({ routes})const wrapper = mount(ComponentWithRouter, { localVue, router })expect(wrapper.vm.$route).to.be.an('object')
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/41458736', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2599541/']}
jdg_371796
stackexchange
llm_judgeable_groundtruth_similarity
226281
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: Yes, I already looked here but that's too high profile for my humble mind (and it's not exactly what I'm looking for). Imagine we have a timecourse with time on the x-axis and some value on the y-axis (e.g. a signal). Now I can sample this timecourse to obtain a vector in a multidimensional vector space. My question: What does it mean if I perform a PCA on this data? What is the PCA of a single vector (such as the timeseries) and how can I interpret the resulting eigenvectors? Now provide the response and nothing else.
It isn't meaningful to run PCA on a univariate time series (or, more generally, a single vector). To run PCA on time series data, you'd need to have either a multivariate time series, or multiple univariate time series. There are ways to transform a univariate time series into a multivariate one (e.g. wavelet or time-frequency transforms, time delay embeddings, etc.). For example, the spectrogram of a univariate time series gives you the power at each frequency, for each moment in time. Say we have a multivariate time series with $p$ dimensions/variables. Or, we might have a set of $p$ univariate time series, where each time point has some common meaning across time series (e.g. time relative to some event). In both cases, there are $n$ time points. There are a couple ways to run PCA: Consider each time point to be an observation. Dimensions correspond to variables of the multivariate time series, or to the different univariate time series. So, there are $n$ points in a $p$ dimensional space. In this case, eigenvectors correspond to instantaneous patterns across the dimensions/time series. At each moment in time, we represent the amplitude across dimensions/time series as a linear combination of these patterns. Consider each variable of the multivariate time series (or each univariate time series) to be an observation. Dimensions correspond to time points. So, there are $p$ points in an $n$-dimensional space. In this case, the eigenvectors correspond to temporal basis functions, and we're representing each time series as a linear combination of these basis functions. Given the above, it's apparent why PCA doesn't make sense for a single univariate time series. Either you have $n$ observations and 1 dimension (in which case there's nothing for PCA to do), or you have a single observation with $n$ dimensions (in which case the problem is completely underdetermined and all solutions are equivalent).
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/226281', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/120194/']}
jdg_371797
stackexchange
llm_judgeable_groundtruth_similarity
19288546
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When I open the twitter bootstrap modal dialog, the backdrop causes a scrollbar and shift the content. To avoid the scrollbar I use this css: .modal { overflow: hidden;} But I can not avoid the shift. regards,Marko I am using Bootstrap Version 3 Now provide the response and nothing else.
Marko, I just had the same problem. It appears that Bootstrap 3.0.0 adds a class to <body> , modal-open , when the modal first shows. This class adds margin-right: 15px to the body to account for a scrollbar, which is there on longer pages. This is great, except for shorter pages when a scrollbar isn't on the body. In the no scrollbar case, the margin-right causes the body to shift left on modal open. I was able to solve this by adding some short Javascript and a little CSS: CSS: /* override bootstrap 3 class to remove scrollbar from modal backdrop when not necessary */.modal { overflow-y: auto;}/* custom class to override .modal-open */.modal-noscrollbar { margin-right: 0 !important;} JS: (function($) {$(document) .on( 'hidden.bs.modal', '.modal', function() { $(document.body).removeClass( 'modal-noscrollbar' ); }) .on( 'show.bs.modal', '.modal', function() { // Bootstrap adds margin-right: 15px to the body to account for a // scrollbar, but this causes a "shift" when the document isn't tall // enough to need a scrollbar; therefore, we disable the margin-right // when it isn't needed. if ( $(window).height() >= $(document).height() ) { $(document.body).addClass( 'modal-noscrollbar' ); } });})(window.jQuery); These combined permit the margin-right scrollbar fix to work for long pages, yet is disabled for shorter pages (when document height <= window height). I hope this helps! Bootstrap 3.0.1 + (tested up to 3.1.1) is a different story. Try the following: CSS: /* override bootstrap 3 class to remove scrollbar from modal backdrop when not necessary */.modal { overflow-y: auto;}/* custom class to add space for scrollbar */.modal-scrollbar { margin-right: 15px;} JS: (function($) {$(document) .on( 'hidden.bs.modal', '.modal', function() { $(document.body).removeClass( 'modal-scrollbar' ); }) .on( 'show.bs.modal', '.modal', function() { // Bootstrap's .modal-open class hides any scrollbar on the body, // so if there IS a scrollbar on the body at modal open time, then // add a right margin to take its place. if ( $(window).height() < $(document).height() ) { $(document.body).addClass( 'modal-scrollbar' ); } });})(window.jQuery); EDIT : In light of Mac eliminating scrollbars from inhabiting window render width, here's a more portable solution (3.0.1+) if you don't mind some feature detection. Reference: http://davidwalsh.name/detect-scrollbar-width CSS: .scrollbar-measure { height: 100px; overflow: scroll; position: absolute; top: -9999px;} JS: window.jQuery(function() { // detect browser scroll bar width var scrollDiv = $('<div class="scrollbar-measure"></div>') .appendTo(document.body)[0], scrollBarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth; $(document) .on('hidden.bs.modal', '.modal', function(evt) { // use margin-right 0 for IE8 $(document.body).css('margin-right', ''); }) .on('show.bs.modal', '.modal', function() { // When modal is shown, scrollbar on body disappears. In order not // to experience a "shifting" effect, replace the scrollbar width // with a right-margin on the body. if ($(window).height() < $(document).height()) { $(document.body).css('margin-right', scrollBarWidth + 'px'); } });});
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19288546', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2745306/']}
jdg_371798
stackexchange
llm_judgeable_groundtruth_similarity
20259827
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have read that there are different class loaders in java, the one is primordial class loader and there are custom class loaders as well, so I want to understand why primordial class loader is not able to serve all classes in java? Why is there need for other class loaders? Now provide the response and nothing else.
The main need is isolation. Let's say there are 3 applets on a page, each using a different version of the library foo.jar. You want each of those applets to run with its own version of the library, and to make sure it doesn't walk on another applet's toes. This is accomplished thanks to different class loaders. The same goes for web applications deployed on a single container. The Java container is started without any app deployed, and then an app is deployed. You want the container to be able to load classes from a location it didn't even know about when it was started. And if another webapp is deployed, you want this other app to have its own classes and libraries, that are different and isolated from the classes and libraries of the first app. Another need is to be able to load classes from various locations: the file system, but also URLs, databases, or whatever.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20259827', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2453173/']}
jdg_371799
stackexchange
llm_judgeable_groundtruth_similarity
61713
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: $$\lim_{n \to\infty} \frac{n!}{n^n}$$ I have a question: is it valid to use Stirling's Formula to prove convergence of the sequence? Now provide the response and nothing else.
There are two distinct questions here. The first one in the title is what the limit actually is. This is easy to see by writing out the expression as a product of $n$ positive factors:$$\frac{n!}{n^n}=\left(\frac{1}{n}\right)\left(\frac{2}{n}\right)\left(\frac{3}{n}\right)\cdots\left(\frac{n}{n}\right).$$ Every one of the factors $k/n$, $k=1,2,3,\dots,n$, is less than or equal to $1$. Hence the product is $$\le\left(\frac{1}{n}\right)\cdot1\cdot1\cdots1=1/n.$$But $1/n$ converges to $0$ as $n\to\infty$, so by the Squeeze theorem so does the original expression. The second question is whether or not it's allowed to use Stirling's formula to derive the limit, which I believe Arturo's comment covers: there is no apparent circularity, but in the context of classwork the answer depends on whether or not you've formally learned the formula and are allowed to use it as a given.
{}
{'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/61713', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/14759/']}
jdg_371800
stackexchange
llm_judgeable_groundtruth_similarity
37557343
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Firebase storage looks very cool and easy to use, but I'm wondering if there's a way to resize an image before uploading it to Firebase Storage, e.g., run a proccess using ImageMagick in a server and then run the uploading process using Firebase SDK but I notice there aren't storage functions for Firebase SDK Server. Now provide the response and nothing else.
You can also use Firebase Storage + Google Cloud Functions to upload an image, resize the image (using ImageMagick or similar), and write it back to Firebase Storage. I have an example using these together here (though I trigger the Cloud Vision API , rather than an image resizer). A quick side note: Firebase Storage doesn't have a Node.js client, instead we recommend using the GCloud-Node library.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37557343', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1301872/']}
jdg_371801
stackexchange
llm_judgeable_groundtruth_similarity
6215841
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 create html links out of text that is rendered in a canvas element? Now provide the response and nothing else.
There is no easy way. You will have to draw the link text onto the canvas and then check for mouseclicks. Here is a demo html page: <html><head><script type="text/javascript">var canvas = document.getElementById("myCanvas");var ctx;var linkText="https://stackoverflow.com";var linkX=5;var linkY=15;var linkHeight=10;var linkWidth;var inLink = false;// draw the balls on the canvasfunction draw(){ canvas = document.getElementById("myCanvas"); // check if supported if(canvas.getContext){ ctx=canvas.getContext("2d"); //clear canvas ctx.clearRect(0, 0, canvas.width, canvas.height); //draw the link ctx.font='10px sans-serif'; ctx.fillStyle = "#0000ff"; ctx.fillText(linkText,linkX,linkY); linkWidth=ctx.measureText(linkText).width; //add mouse listeners canvas.addEventListener("mousemove", on_mousemove, false); canvas.addEventListener("click", on_click, false); }}//check if the mouse is over the link and change cursor stylefunction on_mousemove (ev) { var x, y; // Get the mouse position relative to the canvas element. if (ev.layerX || ev.layerX == 0) { //for firefox x = ev.layerX; y = ev.layerY; } x-=canvas.offsetLeft; y-=canvas.offsetTop; //is the mouse over the link? if(x>=linkX && x <= (linkX + linkWidth) && y<=linkY && y>= (linkY-linkHeight)){ document.body.style.cursor = "pointer"; inLink=true; } else{ document.body.style.cursor = ""; inLink=false; }}//if the link has been clicked, go to linkfunction on_click(e) { if (inLink) { window.location = linkText; }}</script></head><body onload="draw()"><center><canvas id="myCanvas" width="200" height="200" style="border-style:solid;border-width:1px">Canvas not supported.</canvas></center></body></html>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6215841', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/386276/']}
jdg_371802
stackexchange
llm_judgeable_groundtruth_similarity
3844
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: John Doe told me the following story: I got a mail from a good friend. It just contained a single link. That seemed odd but I didn't think a lot about it. After clicking on the link, the web site of a company in my area of work opened. It didn't seem terribly interesting, so I closed it. A few days later, I started to get mails from old friends saying "Hi, nice to hear from you" and yesterday, I got a mail from myself. Mail that I've never sent. Since Mr. Doe is not a computer specialist what should he do next? I suggested: Get the latest virus scanner, maybe even a bootable CD like STD and check for viruses/trojans Backup his private data Get in contact with the company - their web site might have been compromised Change the web mail password just in case Contact the webmail provider and let them know about the security breach Install Firefox instead of the default Web browser Was that good advice? Anything I'm missing? Now provide the response and nothing else.
For a "paranoid dial turned to 11" approach, I suggest: On the system: Backup all essential data. Rebuild. Install resident antivirus/anti-malware/firewall protection. Install secure browser of choice, or update existing browser to latest version. Install secure browsing and OS plugins and configurations of choice. Make sure the OS and all applications are kept up-to-date. For all user accounts, do the following, recusively.* Change the password of the compromised webmail account. Change the passwords of any accounts which use the same password as his webmail account. Change the passwords of any accounts associated with the webmail account. * (Example: GMail account was compromised. Facebook and Hotmail accounts use the same password. Change Facebook and Hotmail passwords. LinkedIn account is associated with Hotmail account. Change LinkedIn password.) Also, contact the owner of the account that sent the e-mail to you, and let them know what's happened. This is a very high-level view of the recovery process. In the end, it is up to you to determine to what depth certain protective measures need to be applied, based on whatever value you place on the data and/or accounts that may have been compromised.
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/3844', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/2464/']}
jdg_371803
stackexchange
llm_judgeable_groundtruth_similarity
11372546
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 searched the site and have found some answers, but i'm having trouble understanding the difference between these two classes. Can someone explain the differences between these two classes? Now provide the response and nothing else.
PrintStream was the original bridge to deal with encoding characters and other datatypes. If you look at the javadoc for java.io.OutputStream you'll see methods only for writing two distinct data types: byte and int . In early versions of the JDK (1.0.x), when you wanted to write characters, you could do one of two things, write bytes to an output stream (which are assumed to be in the system default character set): outputStream.write("foobar".getBytes()); or wrap another outputStream in a PrintStream : PrintStream printStream = new PrintStream(outputStream);printStream.write("foobar"); See the difference? PrintStream is handling the character conversion to bytes, as well as encoding (the constructor call above uses the system default encoding, but you could pass it as a parameter). It also provides convenience methods for writing double , boolean , etc.... In fact System.out and System.err are defined as PrintStream instances. Along comes JDK 1.1, and they realize they need a better way to deal with pure character data, since PrintStream still has the byte based methods for writing. So they introduced the Writer abstract class to deal strictly with char , String and int data. PrintWriter adds methods for other types like double , boolean , etc... Nowadays PrintWriter also has format() / printf() methods for format printing, etc... As a general rule, if you're writing character data, use Writer instances. If you're writing binary (or mixed) data use OutputStream instances.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11372546', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1508034/']}
jdg_371804
stackexchange
llm_judgeable_groundtruth_similarity
1800253
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Simple scenario:I have a signup form, with user name, password, email address, may be credit card number. At the bottom of the page, I implement the Google Analytics code. when user clicks submit, it goes to a page wihtout google analytics. question is..can GA get the data (user naem, password..email..etc) in the first form after user input the data? Do they say anything about it in their TOS or Privacy policy? Now provide the response and nothing else.
Yes. Any <script> you include in the page has complete access to alter the user's interaction with the site due to the Same Origin Policy. Google, if they were feeling Evil today, could certainly rewrite the action of your <form> to point to themselves, or log every keypress, or create an <iframe> containing another page on your site and simulate the user clicking on any action in that page. Do not include <script> on any page from a party you don't completely trust with the security of everything on your site. Even a single tracking or advertiser script on any page compromises everything on the same hostname (and maybe other subdomains if you are setting window.domain to allow cross-hostname-scripting, or sharing cookies between hostnames). However, the Analytics script doesn't currently do any of these things and the form submission will not flow to Google as a matter of course; they would have to deliberately act to steal the data. Clearly it would be disastrous for them to be discovered doing it, so they presumably won't. But technically, they could . It always pains me to see third-party ad and tracking scripts on bank sites.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1800253', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/71671/']}
jdg_371805
stackexchange
llm_judgeable_groundtruth_similarity
4096366
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Execute this with msbuild: <?xml version="1.0" encoding="utf-8"?><Project DefaultTargets="Main" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ItemGroup> <Colors Include="Blue"> <Shade>Dark</Shade> </Colors> </ItemGroup> <Target Name="Main"> <Message Text="Color: %(Colors.Shade) %(Colors.Identity)"/> </Target></Project> And it outputs: Color: Dark Blue All well, and good, but delete the color and use this: <?xml version="1.0" encoding="utf-8"?><Project DefaultTargets="Main" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ItemGroup> </ItemGroup> <Target Name="Main"> <Message Text="Color: %(Colors.Shade) %(Colors.Identity)"/> </Target></Project> And it outputs: Color: Why is one batch of the Message task being executed when there are no items in the group? I would have expected for zero items, the batch would execute zero times and I would not see "Color:" followed by nothing in the output. Am I doing something wrong or is there a workaround for this? Thanks. Update:I've found you can do: <Message Condition="'@(Colors)'!=''" Text="Color: %(Colors.Shade) %(Colors.Identity)"/> But, if feels unsatisfactory to have to explicitly write code for the case when there are no items every time batching is used. Now provide the response and nothing else.
My 2 cents : In your Message Task, there is information from Batching and static information ("Colors :"). I think MsBuild prints the static information and then batch over the values of your Colors Item. The probleme is that you don't have any data in your collection (it is even undeclared), I suppose MsBuild interpretates this as an empty list, which, when you try to print it, print the empty string ''. If you remove the static content ("Colors :" and the whitespace before identity), you won't have anything displayed. A solution for printing with batching only if the items collection is not empty would be either : Check if the collection is empty <Message Condition="'@(Colors)'!=''" Text="Color: %(Colors.Shade) %(Colors.Identity)"/> Use MSBuild transforms <Message Text="@(Colors->'Color : %(Shade) %(Identity)')"/>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4096366', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11898/']}
jdg_371806
stackexchange
llm_judgeable_groundtruth_similarity
12217644
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 understand that a lot of people here complain about strcpy, but I haven't found anything using search that addresses the issue I have. First off, calling strcpy itself doesn't cause any sort of crash/segmentation fault itself. Secondly, the code is contained within a function, and the first time that I call this function it works perfectly. It only crashes on the second time through. I'm programming with the LPC1788 microcontroller; memory is pretty limited, so I can see why things like malloc may fail, but not free. The function trimMessage() contains the code, and the purpose of the function is to remove a portion of a large string array if it becomes too large. void trimMessage(){ int trimIndex; // currMessage is a globally declared char array that has already been malloc'd // and written to. size_t msgSize = strlen(currMessage); // Iterate through the array and find the first newline character. Everything // from the start of the array to this character represents the oldest 'message' // in the array, to be got rid of. for(int i=0; i < msgSize; i++) { if(currMessage[i] == '\n') { trimIndex = i; break; } } // e.g.: "\fProgram started\r\nHow are you?\r". char *trimMessage = (char*)malloc((msgSize - trimIndex - 1) * sizeof(char)); trimMessage[0] = '\f'; // trimTimes = the number of times this function has been called and fully executed. // freeing memory just below is non-sensical, but it works without crashing. //if(trimTimes == 1) { printf("This was called!\n"); free(trimMessage); } strcpy(&trimMessage[1], &currMessage[trimIndex+1]); // The following line will cause the program to crash. if(trimTimes == 1) free(trimMessage); printf("trimMessage: >%s<\n", trimMessage); // Frees up the memory allocated to currMessage from last iteration // before assigning new memory. free(currMessage); currMessage = malloc((msgSize - trimIndex + 1) * sizeof(char)); for(int i=0; i < msgSize - trimIndex; i++) { currMessage[i] = trimMessage[i]; } currMessage[msgSize - trimIndex] = '\0'; free(trimMessage); trimMessage = NULL; messageCount--; trimTimes++;} Thank you to everyone that helped. The function works properly now. To those asking why I was trying to print out an array I just freed, that was just there to show that the problem occurred after strcpy and rule out any other code that came after it. The final code is here, in case it proves useful to anyone who comes across a similar problem: void trimMessage(){ int trimIndex; size_t msgSize = strlen(currMessage); char *newline = strchr(currMessage, '\n'); if (!newline) return; trimIndex = newline - currMessage; // e.g.: "\fProgram started\r\nHow are you?\r". char *trimMessage = malloc(msgSize - trimIndex + 1); trimMessage[0] = '\f'; strcpy(&trimMessage[1], &currMessage[trimIndex+1]); trimMessage[msgSize - trimIndex] = '\0'; // Frees up the memory allocated to currMessage from last iteration // before assigning new memory. free(currMessage); currMessage = malloc(msgSize - trimIndex + 1); for(int i=0; i < msgSize - trimIndex; i++) { currMessage[i] = trimMessage[i]; } currMessage[msgSize - trimIndex] = '\0'; free(trimMessage); messageCount--;} Now provide the response and nothing else.
free can and will crash if the heap is corrupt or if you pass it an invalid pointer. Looking at that, I think your first malloc is a couple of bytes short. You need to reserve a byte for the null terminator and also you're copying into offset 1, so you need to reserve another byte for that. So what is going to happen is that your copy will overwrite information at the start of the next block of heap (often used for length of next block of heap and an indication as to whether or not it is used, but this depends on your RTL). When you next do a free, it may well try to coalesce any free blocks. Unfortunately, you've corrupted the next blocks header, at which point it will go a bit insane.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12217644', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1636276/']}
jdg_371807
stackexchange
llm_judgeable_groundtruth_similarity
33303
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Say we have $n$-gons $P$ and $Q$. Is there any necessary condition for $Q = f(P)$, for some linear transformation $f : \mathbb{R}^2 \to \mathbb{R}^2$? Sorry if this is too elementary / general. Now provide the response and nothing else.
Jesse Douglas studied linear transformations of polygons on the complex plane in 1930s. He proved, in particular, that a transformation $z_i{}'=\sum_{i=1}^na_{ij}z_j$ (all numbers are complex) will transform a polygon $\pi=(z_1,\cdots,z_n)$ into a polygon $\pi'=(z_1{}',\cdots,z_n{}')$ if, and only if, the matrix $a_{ij}$ is cyclic, that is, if, and only if, $a_{ij}=\alpha_{j-i}$, $\alpha_{j-i}=\alpha_k$ if $k\equiv j-1\ (\text{mod}\,n)$. (See his article "On linear polygon transformations" , Bull. Amer. Math. Soc. 46, (1940) pp. 551 - 560.)
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/33303', 'https://mathoverflow.net', 'https://mathoverflow.net/users/2503/']}
jdg_371808
stackexchange
llm_judgeable_groundtruth_similarity
37089
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 have the sphere $$(x-1)^2 + (y-2)^2 + (z-3)^2 = 36.$$From the sphere, I find some points with integral coordinates. And select three points from this list so that the triangles are not right triangle. I tried ClearAll[a, b, r];a = 1;b = 2;c = 3;r = 6;ss = Subsets[{x, y, z} /. Solve[{(x - a)^2 + (y - b)^2 + (z - c)^2 == r^2, x != a, y != b, z != c}, {x, y, z}, Integers], {3}];Pick[ss, (FreeQ[#, \[Pi]/2] &) /@ ({VectorAngle[#2 - #1, #3 - #1], VectorAngle[#1 - #2, #3 - #2], VectorAngle[#1 - #3, #2 - #3]} & @@@ ss)] Now, I want to select three points $A$, $B$, $C$ so that the circle passing through points $A$, $B$, $C$ take the point $(1,2,3)$ as its centre. How can I select them? Now provide the response and nothing else.
Before any real answer appears: ContourPlot[Evaluate[u[x, t] /. sol] == 1, {x, -50, -58}, {t, 50, 58} ] // Normal // Cases[#, Line[x__] :> x, Infinity][[ 1, ;; , 2]] & // Max 56.0628 ...and the real answer: U = u /. sol[[ 1]]FindRoot[{U[x, t] == 1, D[U[x, t], x] == 0}, {{x, -56}, {t, 54}}] {x -> -56.0326, t -> 56.0635} So graphical method was not so bad. :)
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/37089', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/2241/']}
jdg_371809
stackexchange
llm_judgeable_groundtruth_similarity
30575041
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have two remotes set up in my local git repo. One is the repo of an open-source project I'm contributing to, and the other is my fork of that repo. It seems that I'm only able to check out stuff that I pull down from the origin remote. My normal method of grabbing a branch from a remote consists of $ git fetch <remote> <branch>$ git checkout <branch> But this doesn't seem to work in my current situation. $ git fetch my-remote my-branchremote: Counting objects: 2297, done.remote: Compressing objects: 100% (1951/1951), done.remote: Total 2297 (delta 1044), reused 0 (delta 0), pack-reused 50Receiving objects: 100% (2297/2297), 2.10 MiB | 1.59 MiB/s, done.Resolving deltas: 100% (1045/1045), done.From https://github.com/me/my-repo * branch my-branch -> FETCH_HEAD * [new branch] my-branch -> origin/my-branch$ git checkout my-brancherror: pathspec 'my-branch' did not match any file(s) known to git. Furthermore, the branch does not appear when I do git branch . What's going on here? Now provide the response and nothing else.
When you have only a single remote (let's call it origin ) then when you type git checkout foo when foo doesn't exist but origin/foo does exist git will behave as though you typed the following git checkout -b foo origin/foo If you have multiple remotes, and foo does not exist locally but exists in 2 or more remotes then this behavior is suppressed. You will need to explicitly create foo and instruct git what remote/branch you want it to track. git checkout -b foo <remote>/foo
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/30575041', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1467997/']}
jdg_371810
stackexchange
llm_judgeable_groundtruth_similarity
27097978
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 break out of a loop in Clojure if a condition is matched returning the last value? Most algorithms benefit from returning a result when they find it and avoiding completing the whole execution. Let's say that I have a vector of 100 numbers ranging from 0 to 100 and I want to find the number 10. Once 10 is found I want the execution to stop. An even simpler case than my example is the following: (defn MySearch [y] (when (< y 10);;Corrected. Thanks to dsm who pointed it out. Previously was (< y 5). (if (= (nth [1 2 3 4 5 6 7 8 9 10] y) 10) (println "I found it! Now I want to stop executing!" ) ) (recur (inc y) ) ))(MySearch 0) How can I stop when I find 5? I have searched enough and I can't find any way of implementing this. I have also found an answer here that states that what I am asking doesn't exist in Clojure but I find it a little far-fetched. Even if this is the case can I implement something like that myself? (I am new to Clojure.) Now provide the response and nothing else.
You nearly got it right. Reformatting your code, we get (defn MySearch [y] (when (< y 10) (if (= (nth [1 2 3 4 5 6 7 8 9 10] y) 10) "I found it! Now I want to stop executing!") (recur (inc y)))) ... where - for simplicity - I've got rid of the println , and had the function hopefully return your message. But, as you've noticed, it doesn't: (MySearch 0);nil Why? The trouble is that the (recur ...) is outside the if . What does this do? If the (< y 10) condition for the when is met, the (if ...) andthe (recur ...) are executed in turn, and the result of the latterreturned. Eventually, y is 10 , so the when condition fails, so the when returns nil . Let's move the recur inside the if : (defn MySearch [y] (when (< y 10) (if (= (nth [1 2 3 4 5 6 7 8 9 10] y) 10) "I found it! Now I want to stop executing!" (recur (inc y))))) Now, Lo and Behold: (MySearch 0);"I found it! Now I want to stop executing!" Because we returned the message, we know that the function did stop executing. Otherwise it would have gone on and returned nil . With the println in place, the function would output the message and return nil immediately, as it would do had it gone on executing. So - as to whether it stopped executing, you're none the wiser. By the way, as the author of the answer you find far-fetched , let me try again: There is no break statement in Clojure. It's the other way round: You break out of a loop by default. You have to use recur to continue it. recur is a special recursive call to the function (or loop ) you are executing: one where it is the returned value. It is said to be in tail position . Most Lisp systems detect such calls - so called tail calls - automatically. So they don't have or need a construct like recur . Having said that, Clojure 1.5 introduced reduced : a break -like construct for reduce. You can read about it here .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27097978', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3599135/']}
jdg_371811
stackexchange
llm_judgeable_groundtruth_similarity
54858701
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an Azure Function 2.x that reside on a static class that looks like this [FunctionName("Register")]public static async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post")]HttpRequest req, ILogger log){ MyTypeClass defReturn = new MyTypeClass(); HttpStatusCode defCode = HttpStatusCode.BadRequest; /* * Logics that might or might not changes * defReturn and defCode value */ return StatusCode((int) defCode, JsonConvert.SerializeObject(defReturn))} How can i achieve the return StatusCode((int) defCode, JsonConvert.SerializeObject(defReturn)) part ? is there any such method or equivalent in Azure Functions 2.x ? in Azure Functions 1.x i can do the equivalent with req.CreateResponse(defCode, defReturn) where req is HttpRequestMessage , but i'm trying to stick with 2.x template/standard Additional explanation : The said Code should return HTTP 400 Bad Request with the defReturn as it's response body to the client. But when i change the defCode to HttpStatusCode.Accepted , it should return HTTP 202 Accepted with the same response body. How can i achieve this ? Additional explanation#2 : (If i remember correctly) in ASP.NET Core 1.x i can exactly do like that, returning IActionResult by calling a static method StatusCode not StatusCodes (which is a static class that contains HTTP codes constants Thank you Now provide the response and nothing else.
Quite late reply, but I was stumbling into the same problem today, so maybe this is helpful for other searchers Option 1: Default Codes This is stated in detail on the blog Here Some codes like 200 and 400 are predefined and can be used by return new OkObjectResult("Your message"); // 200return new BadRequestObjectResult("Your error message"); // 400 These functions are not available for every known Status Codes but some of the most frequent. Option 2: Manual setting Code If you need specific codes, that are not provided by default, you can use the base classes and create them yourself. To achieve the Teapot Response for example, you can just use using Microsoft.AspNetCore.Http;var result = new ObjectResult("Your message");result.StatusCode = StatusCodes.Status418ImATeapot;return result; In this example, the Statuscode is used from the StatusCodes class, but you can use enter other codes as well (usually, just stick to these codes) Also, the ObjectResult class offers additional formatting options, if needed.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/54858701', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3079908/']}
jdg_371812
stackexchange
llm_judgeable_groundtruth_similarity
5247250
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I was going to ask "How to pickle a class that inherits from dict and defines __slots__ ". Then I realized the utterly mind-wrenching solution in class B below actually works... import pickleclass A(dict): __slots__ = ["porridge"] def __init__(self, porridge): self.porridge = porridgeclass B(A): __slots__ = ["porridge"] def __getstate__(self): # Returning the very item being pickled in 'self'?? return self, self.porridge def __setstate__(self, state): print "__setstate__(%s) type(%s, %s)" % (state, type(state[0]), type(state[1])) self.update(state[0]) self.porridge = state[1] Here is some output: >>> saved = pickle.dumps(A(10))TypeError: a class that defines __slots__ without defining __getstate__ cannot be pickled>>> b = B('delicious')>>> b['butter'] = 'yes please'>>> loaded = pickle.loads(pickle.dumps(b))__setstate__(({'butter': 'yes please'}, 'delicious')) type(<class '__main__.B'>, <type 'str'>)>>> b{'butter': 'yes please'}>>> b.porridge'delicious' So basically, pickle cannot pickle a class that defines __slots__ without also defining __getstate__ . Which is a problem if the class inherits from dict - because how do you return the content of the instance without returning self , which is the very instance pickle is already trying to pickle, and can't do so without calling __getstate__ . Notice how __setstate__ is actually receiving an instance B as part of the state. Well, it works... but can someone explain why? Is it a feature or a bug? Now provide the response and nothing else.
Maybe I'm a bit late to the party, but this question didn't get an answer that actually explains what's happening, so here we go. Here's a quick summary for those who don't want to read this whole post (it got a bit long...): You don't need to take care of the contained dict instance in __getstate__() -- pickle will do this for you. If you include self in the state anyway, pickle 's cycle detection will prevent an infinite loop. Writing __getstate__() and __setstate__() methods for custom classes derived from dict Let's start with the right way to write the __getstate__() and __setstate__() methods of your class. You don't need to take care of pickling the contents of the dict instance contained in B instances -- pickle knows how to deal with dictionaries and will do this for you. So this implementation will be enough: class B(A): __slots__ = ["porridge"] def __getstate__(self): return self.porridge def __setstate__(self, state): self.porridge = state Example: >>> a = B("oats")>>> a[42] = "answer">>> b = pickle.loads(pickle.dumps(a))>>> b{42: 'answer'}>>> b.porridge'oats' What's happening in your implementation? Why does your implementation work as well, and what's happening under the hood? That's a bit more involved, but -- once we know that the dictionary gets pickled anyway -- not too hard to figure out. If the pickle module encounters an instance of a user-defined class, it calls the __reduce__() method of this class, which in turn calls __getstate__() (actually, it usually calls the __reduce_ex__() method, but that does not matter here). Let's define B again as you originally did, i.e. using the "recurisve" definition of __getstate__() , and let's see what we get when calling __reduce__() for an instance of B now: >>> a = B("oats")>>> a[42] = "answer">>> a.__reduce__()(<function _reconstructor at 0xb7478454>, (<class '__main__.B'>, <type 'dict'>, {42: 'answer'}), ({42: 'answer'}, 'oats')) As we can see from the documentation of __reduce__() , the method returns a tuple of 2 to 5 elements. The first element is a function that will be called to reconstruct the instance when unpickling, the second element is the tuple of arguments that will be passed to this function, and the third element is the return value of __getstate__() . We can already see that the dictionary information is included twice. The function _reconstructor() is an internal function of the copy_reg module that reconstructs the base class before __setstate__() is called when unpickling. (Have a look at the source code of this function if you like -- it's short!) Now the pickler needs to pickle the return value of a.__reduce__() . It basically pickles the three elements of this tuple one after the other. The second element is a tuple again, and its items are also pickled one after the other. The third item of this inner tuple (i.e. a.__reduce__()[1][2] ) is of type dict and is pickled using the internal pickler for dictionaries. The third element of the outer tuple (i.e. a.__reduce__()[2] ) is also a tuple again, consisting of the B instance itself and a string. When pickling the B instance, the cycle detection of the pickle module kicks in: pickle realises this exact instance has already been dealt with, and only stores a reference to its id() instead of really pickling it -- this is why no infinte loop occurs. When unpickling this mess again, the unpickler first reads the reconstruction function and its arguments from the stream. The function is called, resulting in an B instance with the dictionary part already initialised. Next, the unpickler reads the state. It encounters a tuple consisting of a reference to an already unpickled object -- namely our instance of B -- and a string, "oats" . This tuple now is passed to B.__setstate__() . The first element of state and self are the same object now, as can be seen by adding the line print self is state[0] to your __setstate__() implementation (it prints True !). The line self.update(state[0]) consequently simply updates the instance with itself.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5247250', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/254704/']}
jdg_371813
stackexchange
llm_judgeable_groundtruth_similarity
733231
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I have been tasked with the project of making Windows Server 2012 r2 PXE boot live Linux distributions using WDS and I'm having trouble. I have a Blade server acting as the WDS, a Sonicwall handling DHCP and acting as a firewall (I do not have access to the Sonicwall) and a lab full of computers to PXE boot. I've followed the instructions I could find from multiple sources online. I have used the necessary files from Syslinux 5.01 (pxelinux, vesamenu, and chain) and renamed them as suggested, I have created the NFS share folder as suggested and created a TFTP server as found in other guides to serve the filesystem.squashfs file when NFS failed to boot. I believe that the error is in my default file (below) but I have no idea what it would be. Neither option (NFS for Ubuntu or TFPT for Kali) boots successfully. NFS gives me an error about needing a path, yet the path points exactly where the guides say to, and the TFTP errors out with no live filesystem found, but filesystem.squashfs is the live filesystem. Anyone have any ideas?Thanks! Sources: Combining PXELinux with WDS How to PXE boot live Linux CD DEFAULT vesamenu.c32 PROMPT 0 MENU TITLE PXE Boot Menu (x64)MENU INCLUDE pxelinux.cfg/graphics.confMENU AUTOBOOT Starting Local System in 8 seconds Option 1 - Exit PXE Linux & boot normally LABEL bootlocal menu label ^Boot Normally menu default localboot 0 timeout 80 TOTALTIMEOUT 9000 Option 2 - Run WDS LABEL wds MENU LABEL ^Windows Deployment Services KERNEL pxeboot.0 LABEL kali MENU LABEL ^Kali 2.0 # Load the correct kernel kernel /Linux/Kali/live/vmlinuz # Boot options append priority=low vga=normal boot=live initrd=/Linux/Kali/live/initrd.img fetch=tftp://192.168.2.138/Linux/Kali/live/filesystem.squashfs LABEL ubuntu MENU LABEL ^Ubuntu # Load the correct kernel kernel /Linux/Ubuntu/casper/vmlinuz.efi # Boot options append root=/dev/nfs priority=low vga=normal boot=casper netboot=nfs initrd=/Linux/Ubuntu/casper/initrd.lz nfsroot=192.168.2.13/RemoteInstall/Boot/x64/Linux/Ubuntu/casper/ Option 3 - Exit PXE Linux LABEL Abort MENU LABEL E^xit KERNEL abortpxe.0 Now provide the response and nothing else.
This is resolved. There were two issues with my above code. Issue #1 - Only Apache 2.4.10 and above can support sockets The default version of Apache that comes in the base CentOS repositories ( Apache 2.4.6 ) only support TCP ports. The above code is therefore incorrect, and the listen directive in the php-fpm config file needed to be changed to something like this: listen = 127.0.0.1:9001 I also made the appropriate change in my http.d conf file, but in addition, I also switched to using the ProxyPassMatch directive instead of using the FilesMatch directive. So my code then became: ProxyPassMatch "^/(.*\.php)$" "fcgi://127.0.0.1:9001/site1.com" Note that this code is still wrong... see below Moving on... Issue #2 - Relevant Paths The path in the ProxyPassMatch directive (or, in the case of my older code using the FilesMatch directive) inside my http.d conf file becomes relative to the chroot . It is not relative to the www document root (if different). So my code in my http.d conf file became: ProxyPassMatch "^/(.*\.php)$" "fcgi://127.0.0.1:9001/www/$1" And voila! I have a php-fpm chroot.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/733231', 'https://serverfault.com', 'https://serverfault.com/users/319916/']}
jdg_371814
stackexchange
llm_judgeable_groundtruth_similarity
42367975
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 had developed rest API on spring boot application. The APIs accept only GET , and POST , but on requesting using OPTIONS method , API responding 200 status (instead of 405). I googled this issue , but none of the solution was springboot based . Response: Allow: OPTIONS, TRACE, GET, HEAD, POSTPublic: OPTIONS, TRACE, GET, HEAD, POST Need to disable OPTIONS method. Now provide the response and nothing else.
Previous answer is for tomcat only, so adding mine as well. You can disable the method cross-container by, for example, using a standard servlet filter: import java.io.IOException;import javax.servlet.FilterChain;import javax.servlet.ServletException;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; @Componentpublic class MethodFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { if (request.getMethod().equals("OPTIONS")) { response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } else { filterChain.doFilter(request, response); } }} Note: it is assumed that this class is componentscanned by Spring. If not, you can use other registration methods as detailed in here .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42367975', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3369025/']}
jdg_371815
stackexchange
llm_judgeable_groundtruth_similarity
1318647
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am studying Joint Probability Distributions and Random Samples. I have a function for a probability distribution, defined as: $ f(x, y) = K(x^2 + y^2)~~~~~~~~~ 20 \leq x \leq 30, ~~~20 \leq y \leq 30$ and $0$ otherwise. I want to compute the probability that the difference between $x$ and $y$ is at most $2$. How can I approach this problem? Edit: I know that the region to consider is that inside the two lines in the plot. But I don't understand how to define the boundaries inside the integrals. Now provide the response and nothing else.
Firstly, calculate $K$. To do that, use the fact that $\int\int fdxdy=1$. Secondly, draw the region, within $[20,30]\times[20,30]$, where $|x-y|\leq2$. Express that region as double integrals of $f$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1318647', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/113873/']}
jdg_371816
stackexchange
llm_judgeable_groundtruth_similarity
2578042
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 Perl modules autodie and Fatal seem to be doing similar things. What are the reasons for using one in preference to the other? Now provide the response and nothing else.
The Fatal module was added to the Perl core in version 5.05 (1998). The Fatal module has some significant shortcomings and inconsistencies in its API which couldn't be fixed in a backwards compatible way (ie: fixing the API would break existing code which used Fatal). The newer autodie module was written to provide a more consistent API and to allow the effect of the pragma to be lexically scoped rather than global (which can have unexpected side effects). If you have a choice, you should definitely prefer autodie. It will be included as a core module in the upcoming 5.12 release of Perl. The autodie module requires Perl 5.8. About the only reason you'd use Fatal is if you were stuck with a really old version of Perl (eg: 5.6), but 5.8 has been out since 2002 so hopefully that won't be the case for you.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2578042', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/70880/']}
jdg_371817
stackexchange
llm_judgeable_groundtruth_similarity
5617211
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Quite often, Git and Ruby on Rails looks like magic... such as in the first chapter of Ruby on Rails 3 Tutorial book , it talks about Git: git remote add origin git@github.com:peter/first_app.gitgit push origin master And it pretty much says "it just works" without saying too much about what they are and start talking about branching. Searching on the Internet shows that git remote add is to add a "short name", such as origin , and it can be any name as well, which is like an alias to a URL. And origin is the usual path of where the remote repository points to (in http://git-scm.com/book/en/Git-Basics-Working-with-Remotes under "Adding Remote Repositories"). So why is the URL not git://git@github.com/peter/first_app.git , but in the other syntax -- what syntax is it? Why must it end with .git ? I tried not using .git at the end and it works too. If not .git , what else can it be? The git in git@github.com seems to be a user account on the Git server? Also, why does it need to be so verbose to use git push origin master ? Can't the default be origin and master? I found that the first time, the origin master is needed, but after a small edit and commit, then git push is all it needs (no need origin master ). Can somebody who knows what is going on give some details? Sometimes it feels like a lot of magic without explanation... and sometimes the person using it is so confident and when asked why, can't explain it, and respond with something like "that's the way it is". Sometimes very practical and pragmatic. It is not bad to be practical, but probably not practical to the point to not know what is going on. Now provide the response and nothing else.
Git is like Unix. It is user-friendly, but it is picky about its friends. It's about as powerful and as user-friendly as a shell pipeline. That being said, once you understand its paradigms and concepts, it has the same Zenlike clarity that I've come to expect from Unix command-line tools. You should consider taking some time off to read one of the many good Git tutorials available online. The Pro Git book is a good place to start. To answer your first question. What is git remote add ... ? As you probably know, Git is a distributed version control system. Most operations are done locally. To communicate with the outside world, Git uses what are called "remotes" . These are repositories other than the one on your local disk which you can push your changes into (so that other people can see them) or pull from (so that you can get others changes). The command git remote add origin git@github.com:peter/first_app.git creates a new remote called origin located at git@github.com:peter/first_app.git . Once you do this, in your push commands, you can push to origin instead of typing out the whole URL. What is git push origin master ? This is a command that says "push the commits in the local branch named master to the remote named origin ". Once this is executed, all the stuff that you last synchronised with origin will be sent to the remote repository and other people will be able to see them there. Now about transports (i.e., what git:// ) means. Remote repository URLs can be of many types ( file:// , https:// , etc.). Git simply relies on the authentication mechanism provided by the transport to take care of permissions and stuff. This means that for file:// URLs, it will be Unix file permissions, etc. The git:// scheme is asking Git to use its own internal transport protocol, which is optimised for sending Git changesets around. As for the exact URL, it's the way it is because of the way GitHub has set up its Git server. Now the verbosity. The command you've typed is the general one. It's possible to tell Git something like "the branch called master over here is local mirror of the branch called foo on the remote called bar ". In Git speak, this means that master tracks bar/foo . When you clone for the first time, you will get a branch called master and a remote called origin (where you cloned from) with the local master set to track the master on origin. Once this is set up, you can simply say git push and it'll do it. The longer command is available in case you need it (e.g., git push might push to the official public repository and git push review master can be used to push to a separate remote which your team uses to review code). You can set your branch to be a tracking branch using the --set-upstream option of the git branch command. I've felt that Git (unlike most other applications I've used) is better understood from the inside out. Once you understand how data is stored and maintained inside the repository, the commands and what they do become crystal clear. I do agree with you that there's some elitism amongst many Git users, but I also found that with Unix users once upon a time, and it was worth ploughing past them to learn the system. Good luck!
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/5617211', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/325418/']}
jdg_371818
stackexchange
llm_judgeable_groundtruth_similarity
30893667
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 set of JSON array and I want the result to be grouped by the "Id" column. I will not use underscore.js for this, as this can't be used in our project. The only option is to do it with jQuery. My source array and expected results are below. var origObj = [{ "Id": "1", "name": "xxx", "age": "22" }, { "Id": "1", "name": "yyy", "age": "15" }, { "Id": "5", "name": "zzz", "age": "59" }]var output = [{"1": [{ "Id": "1", "name": "xxx", "age": "22" }, { "Id": "1", "name": "yyy", "age": "15" }], "5": [{ "Id": "5", "name": "zzz", "age": "59" }]}] Now provide the response and nothing else.
You can use Array.prototype.reduce to get this done. Check this post for more details https://stackoverflow.com/a/22962158/909535 Extending on that this is what you would need var data= [{ "Id": "1", "name": "xxx", "age": "22" }, { "Id": "1", "name": "yyy", "age": "15" }, { "Id": "5", "name": "zzz", "age": "59" }]; console.log(data.reduce(function(result, current) { result[current.Id] = result[current.Id] || []; result[current.Id].push(current); return result; }, {}));
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30893667', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/447589/']}
jdg_371819
stackexchange
llm_judgeable_groundtruth_similarity
67723
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Is it true that an irreducible component of a Cohen-Macaulay variety is also Cohen-Macaulay? If not, then in what cases does this fact hold? Now provide the response and nothing else.
Start with your favorite example of an affine irreducible variety $X$ that is not Cohen-Macaulay. Embed $X$ in $\mathbb A^N$, and call $c$ its codimension. Now take $c$ general polynomials that contain $X$: their intersection $Y$ has codimension $c$, and contains $X$. Then $Y$ is a complete intersection (hence Cohen-Macaulay) subvariety of $\mathbb A^N$, and contains $X$ as an irreducible component.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/67723', 'https://mathoverflow.net', 'https://mathoverflow.net/users/15764/']}
jdg_371820
stackexchange
llm_judgeable_groundtruth_similarity
177681
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How can $e$ be used for practical mathematics? This is for a presentation on (among other numbers) $e$, aimed at people between the ages of 10 and 15. To clarify what I want: Not wanted: $e^{i\pi}+1=0$ is cool, but (as far as I know) it can't be used for practical applications outside a classroom. What I do want: $e$ I think is used in calculations regarding compound interest. I'd like a simple explanation of how it is used (or links to simple explanations), and more examples like this. Now provide the response and nothing else.
$e$ is not useful. It just happens to be the value at $x = 1$ of the exponential function $$e^x = \sum_{n=0}^{\infty} \frac{x^n}{n!}$$ which is incredibly useful because it is its own derivative. This fundamental property helps us solve differential equations , which are a very powerful language for understanding the universe. The boring example is modeling something like the growth of bacteria. (As Raymond Manzoni's comment says, a more interesting example involving exponential growth is carbon dating .) A much more interesting example (to me, anyway) occurs if you allow $x$ to be something more general than a real number: allow it to be complex and you get Euler's formula $$e^{ix} = \cos x + i \sin x$$ which tells you that the exponential can represent rotations in the plane. It also tells you that $\cos x$ and $\sin x$ can be used to describe simple harmonic motion , a basic and fundamental example of a differential equation describing real-world phenomena (such as circuits) that we know how to solve exactly thanks to the exponential function. To be more specific, the current $I(t)$ in an LC circuit satisfies the differential equation $$\frac{d^2 I}{dt^2} + \frac{1}{LC} I = 0$$ where $L$ is the inductance and $C$ is the capacitance. The complex exponential can be used to deduce that the solutions to this differential equation look like $$I(t) = A \cos \omega t + B \sin \omega t$$ where $\omega^2 = \frac{1}{LC}$. This is a very precise description: the current is periodic and we can explicitly compute its period. Add in a resistor and you get a similar differential equation whose solutions can now be damped , and again we can explicitly compute how quickly the current is damped. Exponentials are also closely related to the theory of the Fourier transform (which also helps us solve differential equations and much more besides), the normal distribution (which we use to understand statistics), approximating factorials (which we often need to do in computer science)...
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/177681', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/36974/']}
jdg_371821
stackexchange
llm_judgeable_groundtruth_similarity
97060
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Let $\Gamma$ be a finitely generated group of exponential growth and $gr(S)=\lim_{k\rightarrow \infty} \sqrt[k]{|B_k(S)|}$ be the growth rate of $\Gamma$ with respect to the generating set $S$. I am confused with the following question: Does there always exist a generating set $S'$ such that$$\frac{|B_k(S')|}{gr(S')^k}\rightarrow 1, \text{ when }k\rightarrow \infty$$ Now provide the response and nothing else.
There is never a (finite) generating set with that property. Consider a generating set $S=\{x_1,\ldots,x_{\ell}\}$ of cardinality $\ell$. Let $B_k := B_k(S)$, $S_k := B_k \setminus B_{k-1}$, and $g := gr(S)$. Let $b_k := |B_k|$ and $s_k: = |S_k|$. Assume for simplicity that $L := \lim_{k \to \infty} \frac{b_k}{g^k}$ exists (although it shouldn't be difficult to get general liminf bounds). Also set$$ L' := \lim_{k \to \infty} \frac{s_k}{g^k} = \lim_{k \to \infty} \frac{b_k-b_{k-1}}{g^k} = \left(1-\frac{1}{g}\right)L. $$ For the spheres, there's a trivial inequality $s_{m+n} \leq s_m s_n$. (Any word of minimal length $m+n$ in the generators may be written at least one way as a product of two words of minimal length $m$ and $n$.) This is already enough to give $L' \geq 1$, and thus$$ L \geq \frac{1}{1-\frac{1}{g}} > 1. $$ This is unsatisfying and still leaves the possibility that $L'=1$. Thus, I eliminate that possibility as well, by improving the trivial bound $s_{2k} \leq s_k^2$ to $s_{2k} \leq \left(1-\frac{1}{2\ell}\right)s_k^2$. This improvement (unlike the trivial improvement above) does not hold for monoids, so the extra cancellation comes (unsurprisingly) from the existance of inverses. Specifically, fix $k$, let $E_i$ be the set of all elements of $S_k$ which may be written as a word of length $k$ ending in $x_i$, and let $E_{\ell+i}$ be the set of all elements of $S_k$ which may be written as a word of length $k$ ending in $x_i^{-1}$. Set$$ F_i = E_i \setminus \bigcup_{j < i} E_j, $$so the $F_i$ are disjoint.Let $F_i'$ be the image of $F_i$ under the inversion map, and let $n_i = |F_i|$. The product of an element of $F_i$ and an element of $F_i'$ may be written with $2k-2$ letters (because the $x_i$ and $x_i^{-1}$ cancel), so those $n_i^2$ products are not in $S_{2k}$. Thus, we have$$ s_{2k} \leq s_k^2 - \sum_{i=1}^{2\ell} n_i^2. $$By the Hölder inequality, we have$$ s_k = \sum_{i=1}^{2\ell} n_i \leq \sqrt{\sum_{i=1}^{2\ell} 1^2} \sqrt{\sum_{i=1}^{2\ell} n_i^2} $$$$ \frac{s_k^2}{2\ell} \leq \sum_{i=1}^{2\ell} n_i^2. $$Combining the inequalities gives$$ s_{2k} \leq \left(1-\frac{1}{2\ell}\right)s_k^2. $$Dividing by $g^{2k}$ and sending $k \to \infty$ gives$$ L' \geq \frac{1}{1-\frac{1}{2\ell}} > 1. $$For balls, we obtain the bound$$ L \geq \frac{1}{\left(1-\frac{1}{g}\right)\left(1-\frac{1}{2\ell}\right)}. $$This bound is optimal for free generating sets of free groups. I'd be interested in seeing what Kate's limit says (or don't say) about the underlying group. Can the lower bound I just gave be achieved for non-free groups? Can the limit generally be made arbitrarily close to $1$ by increasing the number of generators appropriately (as Misha speculated in the comments)? I'm far from an expert in combinatorial/asymptotic group theory, so I don't have good intuition for what intrinsic information this value holds.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/97060', 'https://mathoverflow.net', 'https://mathoverflow.net/users/8699/']}
jdg_371822
stackexchange
llm_judgeable_groundtruth_similarity
15147900
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 writing a simple batch file (remove.bat) to remove a directory and all its subdirectories. The file contains the following command- rmdir /S modules where modules is the name of the non-empty directory. I get the following message - C:\...\bin>rmdir /S modulesmodules, Are you sure (Y/N)? How can I supply through the batch file the console input "Y" to the Y/N question above? Is there a command that can do this? Now provide the response and nothing else.
As others have pointed out, you should use the /Q option. But there is another "old school" way to do it that was used back in the day when commands did not have options to suppress confirmation messages. Simply ECHO the needed response and pipe the value into the command. echo y|rmdir /s modules I recommend using the /Q option instead, but the pipe technique might be important if you ever run into a command that does not provide an option to suppress confirmation messages. Note - This technique only works if the command reads the input from stdin, as is always the case with cmd.exe internal commands. But this may not be true for some external commands.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/15147900', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1199882/']}
jdg_371823
stackexchange
llm_judgeable_groundtruth_similarity
828920
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In contemporary real analysis we use a limit definition in terms of deltas and epsilons.Before that, people used infinitesimals to calculate limits. Is there a specific non-philosophical reason why we didn't keep on using infinitesimals?I.e. are there concrete examples in which the use of infinitesimals lead to serious problems? Now provide the response and nothing else.
Before the formalization of limit in terms of $\epsilon $ and $\delta $ the arguments given in analysis were heuristic, simply because at the time no known model of reals with infinitesimals was known. People used infinitesimals intuitively, though they knew no infinitesimals existed (at least for them, at the time). The fact that (correct, in whatever sense) use of infinitesimals did not lead to any blunders was somewhat of a strange phenomenon then. Once Cauchy formalized limits using $\epsilon $ and $\delta $ it became possible to eliminate any infinitesimals from the formal proofs. One could still think infinitesimally, or not, but one could finally give rigorous proofs. Things changed when Robinson discovered a construction, using tools from logic that were new at the time, by which one can enlarge the reals to include actual infinitesimals. Retrospectively, this discovery explained why infinitesimals did not lead to blunders. Simply since they do exist! Today inertia dictates one's first encounter with analysis, and so non-standard analysis is usually never met until one stumbles upon it or in advanced courses, usually in logic rather than analysis. Having said that, there are textbooks aimed at a beginner's course in calculus using non-standard analysis. There are probably two reasons why that is unlikely to catch momentum. First is the name; nobody really wants to do things non-standardly. Secondly, and more importantly, the prerequisites for Cauchy's $\epsilon $ $\delta $ formalism is very modest. However, even the simplest models of non-standard analysis require a significant dose of logic, one that will take a week or two at least of a beginner's course. And since non-standard analysis is as powerful as ordinary analysis, it is difficult to justify putting in the logic(al) effort, for what many may consider to be only cosmetic gain. Some, disagree though and claim non-standard analysis is superior.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/828920', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/53989/']}
jdg_371824
stackexchange
llm_judgeable_groundtruth_similarity
53432103
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have the following code: everything:-give_birth(X), give_eggs(Y), format('Animal Name: \t~w, \tGives Birth', X), nl, format('Animal Name: \t~w, \tGives egg', Y), nl,fail. and this is the output: Animal Name: cheetah, Gives BirthAnimal Name: ostrich, Gives eggAnimal Name: cheetah, Gives BirthAnimal Name: penguin, Gives eggAnimal Name: cheetah, Gives BirthAnimal Name: albatross, Gives eggAnimal Name: tiger, Gives BirthAnimal Name: ostrich, Gives eggAnimal Name: tiger, Gives BirthAnimal Name: penguin, Gives eggAnimal Name: tiger, Gives BirthAnimal Name: albatross, Gives eggAnimal Name: giraffe, Gives BirthAnimal Name: ostrich, Gives eggAnimal Name: giraffe, Gives BirthAnimal Name: penguin, Gives eggAnimal Name: giraffe, Gives BirthAnimal Name: albatross, Gives eggAnimal Name: zebra, Gives BirthAnimal Name: ostrich, Gives eggAnimal Name: zebra, Gives BirthAnimal Name: penguin, Gives eggAnimal Name: zebra, Gives BirthAnimal Name: albatross, Gives egg first problem is: I want the third column to be aligned. Second problem: the output is not what I want it, I want it first to print all the animals that gives birth which are only 4(the rest are repeated in this output I don't know why). and then the rest of the animals that gives egg. Now provide the response and nothing else.
I would use a subject to keep everything reactive. In your template html listen to change events and emit a new value to the subject. <searchBar (change)="search$.next($event.target.value)" /> then in your component: this.subscription = this.search$.pipe( debounceTime(800), distinctUntilChanged(), switchMap(searchText=>http.post('api_link', {searchText}) }).subscribe(response=>{ this.response = response. }); The switchMap will cancel any HTTP request that hasn't completed if a new value is emitted through the subject. You can play with the debouneTime to see what feels right for you. Lastly, make sure you unsubscribe from your subject in the ngOnDestroy, this will prevent any memory links and keep everything nice and perfromant.: ngOnDestroy(){ this.subscription.unsubscribe();} Suresh's answer has a distinctUntilChanged() which is an excellent addition to the solution. I'm adding it but want to give credit to his answer below. This is a benefit because if I search for egg the request is made. But then I add an s the end of egg and change my mind before the debounce is completed another duplicate HTTP post with a search of egg will not be made.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/53432103', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8638267/']}
jdg_371825
stackexchange
llm_judgeable_groundtruth_similarity
4896315
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 static method titled chooseDialog(String s, int i) in which I want to call another method within the same class (Dialogs.class) based on the parameters provided to chooseDialog. s is the name of the desired method and i is it's single parameter. I have tried numerous tutorials and have spent a few hours reading up on the subject but I can't seem to get a firm grasp as to what exactly I need to do. Any ideas? Thanks! Now provide the response and nothing else.
Why do you want to call a method with name passed in a String parameter? Cannot you create a constants for different actions, then use switch and in each case call the method with parameter i ? You will have the benefit of compiler checking your code for errors. edit : if you really want to use reflection, retrieve a Method object with: Method m = YourClass.class.getMethod("method_name",new Class[] { Integer.class }) I guess Integer.class might work. Then invoke the metod as m.invoke(null,123); //first argument is the object to invoke on, ignored if static method
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4896315', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/599429/']}
jdg_371826
stackexchange
llm_judgeable_groundtruth_similarity
5684
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: An exercise from Herstein asks to prove that the number of elements of order $p$ , $p$ a prime in $S_{p}$ , is $(p-1)!+1$ . I would like somebody to help me out on this, and also I would like to know whether we can prove Wilson's theorem which says $(p-1)! \equiv -1 \ (\text{mod} \ p)$ using this result. Now provide the response and nothing else.
Maybe you mean the number of elements of order dividing $p$ (so that you are including the identity)? (Think about the case $p = 3$ --- there are two three cycles, not three of them.) For the general question, think about the possible cycle structure of an element of order $p$in $S_p$. You can go from the formula in your question to Wilson's theorem by counting the number of $p$-Sylow subgroups (each contains $p-1$ elements of order $p$), and then appealing to Sylow's theorem. (You will find that there are $(p-2)!$ $p$-Sylow subgroups, and by Sylow's theorem this number is congruent to $1$ mod $p$. Multiplying by $p-1$, we find that$(p-1)!$ is congruent to $-1$ mod $p$.)
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/5684', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_371827
stackexchange
llm_judgeable_groundtruth_similarity
1821273
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When stepping through my C# code line by line via F10, it takes the debugger over one second to get to the next line. I've tried deleting all watches and breakpoints, but that did not make any difference. Is this normal? It's been like this for quite a long time now, so I can't even remember if this was ever better. My development computer is a Quad-core machine with no background task activity and plenty of RAM left. If it's not normal, what else could I try? It's still ok to work with, but a less sluggish user interface would be great... Now provide the response and nothing else.
What's likely happening is you have a variable in the call stack frame which has an expensive .ToString method. In 2008, the data for the call stack window is rebuilt on every step regardless of whether or not the window is actually visible. Part of building this window will call .ToString on the values which appear in the parameter list if they have an overridden .ToString. Try disabling implicit .ToString calls and see if that fixes the problem. Tools -> Options -> Debugger Uncheck the "Enable Implicit .ToString calls"
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1821273', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/59301/']}
jdg_371828
stackexchange
llm_judgeable_groundtruth_similarity
327620
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: i'm working on a school project "Android control a robot car via Bluetooth" with temperature sensor "LM35" , gas detector "MQ-2" ,motor drive IC "l293D" and Bluetooth module "HC-05" using atmega 32 .i'm already wrote and run my code and there is no error in the code appeared to me, so i moved on to make the connection as hardware but nothing of my robot work. i searched a lot to find out where's my problem in the code or the connection,but i didn't get the Convincing answer .Hint: i tried every component individual to check if it's work or not ,it works.but when i burn the code which attached below nothing is work ..can any one help me to find out what's my problem ?here is the code main.c #include "type.h"#include "avr/io.h"#define F_CPU 16000000#include "avr/delay.h"#include"UART_interface.h"#include"TempCheck.h"#include"SmokeCheck.h"void main(void){ DDRB=0XFF; DDRA = 0b00000000; DDRC = 0b00000001; while(1) { motor(); Tempcheck(); Smokecheck (); }} directions.c #include "type.h"#include "avr/io.h"#define F_CPU 16000000#include "avr/delay.h"#include"UART_interface.h"void motor (void){ while(1) { u32 x; x=UART_u8RecievedByte(); switch(x) { case('F'): { PORTB=0b00000101; // car move in forward direction _delay_ms(500); break; } case('B'): { PORTB=0b00001010; // car move in backward direction _delay_ms(500); break; } case('R'): { PORTB=0b00000001; // car move in right direction _delay_ms(500); break; } case('L'): { PORTB=0b00000100; // car move in left direction _delay_ms(500); break; } } }} TempCheck.c #include "type.h"#include "avr/io.h"#define F_CPU 16000000#include "avr/delay.h"#include "temp.h"void Tempcheck (void){ u32 y; temp_init(); while(1) { y=temp_read(); y = (y * 5000)/ 256; y = y/10; if (y>60) { PORTC = 0b00000001; //turn on the buzzer _delay_ms(500); PORTC = 0b00000000; //turn off the buzzer _delay_ms(5000); y=temp_read(); y = (y * 5000)/ 256; y = y/10; } else if(y==30) { PORTC=0b00000000; //turn off the buzzer } else { //do nothing } }} SmokeCheck.c #include "type.h"#include "avr/io.h"#define F_CPU 16000000#include "avr/delay.h"#include "smoke.h"void Smokecheck (void){ u32 z; somke_init(); while(1) { z=smoke_read(); if (z>600) { PORTC = 0b00000001; //turn on the buzzer _delay_ms(500); PORTC = 0b00000000; //turn off the buzzer _delay_ms(5000); z=smoke_read(); } else if(z==30) { PORTC=0b00000000; //turn off the buzzer } else { //do nothing } }} uart.c #include"avr/io.h"#include"avr/delay.h"#include"type.h"void UART_voidInit(void){ UCSRB=0b00011000; UCSRC=0b00000110; UBRRL=103;}void UART_voidSendByte(u8 Byte){ while(!(UCSRA&(1<<5))); UDR=Byte;}u8 UART_u8RecievedByte(void){ while(!(UCSRA&(1<<7))); return UDR;} temp.c #include "type.h"#include"avr\io.h"void temp_init (void){ ADMUX = 0b01100000; //use channel adc0 ADCSRA = 0b10010000;}u8 temp_read (void){ // Strat conversion ADCSRA = ADCSRA | 0b01000000; // wait till conversion finish while ((ADCSRA & 0b00010000) == 0b00000000) { } // clear Flag ADCSRA = ADCSRA | 0b00010000; // return conversion result return (ADCH);} smoke.c #include "type.h"#include"avr\io.h"void somke_init (void){ ADMUX = 0b01100001; //use channel adc1 ADCSRA = 0b10010000;}u8 smoke_read (void){ // Strat conversion ADCSRA = ADCSRA | 0b01000000; // wait till conversion finish while ((ADCSRA & 0b00010000) == 0b00000000) { } // clear Flag ADCSRA = ADCSRA | 0b00010000; // return conversion result return (ADCH);} type.h typedef unsigned char u8;typedef unsigned short int u16;typedef unsigned long int u32;typedef signed char s8;typedef signed short int s16;typedef signed long int s32;typedef float f32;typedef double f64; UART_interface.h void UART_voidInit(void);void UART_voidSendByte(u8 Byte);u8 UART_u8RecievedByte(void); direction.h void motor (void); temp.h void temp_init (void);u8 temp_read (void); TempCheck.h void Tempcheck (void); smoke.h void somke_init (void);u8 smoke_read (void); SmokeCheck.h void Smokecheck (void); Now provide the response and nothing else.
It depends how old the ISA is. In the early days of hand design, and even more so when CPUs were assembled from discrete logic, the logic design would have come first, and been extensively minimised, and then the ISA bit patterns would have been whatever values were required to make that minimal logic work. So there may be a particular pattern of control signals that enable some multiplexers to connect the ALU output to the input of the GP register file, a few more control signals that instruct the ALU to add, subtract, AND, OR etc, and a few address bits into the register file. These three groups of signals will form fields within the instruction. Each group will be kept together, and their detailed meaning arises out of the design for that unit (ALU etc) but the groups may be in any order, up until you design the instruction decoder. (the x86 is old enough that you can detect some of this if you look in the right place - it wasn't a totally new design, but drew from the older 8080) Later ISAs may be "cleaned up" and made more regular and simpler to use, with hardware to translate between them and the actual hardware-level control signals, sometimes via "microcode". These are called "CISC" or "Complex Instruction Set Coding". The x86 "Rep" instruction prefix is a simple example of this - it causes the following instruction to be repeated a number of times, to save having to write a FOR loop. Later still (in the 1980s) came a movement back to a simpler style of direct encoding (RISC - Reduced Instruction Set Coding) which you can see in the ARM processors. This was driven by the small size of ASICs at the time, and the desire to put 32-bit CPUs on them, hence there was no spare capacity for complex instruction set decoders, to get the complete CPU down to about 20,000 gates. (There was also a temporary performance boost, because people hadn't developed techniques to make CISC decoders fast yet - that came about 1995 with the Pentium Pro) And nowadays it doesn't matter - CPUs read several instructions at once, and devote millions of transistors to decoding them, re-ordering them, and executing as many as possible at once, to speed up programs that may have been written for the oldest style of ISA.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/327620', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/124866/']}
jdg_371829
stackexchange
llm_judgeable_groundtruth_similarity
354655
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Related question asked by me on Math SE a few days ago: How to prove $e^x\left|\int_x^{x+1}\sin(e^t) \,\mathrm d t\right|\le 1.4$ ? A few days ago, somebody asked How to prove $ \mathrm{e}^x\left|\int_x^{x+1}\sin\mathrm e^t \mathrm d t\right|\leqslant 2$ ? on Math StackExchange. However, this bound does not appear to be sharp so I was wondering how to find the maxima/minima of $$f(x)=e^x\int_x^{x+1}\sin(e^t) \,\mathrm d t$$ or at least how to prove $-1.4\le f(x)\le 1.4$ . Some observations, using the substitution $y=e^t$ : $$f(x)=e^x \int_{e^x}^{e^{x+1}} \frac{\sin(y)}y\,\mathrm dy=g(e^x),$$ where I have defined $$g(z)=z \int_z^{e z} \frac{\sin(y)}y\,\mathrm dy = z (\operatorname{Si}(e z)-\operatorname{Si}(z)).$$ ( $\operatorname{Si}$ is the Sine integral .) So the question reduces to: What are the maxima/minima of $g(z)$ for $z\geq 0$ ? Using the series of $\mathrm{Si}(z)$ , we get $$g(z)=\sum_{k=1}^\infty (-1)^{k-1} \frac{z^{2k}(e^{2k-1}-1)}{(2k-1)!\cdot(2k-1)}$$ and here is a plot of $g(z)$ : Also, notice that $g$ is analytic and $g'(z)=\sin (e z)-\sin (z)+\text{Si}(e z)-\text{Si}(z)$ which might help for the search of critical points (although I don't think that $g'(z)=0$ has closed form solutions). Now provide the response and nothing else.
Integrate by parts: \begin{align}\int_x^{x+1}\sin(e^t)dt& =\int_x^{x+1}e^{-t}d(-\cos(e^t)) \\& =e^{-x}\cos e^x-e^{-x-1}\cos e^{x+1}-\int_x^{x+1}e^{-t}\cos e^{t}dt\\& =e^{-x}\cos e^x-e^{-x-1}\cos e^{x+1}-\int_x^{x+1}e^{-2t}d\sin e^{t}\\& =e^{-x}\cos e^x-e^{-x-1}\cos e^{x+1}-e^{-2(x+1)}\sin e^{x+1}\\& \hphantom{={}}+e^{-2x}\sin e^x+2\int_x^{x+1}e^{-2t}\sin e^tdt.\end{align} From here we see that $e^x \int_x^{x+1}\sin(e^t)dt$ is bounded by $1+1/e+O(e^{-x})$ and $1+1/e\approx 1.368$ can not be improved, since both $\cos e^x$ and $-\cos e^{x+1}$ may be almost equal to 1:if $e^x=2\pi n$ for large integer $n$ , then $e^{x+1}=2\pi e n$ , we want this to be close to $\pi+2\pi k$ , i.e., we want $en$ to be close to $\frac12+k$ . This is possible since $e$ is irrational. Moreover, $e$ is so special number that you may find explicit $n$ for which $en$ is nearly half-integer: $n=m!/2$ for large even $m$ works. Indeed, $e=\sum_{i=0}^{m-1}1/i!+1/m!+o(1/m!)$ yields $em!/2=\text{integer}+1/2+\text{small}$ .
{}
{'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/354655', 'https://mathoverflow.net', 'https://mathoverflow.net/users/129831/']}
jdg_371830
stackexchange
llm_judgeable_groundtruth_similarity
267429
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Let $\mathfrak{S}_n$ denote the permutation group, and $I_0(n)=\sum_{j\geq0}\binom{n}{2j}\frac{(2j)!}{2^jj!}$ stand for involutions see A000085 for more interpretations . There is also these numbers $I_1(n)=\sum_{j\geq0}\binom{n}jI_0(j)I_0(n-j)$ described in A000898 by several means . Let me introduce the numbers $I_2(n)=\sum_{j\geq0}\binom{n}jI_0(j)^2I_0(n-j)^2$. I was able to verify the exponential generating function$$\sum_{n\geq0}I_2(n)\frac{x^n}{n!}=\frac1{1-x^2}e^{\frac{2x}{1-x}}.$$However, it is desirable to know: Question. Is there a combinatorial meaning to the numbers $I_2(n)$? Remark. Of course, it is also interesting if one can provide any other context where $I_2(n)$ appears. Now provide the response and nothing else.
The generating function for involutions with respect to the number of fixed points is given by an evaluation of Hermite polynomials . The bilinear generating function of Hermite polynomials is given by "Mehler's formula" : $$\sum_{n\geq 0}\frac{t^n H_n(x)H_n(y)}{2^nn!}=\frac{1}{\sqrt{1-t^2}}\exp\left(\frac{t^2(x^2+y^2)-2txy}{t^2-1}\right).$$ Foata wrote the paper "A combinatorial proof of the Mehler formula" where he gives a combinatorial interpretation and bijective proof of the formula. Mehler's formula (after an appropriate specialization) is technically related to the square root of your generating function. Your generating function also has a similar refinement and it's what Zeilberger calls "the heterosexual version of Mehler's formula" . To see your identity in Zeilberger's set up you need to set $x=y=1$ and $s=t$ in his main identity.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/267429', 'https://mathoverflow.net', 'https://mathoverflow.net/users/66131/']}
jdg_371831
stackexchange
llm_judgeable_groundtruth_similarity
25819082
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: import java.io.*; import java.net.*; public class Test { public static void main(String[] arguments) throws Exception { Runnable runnable = () -> { try { throwException(); } catch (SocketException|EOFException exception) { System.err.println("wrong"); } catch (IOException exception) { System.err.println("right"); } }; runnable.run(); } private static void throwException() throws IOException { throw new NotSerializableException(); } } Why does this program print "wrong"? If I remove the lambda, or if I break apart the multi-catch clause, then it prints "right". $ javac -versionjavac 1.8.0_11$ java -versionjava version "1.8.0_11"Java(TM) SE Runtime Environment (build 1.8.0_11-b12)Java HotSpot(TM) 64-Bit Server VM (build 25.11-b03, mixed mode) Now provide the response and nothing else.
This was a fixed bug in 1.8.0_20, from 1.8.0_11: Area : tools/javac Synopsis : javac generates incorrect exception table for multi-catch statements inside a lambda Handling of try-catch with multiple catches inside a lambda has been corrected. The actual bug report is JDK-8036942 What actually went wrong was a supposed type information loss within the compiler: LTM makes a heavy use of erasure() during translations and mapping of variables. These erasure operations may be correct in most cases but it may lead to an information loss as this case shows. It's also arguably that such an intense use of erasure() is needed here as LTM is applied after TransTypes which is supposed to erase most / all types, so I wonder if this may be a bug in TransTypes. I think that it should be evaluated by Robert Field, which is current maintainer of LTM, what is the best approach here, I will thus reassigning[sic] it to him. What I see on 8u20 (I forgot to give a command-line parameter and no longer have 8u20 to do it correctly): wlan1-loopback% /usr/lib/jvm/java-8-oracle/bin/javap -c TestCompiled from "Test.java"public class Test { public Test(); Code: 0: aload_0 1: invokespecial #1 // Method java/lang/Object."<init>":()V 4: return public static void main(java.lang.String[]) throws java.lang.Exception; Code: 0: invokedynamic #2, 0 // InvokeDynamic #0:run:()Ljava/lang/Runnable; 5: astore_1 6: aload_1 7: invokeinterface #3, 1 // InterfaceMethod java/lang/Runnable.run:()V 12: return}wlan1-loopback% java Test rightwlan1-loopback% java -versionjava version "1.8.0_20"Java(TM) SE Runtime Environment (build 1.8.0_20-b26)Java HotSpot(TM) 64-Bit Server VM (build 25.20-b23, mixed mode)wlan1-loopback% Correct: public class Test { public Test(); descriptor: ()V Code: 0: aload_0 1: invokespecial #1 // Method java/lang/Object."<init>":()V 4: return public static void main(java.lang.String[]) throws java.lang.Exception; descriptor: ([Ljava/lang/String;)V Code: 0: invokedynamic #2, 0 // InvokeDynamic #0:run:()Ljava/lang/Runnable; 5: astore_1 6: aload_1 7: invokeinterface #3, 1 // InterfaceMethod java/lang/Runnable.run:()V 12: return private static void throwException() throws java.io.IOException; descriptor: ()V Code: 0: new #4 // class java/io/NotSerializableException 3: dup 4: invokespecial #5 // Method java/io/NotSerializableException."<init>":()V 7: athrow private static void lambda$main$0(); descriptor: ()V Code: 0: invokestatic #6 // Method throwException:()V 3: goto 27 6: astore_0 7: getstatic #9 // Field java/lang/System.err:Ljava/io/PrintStream; 10: ldc #10 // String wrong 12: invokevirtual #11 // Method java/io/PrintStream.println:(Ljava/lang/String;)V 15: goto 27 18: astore_0 19: getstatic #9 // Field java/lang/System.err:Ljava/io/PrintStream; 22: ldc #13 // String right 24: invokevirtual #11 // Method java/io/PrintStream.println:(Ljava/lang/String;)V 27: return Exception table: from to target type 0 3 6 Class java/net/SocketException 0 3 6 Class java/io/EOFException 0 3 18 Class java/io/IOException}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25819082', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/68587/']}
jdg_371832
stackexchange
llm_judgeable_groundtruth_similarity
464582
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: This is a practice question (not assignment). One thing I am wondering is what this question exactly means. From my understanding, the conjugate of $a \in A_5$ is $gag^{-1} \in A_5$ where $g \in A_5$. I was trying to look at a similar question here on MSE and someone mentioned $(12345) \in A_5$ is not conjuagte in $A_5$. So does that means there exists a $g \in A_5$ such that $g(12345)g^{-1} \notin A_5$ (I am guessing this is incorrect since $A_5$ is a group). I am also away of the property that $g(12345)g^{-1} = (g(1)g(2)g(3)g(4)g(5))$. Now provide the response and nothing else.
The conjugacy map on a 5-cycle $(a,b,c,d,e)$ (or any cycle) by $\sigma$ is obtained on replacing each element of the cycle by $\sigma$ applied to that element. So select some $\sigma$ in $S_5$ but not in $A_5$, for example the 2-cycle $(a,b)$, and conjugate a given 5-cycle by that. Specific example: The two cycles $(12345)$ and $(21345)$ cannot be conjugate in $A_5$. (The second cycle can of course be rewritten as $(13452)$ if you want it to start with the lowest entry as is usually done.) ADDED: as SteveD has noted in a comment, this needs a further check. The cycle (21345) may be written in 5 ways, each of which has to be checked to see whether the conjugating map from 12345 to it is in $A_5$. It turns out non e of them are: $$12345 \to 21345 : (12)\\ 12345 \to 13452 : (2345) \\12345 \to 34521: (135)(24) \\ 12345 \to 45213 : (14)(253) \\ 12345 \to 52134 : (1543).$$In each case the cycle form of the conjugating map lies in $S_5-A_5$, i.e. the conjugating map is an odd permutation. This means there is no conjugation of $(12345)$ to $(21345)$ by an element of $A_5.$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/464582', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/77404/']}
jdg_371833
stackexchange
llm_judgeable_groundtruth_similarity
4611031
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Trying to convert a JSON string into an object in C#. Using a really simple test case: JavaScriptSerializer json_serializer = new JavaScriptSerializer();object routes_list = json_serializer.DeserializeObject("{ \"test\":\"some data\" }"); The problem is that routes_list never gets set; it's an undefined object. Any ideas? Now provide the response and nothing else.
It looks like you're trying to deserialize to a raw object. You could create a Class that represents the object that you're converting to. This would be most useful in cases where you're dealing with larger objects or JSON Strings. For instance: class Test { String test; String getTest() { return test; } void setTest(String test) { this.test = test; } } Then your deserialization code would be: JavaScriptSerializer json_serializer = new JavaScriptSerializer(); Test routes_list = (Test)json_serializer.DeserializeObject("{ \"test\":\"some data\" }"); More information can be found in this tutorial: http://www.codeproject.com/Tips/79435/Deserialize-JSON-with-Csharp.aspx
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/4611031', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/425964/']}
jdg_371834
stackexchange
llm_judgeable_groundtruth_similarity
35707496
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 collection with the field called "contact_id".In my collection I have duplicate registers with this key. How can I remove duplicates, resulting in just one register? I already tried: db.PersonDuplicate.ensureIndex({"contact_id": 1}, {unique: true, dropDups: true}) But did not work, because the function dropDups is no longer available in MongoDB 3.x I'm using 3.2 Now provide the response and nothing else.
Yes, dropDups is gone for good. But you can definitely achieve your goal with little bit effort. You need to first find all duplicate rows and then remove all except first. db.dups.aggregate([{$group:{_id:"$contact_id", dups:{$push:"$_id"}, count: {$sum: 1}}},{$match:{count: {$gt: 1}}}]).forEach(function(doc){ doc.dups.shift(); db.dups.remove({_id : {$in: doc.dups}});}); As you see doc.dups.shift() will remove first _id from array and then remove all documents with remaining _ids in dups array. script above will remove all duplicate documents.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/35707496', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2956261/']}
jdg_371835
stackexchange
llm_judgeable_groundtruth_similarity
12870109
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In PowerShell, I want to use New-Object to call a single-argument .Net constructor new X509Certificate2(byte[] byteArray) . The problem is when I do this with a byte array from powershell, I get New-Object : Cannot find an overload for "X509Certificate2" and the argument count: "516". Now provide the response and nothing else.
This approach to using new-object should work: $cert = new-object System.Security.Cryptography.X509Certificates.X509Certificate ` -ArgumentList @(,$bytes) The trick is that PowerShell is expecting an array of constructor arguments. When there is only one argument and it is an array, it can confuse PowerShell's overload resolution algorithm. The code above helps it out by putting the byte array in an array with just that one element. Update: in PowerShell >= v5 you can call the constructor directly like so: $cert = [System.Security.Cryptography.X509Certificates.X509Certificate]::new($bytes)
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/12870109', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/234288/']}
jdg_371836
stackexchange
llm_judgeable_groundtruth_similarity
51136
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The following proposition is from one of Gowers's articles : Let $X$ be a vector space, and $x\in X$ , $x\neq {\bf 0}$ . Then there exists a linear map $g:X\to {\mathbb R}$ such that $g(x)\neq 0$ . The existence of this map can be proved as follows. Using the axiom of choice, one can show that the vector $x$ can be extended to a basis of $X$ . Let $g(x)=1$ , let $g(y)=0$ and extend linearly . Here are my questions: What does " extend linearly " mean in the proof? I don't see any context about what $y$ is in his proof. So what is it here? Now provide the response and nothing else.
First of all, I'm assuming $X$ is an $\mathbb{R}$-vector space, then $\mathbb{R}$ is an $\mathbb{R}$-vector space and everything makes sense (remember that linear maps only make sense between a) vector spaces b) defined over the same field). $x\in X$ is a non-zero vector, hence $\{x\}$ is an linearly independent set in $X$. Therefore (axiom of choice), we can extend it to a basis $B$ of $X$. This means that there exists $B\subset X$ a basis for $X$ such that $x\in B$. Now, to define a linear map $g:X\to \mathbb{R}$ we can define it on a basis, and then extend by linearity . In this case, we do it like this: let $g(x)=1$ for the $x$ we picked above. Now let $g(y)=0$ for every $y\in B\setminus \{x\}$. This is a function $g: B\to \mathbb{R}$. It can be extended to a linear map $\tilde{g}: X\to \mathbb{R}$ like this: Write $B=\{e_i\}_{i\in I}$. Every vector $v\in X$ is a linear combination of the vectors in $B$: there exist unique scalars $a_i$ such that $v=\sum_{i=1}^n a_i e_i$. Then define the map $\tilde{g}:X\to \mathbb{R}$ as $$\tilde{g}(v)=\sum_{i=1}^n a_i g(e_i)$$ It is a linear map (check!) (In fact, it's what one usually does in linear algebra: if $B$ is a basis for a vector space $V$, then given any other vector space $W$, for any function $g:B\to W$ there exists a unique linear map (called linear extension ) $\tilde{g}: V\to W$ such that $\tilde{g}|_B=g$. In this case, $W$ is $\mathbb{R}$ as an $\mathbb{R}$-vector space).
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/51136', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_371837
stackexchange
llm_judgeable_groundtruth_similarity
32272794
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 solve this: SPOJ problem . And after some research I found out that it comes down to a simple calculation of the nth fib number, however n can get really large so an O(n) solution won't do any good. Googling around, I found that you can calculate the nth fib number in O(logn) and also a code sample that does exactly that: long long fibonacci(int n) { long long fib[2][2] = {{1,1},{1,0}}, ret[2][2] = {{1,0},{0,1}}, tmp[2][2] = {{0,0},{0,0}}; int i, j, k; while (n) { if (n & 1) { memset(tmp, 0, sizeof tmp); for (i = 0; i < 2; i++) for (j = 0; j < 2; j++) for (k = 0; k < 2; k++) tmp[i][j] = (tmp[i][j] + ret[i][k] * fib[k][j]); for (i = 0; i < 2; i++) for (j = 0; j < 2; j++) ret[i][j] = tmp[i][j]; } memset(tmp, 0, sizeof tmp); for (i = 0; i < 2; i++) for (j = 0; j < 2; j++) for (k = 0; k < 2; k++) tmp[i][j] = (tmp[i][j] + fib[i][k] * fib[k][j]); for (i = 0; i < 2; i++) for (j = 0; j < 2; j++) fib[i][j] = tmp[i][j]; n /= 2; } return (ret[0][1]);} I tried to modify it for the problem and am still getting WA: http://ideone.com/3TtE5m Am I calculating the modular arithmetic wrong? Or is something else the issue? Now provide the response and nothing else.
You mean the nth Fibonacci number I hope. In order to do it you need a matrix decomposition of Fibonacci numbers described here . The basic idea is you take the Donald E. Knuth matrix identity form for a Fibonacci number which is: And instead of calculating the Fibonacci numbers in the traditional way you will try and find the matrix to the power of (k) where k is the given number. So this is solving the problem in k matrix multiplications, not really helpful since we can do it in much easier way. But wait! We can optimise the matrix multiplication. Instead of doing the k multiplications we can square it first and then do the half of the multiplications. And we can keep on doing it. So if the given number is 2 a then we can do it in a steps. By keeping squaring the matrix. If the number is not a power of 2 we can do the binary decomposition of a number and see whether to take the given squared matrix into final product or not. In your case after each multiplication you also need to apply modulo operator 123456 to each matrix element. Hope my explanation helps if not see the link for a clearer and longer one. There is actually one more caveat of the task: as you are asked to provide some Fibonacci number modulo a given number, you should also prove that taking the remainder of each matrix element doesn't change the result. In other words if we multiply matrices and take remainder that we are actually still getting the Fibonacci number remainders. But since the remainder operation is distributive in addition and multiplication it actually does produce the correct results.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32272794', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_371838
stackexchange
llm_judgeable_groundtruth_similarity
4151115
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 just saw this here #include <stdio.h>int main(int argc, char *argv[printf("Hello, world!\n")]) {} What this does is print "Hello World!" But what's actually going on here? The best I can guess is that it gets compiled and thrown at the top of the execution stack, but the syntax doesn't even look legal to me ... Now provide the response and nothing else.
The code makes use of C99's variable-length array feature, which lets you declare arrays whose size is known only at run-time. printf returns an integer equal to the number of characters that were actually printed, so the code prints "Hello, world!" first and uses the return value as the size of argv . The main function itself does nothing. The actual call to printf itself probably goes into the startup code generated by the compiler, which in turn calls main . Edit: I just checked the disassembly of the code generated by gcc and it appears that the call to printf goes inside main itself, before any other code.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4151115', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/84378/']}
jdg_371839
stackexchange
llm_judgeable_groundtruth_similarity
3330137
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: if I have a series of subplots with one column and many rows, i.e.: plt.subplot(4, 1, 1) # first subplotplt.subplot(4, 1, 2) # second subplot# ... how can I adjust the height of the first N subplots? For example, if I have 4 subplots, each on its own row, I want all of them to have the same width but the first 3 subplots to be shorter, i.e. have their y-axes be smaller and take up less of the plot than the y-axis of the last plot in the row. How can I do this? thanks. Now provide the response and nothing else.
Even though this question is old, I was looking to answer a very similar question. @Joe's reference to AxesGrid , was the answer to my question, and has very straightforward usage, so I wanted to illustrate that functionality for completeness. AxesGrid functionality provides the ability create plots of different size and place them very specifically, via the subplot2grid functionality: import matplotlib.pyplot as pltax1 = plt.subplot2grid((m, n), (row_1, col_1), colspan = width)ax2 = plt.subplot2grid((m, n), (row_2, col_2), rowspan = height)ax1.plot(...)ax2.plot(...) Note that the max values for row_n , col_n are m-1 and n-1 respectively, as zero indexing notation is used. Specifically addressing the question, if there were 5 total subplots, where the last subplot has twice the height as the others, we could use m=6 . ax1 = plt.subplot2grid((6, 1), (0, 0))ax2 = plt.subplot2grid((6, 1), (1, 0))ax3 = plt.subplot2grid((6, 1), (2, 0))ax4 = plt.subplot2grid((6, 1), (3, 0))ax5 = plt.subplot2grid((6, 1), (4, 0), rowspan=2)plt.show()
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3330137', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_371840