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
9020409
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a string that I'm encoding into base64 to conserve space. Is it a big deal if I remove the equal sign at the end? Would this significantly decrease entropy? What can I do to ensure the length of the resulting string is fixed? >>> base64.b64encode(combined.digest(), altchars="AB")'PeFC3irNFx8fuzwjAzAfEAup9cz6xujsf2gAIH2GdUM=' Thanks. Now provide the response and nothing else.
Looking at your code: >>> base64.b64encode(combined.digest(), altchars="AB")'PeFC3irNFx8fuzwjAzAfEAup9cz6xujsf2gAIH2GdUM=' The string that's being encoded in base64 is the result of a function called digest() . If your digest function is producing fixed length values (e.g. if it's calculating MD5 or SHA1 digests), then the parameter to b64encode will always be the same length. If the above is true, then you can strip of the trailing equals signs, because there will always be the same number of them. If you do that, simply append the same number of equals signs to the string before you decode. If the digest is not a fixed length, then it's not safe to trim the equals signs. Edit: Looks like you might be using a SHA-256 digest? The SHA-256 digest is 256 bits (or 32 bytes). 32 bytes is 10 groups of 3, plus two left over. As you'll see from the Wikipedia section on padding ; that'd mean you always have one trailing equals. If it is SHA-256, then it'd be OK to strip it, so long as you remember to add it again before decoding.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9020409', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/216605/']}
jdg_86441
stackexchange
llm_judgeable_groundtruth_similarity
4379873
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 coming up with the wrong answer. The problem is $\sin[\arctan(4x)]$ Here are the reciprocal functions I am using $\sin\theta= \frac {1}{\csc\theta}$ and $\cot\theta = \frac{1}{\tan\theta}$ Here is the Pythagorean identity I am using $\csc^2 \theta = 1+\cot^2 \theta$ I am trying to rewrite the problem $\sin[\arctan(4x)]$ in terms of the Pythagorean Identity using the reciprocal identities. $$ \frac{1}{\csc^2 \theta} = \frac {1}{1 + \frac{1}{1+\tan^2 \theta}}$$ This seems to be a stretch, I do not think I am expressing the Pythagorean Identity right, and I am not sure how to either. I did start to try to plug in the numbers. $$ \frac{1}{\csc^2 \theta} = \frac {1}{1 + \frac {1}{(4x^2)}}$$ $$ \frac{1}{\csc \theta} = \sqrt{1+4x} $$ $$\sin\theta = \frac{1}{\sqrt{1+4x}} $$ I could rationalize the denominator and multiply the by its conjugate to get; $$\frac{\sqrt{1-4x}}{\sqrt{(1+4x)(1-4x)}} $$ But, at this point I know I am wrong. The answer is $$ \frac{4x}{\sqrt{16x^2+1}}$$ Now provide the response and nothing else.
I am going to bypass examining your work, because the problem permits a very easy shortcut. If you have a right triangle, whose tangent is $(4x)$ , then the legs are (in effect) $(4x)$ and $(1)$ . Therefore, the hypotenuse is $~\displaystyle \sqrt{16x^2 + 1}.$ Therefore, the sine of this angle must be $$\frac{4x}{\sqrt{16x^2 + 1}}.$$ Addendum Responding to the comment of Dan: Need to show that it's still valid when $x < 0$ . I agree, my oversight. When $x < 0,$ you can let $y = -x \implies y > 0$ . Then, if $\tan(\theta) = 4x$ , you have that $\tan(-\theta) = 4y.$ Then, by the analysis at the start of this answer, $\sin(-\theta) = \displaystyle ~\frac{4y}{\sqrt{16y^2 + 1}} = \frac{-4x}{\sqrt{16x^2 + 1}}.$ Therefore, since $\sin(\theta) = -\sin(-\theta)$ , you have that $\sin(\theta) = \displaystyle \frac{4x}{\sqrt{16x^2 + 1}}.$ Edit In my opinion, an open issue is whether the Addendum is actually needed. In Analytical Geometry, where the domain of trig functions are angles, you have the issue of whether a right triangle can be constructed , some of whose side lengths are negative. The analysis at the start of my answer was based on physically constructing the analogous right triangle. I don't know how the issue is being taught in Analytical Geometry, so it is better to add the Addendum, erring on the side of caution. In Real Analysis (AKA Calculus) the issue is somewhat convoluted, because the domain of the trig functions are real numbers, rather than angles. However, you can interpret the domain of the trig functions to be various arc lengths, with respect to the unit circle. Under this interpretation, it seems to me that the Addendum is not needed, because you can construct a right triangle [whose hypotenuse is $(1)$ ] that lies in the $4$ th quadrant just as appropriately as constructing a right triangle that lies in the $1$ st quadrant. Then, you have constructed a right triangle, one of whose legs is a negative number.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4379873', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/441156/']}
jdg_86442
stackexchange
llm_judgeable_groundtruth_similarity
541135
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: $$\int_0^1\frac{\mathrm dx}{\sqrt{1-x}\ \sqrt[4]x\ \sqrt[4]{2-x\,\sqrt3}}\stackrel?=\frac{2\,\sqrt2}{3\,\sqrt[8]3}\pi\tag1$$The equality numerically holds up to at least $10^4$ decimal digits. Can we prove that the equality is exact? An equivalent form of this conjecture is$$I\left(\frac{\sqrt3}2;\ \frac14,\frac14\right)\stackrel?=\frac23,\tag2$$where $I\left(z;\ a,b\right)$ is the regularized beta function . Even simpler case:$$\int_0^1\frac{\mathrm dx}{\sqrt{1-x}\ \sqrt[6]{9-x}\ \sqrt[3]x}\stackrel?=\frac\pi{\sqrt3},\tag3$$which is equivalent to$$I\left(\frac19;\ \frac16,\frac13\right)\stackrel?=\frac12.\tag4$$ A related question . Now provide the response and nothing else.
For $\alpha, \beta, \gamma \in (0,1)$ satisfying $\alpha+\beta+\gamma = 1$ and $\mu \in \mathbb{C} \setminus [1,\infty)$, define $$F_{\alpha\beta}(\mu) = \int_0^1\frac{dx}{x^\alpha(1-x)^\beta(1-\mu x)^\gamma}\quad\text{ and }\quad\Delta = \frac{\Gamma(1-\alpha)\Gamma(1-\beta)}{\Gamma(1+\gamma)}$$When $|\mu| < 1$, we can rewrite the integral $F_{\alpha\beta}(\mu)$ as $$\begin{align}F_{\alpha\beta}(\mu) = & \int_0^1 \frac{1}{x^\alpha(1-x)^{\beta}}\left(\sum_{n=0}^{\infty}\frac{(\gamma)_n}{n!}\mu^n x^n\right) dx= \sum_{n=0}^{\infty}\frac{(\gamma)_n}{n!}\frac{\Gamma(n+1-\alpha)\Gamma(1-\beta)}{\Gamma(n+1+\gamma)}\mu^n\\= & \Delta\sum_{n=0}^{\infty}\frac{(\gamma)_n (1-\alpha)_n}{n!(\gamma+1)_n}\mu^n= \Delta\gamma \sum_{n=0}^{\infty}\frac{(1-\alpha)_n}{n!(\gamma+n)}\mu^n\end{align}$$This implies $$\mu^{-\gamma} \left(\mu\frac{\partial}{\partial \mu}\right) \mu^{\gamma} F_{\alpha\beta}(\mu) = \Delta\gamma \sum_{n=0}^{\infty}\frac{(1-\alpha)_n}{n!}\mu^n= \Delta\gamma\frac{1}{(1-\mu)^{1-\alpha}}$$and hence$$F_{\alpha\beta}(\mu) = \Delta\gamma \mu^{-\gamma} \int_0^\mu \frac{\nu^{\gamma-1}d\nu}{(1-\nu)^{1-\alpha}}= \Delta\gamma \int_0^1 \frac{t^{\gamma-1} dt}{(1-\mu t)^{1-\alpha}}= \Delta \int_0^1 \frac{dt}{(1 - \mu t^{1/\gamma})^{1-\alpha}}$$ Notice if we substitute $x$ by $y = 1-x$, we have $$F_{\alpha\beta}(\mu) = \int_0^1 \frac{dy}{y^\beta(1-y)^\alpha(1-\mu - \mu y)^{\gamma}}= \frac{1}{(1-\mu)^\gamma} F_{\beta\alpha}(-\frac{\mu}{1-\mu})$$ Combine these two representations of $F_{\alpha\beta}(\mu)$ and let $\omega = \left(\frac{\mu}{1-\mu}\right)^{\gamma}$, we obtain $$F_{\alpha\beta}(\mu) = \frac{\Delta}{(1-\mu)^{\gamma}}\int_0^1 \frac{dt}{( 1 + \omega^{1/\gamma} t^{1/\gamma})^{1-\beta}} = \frac{\Delta}{\mu^\gamma}\int_0^\omega \frac{dt}{(1 + t^{1/\gamma})^{1-\beta}}$$ Let $(\alpha,\beta,\gamma) = (\frac14,\frac12,\frac14)$ and $\mu = \frac{\sqrt{3}}{2}$, the identity we want to check becomes $$\frac{\Gamma(\frac34)\Gamma(\frac12)}{\Gamma(\frac54) (\sqrt{3})^{1/4}}\int_0^\omega \frac{dt}{\sqrt{1+t^4}} \stackrel{?}{=} \frac{2\sqrt{2}}{3\sqrt[8]{3}} \pi\tag{*1}$$ Let $K(m)$ be the complete elliptic integral of the first kind associated with modulus $m$. i.e. $$K(m) = \int_0^1 \frac{dx}{\sqrt{(1-x^2)(1-mx^2)}}$$It is known that $\displaystyle K(\frac12) = \frac{8\pi^{3/2}}{\Gamma(-\frac14)^2}$. In term of $K(\frac12)$, it is easy to check $(*1)$ is equivalent to $$\int_0^\omega \frac{dt}{\sqrt{1+t^4}} \stackrel{?}{=} \frac23 K(\frac12)\tag{*2}$$ To see whether this is the case, let $\varphi(u)$ be the inverse function of above integral.More precisely, define $\varphi(u)$ by following relation: $$u = \int_0^{\varphi(u)} \frac{dt}{\sqrt{1+t^4}}$$ Let $\psi(u)$ be $\frac{1}{\sqrt{2}}(\varphi(u) + \varphi(u)^{-1})$. It is easy to check/verify$$\varphi'(u)^2 = 1 + \varphi(u)^4\implies\psi'(u)^2 = 4 (1 - \psi(u)^2)(1 - \frac12 \psi(u)^2)$$ Compare the ODE of $\psi(u)$ with that of a Jacobi elliptic functions with modulus $m = \frac12$, we find $$\psi(u) = \text{sn}(2u + \text{constant} | \frac12 )\tag{*3}$$ Since we are going to deal with elliptic functions/integrals with $m = \frac12$ only,we will simplify our notations and drop all reference to modulus, i.e $\text{sn}(u)$ now means $\text{sn}(u|m=\frac12)$ and $K$ means $K(m = \frac12)$. Over the complex plane, it is known that $\text{sn}(u)$ is doubly periodic withfundamental period $4 K$ and $2i K$. It has two poles at $i K$ and $(2 + i)K$ in the fundamental domain.When $u = 0$, we want $\varphi(u) = 0$ and hence $\psi(u) = \infty$. So the constantin $(*3)$ has to be one of the pole. For small and positive $u$, we want $\varphi(u)$ and hence $\psi(u)$ to be positive. This fixes the constant to $i K$. i.e. $$\psi(u) = \text{sn}(2u + iK )$$ and the condition $(*2)$ becomes whether following equality is true or not. $$\frac{1}{\sqrt{2}} (\omega + \omega^{-1}) \stackrel{?}{=} \text{sn}( \frac43 K + i K)\tag{*4}$$ Notice $ 3( \frac43 K + i K) = 4 K + 3 i K $ is a pole of $\text{sn}(u)$. if one repeatapply the addition formula for $\text{sn}(u+v)$ $$\text{sn}(u+v) = \frac{\text{sn}(u)\text{cn}(v)\text{dn}(v)+\text{sn}(v)\text{cn}(u)\text{dn}(u)}{1-m\,\text{sn}(u)^2 \text{sn}(v)^2}$$ One find in order for $\text{sn}(3u)$ to blow up, $\text{sn}(u)$ will be a root offollowing polynomial equation:$$3 m^2 s^8-4 m^2 s^6-4 m s^6+6 m s^4-1 = 0$$Substitute $m = \frac12$ and $s = \frac{1}{\sqrt{2}}(t+\frac{1}{t})$ into this, the equation $\omega$ need to satisfy is given by: $$(t^8 - 6 t^4 - 3)(3 t^8 + 6 t^4 - 1 ) = 0$$ One can check that $\omega = \sqrt[4]{\frac{\sqrt{3}}{2-\sqrt{3}}}$ is indeed a root of this polynomial. As a result, the original equality is valid.
{}
{'log_upvote_score': 8, 'links': ['https://math.stackexchange.com/questions/541135', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/19661/']}
jdg_86443
stackexchange
llm_judgeable_groundtruth_similarity
36722170
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 I can get access to parent's data variable (limitByNumber) in my child component Post? I tried to use prop but it doesn't work. Parent: import Post from './components/Post.vue';new Vue ({ el: 'body', components: { Post }, data: { limitByNumber: 4 }}); Component Post: <template> <div class="Post" v-for="post in list | limitBy limitByNumber"> <!-- Blog Post --> .... </div></template><!-- script --> <script>export default { props: ['list', 'limitByNumber'], created() { this.list = JSON.parse(this.list); }}</script> Now provide the response and nothing else.
Option 1 Use this.$parent.limitByNumber from child component. So your Component template would be like this <template> <div class="Post" v-for="post in list | limitBy this.$parent.limitByNumber" /> </template> Option 2 If you want to use props, you can also achieve what you want. Like this. Parent <template> <post :limit="limitByNumber" /></template><script>export default { data () { return { limitByNumber: 4 } }}</script> Child Pots <template> <div class="Post" v-for="post in list | limitBy limit"> <!-- Blog Post --> .... </div></template><script>export default { props: ['list', 'limit'], created() { this.list = JSON.parse(this.list); }}</script>
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/36722170', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4644010/']}
jdg_86444
stackexchange
llm_judgeable_groundtruth_similarity
11642
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: Let's say I have a Histogram : Histogram[RandomVariate[NormalDistribution[10, 2], 500]] and I want the bars positioned to the left of 8 on the horizontal axis to be a different colour. The Mathematica documentation shows how to do this for the height of bars, but not for their position: Histogram[RandomVariate[NormalDistribution[10, 2], 500], ColorFunction -> (Which[# < 40, Yellow, 40 <= # < 90, Red, True, Blue] &), ColorFunctionScaling -> False] How do I call the positions of the bars from Histogram and put them into my ColorFunction ? Now provide the response and nothing else.
You can use a custom ChartElementDataFunction as follows: cedF[{{xmin_, xmax_}, {ymin_, ymax_}}, ___] :={If[xmax <= 8, RGBColor[1, 0, 0], Sequence[]], Dynamic@EdgeForm[Directive[Thickness[.015], Lighter@CurrentValue["Color"]]], Rectangle[{xmin, ymin}, {xmax, ymax}, RoundingRadius -> 5]};Histogram[RandomVariate[NormalDistribution[10, 2], 500],ChartStyle -> "Pastel", ChartElementFunction -> cedF] EDIT: Adding arguments to cedf : cedf2[from_,to_,color_: Red, t_:Small, rr_: 0][{{xmin_, xmax_}, {ymin_, ymax_}}, ___] := {If[from < xmax <= to, color, Sequence[]], Dynamic@EdgeForm[Directive[Thickness[t], Lighter@CurrentValue["Color"]]], Rectangle[{xmin, ymin}, {xmax, ymax}, RoundingRadius -> rr]} Histogram[RandomVariate[NormalDistribution[10, 2], 500], ChartStyle -> "Pastel", ChartElementFunction -> cedf2[6, 10, Purple, Small, 3]] Alternatively, you can build a custom data function using the built-in ChartElementDataFunctions : sgmntsclF = ChartElementDataFunction["SegmentScaleRectangle", "Segments" -> 8, "ColorScheme" -> "TemperatureMap"];grdntrctF = ChartElementDataFunction["GradientRectangle", "ColorScheme" -> "Rainbow", "GradientOrigin" -> Top];Histogram[RandomVariate[NormalDistribution[10, 2], 500], ChartStyle -> "Pastel", ChartElementFunction -> ((If[7 < #[[1, 2]] <= 10, sgmntsclF[##], grdntrctF[##]]) &)]
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/11642', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/2329/']}
jdg_86445
stackexchange
llm_judgeable_groundtruth_similarity
21795336
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 disable the swipe delete feature of an android notification from the notifications list in android. Please help me. Thanks in advance. Now provide the response and nothing else.
Try this code builder.setOngoing(true); // Cant cancel your notification (except notificationManager.cancel(); ) Above code in Notifcation Builder. public void DisplayNotification() {// Use NotificationCompat.Builder to set up our notification.NotificationCompat.Builder builder = new NotificationCompat.Builder(this);//icon appears in device notification bar and right hand corner of notificationbuilder.setSmallIcon(R.drawable.ic_stat_notification);// This intent is fired when notification is clickedIntent tapIntent = new Intent(CurrentActivity.this, SecondActivity.class);PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, tapIntent, 0);// Set the intent that will fire when the user taps the notification.builder.setContentIntent(pendingIntent);builder.setOngoing(true); // Cant cancel your notification (except NotificationManger.cancel(); )// Content title, which appears in large type at the top of the notificationbuilder.setContentTitle("Notifications Title");// Content text, which appears in smaller text below the titlebuilder.setContentText("Your notification content here.");NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);// Will display the notification in the notification barnotificationManager.notify(NOTIFICATION_ID, builder.build());} Cancel Notification public void cancelNotification() { mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); mNotificationManager.cancel(NOTIFICATION_ID); // Notification ID to cancel } Happy Coding :)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21795336', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/954911/']}
jdg_86446
stackexchange
llm_judgeable_groundtruth_similarity
43585380
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: We sign our executables on the build server. Suddenly the build server failed to build giving the error: SingTool Error: The sepcified timestamp server either could not be reached or returned an invalid response. After changing the timestamp server to http://sha256timestamp.ws.symantec.com/sha256/timestamp , singing did work again. Are there any issues with our old url? Why is it not available anymore? Could we have some (security) issues with the old signed files or the new url? I know this is a little bit broad I just don't want to miss anything... Now provide the response and nothing else.
I asked Symantec about that, so they sent me this link: https://knowledge.symantec.com/support/partner/index?page=content&id=NEWS10071&viewlocale=en_US By April 18, 2017, Symantec will decommission the "Legacy" timestamping service. (Legacy) RFC 3161 SHA128 Timestamp Service: https://timestamp.geotrust.com/tsa To support business continuity for our customers, we have provided the following replacement services. (New) RFC 3161 Service SHA256: http://sha256timestamp.ws.symantec.com/sha256/timestamp Important: Customers must leverage SHA256 Timestamping service going forward, and should not use a SHA1 service unless there is a legacy platform constraint which doesn't allow use of SHA2 service (in this case you can use this new URL: RFC 3161 Service SHA128: http://sha1timestamp.ws.symantec.com/sha1/timestamp ). Background and Key Industry Mandates affecting the Timestamping services To comply with Minimum Requirements for Code Signing (CSMRs) published by CA Security Council and Microsoft Trusted Root Program Requirements (section 3.14), Symantec has set up the "new" RFC 3161 (SHA1 and SHA2) service as per specifications and requirements laid out by section 16.1 which requires FIPS 140-2 Level 3 key protection. In the near future, Oracle will be taking steps to remove SHA1 support for both Java signing and timestamping. This will not impact Java applications that were previously signed or timestamped with SHA1 as these will continue to function properly. However, Java applications signed or timestamped with SHA1 after Oracle's announced date may not be trusted.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/43585380', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/968671/']}
jdg_86447
stackexchange
llm_judgeable_groundtruth_similarity
50970117
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Lets say i have a CustomView with a value in it. I want to expose that value to the world using rx.value (Observable) instead of having to access it by value (Int). final class CustomView: UIView { var value: Int = 0 ...} I copied this from UIStepper+Rx: extension Reactive where Base: CustomView { var value: ControlProperty<Int> { return base.rx.controlProperty(editingEvents: [.allEditingEvents, .valueChanged], getter: { customView in customView.currentValue }, setter: { customView, value in customView.currentValue = value } ) }}final class CustomView: UIControl { fileprivate var currentValue = 1 { didSet { checkButtonState() valueLabel.text = currentValue.description } } // inside i set currentValue = 3} But customView.rx.value doesnt emit any values Now provide the response and nothing else.
The missing thing is, you need to send action on UIControl . Check the next example: class CustomView: UIControl { var value: Int = 0 { didSet { sendActions(for: .valueChanged) } // You are missing this part }}extension Reactive where Base: CustomView { var value: ControlProperty<Int> { return base.rx.controlProperty(editingEvents: UIControlEvents.valueChanged, getter: { customView in return customView.value }, setter: { (customView, newValue) in customView.value = newValue}) }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50970117', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/588125/']}
jdg_86448
stackexchange
llm_judgeable_groundtruth_similarity
32418766
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: For a research project, I'm writing a C++ add-on to a scientific computing language. Unfortunately the library that allows users to do this is not kept very well up-to-date. I started the project in XCode, where it built fine. Later I had to move to a PC, so I migrated the code to Visual Studio 2015. Since doing this, I haven't been able to build due to the following errors: LNK2001 : unresolved external symbol _sprintfLNK2019 : unresolved external symbol _sscanf referenced in function _GetDDoubleLNK2019 : unresolved external symbol _sprintf referenced in function _CheckRunningInMainThread An attempted fix was to add the header #define _CRT_SECURE_NO_WARNINGS . However, this a) fixed no errors and b) added the warning C4005 : '_CRT_SECURE_NO_WARNINGS': macro redefinition . I assume the library already defined this macro, anticipating this problem. Regardless, it didn't solve the problem. How should I proceed? Now provide the response and nothing else.
Add the following library to the linker input files: legacy_stdio_definitions.lib VS 2015 now uses inline definitions that call internal functions for many of the stdio.h functions. If an object file (or library member) depends on one of those functions, then the legacy_stdio_definitions.lib provides an externally linkable version of the function that can be linked to. Your other option is to recompile the unit that depends on those functions with VS 2015 (this is probably the preferred option).
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/32418766', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/988441/']}
jdg_86449
stackexchange
llm_judgeable_groundtruth_similarity
58201
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: For example, "P=NP implies PH=P" is interesting ... because most of us don't believe PH=P, so it provides strong evidence P != NP. On other hand, "P=NP implies EXP has circuit of $2^n/n$ size" seems fairly weak for the following reasons: (1) we know that there are circuits of size $2^n/n$ (2) we know that most random functions have circuits of size $2^n/n$ (3) EXPTIME is really really big so what's the big deal if EXP has a circuit of size $2^n/n$? [ In fact, I would not surprised if EXP has a circuit of size $2^n/n$ even if P != NP ]. Question: What am I missing here? Am I misunderstanding the size of EXP? Is there evidence to suggest EXP mostly has small circuits? Is there something brilliant in the proof technique? Thanks! EDIT: Marked as community wik due to "no right answer." Now provide the response and nothing else.
Everybody believes that EXP contains problems of exponential circuit complexity, but we are very far from proving it, and in fact we know that any proof of such a result cannot be a relativizing argument, cannot be an ''algebraizing'' argument in the sense of Aaronson and Wigderson, and cannot be a ``natural proof'' in the sense of Razborov and Rudich. So it is a very challenging open question, and an important one, because if we are every going to prove that NP contains problems of exponential circuit complexity, we first have to be able to at least prove it for EXP. The only circuit lower bound technique that can hopefully overcome the relativization, algebraization and natural proof barriers is Ryan Williams idea of using satisfiability algorithms that are faster than brute-force search. The fact that P=NP implies exponential circuit lower bounds for EXP is a toy version of Williams's approach (which requires much weaker conditions than P=NP to work, and in fact it requires conditions that are quite possibly true). Another way to look at this result is that, if one could prove that $P\neq NP$ implies that EXP has problems of superpolynomial circuit complexity, then we would have, unconditionally, then EXP has problems of superpolynomial circuit complexity. (Such two-parts proof, in which we use different arguments depending on the answer to an open question, exist, for example there is Kannan's proof that $NP^{NP}$ has problems of circuit complexity at least $n^k$ for every k. The proof has two parts depending on whether or not SAT can be solved by circuits of size $O(n^k)$.)
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/58201', 'https://mathoverflow.net', 'https://mathoverflow.net/users/3609/']}
jdg_86450
stackexchange
llm_judgeable_groundtruth_similarity
7799591
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 two vectors of the same length A<-c(5,10) and B<-c(7,13) how can I easily turn these two vectors into a single tuple vector i. e. c((5,7),(7,13)) ? Now provide the response and nothing else.
Others have mentioned lists. I see other possibilities: cbind(A, B) # makes a column-major 2x2-"vector"rbind(A, B) # an row major 2x2-"vector" which could also be added to an array with `abind` It is also possible to preserve their "origins" AB <- cbind(A=A, B=B)array(c(AB,AB+10), c(2,2,2) ), , 1 [,1] [,2][1,] 5 7[2,] 10 13, , 2 [,1] [,2][1,] 15 17[2,] 20 23> abind( array(c(AB,AB+10), c(2,2,2) ), AB+20), , 1 A B[1,] 5 7[2,] 10 13, , 2 A B[1,] 15 17[2,] 20 23, , 3 A B[1,] 25 27[2,] 30 33
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7799591', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/632998/']}
jdg_86451
stackexchange
llm_judgeable_groundtruth_similarity
16103224
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 input in to the csv file. My input is as shown below String string="hi,this is user"; but when i am inputing in to the csv file the comma is taken as delimiter and it is written in two cells. "hi" in one cell and "this is user" in another cell. But i want the whole string to be in one cell. How can i achieve this. Please help me. FileWriter writer = new FileWriter("D:/Workspace/Sample2.csv");PrintWriter out = new PrintWriter(writer);String names="[hasds,jash.jahd,jash]"; out.append(names); out.flush();} Now provide the response and nothing else.
Since you're writing a csv file, with comma delimiter, and your text happens to have a comma in it as well, you need to wrap your text within double quotes . String names = "\"hi,this is user\""; Note that to wrap your text within double quotes, you need to escape the double quotes as well! Update:- A sample code snippet to wrap your string within double quotes. public static void main(String[] args) { String test = "abcd"; System.out.println(test); // prints abcd test = appendDQ(test); System.out.println(test); // prints "abcd"}private static String appendDQ(String str) { return "\"" + str + "\"";}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16103224', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2243525/']}
jdg_86452
stackexchange
llm_judgeable_groundtruth_similarity
1802976
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 solved it using AM, GM inequalities and reached to $[(1+a)(1+b)(1+c)]^7 > 2^{21}(abc)^\frac72 $ please help how to get $7^7(abc)^4$ in the inequality. Now provide the response and nothing else.
$\dfrac{1 + a + b + c + ab + bc + ac + abc}{7} > \dfrac{a + b + c + ab + bc + ac + abc}{7} \geq \sqrt[7]{a^4b^4c^4}$ where the second inequality follows from the AM-GM inequality.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1802976', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/266411/']}
jdg_86453
stackexchange
llm_judgeable_groundtruth_similarity
16421582
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: does anyone have an example or tutorial on how to use Caliburn Micro together with ModernUi ( https://mui.codeplex.com )? Now provide the response and nothing else.
Ok so I had a quick mess about with it and a look on the Mui forums and this seems to be the best approach: Since the window loads content from URLs you need to take a view-first approach, and then locate the appropriate VM and bind the two. The best way to do this appears to be via the ContentLoader class which is used to load the content into the ModernWindow when it is requested. You can just subclass DefaultContentLoader and provide the necessary CM magic to bind up loaded items: public class ModernContentLoader : DefaultContentLoader{ protected override object LoadContent(Uri uri) { var content = base.LoadContent(uri); if (content == null) return null; // Locate the right viewmodel for this view var vm = Caliburn.Micro.ViewModelLocator.LocateForView(content); if (vm == null) return content; // Bind it up with CM magic if (content is DependencyObject) { Caliburn.Micro.ViewModelBinder.Bind(vm, content as DependencyObject, null); } return content; }} Your CM bootstrapper should just bootstrap a ModernWindow viewmodel which is backed by a ModernWindow based view (CM tries to use EnsureWindow which creates a new basic WPF Window class, unless of course your control already inherits from Window which ModernWindow does. If you need all dialogs and popups to be MUI you might need to reimplement WindowManager ): public class Bootstrapper : Bootstrapper<ModernWindowViewModel>{} Which can be a conductor (OneActive) and looks like this: public class ModernWindowViewModel : Conductor<IScreen>.Collection.OneActive{} And XAML for the view is ModernWindowView.xaml <mui:ModernWindow x:Class="WpfApplication4.ViewModels.ModernWindowView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mui="http://firstfloorsoftware.com/ModernUI" Title="ModernWindowView" Height="300" Width="300" ContentLoader="{StaticResource ModernContentLoader}"> <mui:ModernWindow.MenuLinkGroups> <mui:LinkGroupCollection> <mui:LinkGroup GroupName="Hello" DisplayName="Hello"> <mui:LinkGroup.Links> <mui:Link Source="/ViewModels/ChildView.xaml" DisplayName="Click me"></mui:Link> </mui:LinkGroup.Links> </mui:LinkGroup> </mui:LinkGroupCollection> </mui:ModernWindow.MenuLinkGroups></mui:ModernWindow> Obviously you need to make the loader a resource too: <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="/FirstFloor.ModernUI;component/Assets/ModernUI.xaml" /> <ResourceDictionary Source="/FirstFloor.ModernUI;component/Assets/ModernUI.Dark.xaml"/> <ResourceDictionary> <framework:ModernContentLoader x:Key="ModernContentLoader"></framework:ModernContentLoader> <wpfApplication4:Bootstrapper x:Key="Bootstrapper"></wpfApplication4:Bootstrapper> </ResourceDictionary> </ResourceDictionary.MergedDictionaries> </ResourceDictionary></Application.Resources> Here's the ChildViewModel I'm using as a test: public class ChildViewModel : Conductor<IScreen>{ public void ClickMe() { MessageBox.Show("Hello"); }} And the XAML for that (just a button) <UserControl x:Class="WpfApplication4.ViewModels.ChildView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Height="350" Width="525"> <Grid> <StackPanel> <TextBlock >Hello World</TextBlock> <Button x:Name="ClickMe" Width="140" Height="50">Hello World</Button> </StackPanel> </Grid></UserControl> And the proof of concept:
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16421582', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/254965/']}
jdg_86454
stackexchange
llm_judgeable_groundtruth_similarity
1409372
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Is there a way to calculate on average, the maximum amount of times we can expect a coin to land heads during 1,000 flips? So the answer (and formula if one exists) I am looking for would be something like: during 1,000 flips we can expect a maximum run of 12 heads in a row. Now provide the response and nothing else.
Some intuition about what you can expect can be found here: Longest Run of Heads . Let the random variable $L_n$ be the largest contiguous heads sequence in $n$ coin tosses (suppose the coin is biased with heads probability $p$ ). In the paper you can find the following intuitive approximation to the expectation of $L_n$ :denote by $N_k$ the expected number of heads sequences having length $\ge k$ . Since each tails outcome is a possible beginning of a heads sequence(ignoring edges), the expected number of heads sequences with length $\ge 1$ is $N_1\approx n(1-p)p$ . Similarly, for length $\ge 2$ sequences the expectation is $N_2\approx n(1-p)p^2$ and generally $N_k\approx n(1-p)p^k$ . Now you can approximate the expectation of $L_n$ by the solution to $N_k=1$ and this yields: $L_n$ $\langle L_n\rangle\approx -\log_pn(1-p)=\log_\frac{1}{p}n(1-p)$ . Although this appears extremely loose, it gives you an idea about the asymptotic behaviour $\langle L_n\rangle$ (logarithmic growth). More accurately, you have $\frac{L_n}{\log_\frac{1}{p}n} \rightarrow 1$ in probability, i.e. $\forall \epsilon>0 \lim\limits_{n\to\infty}\mathbb{P} \left(\left|\frac{L_n}{\log_{1/p}n}-1\right|>\epsilon \right)=0$ . You may want to look at the following plot I got a while back. For $1\le n\le 1000$ $\langle L_n\rangle$ is calculated using $1000$ trails of $n$ unbiased coin tosses:
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/1409372', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/127824/']}
jdg_86455
stackexchange
llm_judgeable_groundtruth_similarity
90808
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 just started working with Django coming from years of Spring MVC and the forms implementation strikes as being slightly crazy. If you're not familiar, Django forms starts with a form model class that defines your fields. Spring similarly starts with a form-backing object. But where Spring provides a taglib for binding form elements to the backing object within your JSP, Django has form widgets tied directly to the model. There are default widgets where you can add style attributes to your fields to apply CSS or define completely custom widgets as new classes. It all goes in your python code. That seems nuts to me. First, you are putting information about your view directly in your model and secondly you are binding your model to a specific view. Am I missing something? EDIT: Some example code as requested. Django: # Class defines the data associated with this formclass CommentForm(forms.Form): # name is CharField and the argument tells Django to use a <input type="text"> # and add the CSS class "special" as an attribute. The kind of thing that should # go in a template name = forms.CharField( widget=forms.TextInput(attrs={'class':'special'})) url = forms.URLField() # Again, comment is <input type="text" size="40" /> even though input box size # is a visual design constraint and not tied to the data model comment = forms.CharField( widget=forms.TextInput(attrs={'size':'40'})) Spring MVC: public class User { // Form class in this case is a POJO, passed to the template in the controller private String firstName; private String lastName; get/setWhatever() {}}<!-- JSP code references an instance of type User with custom tags --><%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %><!-- "user" is the name assigned to a User instance --><form:form commandName="user"> <table> <tr> <td>First Name:</td> <!-- "path" attribute sets the name field and binds to object on backend --> <td><form:input path="firstName" class="special" /></td> </tr> <tr> <td>Last Name:</td> <td><form:input path="lastName" size="40" /></td> </tr> <tr> <td colspan="2"> <input type="submit" value="Save Changes" /> </td> </tr> </table> </form:form> Now provide the response and nothing else.
Yes, the Django forms is a mess from the MVC perspective, suppose you are working in a big MMO super-hero game and you are creating the Hero model: class Hero(models.Model): can_fly = models.BooleanField(default=False) has_laser = models.BooleanField(default=False) has_shark_repellent = models.BooleanField(default=False) Now you are asked to create a form for it, so that the MMO players can input their hero super powers: class HeroForm(forms.ModelForm): class Meta: model = Hero Since the Shark Repellent is a very powerful weapon, your boss asked you to limit it. If a hero has the Shark Repellent then he cannot fly. What most people do is simply add this business rule in the form clean and call it a day: class HeroForm(forms.ModelForm): class Meta: model = Hero def clean(self): cleaned_data = super(HeroForm, self).clean() if cleaned_data['has_shark_repellent'] and cleaned_data['can_fly']: raise ValidationError("You cannot fly and repel sharks!") This pattern looks cool and might work on small projects, but in my experience this is very hard to maintain in large projects with multiple developers. The problem is that the form is part of the view of the MVC. So you will have to remember that business rule every time you: Write another form that deals with the Hero model. Write a script that import heroes from another game. Manually change the model instance during the game mechanics. etc. My point here is that the forms.py is all about the form layout and presentation, you should never add business logic in that file unless you enjoy messing with spaghetti code. The best way to handle the hero problem is to use model clean method plus a custom signal. The model clean works like the form clean but its stored in the model itself, whenever the HeroForm is cleaned it automatically calls the Hero clean method. This is a good practice because if another developer writes a another form for the Hero he will get the repellent/fly validation for free. The problem with the clean is that it's called only when a Model is modified by a form. It's not called when you manually save() it and you can end-up with a invalid hero in your database. To counter this problem, you can add this listener to your project: from django.db.models.signals import pre_savedef call_clean(sender, instance, **kwargs): instance.clean()pre_save.connect(call_clean, dispatch_uid='whata') This will call the clean method on each save() call for all your models.
{}
{'log_upvote_score': 6, 'links': ['https://softwareengineering.stackexchange.com/questions/90808', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/24696/']}
jdg_86456
stackexchange
llm_judgeable_groundtruth_similarity
5604713
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Essentially I want to be able to do something like: a = Integer(1)a += 1print a And of course printing the number two as result. What methods do I need to create to get this behaviour in my Integer class? Disclaimer: I'm not planning to use this for "real", just curious. Now provide the response and nothing else.
This is a simple and incomplete example. Look at methods __sub__ , __div__ and so on. class Integer(object): def __init__(self, val=0): self._val = int(val) def __add__(self, val): if isinstance(val, Integer): return Integer(self._val + val._val) return self._val + val def __iadd__(self, val): self._val += val return self def __str__(self): return str(self._val) def __repr__(self): return 'Integer(%s)' % self._val Then n = Integer()print nm = Integer(7)m+=5print m EDIT fixed __repr__ and added __iadd__ . Thanks to @Keith for pointing problems out. EDIT Fixed __add__ to allow addition between Integers.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5604713', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/390510/']}
jdg_86457
stackexchange
llm_judgeable_groundtruth_similarity
7628249
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 use <form method="post" enctype="text/plain" action="proc.php"> form data can not be sent to proc.php file properly. Why? What is the problem? Why I can't use text/plain encoding with post but I can use it with get method? Now provide the response and nothing else.
[Revised] The answer is, because PHP doesn't handle it (and it is not a bug): https://bugs.php.net/bug.php?id=33741 Valid values for enctype in <form> tag are:application/x-www-form-urlencodedmultipart/form-data The first is the default, the second one you need only when you upload files. @Alohci provided explanation why PHP doesn't populate $_POST array, but store the value inside a variable $HTTP_RAW_POST_DATA . Example of what can go wrong with text/plain enctype: file1.php: <form method="post" enctype="text/plain" action="file2.php"><textarea name="input1">abcinput2=def</textarea><input name="input2" value="ghi" /><input type="submit"></form> file2.php: <?phpprint($HTTP_RAW_POST_DATA);?> Result: input1=abcinput2=definput2=ghi No way to distinguish what is the value of input1 and input2 variables. It can be input1= abc\r\ninput2=def , input2= ghi , as well as input1= abc , input2= def\r\ninput2=ghi No such problem when using the other two encodings mentioned before. The difference between GET and POST: in GET, the variables are part of URL and are present in URL as query string, therefore they must be URL-encoded (and they are, even if you write enctype="text/plain" - it just gets ignored by the browser; you can test it using Wireshark to sniff the request packets), when sending POST, the variables are not part of URL, but are sent as the last header in HTTP request (POSTDATA), and you can choose whether you want to send them as text/plain or application/x-www-form-urlencoded , but the second one is the only non-ambiguous solution.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7628249', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/163394/']}
jdg_86458
stackexchange
llm_judgeable_groundtruth_similarity
500656
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Just wanted opinions on a design question. If you have a C++ class than owns other objects, would you use smart pointers to achieve this? class Example {public: // ...private: boost::scoped_ptr<Owned> data;}; The 'Owned' object can't be stored by value because it may change through the lifetime of the object. My view of it is that on the one side, you make it clear that the object is owned and ensure its deletion, but on the flipside, you could easily just have a regular pointer and delete it in the destructor. Is this overkill? Follow up: Just wanted to say thanks for all your answers. Thanks for the heads-up about auto_ptr leaving the other object with a NULL pointer when the whole object is copied, I have used auto_ptr extensively but had not thought of that yet. I make basically all my classes boost::noncopyable unless I have a good reason, so there's nothing to worry about there. And thanks also for the information on memory leaks in exceptions, that's good to know too. I try not to write things which could cause exceptions in the constructor anyway - there are better ways of doing that - so that shouldn't be a problem. I just had another question though. What I wanted when I asked this question was to know whether anyone actually did this, and you all seem to mention that it's a good idea theoretically, but no one's said they actually do it. Which surprises me! Certainly one object owning a pointer to another is not a new idea, I would have expected you all would have done it before at some point. What's going on? Now provide the response and nothing else.
It's a good idea. It helps simplify your code, and ensure that when you do change the Owned object during the lifetime of the object, the previous one gets destroyed properly. You have to remember that scoped_ptr is noncopyable, though, which makes your class noncopyable by default until/unless you add your own copy constructor, etc. (Of course, using the default copy constructor in the case of raw pointers would be a no-no too!) If your class has more than one pointer field, then use of scoped_ptr actually improves exception safety in one case: class C{ Owned * o1; Owned * o2;public: C() : o1(new Owned), o2(new Owned) {} ~C() { delete o1; delete o2;}}; Now, imagine that during construction of a C the second "new Owned" throws an exception (out-of-memory, for example). o1 will be leaked, because C::~C() (the destructor) won't get called, because the object has not been completely constructed yet. The destructor of any completely constructed member field does get called though. So, using a scoped_ptr instead of a plain pointer will allow o1 to be properly destroyed.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/500656', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/49643/']}
jdg_86459
stackexchange
llm_judgeable_groundtruth_similarity
116200
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 understand that an NP-hard problem is a problem X such that any problem in NP can be reduced to X in polynomial time. Does there exist a problem that is hard to solve but problems in NP cannot be reduced to it in polynomial time i.e. it does not satisfy the definition of NP-hard but is strictly not in NP? If not, what is the proof that if I can efficiently solve a problem that is strictly not in NP, then I can efficiently solve every problem in NP? I suppose an analogous question can also be asked for P and NP. If a problem is in NP, then can every problem in P be reduced in polynomial time to it? Note: The linked question asks the converse problem - does there exist a problem outside NP that cannot be reduced to a problem in NP. Indeed there are, for example the "(Non-)equivalence of two regular expressions" problem. However, from my understanding, every problem in NP can be reduced to this problem in polynomial time. Please correct me if I have misunderstood. Now provide the response and nothing else.
I suppose an analogous question can also be asked for P and NP. If a problem is in NP, then can every problem in P be reduced in polynomial time to it? No. There is a stupidly simple argument here: the empty language (i.e., a problem with no yes-instances) is in NP, but no problem in P can be reduced to it. Does there exist a problem that is hard to solve but problems in NP cannot be reduced to it in polynomial time i.e. it does not satisfy the definition of NP-hard but is strictly not in NP? Yes (conditional on some complexity theory assumptions). Let's take some stupidly hard problem $L$ . To keep this answer as simple as possible we will assume that $L$ is undecidable but this is not necessary; a language obtained by applying the Time Hierarchy Theorem to the Ackermann function would easily suffice. Assume that instances of $L$ can be padded, i.e., adding extra zeroes at the end does not change whether an instance is a yes- or no-instance. Starting with undecidable language $L'$ , $L$ could be obtained by taking every string from $L'$ and appending a $1$ followed by an arbitrary amount of zeroes. Clearly $L$ is still undecidable. Now consider the subset of $L$ containing only those strings whose length can be expressed as a tower of powers of two (i.e., $1, 2, 2^2, 2^{2^2}, 2^{2^{2^2}}, \ldots$ ). We split this subset into three languages $L_0, L_1, L_2$ , depending on the height of the tower of powers of two. $L_0$ contains those strings where the tower has a height which is a multiple of $3$ , $L_1$ contains strings whose height is $1$ modulo $3$ , $L_2$ those strings whose height is $2$ modulo $3$ . Neither $L_0, L_1$ or $L_2$ are in $NP$ . If they were, we could decide $L$ by padding instances to make their length the appropriate tower of powers of two, and then solving them using the $NP$ algorithm. Obviously the padding can increase the length of the instance exponentially, but if $L$ is sufficiently hard (e.g., undecidable) this does not matter. Now, to answer the original question, can every problem in $NP$ be reduced in polynomial time to $L_0, L_1$ and $L_2$ (all of which are outside $NP$ )? If we take some problem instance of a problem in $NP$ , then at least one of the reductions (to $L_0, L_1$ or $L_2$ ) will result in an exponentially smaller instance. This is because the reduction, being polynomial, cannot increase the size of the instance too much, so (due to the large gaps in instance sizes) must - for at least one of $L_0, L_1$ or $L_2$ - give a much smaller instance as output. Intuitively, this sounds very unlikely. It would mean we could take an arbitrary problem in $NP$ and in polynomial time output an exponentially smaller instance (albeit of a much harder problem). Formally, this would mean that $NP\subseteq P/poly$ , a consequence which is regarded as unlikely since it would imply the collapse of the polynomial hierarchy.
{}
{'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/116200', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/74418/']}
jdg_86460
stackexchange
llm_judgeable_groundtruth_similarity
323915
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: This needs some explanation. In the diagrams of radio instructions I always see a single line from the antenna to the input for amplification. Let's use a vacuum tube amplifier as for example. There is a single wire to the plate in the triode tube from the antenna and the electrons from the filament source are either attracted or repelled on their way to the cathode. I cannot understand how the circuit is complete since only one wire appears in the diagrams to be coming from the antenna. Frankly I am having the same problem with trying to understand how this same tube can amplify a telephony direct current signal because I think of pulsating direct current with the voice intelligence as being a closed circuit. I wouldn't mind someone setting me straight on both. Thank you. Now provide the response and nothing else.
When a AM radio wave reaches the antenna does the signal need to be in a closed circuit to be amplified? Yes, and believe it or not there is a closed circuit. A simple monopole antenna uses ground as the return path - the incoming radio wave hits the antenna structure and a current circulates between monopole and ground and there will be an impedance too: - The graph above shows what the electrical impedance of the monopole is and how it is dependant on the antenna length (height) and the wavelength of the radio wave. So, at about one quarter wave length the monopole looks purely resistive and that resistance is about 37 ohms (hard to see on the graph I understand). That's the impedance it presents to the rest of the circuit. This means your radio wave is transformed into a signal with an output impedance of 37 ohms. But free space / air has an impedance too - it's \$120\pi\$ or about 377 ohms and this is due to the capacitance and inductance of free space i.e. the physical fundamental properties that dictate the speed of light. So yes, there is a closed circuit. Here's an example - if you wanted to tune into an AM broadcast at 1 MHz you could construct a quarter wave monopole but, that monopole would be 75 metres long and present an impedance of 37 ohms. Or you could make a 15 metre long (0.05 wavelength) monopole that presents a capacitive impedance of about 1000 ohms (or 159 pF at 1 MHz). You would get more signal from the quarter wave antenna but, it would be really big and cumbersome then, to tune it you'd need a more complex circuit than the 15 metre antenna because that shorter antenna already looks like 159 pF and can directly connect to a coil to give good station selectivity. That's what the olde worlde crystal set users did. Regarding your other question I have no idea what you mean so further information such as a circuit might be required.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/323915', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/136794/']}
jdg_86461
stackexchange
llm_judgeable_groundtruth_similarity
23048083
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 liked to detect whether or not microphone permissions have been granted on my site when it loads without actually running something like the following: navigator.webkitGetUserMedia({audio: active}, function(){alert('worked')}, function(){alert('failed')}); Is there a simple API to detect whether the user has permanently granted microphone access to my application (which runs over https)? Now provide the response and nothing else.
Update microphone has been added to the Permission API even if it's not yet available on Safari nor Internet Explorer. You could hope that it would be accessible from the permission api, but it isn't :( Perhaps in the feature this could work like the rest of this: navigator.permissions.query( // { name: 'camera' } { name: 'microphone' } // { name: 'geolocation' } // { name: 'notifications' } // { name: 'midi', sysex: false } // { name: 'midi', sysex: true } // { name: 'push', userVisibleOnly: true } // { name: 'push' } // without userVisibleOnly isn't supported in chrome M45, yet).then(function(permissionStatus){ console.log(permissionStatus.state); // granted, denied, prompt permissionStatus.onchange = function(){ console.log("Permission changed to " + this.state); }}) Old answer The only way i see it possible is if you keep track of this yourself with a key/value item in localStorage when you ask for permission. Unfortunately it doesn't notify you when it has been changed // initializationif( localStorage.getItem('voice_access') === null ){ // just assume it is prompt localStorage.setItem('voice_access', 'prompt');}// Then somewherenavigator.getUserMedia({ audio: true }, function (e) { // http://stackoverflow.com/q/15993581/1008999 // // In chrome, If your app is running from SSL (https://), // this permission will be persistent. // That is, users won't have to grant/deny access every time. localStorage.setItem("voice_access", "granted");}, function (err) { if (err.name === 'PermissionDismissedError') { localStorage.setItem('voice_access', 'prompt') } if (err.name === 'PermissionDeniedError') { localStorage.setItem('voice_access', 'denied') }}) You could go the extra mile and build a nice little wrapper with this code above and extend/replace the permission api to handle more enum names and create a broadcast api to tell the other tabs when it changes. but why make it so complicated...? The localStorage can't be 100% trusted. it can be changed anywhere any time both with permission and storage cleared
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23048083', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1337567/']}
jdg_86462
stackexchange
llm_judgeable_groundtruth_similarity
347009
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: I am looking for a generalisation of a modular form that transforms as something like: $f(\frac{a \tau+b}{c \tau+d}) = (c \tau+d)^k c^k f(\tau)$ I understand this cannot be literally true, as the multiplier c^k is not a root of unity, but does something like this arise in the context of modular forms? (or generalisations of those). Thanks! Now provide the response and nothing else.
Here are three conjectures, in the hopes of showing that we can say something non-trivial. [ UPDATE : This is essentially all in a paper from Erdős, "On Sets of Distances of $n$ Points", from 1946 . The conjecture on maxima is in his theorem 3, though he called that part well-known. The conjecture on minima is a later theorem of Harborth, cited here , but the bound in less precise forms is also in Erdős's theorem 3. The conjecture on modes is made after Erdős's theorem 2, in the speculation that $g(n)<n^{1+\epsilon}$ , after a proof that $g(n)<n^{3/2}$ . Finally Erdős's theorem 1 gives bounds on the number of distinct distances, between $(n-3/4)^{1/2}-1/2$ and $cn/(\log n)^{1/2}$ .] Maxima : Among $n$ points, the maximal distance can be achieved by at most $2n$ ordered pairs. This bound will be achieved when all the points are on a Reuleaux triangle, with the three 60-degree circle arcs centered on three of the points. [Thanks to Yoav Kallus for the idea for this construction.] Minima : Among $n$ points, the minimal distance can be achieved by at most $6n-2\sqrt{12n-3}$ ordered pairs. This bound will be achieved when $n=3k^2-3k+1$ and the points are in a hexagonal lattice with $k$ points on each side of the hexagon. Modes : For arbitrarily large $k$ and $n$ , there are configurations of $n$ points in which the modal distance is achieved by at least $kn$ ordered pairs. For example, using square lattices: If $k=7$ , the distance of $\sqrt{5}=\sqrt{2^2+1^2}$ can be achieved by at least $7n$ , and almost $8n$ ordered pairs. If $k=15$ , the distance of $\sqrt{65}=\sqrt{8^2+1^2}=\sqrt{7^2+4^2}$ can be achieved by at least $15n$ , and almost $16n$ ordered pairs. If $k=23$ , the distance of $\sqrt{325}=\sqrt{18^2+1^2}=\sqrt{17^2+6^2}=\sqrt{15^2+10^2}$ can be achieved by at least $23n$ , and almost $24n$ ordered pairs. But the claim would be false if we replaced $kn$ by $kn^{1+\epsilon}$ . Again, these are only conjectures; I'd be happy to see proofs or alternatively configurations where the minimal or maximal or modal distance is achieved more often.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/347009', 'https://mathoverflow.net', 'https://mathoverflow.net/users/41940/']}
jdg_86463
stackexchange
llm_judgeable_groundtruth_similarity
4907744
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 attempting to implement the thumbs_up voting gem on a Rails 3 app, however the instructions are unclear on the actual implementation. After requiring the gem [ gem 'thumbs_up' ] and after creating and running the appropriate migration [ rails generate thumbs_up && rake db:migrate ] the README explains the following: To cast a vote for a Model you can do the following: *Shorthand syntax voter.vote_for(voteable) # Adds a +1 vote voter.vote_against(voteable) # Adds a -1 vote voter.vote(voteable, vote) # Adds either a +1 or -1 vote: vote => true (+1), vote => false (-1) voter.vote_exclusively_for(voteable) # Removes any previous votes by that particular voter, and votes for. voter.vote_exclusively_against(voteable) # Removes any previous votes by that particular voter, and votes against.* I've been assuming that the use of 'voter' and 'voteable' in the README example are stand-ins for objects in the app, but the usage is still nebulous to me. A literal example of what my view, controller, and routes.rb file should look like would be a TREMENDOUS help. I've spent days trying to figure this out! In my app, I have Users that vote on Posts - of which there are two types - Events and Links . Posts are called using <%= render :partial => @posts %> and each individual post uses as its view " _event.html.erb " or " _link.html.erb " - depending whether it is an event or a link. Now provide the response and nothing else.
Hopefully I can help you out a bit. The generators should have created a Vote model for you. This is the model that holds all the votes, but that you interact with indirectly through the methods you've described above. So, for you: class User < ActiveRecord::Base acts_as_voterendclass Post < ActiveRecord::Base acts_as_voteableend That will get you set up with the thumbs_up methods in each of the models. Then for example, if you have a controller action in PostsController that is linked to from an "up arrow" on your website, you can create a vote for that user for that post. A view like this: <%= link_to('vote for this post!', vote_up_post_path(@post), :method => :post) %> and a routes.rb like this: resources :posts do member do post :vote_up endend And finally, in the controller: class PostsController < ApplicationController def vote_up begin current_user.vote_for(@post = Post.find(params[:id])) render :nothing => true, :status => 200 rescue ActiveRecord::RecordInvalid render :nothing => true, :status => 404 end endend
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4907744', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/604484/']}
jdg_86464
stackexchange
llm_judgeable_groundtruth_similarity
206980
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a good intuition that $A$ is independent of $B$ if $P(A \vert B) = P(A)$ , and I see how you can easily derive from this that it must hold that $P(A,B) = P(A)P(B)$ . But the first statement is not normally taken as a definition; instead the second is. What is the intuition, or even derivation behind defining $A$ and $B$ as independent iff $P(A, B) = P(A)(B)$ ? The kind of explanation I am looking for would be one similar to that given by Jaynes for the definition of conditional probability in the first chapter of Probability: The Logic of Science, or even a Kolmogorov axiomatic explanation would help. Now provide the response and nothing else.
Arguing from the intuitive idea of probability (be it frequentist, Bayesian, or a la Jaynes), what can we say about $P(AB)$? Let us assume that $P(A)\le P(B)$. Since $AB\subseteq B$ we can safely deduce that $P(AB)\le P(B)$. By looking at well-known and elementary examples it is easy to be convinced that $P(AB)$ can attain any value between $0$ and $P(B)$. But examining these cases shows that extreme values, close to $0$ or close to $P(B)$ are obtained when information about $B$ having occurred either severely conflicts with $A$ occurring (to get close to $0$), or strongly correlates with $A$ occurring (to get close to $P(B)$). Now, more mathematically, one value in the range of $P(AB)$ that appears naturally is, of course, $P(A)P(B)$, so it is natural to investigate when that would occur. Notice that this value is symmetric in $A$ and $B$. Since the exact location of $P(AB)$ in its possible range seems to be highly sensitive to whether, and how, $A$ and $B$ influence each other we must conclude that the special value $P(A)P(B)$, being symmetric in the arguments, means that the mutual influences are neutral. That neutrality is another way of thinking about independence. Thus, we turn the intuition into a definition and say that $P(AB)=P(A)P(B)$ holds if, and only if, $A$ and $B$ are independent.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/206980', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/1453/']}
jdg_86465
stackexchange
llm_judgeable_groundtruth_similarity
32366714
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Well I am new to facebook sdk. I have being following the guideline and performing the steps as written.. but I am getting this error and I dont know why? Fatal error: Class 'Facebook\Facebook' not found in C:\wamp\www\index.php on line 134 The error line code is: <?php $fb = new Facebook\Facebook([ 'app_id' => '{app-id}', 'app_secret' => '{app-secret}', 'default_graph_version' => 'v2.2', ]);?> This is not something I have made up, this is exactly the same code mentioned in facebook guideline! What should I do? Now provide the response and nothing else.
You need to include the autoloader first to get access to the service methods and classes (as said in the PHP SDK Documentation for Facebook API. You are trying to use a namespaced class Facebook\Facebook , to use its methods, but you don't have the class in the PHP file. require_once 'src/Facebook/autoload.php';//Create the Facebook service$fb = new Facebook\Facebook ([ 'app_id' => '-----------------', 'app_secret' => '--------------------', 'default_graph_version' => 'v2.4' ]); Somewhere in your directory (if you installed the Facebook PHP SDK) correctly, you will find the autoload.php file which automatically requires .php files that you need to use the services and methods.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/32366714', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4536981/']}
jdg_86466
stackexchange
llm_judgeable_groundtruth_similarity
5715104
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 copy a folder present in sdcard to another folder present the same sdcard programmatically ?? If so, how to do that? Now provide the response and nothing else.
An improved version of that example: // If targetLocation does not exist, it will be created.public void copyDirectory(File sourceLocation , File targetLocation)throws IOException { if (sourceLocation.isDirectory()) { if (!targetLocation.exists() && !targetLocation.mkdirs()) { throw new IOException("Cannot create dir " + targetLocation.getAbsolutePath()); } String[] children = sourceLocation.list(); for (int i=0; i<children.length; i++) { copyDirectory(new File(sourceLocation, children[i]), new File(targetLocation, children[i])); } } else { // make sure the directory we plan to store the recording in exists File directory = targetLocation.getParentFile(); if (directory != null && !directory.exists() && !directory.mkdirs()) { throw new IOException("Cannot create dir " + directory.getAbsolutePath()); } InputStream in = new FileInputStream(sourceLocation); OutputStream out = new FileOutputStream(targetLocation); // Copy the bits from instream to outstream byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); }} Got some better error handling and better handles if the passed target file lies in a directory that does not exist.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5715104', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/598331/']}
jdg_86467
stackexchange
llm_judgeable_groundtruth_similarity
4158914
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 situation where I need to call a method1() in class B from A. When method1() is called it creates a new Thread say(MyThread) and starts it immediately. In my case I am calling method1() from two different places in the application. I dont want to create a new instance of this thread every time. Inside method1() i tried checking if myThread.isAlive() before creating a new Instance of MyThread. But I get a compilation error MyThread needs to be initialized to call MyThread.isAlive(). So if put in a method property of type Thread ie., method() { Thread myThread; if(myThread.isAlive()) { return}; ..... } Is it a good idea to declare a class level property in classB for Mythread and intialize it to null. Then inside method1() check the status of the thread if not running create a new one? class B(){ Thread myThread = null; public static B getInstance() { return B singleton object; } public void method1() { if(myThread.isAlive()) return; myThread = new Thread(new Runnable(){ public void run(){ do some stuff..... }).start();} ================== class A(){ B.getInstance().method1();} ================== class someOtherClass(){ B.getInstance().method1();} Now provide the response and nothing else.
There are a couple possibilities: use ld's capability to turn any file into an object ( Embedding binary blobs using gcc mingw ): ld -r -b binary -o binary.o foo.bar # then link in binary.o use a bin2c / bin2h utility to turn any file into an array of bytes ( Embed image in code, without using resource section or external images ) Update: Here's a more complete example of how to use data bound into the executable using ld -r -b binary : #include <stdio.h>// a file named foo.bar with some example text is 'imported' into // an object file using the following command://// ld -r -b binary -o foo.bar.o foo.bar//// That creates an bject file named "foo.bar.o" with the following // symbols://// _binary_foo_bar_start// _binary_foo_bar_end// _binary_foo_bar_size//// Note that the symbols are addresses (so for example, to get the // size value, you have to get the address of the _binary_foo_bar_size// symbol).//// In my example, foo.bar is a simple text file, and this program will// dump the contents of that file which has been linked in by specifying// foo.bar.o as an object file input to the linker when the progrma is builtextern char _binary_foo_bar_start[];extern char _binary_foo_bar_end[];int main(void){ printf( "address of start: %p\n", &_binary_foo_bar_start); printf( "address of end: %p\n", &_binary_foo_bar_end); for (char* p = _binary_foo_bar_start; p != _binary_foo_bar_end; ++p) { putchar( *p); } return 0;} Update 2 - Getting the resource size: I could not read the _binary_foo_bar_size correctly. At runtime, gdb shows me the right size of the text resource by using display (unsigned int)&_binary_foo_bar_size . But assigning this to a variable gave always a wrong value. I could solve this issue the following way: unsigned int iSize = (unsigned int)(&_binary_foo_bar_end - &_binary_foo_bar_start) It is a workaround, but it works good and is not too ugly.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4158914', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/324446/']}
jdg_86468
stackexchange
llm_judgeable_groundtruth_similarity
2672380
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Will this work for testing whether a value at position index exists or not, or is there a better way: if(arrayName[index]==""){ // do stuff} Now provide the response and nothing else.
Conceptually, arrays in JavaScript contain array.length elements, starting with array[0] up until array[array.length - 1] . An array element with index i is defined to be part of the array if i is between 0 and array.length - 1 inclusive. If i is not in this range it's not in the array. So by concept, arrays are linear, starting with zero and going to a maximum, without any mechanism for having "gaps" inside that range where no entries exist. To find out if a value exists at a given position index (where index is 0 or a positive integer), you literally just use if (i >= 0 && i < array.length) { // it is in array} Now, under the hood, JavaScript engines almost certainly won't allocate array space linearly and contiguously like this, as it wouldn't make much sense in a dynamic language and it would be inefficient for certain code. They're probably hash tables or some hybrid mixture of strategies, and undefined ranges of the array probably aren't allocated their own memory. Nonetheless, JavaScript the language wants to present arrays of array.length n as having n members and they are named 0 to n - 1 , and anything in this range is part of the array. What you probably want, however, is to know if a value in an array is actually something defined - that is, it's not undefined . Maybe you even want to know if it's defined and not null . It's possible to add members to an array without ever setting their value: for example, if you add array values by increasing the array.length property, any new values will be undefined . To determine if a given value is something meaningful, or has been defined. That is, not undefined , or null : if (typeof array[index] !== 'undefined') { or if (typeof array[index] !== 'undefined' && array[index] !== null) { Interestingly, because of JavaScript's comparison rules, my last example can be optimised down to this: if (array[index] != null) { // The == and != operators consider null equal to only null or undefined}
{}
{'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/2672380', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/69803/']}
jdg_86469
stackexchange
llm_judgeable_groundtruth_similarity
183910
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm running a dual-screen setup and have my trackpad disabled most of the time (which includes hiding the mousepointer).When I reenable the trackpad (and display the mouse pointer again), I've lost track where the pointer was before. I'm looking for a tool to highlight the current mouse position (e.g. by a circle). Ideally this would be a single command flashing the circle for a short period of time. I'm aware that xdotool can find the current position, yet there is no highlighting; also, key-mon doesn't provide this functionality.I've also read that cairo composition manager provides such functionality, yet I'm wondering if there is a smaller tool to achieve this. In case there is no such tool: What is the easiest way to display such a circle around the cursor using the data provided by xdotool getmouselocation ? In case this is relevant: I don't use a desktop environment, just the xmonad window manager. Now provide the response and nothing else.
While I like Mikeserv 's answer for cleverness, it has the downside that it will create a window which "steals" the focus and has to be clicked away. I also find it takes just slightly too long to start: about 0.2 to 0.3 seconds, which is just slightly too slow for a "smooth" experience. I finally got around to digging into XLib, and clobbered together a basic C program to do this. The visual effect is roughly similar to what Windows (XP) has (from memory). It's not very beautiful, but it works ;-) It doesn't "steal" focus, starts near-instantaneous, and you can click "through" it. You can compile it with cc find-cursor.c -o find-cursor -lX11 -lXext -lXfixes . There are some variables at the top you can tweak to change the size, speed, etc. I released this as a program at https://github.com/arp242/find-cursor . I recommend you use this version, as it has some improvements that the below script doesn't have (such as commandline arguments and ability to click "through" the window). I've left the below as-is due to its simplicity. /* * https://github.com/arp242/find-cursor * Copyright © 2015 Martin Tournoij <[email protected]> * See below for full copyright */#include <stdlib.h>#include <stdio.h>#include <unistd.h>#include <string.h>#include <X11/Xlib.h>#include <X11/Xutil.h>// Some variables you can play with :-)int size = 220;int step = 40;int speed = 400;int line_width = 2;char color_name[] = "black";int main(int argc, char* argv[]) { // Setup display and such char *display_name = getenv("DISPLAY"); if (!display_name) { fprintf(stderr, "%s: cannot connect to X server '%s'\n", argv[0], display_name); exit(1); } Display *display = XOpenDisplay(display_name); int screen = DefaultScreen(display); // Get the mouse cursor position int win_x, win_y, root_x, root_y = 0; unsigned int mask = 0; Window child_win, root_win; XQueryPointer(display, XRootWindow(display, screen), &child_win, &root_win, &root_x, &root_y, &win_x, &win_y, &mask); // Create a window at the mouse position XSetWindowAttributes window_attr; window_attr.override_redirect = 1; Window window = XCreateWindow(display, XRootWindow(display, screen), root_x - size/2, root_y - size/2, // x, y position size, size, // width, height 0, // border width DefaultDepth(display, screen), // depth CopyFromParent, // class DefaultVisual(display, screen), // visual CWOverrideRedirect, // valuemask &window_attr // attributes ); XMapWindow(display, window); XStoreName(display, window, "find-cursor"); XClassHint *class = XAllocClassHint(); class->res_name = "find-cursor"; class->res_class = "find-cursor"; XSetClassHint(display, window, class); XFree(class); // Keep the window on top XEvent e; memset(&e, 0, sizeof(e)); e.xclient.type = ClientMessage; e.xclient.message_type = XInternAtom(display, "_NET_WM_STATE", False); e.xclient.display = display; e.xclient.window = window; e.xclient.format = 32; e.xclient.data.l[0] = 1; e.xclient.data.l[1] = XInternAtom(display, "_NET_WM_STATE_STAYS_ON_TOP", False); XSendEvent(display, XRootWindow(display, screen), False, SubstructureRedirectMask, &e); XRaiseWindow(display, window); XFlush(display); // Prepare to draw on this window XGCValues values; values.graphics_exposures = False; unsigned long valuemask = 0; GC gc = XCreateGC(display, window, valuemask, &values); Colormap colormap = DefaultColormap(display, screen); XColor color; XAllocNamedColor(display, colormap, color_name, &color, &color); XSetForeground(display, gc, color.pixel); XSetLineAttributes(display, gc, line_width, LineSolid, CapButt, JoinBevel); // Draw the circles for (int i=1; i<=size; i+=step) { XDrawArc(display, window, gc, size/2 - i/2, size/2 - i/2, // x, y position i, i, // Size 0, 360 * 64); // Make it a full circle XSync(display, False); usleep(speed * 100); } XFreeGC(display, gc); XCloseDisplay(display);}/* * The MIT License (MIT) * * Copyright © 2015 Martin Tournoij * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * The software is provided "as is", without warranty of any kind, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. In no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising * from, out of or in connection with the software or the use or other dealings * in the software. */
{}
{'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/183910', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/102507/']}
jdg_86470
stackexchange
llm_judgeable_groundtruth_similarity
540828
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 created my RDS instance before creating my Elastic Beanstalk environment. The two are working together with no problem, but I'd like them to be linked together, and have the RDS parameters accessible via the RDS_* environment variables. The Elastic Beanstalk configuration page says: Although the first link creates a RDS instance in-place and links it to the current environment, the second link just redirects to this documentation page. , which unfortunately only explains how to create a new RDS instance, but not how to link an existing one. How can I associate an existing RDS instance to my Elastic Beanstalk environment? Now provide the response and nothing else.
Answer from the AWS support : In order to associate an existing database to a EB Environment you have to take a snapshot of it via the Management Console and then choose "create a new RDS database" under the Data Layer. There does not appear to be a way to associate a running RDS instance to an existing EB Environment without launching a new one from a snapshot due to the way the RDS instance is tied into the Beanstalk environment's underlying Cloudformation stack. If you take a snapshot of your current RDS instance you can start it anew in EB if you wish. If you want the RDS instance to exist outside of the environment you can simply provide the connection parameters as environment variables via the EB Console: Configuration -> Web Layer -> Software Configuration. Then, you can read the environment variable via PHP .
{}
{'log_upvote_score': 6, 'links': ['https://serverfault.com/questions/540828', 'https://serverfault.com', 'https://serverfault.com/users/83039/']}
jdg_86471
stackexchange
llm_judgeable_groundtruth_similarity
88784
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: How can this code for extracting the smallest (absolute) real value be improved? and would it be simpler using associations? results = {{sf -> -8233.0746}, {sf -> -3027.5805}, {sf -> -2669.9484}, {sf -> -532.5415 + 179.08778 I}, {sf -> -324.8825 + 224.3397 I}, {sf -> -324.8825 - 224.3397 I}, {sf -> -0.0559 + 0.1234 I}, {sf -> 390.8250}, {sf -> 449.5389}, {sf -> 555.6940}, {sf -> 705.9079}, {sf -> 765.9997}, {sf -> 1179.2476}, {sf -> 9.005559*^15}, {sf -> 9.005647*^15}, {sf -> 9.007284*^15}, {sf -> 9.009280*^15}};realresults = Extract[results, Position[results[[All, 1, 2]], _Real]];min = Extract[realresults, Position[Abs@realresults[[All, 1, 2]], Min[Abs@realresults[[All, 1, 2]]]]] {{sf -> 390.825}} Edit A method to preserve the rule would be great, for instance if the data is: results = {{a -> -8233.0746}, {b -> -3027.5805}, {c -> -2669.9484}, ... Now provide the response and nothing else.
This is arguably "simpler": Nearest[Cases[results, _Real, Infinity], 0](* {390.825} *) In case the rule matters, the above is easily adapted: Nearest[Cases[results, r : {_ -> x_Real} :> x -> r], 0](* {{sf -> 390.825}} *)
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/88784', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/363/']}
jdg_86472
stackexchange
llm_judgeable_groundtruth_similarity
2679141
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: For instance, I am setting an interval like timer = setInterval(fncName, 1000); and if i go and do clearInterval(timer); it does clear the interval but is there a way to check that it cleared the interval? I've tried getting the value of it while it has an interval and when it doesn't but they both just seem to be numbers. Now provide the response and nothing else.
There is no direct way to do what you are looking for. Instead, you could set timer to false every time you call clearInterval : // Start timervar timer = setInterval(fncName, 1000);// End timerclearInterval(timer);timer = false; Now, timer will either be false or have a value at a given time, so you can simply check with if (timer) ... If you want to encapsulate this in a class: function Interval(fn, time) { var timer = false; this.start = function () { if (!this.isRunning()) timer = setInterval(fn, time); }; this.stop = function () { clearInterval(timer); timer = false; }; this.isRunning = function () { return timer !== false; };}var i = new Interval(fncName, 1000);i.start();if (i.isRunning()) // ...i.stop();
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/2679141', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/291809/']}
jdg_86473
stackexchange
llm_judgeable_groundtruth_similarity
4407040
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: Reading through the Wiki article on direct products ( https://en.wikipedia.org/wiki/Direct_product ), an example is given using the set of real numbers, $\mathbb{R}$ , viewed as a set endowed with different algebraic structures. In all cases the underlying set of $\mathbb{R}\times\mathbb{R}$ is (of course) $\mathbb{R}^2$ . However, when considering $\mathbb{R}$ as a field, the article states that the direct product is undefined, since the set $\mathbb{R}^2$ endowed with the naïve addition $(a,b)+(c,d)=(a+c,b+d)$ and multiplication $(a,b)\cdot(c,d)=(ac,bd)$ is clearly not a field. My problem is that the set $\mathbb{R}^2$ can be endowed with a multiplicative structure that makes it into a field (since $\mathbb{R}^2=\mathbb{C}$ as a set), so my question is the following: Why can we not define $\mathbb{R}\times\mathbb{R}$ as $\mathbb{C}$ , when viewing $\mathbb{R}$ as the field of real numbers? Is there an implicit assumption in the definition of direct product that if $X$ has some algebraic operation $*$ , then $X\times X$ must have the corresponding operation $*_{\times}$ defined as $(x_1,x_2)*_{\times}(y_1,y_2):=(x_1 * y_1,x_2 * y_2)$ ? If so, is this because of the way the direct product is defined in category theory? Now provide the response and nothing else.
A product $A \times B$ also comes with a pair of projection maps $\pi_1: A \times B \rightarrow A$ and $\pi_2: A \times B \rightarrow B$ . These are a fundamental part of the definition of a direct product. We want these projections to be morphisms in the category we're considering. In this case, we want them to be ring homomorphisms, so they need to preserve the operations of the ring. Using this, we can prove that the operation of the product has to be as expected. $$\pi_1((x_1,x_2)*_{\times}(y_1,y_2)) = \pi_1(x_1,x_2) *\pi_1(y_1,y_2) = x_1 * y_1$$ So the first entry of the result under the operation has to be $x_1 * y_1$ . The same idea works for the second element, giving $(x_1,x_2)*_{\times}(y_1,y_2):=(x_1 * y_1,x_2 * y_2)$ . If you try to define the product of $\mathbb{R}$ with itself as $\mathbb{C}$ , you find that no pair of projection maps can work, in part because any ring homomorphism out of a field must be injective.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4407040', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/215489/']}
jdg_86474
stackexchange
llm_judgeable_groundtruth_similarity
2305496
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$ be the free group on the generating set $A$. Note that $F$ is not abelian if $A$ contains more than one element. How am I suppose to note this? Doesn't $Z\times Z$ has 2 elements in it's generating set (more than one element) but abelian? How? Now provide the response and nothing else.
$\mathbb Z\times \mathbb Z$ is the free abelian group of two generators, but it is not the free group of two generators. The free group of two generators $F(a,b)$ is the set of all (reduced) finite strings containing the letters $a, b, a^{-1},$ and $b^{-1}$, whose group operation is concatenation-and-reduction. It, then, should be clear that $ab$ and $ba$ are two different elements of $F(a,b)$, and so this group is not abelian.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2305496', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_86475
stackexchange
llm_judgeable_groundtruth_similarity
2340223
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 drop down menu in only CSS and no JAVASCRIPT and I'm having a problem keeping the top (main menu item) highlighted when I move the cursor over the sub menu items. You can see the menu here http://www.codedecks.com/cssnav.html . If you hover over "Kids" and move your cursor down, as soon as your over "Girls" the top "Kids" looses the highlight. Any suggestion would be greatly appreciated! Thanks in advance Now provide the response and nothing else.
Change #nav > li a:hover to #nav > li:hover a in your CSS. Since you have the hidden second-level ul being shown when the top-level li is hovered, it makes sense to have the top-level a get the hover style at the same time. When you move your mouse over the second-level menu links, the a still looks active. li:hover applies even when you mouse over the child elements of the li , even if they're positioned so that they look like they're outside of the li 's box.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2340223', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/281867/']}
jdg_86476
stackexchange
llm_judgeable_groundtruth_similarity
17580150
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What is the best (shortest and fastest) way to check if StringBuilder ends with specific string? If I want to check just one char, that's not a problem sb[sb.Length-1] == 'c' , but how to check if it's ends with longer string? I can think about something like looping from "some string".Length and read characters one by one, but maybe there exists something more simple? :) At the end I want to have extension method like this: StringBuilder sb = new StringBuilder("Hello world");bool hasString = sb.EndsWith("world"); Now provide the response and nothing else.
To avoid the performance overhead of generating the full string, you can use the ToString(int,int) overload that takes the index range. public static bool EndsWith(this StringBuilder sb, string test){ if (sb.Length < test.Length) return false; string end = sb.ToString(sb.Length - test.Length, test.Length); return end.Equals(test);} Edit : It would probably be desirable to define an overload that takes a StringComparison argument: public static bool EndsWith(this StringBuilder sb, string test){ return EndsWith(sb, test, StringComparison.CurrentCulture);}public static bool EndsWith(this StringBuilder sb, string test, StringComparison comparison){ if (sb.Length < test.Length) return false; string end = sb.ToString(sb.Length - test.Length, test.Length); return end.Equals(test, comparison);} Edit 2 : As pointed out by Tim S in the comments, there is a flaw in my answer (and all other answers that assume character-based equality) that affects certain Unicode comparisons. Unicode does not require two (sub)strings to have the same sequence of characters to be considered equal. For example, the precomposed character é should be treated as equal to the character e followed by the combining mark U+0301 . Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");string s = "We met at the cafe\u0301";Console.WriteLine(s.EndsWith("café")); // True StringBuilder sb = new StringBuilder(s);Console.WriteLine(sb.EndsWith("café")); // False If you want to handle these cases correctly, it might be easiest to just call StringBuilder.ToString() , and then use the built-in String.EndsWith .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17580150', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1127918/']}
jdg_86477
stackexchange
llm_judgeable_groundtruth_similarity
489186
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: A complex number $z$ is said to be algebraic if there are integers $a_0, ..., a_n$, not all zero, such that $a_0z^n+a_1z^{n-1}+...+a_{n-1}z+a_n=0$.Prove that the set of all algebraic numbers is countable. The Hint is: For every positive integer $N$ there are only finitely many equations with$n+|a_0|+|a_1|+...+|a_n|=N$. Here is a proof I have. The problem though, is that I did not use the hint provided in the text, so maybe this proof is invalid or that there is analternate (simpler) proof? Please help me out here. Thanks in advance. Proof: The set of integers is countable, we have this following theorem: Let $A$ be a countable set, and let $B_n$ be the set of all n-tuples $(a_1,...,a_n)$, where $a_k \in A, k=1,...,n,$ and the elements $a_1,...,a_n$ need not be distinct. Then $B_n$ is countable. So by this theorem, the set of all $(k+1)$-tuples $(a_0,a_1,...,a_k)$ with $a_0 \neq 0$ is also countable. Let this set be represented by $\mathbb Z ^k$. For each a $a \in \mathbb Z ^k$ consider the polynomial $a_0z^k+a_1z^{k-1}+...+a_k=0$. From the fundamental theorem of algebra, we know that there are exactly $k$ complex roots for this polynomial. We now have a series of nested sets that encompass every possible root for every possible polynomial with integer coefficients. More specifically, we have a countable number of $\mathbb Z^k s$, each containing a countable number of $(k + 1)$-tuples, each of which corresponds with $k$ roots of a $k$-degree polynomial. So our set of complex roots (call it $R$) is a countable union of countable unions of finite sets. This only tells us that $R$ is at most countable: it is either countable or finite. To show that $R$ is not finite, consider the roots for $2$-tuples in $\mathbb Z^1$. Each $2$-tuple of the form $(-1, n)$ corresponds with the polynomial $-z + n = 0$ whose solution is $z = n$. There is clearly a unique solution for each $n \in \mathbb Z$, so $R$ is an infinite set. Because $R$ is also at most countable, this proves that $R$ is countable. Now provide the response and nothing else.
Yes, you're correct; if you want to be more formal, you're using Cantor-Schroeder-Bernstein in your last step http://en.wikipedia.org/wiki/Cantor-Schroder-Bernstein_theorem , in concluding, from the existence of an injection between the set of all roots and the collection of polynomials and an injection between the pairs ($(1,n)$ and the set of all possible roots, that the collection of roots (i.e., the algebraic numbers) is countably-infinite.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/489186', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/75343/']}
jdg_86478
stackexchange
llm_judgeable_groundtruth_similarity
52452979
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Adding application.statusBarStyle = .lightContent to my AppDelegate's didFinishLaunchingWithOptions method nor adding override var preferredStatusBarStyle: UIStatusBarStyle { return UIStatusBarStyle.lightContent} to the VC no longer works on iOS12/Xcode10 Any ideas? Now provide the response and nothing else.
This has nothing to do with iOS 12. You just have the rules wrong. In a navigation controller situation, the color of the status bar is not determined by the view controller’s preferredStatusBarStyle . It is determined, amazingly, by the navigation bar’s barStyle . To get light status bar text, say (in your view controller): self.navigationController?.navigationBar.barStyle = .black Hard to believe, but true. I got this info directly from Apple, years ago. You can also perform this setting in the storyboard. Example! Navigation bar's bar style is .default : Navigation bar's bar style is .black : NOTE for iOS 13 This still works in iOS 13 as long as you don't use large titles or UIBarAppearance. But basically you are supposed to stop doing this and let the status bar color be automatic with respect to the user's choice of light or dark mode.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/52452979', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/961425/']}
jdg_86479
stackexchange
llm_judgeable_groundtruth_similarity
110357
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I've been trying to focus a bit more on Analog circuits lately and found that my design and actual results often don't match up exactly. An example is a Pierce oscillator I built a while back, the circuit worked mostly as expected but the gain required was much less than I calculated for (meaning I got some distortion). Is it common practice to just change the values to what seems to work right and go on or is it better to make sure the theory matches up as well? To clarify, I mean that after observing the difference and playing around with some values I change the design to match, the circuit then gives the desired output but my initial design was inaccurate. Should I go back and try to identify why or is it just not worth it? ie, no calibration on production units. Thanks for all the replies, I'm going back to the drawing board because there's clearly something going on that I don't understand. Ignoring it would possibly create other problems. Now provide the response and nothing else.
If your prototype performance doesn't match your anticipated performance this can indicate an error in the design process or a build error. You really should sort this out if you are going to be making several units or more because it will only come back and bite you. ISO9000 talks about "Design Verification" - this is basically proving the design/prototype does what it was intended to do. This is important and shouldn't be short-changed - if your pierce oscillator doesn't produce the correct amplitude I'd want to know why. "Design validation" checks that production units are still meeting expectations. A really good test that I always do is spray the circuit with a freezer spray and see what happens and I also touch each chip and transistor with the tip of a soldering iron. This is done on the bench and I'm looking for unexpected brief changes in amplitudes (or some other parameter) as an indicator that something is wrong. If all is OK then nothing beats a good full load test at elevated temperatures. This can find a lot of anomalies on a complex circuit.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/110357', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/6173/']}
jdg_86480
stackexchange
llm_judgeable_groundtruth_similarity
5781099
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Using AutoMapper, is it possible to map only the changed properties from the View Model to the Domain Object? The problem I am coming across is that if there are properties on the View Model that are not changed (null), then they are overwriting the Domain Objects and getting persisted to the database. Now provide the response and nothing else.
Yes, it can be done, but you have to specify when to skip the destination property using Condition() in your mapping configuration. Here's an example. Consider the following classes: public class Source{ public string Text { get; set; } public bool Map { get; set; }}public class Destination{ public string Text { get; set; }} The first map won't overwrite destination.Text , but the second will. Mapper.CreateMap<Source, Destination>() .ForMember(dest => dest.Text, opt => opt.Condition(src => src.Map));var source = new Source { Text = "Do not map", Map = false };var destination = new Destination { Text = "Leave me alone" };Mapper.Map(source, destination);source.Map = true;var destination2 = new Destination { Text = "I'll be overwritten" };Mapper.Map(source, destination2);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5781099', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/587920/']}
jdg_86481
stackexchange
llm_judgeable_groundtruth_similarity
164015
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 used to search for the Landau (Big O, Theta...) notation of my algorithms by hand to make sure they are as optimized as they can be, but when the functions are getting really big and complex, it's taking way too much time to do it by hand. it's also prone to human errors. I spent some time on Codility (coding/algo exercises), and noticed they will give you the Landau notation for your submitted solution (both in Time and Memory usage). I was wondering how they do that...How would you do it? Is there another way besides Lexical Analysis or parsing of the code? This question concerns mainly PHP and or JavaScript, but I'm opened to any language and theory. Now provide the response and nothing else.
I was wondering how they do that... How would you do it? I imagine that they are actually estimating the Big O measures ... by running the program for different problem sizes, measuring time and space usage, and fitting curves to the results. The problem with this approach is that it can get it wrong if the cost functions change shape as N gets large; e.g. 1000 N + N^1.5 . Is there another way besides Lexical Analysis or parsing of the code? Lexical analysis and parsing are not sufficient. You also need to do some reasoning about the behaviour of the algorithm. And doing that automatically for a previously unknown algorithm is hard.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/164015', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/63607/']}
jdg_86482
stackexchange
llm_judgeable_groundtruth_similarity
2592200
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: While doing a course, a questions tells me the following: Given an infinite collection $A_n$, $n=1,2,\dots$ of intervals of the real line, their intersection is defined to be $\bigcap^∞_{n=1}A_n=\{x\mid(\forall n)(x\in A_n)\}$. What does this mean? Is $A_n$ the collection of $(1,2),(2,3),(3,4),\dots$? Or is it $[1,2],[2,3],[3,4],\dots$? Or is it something else entirely? This may be a very silly question, but I was taught real analysis in a lecture half an hour long, so my knowledge is extremely lacking. Please help. Now provide the response and nothing else.
Here's a situation which is perhaps more familiar to you. Sometimes, in calculus, you run across a question which starts like this: Given an infinite sequence $x_n$, $n=1,2,...$ of real numbers,... When you see this, you know that $x_1$ can be an arbitrary real number, and $x_2$ can be an arbitrary real number, and the same for $x_3$, $x_4$, and for every other number in this sequence. This kind of question will be telling you some information about an arbitrary sequence of real numbers. For example, this is how you would start the definition of the limit of the sequence. Or, this is how you would start the theorem that the limit of a sum of two sequences (this sequence $x_n$ and another sequence $y_n$) is equal to the sum of the limits. Or something else, who knows. So, suppose you run across a question which starts like this: Given an infinite collection $A_n$, $n=1,2,...$ of intervals in the real line... When you see this, you know that $A_1$ can be an arbitrary interval in the real line, and $A_2$ can be an arbitrary interval in the real line, and the same for $A_3$, $A_4$, and for every other interval in this collection. This kind of question will be telling you something about an arbitrary collection of intervals in the real line. So, for example, your question is giving you the definition of the intersection of an arbitrary collection of intervals in the real line.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2592200', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/395207/']}
jdg_86483
stackexchange
llm_judgeable_groundtruth_similarity
1831401
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $A$ be a real $m \times n$ matrix. How do you prove that $\{ Ax \mid x \geq 0, x \in \mathbb R^n \}$ is closed (as in, contains all its limit points)? The inequality $x \geq 0$ is interpreted component-wise. This fact is used in some proofs of Farkas's lemma. It seems like it should be easy, but the proof I've seen seems to be unexpectedly complicated. Is there a very clear / easy / obvious proof of this fact? (Note that linear transformations do not always map closed sets to closed sets, as discussed in this question . For example, let $S = \{ (x,y) \in \mathbb R^2 \mid y \geq e^x \}$ and let $T:\mathbb R^2 \to \mathbb R^2$ such that $T(x,y) = (0,y)$. Then $S$ is closed, but $T(S)$ is not closed.) Edit: Here is a simple proof in the case where $A$ has full column rank. (A very similar proof is given in Nocedal and Wright, in the Notes and References at the end of chapter 12.)Let $y^*$ be a limit point of $\Omega = \{ Ax \mid x \geq 0, x \in \mathbb R^n \}$. There exists a sequence $(x_i)_{i=1}^\infty$ of points in $\mathbb R^n$ such that $x_i \geq 0$ for all $i$ and $A x_i \to y^*$ as $i \to \infty$. Let $B$ be a left inverse for $A$. Then $B A x_i \to B y^*$ as $i \to \infty$. In other words, $x_i \to x^*$ as $i \to \infty$, where we have defined $x^* = B y^*$. Clearly, $x^* \geq 0$ and $A x^* = y^*$. This shows that $y^* \in \Omega$. (Alternatively, you could just note that if $A$ has full column rank then the mapping $x \mapsto Ax$ is a homeomorphism between $\mathbb R^n$ and $R(A)$, so it maps closed sets to closed sets. This shows that $\Omega$ is a closed subset of $R(A)$, and it follows that $\Omega$ is a closed subset of $\mathbb R^m$.) Now provide the response and nothing else.
We denote by $a_i \in \mathbb R^m$, $i = 1, \ldots, n$ the columns of $A$. By a conic variant of Carathéodory's theorem, each conic combination of $\{a_i\}$ can be written as a conic combination of a linearly independent subset of $\{a_i\}$. Since there are only finitely many linearly independent subsets of $\{a_i\}$, it is sufficient to prove the claim for matrices $A$ which have full column rank (i.e., all columns are linearly independent). But in this case, the claim is easy to establish.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1831401', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/40119/']}
jdg_86484
stackexchange
llm_judgeable_groundtruth_similarity
6295185
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 Python how do i loop through list starting at a key and not the beginning.e.g. l = ['a','b','c','d'] loop through l but starting at b e.g. l[1] Now provide the response and nothing else.
The straightforward answer Just use slicing : >>> l = ['a','b','c','d']>>> for i in l[1:]:... print(i)... bcd It will generate a new list with the items before 1 removed: >>> l[1:]['b', 'c', 'd'] A more efficient alternative Alternatively, if your list is huge, or you are going to slice the list a lot of times, you can use itertools.islice() . It returns an iterator, avoiding copying the entire rest of the list, saving memory: >>> import itertools>>> s = itertools.islice(l, 1, None)>>> for i in s:... print(i)... bcd Also note that, since it returns an interator, you can iterate over it only once: >>> import itertools>>> s = itertools.islice(l, 1, None)>>> for i in s:... print(i)... bcd>>> for i in s:... print(i)>>> How to choose I find slicing clearer/more pleasant to read but itertools.islice() can be more efficient. I would use slicing most of the time, relying on itertools.islice() when my list has thousands of items, or when I iterate over hundreds of different slices.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6295185', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/220129/']}
jdg_86485
stackexchange
llm_judgeable_groundtruth_similarity
39451822
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Say I have two files: # spam.pyimport library_Python3_only as l3def spam(x,y) return l3.bar(x).baz(y) and # beans.pyimport library_Python2_only as l2... Now suppose I wish to call spam from within beans . It's not directly possible since both files depend on incompatible Python versions. Of course I can Popen a different python process, but how could I pass in the arguments and retrieve the results without too much stream-parsing pain? Now provide the response and nothing else.
Here is a complete example implementation using subprocess and pickle that I actually tested. Note that you need to use protocol version 2 explicitly for pickling on the Python 3 side (at least for the combo Python 3.5.2 and Python 2.7.3). # py3bridge.pyimport sysimport pickleimport importlibimport ioimport tracebackimport subprocessclass Py3Wrapper(object): def __init__(self, mod_name, func_name): self.mod_name = mod_name self.func_name = func_name def __call__(self, *args, **kwargs): p = subprocess.Popen(['python3', '-m', 'py3bridge', self.mod_name, self.func_name], stdin=subprocess.PIPE, stdout=subprocess.PIPE) stdout, _ = p.communicate(pickle.dumps((args, kwargs))) data = pickle.loads(stdout) if data['success']: return data['result'] else: raise Exception(data['stacktrace'])def main(): try: target_module = sys.argv[1] target_function = sys.argv[2] args, kwargs = pickle.load(sys.stdin.buffer) mod = importlib.import_module(target_module) func = getattr(mod, target_function) result = func(*args, **kwargs) data = dict(success=True, result=result) except Exception: st = io.StringIO() traceback.print_exc(file=st) data = dict(success=False, stacktrace=st.getvalue()) pickle.dump(data, sys.stdout.buffer, 2)if __name__ == '__main__': main() The Python 3 module (using the pathlib module for the showcase) # spam.pyimport pathlibdef listdir(p): return [str(c) for c in pathlib.Path(p).iterdir()] The Python 2 module using spam.listdir # beans.pyimport py3bridgedelegate = py3bridge.Py3Wrapper('spam', 'listdir')py3result = delegate('.')print py3result
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39451822', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/745903/']}
jdg_86486
stackexchange
llm_judgeable_groundtruth_similarity
4068862
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 all $k$ such that $$2^k + k \equiv 0 \pmod{323}.$$ I noticed that $323 = 17\cdot 19$ so I thought about using the Chinese Remainder theorem by considering $2^k+k$ modulo 17 and 19. I got $k \equiv 16 \pmod{17}$ and $k\equiv 18 \pmod{19}$ , which gives $k\equiv 322 \pmod{323}$ . However, after trying this, the given solution was not valid : $2^{322} + 322 \equiv 156 \not \equiv 0 \mod{323}$ . Can someone explain why this didn't work, and what I can do to solve this problem? Thanks. Now provide the response and nothing else.
As explained in the comments, it didn't work because CRT wasn't applied correctly. In particular, the solution to $ 2^k + k \equiv 0 \pmod{17}$ has a cycle length of $ 16 \times 17$ , because $2^k$ has a cycle length of 16 and $k$ has a cycle length of 17. So, the (theoretical) approach is to find all the solutions to $2^k+k \equiv 0 \pmod{17} $ working in $\pmod{17 \times 16}$ , and likewise for the other equation working in $\pmod{19 \times 18}$ , and finally combine them via CRT in $ \pmod{17 \times 19 \times 144}$ . If you understand the above logic, I do not recommend actually finding all the solutions, as it's just a very tedious process that's best left to the computer.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4068862', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_86487
stackexchange
llm_judgeable_groundtruth_similarity
54299037
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 learning how to make a game with the canvas via JavaScript, and I have the arrow keys set to move a block on the canvas. I want to add a modifier in which while holding shift, the block moves twice as fast, and I cannot get my function to work properly when the shift key is pressed. Any suggestions/help would be much appreciated! var myGameArea = { canvas : document.createElement("canvas"), start : function() { this.canvas.width = 540; this.canvas.height = 330; this.context = this.canvas.getContext("2d"); document.body.appendChild(this.canvas,document.body.childNodes[0]); this.canvas.setAttribute("id", "myCanvas"); this.canvas.hidden = true; this.interval = setInterval(updateGameArea, 1000/FPS); window.addEventListener('keydown', function (e) { myGameArea.keys = (myGameArea.keys || []); myGameArea.keys[e.keyCode] = (e.type == "keydown"); }) window.addEventListener('keyup', function (e) { myGameArea.keys[e.keyCode] = (e.type == "keydown"); })}, clear : function(){ this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); } }function component(width, height, color, x, y) {this.gamearea = myGameArea;this.width = width;this.height = height;this.speedX = 0;this.speedY = 0; this.x = x;this.y = y; this.update = function() { ctx = myGameArea.context; ctx.fillStyle = color; ctx.fillRect(this.x, this.y, this.width, this.height);}this.newPos = function() { this.x += this.speedX; this.y += this.speedY; }}function updateGameArea() {myGameArea.clear();myGamePiece.speedX = 0;myGamePiece.speedY = 0;if (myGameArea.keys && myGameArea.keys[37]) {myGamePiece.speedX = -10; }if (myGameArea.keys && myGameArea.keys[39]) {myGamePiece.speedX = 10; }if (myGameArea.keys && myGameArea.keys[38]) {myGamePiece.speedY = -10; }if (myGameArea.keys && myGameArea.keys[40]) {myGamePiece.speedY = 10; }if (myGameArea.keys && myGameArea.keys[65]) {myGamePiece.speedX = -10; }if (myGameArea.keys && myGameArea.keys[68]) {myGamePiece.speedX = 10; }if (myGameArea.keys && myGameArea.keys[87]) {myGamePiece.speedY = -10; }if (myGameArea.keys && myGameArea.keys[83]) {myGamePiece.speedY = 10; } //What do I need to do to get the following function to execute? (NOTE //THIS WAS MOVED TO AFTER IF STATEMENTS PER COMMENT BELOW, THIS DID NOT /////FIX the ISSUE)GetShiftState(e);myGamePiece.newPos(); myGamePiece.update();}//Below is the get shift key function I cannot get to work. //What I am trying to do is increase the speed of the gamepiece moving //when holding shift + the directional arrow function GetShiftState (e) { if (e.shiftKey) { switch(e.which) { case 37: console.log("shift + left arrow"); myGamePiece.speedX = -20; break; case 38: console.log("shift + up arrow"); myGamePiece.speedY = -20; break; case 39: console.log("shift + right arrow"); myGamePiece.speedX = 20; break; case 40: console.log("shift + down arrow"); myGamePiece.speedY = 20; break; default: break; } } else { console.log("Shift key is up."); } } Now provide the response and nothing else.
You need a second $ in your recipe: remove_all_containers: docker container rm $$(docker ps -aq) -f# ^ The single $ is expanded as a makefile variable when the makefile is parsed. It expands to blank. Make therefore passes docker container rm -f to your shell. The second $ sign causes make to expand $$ to $ , and it will pass docker container rm $(docker ps -aq) -f to bash, which I'm guessing is what you want. Notice, if you put the shell in there as @EricMd proposed, it will run a shell command, but that command will be run at Makefile read time, as opposed to the time that the recipe is executed. If the docker ps -aq command is dependent on any other artifacts of your build it would not work.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/54299037', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9727990/']}
jdg_86488
stackexchange
llm_judgeable_groundtruth_similarity
5085974
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've got a mailer sending through a GMail account, and I want to test that ActionMailer can actually log in to GMail's SMTP server with the credentials I've given it. What's the best way to test this? Now provide the response and nothing else.
It's not a full-stack solution, but you can check that the server authentication happens correctly by using Net::SMTP directly. The Mail gem that Rails 3 uses to send ActionMailer emails uses Mail like so (with your ActionMailer.smtp_settings): #line 96 of mail-2.2.7/lib/mail/network/delivery_methods/smtp.rb smtp = Net::SMTP.new(settings[:address], settings[:port]) if settings[:enable_starttls_auto] smtp.enable_starttls_auto if smtp.respond_to?(:enable_starttls_auto) end smtp.start(settings[:domain], settings[:user_name], settings[:password], settings[:authentication]) do |smtp| smtp.sendmail(message, envelope_from, destinations) # @Mason: this line need not be included in your code. SMTP#start throws # a Net::SMTPAuthenticationError if the authentication was not successful. # So just putting this call to #start with an empty block in a method and # calling assert_no_raise Net::SMTPAuthenticationError should do the trick. # The empty block is necessary so that the connection gets closed. # Reference #{rubydir}/lib/ruby/1.8/net/smtp.rb for more info. end Looks like ActionMailer::Base.smtp_settings is accessible too: settings = ActionMailer::Base.smtp_settings Putting that in your test and commenting out the line spoken of above should have a working example for you.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5085974', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/485583/']}
jdg_86489
stackexchange
llm_judgeable_groundtruth_similarity
182696
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: With NGINX and PHP I am allowing 5GB files to be 'uploaded' to my server although they will not be downloaded unless they are 'legitimate' (that is for another question ;)). I was wondering is this is making it easier for DDOS attacks or other attacks or is it as vulnerable as normal seeing as 1 large request is the same if not less intensive than as many small http requests. Now provide the response and nothing else.
I'm going to go for an answer but I'm also not an expert on this particular topic, so I'll be curious to read any other answers that might come in. I believe that the short answer is this: allowing large HTTP post bodies certainly provides an avenue for DOS attacks, but it isn't necessarily the most attractive avenue for DOS attacks. As a result, I certainly wouldn't set a max body size substantially larger than what I need, but if I needed a large post body I would allow it and not worry to much about it. In detail: Preferred DDOS attack vectors There are lots of ways to DOS a website. These days the largest DDOS attacks come from amplified DDOS attacks. These are attacks that (typically) hit UDP protocols that can receive a small amount of traffic and respond with a much larger amount of traffic which can be directed to arbitrary IP addresses on the internet. For instance, the current (March 2018) record for largest DDOS attack hit github using such an attack vector ( https://githubengineering.com/ddos-incident-report/ ). These sorts of attacks seek to completely overwhelm the network capacity of the target servers, taking them down for as long as the attack lasts. The vector used in the github incident had an amplification factor of ~51,000, which means that for each byte of network traffic the originating botnet created, 51,000 bytes hit github. At the peak of the attack github's network (or their DDOS mitigation provider's network) saw roughly 1.35Tbs of traffic. Assuming an amplification factor of 51000x, this means the actual botnet that triggered the attack could push out roughly 26Mbs of traffic. If that same botnet had been used to simply upload large amounts of data to an endpoint that accepted large uploads, there would have been no amplification and githhub would have been hit with a DDOS attack that consumed roughly 26Mbs of github's traffic. I doubt they would have noticed. Above I focused on amplification-based DDOS attacks, but they obviously aren't the only option. The amplification part is what made this one so successful (in terms of network traffic - it didn't actually take down github), but you also need to find a suitable amplification vector that you can exploit to perform such an attack. Otherwise though, there are many other ways to DDOS a service: you can overrun its CPU capabilities (imagine repeatedly hitting a poorly performing endpoint that sucks up substantial CPU or database resources per request), you can overrun its network by simply throwing lots of data at it, you can hold open TCP/IP connections until the server empties its connection pool, etc... Disadvantages of attacking a file upload All this to say: overrunning a file upload endpoint is certainly one way to try to DOS a system, but probably not the best. The trouble is that it leaves the attacker and defender on equal territory. You can only overwhelm the target with as much data as you are able to send. Using up open connection pools, hitting high-resource endpoints, amplification attacks, etc, are all ways to attack a resource that give your resources extra leverage, and make it easier to DDOS people. As a result, you certainly can DOS someone by overwhelming a file upload endpoint, but there are probably more effective ways to do it. Moreover, as long as you have enough network traffic at your disposal, I don't think that hitting a file upload endpoint will have any particular advantages: I believe that you can send the data regardless of whether or not the server on the other end feels like receiving it. The only possible advantage I can see about hitting a file upload endpoint (although again, not an expert in this area), is that the file ends up actually stored on a server somewhere, and you may be able to fill up a hard-drive with large temporary files. Even this though is probably not the most effective DOS strategy. All this brings us back to what I originally said: be smart and don't configure your server to allow substantially larger uploads than you need, but in terms of security concerns there are likely larger ones than this. Securing a file upload endpoint While a file upload endpoint may not be the first choice of places to hit with a DDOS attack, that doesn't mean that security concerns should go out the window. As you mention in comments, requiring user access doesn't help much: PHP will accept the upload regardless and store it in a temporary location. It will get immediately deleted when you don't do anything with the upload, but it will still get written to disk temporarily. Your other suggestion of setting the /tmp directory size large enough that you can't run out of free space (as determined by your available bandwidth) will certainly make sure your hard-drive won't fill up (although overflowing a /tmp directory wouldn't necessarily kill a server, especially if it is on its own partition). That then shows the next weak point in your chain - if all your bandwidth is being used up in an attempt to overwhelm a file upload endpoint, then your service is going to be down regardless of whether or not your machine has space on its hard-drive (because your network bandwidth is all used up). Which pretty much answers your question because at that point in time a DDOS via file upload is no longer possible. If your file upload endpoint can't be DDOS'd except by completely overwhelming your network bandwidth, then no one will bother trying to DDOS your file upload endpoint: they'll just aim enough traffic at you to try to overwhelm your network connection. At that point in time, I'd say that your file upload is secure! I'm not sure how much it would cost to purchase that much hard-drive space. It would depend on your hosting provider (although hard-drive space is usually cheap) and your available bandwidth. That being said, there is also a pretty simple solution to protect such a system: put your file upload system on a separate server on a separate network, ( uploads.example.com ) and make sure all your systems have some DDOS protection (i.e. cloudflare). Then a DDOS against your file upload endpoint can take it down, but the rest of your systems would continue on their merry way. Of course in that case, I can't imagine someone would try to DDOS your file upload. They would just try to find a more appealing attack vector that impacts your main systems.
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/182696', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/108497/']}
jdg_86490
stackexchange
llm_judgeable_groundtruth_similarity
1124788
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What are the possible causes of a "java.lang.Error: Unresolved compilation problem"? Additional information: I have seen this after copying a set of updated JAR files from a build on top of the existing JARs and restarting the application. The JARs are built using a Maven build process. I would expect to see LinkageErrors or ClassNotFound errors if interfaces changed. The above error hints at some lower level problem. A clean rebuild and redeployment fixed the problem. Could this error indicate a corrupted JAR? Now provide the response and nothing else.
(rewritten 2015-07-28) The default behavior of Eclipse when compiling code with errors in it, is to generate byte code throwing the exception you see, allowing the program to be run. This is possible as Eclipse uses its own built-in compiler, instead of javac from the JDK which Apache Maven uses, and which fails the compilation completely for errors. If you use Eclipse on a Maven project which you are also working with using the command line mvn command, this may happen. The cure is to fix the errors and recompile, before running again. The setting is marked with a red box in this screendump:
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1124788', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_86491
stackexchange
llm_judgeable_groundtruth_similarity
376552
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: For example, suppose I have a ZipCode class: public class ZipCode{ public value String value; public boolean validateFormat(){ ... } public otherMethod1(){ ... }} I found many classes uses ZipCode instances, but validateFormat() is used in one place only : register page: public class RegisterPage{ public void submit(){ ... ZipCode z=new ZipCode(); z.value=zipCodeTextField.getText(); if(z.validateFormat()){ } ... }} So my question is, should I move the codes in validateFormat() into submit(), in order to fit YAGNI rule? Now provide the response and nothing else.
The question you ask is generalized, but the issue here is not what you think it is. The majority of this answer focuses on the real issue, but I want to respond to your direct question first. So my question is, should I move the codes in validateFormat() into submit(), in order to fit YAGNI rule? Unless your validation logic is complex enough to warrant its own class, or you're specifically striving for an anemic data model, I don't see a need to separate the logic here. It's not so much YAGNI, but more a consideration of why you have the validation. Based on your code, the validation exists specifically to prevent creating invalid zip codes. This means that the existence of an object and the validation of its input are closely tied together, and the validation merely exists to support the existence of the object. If that is the case, then it's not wrong to keep these two together, as long as the validation does not far outweigh the complexity of the ZipCode class. For example, a simple "has 4 digits" check is fine. A complex algorithm that performs checksum calculations and queries external resources is not good to put in your class. If a instance method is used in one place only, should I move that method to that place? If Bob is the only one that drinks coffee in the office, should we put the coffee maker on Bob's desk? The good practice answer is "no". The coffee maker belongs in the kitchen for a good reason. We might hire a new employee who also drinks coffee (= new code that uses the validation). Bob needs his desk space for things related to his work (= SRP). If maintenance needs to repair the machine, they're going to be looking for it with the other drink machines. (= other developers won't always know where to look). Your code is putting the cart before the horse. While I do admit this issue is currently more on principle, it is part of the root of your problem. //Make a new zip codeZipCode z=new ZipCode();z.value=zipCodeTextField.getText();//Is this zipcode a valid zipcode?if(z.validateFormat()){ It doesn't quite make sense to first make something a zip code, and then retroactively check if it's actually a (valid) zip code. The consequence is that you've created a system where a ZipCode object can be valid or invalid. It's going to lead to you second-guessing ZipCode objects all over your codebase, often repeated the same validity check You should invert that logic: //Is this value a valid zipcode?// YES => Then make it into a zipcode object.// NO => We refuse to make an invalid zipcode object. This means that the existence of a ZipCode object inherently tells you that it's a valid zip code. There are two ways to achieve this. I've heard arguments pro/con either way, so I'm just presenting them both. 1. Constructor validation. Example: public class ZipCode{ public string Value { get; private set; } public ZipCode(string value) { if(!validateFormat(value)) throw new Exception($"{value} is not a valid zip code format.!"); this.Value = value; } private boolean validateFormat(){ ... }} Pro : You guarantee that no one can create a ZipCode object that contains an invalid zip code. Any subsequent code that handles a ZipCode object can blindly rely on having received a valid zip code. Con : Some developers really dislike throwing exceptions. I have a more nuanced view, and consider exceptions appropriate here as they are a last resort refusal to create an invalid object. You can't easily (de)serialize objects when they don't have a parameterless constructor. 2. Property validation. Example: public class ZipCode{ private string _value; public string Value { get { return this._value; } set { if(!validateFormat(value)) throw new Exception($"{value} is not a valid zip code format.!"); this.Value = value; } } private boolean validateFormat(){ ... }} Pro : You guarantee that no one can set a ZipCode 's value in a way that it contains an invalid zip code. Any subsequent code that handles a ZipCode object can pretty much rely on having received a valid zip code. There are caveats here, which I will point out in the "con". Compared to the constructor validation, you are now able to (de)serialize this object since it has a parameterless constructor. Con : If you do new ZipCode() and never set the property, you will still have an invalid value in your ZipCode . If you're okay with having a "default null" value, you should really consider using a Nullable<ZipCode> (or ZipCode? ) instead of a ZipCode with a possible invalid state. If you're not okay with having a "default null" value, then you can combine constructor validation and property validation in order to allow people to change the value to other valid values. However, if you need a parameterless constructor (e.g. for deserialization), you're either going to have to define a default value for the property, or accept that it may be null if no one has hever set the property. Some developers really dislike throwing exceptions. I have a more nuanced view, and consider exceptions appropriate here as they are a last resort refusal to create an invalid object. 3. Validate before you create. This effectively makes it so that you separate your zip code from your zip code validation. Example: public static class ZipCodeValidator{ public static boolean Validate(string value){ ... }} And then: public void submit(){ string zipCodeValue = zipCodeTextField.getText(); if(ZipCodeValidator.Validate(zipCodeValue)) { var zipCode = new ZipCode() { Value = zipCodeValue }; } } Pro : The current code ensures that you only create a ZipCode when the supplied value is valid. This allows you to separate the object from its validation. However, I'm not quite convinced that that's necessary to do so, unless your validation logic is excessively massive (e.g. doing online lookups or complex calculations). Con : Nothing is preventing a developer from (mistakenly) creating a ZipCode object and forgetting to validate the input at some other point in time (or when making a change to the existing code). It's no longer a guarantee that ZipCode objects are guaranteed to be valid. For 3., you could've just as well put this static method in the class. It doesn't matter on a technical level. And the same argumetn applies here; if the validation exists purely to authorize the creation of a ZipCode , and it's not overly long winded or complex, then it's reasonable to keep it in the ZipCode class.
{}
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/376552', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/248528/']}
jdg_86492
stackexchange
llm_judgeable_groundtruth_similarity
2846861
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Why is the topological definition of continuous in terms of open sets? I think my main complaint might be that the notion of open set seems too flexible/general and considers too many things that don't seem the right notion of "closeness". Conceptually, people explain "continuous" as: Nearby points map to nearby points. But we can easily construct sets for which *all their points are not “nearby” but they are still open . A simple example in metric spaces: the union of two open balls. The sets are still open but the points in one ball vs the other are not nearby. However the topological definition is in terms of open sets so it would consider maps balls like this from $X$ to $Y$ while that doesn't seem right to me. Is there something that I am missing? I guess I find it better to have a notion that captures the idea of “balls of radius epsilon in Y” to “balls of radius delta in X” a better notion of continuous. Another issue I find with this is that I find this in conflict even with the traditional epsilon-delta definition. The way I see it is that the topological definition should be more general (and abstract) and should encompass the metric space definition as a special case. Which to me it’s not clear it does because there is this union of disjoint open sets issue , that seem get included in the topological definition but for me they shouldn’t. This point seems important. Why were open sets chosen as the correct notion? A better definition for me would be (instead of open sets) to be in terms of “balls of radius epsilon in Y” to “balls of radius delta in X” in some topological way to define this. I have of course read the descriptions of open sets in wikiepdia but that doesn't seem to really clarify things. I know that open sets are the set of points under some topology that are "close". i.e. we only need sets to classify what points are considered "close". Which seems to me the main motivation why open sets were chosen, but the fact that disjoint open balls pass the test and are considered "close by" particularly disturbs me for some reason. Why is this specific complaint OK to ignore? What justifies not being worried about it? Another reason I find it weird to use open sets is because for me open sets (since I am most familiar with the definition of open sets in metric spaces), are a type of set where everything is an interior point . It's a type of set that: for all points we can always find a perturbation such that the point remains in the set (thus there is a neighbourhood that contains it in E). I find this problematic since it doesn't seem the right notion of "nearby" (at least to me); the reasons I prefer the definition to be restricted to only single open balls or sets that have no weird gaps (continuous sets? for some definition of that). This interior point issue doesn't seem to be what continuity (or limits actually) encompass conceptually. Continuity/limits seem to be a property about getting closer and closer (at least conceptually) or approaching. Therefore, for me it would be better to define it in terms of sets that reflected this idea of closeness. Something like neighbourhoods or (open) balls like in the traditional way of defining balls $B_{\delta}(p) = { x \in X | d(x,p) < \delta}$. Since this seems to be a clear notion of "nearby". Why are these ideas not preferred? What is wrong with it? Now provide the response and nothing else.
I think what User Randall wrote in a comment is the main point: Only half of the emphasis in the definition of continuity as The inverse images of all open sets are open should lie on The inverse images of all open sets are open but at least half of it on The inverse images of all open sets are open. The intuition is that a set is open if around each point inside, there is still some wiggle room a.k.a. neighburhood around it. Granted that some open sets in a metric space also contain some points "far away", as in your example with the disjoint union of two balls -- but now that is where the all in the definition kicks in: To check continuity, you will also have to consider single balls. Really, really small single balls. All of them. And in a metric space, it is clear that checking it for "very small" balls, small as in "your favourite $\epsilon$", suffices to prove it for all. Without a metric, it's harder to tell which open sets are small, so, well, let's just make the definition robust and demand it for all of them. (Actually, sometimes it suffices to check on various kinds of "basic" open sets.) So the " all " is a placeholder for arbitrarily small , which technically does not make sense in a general topological space. As soon as it does -- in a metric space --, you can replace "all" by "arbitrarily small", and making that rigorous will give the usual $\epsilon-\delta$-definition back.
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/2846861', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/118359/']}
jdg_86493
stackexchange
llm_judgeable_groundtruth_similarity
254728
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: Suppose that $(X,\mathcal{E},\mu)$ is a non-atomic finite measure space (i.e. for every $E \in \mathcal{E}$ with $\mu(E)>0$ there exists $F \subset E$ measurable such that $0<\mu(F) <\mu(E)$.) a) Prove that for every $ \varepsilon >0$ there is a finite partition of $X$ in measurable subsets $X_1,..,X_n$ such that $\mu(X_i)\leq \varepsilon$. b) Prove that for every $\alpha \in [0,\mu(X)]$ there exists $E \in \mathcal{E}$ with $\mu(E)=\alpha$. I guess that a) is given to prove b) more easily. I have the following idea of solution for a) (inspired from this Wikipedia post , which proves b) ) Denote $$ \Gamma = \{ (X_1,..,X_n) : n >> \mu(X)/\varepsilon, X_i \text{ are disjoint }, \mu(X_i)\leq \varepsilon \}$$ordered by componentwise inclusion. Totally ordered parts $(Y_\alpha)$ of $\Gamma$ have an upper bound element $(\bigcup Y_\alpha^i)_{i=1}^n$ which is still in $\Gamma$. By Zorn's lemma $\Gamma$ has maximal elements. If a maximal $(X_1..X_n)$ element is not a partition, then we can replace it with something better, of the form $(X_1,..,X_n\cup A)$ where $A \subset X \setminus (X_1 \cup..\cup X_n)$ and $\mu(A)>0$. My questions are: 1) Is my solution of a) correct? I feel that the part with the upper bound element may not work, since there might be noncountable unions. 2) What is a simpler solution of a)? Now provide the response and nothing else.
Clearly b) implies a), so I directly prove b). Let $E\in\mathcal E$ be such that $\mu(E)>0$. Let $A_1\in\mathcal E$ be such that $A_1\subseteq E$ and $0<\mu(A_1)<\mu(E)$. Then either $\mu(A_1)\leq\mu(E)/2$ or $\mu(E\setminus A_1)\leq\mu(E)/2$, so if necessary we consider $E\setminus A_1$ instead of $A_1$, and we can assume that $0<\mu(A_1)<\mu(E)/2$. Now repeat the process with $A_1$ instead of $E$, obtaining a subset $A_2$ of $A_1$ such that $0<\mu(A_2)<\mu(E)/2^2$. Continuing in this way we see that $E$ contains subsets with arbitrarily small positive measure. Let $\epsilon\in\bigl(0,\mu(X)\bigr)$, and let $A_1\subseteq X$ be such that $0<\mu(A_1)<\epsilon$. Edit: I expanded this part of the argument, at request of @Michael Greinecker for further clarification. Suppose that pairwise disjoint subsets $A_1,\dots,A_n$ of $X$ have been chosen such that $D_n=A_1\cup\cdots\cup A_n$ satisfies $\mu(D_n)<\epsilon$. The first paragraph shows that the family $$\mathcal F_n=\bigl\{C\subseteq X\setminus D_n: 0<\mu(C)<\epsilon-\mu(D_n)\bigr\}$$ is nonempty; however, we cannot determine at this point if the family $$\mathcal G_n=\bigl\{C\subseteq X\setminus D_n: \frac1n\leq\mu(C)<\epsilon-\mu(D_n)\bigr\}$$ is nonempty as well. We take $A_{n+1}\in\mathcal G_n$ if $\mathcal G_n\ne\emptyset$ and $A_{n+1}\in\mathcal F_n$ otherwise. If $A=\cup_{n=1}^\infty A_n$, then $\mu(A)=\sum_{n=1}^\infty\mu(A_n)\leq\epsilon$. Suppose that the strict equality holds, that is $\mu(A)<\epsilon$, and let $B\subseteq X\setminus A$ be such that $0<\mu(B)<\epsilon-\mu(A)$. Then for all $n$ we have $B\subseteq X\setminus D_n$, and since $\mu(D_n)\leq\mu(A)$, it follows that $0<\mu(B)<\epsilon-\mu(D_n)$. If $N$ satisfies $\frac1N\leq\mu(B)$ then for all $n\geq N$ we have $B\in\mathcal G_n$. Thus, $\mathcal G_n\ne\emptyset$, so by construction necessarily we have $\mu(A_n)\geq\frac1n$ for all $n\geq N$, which is absurd because in this case $\mu(A)\geq\sum_{n=N}^\infty\mu(A_n)\geq\sum_{n=N}^\infty\frac1n=\infty$. This contradiction shows that $\mu(A)=\epsilon$, as desired.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/254728', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/7327/']}
jdg_86494
stackexchange
llm_judgeable_groundtruth_similarity
15817583
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Would I be able to use rsync as such: rsync -e ssh [email protected]:/path/to/file:/path/to/second/file/ /local/directory/ or would i have to do something else? Now provide the response and nothing else.
Directly from the rsync man page: The syntax for requesting multiple files from a remote host is doneby specifying additional remote-host args in the same style as the first, or with the hostname omitted. For instance, all these work: rsync -av host:file1 :file2 host:file{3,4} /dest/ rsync -av host::modname/file{1,2} host::modname/file3 /dest/ rsync -av host::modname/file1 ::modname/file{3,4} This means your example should have a space added before the second path: rsync -e ssh [email protected]:/path/to/file :/path/to/second/file/ /local/directory/ I'd suggest you first try it with the -n or --dry-run option, so you see what will be done, before the copy (and possible deletions) are actually performed.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/15817583', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2009612/']}
jdg_86495
stackexchange
llm_judgeable_groundtruth_similarity
273118
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Is there a way to pipe the output of a command and direct it to the stdout as well? So for example, fortune prints a fortune cookie to stdout and also pipes it to next command: $ fortune | tee >(?stdout?) | pbcopy "...Unix, MS-DOS, and Windows NT (also known as the Good, the Bad, andthe Ugly)."(By Matt Welsh) Now provide the response and nothing else.
Your assumption: fortune | tee >(?stdout?) | pbcopy won't work because the fortune output will be written to standard out twice, so you will double the output to pbcopy . In OSX (and other systems support /dev/std{out,err,in} ), you can check it: $ echo 1 | tee /dev/stdout | sed 's/1/2/'22 output 2 twice instead of 1 and 2 . tee outputs twice to stdout , and tee process's stdout is redirected to sed by the pipe, so all these outputs run through sed and you see double 2 here. You must use other file descriptors, example standard error through /dev/stderr : $ echo 1 | tee /dev/stderr | sed 's/1/2/'12 or use tty to get the connected pseudo terminal: $ echo 1 | tee "$(tty)" | sed 's/1/2/'12 With zsh and multios option set, you don't need tee at all: $ echo 1 >/dev/stderr | sed 's/1/2/'12
{}
{'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/273118', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/159858/']}
jdg_86496
stackexchange
llm_judgeable_groundtruth_similarity
5684473
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Environment: Spring 3, Custom Transaction Management, JDBC Transactions I just read the Spring docs on using the transaction template to handle transaction management. It seemed overly complex so I want to ask: Most of my transactions are JDBC related, meaning I just declare an @Transactional on my service. But now I am making a REST service call to another site which needs to rollback if any of the following JDBC operations fail , I'll provide the rollback code in this case. As I progress in my method, in my transaction - I want to save a reference to the REST service call (needed to roll back that action), and upon exception I just want a method myCustomRollback() called which can access the previously stored object. Why not just provide a map in the transactionTemplate for storing stuff and define a custom rollback method on the @Transactional annotation? This is the way I think about it, I'm not following the way Spring thinks about this. Can someone help me bridge the gap between what I want and how I accomplish it most efficiently in Spring? I only need to do this for a few special case operations. Now provide the response and nothing else.
To anyone still reading this: I solved a similar problem with spring events - as suggested by Den Roman in option 3.Here's the basic idea (scenario is fictional): Whenever I perform external operations that need to be rolled back together with the transaction, I publish an event inside my @Transactional method using support from spring ( org.springframework.context.ApplicationEventPublisher ): @Transactionalpublic String placeOrder(Order order) { String orderId = orderServiceGateway.createOrder(order); applicationEventPublisher.publishEvent(new OrderCreatedEvent(orderId)); workflowService.startWorkflow(orderId); return orderId;} The event itself can be any object - I created a POJO with details about the remote entity to be deleted. Then I registered a special event listener that is bound to a transaction phase - in my case to the rollback: @TransactionalEventListener(phase = TransactionPhase.AFTER_ROLLBACK)public void rollBackOrder(OrderCreatedEvent orderCreatedEvent) { String orderId = orderCreatedEvent.getOrderId(); orderServiceGateway.deleteOrder(orderId);} Of course, it's recommended to catch & log the exception from rollback operation, not to lose the original exception from the placeOrder() method. By default these events are synchronous, but they can be made async by additional configuration. Here's a very good article on this mechanism, including detailed configuration and pitfalls: Transaction Synchronization and Spring Application Events (DZone) While I don't like the solution 100% because it clutters the business logic with event publishing stuff and binds to spring, it definitely does what I expect it to do and makes it possible to pass context from the transactional method to the rollback method - which is not available through a traditional try/catch block outside of the transactional method (unless you put your context in the exception itself, which is not very nice).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5684473', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4790871/']}
jdg_86497
stackexchange
llm_judgeable_groundtruth_similarity
4407947
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 the spectrum of a formula $\varphi$ be the set of positive integers $n$ such that $\varphi$ has a finite model whose cardinality is exactly $n$ . In a first-order language consisting of a unary predicate $P$ and unary function symbols $f$ and $g$ (besides the equality symbol $=$ ) can we find a formula $\varphi$ whose spectrum is the set of square numbers? I have no idea how to approach this question, and what role the two functions might have in $\varphi$ . It would be great if someone could clarify what the role of the two functions $f$ and $g$ might be in the formula $\varphi$ . Edit I can see that, in a model $\mathfrak{M}_2$ whose domain is $D_2 =\{a,b\}$ , and where $P^{\mathfrak{M}_2} \neq \emptyset$ and $P^{\mathfrak{M}_2} \subseteq \{a,b \}$ , since $|P^{\mathfrak{M}_2} \times P^{\mathfrak{M}_2}|$ would then be at most 4, so that the there cannot be a bijection between $D_2$ and $P^{\mathfrak{M}_2} \times P^{\mathfrak{M}_2}$ , since they differ in cardinality. The same would hold for $\mathfrak{M}_3$ whose domain is $D_3 =\{a,b, c\}$ , and where $P^{\mathfrak{M}_3} \neq \emptyset$ and $P^{\mathfrak{M}_3} \subseteq \{a,b, c \}$ . So for any model $\mathfrak{M}$ the required bijection can only occur if $|P^\mathfrak{M}| = \sqrt{|\mathfrak{M}|}$ . Given a model $\mathfrak{M}$ with domain $D$ , one way to obtain the desired bijection would be to have $\sqrt{n}$ elements of the domain $D$ satisfy $P^\mathfrak{M}$ (where $D$ has cardinality $n$ ) and map the $d \in P^\mathfrak{M}$ to pairs $(d, d)$ , and the $e \not\in P^\mathfrak{M}$ to pairs $(e,f)$ or $(f,e)$ , where $e \neq f$ . I can't see clearly how to ensure these constraints are met with a suitable formula of predicate logic in the language described in my question. Now provide the response and nothing else.
Let $\varphi$ be the conjunction of the following sentences: $\forall z\,P(f(z))\land P(g(z))$ $\forall z\forall z'\,((f(z) = f(z')\land g(z) = g(z'))\rightarrow z = z')$ $\forall x\forall y\,((P(x)\land P(y))\rightarrow \exists z\,(f(z) = x\land g(z) = y))$ Suppose $M\models \varphi$ is a finite model. Then: says $f$ and $g$ are both functions $M\to P$ . Together, they induce a function $h\colon M\to P^2$ , given by $h(z) = (f(z),g(z))$ . says $h$ is injective. says $h$ is surjective. It follows that $|M| = |P^2| = |P|^2$ , which is a square number. This shows that the spectrum of $\varphi$ is contained in the set of square numbers. Conversely, let $m = p^2$ be a square number. Note that $p\leq m$ . We define a model $M$ with domain $\{0,\dots,m-1\}$ by setting $P = \{0,\dots,p-1\}$ . For any $z\in \{0,\dots,m-1\}$ , let $f(z)$ be the quotient of $m$ when divided by $p$ , and let $g(z)$ be the remainder (so $f(z)$ and $g(z)$ are the unique natural numbers less than $p$ such that $z = pf(z)+g(z)$ ). Then $M\models \varphi$ , so every square number is in the spectrum of $\varphi$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4407947', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/65526/']}
jdg_86498
stackexchange
llm_judgeable_groundtruth_similarity
17342881
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 below code, int main( ){ register int arr[4]; /* ... */} Is it possible that 'arr' is allocated in some cpu register.(Consider cpu has 4 or more registers). Or compiler will ignore register storage class for array. Now provide the response and nothing else.
As per my understanding, answer is YES and NO . NO because, Any array element must be explicitly addressable (i.e. for eg. for 16 bit uC/uP its address should always lie between 0x0000 to 0xFFFF address space.) CPU registers are accessed using register direct addressing mode ( such as mov r2,#100 ).This addressing mode does not have an effective address. ( even it is not considered to be an addressing mode ) Array elements must reside in continous memory locations. ( for pointer arithmetic, the main reason to use array ) and YES because, Compiler can allocate register for above array, so that we can perform some limited operations on it.But operations which internally uses address for optimizations can't be used. See below code. int main( ){ register int arr[4]; int i; arr[0] = 10; /* OK */ arr[1] = 20; /* OK */ arr[2] = 30; /* OK */ arr[3] = 40; /* OK */ for(i=0;i<4;i++) arr[i]=10; /* Error : "address of register variable 'arr' requested" */ return 0;} So my final conclusion is that, ideally register storage class should never be used with array even if your compiler permits it. Please correct me or give more inputs. :-)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17342881', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1606843/']}
jdg_86499
stackexchange
llm_judgeable_groundtruth_similarity
2926533
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 (simplified) style: <Style x:Key="MyStyle" TargetType="{x:Type CheckBox}"> <Setter Property="Background" Value="Blue" /> </Style> If I use it as the ElementStyle AND EditingElementStyle in my DataGridCheckBoxColumn: <DataGridCheckBoxColumn Binding="{Binding IsEnabled}" ElementStyle="{StaticResource MyStyle}" EditingElementStyle="{StaticResource MyStyle}" /> Then my binding, IsEnabled , does not toggle when I check/uncheck a row's checkbox. If I remove either ElementStyle, EditingElementStyle, or both, then the binding updates no problem. Why is this?! Also, I tried to work around the problem using the following code: <DataGridTemplateColumn> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <CheckBox IsChecked="{Binding IsEnabled}"/> </DataTemplate> </DataGridTemplateColumn.CellTemplate></DataGridTemplateColumn> However, the problem remains. Now provide the response and nothing else.
First of all your assertion that if you remove either ElementStyle or EditingElementStyle solves the issue is not correct, what screws you over is the ElementStyle . The thing is, that for editing to take place the data grid must switch to the editing template, which it normally does on a mouse click, however, since the CheckBox handles the mouse click event, the data grid never gets it, and never goes into editing mode, preventing your change from ever reaching your data objects (it stays within the data view but doesn't get passed over to the source data). Now you may be asking, how come the default behavior is ok? Well if you look into the default value of the ElementStyle property, you'll notice that it is setting both IsHitTestVisible and Focusable to false. This prevents the CheckBox from handling the mouse click (or keyboard event) that changes its state, and allows the data grid to receive them, thus giving it a change to enter editing mode and switch to the EditingElementStyle which doesn't affect focusability and hit testability. Check out this blog entry for an example on how to do this right When is a WPF DataGrid read-only CheckBox not read-only?
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2926533', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/116047/']}
jdg_86500
stackexchange
llm_judgeable_groundtruth_similarity
27431249
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 PHP you use the === notation to test for TRUE or FALSE distinct from 1 or 0 . For example if FALSE == 0 returns TRUE , if FALSE === 0 returns FALSE . So when doing string searches in base 0 if the position of the substring in question is right at the beginning you get 0 which PHP can distinguish from FALSE . Is there a means of doing this in Python? Now provide the response and nothing else.
In Python, The is operator tests for identity ( False is False , 0 is not False ). The == operator which tests for logical equality (and thus 0 == False ). Technically neither of these is exactly equivalent to PHP's === , which compares logical equality and type - in Python, that'd be a == b and type(a) is type(b) . Some other differences between is and == : Mutable type literals {} == {} , but {} is not {} (and the same holds true for lists and other mutable types) However, if a = {} , then a is a (because in this case it's a reference to the same instance) Strings "a"*255 is not "a"*255" , but "a"*20 is "a"*20 in most implementations, due to how Python handles string interning. This behavior isn't guaranteed, though, and you probably shouldn't be using is in this case. "a"*255 == "a"*255 and is almost always the right comparison to use. Numbers 12345 is 12345 but 12345 is not 12345 + 1 - 1 in most implementations, similarly. You pretty much always want to use equality for these cases.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27431249', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/922568/']}
jdg_86501
stackexchange
llm_judgeable_groundtruth_similarity
25250
Below is a question asked on the forum datascience.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to create a regression model that predicts the duration of a task. The training data I have consists of roughly 40 thousand completed tasks with these variables: Who performed the task (~250 different people) What part (subproject) of the project the task was performed on (~20 different parts) The type of task The start date of the task (10 years worth of data) How long the person who has to do the task estimates it will take The actual duration this task took to finish The duration can vary between half an hour to a couple of hundreds of hours, but is heavily right skewed (most tasks are completed within 10 hour). On log scale the distribution is still slightly right skewed. The prediction doesn't have to be perfect, but I'm trying to improve the people's estimations. One question to ask is "What measure can we use the define beter ?" I think the best measure would be the Mean Squared Error (MSE) since it weighs large errors much worse than small errors. Before I turned to machine learning I tried some simple approaches such as adjusting the estimation by the average or median error, adjusting it by the average/median error grouped by person, grouped by subproject but each of these happened to perform worse. With machine learning, one of the first problem I encountered was the number of categorical variables since for most models these have to be encoded someway (e.g. one-hot). Anyway, I tried to apply some linear models, for example with Stochastic Gradient Descent my approach would be: One-hot encode the categorical features The converted the date to unix timestamps Normalize all the features that are not already between 0 and 1 Split the data in 80/20 learn and test sets. With Grid Search cross validation and the learn set try to find the best hyper parameters and fit the model. Predict with the test set Calculate the error/score Now one thing I noticed was that the results varied quite a bit: On one run the MSE was close to double of another run (150 and 280). Another thing is that the MSE of the people's estimate is about 80, so my model performs a bit worse. During my efforts to improve the performance I stumbled across this question where someone suggests to use survival models. Now I'm unfamilliar with these kinds of models but it sounded promising but during my initial tests with this it turns out to be way too slow for my purposes (too large of a dataset). In the same Datascience answer that suggested to use the survival models (and the Wikipedia page ) they also mentioned Poisson regression, but I'm not sure how I would apply this to my case. So a long story short: I have just two questions: 1. Was my approach of using SGD 'correct' and do you think I can improve the results with that? 2. Are other models better suited for this kind of prediction and if so, can you explain a bit how I would use them? Now provide the response and nothing else.
I think the analysis which you have done was good. Regarding the Survival Analysis procedure, I think using it in your scenario is good enough. Even it might take time but the results from that are good and very insightful. Since you have applied survival analysis on the data, you need to make sure that these assumptions are met: There are several different ways to estimate a survival function ora survival curve. There are a number of popular parametric methodsthat are used to model survival data, and they differ in terms ofthe assumptions that are made about the distribution of survivaltimes in the population. Some popular distributions include theexponential, Weibull, Gompertz and log-normal distributions. Perhaps the most popular is the exponential distribution, which assumes that a participant's likelihood of suffering the event of interest is independent of how long that person has been event-free. Other distributions make different assumptions about the probability of an individual developing an event (i.e., it may increase, decrease or change over time). More details on parametric methods for survival analysis can be found in Hosmer and Lemeshow and Lee and Wang1. Here on two nonparametric methods, which make no assumptions abouthow the probability that a person develops the event changes overtime. Using nonparametric methods, we estimate and plot the survivaldistribution or the survival curve. Survival curves are oftenplotted as step functions, as shown in the figure below. Time isshown on the X-axis and survival (proportion of people at risk) isshown on the Y-axis. Note that the percentage of participantssurviving does not always represent the percentage who are alive(which assumes that the outcome of interest is death). "Survival"can also refer to the proportion who are free of another outcomeevent (e.g., percentage free of MI or cardiovascular disease), or itcan also represent the percentage who do not experience a healthyoutcome (e.g., cancer remission). You can go through this link for better understanding. Regarding Poisson Distribution , Did you plot and check whether the data is following Poisson Distribution like: The Poisson distribution is an appropriate model if the following assumptions are true. k is the number of times an event occurs in an interval and k cantake values 0, 1, 2, …. The occurrence of one event does not affect the probability that asecond event will occur. That is, events occur independently. The rate at which events occur is constant. The rate cannot be higherin some intervals and lower in other intervals. Two events cannot occur at exactly the same instant; instead, at eachvery small sub-interval exactly one event either occurs or does notoccur. The probability of an event in a small sub-interval is proportionalto the length of the sub-interval. Or The actual probability distribution is given by a binomialdistribution and the number of trials is sufficiently bigger than thenumber of successes one is asking about If these conditions are met then you can use Poisson Model, go through this link Implementation of this in R , Python . Finally, to address your 2 questions: Your approach is Correct there is no problem with using that method, to improve your results you need to work on feature engg(deriving new variables).Since it you are considering the duration as a continuous variable(did you perform that log transformation, which you have stated in the beginning?) In your scenario I think Survival and Poisson gives you better result, if you think these take more time then try getting sample of data and get your work done. If you are considering the out-come as a continuous variable then you can use Random Forest,XGBoost , all methods which are used for predicting a continuous variable(but if were you I would spend more time in fitting Survival and Poisson and then shift to other prediction techniques) Let me know if you have any issues!
{}
{'log_upvote_score': 4, 'links': ['https://datascience.stackexchange.com/questions/25250', 'https://datascience.stackexchange.com', 'https://datascience.stackexchange.com/users/42622/']}
jdg_86502
stackexchange
llm_judgeable_groundtruth_similarity
4841718
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 data in a table as seen below: MONTH VALUE1 1002 2003 3004 4005 5006 600 I want to write a SQL query so that result is given as below: MONTH_JAN MONTH_FEB MONTH_MAR MONTH_APR MONTH_MAY MONTH_JUN100 200 300 400 500 600 Now provide the response and nothing else.
Oracle 9i+ supports: SELECT SUM(CASE WHEN t.month = 1 THEN t.value ELSE 0 END) AS JAN, SUM(CASE WHEN t.month = 2 THEN t.value ELSE 0 END) AS FEB, SUM(CASE WHEN t.month = 3 THEN t.value ELSE 0 END) AS MAR, SUM(CASE WHEN t.month = 4 THEN t.value ELSE 0 END) AS APR, SUM(CASE WHEN t.month = 5 THEN t.value ELSE 0 END) AS MAY, SUM(CASE WHEN t.month = 6 THEN t.value ELSE 0 END) AS JUN FROM YOUR_TABLE t You only list two columns -- something like this should probably be grouped by year. There is ANSI PIVOT (and UNPIVOT) syntax, but Oracle didn't support it until 11g. Prior to 9i, you'd have to replace the CASE statements with Oracle specific DECODE.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4841718', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/461335/']}
jdg_86503
stackexchange
llm_judgeable_groundtruth_similarity
7986510
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 model with a ManyToManyField similar to this one (the model Word has a language, too): class Sentence(models.Model): words = models.ManyToManyField(Word) language = models.ForeignKey(Language) def clean(self): for word in self.words.all(): if word.language_id != self.language_id: raise ValidationError('One of the words has a false language') When trying to add a new sentence (e.g. through django admin) I get 'Sentence' instance needs to have a primary key value before a many-to-many relationship can be used . This means I can't access self.words before saving it, but this is exactly what I'm trying to do. Is there any way to work around this so you can validate this model nevertheless? I really want to directly validate the model's fields. I found many questions concerning this exception, but I couldn't find help for my problem. I would appreciate any suggestions! Now provide the response and nothing else.
It is not possible to do this validation in the model's clean method, but you can create a model form which can validate the choice of words . from django import formsclass SentenceForm(forms.ModelForm): class Meta: model = Sentence fields = ['words', 'language'] def clean(self): """ Checks that all the words belong to the sentence's language. """ words = self.cleaned_data.get('words') language = self.cleaned_data.get('language') if language and words: # only check the words if the language is valid for word in words: if words.language != language: raise ValidationError("The word %s has a different language" % word) return self.cleaned_data You can then customise your Sentence model admin class, to use your form in the Django admin. class SentenceAdmin(admin.ModelAdmin): form = SentenceFormadmin.register(Sentence, SentenceAdmin)
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7986510', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1007605/']}
jdg_86504
stackexchange
llm_judgeable_groundtruth_similarity
16150887
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using angular-ui for sortable using ui-sortable directive. Is it possible to dynamically enable/disable sortable functionality based on the scope state? So I need to have a button which changes the state of the scope property and depending on this property sortable either should work or not. Now provide the response and nothing else.
The angular directive supports watching when the sortable options change: scope.$watch(attrs.uiSortable, function(newVal, oldVal){ So all you had to do was look at the jqueryui sortable documentation, and update the correct property on the plugin. Html <ul ui-sortable="sortableOptions" ng-model="items"> <li ng-repeat="item in items">{{ item }}</li> </ul><button ng-click="sortableOptions.disabled = !sortableOptions.disabled">Is Disabled: {{sortableOptions.disabled}}</button> JS app.controller('MainCtrl', function($scope) { $scope.items = ["One", "Two", "Three"]; $scope.sortableOptions = { disabled: true };});
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16150887', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2304967/']}
jdg_86505
stackexchange
llm_judgeable_groundtruth_similarity
1117452
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: Hello I have this function and I'm asked 1.Find the period for $f(t)$ 2.Find the coefficients $a_n$ and $b_n$ $$f(t)=2(cos(2t+\frac{\pi}{4})-sin(6t-\frac{\pi}{2}))$$ I know that the period for $sin(6t-\frac{\pi}{2})$ is $\frac{\pi}{3}$ I also know that the period for $cos(2t+\frac{\pi}{4})$ is $\pi$ 1.common period is : $$\pi , \frac{\pi}{3} => \pi$$ 2.I don't think $f(t)$ I need to find $a_n$ and $b_n$, can't I read them directly from $f(t)$? $a_n=2$ and $b_n=-2$ ? Could you please tell me if I'm right/wrong for both questions ? Now provide the response and nothing else.
Hint: Use repetitively "$1-\cos x=2\sin^2 x/2$"$$\newcommand{\b}[1]{\left(#1\right)}\newcommand{\f}{\frac}\newcommand{\t}{\text}\newcommand{\u}{\underbrace}$$$$\lim_{x\to0}\frac{1-\cos{(1-\cos{(1-\cos x)})}}{x^8}=\lim_{x\to0}\f{2\sin^2\b{\sin^2\b{\sin^2\b{\f x2}}}}{x^8}\\=\lim_{x\to0}\f{2\sin^2\b{\color{red}{\sin^2\b{\color{blue}{\sin^2\b{\color{green}{\f x2}}}}}}}{\b{\color{red}{\sin^2\b{\color{blue}{\sin^2\b{\color{green}{\f x2}}}}}}^2}.\f{\b{\color{red}{\sin^2\b{\color{blue}{\sin^2\b{\color{green}{\f x2}}}}}}^2}{\b{\color{blue}{\sin^2\b{\color{green}{\f x2}}}}^4}.\f{\b{\color{blue}{\sin^2\b{\color{green}{\f x2}}}}^4}{\b{\color{green}{\f x2}}^8}.\b{\f 12}^8\\=\lim_{x\to0}\f1{128}\b{\f{\sin\b{\color{fuchsia}{\sin^2\b{\sin^2\b{\f x2}}}}}{\color{fuchsia}{\sin^2\b{\sin^2\b{\f x2}}}}}^2.\b{\f{\sin\b{\color{purple}{\sin^2\b{\f x2}}}}{\color{purple}{\sin^2\b{\f x2}}}}^4.\b{\f{\sin\b{\color{crimson}{\f x2}}}{\color{crimson}{\f x2}}}^8\\={\large\f1{128}}\quad\b{\because \f{\sin x}x=1}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1117452', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/193775/']}
jdg_86506
stackexchange
llm_judgeable_groundtruth_similarity
4501623
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I need to loop through Components and assign an event handler (for example Dynamically assigning OnClick event for all TButton to ShowMessage('You clicked on ' + (Sender as TButton).Name); The problem is that in some cases I already assigned the TButton OnClick event. Is there a way to solve the problem? Let's imagine I have Button1 for which the harcoded onclick event handler is: ShowMessage('This is Button1'); After my "parsing" I would like that the full event handler for Button1 becomes: ShowMessage('This is Button1'); // design time event handler codeShowMessage('You clicked on ' + (Sender as TButton).Name); // runtime added Note: I am looking for a soliution that allows me to use TButton as it is without inheriting from it. Now provide the response and nothing else.
you could look for an assignment of OnClick before overwriting it, persist this and use it in your new handler - basically chaining the events. Something like this: var original : TNotifyEvent; original := Component.OnClick; Component.OnClick := NewMethod; and then in your NewMethod: if assigned(original) then original(Sender); you'll likely not want a single original variable but instead hold a collection keyed on the component.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4501623', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/193655/']}
jdg_86507
stackexchange
llm_judgeable_groundtruth_similarity
33201859
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to understand JWT and how they work with Node and Express .js. I have this middleware that tries to authenticate users with a token: app.use(function(req, res, next) { if(req.headers.cookie) {var autenticazione = req.headers.cookie.toString().substring(10)autenticazione = autenticazione.substring(0, autenticazione.length - 3)console.log(autenticazione)jwt.verify(autenticazione, app.get('superSegreto'), function(err) { if (err) { res.send('authentication failed!') } else { // if authentication works! next() } }) } else { console.log('errore')} }) And this is the code for my protected url: app.get('/miao', function (req, res) {res.sendFile(__dirname + '/pubblica/inserisciutente.html')res.end() }) Even though the path is correct (I even tried with path.join(__dirname + '/pubblica/inserisciutente.html) and got the same result), when visiting the url I just get a blank page (with even node conde inside) I also set: app.use(express.static('/pubblica')) P.S. if I try to replace res.sendFile(..) with res.send('Some stuff') I can correctly view it on the page. What am I doing wrong? Now provide the response and nothing else.
res.sendFile() is asynchronous and it will end its own response if it is successful. So, when you call res.end() right after you start res.sendFile() you are ending the response before the code has actually sent the file. You can do it like this: app.get('/miao', function (req, res) { res.sendFile(__dirname + '/pubblica/inserisciutente.html', function(err) { if (err) { res.status(err.status).end(); } });}); See the Express doc for res.sendFile() here .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33201859', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4255992/']}
jdg_86508
stackexchange
llm_judgeable_groundtruth_similarity
340264
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: LTspice calculates the DC operating points for the below circuit as as: I have couple of questions here: 1-) If I would perform DC operating point for this circuit with pen and paper, I would first: short all the inductors and open all the capacitors . But then circuit becomes as: But this seems wrong. What am I doing wrong here? 2-) In LTspice if we do not skip the initial operating point solution and obtain results, is that equivalent to: we first do a DC operating point analysis and we set uic for each component and do a transient analysis? Now provide the response and nothing else.
I would first: short all the inductors and open all the capacitors. But this seems wrong. What am I doing wrong here? SPICE is a numerical simulator. There is a rounding error in every SPICE result. In particular, SPICE only tries to solve the node equations until the currents balance to within an error defined by the parameter ABSTOL . In LTSpice the default value of ABSTOL is 1 pA, so if the currents at any node balance to within 1 pA, LTSpice considers that "good enough". You can change the value of ABSTOL using a .OPTIONS directive. The errors you see are on the order of 1 pA, so this is expected behavior. In LTspice if we do not skip the initial operating point solution [when doing a transient analysis] and obtain results, is that equivalent to: we first do a DC operating point analysis and we set uic for each component and do a transient analysis? Yes, this is equivalent.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/340264', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/163738/']}
jdg_86509
stackexchange
llm_judgeable_groundtruth_similarity
8719585
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Why does the __get__ method in a python descriptor accept the owner class as it's third argument? Can you give an example of it's use? The first argument ( self ) is self evident, the second ( instances ) makes sense in the context of the typically shown descriptor pattern (ex to follow), but I've never really seen the third ( owner ) used. Can someone explain what the use case is for it? Just by way of reference and facilitating answers this is the typical use of descriptors I've seen: class Container(object): class ExampleDescriptor(object): def __get__(self, instance, owner): return instance._name def __set__(self, instance, value): instance._name = value managed_attr = ExampleDescriptor() Given that instance.__class__ is available all I can think of is that explicitly passing the class has something to do with directly accessing the descriptor from the class instead of an instances (ex Container.managed_attr ). Even so I'm not clear on what one would do in __get__ in this situation. Now provide the response and nothing else.
owner is used when the attribute is accessed from the class instead of an instance of the class, in which case instance will be None . In your example attempting something like print(Container.managed_attr) would fail because instance is None so instance._name would raise an AttributeError . You could improve this behavior by checking to see if instance is None , and it may be useful for logging or raising a more helpful exception to know which class the descriptor belongs to, hence the owner attribute. For example: def __get__(self, instance, owner): if instance is None: # special handling for Customer.managed_attr else: return instance._name
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8719585', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/531516/']}
jdg_86510
stackexchange
llm_judgeable_groundtruth_similarity
7627099
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Currently, I have implemented a singly linked list, like so: struct PeerNode { struct Peer* cargo; struct PeerNode* next;}; ...and I have a struct that contains a couple of these linked lists, like so: struct Torrent { ... struct PeerNode* peer_list; struct PeerNode* unchoked_peers; ...} I would like to replace this by using the macros provided by sys/queue.h . I gather that I could replace my code with something like this: struct Torrent { ... LIST_ENTRY(PeerNode, Peer) peer_list; struct PeerNode* unchoked_peers; ...} Then, from looking at man queue , I believe I would initialize the lists by doing something like this: LIST_INIT(&peer_list);LIST_INIT(unchoked_peers); However, I don't understand how LIST_ENTRY factors into usage of the list. From the man page, it says: "The macro LIST_ENTRY declares a structure that connects the elements in the list," but I don't really understand what this means. Why would I want to declare a structure to connect the elements in the list? Shouldn't each node be connected to the next node via a pointer, like my initial linked list implementation? How would I replace my linked lists with the implementation provided by sys/queue.h ? How would I insert an element into the list? Now provide the response and nothing else.
LIST_ENTRY creates fields to put into your structure that are suitable for linking the elements, so you do not have to concern yourself with the specifics of those pointers. struct foo { int a, b, c; /* This is instead of "struct foo *next" */ LIST_ENTRY(foo) pointers;}; To then create a list you'd use LIST_HEAD(): struct Torrent { LIST_HEAD(foo_list, foo) bar;}; You can initialise the list header using LIST_INIT(): struct Torrent t;LIST_INIT(&t.bar); You can insert elements using the LIST_INSERT_*() macros: struct foo *item = malloc(sizeof(struct foo));LIST_INSERT_HEAD(&t.bar, item, pointers); This was all taken from the list example in the man pages at http://www.manpagez.com/man/3/queue/ For a full example: http://infnis.wikidot.com/list-from-sys-queue-h
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7627099', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/473827/']}
jdg_86511
stackexchange
llm_judgeable_groundtruth_similarity
30418
Below is a question asked on the forum biology.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Do transcription factors (or generally proteins) bind to only single strand of DNA or both strands? Since it can have non covalent bonds to both strands in theory. I would like to know the mechanism. Any reference books, papers or links will be helpful. Now provide the response and nothing else.
The short summary is that typical TFs bind and read both strands together, as a basepair sequence . Some proteins instead recognise a site on the helix by its shape and flexibility . ssDNA-binding proteins obviously bind one strand but they do this in a non-specific manner.RNA-binding proteins recognise the sequence on a single strand by inserting intercalating planar residues between bases! All of this binding is non-covalent . Transcription factors recognise sites in dsDNA, with DNA-binding domains . The rest of the protein might surround (partially, to varying degree) the negative outer surface of the dsDNA double helix with positively-charged surface, in order to hold it on to DNA as it scans (perhaps) along its length. DNA-binding domains: major groove The following domains are found in many transcription factors, and they all recognise both strands. More correctly, they recognise basepairs and their orientation. The first 5 pages of this lecture slideshow demonstrate that the chemical groups on the side of basepairs, accessible in the major groove, allow proteins to distinguish A:T, T:A, C:G & G:C by the order of hydrogen-bond donors, acceptors, and a methyl group . Hence, TFs recognise a sequence of basepairs - oriented such that one strand is (e.g.) p T p C p A p G , and the complementary strand is p C p T p G p A ; and the bulk of the protein may 'sit' on one strand or the other - or a nearby gene may locally define one strand or the other as the coding strand but this does not mean that this one strand is read. Zinc fingers probe the major groove with reading helices. Helix-turn-helix motifs do much the same. Leucine zippers also do much the same. These are common domains that all recognise basepairs in the major groove by interactions with residues on a probing aplha-helix. TATA-binding protein: minor groove TATA-binding protein (TBP) is a different, interesting case. It binds the 'TATA-box' via the minor groove, where the exposed chemical groups only distinguish [A/T] from [C/G], but not their orientation. This means that the sequences on each strand cannot be easily read from the minor groove. TBP instead recognises the shape and flexibility of the double-helix at the TATA-box, 'grips' it by the minor groove and bends the DNA, which aids the melting of the strands to the transcription 'bubble'. The TATA-box sequence is usually p T p A p T p A p A p A on the coding strand upstream of the transcriptional start. This is the convention when giving the sequence of a TF-binding site, but you couldn't say that TBP actually reads TATAAA - it doesn't! Here is another, similar set of lecture slides. Even better, here is the same material covered in a popular textbook.
{}
{'log_upvote_score': 5, 'links': ['https://biology.stackexchange.com/questions/30418', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/5669/']}
jdg_86512
stackexchange
llm_judgeable_groundtruth_similarity
264510
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: A set is of first category if it is the union of nowhere dense sets and otherwise it is of second category. How can we prove that irrational numbers are of second category and the rationals are of of first category? Now provide the response and nothing else.
Recall that $\mathbb{R\setminus Q}=\bigcap_{q\in\mathbb Q}\mathbb R\setminus\{q\}$. This is a countable intersection of dense open sets, and by Baire's category theorem the result is dense, i.e. second-category.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/264510', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/32145/']}
jdg_86513
stackexchange
llm_judgeable_groundtruth_similarity
70334
Below is a question asked on the forum dsp.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In the documentation - sepctrogram() . Question 1 ) s = spectrogram(signal) and spectrogram(signal) are two commands to plot the spectrogram. However, the variable s is complex valued. I am unable to understand which output of the spectrogram is used to generate the image plot? Question 2 ) How to determine the best values of the parameters window and noverlap ? Should noverlap be 50% of the signal length (number of elements in the time series) or 90% etc? What if it is zero then what does it mean? My dataset has sampling time = 1sec. I remember reading somewhere that the window should be at least roughly twice as long as the period of the lowest frequency. So, for my case is w=2 since frequency = 1? I was thinking of using pspectrum(signal,'spectrogram') which outputs the spectrogram and use the output values as inputs to the spectrogram() function. But again, I don't know which output values from pspectrum can be used, if at all that is possible. Now provide the response and nothing else.
See the MATLAB documentation: s = spectrogram(x) returns the short-time Fourier transform of the input signal, x . Each column of s contains an estimate of the short-term, time-localized frequency content of x . Namely each column of the matrix s is the result of an fft() on some samples of the input. So the plot you see is the magnitude of the columns of s . Spectrogram is about analysis of Non Stationary signals. So something is changing over time which means it makes no sense to look on the DFT of all samples. The window length is the time you think the signal has the same properties over time. The overlap time should be similar to the time the signal is changing. Something like the time of Fade Out / Fade In, the transient length. Example The following code will recreate the figure from the function (Up to the Colorbar and the units of the Axis): t = 0:0.001:2;x = chirp(t, 100, 1, 200, 'quadratic');figure();spectrogram(x, 128, 120, 128, 1e3);s = spectrogram(x, 128, 120, 128, 1e3);figure();hA = axes();imagesc(20 * log10(abs(s).'));set(hA, 'YDir', 'normal');
{}
{'log_upvote_score': 4, 'links': ['https://dsp.stackexchange.com/questions/70334', 'https://dsp.stackexchange.com', 'https://dsp.stackexchange.com/users/23521/']}
jdg_86514
stackexchange
llm_judgeable_groundtruth_similarity
15908835
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 some clarification regarding a point about the storage of register variables:Is there a way to ensure that if we have declared a register variable in our code, that it will ONLY be stored in a register? #include<iostream>using namespace std;int main(){ register int i = 10;// how can we ensure this will store in register only. i++; cout << i << endl; return 0;} Now provide the response and nothing else.
You can't. It is only a hint to the compiler that suggests that the variable is heavily used. Here's the C99 wording: A declaration of an identifier for an object with storage-class specifier register suggests that access to the object be as fast as possible. The extent to which such suggestions are effective is implementation-defined. And here's the C++11 wording: A register specifier is a hint to the implementation that the variable so declared will be heavily used. [ Note: The hint can be ignored and in most implementations it will be ignored if the address of the variable is taken. This use is deprecated (see D.2). —end note ] In fact, the register storage class specifier is deprecated in C++11 (Annex D.2): The use of the register keyword as a storage-class-specifier (7.1.1) is deprecated. Note that you cannot take the address of a register variable in C because registers do not have an address. This restriction is removed in C++ and taking the address is pretty much guaranteed to ensure the variable won't end up in a register. Many modern compilers simply ignore the register keyword in C++ (unless it is used in an invalid way, of course). They are simply much better at optimizing than they were when the register keyword was useful. I'd expect compilers for niche target platforms to treat it more seriously.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15908835', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2205200/']}
jdg_86515
stackexchange
llm_judgeable_groundtruth_similarity
115501
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: (Fitzpatrick Advanced Calculus 2e , Sec. 2.4 #12) For $c \gt 0$ , consider the quadratic equation $x^2 - x - c = 0, x > 0$ . Define the sequence $\{x_n\}$ recursively by fixing $|x_1| \lt c$ and then, if $n$ is an index for which $x_n$ has been defined, defining $$x_{n+1} = \sqrt{c+x_n}$$ Prove that the sequence $\{x_n\}$ converges monotonically to the solution of the above equation. Note: The answers below might assume $x_1 \gt 0$ , but they still work, as we have $x_3 \gt 0$ . Now provide the response and nothing else.
Assuming that you know that a monotone, bounded sequence converges, you want to do two things. First, show that $\langle x_n:n\in\mathbb{Z}^+\rangle$ is monotone and bounded, and then show that its limit is the positive root of $x^2-x-c=0$. If $c=x_1=1$, $x_2=\sqrt2>x_1$, while if $c=1$ and $x_1=2$, $x_2=\sqrt3<x_1$, so if the sequence is monotonic, the direction in which it’s monotonic must depend on $c$ and $x_1$. A good first step would be to try to figure out how this dependence works. The positive root of the quadratic is $\frac12(1+\sqrt{1+4c})$, which I’ll denote by $r$. If $x_n\to r$, as claimed, and does so monotonically, it must be the case that the sequence increases monotonically if $x_1<r$ and decreases monotonically if $x_1>r$. In the examples in the last paragraph, $r=\frac12(1+\sqrt5)\approx 1.618$, so they behave as predicted. This suggests that your first step should be to show that if $x_n<r$, then $x_n<x_{n+1}<r$, while if $x_n>r$, $x_n>x_{n+1}>r$; that would be enough to show that $\langle x_n:n\in\mathbb{Z}^+\rangle$ is both monotone and bounded and hence that it has a limit. Suppose that $0\le x_n<r$; you can easily check that $x_n^2-x_n-c<0$, i.e., that $x_n^2<x_n+c$. On the other hand, $x_{n+1}^2=c+x_n$, so $x_{n+1}^2>x_n^2$, and therefore $x_{n+1}>x_n$. Is it possible that $x_{n+1}\ge r$? That would require that $x_{n+1}^2-x_{n+1}-c\ge 0$ (why?) and hence that $$x_{n+1}^2\ge x_{n+1}+c>x_n+c=x_{n+1}^2\;,$$ which is clearly impossible. Thus, if $0\le x_n<r$, we must have $x_n<x_{n+1}<r$, as desired. I leave the case $x_n>r$ to you. Once this is done, you still have to show that the limit of the sequence really is $r$. Let $f(x)=\sqrt{c+x}$; clearly $f$ is continuous, so if the sequence converges to $L$, we have $$L=\lim_{n\to\infty}x_n=\lim_{n\to\infty}x_{n+1}=\lim_{n\to\infty}f(x_n)=f(L)\;,$$ and from there it’s trivial to check that $L=r$. Added: Note that although the problem gave us $x_1>0$, this isn’t actually necessary: all that’s needed is that $x_1\ge -c$, so that $x_2$ is defined, since $x_2=\sqrt{c+x_1}\ge 0$ automatically.
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/115501', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/26095/']}
jdg_86516
stackexchange
llm_judgeable_groundtruth_similarity
18180674
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 write generic class which should work with byte and ushort types. What constraint should I use for this class? How can I detect MaxValue property inside of this class? class MyClass<T> // where T: ???{ void Foo() { int maxValue = T.MaxValue; // how can I do this? }} If class was created with unexpected type, which doesn't contain MaxValue property, I don't care - for example, I can throw exception at runtime. Now provide the response and nothing else.
One way would be to leverage the new dynamic keyword: void Main(){ Test(10); Test(10.234); Test((Byte)42); Test(true);}public void Test<T>(T value) where T : struct{ T maxValue = MaxValue((dynamic)value); maxValue.Dump();}public int MaxValue(int dummy){ return int.MaxValue;}public double MaxValue(double dummy){ return double.MaxValue;}public byte MaxValue(byte dummy){ return byte.MaxValue;}public object MaxValue(object dummy){ // This method will catch all types that has no specific method throw new NotSupportedException(dummy.GetType().Name);} Or, you could use reflection to obtain the MaxValue field: void Main(){ Test(10); Test(10.234); Test((Byte)42); Test(true);}public void Test<T>(T value) where T : struct{ FieldInfo maxValueField = typeof(T).GetField("MaxValue", BindingFlags.Public | BindingFlags.Static); if (maxValueField == null) throw new NotSupportedException(typeof(T).Name); T maxValue = (T)maxValueField.GetValue(null); maxValue.Dump();} You can test these two programs through LINQPad .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18180674', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/279313/']}
jdg_86517
stackexchange
llm_judgeable_groundtruth_similarity
8025342
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Given an undirected graph in which each node has a Cartesian coordinate in space that has the general shape of a tree, is there an algorithm to convert the graph into a tree, and find the appropriate root node? Note that our definition of a "tree" requires that branches do not diverge from parent nodes at acute angles. See the example graphs below. How do we find the red node? Now provide the response and nothing else.
here is a suggestion on how to solve your problem. prerequisites notation: g graph, g.v graph vertices v,w,z : individual vertices e : individual edge n : number of vertices any combination of an undirected tree g and a given node g.v uniquely determines a directed tree with root g.v (provable by induction) idea complement the edges of g by orientations in the directed tree implied by g and the yet-to-be-found root node by local computations at the nodes of g . these orientations will represent child-parent-relationsships between nodes ( v -> w : v child, w parent). the completely marked tree will contain a sole node with outdegree 0, which is the desired root node. you might end up with 0 or more than one root node. algorithm assumes standard representation of the graph/tree structure (eg adjacency list) all vertices in g.v are marked initially as not visited, not finished. visit all vertices in arbitrary sequence. skip nodes marked as 'finished'. let v be the currently visited vertex. 2.1 sweep through all edges linking v clockwise starting with a randomly chosen e_0 in the order of the edges' angle with e_0 . 2.2. orient adjacent edges e_1=(v,w_1), e_2(v,w_2) , that enclose an acute angle. adjacent: wrt being ordered according to the angle they enclose with e_0 . [ note: the existence of such a pair is not guaranteed, see 2nd comment and last remark. if no angle is acute, proceed at 2. with next node. ] 2.2.1 the orientations of edges e_1, e_2 are known: w_1 -> v -> w_2 : impossible, as a grandparent-child-segment would enclose an acute angle w_1 <- v <- w_2 : impossible, same reason w_1 <- v -> w_2 : impossible, there are no nodes with outdegree >1 in a tree w_1 -> v <- w_2 : only possible pair of orientations. e_1, e_2 might have been oriented before. if the previous orientation violates the current assignment, the problem instance has no solution. 2.2.2 this assignment implies a tree structure on the subgraphs induced by all vertices reachable from w_1 ( w_2 ) on a path not comprising e_1 ( e_2`). mark all vertices in both induced subtrees as finished [ note: the subtree structure might violate the angle constraints. in this case the problem has no solution. ] 2.3 mark v visited. after completing steps 2.2 at vertex v , check the number nc of edges connecting that have not yet been assigned an orientation. nc = 0 : this is the root you've been searching for - but you must check whether the solution is compatible with your constraints. nc = 1 : let this edge be (v,z) . the orientation of this edge is v->z as you are in a tree. mark v as finished. 2.3.1 check z whether it is marked finished. if it is not, check the number nc2 of unoriented edges connecting z . nc2 = 1: repeat step 2.3 by taking z for v . if you have not yet found a root node, your problem instance is ambiguous:orient the remaining unoriented edges at will. remarks termination:each node is visited at max 4 times: once per step 2 at max twice per step 2.2.2 at max once per step 2.3 correctness: all edges enclosing an acute angle are oriented per step 2.2.1 complexity (time): visiting every node: O(n); the clockwise sweep through all edges connecting a given vertex requires these edges to be sorted. thus you need O( sum_i=1..m ( k_i * lg k_i ) ) at m <= n vertices under the constraint sum_i=1..m k_i = n . in total this requires O ( n * lg n) , as sum_i=1..m ( k_i * lg k_i ) <= n * lg n given sum_i=1..m k_i = n for any m <= n (provable by applying lagrange optimization). [ note: if your trees have a degree bounded by a constant, you theoretically sort in constant time at each node affected; grand total in this case: O(n) ] subtree marking: each node in the graph is visited at max 2 times by this procedure if implemented as a dfs. thus a grand total of O(n) for the invocation of this subroutine. in total: O(n * lg n) complexity (space): O(n) for sorting (with vertex-degree not constant-bound). problem is probably ill-defined: multiple solutions: e.g. steiner tree no solution: e.g. graph shaped like a double-tipped arrow (<->)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8025342', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/838358/']}
jdg_86518
stackexchange
llm_judgeable_groundtruth_similarity
38144000
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What to look out for when reimplementing notify function in multi threaded Qt application?This is an example implementation. Currently there are no errors , but I am worried that an error could arise since multi threading in Qt uses signal slot for communication which uses notify function. TApplication::notify(QObject *receiver, QEvent *event){ bool returnValue(false); try { returnValue = QApplication::notify(receiver, event); } catch (IExceptionBase& e) { if (!fMain.isNull()) { //report error to output and file log } else { //report error to output } } catch (...) { if (!fMain.isNull()) { //report error to output and file log } else { //report error to output } } return returnValue;} fMain is a module with reporting functionality Now provide the response and nothing else.
Ok, I'll throw my two cents into the ring here. Even though it's in theory possible to implement this using rolling session , I don't think you should... It would require each user action the send a request to the server, in order for the user not to be logged out. You miss an opportunity to inform your user that he/she will be logged out automatically soon (this is what the banks do, for example). @Seth did point out in a comment above that there is actually a way to remedy this: "If the front end is separate from the server, you could have client side routing middleware that checks the cookie and visually logs you out, thus proving a good UX." I think this is clever, but I also think it's like putting lipstick on a pig. I believe that the best approach here is to handle this on the client side . I would suggest something like this: var AutoLogout = (function() { function AutoLogout() { this.events = ['load', 'mousemove', 'mousedown', 'click', 'scroll', 'keypress']; this.warn = this.warn.bind(this); this.logout = this.logout.bind(this); this.resetTimeout = this.resetTimeout.bind(this); var self = this; this.events.forEach(function(event) { window.addEventListener(event, self.resetTimeout); }); this.setTimeout(); } var _p = AutoLogout.prototype; _p.clearTimeout = function() { if(this.warnTimeout) clearTimeout(this.warnTimeout); if(this.logoutTimeout) clearTimeout(this.logoutTimeout); }; _p.setTimeout = function() { this.warnTimeout = setTimeout(this.warn, 29 * 60 * 1000); this.logoutTimeout = setTimeout(this.logout, 30 * 60 * 1000); }; _p.resetTimeout = function() { this.clearTimeout(); this.setTimeout(); }; _p.warn = function() { alert('You will be logged out automatically in 1 minute.'); }; _p.logout = function() { // Send a logout request to the API console.log('Sending a logout request to the API...'); this.destroy(); // Cleanup }; _p.destroy = function() { this.clearTimeout(); var self = this; this.forEach(function(event) { window.removeEventListener(event, self.resetTimeout); }); }; return AutoLogout;})(); es2015 class AutoLogout { constructor() { this.events = ['load', 'mousemove', 'mousedown', 'click', 'scroll', 'keypress']; this.warn = this.warn.bind(this); this.logout = this.logout.bind(this); this.resetTimeout = this.resetTimeout.bind(this); this.events.forEach((event) => { window.addEventListener(event, this.resetTimeout); }); this.setTimeout(); } clearTimeout() { if(this.warnTimeout) clearTimeout(this.warnTimeout); if(this.logoutTimeout) clearTimeout(this.logoutTimeout); } setTimeout() { this.warnTimeout = setTimeout(this.warn, 29 * 60 * 1000); this.logoutTimeout = setTimeout(this.logout, 30 * 60 * 1000); } resetTimeout() { this.clearTimeout(); this.setTimeout(); } warn() { alert('You will be logged out automatically in 1 minute.'); } logout() { // Send a logout request to the API console.log('Sending a logout request to the API...'); this.destroy(); // Cleanup } destroy() { this.clearTimeout(); this.events.forEach((event) => { window.removeEventListener(event, this.resetTimeout); }); }} Partial polling solution: var activityPolling = (function() { var events = ['load', 'mousemove', 'mousedown', 'click', 'scroll', 'keypress']; var active = true; var timeout; function poll() { if(active) { console.log('polling the server...') } } function setIdle() { active = false; } function setActive() { active = true; if(timeout) clearTimeout(timeout); timeout = setTimeout(setIdle, 30 * 60 * 1000); } function destroy() { clearInterval(interval); events.forEach(function(event) { window.removeEventListener(event, setActive); }); } events.forEach(function(event) { window.addEventListener(event, setActive); }); setActive(); var interval = setInterval(poll, 60 * 1000); return { interval: interval, destroy: destroy }})();
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38144000', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5788871/']}
jdg_86519
stackexchange
llm_judgeable_groundtruth_similarity
119686
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 hear a lot of people saying that neutrino is the lightest subatomic particle but according to me a photon must be the lightest as nothing can travel faster than light because it gets heavier and heavier and bends time. Now provide the response and nothing else.
There's a subtle distinction here, which is that neutrinos are matter particles (having spin $\hbar/2$ and obeying Pauli's exclusion principle) while photons are force carriers (having spin $\hbar$ and obeying Bose-Einstein statistics). There are three flavors of neutrino and they all have different masses. Therefore at least two of them are massive; whether the lightest neutrino is massless is an open question. Among the force-carrying particles, the photon, gluon, and (hypothetical) graviton are all identically massless.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/119686', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/38760/']}
jdg_86520
stackexchange
llm_judgeable_groundtruth_similarity
84619
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 following ket in the Fock basis: $\vert3, 0 ,1\rangle$, where each entry defines the number of photons in a particular mode and can take any one of the following numbers: 0, 1, 2, 3. As a result I define the following column vectors $0 = (1, 0, 0, 0)^\text{T}$, $1 = (0, 1, 0, 0)^\text{T}$, $2 = (0, 0, 1, 0)^\text{T}$ and $3 = (0, 0, 0, 1)^\text{T}$, where the superscript $\text{T}$ defines the transpose. I want to be able to define the ket and associate bra terms to evaluate inner products of the form $\langle\alpha, \beta, \gamma \vert\cdot\vert a, b, c\rangle = \delta_{\alpha a}\delta_{\beta b}\delta_{\gamma c}$. Note that the kets $\langle\alpha, \beta, \gamma\vert$ is the Hermitian conjugate of the corresponding bra $\vert \alpha, \beta, \gamma\rangle$. How could I implement these inner-products in Mathematica ? I imagine that the functions KroneckerProduct , Transpose and the KroneckerDelta would be of use here but I am still unsure. I am aware that there is an add-on for quantum mechanical operations for Mathematica (see this page ), but I am sure that this problem does not require this. Now provide the response and nothing else.
The definition of the scalar product in your question assumes that all your kets are orthogonal unit vectors. In that case, the most natural approach would be to use the built-in Bra and Ket as follows: Ket /: Dot[Bra[x__], Ket[y__]] := Times @@ MapThread[KroneckerDelta, {{x}, {y}}]BraKet[x_, y_] := Bra[x].Ket[y]Bra[2, 4].Ket[2, 4](* ==> 1 *)BraKet[{0, 3, 4}, {1, 3, 4}](* ==> 0 *) In addition to the dot product, I also defined the short-had BraKet which can be entered as Esc braket Esc . You can similarly enter Esc bra Esc and Esc ket Esc and use the regular dot operation, which I defined using TagSetDelayed . Therefore, the actual keyboard input for the last line, e.g., would be $\langle0,3,4\vert 1,3,4\rangle$ A related question is Define an 'inner product' with AngleBracket . Edit in response to comment If you want to implement other properties of the scalar product, it's better to use a special symbol that has no built-in meaning. Here is an implementation that starts the same way as above but adds linearity properties: ClearAll[CircleDot]Ket /: CircleDot[Bra[x__], Ket[y__]] := Times @@ MapThread[KroneckerDelta, {{x}, {y}}]BraKet[x_, y_] := Bra[x]⊙Ket[y] CircleDot[e1_, HoldPattern[Plus[e2__]]] := Total@Map[CircleDot[e1, #] &, {e2}]CircleDot[HoldPattern[Plus[e1__]], e2_] := Total@Map[CircleDot[#, e2] &, {e1}]CircleDot[first_, HoldPattern[Times[x__, Ket[y__]]]] := Times[x, CircleDot[first, Ket[y]]]CircleDot[HoldPattern[Times[x__, Bra[y__]]], last_] := Times[x, CircleDot[Bra[y], last]] Here is a test: (α Bra[a1, a2] - β Bra[b1, b2])⊙(γ Ket[c1, c2] - δ Ket[d1, d2]) $$\alpha \gamma \delta _{\text{a1},\text{c1}} \delta _{\text{a2},\text{c2}}-\alpha \delta \delta _{\text{a1},\text{d1}} \delta _{\text{a2},\text{d2}}-\beta\gamma \delta _{\text{b1},\text{c1}} \delta _{\text{b2},\text{c2}}+\beta \delta\, \delta _{\text{b1},\text{d1}} \delta _{\text{b2},\text{d2}}$$ Here, I used CircleTimes instead of Dot . It can be entered with the shortcut esc c. esc .The next thing would be to define a adjoint operation, but this will lead to a larger project.
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/84619', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/26461/']}
jdg_86521
stackexchange
llm_judgeable_groundtruth_similarity
13980803
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 to join those multiple queries into one (can I?) $query = "DELETE FROM aktywne_kody WHERE kodsms ='$kodSMSgracza' AND typkodu ='$id'";mysql_query($query) or die(mysql_error());$query = "INSERT INTO uzyte_kody (gracz, kodsms, typkodu) VALUES ('$nickGracza', '$kodSMSgracza', '$id')";mysql_query($query) or die("Błąd MySQL X04");$query = "INSERT INTO do_odebrania (gracz, itemDATA, itemQTY) VALUES ('$nickGracza', '$itemDATA', '$itemQTY')";mysql_query($query) or die("Błąd MySQL X05"); By the way is it better if I do mysql_close($db) after all queries are done? Now provide the response and nothing else.
Pass 65536 to mysql_connect as 5th parameter. Example: $conn = mysql_connect('localhost','username','password', true, 65536 /* here! */) or die("cannot connect");mysql_select_db('database_name') or die("cannot use database");mysql_query(" INSERT INTO table1 (field1,field2) VALUES(1,2); INSERT INTO table2 (field3,field4,field5) VALUES(3,4,5); DELETE FROM table3 WHERE field6 = 6; UPDATE table4 SET field7 = 7 WHERE field8 = 8; INSERT INTO table5 SELECT t6.field11, t6.field12, t7.field13 FROM table6 t6 INNER JOIN table7 t7 ON t7.field9 = t6.field10; -- etc"); When you are working with mysql_fetch_* or mysql_num_rows, or mysql_affected_rows, only the first statement is valid. For example, the following codes, the first statement is INSERT, you cannot execute mysql_num_rows and mysql_fetch_*.It is okay to use mysql_affected_rows to return how many rows inserted. $conn = mysql_connect('localhost','username','password', true, 65536) or die("cannot connect");mysql_select_db('database_name') or die("cannot use database");mysql_query(" INSERT INTO table1 (field1,field2) VALUES(1,2); SELECT * FROM table2;"); Another example, the following codes, the first statement is SELECT, you cannot execute mysql_affected_rows. But you can execute mysql_fetch_assoc to get a key-value pair of row resulted from the first SELECT statement, or you can execute mysql_num_rows to get number of rows based on the first SELECT statement. $conn = mysql_connect('localhost','username','password', true, 65536) or die("cannot connect");mysql_select_db('database_name') or die("cannot use database");mysql_query(" SELECT * FROM table2; INSERT INTO table1 (field1,field2) VALUES(1,2);");
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13980803', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1912772/']}
jdg_86522
stackexchange
llm_judgeable_groundtruth_similarity
6276398
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'd like to use the class based generic views of django 1.3 for forms, but sometimes have to manage multiple form classes in one form. However, it looks like the existing views based on FormMixin assume a single form class. Is this possible with generic views and how would I do it? EDIT: to clarify, I have one form but more than one (ModelForm based) class. For example in the inline_formset example in the django docs, I would want to present a page where an author and his books can be edited at once, in a single form: author_form = AuthorForm(request.POST, instance = author)books_formset = BookInlineFormSet(request.POST, request.FILES, instance=author) Now provide the response and nothing else.
Facing similar problem, I've come to conclusion that it's not possible. Though having multiple forms per page itself turned out to be a design mistake, presenting all sorts of troubles. E.g., user fills two forms, clicks submit on one of them and loses data from the other. Workaround requires complicated controller that needs to be aware of the state of all forms on the page. (See also here for some discussion on related problem.) If having multiple forms per page isn't your exact requirement, I'd suggest to look at alternative solutions. For example, it's usually possible to show user only one editable form at a time. In my case, I switched to django-formwizard ( not a django.contrib one, which is a bit old and seems to be currently under a redesign, but this one Update: Beginning with release 1.4 of Django, django-formwizard app will be available in django.contrib , replacing old formwizard. It's already in trunk, see docs ). For the user I made it to look like there are actually multiple forms on the page, but only one is editable. And user had to fill forms in predetermined order. This made dealing with multiple forms much easier. Otherwise, if forms really need to be presented all at once, it may make sense to combine them into one. UPDATE (after your clarification): No, you can't deal with formsets using generic FormView either. Though your example appears to be quite simple to implement: I think it's very similar to this example in Django docs on formsets. It deals with two formsets, and you just need to replace one with the form (I think you still need to specify prefix to avoid possible clashes of elements' id attributes). In short, in your case I'd subclass django.views.generic.base.View and override get() and post() methods to deal with form and formset similar to above example from Django docs. In this case, I think it's fine to present both form and formset editable—with a single button to submit them both. ANOTHER UPDATE: There's an active recent ticket in Django trac, #16256 More class based views: formsets derived generic views . If all goes well, new generic views will be added to Django: FormSetsView , ModelFormSetsView and InlineFormSetsView . Particularly, the last one ‘provides a way to show and handle a model with it's inline formsets’.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6276398', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/231662/']}
jdg_86523
stackexchange
llm_judgeable_groundtruth_similarity
45488088
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 snippet: List<O> os = new ArrayList<>();os.add(new O("A", 3, "x"));os.add(new O("A", 2, "y"));os.add(new O("B", 1, "z"));Comparator<O> byA = Comparator.comparing(O::getA);Comparator<O> byB = Comparator.comparing(O::getB);// I want to use rather this... List<Comparator<O>> comparators = new ArrayList<>();comparators.add(byA);comparators.add(byB);os.stream() .sorted(byB.thenComparing(byA)) .forEach(o -> System.out.println(o.getC())); As you can see, I sort using explicitly two comparators. But what if I have the unknown number of comparators in some list and I want to sort by them all? Is there any way? Or should rather use the old fashion way comparator with multiple ifs? Now provide the response and nothing else.
If you have multiple comparators in a list or any other collection, you can replace them with a single one by performing the reduction on a Stream : List<Comparator<String>> comparators = ...Comparator<String> combined = comparators.stream() .reduce(Comparator::thenComparing) .orElse(someDefaultComparator); // empty list case All instances will be composed together using thenComparing according to their order from the input list. The same would be achievable using a non-stream approach by utilizing a simple for-loop: Comparator<String> result = comparators.get(0);for (int i = 1; i < comparators.size(); i++) { result = result.thenComparing(comparators.get(i));}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45488088', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1171170/']}
jdg_86524
stackexchange
llm_judgeable_groundtruth_similarity
417928
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: This is a question that a classmate asked me three years ago. Let $P(x)=\sum_{i=0}^n a_ix^i$ be a polynomial such that each $a_i>0$ . Prove or disprove that there exists a positive integer $r$ such that $P(x)^r=\sum_{i=0}^{nr} b_ix^i$ and there exists $0\le j\le nr$ such that $b_0\le b_1\le \dots\le b_{j}$ and $b_{j+1}\ge\dots\ge b_{nr}$ . This problem may have a probability problem as its original problem, since the classmate asked this while taking a probability class. What I could do is to try to apply CLT to claim that the "central terms" has only one peak and try to select some $r$ to make the first few terms and last few terms increasing/decreasing (that is, I proved that I can choose an $r$ to make $b_0\le b_1\le\dots \le b_k$ for any $k$ , and same at the other side). But I failed to prove the problem... I also tried to factorize it into smaller quadratic polynomials but also failed... Also, I can't come up with a counterexample, too... Note: if polynomials $p,q$ are single peak, this DOES NOT imply that $pq$ is single peak. For example: $p(x)=1+x+100x^2$ and $q(x)=10000+10000x+10100x^2+9000x^3+9000x^4$ . But $p(x)q(x)=900000x^6+909000x^5+1028000x^4+1019100x^3+1020100x^2+20000x+10000$ P.S. This is exactly same as the problem in MSE . As @ChrisSanders in the comment pointed out, I just ask the question here... Now provide the response and nothing else.
This is answered affirmatively by Odlyzko and Richmond, On the unimodality of high convolutions of discrete distributions , Annals of probability (1985) 299--306: all sufficiently large powers of the polynomial (with positive coefficients and no gaps) are strongly unimodal, that is, the coefficients form a log concave sequence. The proof uses estimates of contour integrals over circles of just the right radius.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/417928', 'https://mathoverflow.net', 'https://mathoverflow.net/users/170895/']}
jdg_86525
stackexchange
llm_judgeable_groundtruth_similarity
17002119
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 wonder how I/O were done in Haskell in the days when IO monad was still not invented. Anyone knows an example. Edit: Can I/O be done without the IO Monad in modern Haskell? I'd prefer an example that works with modern GHC. Now provide the response and nothing else.
Before the IO monad was introduced, main was a function of type [Response] -> [Request] . A Request would represent an I/O action like writing to a channel or a file, or reading input, or reading environment variables etc.. A Response would be the result of such an action. For example if you performed a ReadChan or ReadFile request, the corresponding Response would be Str str where str would be a String containing the read input. When performing an AppendChan , AppendFile or WriteFile request, the response would simply be Success . (Assuming, in all cases, that the given action was actually successful, of course). So a Haskell program would work by building up a list of Request values and reading the corresponding responses from the list given to main . For example a program to read a number from the user might look like this (leaving out any error handling for simplicity's sake): main :: [Response] -> [Request]main responses = [ AppendChan "stdout" "Please enter a Number\n", ReadChan "stdin", AppendChan "stdout" . show $ enteredNumber * 2 ] where (Str input) = responses !! 1 firstLine = head . lines $ input enteredNumber = read firstLine As Stephen Tetley already pointed out in a comment, a detailed specification of this model is given in chapter 7 of the 1.2 Haskell Report . Can I/O be done without the IO Monad in modern Haskell? No. Haskell no longer supports the Response / Request way of doing IO directly and the type of main is now IO () , so you can't write a Haskell program that doesn't involve IO and even if you could, you'd still have no alternative way of doing any I/O. What you can do, however, is to write a function that takes an old-style main function and turns it into an IO action. You could then write everything using the old style and then only use IO in main where you'd simply invoke the conversion function on your real main function. Doing so would almost certainly be more cumbersome than using the IO monad (and would confuse the hell out of any modern Haskeller reading your code), so I definitely would not recommend it. However it is possible. Such a conversion function could look like this: import System.IO.Unsafe-- Since the Request and Response types no longer exist, we have to redefine-- them here ourselves. To support more I/O operations, we'd need to expand-- these typesdata Request = ReadChan String | AppendChan String Stringdata Response = Success | Str String deriving Show-- Execute a request using the IO monad and return the corresponding Response.executeRequest :: Request -> IO ResponseexecuteRequest (AppendChan "stdout" message) = do putStr message return SuccessexecuteRequest (AppendChan chan _) = error ("Output channel " ++ chan ++ " not supported")executeRequest (ReadChan "stdin") = do input <- getContents return $ Str inputexecuteRequest (ReadChan chan) = error ("Input channel " ++ chan ++ " not supported")-- Take an old style main function and turn it into an IO actionexecuteOldStyleMain :: ([Response] -> [Request]) -> IO ()executeOldStyleMain oldStyleMain = do -- I'm really sorry for this. -- I don't think it is possible to write this function without unsafePerformIO let responses = map (unsafePerformIO . executeRequest) . oldStyleMain $ responses -- Make sure that all responses are evaluated (so that the I/O actually takes -- place) and then return () foldr seq (return ()) responses You could then use this function like this: -- In an old-style Haskell application to double a number, this would be the-- main functiondoubleUserInput :: [Response] -> [Request]doubleUserInput responses = [ AppendChan "stdout" "Please enter a Number\n", ReadChan "stdin", AppendChan "stdout" . show $ enteredNumber * 2 ] where (Str input) = responses !! 1 firstLine = head . lines $ input enteredNumber = read firstLine main :: IO ()main = executeOldStyleMain doubleUserInput
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/17002119', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1806553/']}
jdg_86526
stackexchange
llm_judgeable_groundtruth_similarity
257124
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: This problem arose when considering storage of cannonballs in n-dimensional pirate ships, as explained in this MSE post . This MO question can also be reduced to the $n=3$ case. If $x,y$ is a solution then $$0<\frac{x}{y}-2^\frac1n<\frac{2^\frac1n}{2ny^n}$$ then by Roth's theorem this has finitely many solutions for fixed $n$. Let $$2^{1/n}=a_0+\frac{1}{a_1+\dots}$$be the canonical continued fraction of $2^{1/n}$, then $a_0=1$ and $a_1\in\{\lfloor\frac{n}{\ln(2)}\rfloor,\lfloor\frac{n}{\ln(2)}\rfloor-1\}$, and since $\frac{x}{y}$ is a convergent of this continued fraction, $y>\frac{n}{\ln(2)}-1$. There are no solutions with $x^{n}<2^{64}$. It is also sufficient to only consider $n=4$ and odd primes, in FLT fashion. Now provide the response and nothing else.
Delone (1930) and Nagell (1928) showed for any nonzero integer $d$ that the equation $x^3 - dy^3 = 1$ has at most one solution in integers $(x,y)$ besides $(1,0)$, with no constraint on the signs of $x$ and $y$. In particular, since $x^3 - 2y^3 = 1$ has the integral solution $(-1,-1)$, there is no integral solution $(x,y)$ in positive integers. This theorem was extended to exponent 4 by Ljunggren (1942) and to exponent 5 and higher by Bennett (2001): for $n \geq 3$ and $d \not= 0$, the equation $|x^n - dy^n| = 1$ has at most one solution in positive integers. See Theorem 1.1 of https://www.math.ubc.ca/~bennett/B-Crelle2.pdf (which actually treats a slightly more general equation). In particular, $|x^n - 2y^n| = 1$ has at most one solution $(x,y)$ in positive integers. Since $(x,y) = (1,1)$ fits, it is the only one. Of course $x^n - 2y^n = -1$ when $(x,y) = (1,1)$, so for $n \geq 3$ there is no solution to $x^n - 2y^n = 1$ when $x$ and $y$ are positive integers.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/257124', 'https://mathoverflow.net', 'https://mathoverflow.net/users/100723/']}
jdg_86527
stackexchange
llm_judgeable_groundtruth_similarity
2164986
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,suppose I have the following xml: <Users> <User Name="Foo"> <Friends> <Friend Name="Bar"/> </Friends> </User> <User Name="Foo2" /> <User Name="Foo3"> <Friends> <Friend Name="Bar"/> </Friends> </User> </Users> How can I get all the users that have a "Bar" as a friend?(In this example it would be Foo,Foo3). Should I use xpath? Thanks! Now provide the response and nothing else.
I have a preference for using XPath these days. I've run into issues using PowerShell's xml adapter that are annoying like the name collision on item : $xml = [xml]@' <Users> <User Name="Foo"> <Friends> <Friend Name="Bar"/> </Friends> </User> <User Name="Foo2" /> <User Name="Foo3"> <Friends> <Friend Name="Bar"/> </Friends> </User> </Users> '@Select-Xml '//User[contains(Friends/Friend/@Name, "Bar")]' $xml |%{$_.Node.Name}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2164986', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/20257/']}
jdg_86528
stackexchange
llm_judgeable_groundtruth_similarity
45134118
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 really new in WSO2 and are having some little problems to carry on with my project.I do what the tutorials: www.docs.wso2.com/display/EI600/Installing+as+a+Windows+Service www.docs.wso2.com/display/Carbon420/Installing+as+a+Windows+Service Teaches, and create de windows service. I start it and close the command prompts with the 'runConsole.bat' command, the link continue working in the first 10 seconds, later it stop's. How can i solve it? If anyone could help me i would stay quite grateful.Thank you everyone. Now provide the response and nothing else.
Use copy insted of move, it should overwrite files automatically shutil.copy(sourcePath, destinationPath) Then of course you need to delete original files. Be aware, shutil.copy does not copy or create directories, so you need to make sure they exist. If this does not work either, you can manually check if file exists, remove it, and move new file: To check that file exists, use: from pathlib import Pathmy_file = Path("/path/to/file") if my_file.exists(): to check that something at path exist if my_file.is_dir(): to check if directory exists if my_file.is_file(): to check if file exists To delete directory with all its contents use: shutil.rmtree(path) Or delete a single file with os.remove(path) and then move them one by one
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45134118', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7619648/']}
jdg_86529
stackexchange
llm_judgeable_groundtruth_similarity
1705147
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 could do struct initialization with code: struct struct_type_id struct_name_id = { value1, value2, value3 }; but could not with: struct struct_type_id struct_name_id;struct_name_id = { value1, value2, value3 }; why I could do it with the former,but could not with the latter with gcc,g++,vc2008,vc6?In other words,why the c/c++ programming language do not support this syntax? thanks. Now provide the response and nothing else.
The first statement creates a variable initialized to the given values, i.e., these values are built in memory and stored directly in the program executable in that variable address (for globals) or ready for memory copy (for stack variables). The second statement of the second block is very different. Although it looks similar, it is an assign expression. It means that the RHS of the equals operator is an expression that is evaluated (independently of what is in the LHS of =), and then passed to the = operator. Without proper context, {...} doesn't have any meaning. In C99, you can do this: struct_name_id = (struct struct_type_id){ value1, value2, value3 }; Now the RHS of the equals operator is a valid expression, since there is proper context for the compiler to know what is in {...} . In C++11, the syntax is: struct_name_id = struct_type_id{ value1, value2, value3 };
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1705147', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/193251/']}
jdg_86530
stackexchange
llm_judgeable_groundtruth_similarity
61053432
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Consider the canonical useState example: import React, { useState } from 'react';const MyComponent = () => { const [count, setCount] = useState(0); console.log(count); return ( <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}> count: {count} <button onClick={() => setCount(count + 1)}>Increment</button> </div> );};export default MyComponent; Clicking the button makes each state print twice. Why is that? Now provide the response and nothing else.
Put the console.log in an useEffect hook without dependencies and you'll see it isn't actually rendering twice. import React, { useEffect, useState } from 'react';const MyComponent = () => { const [count, setCount] = useState(0); useEffect(() => { console.log(count); }); return ( <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}> count: {count} <button onClick={() => setCount(count + 1)}>Increment</button> </div> );};export default MyComponent; Here's a good diagram of the component lifecycle, it lists the class-based lifecycle functions, but the render/commit phases are the same. The import thing to note is that the component can be "rendered" without actually being committed (i.e. the conventional render you see to the screen). The console.log alone is part of that. The effects run after in the "commit" phase. useEffect ... The function passed to useEffect will runafter the render is committed to the screen. ... By default, effects run after every completed render, ... React Strict Mode Detecting Unexpected Side-effects Strict mode can’t automatically detect side effects for you, but itcan help you spot them by making them a little more deterministic.This is done by intentionally double-invoking the following functions: Class component constructor , render , and shouldComponentUpdate methods Class component static getDerivedStateFromProps method Function component bodies State updater functions (the first argument to setState ) Functions passed to useState , useMemo , or useReducer This only applies to development mode.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/61053432', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5151909/']}
jdg_86531
stackexchange
llm_judgeable_groundtruth_similarity
41946473
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 unable to use hasRole method in @PreAuthorize annotation. Also request.isUserInRole(“ADMIN”) gives false . What am I missing?Although .hasAuthority(“ADMIN”) works fine. I am assigning authorities to the users from a database. Now provide the response and nothing else.
You have to name your authority with prefix ROLE_ to use isUserInRole , see Spring Security Reference : The HttpServletRequest.isUserInRole(String) will determine if SecurityContextHolder.getContext().getAuthentication().getAuthorities() contains a GrantedAuthority with the role passed into isUserInRole(String) . Typically users should not pass in the "ROLE_" prefix into this method since it is added automatically. For example, if you want to determine if the current user has the authority "ROLE_ADMIN", you could use the following: boolean isAdmin = httpServletRequest.isUserInRole("ADMIN"); Same for hasRole (also hasAnyRole ), see Spring Security Reference : Returns true if the current principal has the specified role. By default if the supplied role does not start with 'ROLE_' it will be added. This can be customized by modifying the defaultRolePrefix on DefaultWebSecurityExpressionHandler . See also Spring Security Reference : 46.3.3 What does "ROLE_" mean and why do I need it on my role names? Spring Security has a voter-based architecture which means that an access decision is made by a series of AccessDecisionVoters . The voters act on the "configuration attributes" which are specified for a secured resource (such as a method invocation). With this approach, not all attributes may be relevant to all voters and a voter needs to know when it should ignore an attribute (abstain) and when it should vote to grant or deny access based on the attribute value. The most common voter is the RoleVoter which by default votes whenever it finds an attribute with the "ROLE_" prefix. It makes a simple comparison of the attribute (such as "ROLE_USER") with the names of the authorities which the current user has been assigned. If it finds a match (they have an authority called "ROLE_USER"), it votes to grant access, otherwise it votes to deny access.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/41946473', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/642510/']}
jdg_86532
stackexchange
llm_judgeable_groundtruth_similarity
5823770
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How would I write the equivalent code in C#: typedef void (^MethodBlock)(int); - (void) fooWithBlock:(MethodBlock)block{ int a = 5; block(a);}- (void) regularFoo{ [self fooWithBlock:^(int val) { NSLog(@"%d", val); }];} Now provide the response and nothing else.
Something like this: void Foo(Action<int> m){ int a = 5; m(a);}void RegularFoo(){ Foo(val => // Or: Foo(delegate(int val) { Console.WriteLine(val); });} Action<T> is a delegate that takes exactly one argument of a type you specify (in this case, int ), that executes without returning anything. Also see the general C# delegate reference . For a simple case like this, it's pretty straightforward. However, I believe there are some semantic/technical differences between blocks in Objective-C and delegates in C#, which are probably beyond the scope of this question.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5823770', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/204884/']}
jdg_86533
stackexchange
llm_judgeable_groundtruth_similarity
14621581
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 new to angular, so please bear with me. I was reading an article/documentation the other day that highlighted the best way to structure modules in your app, and can only remember it loosely. App.controllersApp.services....angular.module('App', [App.controllers, App.services ...); This code sample is very likely to be incorrect, but the point was to group controllers, services etc together in one namespace. Could anyone expand upon this approach? Now provide the response and nothing else.
Enterprise project organization The way I organize my angular project is: /app /img # application-level images /css # application-level css styles /js # application-level javascripts /modules # application modules /gallery # independent module with its own infrastructure /controllers # gallery module's controllers /css # gallery module's css styles /directives # gallery module's directives /img # gallery module's images /filters # gallery module's filters /services # gallery module's services /views # gallery module's views (htmls) / ... # other gallery module component folders galleryMod.js # the module itself /user # independent module with its own infrastructure /controllers # user module's controllers / ... # other user module component folders userMod.js # the module itself / ... # other modules / ... # other application-level folders index.html Alternative enterprise project organization (simplified) /app /img # application-level images /css # application-level css styles /js # application-level javascripts /modules # application modules /gallery # independent module with its own infrastructure /js # gallery module's javascripts (includes # services.js, directives.js, filters.js, ...) /css # gallery module's css styles /img # gallery module's images /views # gallery module's views (htmls, "partials") / ... # other gallery module component folders galleryMod.js # the module itself /user # independent module with its own infrastructure /controllers # user module's controllers / ... # other user module component folders userMod.js # the module itself / ... # other modules / ... # other application-level folders index.html Middle project organization (without modules) /app /img # application's images /css # application's css styles /controllers # application's controllers /directives # application's directives /filters # application's filters /services # application's services /views # application's views (htmls) / ... # other component folders index.html Simple project organization (just like a seed) /app /img # application's images /css # application's css styles /js # application's javascripts (includes # services.js, directives.js, filters.js, ...) /views # application's views (htmls), e.g. partials / ... # other component folders index.html Use the way your project needs to be organized and don't choose the way that will unnecessarily complicate your project.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14621581', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1108312/']}
jdg_86534
stackexchange
llm_judgeable_groundtruth_similarity
81711
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 want to list all the physical volume associated with logical volume. I know lvdisplay , pvscan , pvdisplay -m could do the job. but I don't want to use these commands. Is there any other way to do it without using lvm2 package commands? Any thoughts on comparing the major and minor numbers of devices? Now provide the response and nothing else.
There are two possibilities: If you accept dmsetup as a non-lvm package command (at openSUSE the is a separate package device-mapper ) then you can do this: dmsetup table "${vg_name}-${lv_name}" Or you do this: start cmd: # ls -l /dev/mapper/linux-rootfs lrwxrwxrwx 1 root root 7 27. Jun 21:34 /dev/mapper/linux-rootfs -> ../dm-0start cmd: # ls /sys/block/dm-0/slaves/sda9
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/81711', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/40151/']}
jdg_86535
stackexchange
llm_judgeable_groundtruth_similarity
110396
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 two facts seem really intriguing and I am trying to figure out how to use computations of homology to deduce them: (a) The boundary of an ($n+1$)-simplex is homeomorphic to $S^n$. (b) An $n$-dimensional convex body is a compact convex set in $\mathbb{R}^n$. Show that any two $n$-dimensional convex bodies are homeomorphic. Any input to help me think about these exercises would be greatly appreciated. Now provide the response and nothing else.
You can find proofs of both facts in Ch.1 section 16 of Bredon's book Topology and Geometry. Here are the two relevant statements. 16.3 Proposition . Let $C\subset \mathbb R^n$ be a compact convex body with $0\in int(C)$. Then the function $f\colon\partial C\to S^{n-1}$ given by $f(x)=x/||x||$ is a homeomorphism. This is easy to verify now that you know what the map is! 16.4 Theorem . A compact convex body $C$ in $\mathbb R^n$ with nonempty interior is homeomorphic to the closed $n$ ball, and $\partial C\cong S^{n-1}$. To prove this, assume by translating if necessary that $0\in int(C)$. Define $k\colon D^n\to C$ by $k(x)=||x||f^{-1}(x/||x||)$ for $x\neq 0$ and $k(0)=0$, where $f$ is as above. Now check this is a homeomorphism.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/110396', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/23689/']}
jdg_86536
stackexchange
llm_judgeable_groundtruth_similarity
1009762
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Duplicate of: In C#, how can I rethrow InnerException without losing stack trace? I have some operations that I invoke asynchronously on a background thread. Sometimes, things go bad. When this happens, I tend to get a TargetInvocationException, which, while appropriate, is quite useless. What I really need is the TargetInvocationException's InnerException, like this: try { ReturnValue = myFunctionCall.Invoke(Target, Parameters); } catch (TargetInvocationException err) { throw err.InnerException; } That way, my callers are served up with the REAL exception that occured. The problem is, that the throw statement seems to reset the stack trace. I'd like to basically rethrow the inner exception, but keep the stack trace it originally had. How do I do that? CLARIFICATION: The reason I want only the inner exception is that this class tries to 'abstract away' the whole fact that these functions (delegates supplied by caller) are run on other threads and whatnot. If there is an exception, then odds are it has nothing to do with being run on a background thread, and the caller would really like the stack trace that goes into their delegate and finds the real issue, not my call to invoke. Now provide the response and nothing else.
It is possible to preserve the stack trace before rethrowing without reflection: static void PreserveStackTrace (Exception e){ var ctx = new StreamingContext (StreamingContextStates.CrossAppDomain) ; var mgr = new ObjectManager (null, ctx) ; var si = new SerializationInfo (e.GetType (), new FormatterConverter ()) ; e.GetObjectData (si, ctx) ; mgr.RegisterObject (e, 1, si) ; // prepare for SetObjectData mgr.DoFixups () ; // ObjectManager calls SetObjectData // voila, e is unmodified save for _remoteStackTraceString} This wastes a lot of cycles compared to InternalPreserveStackTrace, but has the advantage of relying only on public functionality. Here are a couple of common usage patterns for stack-trace preserving functions: // usage (A): cross-thread invoke, messaging, custom task schedulers etc.catch (Exception e){ PreserveStackTrace (e) ; // store exception to be re-thrown later, // possibly in a different thread operationResult.Exception = e ;}// usage (B): after calling MethodInfo.Invoke() and the likecatch (TargetInvocationException tiex){ PreserveStackTrace (tiex.InnerException) ; // unwrap TargetInvocationException, so that typed catch clauses // in library/3rd-party code can work correctly; // new stack trace is appended to existing one throw tiex.InnerException ;}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1009762', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/18071/']}
jdg_86537
stackexchange
llm_judgeable_groundtruth_similarity
13421424
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to know if there is a way to solve infix expressions in a single pass using 2 stacks?The stacks can be one for operator and the other for operands... The standard way to solve by shunt-yard algorithm is to convert the infix expression to postfix(reverse polish) and then solve. I don't want to convert the expression first to postfix. If the expression is like 2*3-(6+5)+8 , how to solve? Now provide the response and nothing else.
Quite late, but here is the answer. Take two stacks: operator stack { for operators and parentheses }. operand stack . Algorithm If character exists to be read: If character is operand push on the operand stack , if character is ( , push on the operator stack . Else if character is operator While the top of the operator stack is not of smaller precedence than this character. Pop operator from operator stack . Pop two operands ( op1 and op2 ) from operand stack . Store op1 op op2 on the operand stack back to 2.1. Else if character is ) , do the same as 2.2 - 2.4 till you encounter ( . Else (no more character left to read): Pop operators untill operator stack is not empty. Pop top 2 operands and push op1 op op2 on the operand stack . return the top value from operand stack .
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/13421424', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1768245/']}
jdg_86538
stackexchange
llm_judgeable_groundtruth_similarity
111756
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: Benjamini and Hochberg developed the first (and still most widely used, I think) method for controlling the false discovery rate (FDR). I want to start with a bunch of P values, each for a different comparison, and decide which ones are low enough to be called a "discovery", controlling the FDR to a specified value (say 10%). One assumption of the usual method is that the set of comparisons are either independent or have "Positive dependency" but I can't figure out exactly what that phrase means in the context of analyzing a set of P values. Now provide the response and nothing else.
From your question and in particular your comments to other answers, it seems to me that you are mainly confused about the "big picture" here: namely, what does "positive dependency" refer to in this context at all -- as opposed to what is the technical meaning of the PRDS condition. So I will talk about the big picture. The big picture Imagine that you are testing $N$ null hypotheses, and imagine that all of them are true. Each of the $N$ $p$ -values is a random variable; repeating the experiment over and over again would yield a different $p$ -value each time, so one can talk about a distribution of $p$ -values (under the null). It is well-known that for any test, a distribution of $p$ -values under the null must be uniform; so, in the case of multiple testing, all $N$ marginal distributions of $p$ -values will be uniform. If all the data and all $N$ tests are independent from each other, then the joint $N$ -dimensional distribution of $p$ -values will also be uniform. This will be true e.g. in a classic "jelly-bean" situation when a bunch of independent things are being tested: However, it does not have to be like that. Any pair of $p$ -values can in principle be correlated, either positively or negatively, or be dependent in some more complicated way. Consider testing all pairwise differences in means between four groups; this is $N=4\cdot 3/2=6$ tests. Each of the six $p$ -values alone is uniformly distributed. But they are all positively correlated: if (on a given attempt) group A by chance has particularly low mean, then A-vs-B comparison might yield a low $p$ -value (this would be a false positive). But in this situation it is likely that A-vs-C, as well as A-vs-D, will also yield low $p$ -values. So the $p$ -values are obviously non-independent and moreover they are positively correlated between each other. This is, informally, what "positive dependency" refers to. This seems to be a common situation in multiple testing. Another example would be testing for differences in several variables that are correlated between each other. Obtaining a significant difference in one of them increases the chances of obtaining a significant difference in another. It is tricky to come up with a natural example where $p$ -values would be "negatively dependent". @user43849 remarked in the comments above that for one-sided tests it is easy: Imagine I am testing whether A = 0 and also whether B = 0 against one-tailed alternatives (A > 0 and B > 0). Further imagine that B depends on A. For example, imagine I want to know if a population contains more women than men, and also if the population contains more ovaries than testes. Clearly knowing the p-value of the first question changes our expectation of the p-value for the second. Both p-values change in the same direction, and this is PRD. But if I instead test the second hypothesis that population 2 has more testes than ovaries, our expectation for the second p-value decreases as the first p-value increases. This is not PRD. But I have so far been unable to come up with a natural example with point nulls. Now, the exact mathematical formulation of "positive dependency" that guarantees the validity of Benjamini-Hochberg procedure is rather tricky. As mentioned in other answers, the main reference is Benjamini & Yekutieli 2001 ; they show that PRDS property ("positive regression dependency on each onefrom a subset") entails Benjamini-Hochberg procedure. It is a relaxed form of the PRD ("positive regression dependency") property, meaning that PRD implies PRDS and hence also entails Benjamini-Hochberg procedure. For the definitions of PRD/PRDS see @user43849's answer (+1) and Benjamini & Yekutieli paper. The definitions are rather technical and I do not have a good intuitive understanding of them. In fact, B&Y mention several other related concepts as well: multivariate total positivity of order two (MTP2) and positive association. According to B&Y, they are related as follows (the diagram is mine): $\hskip{10em}$ MTP2 implies PRD that implies PRDS that guarantees correctness of B-H procedure. PRD also implies PA, but PA $\ne$ PRDS.
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/111756', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/25/']}
jdg_86539
stackexchange
llm_judgeable_groundtruth_similarity
34737898
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 making a simple "Hello World" program in React.js. I am expecting "Hello World" to be printed in the body of the html. index.html <html><head><script src="http://fb.me/react-0.12.2.min.js"></script><script>var HelloWorld = React.createClass({ render: function() { return <div>Hello, world!</div>; }});React.render(new HelloWorld(), document.body);</script></head><body> </body> </html> Error: Uncaught SyntaxError: Unexpected token < Can someone tell me where am I making a mistake? Now provide the response and nothing else.
What you're missing is including something that transforms the JSX into JS. You need to include the JSXTransformer.js. Also notice the React.render doesn't use document.body, it should be a dom element. Here's an example that should work: <!DOCTYPE html><html> <head> <title>My First React Example</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/react.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/JSXTransformer.js"></script> </head> <body> <div id="greeting-div"></div> <script type="text/jsx"> var Greeting = React.createClass({ render: function() { return ( <p>Hello, Universe</p> ) } }); React.render( <Greeting/>, document.getElementById('greeting-div') ); </script> </body></html>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34737898', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2685914/']}
jdg_86540