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
4432931
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 to ask is there a possibility to bind some listener to the ListView scroll event. What I would like to achieve is that once ListView have been scrolled to the bottom I would like to ask server for more data if any is there. I know that there is a function like: getLastVisiblePosition() but I assume it must bu used in some kind of listener in order to compare with currently last visible position, am I right ? cheers,/Marcin Now provide the response and nothing else.
Just to extrapolate on TomTo's answer, some thoughts on how you might do this (theoretical, I haven't tried this in practice): ListView lv = (ListView)findViewById(R.id.list_view);lv.setOnScrollListener(new OnScrollListener() { @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { //Check if the last view is visible if (++firstVisibleItem + visibleItemCount > totalItemCount) { //load more content } }}); Since firstVisibleItem is returns an index (0-based), I increment by one to get the actual item number. Then, if that, plus the number of visible items, is greater than the total number of items, then in theory the last view should be visible. Shouldn't be a problem, but keep in mind this isn't called till the scrolling is finished.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4432931', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/193400/']}
jdg_379241
stackexchange
llm_judgeable_groundtruth_similarity
980941
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How can I calculate $1+(1+2)+(1+2+3)+\cdots+(1+2+3+\cdots+n)$? I know that $1+2+\cdots+n=\dfrac{n+1}{2}\dot\ n$. But what should I do next? Now provide the response and nothing else.
Hint: use also that$$1^2 + 2^2 + \dots + n^2 = \frac{n(n+1)(2n+1)}6$$ $$1 + (1+2) + \dots + (1 +2+\dots +n) =\frac{1(1+1)}2 + \frac{2(2+1)}2 + \dots + \frac{n(n+1)}2 \\=\frac 12 \left[(1^2 + 1) + (2^2 + 2 ) + \dots + (n^2 + n)\right]\\=\frac 12 \left[(1^2 + 2^2 + \dots + n^2) + (1 + 2 + \dots + n)\right]$$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/980941', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/123499/']}
jdg_379242
stackexchange
llm_judgeable_groundtruth_similarity
383918
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I came to ask this because I am really stuck at this problem. I have tried everything from arithmetic mean, geometric mean and harmonic mean. Also, I have tried playing with the variables and such, but it got me to nowhere. If $a+b+c=1$; $a,b,c$ nonnegative, calculate the minimum of $$\frac{4+3abc}{ab+bc+ac}$$All I've got so far is:$$\frac{3abc}{ab+bc+ac} \le \frac{1}{3}$$But this is obviously on the wrong side of the inequality.Also, I think that$$\frac{1}{ab+bc+ac}\ge3$$But I haven't been able to prove it. Playing with the most possible and obvious values, one could think that the answer is 37/3, but the excercise is about proving it. Any help and little hints are greatly apprecieated. Now provide the response and nothing else.
It seems you are right and the minimum is indeed 37/3. We shall use the standard techniques for proving the inequalities. If we put $a=b=c=1/3$ then the obtain the upper bound $37/3$ for the minimum. It rests to show that holds (1) $\frac{4+3abc}{ab+bc+ac}\ge 37/3.$ At first we homogenize [Lee, Ch 3] the left side $$\frac{4+3abc}{ab+bc+ac}=\frac{4(a+b+c)^3+3abc}{(ab+bc+ac)(a+b+c)}.$$ Expanding and simplifying, we reduce inequality (1) to the form $$12(a^3+b^3+c^3)\ge (a^2b+ab^2+ab^2+ac^2+b^2c+bc^2)+30abc,$$ which should follow from Muirhead Theorem [Lee, Ch. 3.3]. References [Lee] Hojoo Lee. Topics in Inequalities - Theorems and Techniques (February 25, 2006) .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/383918', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/37844/']}
jdg_379243
stackexchange
llm_judgeable_groundtruth_similarity
288165
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: How do I design a subclass whose method contradicts its superclass? Let's say we have this example: # Example 1class Scissor def right_handed? true endendclass LeftHandedScissor < Scissor def right_handed? false endend Let's assume that the inheritance is necessary in this example e.g. that there might be other methods aside from right_handed? that are being inherited. So a LeftHandedScissor is a Scissor. Its method right_handed? matches the signature and return value type of its superclass's method. However, the subclass method contradicts the return value of the superclass method. This bothers me because it looks like a logical contradiction: All scissors are right-handed. A left-handed scissor is a scissor. Therefore, a left-handed scissor is right-handed. I considered introducing an AbstractScissor to avoid this contradiction: # Example 2class AbstractScissor def right_handed? raise NotImplementedError endendclass RightHandedScissor < AbstractScissor def right_handed? true endendclass LeftHandedScissor < AbstractScissor def right_handed? false endend My colleague says the downside to this solution is that it's more verbose. Aside from adding an extra class, it requires us to call scissors "right-handed scissors", which no one does in the real world. This leads me to my last solution: # Example 3class AbstractScissor def right_handed? raise NotImplementedError endendclass Scissor < AbstractScissor def right_handed? true endendclass LeftHandedScissor < AbstractScissor def right_handed? false endend It's nearly the same as example 2 but I just renamed RightHandedScissor as Scissor. There's a chance that someone might assume LeftHandedScissor is a subclass of Scissor based solely on the class names, but at least the code makes it obvious that that's not the case. Any other ideas? Now provide the response and nothing else.
There is nothing wrong with the design shown in the question. While one could also introduce abstract Scissor with two concrete subclasses, and maybe more overall clarity, it's also common to do it like shown (especially when the hierarchy is a result of years of incremental development, with Scissor being around for much longer than the concept of handedness). " Okay, I guess the lesson here is that you don't make assumptions about the subclasses based solely on the superclass? " You do make such assumptions based on the contracts (method signatures) of the base class, but not based on method implementations. In this case the contract says that right_handed is a Boolean method which can be true or false, so it can be either. You should ignore the fact that the base class implementation always returns true, especially if you allowed to derive from the base class by not freezing it. The base class implementation is then just a default, and the method right_handed exists exactly because the scissor could also be left handed.
{}
{'log_upvote_score': 6, 'links': ['https://softwareengineering.stackexchange.com/questions/288165', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/185220/']}
jdg_379244
stackexchange
llm_judgeable_groundtruth_similarity
51810076
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 try to redirect the user from one component to another after a few seconds. The user lands on a page and after few second he is automatically redirect to another page.I thought to redirect in an action but I am not sure if it is the best idea (if you have easier way to do it I am interested). My code so far: a basic component: import React, { Component } from "react";import { connect } from "react-redux";import { withRouter } from "react-router-dom";import { redirectToProfile } from "../../actions/searchActions";class Search extends Component { componentDidMount() { setTimeout(this.props.redirectToProfile(this.props.history), 3000); } render() { return ( <div> <h1>search page</h1> </div> ); }}export default connect( null, { redirectToProfile })(withRouter(Search)); and the action: export const redirectToProfile = history => { history.push("/");}; So far I have an error message: Actions must be plain objects. Use custom middleware for async actions. After some research I see that some people resolve the problem with the middleware thunk but I am already using it so I don't know what to do.Thank you for your help. Now provide the response and nothing else.
Why not use the <Redirect/> component that react-router provides? I think that's clearer and more in keeping with React's declarative model, rather than hiding away the logic in an imperative thunk/action. class Foo extends Component { state = { redirect: false } componentDidMount() { this.id = setTimeout(() => this.setState({ redirect: true }), 1000) } componentWillUnmount() { clearTimeout(this.id) } render() { return this.state.redirect ? <Redirect to="/bar" /> : <div>Content</div> }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51810076', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8996116/']}
jdg_379245
stackexchange
llm_judgeable_groundtruth_similarity
10014252
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 plugins and plugin features do I need to set in order to get my Jenkins job to trigger a build any time code is committed to an SVN project? I have installed both the standard SVN plugin as well as the SVN tagging plugin, but I do not see any new features that allow trigger configuration. Now provide the response and nothing else.
There are two ways to go about this: I recommend the first option initially, due to its ease of implementation. Once you mature in your build processes, switch over to the second. Poll the repository to see if changes occurred. This might "skip" a commit if two commits come in within the same polling interval. Description of how to do so here , note the fourth screenshot where you configure on the job a "build trigger" based on polling the repository (with a crontab-like configuration). Configure your repository to have a post-commit hook which notifies Jenkins that a build needs to start. Description of the plugin here , in the section "post-commit hooks" The SVN Tag feature is not part of the polling, it is part of promoting the current "head" of the source code to a tag, to snapshot a build. This allows you to refer to Jenkins buid #32 as SVN tag /tags/build-32 (or something similar).
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/10014252', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/892029/']}
jdg_379246
stackexchange
llm_judgeable_groundtruth_similarity
2355723
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Find the value of the sum $\displaystyle \sum\limits_{n=1}^{\infty} \frac{(7n+32) \cdot3^n}{n(n+2) \cdot 4^n}.$ Using partial fraction decomposition, I found the above expression is equivalent to $\displaystyle \sum\limits_{n=1}^{\infty} \frac{25}{n} \cdot \left(\frac{3}{4}\right)^n - \sum\limits_{n=1}^{\infty} \frac{18}{n+2} \cdot \left(\frac{3}{4}\right)^n,$ where I got couldn't find a closed form of either expression because of the $\left(\dfrac{3}{4}\right)^n.$ Similarly, trying to telescope one of the the sums with $\displaystyle \sum\limits_{n=1}^{\infty} \left(\frac{1}{n} - \frac{1}{n+2}\right) \cdot \left(\frac{3}{4}\right)^n$ fails for the same reason. How can I further simplify the above expression? Thanks. Now provide the response and nothing else.
HINT: $$7n+32=4^2(n+2)-3^2\cdot n$$ $$\implies\dfrac{7n+32}{n(n+2)}\left(\dfrac34\right)^n=\dfrac{4^2(n+2)-3^2\cdot n}{n(n+2)}\left(\dfrac34\right)^n=\dfrac{16\left(\dfrac34\right)^n}n-\dfrac{16\left(\dfrac34\right)^{n+2}}{(n+2)}$$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2355723', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/459934/']}
jdg_379247
stackexchange
llm_judgeable_groundtruth_similarity
8888834
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 vector<int> with 10,000,000 (10 million) elements, and that my workstation has four cores. There is a function, called ThrFunc , that operates on an integer. Assume that the runtime for ThrFunc for each integer in the vector<int> is roughly the same. How should I determine the optimal number of threads to fire off? Is the answer as simple as the number of elements divided by the number of cores? Or is there a more subtle computation? Editing to provide extra information No need for blocking; each function invocation needs only read-onlyaccess Now provide the response and nothing else.
The optimal number of threads is likely to be either the number of cores in your machine or the number of cores times two. In more abstract terms, you want the highest possible throughput. Getting the highest throughput requires the fewest contention points between the threads (since the original problem is trivially parallelizable). The number of contention points is likely to be the number of threads sharing a core or twice that, since a core can either run one or two logical threads (two with hyperthreading). If your workload makes use of a resource of which you have fewer than four available (ALUs on Bulldozer? Hard disk access?) then the number of threads you should create will be limited by that. The best way to find out the correct answer is, with all hardware questions, to test and find out.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8888834', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/631115/']}
jdg_379248
stackexchange
llm_judgeable_groundtruth_similarity
4692542
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 stackoverflow approved (and hence correct) method to force a VBS to run using cscript instead of wscript - irrespective of what the user tries? A quick Google search shows plenty of examples, but some of them simply don't work and those which do often don't handle the fact that it may have been run with arguments so I'm keen to know what the best way is. Here is one example which doesn't handle arguments: sExecutable = LCase(Mid(Wscript.FullName, InstrRev(Wscript.FullName,"\")+1))If sExecutable <> "cscript.exe" Then Set oShell = CreateObject("wscript.shell") oShell.Run "cscript.exe """ & Wscript.ScriptFullName & """" Wscript.QuitEnd If I appreciate that this could probably be easily modified to handle arguments, but realise that this may not be the best way to approach the problem. Background: I'm writing a script which can run by double clicking or (most likely) from either a DOS batch file or as a scheduled task. It can contain one or more optional command line arguments. Now provide the response and nothing else.
My Lord, what unadulterated rubbish. It makes me cry to see such cruddy coding (no offense to anybody, lol). Seriously, though, here's my 2 pence: Sub forceCScriptExecution Dim Arg, Str If Not LCase( Right( WScript.FullName, 12 ) ) = "\cscript.exe" Then For Each Arg In WScript.Arguments If InStr( Arg, " " ) Then Arg = """" & Arg & """" Str = Str & " " & Arg Next CreateObject( "WScript.Shell" ).Run _ "cscript //nologo """ & _ WScript.ScriptFullName & _ """ " & Str WScript.Quit End IfEnd SubforceCScriptExecution It handles arguments, AND checks for spaces in said arguments -- so that in the case of a filename passed to the original script instance that contained spaces, it wouldn't get "tokenized" when passed to cscript.exe. Only thing it doesn't do is test for StdIn (e.g., in the case where someone piped something to the script via the command line, but forgot to use "cscript script.vbs") -- but if it was executed by WScript.exe, WScript.StdIn's methods all return Invalid Handle errors, so there's no way to test that anyway. Feel free to let me know if there's a way to "break" this; I'm willing to improve it if necessary.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4692542', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/185851/']}
jdg_379249
stackexchange
llm_judgeable_groundtruth_similarity
37968
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: In Classical Mechanics, both Goldstein and Taylor (authors of different books with the same title) talk about the centrifugal force term when solving the Euler-Lagrange equation for the two body problem, and I'm a little confused about what it exactly means - is it a real centrifugal force or a mathematical consequence of using polar coordinates for solving the Euler-Lagrange equation. Their derivations of the Lagrangian $$L=\frac{1}{2}\mu(\dot{r}^{2}+r^{2}\dot{\theta}^{2})-U(r)$$ would lead to one motion of equation (theta) showing that angular momentum is constant and one radial equation of motion shown as $$\mu\ddot{r}=-\frac{dU}{dr}+\mu r\dot{\phi}^{2}=-\frac{dU}{dr}+F_{cf}.$$ They call $\mu r\dot{\phi}^{2}$ the fictitious force or the centrifugal force. I'm quite hazy on my memory of non-inertial frames, but I was under the assumption that fictitious forces only appear in non-inertial frames. The frame of reference in the two body problem was chosen such that the Center of Mass of the two bodies would be the origin so that would be an inertial frame, and I'm assuming that there are no non-inertial frames involved since neither author had talked about it in the previous chapters. Would calling $\mu r\dot{\phi}^{2}$ an actual centrifugal force be incorrect then? Isn't it a term that describes the velocity perpendicular to the radius? From this two-body problem, it appears as though if I were to use polar coordinates when solving the Euler-Lagrange equations for any other problem, the centrifugal force term will always appear, so it would be a mathematical consequence of the choice of coordinate system rather than it being an actual fictitious force. Is that term being called a centrifugal force because it actually is a centrifugal force or is it because it has a mathematical form similar to it? Now provide the response and nothing else.
There are two equivalent descriptions$^1$ of the reduced two-body problem with a central potential $V(r)$: In an inertial frame with no fictitious forces: Here $\frac{1}{2}\mu r^{2}\dot{\theta}^{2}$ is the angular part of the kinetic energy. In a rotating frame following the reduced particle with fictitious forces and only 1D radial kinematics: Here $-\frac{1}{2}\mu r^{2}\dot{\theta}^{2}$ is the centrifugal potential (notice the minus sign!). Each description leads to the same Lagrangian $$L~=~T-U~=~L=\frac{1}{2}\mu(\dot{r}^{2}+r^{2}\dot{\theta}^{2})-V(r).$$ $^1$ The reduced particle is confined to an orbit plane, so the problem is effectively just two-dimensional described by two coordinates $r$ and $\theta$. In both descriptions, the center-of-mass serves as the origin of the reference frame. The motion of the center-of-mass itself is trivial, as there is no external forces.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/37968', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/12420/']}
jdg_379250
stackexchange
llm_judgeable_groundtruth_similarity
1385196
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 remapped [[ and ]] to find the previous and next pattern in the file. The mappings are as follows: nmap [[ ?^.section <CR>nmap ]] /?section /<CR> The issue is that when I use any of them, I "loose" the current search pattern, so when doing n for the next match, I search for the next "section". Is there a way to restore the search pattern, or for the [[ and ]] mappings to not affect the current search pattern? Now provide the response and nothing else.
You can probably do it by hand by saving and restoring the "/ register. However, a better way is to just move your code into a function; returning from a function automatically restores it. To quote the VIM documentation: *function-search-undo* The last used search pattern and the redo command "." will not be changed by the function. This also implies that the effect of |:nohlsearch| is undone when the function returns. This would look something like this in your .vimrc : function! Ayman_NextSection /?section /endfunctionnmap ]] call Ayman_NextSection()<CR> Hope that helps.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1385196', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/77222/']}
jdg_379251
stackexchange
llm_judgeable_groundtruth_similarity
29873439
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I used to be able to call cup all and have my applications update. Now, it asks for yes to ensure that I want to install the selected package. Is there a way I can have everything auto update without constantly typing yes for every update? Now provide the response and nothing else.
tl;dr - Yes, completely possible. Use cup all -y Also check out the help menus now - choco -h , choco install -h Longer answer, we've moved a little closer towards other package managers for security reasons, where by default we stop and confirm if you are okay with the state change. I always communicate changes in the release notes / changelog , which also end up in the nuspec file , so I highly recommend folks scan at least one of those to see anything tagged breaking changes. Always scan from your current version up to the one you are upgrading to so that you catch all changes. The one that is the most important right now is the x.y.z release (in this case 0.9.9), once we reach v1 we will be fully SemVer compliant and breaking changes will constitute a major version bump (we're still semver in a less than v1), so you can scan breaking changes and major new features in an x release, new compatible features in a .y release, and .z releases will only contain compatible fixes for the current release. 0.9.9 introduced a new compiled client that was/is a total rewrite. 0.9.10 will have complete feature parity with the older client - see FeatureParity . Why the rewrite? For a more maintainable, faster client that can run on mono now, so you are not completely tied to Windows. We've started adding support for other install providers (like Scriptcs ). The relevant bits of the release notes for your question: [Security] Prompt for confirmation: For security reasons, we now stop for confirmation before changing the state of the system on most commands. You can pass -y to confirm any prompts or set a value in the config that will globally confirm and behave like older versions of Chocolatey ( allowGlobalConfirmation , see choco feature -h for how to enable).
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/29873439', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1757401/']}
jdg_379252
stackexchange
llm_judgeable_groundtruth_similarity
48017877
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: My scenario is I bring some values as autocomplete from database which is as V001/Vendor 1 , V002/Vendor 2 , ..... SO what I want is if User already selected V001/Vendor 1 in first textbox then he should not be able to select the same V001/Vendor 2 in second textbox. Here is how it looks like Also, see my autocomplete code which is in jquery autocompleteOptions = { minLength: 3, source: function (request, response) { var term = $.trim(request.term); $.ajax({ //receives json array answer from the url url: AppConfig.PrefixURL + "App/GetVendorList", data: { "VENDORNAME": "" + extractLast(term) + "" }, dataType: "json", type: "POST", success: function (data) { var datalist = JSON.parse(data); response($.map(datalist, function (element, index) { return { label: element.VENDORNAME, value: element.VENDORCODE + "/" + element.VENDORNAME }; })); }, error: function () { // added an error handler response($.ui.autocomplete.filter( ["VENDORNAME", "VENDORCODE"] , extractLast(term))); } }); }, select: function (e, u) { if (u.item.value == "") { return false; } }, change: function (event, ui) { $(this).val((ui.item ? ui.item.value : "")); if ($(this).val().trim() == "" || $(this).val() == null || $(this).val() == "null") { var name = $(this).attr('id'); var id = parseInt(name.substr(13, name.length)); $('#spFromDate' + id).val(''); $('#spToDate' + id).val(''); } },};$("#txtVendorName1").autocomplete(autocompleteOptions); Kindly suggest how to achieve this. Now provide the response and nothing else.
First off, is the above example code a correct example of how to use php openssl_encrypt? Your usage of the function looks correct, however you may want to consider a mode of operation other than CBC. CBC is tricky to get right because just encrypting data in this mode has known attacks against it, such as the infamous CBC bit-flipping attack , which allows an attacker to make meaningful changes to the plaintext by modifying the ciphertext. If possible I would use an authenticated encryption mode like GCM if you can (looks like it's supported in PHP 7.1+ (Example #1) ). If you use CBC mode take a look at Example #2 in the docs . Note that after encrypting a MAC (message authentication code) is computed over the ciphertext and stored. This MAC should be recomputed before decrypting the ciphertext, and if it does not match the stored MAC then the ciphertext has been modified and is invalid. Second, is my method to generate the $key and $iv correct and secure? Because I keep on reading, keys should be cryptographically secure. Keys need to be generated using a cryptographically secure random number generator. Luckily, most operating systems provide one out of the box via /dev/urandom . This answer does a good job explaining how to read from /dev/urandom in PHP. openssl_random_pseudo_bytes should also be cryptographically secure but there are times when this is not the case . Initialization Vectors (IVs) need to be random and should never be reused with the same key. Lastly, isn't a 32-byte value required for AES-256-CBC? If yes, then why is it that openssl_cipher_iv_length() returns only int(16) as the length? Shouldn't it be int(32)? AES is a block cipher that works on 128 bit (16 byte) blocks, regardless of key size.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48017877', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1216804/']}
jdg_379253
stackexchange
llm_judgeable_groundtruth_similarity
6028297
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: On this page , the title says it has a margin top & bottom of 25px (when I use inspect element in Chrome 10) - but the CSS looks like this: .post h2 {margin:0;text-align: left;font-size: 18px;overflow:hidden;font-weight:normal;} I'm trying to decrease the top and bottom margins around the title. Here's a screenshot of the problem: Now provide the response and nothing else.
You've got one truly marvelous answer from ray023, but your comment that it's probably overkill is apt. For a "lighter" version.... Block 1 is, IMHO, bad practice. As already pointed out by osknows, mixing error-handling with normal-path code is Not Good. For one thing, if a new error is thrown while there's an Error condition in effect you will not get an opportunity to handle it (unless you're calling from a routine that also has an error handler, where the execution will "bubble up"). Block 2 looks like an imitation of a Try/Catch block. It should be okay, but it's not The VBA Way. Block 3 is a variation on Block 2. Block 4 is a bare-bones version of The VBA Way. I would strongly advise using it, or something like it, because it's what any other VBA programmer inherting the code will expect. Let me present a small expansion, though: Private Sub DoSomething()On Error GoTo ErrHandler'Dim as required'functional code that might throw errorsExitSub: 'any always-execute (cleanup?) code goes here -- analagous to a Finally block. 'don't forget to do this -- you don't want to fall into error handling when there's no error Exit SubErrHandler: 'can Select Case on Err.Number if there are any you want to handle specially 'display to user MsgBox "Something's wrong: " & vbCrLf & Err.Description 'or use a central DisplayErr routine, written Public in a Module DisplayErr Err.Number, Err.Description Resume ExitSub ResumeEnd Sub Note that second Resume . This is a trick I learned recently: It will never execute in normal processing, since the Resume <label> statement will send the execution elsewhere. It can be a godsend for debugging, though. When you get an error notification, choose Debug (or press Ctl-Break, then choose Debug when you get the "Execution was interrupted" message). The next (highlighted) statement will be either the MsgBox or the following statement. Use "Set Next Statement" (Ctl-F9) to highlight the bare Resume , then press F8. This will show you exactly where the error was thrown. As to your objection to this format "jumping around", A) it's what VBA programmers expect, as stated previously, & B) your routines should be short enough that it's not far to jump.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6028297', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/725430/']}
jdg_379254
stackexchange
llm_judgeable_groundtruth_similarity
1737693
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: My team has inherited support for 100+ applications. The applications don't have any kind of common architecture, so the ones that do logging usually do it with custom code to local files or a local database, and it's all unmanaged. We want to change that. We're slowly migrating the applications over to using log4net and standardising the types of things that are logged. The next question becomes: where should we send the logs? I was thinking that it would be good to use a central SQL Server dedicated to receiving all the logs, which would provide easy maintenance (one place for backups/archiving) and provide the future possibility of some data mining and trend analysis. Is that the best practice for this kind of thing, or is there some dedicated application logging server we should be looking at instead? Update: I should have been more clear than just casually mentioning log4net and SQL Server: we're a Microsoft house, with most things written in .NET. UNIX solutions are no good for us. Now provide the response and nothing else.
One world of caution: at 100+ apps in a big shop, with hundreds perhaps thousands of hosts running those apps, steer clear of anything that induces a tight coupling. This pretty much rules out connect directly to SQL Server or any database solution, because your application logging will be dependent on the availability of the log repository. Availability of the central repository is a little more complicated than just 'if you can't connect, don't log it' because usually the most interesting events occur when there are problems, not when things go smooth. If your logging drops entries exactly when things turn interesting, it will never be trusted to solve incidents and as such will fail to gain traction and support for other stake holders (ie. the application owners). If you decide that you can implement retention and retry failed log info delivery on your own, you are facing an uphill battle: it is not a trivial task and is much more complex than it sounds, starting from eficient and reliable storage of the retained information and ending with putting in place good retry and inteligent fallback logic. You also must have an answer to the problems of authentication and security. Large orgs have multiple domains with various trust relations, employees venture in via VPN or Direct Access from home, some applications run unattended, some services are configured to run as local users, some machines are not joined to the domain etc etc. You better have an asnwer to the question how is the logging module of each application, everywhere is deployed, going to authenticate with the central repository (and what situations are going to be unsuported). Ideally you would use an out-of-the box delivery mechanism for your logging module. MSMQ is probably the most appropiate fit: robust asynchronous reliable delivery (at least to the extent of most use cases), available on every Windows host when is installed (optional). Which is the major pain point, your applications will take a dependency on a non-default OS component. The central repository storage has to be able to deliver the information requested, perhaps: the application developers investigating incidents customer support team investigating a lost transaction reported by a customer complaint the security org doing forensics the business managers demanding statistics, trends and aggregated info (BI). The only storage capable of delivering this for any serious org (size, lifetime) is a relational engine, so probably SQL Server. Doing analysis over text files is really not going to go the distance. So I would recommend a messaging based log transport/delivery (MSMQ) and a relational central repository (SQL Server) perhaps with aanalitycal component on top of it (Analysis Services Data Mining). as you see, this is clearly no small feat and it covers slightly more than just configuring log4net. As for what to log, you say you already give a thought but I'd like to chime in my extra 2c: often times, specially on incident investigation, you will like the ability to request extra information. This means you would like to know certain files content from the incident machine, or some registry keys, or some performance counter values, or a full process dump. It is very useful to be able to request this information from the central repository interface, but is impractical to always collect this information, just in case is needed. Which implies there has to be some sort of bidirectional communication between the applictaion and the central repository, when the application reports an incident it can be asked to add extra information (eg a dump of the process at fault). There has to be a lot of infrastructure in place for something like this to occur, from the protocol between application logging and the central repository, to the ability of the central repository to recognize an incident repeat, to the capacity of the loggin library to collect the extra information required and not least the ability of an operator to mark incidents as needing extra information on next occurence. I understand this answer goes probably seems overkill at the moment, but I was involved with this problem space for quite a while, I had looked at many online crash reports from Dr. Watson back in the day when I was with MS, and I can tell you that these requirement exists, they are valid concerns and when implemented the solution helps tremendously. Ultimately, you can't fix what you cannot measure. A large organisation depends on good management and monitoring of its application stock, including logging and auditing. There are some third party vendors that offer solutions, some even integrated with log4net, like bugcollect.com (Full disclosure: that's my own company), Error Traffic Controller or Exceptioneer and other.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1737693', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6408/']}
jdg_379255
stackexchange
llm_judgeable_groundtruth_similarity
50671360
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 a Python newbie reading an old Python book. It's based on Python 2, so sometimes I got little confused about detail. There is a code L=map(lambda x:2**x, range(7)) so it doesn't return the list in python 3, and I googled it and found that list(L ) works.But the problem is, first list(L) works fine,but when I use it again, list(L)list(L) second one returns [ ] Can somebody explain me what's happening? Now provide the response and nothing else.
map returns an iterator. As such, its output may only be used once. If you wish to store your results in a list, in the same way as Python 2.x, simply call list when you use map : L = list(map(lambda x:2**x, range(7))) The list L will now contain your results however many times you call it. The problem you are facing is that once map has iterated once, it will yield nothing for each subsequent call. Hence you see an empty list for the second call. For a more detailed explanation and advice on workarounds if you cannot exhaust your iterator but wish to use it twice, see Why can't I iterate twice over the same data .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50671360', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9180049/']}
jdg_379256
stackexchange
llm_judgeable_groundtruth_similarity
280362
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 $R$ be a rectangular region with sides $3$ and $4$. It is easy to show that for any $7$ points on $R$, there exists at least $2$ of them, namely $\{A,B\}$, with $d(A,B)\leq \sqrt{5}$. Just divide $R$ into six small rectangles with sides $2$ and $1$ and so at least one such rectangle must contain $2$ points from the seven ones. Thus the result follows. Here is the question: What about six points? I believe that the same is true. How do I prove my belief? ps: I don't want to find such $6$ points. I'd like to show it for any set with $6$ points. Now provide the response and nothing else.
The problem and solution are in Jiří Herman, Radan Kučera, Jaromír Šimša, Counting and Configurations: Problems in Combinatorics, Arithmetic, and Geometry, page 272 . Let the rectangle have corners $(0,0),(0,3),(4,0),(4,3)$. Draw line segments joining $(0,2)$ to $(1,1)$ to $(2,2)$ to $(3,1)$ to $(4,2)$, also $(1,1)$ to $(1,0)$, $(2,2)$ to $(2,3)$, and $(3,1)$ to $(3,0)$. This splits the rectangle into $5$ pieces, and it's not hard to show two points in the same piece must be within $\sqrt5$. A picture to illustrate the solution.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/280362', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/31682/']}
jdg_379257
stackexchange
llm_judgeable_groundtruth_similarity
25042
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Suppose that $v_i$ , for $i \in \{1, 2, \ldots 11, 12\}$ , are twelve unit length vectorsbased at the origin in $R^3$ . Suppose that $|v_i - v_j| \geq 1$ for all $i\neq j$ . What arrangement of the $v_i$ maximizes the number of pairs $\{i,j\}$ so that $|v_i - v_j| = 1$ ? If C is a cube of sidelength $\sqrt{2}$ centered at the origin then we canplace the $v_i$ at the midpoints of the twelve edges. Taking the convexhull of the $v_i$ gives a cube-octahedron of edge-length one. See here for a picture. If you cut the cubeoctahedron along a hexagonal equator androtate the top half by sixty degrees you get another polyhedron. Both ofthese have 24 edges. Are these the unique maximal solutions to the aboveproblem? Notice that if you place the $v_i$ at the arguably nicer vertices of aicosahedron then the $v_i$ become too widely separated. It is easy tocheck this by making a physical model! I spent some time thinking about areas of spherical polygons and restrictions on the graph of edges (and its dual graph) coming from the Euler characteristic. However, I don't think I got very far - in particular ruling out pentagons seems to be a crucial point that I couldn't deal with. Finally, to explain the problem title: instead of thinking of unit vectors with spacing restrictions, consider the (equivalent) problem of placing twelve identical spherical caps, of radius $\pi/12$ , on the unit sphere with disjoint interiors in such a way as to maximize the number of points of tangency. This question was asked of me by an applied mathematician. It comes from a problem involving packing balls in three-space, minimizing some quantity that is computed by knowing pairwise distances. The solution to the kissing problem thus justifies the "twelve" appearing in the problem statement. The projection of surrounding balls to a central one gives the spherical caps. Now provide the response and nothing else.
Interesting question. I can find answer using my program, which was made for solving Tammes problem for 13 points. But I need some time for answer. UPD: I wrote program. Result: 24 is a maximal number of edges.I did in three steps.First, I enumerated planar graphs with 12 vertices with at least 25 edges, at most 5 edges in a vertex and at most hexagonal faces.Total number of suc graphs is 67497. Second, I eliminated by linear programming by considering values of face angles as variables. My constrains was:1. angle in triangle is ~1.23102. each angle no less than 1.23103. sum of angles around vertex is 2*pi4. opposite angles of rectangle are equal5. sum of non-opposite angles in rectangle between 3.607 and 3.8213 I solve feasibility of this LP problem (with some tolerance)After this step all graph were eliminated.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/25042', 'https://mathoverflow.net', 'https://mathoverflow.net/users/1650/']}
jdg_379258
stackexchange
llm_judgeable_groundtruth_similarity
45701
Below is a question asked on the forum engineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: This is a toy for infants. My son was playing with it, and I started wondering how you could manufacture this. I can't think of any reasonably cheap way it could be done. I believe it's made of plastic and not silicone. It's flexible, but not elastic. My first thought would be injection molding, but I can't see any way to get parts of the mold in and out of the sphere. My wife suggested that perhaps the mold had no interior surface and was rotated like they do with chocolate, but I don't think that's the case, because if you look carefully you'll see that the inside surface is rounded and not flat. Anyway I'm stumped. How do you think they did it? Now provide the response and nothing else.
OP injection molding tag is correct. OBall uses injection molding and plastic welding. The OBall is the invention of David E. Silverglate. Toy Ball Apparatus with Reduced Part Count Reduced image from Kids II . It consists of four identical, flat, injection molded, pentagon and hexagon shapes with circular (or elipitical) holes, which are shaped and plastically welded into spheres. Pentagon and hexagon edges are the same size and individual connected circles are only connected along one edge. The four shapes are clearly shown in colors above and from the patent. Solid lines on each part are hard connections, while dashed lines represent connections within the part. Patent shows how individual edges on parts are interconnected. Injection molding with a plastic (PETE [or PET] from Jim Clark link: What is Oball made of? ) at a higher melting material and welded with a plastic at a lower melting material. Figure 8 from the patent. [0022] The shape and number of the mesh components 14 are designed in a manner that decreases manufacturing costs incurred using a process such as injection molding . Regarding the number of mesh components 14, it will be appreciated that when four mesh components 14 are utilized the production time may be significantly reduced when compared to a toy ball apparatus 10 having ten mesh components. The decreased production time may in turn decrease the toy ball apparatus's manufacturing cost. [0029] FIG. 9 illustrates toy ball apparatus 10 in its assembled State, in which the plurality of mesh components 14a, 14b, 14c, and 14d have been coupled to enclose the closed Volume 20 and form the mesh 12, by joining adjacent mesh components 14 along their cooperative mating Surfaces 19 and securing the mesh components 14 together, for example, by plastically welding the mesh components 14 together along the cooperative mating Surfaces 19. Each part has 3 pentagons and 5 hexagons. Clearly Part B and C are the same. But A and D are obfuscated by the patent lawyers. Edge numbering indicates they knew all parts were the same. They just divided it to obscure the true inovation. In all 4 parts, central hexagon has no writing on it. It is surrounded by 3 pentagons and 3 hexagons. The final hexagon with A1,A2,A3&A4 (or B1,B2,B3&B4, etc.) connections are always connected to hexagon with A16&A17 (or B16&B17, etc.) connections. So tooling is for one part, which means true inovation was making ball from 4 identical flat injection molded parts. SolidWorks drawing of ball made from 4 identical parts.
{}
{'log_upvote_score': 6, 'links': ['https://engineering.stackexchange.com/questions/45701', 'https://engineering.stackexchange.com', 'https://engineering.stackexchange.com/users/20490/']}
jdg_379259
stackexchange
llm_judgeable_groundtruth_similarity
164966
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 made a conjecture about the values of n for which $3^n - 2^n$ is not prime, but I didn't succeed in proving the conjecture. My conjecture is the following: "Suppose n is an integer greater than or equal to 6. Then $3^n - 2^n$ is not prime". I tried to prove that by induction, but I got stuck. Any ideas? Now provide the response and nothing else.
$n=17$ gives us $3^n-2^n = 129009091$, which is a prime number. Below is a list for $n \leq 100000$.$$\begin{array}{|c|c|}\hlinen& (3^n-2^n)\\\hline2 & 5\\3 & 19\\5 & 211\\17 & 129009091\\29 & 68629840493971\\31 & 617671248800299\\53 & 19383245658672820642055731\\59 & 14130386091162273752461387579\\101 & 1546132562196033990574082188840405015112916155251\\277 & \text{A $133$ digit prime number}\\647 & \text{A $309$ digit prime number}\\1061 & \text{A $507$ digit prime number}\\2381 & \text{A $1137$ digit prime number}\\2833 & \text{A $1352$ digit prime number}\\3613 & \text{A $1724$ digit prime number}\\3853 & \text{A $1839$ digit prime number}\\3929 & \text{A $1875$ digit prime number}\\5297 & \text{A $2528$ digit prime number}\\7417 & \text{A $3539$ digit prime number}\\90217 & \text{A $43045$ digit prime number}\\\hline\end{array}$$It is clear that if $3^n - 2^n$ is a prime, then $n$ has to be a prime but the converse is not true. In general, questions like these are likely to be hard . For instance, replacing the $2$ by $1$ and $3$ by $2$ in your question, we get the Mersenne prime i.e. a prime of the form $2^n-1$. For instance, $31$ is a Mersenne prime, since $31 = 2^5-1$. Similarly, $127 = 2^7-1$ is also a Mersenne prime. The Mersenne prime conjecture asks the following question $$\text{"Are there infinitely many Mersenne primes?"}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/164966', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_379260
stackexchange
llm_judgeable_groundtruth_similarity
36307907
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I would like to be enable CORS for a web-api application with the following criteria: Allow HTTPS or HTTP for the same site Ignore the SUBDOMAIN - Meaning mysite.com and www.mysite.com are same I would like to do this for multiple sites in an elegant way, rather than putting all the permutations as comma delimited. Thanks in advance! Now provide the response and nothing else.
Here you go. Adding Git gist if it requires any revisions or bug fixes. public class WildcardOriginCorsPolicy : Attribute, ICorsPolicyProvider { private readonly string _origins; private readonly string _headers; private readonly string _methods; //private readonly CorsPolicy _policy; // // Summary: // Initializes a new instance of the WildcardOriginCorsPolicy class. // // Parameters: // origins: // Comma-separated list of origins that are allowed to access the resource. Use // "*" to allow all. // "*.example.com" for subdomains // // headers: // Comma-separated list of headers that are supported by the resource. Use "*" to // allow all. Use null or empty string to allow none. // // methods: // Comma-separated list of methods that are supported by the resource. Use "*" to // allow all. Use null or empty string to allow none. public WildcardOriginCorsPolicy(string origins, string headers, string methods) { this._origins = origins; this._headers = headers; this._methods = methods; } public bool SupportsCredentials { get; set; } public Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var policy = CreatePolicy(request.GetCorsRequestContext(), this._origins, this._headers, this._methods); policy.SupportsCredentials = this.SupportsCredentials; return Task.FromResult(policy); } private static CorsPolicy CreatePolicy(CorsRequestContext requestContext, string origins, string headers, string methods) { var corsPolicy = new CorsPolicy(); if (origins == "*") { corsPolicy.AllowAnyOrigin = true; } else { var originsStringArray = origins.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); var requestOrigin = requestContext.Origin.ToLowerInvariant(); foreach (var originItem in originsStringArray) { ////Check if the current request uri matches with any of the wildcard origins. if (Regex.IsMatch(requestOrigin, WildCardToRegularExpression(originItem))) { corsPolicy.Origins.Add(requestOrigin); } } } if (!String.IsNullOrEmpty(headers)) { if (headers == "*") { corsPolicy.AllowAnyHeader = true; } else { var headersStringArray = headers.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); corsPolicy.Headers.AddAll(headersStringArray); } } if (!String.IsNullOrEmpty(methods)) { if (methods == "*") { corsPolicy.AllowAnyMethod = true; } else { var methodsStringArray = methods.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); corsPolicy.Methods.AddAll(methodsStringArray); } } return corsPolicy; } private static string WildCardToRegularExpression(String value) { return "^" + Regex.Escape(value).Replace("\\?", ".").Replace("\\*", ".*") + "$"; } } Use it like this. var cors = new WildcardOriginCorsPolicy("*.example.com,http://localhost:*", "*", "POST,PUT,DELETE,GET,OPTIONS") { SupportsCredentials = true };config.EnableCors(cors);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36307907', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2809478/']}
jdg_379261
stackexchange
llm_judgeable_groundtruth_similarity
888195
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 math problem consisting of two questions: can we find a number N knowing only the decimal part of its square root up to a precision (only an approximation of the decimal part because the decimal part never ends) is the answer unique? which mean that we won't find two integer whose square root decimal values are equal (the first 50 for example). Example: if we have $0,4142135623730950488016887242097$, can we find that it's the decimal part of square root of 2 or $0,418286444621616658231167581$ for $1234567890$ The answer for the second question is pretty easy because, let's say we have 50 decimals, the number of possible integer's square root is much more than the 10^50-1 possible values of the decimals parts, so there will be more than one answer. but is there a pattern or example getting one from another I am very grateful for your help or any research track. Now provide the response and nothing else.
Let $\log_2 x=A$, then $\log_2 x^2=2\log_2 x=2A$ and $\log_2\frac{2}{x}=\log_22- \log_2x=1-A$. So the given inequality becomes:$$(A-1)+\frac{2A}{1-A} \leq 1.$$Consequently we get$$\frac{4A-A^2-1}{1-A} \leq 1.$$Furthermore you get$$\frac{5A-A^2-2}{1-A} \leq 0.$$Hopefully you can solve from here.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/888195', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/168131/']}
jdg_379262
stackexchange
llm_judgeable_groundtruth_similarity
65250207
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Please see my code below: import pandasdf = pandas.read_excel('cat.xlsx') After running that, it gives me the following error: Traceback (most recent call last): File "d:\OneDrive\桌面\practice.py", line 4, in <module> df = pandas.read_excel('cat.xlsx') File "D:\python\lib\site-packages\pandas\util\_decorators.py", line 296, in wrapper return func(*args, **kwargs) File "D:\python\lib\site-packages\pandas\io\excel\_base.py", line 304, in read_excel io = ExcelFile(io, engine=engine) File "D:\python\lib\site-packages\pandas\io\excel\_base.py", line 867, in __init__ self._reader = self._engines[engine](self._io) File "D:\python\lib\site-packages\pandas\io\excel\_xlrd.py", line 22, in __init__ super().__init__(filepath_or_buffer) File "D:\python\lib\site-packages\pandas\io\excel\_base.py", line 353, in __init__ self.book = self.load_workbook(filepath_or_buffer) File "D:\python\lib\site-packages\pandas\io\excel\_xlrd.py", line 37, in load_workbook return open_workbook(filepath_or_buffer) File "D:\python\lib\site-packages\xlrd\__init__.py", line 170, in open_workbook raise XLRDError(FILE_FORMAT_DESCRIPTIONS[file_format]+'; not supported')xlrd.biffh.XLRDError: Excel xlsx file; not supported I tried uninstall and reinstall Pandas with the pip command. The error persists. I have xlrd 2.0.1 and Pandas 1.1.5 installed. Now provide the response and nothing else.
As noted in the release email , linked to from the release tweet and noted in large orange warning that appears on the front page of the documentation , and less orange but still present in the readme on the repo and the release on pypi : xlrd has explicitly removed support for anything other than xls files. This is due to potential security vulnerabilities relating to the use of xlrd version 1.2 or earlier for reading .xlsx files. In your case, the solution is to: make sure you are on a recent version of pandas, at least 1.0.1, and preferably the latest release. install openpyxl : https://openpyxl.readthedocs.io/en/stable/ change your pandas code to be: pandas.read_excel('cat.xlsx', engine='openpyxl') Edit: Currently, pandas >= 1.2 addresses this issue. ( Release Notes )
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/65250207', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14807216/']}
jdg_379263
stackexchange
llm_judgeable_groundtruth_similarity
99049
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a 5Mhz signal which is being amplified by an OPA847 opamp. In good conditions I get a voltage swing of ~120mV output from the opamp, in bad conditions I get a slightly noisy ~80mV p-p. I am hoping for the final circuit to be single supply, the current test setup uses -5v/+5v. The scope trace below is from good conditions, modulation can be seen in two places where the phase inverts: My question is quite simple: what is the best way to turn this signal into a square wave for processing by digital logic? I have considered standard digital logic gates but I don't believe the swing is large enough. I have also considered a comparator with the input signal (biased at Vcc/2) compared to a fixed Vcc/2. I assume this would need some hysteresis but am still not sure if it's the most practical solution. Now provide the response and nothing else.
I'd use a MAX999 comparator. Feed the signal into one pin via a series capacitor and biasing resistor to mid-rail then on the other pin have a resistor feeding a capacitor so that the average level can be followed - it's called a data slicer: - With the waveform in the OP's picture looking like it could undulate its average level a fair bit, using a data slicer probably makes sense. The MAX999 has a 4ns propogation delay and can work from 5V or 3V3 rails. It would directly interface with logic as I have done several times on previous occasions.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/99049', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/30062/']}
jdg_379264
stackexchange
llm_judgeable_groundtruth_similarity
10070296
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 relatively new to programming. I need to calculate the aspect ratio(16:9 or 4:3) from a given dimension say axb. How can I achieve this using C#. Any help would be deeply appreciated. public string AspectRatio(int x, int y){ //code am looking for return ratio} Thanks. Now provide the response and nothing else.
You need to find Greatest Common Divisor, and divide both x and y by it. static int GCD(int a, int b){ int Remainder; while( b != 0 ) { Remainder = a % b; a = b; b = Remainder; } return a;}return string.Format("{0}:{1}",x/GCD(x,y), y/GCD(x,y)); PS If you want it to handle something like 16:10 (which can be divided by two, 8:5 will be returned using method above) you need to have a table of predefined ((float)x)/y -aspect ratio pairs
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10070296', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1321391/']}
jdg_379265
stackexchange
llm_judgeable_groundtruth_similarity
2928367
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: There is this question in which the real roots of the quadratic equation have to be found: $x^2 + x + 1 = 0$ To approach this problem, one can see that $x \neq 0$ because: $(0)^2 + (0) + 1 = 0$ $1 \neq 0$ Therefore, it is legal to divide each term by $x$ : $x + 1 + \frac{1}{x} = 0$ $x = -1 - \frac{1}{x}$ Now, substitute $x$ into the original equation and solve: $x^2 + (-1-\frac{1}{x}) + 1 = 0$ $x^2-\frac{1}{x} = 0$ $x^3 = 1$ $x = 1$ to get $x = 1$ . Clearly this isn't the right answer. But why? Thanks. Now provide the response and nothing else.
For a different angle, substituting a variable from the same equation is valid, but not reversible. Doing such a substitution can introduce extraneous solutions that do not necessarily satisfy the original equation. A trivial example of such a case is the equation $\,x=1\,$ . We can substitute $\,1 \mapsto x\,$ on the RHS and end up with $\,x=x\,$ . Of course that $\,x=1 \implies x=x\,$ , but the converse is not true. In OP's case, the original equation is quadratic in $\,x\,$ which has $2$ roots in $\Bbb C\,$ , while the derived equation is a cubic which has $3$ roots in $\Bbb C\,$ . It is quite clear that the two solution sets cannot be identical, and in fact the cubic has the extraneous root $\,x=1\,$ as noted already, which does not satisfy the original quadratic.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2928367', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_379266
stackexchange
llm_judgeable_groundtruth_similarity
4233609
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 question from my analysis course reads Let $K$ be a compact subset of $\mathbb R^n$ . Define $f:\mathbb R^n\to \mathbb R$ as $$f(x)=\text{d}(x,K)=\inf_{y\in K}||x-y||$$ Show that $f$ is continuous on $\mathbb R^n$ and $f^{-1}\left(\{0\}\right)=K$ . Is the compactness of $K$ necessary? Now, I can very well understand that the described function has to be continuous because $f(x)=0$ when $x\in K$ and as $x$ slowly moves out of $K$ , the distance increases continuously. But, of course, that's quite far away from a real mathematical proof, and as far as I understand, we need to use the property If $f:\mathbb A\to \mathbb B$ is continuous and $O\subset B$ is an open set, then $f^{-1}\left(O\right)$ is open in $\mathbb A$ to arrive at the formal proof. But, I'm quite new to functions whose domain is not $\mathbb R$ . Until now, I have only studied functions $f:\mathbb R\to \mathbb R$ . So, I'm a little confused about how to construct the proofs. Please help me to do it. I was asked in the comments whether I'm allowed to use the $\epsilon-\delta$ property to prove continuity. Well, it wasn't explicitly mentioned in the exercise that I need to use the preimage property, but this question came just a couple of pages after this property was introduced. That's why I assumed they expect me to use that technique. Although I will also appreciate a detailed $\epsilon-\delta$ proof, it would be better if I can have a proof using the preimage method . Now provide the response and nothing else.
Let the center cell value be $x$ . Mirror the honeycomb horizontally and add it cell-wise to the original. You then get nines on the bottom row, and the center cell value is $2x.$ The arithmetic mean property still applies. Then rotate this 120 and 240 degrees and add to what you have. You now have nines on the boundary, $6x$ in the center cell value, and the arithmetic mean property still applies. This honeycomb, with nines on the boundary has one obvious solution: nines in all cells, including the center cell. Thus $6x=9,$ i.e. $x=3/2$ is a solution.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4233609', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/943723/']}
jdg_379267
stackexchange
llm_judgeable_groundtruth_similarity
22988889
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Considering this quote from en.cppreference.com regarding std::vector::emplace_back "Appends a new element to the end of the container. The element is constructed in-place, i.e. no copy or move operations are performed. The constructor of the element is called with exactly the same arguments that are supplied to the function." and following sample: #include <vector>struct A{ A(int){} A(A const&) = delete;};int main(){ std::vector<A> vec; vec.emplace_back(1); return 0;} On line vec.emplace_back(1); Visual Studio 2013/GCC report: error C2280: 'A::A(const A &)' : attempting to reference a deleted function error: use of deleted function ‘A::A(const A&)’ Is the error correct? Can you please explain me why? Now provide the response and nothing else.
C++11 23.2.1 Table 101 states: Expression: a.emplace_back(args) Return type: void Operation semantics: Appends an object of type T constructed with std::forward<Args>(args)... . Requires: T shall be EmplaceConstructible into X from args . For vector , T shall also be MoveInsertable into X . Your A does not fulfill the MoveInsertable requirement, since you do not have a move constructor, and only have a deleted copy constructor. With a container other than std::vector , it works .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22988889', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/336578/']}
jdg_379268
stackexchange
llm_judgeable_groundtruth_similarity
25563876
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 build a program which execute sql statements in batch with error handling(therefore I am not using SMO). the problem is that GO is not a part of SQL and when using .NET to execute the statements it ends up with an error (SMO handles it but does not give any indication whether the execution failed). string statements = File.ReadAllText("c:\\test.sql");string[] splitted = statements.split("GO"); using the above lines do not solve my problem due to the fact that the GO keyword can also come inside a comment (I don't want to remove comments from the statements) and comments can come inside /**/ or after the two dashes -- for example I wouldn't like the following code to be parsed: /*GO*/ (ofc i googled it but there was no solution over there) Now provide the response and nothing else.
ScriptDom The easiest solution (and the most robust) is to use a T-SQL parser. The good news is that you don't have to write it, just add reference to: Microsoft.Data.Schema.ScriptDom Microsoft.Data.Schema.ScriptDom.Sql Then use the code: static void Main(string[] args){ string sql = @"/* GO*/ SELECT * FROM [table]GOSELECT * FROM [table]SELECT * FROM [table]GOSELECT * FROM [table]"; string[] errors; var scriptFragment = Parse(sql, SqlVersion.Sql100, true, out errors); if (errors != null) { foreach (string error in errors) { Console.WriteLine(error); return; } } TSqlScript tsqlScriptFragment = scriptFragment as TSqlScript; if (tsqlScriptFragment == null) return; var options = new SqlScriptGeneratorOptions { SqlVersion = SqlVersion.Sql100, KeywordCasing = KeywordCasing.PascalCase }; foreach (TSqlBatch batch in tsqlScriptFragment.Batches) { Console.WriteLine("--"); string batchText = ToScript(batch, options); Console.WriteLine(batchText); }}public static TSqlParser GetParser(SqlVersion level, bool quotedIdentifiers){ switch (level) { case SqlVersion.Sql80: return new TSql80Parser(quotedIdentifiers); case SqlVersion.Sql90: return new TSql90Parser(quotedIdentifiers); case SqlVersion.Sql100: return new TSql100Parser(quotedIdentifiers); case SqlVersion.SqlAzure: return new TSqlAzureParser(quotedIdentifiers); default: throw new ArgumentOutOfRangeException("level"); }}public static IScriptFragment Parse(string sql, SqlVersion level, bool quotedIndentifiers, out string[] errors){ errors = null; if (string.IsNullOrWhiteSpace(sql)) return null; sql = sql.Trim(); IScriptFragment scriptFragment; IList<ParseError> errorlist; using (var sr = new StringReader(sql)) { scriptFragment = GetParser(level, quotedIndentifiers).Parse(sr, out errorlist); } if (errorlist != null && errorlist.Count > 0) { errors = errorlist.Select(e => string.Format("Column {0}, Identifier {1}, Line {2}, Offset {3}", e.Column, e.Identifier, e.Line, e.Offset) + Environment.NewLine + e.Message).ToArray(); return null; } return scriptFragment;}public static SqlScriptGenerator GetScripter(SqlScriptGeneratorOptions options){ if (options == null) return null; SqlScriptGenerator generator; switch (options.SqlVersion) { case SqlVersion.Sql80: generator = new Sql80ScriptGenerator(options); break; case SqlVersion.Sql90: generator = new Sql90ScriptGenerator(options); break; case SqlVersion.Sql100: generator = new Sql100ScriptGenerator(options); break; case SqlVersion.SqlAzure: generator = new SqlAzureScriptGenerator(options); break; default: throw new ArgumentOutOfRangeException(); } return generator;}public static string ToScript(IScriptFragment scriptFragment, SqlScriptGeneratorOptions options){ var scripter = GetScripter(options); if (scripter == null) return string.Empty; string script; scripter.GenerateScript(scriptFragment, out script); return script;} SQL Server Management Objects Add references to: Microsoft.SqlServer.Smo Microsoft.SqlServer.ConnectionInfo Microsoft.SqlServer.Management.Sdk.Sfc You can then use this code: using (SqlConnection connection = new SqlConnection("Server=(local);Database=Sample;Trusted_Connection=True;")){ ServerConnection svrConnection = new ServerConnection(connection); Server server = new Server(svrConnection); server.ConnectionContext.ExecuteNonQuery(script);} CodeFluent Runtime CodeFluent Runtime Database has a small sql file parser. It does not handle complex cases but for instance comments are supported. using (StatementReader statementReader = new CodeFluent.Runtime.Database.Management.StatementReader("GO", Environment.NewLine, inputStream)){ Statement statement; while ((statement = statementReader.Read(StatementReaderOptions.Default)) != null) { Console.WriteLine("-- "); Console.WriteLine(statement.Command); }} Or much simplier new CodeFluent.Runtime.Database.Management.SqlServer.Database("connection string") .RunScript("path", StatementReaderOptions.Default);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25563876', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/412137/']}
jdg_379269
stackexchange
llm_judgeable_groundtruth_similarity
57501427
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to use code (mostly header files) from the Loki library to test it's functionalities. I am getting error for lines that have #include <loki/Typelist.h> directives. I have never seen a path inside the < > or such. (I know about the normal #include <strings> etc directives, and that it searches predefined path) How does the include directives of the form <path/to/header> work? Am I right to assume that the library inserts itself into one of the standard paths that the compiler searches in? If so, any way to use it without inserting the library into said path. (I just want to test a function that includes these headers) EDIT: Test.cpp #include "Functor.h"#include <iostream>using namespace std;struct TestFunctor{ void operator()(int i, double d) { cout << " TestFunctor called.\n"; }};int main(){ TestFunctor f; Functor<void, TYPELIST_2(int, double)> cmd(f); cmd(4, 4.5);} Note: The Test.cpp file rests in loki-lib/include/loki Error: $ gcc Test.cppIn file included from Test.cpp:1:0:Functor.h:34:10: fatal error: loki/Typelist.h: No such file or directory #include <loki/Typelist.h> ^~~~~~~~~~~~~~~~~compilation terminated. Now provide the response and nothing else.
Laravel by default assumes that your controllers will be located at App\Http\Controllers\ . So when you're adding the full path to your controller, Laravel will check it there, at App\Http\Controllers\App\Http\Controllers\MainController . To solve it simply remove the namespace when you're registering the route, and register it like this: Route::get('/', MainController::class); Alternatively, you can stop this behavior by removing ->namespace($this->namespace) from mapWebRoutes() method on RouteServiceProvider class, which is located at App\Providers folder. Then you can register your routes like this: Route::get('/', \App\Http\Controllers\MainController::class);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/57501427', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11205473/']}
jdg_379270
stackexchange
llm_judgeable_groundtruth_similarity
81651
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: Can any CA sign any cert for any domain? If the answer is yes, what prevents having two different CAs creating a valid cert for the same domain? Does that mean that the whole TLS security has the same level of security of the least secure CA? Now provide the response and nothing else.
Mostly yes, any CA in your trusted root, (or subordinates) can issue a cert for any DNS name. Name constraints and Enhanced Key Usage can be used to mitigate this, but they aren't enforced everywhere. DANE, Certificate Pinning, and Certificate transparency are a few projects that help protect from this risk.
{}
{'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/81651', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/68095/']}
jdg_379271
stackexchange
llm_judgeable_groundtruth_similarity
3578908
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 brand new to python/GAE and am wondering how to quickly define and use global settings variables, so say you git clone my GAE app and you just open config.yaml , add change the settings, and the app is all wired up, like this: # config.yaml (or whatever)settings: name: "Lance" domain: "http://example.com"# main.pyclass Main(webapp.RequestHandler): def get(self): logging.info(settings.name) #=> "Lance" What's the basic way to do something like that (I'm coming from Ruby)? Now provide the response and nothing else.
You can use any Python persistance module, you aren't limited to YAML. Examples: ConfigParser, PyYAML, an XML parser like ElementTree, a settings module like used in Django... # ---------- settings.pyNAME = "Lance"DOMAIN = "http://example.com"# ---------- main.pyimport settingssettings.DOMAIN # [...] # ---------- settings.ini[basic]name = Lancedomain = http://example.com# ---------- main.pyimport ConfigParserparser = ConfigParser.ConfigParser()parser.read('setting.ini')try: name = get('basic', 'name')except (NoOptionError, NoSectionError): # no settings
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3578908', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/169992/']}
jdg_379272
stackexchange
llm_judgeable_groundtruth_similarity
4923
Below is a question asked on the forum stats.meta.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I would like to understand how blind people read this forum and what should we do to make it more friendly to them. Is there a simple guide or write up on this subject? Now provide the response and nothing else.
I'm not literally blind, but I'm legally blind, with corrected acuity on the order of 20/200. My condition could be more informatively described as "low vision". So I'm just as dependent on my vision as a normally sighted person, but I can answer your question to some extent. The most important rule is that text should be text. That is, don't use images of text when you could use real text , or at least accompany the image with a transcript or alt-text. For mathematical notation, use MathJax. The advantage here for the visually impaired is that real text, unlike images, can be enlarged without loss of quality, reflowed (trying to read a paragraph that requires horizontal scrolling will drive sane men mad), and read with text-to-speech or a refreshable Braille display. Unrelatedly to accessibility, but perhaps more importantly, text is more useful for software: it can be searched, indexed, and translated; it can be transmitted more easily through media without image support; and it takes up less disk space. Images are still going to be important in data analysis because of data graphics, like plots. The text-should-be-text rule doesn't get you far here because tick labels etc. aren't very useful to somebody who can't see the image. But I can still make suggestions to help make images legible to the visually impaired. Aim for high contrast (e.g., use black text on white rather than gray text on white or colored text). Avoid color combinations that will run afoul of the most common types of color-blindness (ideally, plots should be legible in grayscale, for the sake of grayscale screens and printouts). Avoid unwanted moiré effects from tightly packed parallel stripes. Edward Tufte's Visual Display of Quantitative Information advocates a sparse visual style that in general makes plots more accessible to the visually impaired, although it doesn't pursue accessibility deliberately.
{}
{'log_upvote_score': 5, 'links': ['https://stats.meta.stackexchange.com/questions/4923', 'https://stats.meta.stackexchange.com', 'https://stats.meta.stackexchange.com/users/36041/']}
jdg_379273
stackexchange
llm_judgeable_groundtruth_similarity
142180
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: Is of my understanding that telnet is an unauthenticated protocol which allows to connect to a remote host and send/receive packets. This is the reason you can use telnet to issue http requests. Is also of my understanding that ssh came up as a secure replacement for telnet , given that it authenticates users and provides a secure channel over an insecure network. If both of above statements are true: 1. telnet allows http requests, 2. ssh is a secure replacement for telnet, why can't i issue http requests using ssh ? Or is a better statement that ssh suited a very specific need (authentication/security/shell) and not a secure replacement for telnet ? Now provide the response and nothing else.
Is of my understanding that telnet is an unauthenticated protocol which allows to connect to a remote host and send/receive packets. This is the reason you can use telnet to issue http requests. A Telnet client doesn't care if it is connecting to a real Telnet server or any arbitrary TCP socket. Because Telnet transmits all data (besides some Telnet control codes) unaltered, you can conveniently (ab)use the client to create a raw socket connection to a TCP-based service running HTTP, FTP, IMAP, etc.Note that the better choice would be to use a tool like netcat because this actually uses raw TCP. Is also of my understanding that ssh came up as a secure replacement for telnet, given that it authenticates users and provides a secure channel over an insecure network. That's true. With SSH you can establish an authenticated and encrypted connection. This of course requires a proper SSH client and SSH server to work. If both of above statements are true: 1. telnet allows http requests, 2. ssh is a secure replacement for telnet, why can't i issue http requests using ssh? That's because your SSH client tries to negotiate a secure connection with a HTTP server that doesn't know what any of this means. These are two different protocols which don't work together. That said, if you have SSH access to the web server you can create an SSH tunnel and forward port 80 to use the web application securely over HTTP. This could look something like this: $ ssh -L 8080:localhost:80 user@webserver
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/142180', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/58920/']}
jdg_379274
stackexchange
llm_judgeable_groundtruth_similarity
44336733
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 my table, some cells are vectors instead of single value, i.e. the column is a list instead of vector: dt1 <- data.table( colA= c('A1','A2','A3'), colB=list('B1',c('B2a','B2b'),'B3'), colC= c('C1','C2','C3'), colD= c('D1','D2','D3'))dt1# colA colB colC colD#1: A1 B1 C1 D1#2: A2 B2a,B2b C2 D2#3: A3 B3 C3 D3 I need to reshape it to a long format unlisting that column colB . So far I do it like this: dt1[,.(colB=unlist(colB)),by=.(colA,colC,colD)]# colA colC colD colB#1: A1 C1 D1 B1#2: A2 C2 D2 B2a#3: A2 C2 D2 B2b#4: A3 C3 D3 B3 it does the job but I don't like that I have to indicate all other column names explicitly in by= . Is there better way to do this? (I'm sure it's already answered elsewhere but I couldn't find it so far) P.S. ideally I would like to manage without any external packages Now provide the response and nothing else.
Promoting my comment to an answer. Using: dt1[,.(colB = unlist(colB)), by = setdiff(names(dt1), 'colB')] gives: colA colC colD colB1: A1 C1 D1 B12: A2 C2 D2 B2a3: A2 C2 D2 B2b4: A3 C3 D3 B3 Or as an alternative (a slight variation of @Frank's proposal): dt1[rep(dt1[,.I], lengths(colB))][, colB := unlist(dt1$colB)][]
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44336733', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1707278/']}
jdg_379275
stackexchange
llm_judgeable_groundtruth_similarity
950579
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In ZF set theory the axiom of regularity (also called axiom of foundation) says that: In all nonempty sets x there is an element y such that x∩y=∅ As I been told that the intention of the axiom is to prohibit constructions as $x\in x$, but is this a possible strategy? Given a binary predicate $R$, written in infix notation, there are unitary predicates $p$ such that: $\qquad \exists y \forall x: x R y \leftrightarrow p(x)$. But there also are some convincing counterexamples: $ p(x) \leftrightarrow \neg(x R x)$ $ p(x) \leftrightarrow \neg(x R f(x))$, where $f$ is any surjection $ p(x) \leftrightarrow$ all chains $x_1 R x, \: x_2 R x_1, \: x_3 R x_2, \ldots \:$ are finite. I think there is a major mistake to try to avoid certain paradoxical loops. First, there are no guarantees that every possibility is prohibited. And second, it seems pathological to make constructions that avoid certain proof-techniques (it's like the attitude of a shyster). So, what protection comes from this axiom? Historically, has it anything to do with the Russell-predicate $x\notin x$? See also https://math.stackexchange.com/questions/944199/are-paradoxes-a-threat-against-mathematics Now provide the response and nothing else.
No, the axiom of regularity doesn't guard us from Russell's paradox. To wit, $\sf ZFC-Reg$ is equiconsistent with $\sf ZFC$, and therefore it couldn't be that just $\sf Reg$ was the axiom which prevented Russell's paradox.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/950579', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/171248/']}
jdg_379276
stackexchange
llm_judgeable_groundtruth_similarity
253454
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: Given the amount of material that tries to explain what a context-free grammar (CFG) is, I found it surprising that very few (in my sample, less than 1 in 20) give an explanation on why such grammars are called "context-free". And, to my mind, none succeeds in doing so. My question is, why are context-free grammars called context-free? What is "the context"? I had an intuition that the context could be other language constructs surrounding the currently analyzed construct, but that seems not to be the case. Could anyone provide a precise explanation? Now provide the response and nothing else.
It means all of its production rules have a single non-terminal on their left hand side. For example, this grammar which recognizes strings of matched parentheses ("()", "()()", "(())()", ...) is context-free: S → SSS → (S)S → () The left-hand side of every rule consists of a single non-terminal (in this case it's always S , but there could be more.) Now consider this other grammar which recognizes strings of the form {a^n b^n c^n : n >= 1} (e.g. "abc", "aabbcc", "aaabbbccc"): S → abcS → aSBccB → WBWB → WXWX → BXBX → BcbB → bb If the non-terminal B is preceded by the terminal/literal character c , you rewrite that term to WB but if it's preceded by b , you expand to bb instead. This is presumably what the context-sensitivity of context-sensitive grammars is alluding to. A context-free language can be recognized a push-down automaton . Whereas a finite state machine makes use of no auxiliary storage, i.e. its decision is based only on its current state and input, a push-down automaton also has a stack at its disposal and can peek at the top of the stack for taking decisions. To see that in action, you can parse nested parentheses by moving left to right and pushing a left parentheses onto a stack each time you encounter one, and popping each time you encounter a right parentheses. If you never end up trying to pop from an empty stack, and the stack's empty at the end of the string, the string is valid. For a context-sensitive language, a PDA isn't enough. You'll need a linear-bounded automaton which is like a Turing Machine whose tape isn't unlimited (though the amount of tape available is proportional to the input). Note that that describes computers pretty well - we like to think of them as Turing Machines but in the real world you can't grab arbitrarily more RAM mid-program. If it's not obvious to you how an LBA is more powerful than a PDA, an LBA can emulate a PDA by using part of its tape as a stack, but it can also choose to use its tape in other ways. (If you're wondering what a Finite State Machine can recognize, the answer is regular expressions. But not the regexes on steroids with capture groups and look-behind/look-ahead you see in program languages; I mean the ones you can build with operators like [abc] , | , * , + , and ? . You can see that abbbz matches regex ab*z just by keeping your current position in the string and regex, no stack required.)
{}
{'log_upvote_score': 6, 'links': ['https://softwareengineering.stackexchange.com/questions/253454', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/63610/']}
jdg_379277
stackexchange
llm_judgeable_groundtruth_similarity
63509183
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there a way to stream your webcam to your android app using Webrtc? Now provide the response and nothing else.
Update (Qt 6.2+) As of Qt 6.2, qt_add_qml_module is a single command for building qml modules that should take care of virtually everything, replacing amongst others the old qt6_qml_type_registration command. Old answer (Qt 6.0/6.1) Now that Qt 6.0 is out this is supported, albeit poorly documented. What you need now is: set_target_properties(foo PROPERTIES QT_QML_MODULE_VERSION 1.0 QT_QML_MODULE_URI Foo)qt6_qml_type_registration(foo) you can then do in qml: import Foo and you'll have access to types that have QML_ELEMENT and friends. Notes: Two files are created in the build output folder, <project>_qmltyperegistrations.cpp and <project>.qmltypes , if your imports are failing you can look at those to see which types are missing. I found that I needed to do full recompiles sometimes after adding/removing registered types. Qt examples have been migrated to cmake, so take a look at e.g. Examples/Qt-6.0.0/quick/tableview/gameoflife to see it in action There are now pro2cmake.py and run_pro2cmake.py files in the Qt sources at Qt/6.0.0/Src/qtbase/util/cmake . They are mentioned on this Readme page, you can find them here , haven't tried it myself.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/63509183', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11141427/']}
jdg_379278
stackexchange
llm_judgeable_groundtruth_similarity
44184
Below is a question asked on the forum astronomy.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Not sure if that is possible as I couldn't find an answer about it. Are there places in the Universe where there are no gravitational forces? Now provide the response and nothing else.
In two dimensions I think I can infer in a lame, unconvincing and rigorless numerical way that there are likely to be zeros in gravity from a random distribution of objects there can be points of zero gravity. I create a space with 20 randomly distributed point sources, calculate and plot the force field on a 2000 x 2000 grid then choose the smallest grid point and through a minimization routine find a point with arbitrarily small scalar force. I've done everything on a log10 scale, the max, min values are of order +8 and -1 but I can easily find log10(force_magnitude) around -14 by specifying that tolerance in the minimization routine. I can't prove this extends to 3 dimensions nor arbitrarily large space and numbers, but I have a hunch this can be addressed mathematically, so I have just asked in Math SE: What is the relative density and dimensionality of zeros in inverse square force fields to density of sources in (at least) 1, 2 and 3 dimensions? Here are six cases for flavor: There be zeros here! import numpy as npfrom scipy.optimize import minimizeimport matplotlib.pyplot as plt# https://astronomy.stackexchange.com/questions/44184/are-there-places-in-the-universe-without-gravitydef mini_me(xy, positions): return np.log10(get_force_magnitudes(positions, xy))def get_force_magnitudes(positions, XY): r = positions[:, None, None, :] - XY forces = r * (((r**2).sum(axis=-1))[..., None]**-1.5) # all vectors force_field = forces.sum(axis=0) # vector field return np.sqrt(force_field**2).sum(axis=-1)N = 20positions = np.random.random((N, 2))x = np.linspace(0, 1, 2000)X, Y = np.meshgrid(x, x, indexing='xy')XY = np.stack((X, Y), axis=2)force_magnitude = get_force_magnitudes(positions, XY)indices = np.unravel_index(np.argmax(-force_magnitude), force_magnitude.shape) # find the smallest one on the gridxy0 = XY[indices] # starting point for minimizationresult = minimize(mini_me, xy0, args=(positions, ), method='Nelder-Mead', tol=1E-08)if True: fix, ax = plt.subplots(1, 1) extent = 2*[0, 1] thing = ax.imshow(np.log10(force_magnitude), origin='lower', extent=extent, vmax=2) x, y = positions.T ax.plot(x, y, '.r') x, y = result.x label = str(round(result.fun, 2)) ax.plot([x], [y], 'o', color='none', markeredgecolor='red', markersize=14, markeredgewidth=2) ax.text(x+0.02, y, label, color='red', fontsize=14) plt.colorbar(thing, ax=ax) plt.title('log10 normalized scalar force') plt.show()
{}
{'log_upvote_score': 6, 'links': ['https://astronomy.stackexchange.com/questions/44184', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/1630/']}
jdg_379279
stackexchange
llm_judgeable_groundtruth_similarity
30152688
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm working with the json module creating a json file containing entries of the like json.dumps({"fields": { "name": "%s", "city": "%s", "status": "%s", "country": "%s" }}) However, in the json -file created the fields are in the wrong order {"fields": {"status": "%s", "city": "%s", "name": "%s", "country": "%s"}} which is a problem because the substitions for the %s -strings are now incorrect. How can I force the dumps function to keep the given order? Now provide the response and nothing else.
Like the other answers correctly state, before Python 3.6, dictionaries are unordered . That said, JSON is also supposed to have unordered mappings , so in principle it does not make much sense to store ordered dictionaries in JSON. Concretely, this means that upon reading a JSON object, the order of the returned keys can be arbitrary. A good way of preserving the order of a mapping (like a Python OrderedDict) in JSON is therefore to output an array of (key, value) pairs that you convert back to an ordered mapping upon reading: >>> from collections import OrderedDict>>> import json>>> d = OrderedDict([(1, 10), (2, 20)]) >>> print d[2]20>>> json_format = json.dumps(d.items()) >>> print json_format # Order maintained[[1, 10], [2, 20]]>>> OrderedDict(json.loads(json_format)) # Reading from JSON: works!OrderedDict([(1, 10), (2, 20)])>>> _[2] # This works!20 (Note the way the ordered dictionary is constructed from a list of (key, value) pairs: OrderedDict({1: 10, 2: 20}) would not work: its keys are not necessarily ordered as in the dictionary literal, since the literal creates a Python dictionary whose keys are unordered.) PS : Starting with Python 3.1, the json modules offers a hook for automatically converting a list of pairs (like above) to something else like an OrderedDict.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/30152688', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2668777/']}
jdg_379280
stackexchange
llm_judgeable_groundtruth_similarity
1562676
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 new to Core Data. I have noticed that collection types are not available as attribute types and would like to know what the most efficient way is of storing array/dictionary type data as an attribute (e.g. the elements that make up an address like street, city, etc. does not require a separate entity and is more conveniently stored as a dictionary/array than separate attributes/fields). Thank you. Now provide the response and nothing else.
There is no "native" array or dictionary type in Core Data. You can store an NSArray or an NSDictionary as a transformable attribute. This will use the NSCoding to serialize the array or dictionary to an NSData attribute (and appropriately deserialize it upon access). The advantage of this approach is that it's easy. The downside is that you can't query into the array or dictionary (it's stored as a BLOB in the data store) and if the collections are large, you may have to move a lot of data to/from the data store (if it's an SQLite data store) just to read or modify a small part of the collection. The alternative is to use Core Data to-many relationships to model the semantics of the array or dictionary collection. Arrays are easier, so lets start with that. Core Data to-many relationships are really modelling a set, so if you need array-like functionality, you have to either sort the set (using a fetched property is a convenient way to do this) or add an extra index attribute to the entity that stores the array items and manage the indexes yourself. If you are storing a homogeneous array (all entries are the same type), it's easy to model the entity description for the array entities. If not, you'll have to decide whether to use a transformable attribute to store the item data or create a family of item entities. Modeling a dictionary will likely require a to-many relationship to a set of entities that stores a key and a value. Both key and value are analogous to the item entity for the array, described above. So they could either be native types (if you know them ahead of time), a transformable attribute or a relationship to an instance from a family of type-specific entities. If this all sounds a bit daunting, it is. Shoehorning arbitrary data into a schema-dependent framework like Core Data is tough. For structured data, like addresses, it's almost always easier to spend the time modeling the entities explicitly (e.g. an attribute for each part of the address). Besides avoiding all the extra code to model a dictionary, this makes your UI easier (bindings will "just work") and your validation logic etc. much clearer since much of it can be handled by Core Data. Update As of OS X 10.7, Core Data includes an ordered set type which can be used in place of an array. If you can target 10.7 or later, this is the best solution for ordered (array-like) collections.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/1562676', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/172131/']}
jdg_379281
stackexchange
llm_judgeable_groundtruth_similarity
11680579
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 way to assign to multiple columns using data.table ? For example: f <- function(x) {c("hi", "hello")}x <- data.table(id = 1:10) I would like to do something like this (of course this syntax is incorrect): x[ , (col1, col2) := f(), by = "id"] And to extend that, I may have many columns with names stored in a variable (say col_names ) and I would like to do: x[ , col_names := another_f(), by = "id", with = FALSE] What is the correct way to do something like this? Now provide the response and nothing else.
This now works in v1.8.3 on R-Forge. Thanks for highlighting it! x <- data.table(a = 1:3, b = 1:6) f <- function(x) {list("hi", "hello")} x[ , c("col1", "col2") := f(), by = a][]# a b col1 col2# 1: 1 1 hi hello# 2: 2 2 hi hello# 3: 3 3 hi hello# 4: 1 4 hi hello# 5: 2 5 hi hello# 6: 3 6 hi hellox[ , c("mean", "sum") := list(mean(b), sum(b)), by = a][]# a b col1 col2 mean sum# 1: 1 1 hi hello 2.5 5# 2: 2 2 hi hello 3.5 7# 3: 3 3 hi hello 4.5 9# 4: 1 4 hi hello 2.5 5# 5: 2 5 hi hello 3.5 7# 6: 3 6 hi hello 4.5 9 mynames = c("Name1", "Longer%")x[ , (mynames) := list(mean(b) * 4, sum(b) * 3), by = a]# a b col1 col2 mean sum Name1 Longer%# 1: 1 1 hi hello 2.5 5 10 15# 2: 2 2 hi hello 3.5 7 14 21# 3: 3 3 hi hello 4.5 9 18 27# 4: 1 4 hi hello 2.5 5 10 15# 5: 2 5 hi hello 3.5 7 14 21# 6: 3 6 hi hello 4.5 9 18 27 x[ , get("mynames") := list(mean(b) * 4, sum(b) * 3), by = a][] # same# a b col1 col2 mean sum Name1 Longer%# 1: 1 1 hi hello 2.5 5 10 15# 2: 2 2 hi hello 3.5 7 14 21# 3: 3 3 hi hello 4.5 9 18 27# 4: 1 4 hi hello 2.5 5 10 15# 5: 2 5 hi hello 3.5 7 14 21# 6: 3 6 hi hello 4.5 9 18 27x[ , eval(mynames) := list(mean(b) * 4, sum(b) * 3), by = a][] # same# a b col1 col2 mean sum Name1 Longer%# 1: 1 1 hi hello 2.5 5 10 15# 2: 2 2 hi hello 3.5 7 14 21# 3: 3 3 hi hello 4.5 9 18 27# 4: 1 4 hi hello 2.5 5 10 15# 5: 2 5 hi hello 3.5 7 14 21# 6: 3 6 hi hello 4.5 9 18 27 Older version using the with argument (we discourage this argument when possible): x[ , mynames := list(mean(b) * 4, sum(b) * 3), by = a, with = FALSE][] # same# a b col1 col2 mean sum Name1 Longer%# 1: 1 1 hi hello 2.5 5 10 15# 2: 2 2 hi hello 3.5 7 14 21# 3: 3 3 hi hello 4.5 9 18 27# 4: 1 4 hi hello 2.5 5 10 15# 5: 2 5 hi hello 3.5 7 14 21# 6: 3 6 hi hello 4.5 9 18 27
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/11680579', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/714319/']}
jdg_379282
stackexchange
llm_judgeable_groundtruth_similarity
53085270
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 implement a trait which contains a generic method. trait Trait { fn method<T>(&self) -> T;}struct Struct;impl Trait for Struct { fn method(&self) -> u8 { return 16u8; }} I get: error[E0049]: method `method` has 0 type parameters but its trait declaration has 1 type parameter --> src/lib.rs:8:5 |2 | fn method<T>(&self) -> T; | ------------------------- expected 1 type parameter...8 | fn method(&self) -> u8 { | ^^^^^^^^^^^^^^^^^^^^^^ found 0 type parameters How should I write the impl block correctly? Now provide the response and nothing else.
Type parameters in functions and methods are universal . This means that for all trait implementers, Trait::method<T> must be implemented for any T with the exact same constraints as those indicated by the trait (in this case, the constraint on T is only the implicit Sized ). The compiler's error message that you indicated suggests that it was still expecting the parameter type T . Instead, your Struct implementation is assuming that T = u8 , which is incorrect. The type parameter is decided by the caller of the method rather than the implementer, so T might not always be u8 . If you wish to let the implementer choose a specific type, that has to be materialized in an associated type instead. trait Trait { type Output; fn method(&self) -> Self::Output;}struct Struct;impl Trait for Struct { type Output = u8; fn method(&self) -> u8 { 16 }} Read also this section of The Rust Programming Language : Specifying placeholder types in trait definitions with associated types . See also: "Expected type parameter" error in the constructor of a generic struct When is it appropriate to use an associated type versus a generic type?
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/53085270', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9130732/']}
jdg_379283
stackexchange
llm_judgeable_groundtruth_similarity
455165
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to use Varnish to show the non-logged in users a cached version of my website.I'm able to perfectly detect if the user is logged in or out, but I can't cache pages without extensions. There is no file extension because nginx is rewriting the URL to a php script(so caching .php does not work). For example I'd like varnish to cache:example.comexample.com/forum/example.com/contact/ I have tried if (req.request == "GET" && req.url ~ "^/") {return(lookup);}if (req.request == "GET" && req.url ~ "") {return(lookup);}if (req.request == "GET" && req.url ~ "/") {return(lookup);} but nothing seems to work... any help? EDIT: It still gives me X-Cache: MISS whenever I go to a extensionless page... Website is at http://www.atherys.com And the current VCL is... # This is a basic VCL configuration file for varnish. See the vcl(7)# man page for details on VCL syntax and semantics.## Default backend definition. Set this to point to your content# server.#backend default {.host = "127.0.0.1";.port = "8080";}/* Only permit cluster to purge files from cache */acl purge {"localhost";}sub vcl_recv { /* Before anything else we need to fix gzip compression */ if (req.http.Accept-Encoding) { if (req.url ~ "\.(jpg|png|gif|gz|tgz|bz2|tbz|mp3|ogg)$") { # No point in compressing these remove req.http.Accept-Encoding; } else if (req.http.Accept-Encoding ~ "gzip") { set req.http.Accept-Encoding = "gzip"; } else if (req.http.Accept-Encoding ~ "deflate") { set req.http.Accept-Encoding = "deflate"; } else { # unknown algorithm remove req.http.Accept-Encoding; } } if (req.request == "PURGE") { if (!client.ip ~ purge) { error 405 "Not allowed."; } /* Always purge by URL rather than going via vcl_hash as it hashes other factors which break purging */ purge_url(req.url); error 200 "Purged"; } #Remove cookies,remove queries and cache everything from content.gazamo-cdn.com if (req.http.host == "content.gazamo-cdn.com") { remove req.http.Cookie; set req.url = regsub(req.url, "\?.*$", ""); } #Atherys specific, if not logged in = cache; if logged in = pass if (req.http.host == "atherys.com" || req.http.host == "www.atherys.com") { if (req.http.Cookie ~ "xf_cache=1" && req.request == "GET") { return(lookup); if (req.request == "GET" && req.url ~ "^/") { return(lookup); } } } # always cache these items: if (req.request == "GET" && req.url ~ "\.(js|css)") { remove req.http.Cookie; return(lookup); } ## images if (req.request == "GET" && req.url ~ "\.(gif|jpg|jpeg|bmp|png|tiff|tif|ico|img|tga|wmf)$") { remove req.http.Cookie; return(lookup); } ## various other content pages if (req.request == "GET" && req.url ~ "\.(css|html)$") { remove req.http.Cookie; return(lookup); } ## multimedia if (req.request == "GET" && req.url ~ "\.(svg|swf|ico|mp3|mp4|m4a|ogg|mov|avi|wmv)$") { remove req.http.Cookie; return(lookup); } ## various other content pages if (req.request == "GET" && req.url ~ "\.(css|html)$") { remove req.http.Cookie; return(lookup); } ## multimedia if (req.request == "GET" && req.url ~ "\.(svg|swf|ico|mp3|mp4|m4a|ogg|mov|avi|wmv)$") { remove req.http.Cookie; return(lookup); } ## xml if (req.request == "GET" && req.url ~ "\.(xml)$") { remove req.http.Cookie; return(lookup); } #Do not cache if (req.request != "GET" && req.request != "HEAD") { return(pipe); } if (req.http.Authenticate || req.http.Authorization) { return(pass); } ### don't cache authenticated sessions #if (req.http.Cookie && req.http.Cookie ~ "authtoken=") { # return(pipe); #}}sub vcl_deliver { if (obj.hits > 0) { set resp.http.X-Cache = "HIT"; } else { set resp.http.X-Cache = "MISS"; } } Also, varnishlog: 0 CLI - Rd ping0 CLI - Wr 200 PONG 1354732729 1.00 CLI - Rd ping0 CLI - Wr 200 PONG 1354732732 1.012 SessionOpen c 86.50.90.54 62847 :8012 ReqStart c 86.50.90.54 62847 122512529412 RxRequest c GET12 RxURL c /forum/12 RxProtocol c HTTP/1.112 RxHeader c Host: www.atherys.com12 RxHeader c User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64; rv:16.0) Gecko/20100101 Firefox/16.012 RxHeader c Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.812 RxHeader c Accept-Language: fi-fi,fi;q=0.8,en-us;q=0.5,en;q=0.312 RxHeader c Accept-Encoding: gzip, deflate12 RxHeader c Connection: keep-alive12 RxHeader c Referer: http://www.atherys.com/forum/12 RxHeader c Cookie: xf_session=xxxxxxxxxxxxxxxx; xf_cache=112 RxHeader c If-Modified-Since: Wed, 05 Dec 2012 18:27:16 GMT12 VCL_call c recv12 VCL_return c lookup12 VCL_call c hash12 VCL_return c hash12 VCL_call c miss12 VCL_return c fetch14 BackendClose - default14 BackendOpen b default 127.0.0.1 59671 127.0.0.1 808012 Backend c 14 default default14 TxRequest b GET14 TxURL b /forum/14 TxProtocol b HTTP/1.114 TxHeader b Host: www.atherys.com14 TxHeader b User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64; rv:16.0) Gecko/20100101 Firefox/16.014 TxHeader b Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.814 TxHeader b Accept-Language: fi-fi,fi;q=0.8,en-us;q=0.5,en;q=0.314 TxHeader b Referer: http://www.atherys.com/forum/14 TxHeader b Cookie: xf_session=xxxxxxxxx; xf_cache=114 TxHeader b Accept-Encoding: gzip14 TxHeader b X-Varnish: 122512529414 RxProtocol b HTTP/1.114 RxStatus b 20014 RxResponse b OK14 RxHeader b Server: nginx14 RxHeader b Date: Wed, 05 Dec 2012 18:38:54 GMT14 RxHeader b Content-Type: text/html; charset=UTF-814 RxHeader b Content-Length: 1601314 RxHeader b Connection: keep-alive14 RxHeader b Expires: Thu, 19 Nov 1981 08:52:00 GMT14 RxHeader b Cache-control: private, max-age=014 RxHeader b Last-Modified: Wed, 05 Dec 2012 18:38:54 GMT14 RxHeader b Content-Encoding: gzip14 RxHeader b Vary: Accept-Encoding12 TTL c 1225125294 RFC 0 1354732734 0 0 0 012 VCL_call c fetch12 VCL_return c deliver12 ObjProtocol c HTTP/1.112 ObjStatus c 20012 ObjResponse c OK12 ObjHeader c Server: nginx12 ObjHeader c Date: Wed, 05 Dec 2012 18:38:54 GMT12 ObjHeader c Content-Type: text/html; charset=UTF-812 ObjHeader c Expires: Thu, 19 Nov 1981 08:52:00 GMT12 ObjHeader c Cache-control: private, max-age=012 ObjHeader c Last-Modified: Wed, 05 Dec 2012 18:38:54 GMT12 ObjHeader c Content-Encoding: gzip12 ObjHeader c Vary: Accept-Encoding14 Length b 1601314 BackendReuse b default0 CLI - Rd ping0 CLI - Wr 200 PONG 1354732735 1.012 VCL_call c deliver12 VCL_return c deliver12 TxProtocol c HTTP/1.112 TxStatus c 20012 TxResponse c OK12 TxHeader c Server: nginx12 TxHeader c Content-Type: text/html; charset=UTF-812 TxHeader c Expires: Thu, 19 Nov 1981 08:52:00 GMT12 TxHeader c Cache-control: private, max-age=012 TxHeader c Last-Modified: Wed, 05 Dec 2012 18:38:54 GMT12 TxHeader c Content-Encoding: gzip12 TxHeader c Vary: Accept-Encoding12 TxHeader c Content-Length: 1601312 TxHeader c Date: Wed, 05 Dec 2012 18:38:54 GMT12 TxHeader c X-Varnish: 122512529412 TxHeader c Age: 012 TxHeader c Via: 1.1 varnish12 TxHeader c Connection: keep-alive12 TxHeader c X-Cache: MISS12 Length c 1601312 ReqEnd c 1225125294 1354732734.723051310 1354732735.044378281 0.000048399 0.204994202 0.116332769 12 Debug c "herding"12 ReqStart c 86.50.90.54 62847 122512529512 RxRequest c GET12 RxURL c /cron.php?135473273412 RxProtocol c HTTP/1.112 RxHeader c Host: www.atherys.com12 RxHeader c User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64; rv:16.0) Gecko/20100101 Firefox/16.012 RxHeader c Accept: image/png,image/*;q=0.8,*/*;q=0.512 RxHeader c Accept-Language: fi-fi,fi;q=0.8,en-us;q=0.5,en;q=0.312 RxHeader c Accept-Encoding: gzip, deflate12 RxHeader c Connection: keep-alive12 RxHeader c Referer: http://www.atherys.com/forum/12 RxHeader c Cookie: xf_session=xxxxxx; xf_cache=112 VCL_call c recv12 VCL_return c lookup12 VCL_call c hash12 VCL_return c hash12 VCL_call c miss12 VCL_return c fetch12 Backend c 14 default default Now provide the response and nothing else.
Could you surround the Add-Type with a try catch and print the LoaderExceptions property, as the error is stating to do. It may provide an exception with a more detailed error message. try{ Add-Type -Path "C:\rnd\CloudBerry.Backup.API.dll"}catch{ $_.Exception.LoaderExceptions | % { Write-Error $_.Message }}
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/455165', 'https://serverfault.com', 'https://serverfault.com/users/148314/']}
jdg_379284
stackexchange
llm_judgeable_groundtruth_similarity
29969527
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a database.yml file like development: adapter: mysql2 encoding: utf8 database: d360 host: localhost username: root password: passwordtest: adapter: mysql2 encoding: utf8 database: sample host: localhost username: root password: password Now, I want value of database of test environment (that is sample for the YAML shown).How can we do that using sed? Now provide the response and nothing else.
That is fairly easy, not using sed , but with appropriate shell tools. First, if you need to preserve sample in a variable for later use, then something like the following will work using bash substring replacement to isolate sample on the Test:/database: line: $ db=$(grep -A3 'test:' database.yml | tail -n1); db=${db//*database: /}; echo "$db"sample or for a shorter solution that you can dump to the command line, remove the variable and command substitution and use a tool like cut : $ grep -A3 'test:' database.yml | tail -n1 | cut -c 13-sample or, with awk , simply: $ grep -A3 'test:' database.yml | tail -n1 | awk '{ print $2}'sample All of the different ways can be used inside command substitution (i.e. var=$(stuff) ) to store sample in var , it is just a matter of which you would rather use. I think you get the idea.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/29969527', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3078630/']}
jdg_379285
stackexchange
llm_judgeable_groundtruth_similarity
130985
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: We have a dataset with 10,000 manually labeled instances, and a classifier that was trained on all of this data. The classifier was then evaluated on ALL of this data to obtain a 95% success rate. What exactly is wrong with this approach? Is it just that the statistic 95% is not very informative in this setup? Can there still be some value in this 95% number? While I understand that, theoretically, it is not a good idea, I don't have enough experience in this area to be sure by myself. Also note that I have neither built nor evaluated the classifier in question. Common sense aside, could someone give me a very solid, authoritative reference, saying that this setup is somehow wrong? All I find on the Internet are toy examples supposed to convey some intuition. Here I have a project by professionals with an established track record, so I can't just say "this is wrong", especially since I don't know for sure. For example, this page does say: Evaluating model performance with the data used for training is not acceptable in data mining because it can easily generate overoptimistic and overfitted models. However, this is hardly an authoritative reference. In fact, this quote is plainly wrong, as the evaluation has nothing to do with generating overfitted models. It could generate overoptimistic data scientists who would choose the wrong models, but a particular evaluation strategy does not have anything to do with overfitting models per se. Now provide the response and nothing else.
The argument is simple: when you build a model, you want this model to be efficient on NEW, UNSEEN data, right? Otherwise you don't need a model. Then, your evaluation metric, let's say precision and recall, must give an idea of how well your model will behave on unseen data. Now, if you evaluate on the same data that you used for training, your precision and recall will be biased (almost certainly, higher than they should), because your model has already seen the data. Suppose that you're a teacher writing an exam for some students. If you want to evaluate their skills, will you give them exercises that they have already seen, and that they still have on their desks, or new exercises, inspired by what they learned, but different from them? That's why you always need to keep a totally unseen test set for evaluation. (You can also use cross-validation , but that's a different story).
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/130985', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/64767/']}
jdg_379286
stackexchange
llm_judgeable_groundtruth_similarity
43336954
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: output in json format [{ "school_id": "248", "server_url": "http:\/\/testdummy.brainyknights.in\/AndroidAppv5\/", "school_id_string": "jayanagar", "logo_path": "0", "about": "all"}] how to retrieve the value of school_id in js? Now provide the response and nothing else.
I have found to make the two work and will post here for anyone else looking for the same. There maybe other methods to do this , but this is what worked for me. So basically we will create a Cordova App using(say) :cordova create testapp com.test.testapp testappThis will give me a Folder Structure as so: testapp --hooks --platforms --plugins --www --config.xml Now inside the testapp folder we run : create-react-app teastappReactWhich will add my react app inside testapp folder.Your react app will have a main index.js in the /src directory. I the index.js make sure to wrap your main logic inside a function and then call the function along with Cordova object like so: import React from 'react';import ReactDOM from 'react-dom';import App from './App';import './index.css';const startApp = () => {ReactDOM.render( <App />, document.getElementById('root'));}if(!window.cordova) { startApp()} else { document.addEventListener('deviceready', startApp, false)} That should do now your app will have the Cordova instance along with Device objects like navigator.camera inside your app. Also in your react apps index.html which can be found in the public folder copy the html from the index.html that you will find in the Codova www folder. Now we can delete all files from www folder. We will later manually or via a script copy all files from react apps build folder to Cordova www folder. So my index.html would look something like below, notice the cordova.js file thats included as a script. <!DOCTYPE html><!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.--><html><head> <!-- Customize this policy to fit your own app's needs. For more guidance, see: https://github.com/apache/cordova-plugin-whitelist/blob/master/README.md#content-security-policy Some notes: * gap: is required only on iOS (when using UIWebView) and is needed for JS->native communication * https://ssl.gstatic.com is required only on Android and is needed for TalkBack to function properly * Disables use of inline scripts in order to mitigate risk of XSS vulnerabilities. To change this: * Enable inline JS: add 'unsafe-inline' to default-src --> <meta http-equiv="Content-Security-Policy" content="default-src * 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; img-src * data: content:;"> <meta name="format-detection" content="telephone=no"> <meta name="msapplication-tap-highlight" content="no"> <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width"> <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> <!-- Latest compiled and minified CSS --> <title>React App</title></head><body> <div id="root"></div> <script type="text/javascript" src="cordova.js"></script></body></html> Finally in your react apps' package.json add the following line:...."homepage": "../www"....This will make sure your final build file is pointing at the right path.we can also add the following lines in your package.json build script. "scripts": { "start": "react-scripts start", ***"build": "react-scripts build && robocopy .\\build ..\\www /MIR",*** "test": "react-scripts test --env=jsdom", "eject": "react-scripts eject", "deploy": "npm run build&&gh-pages -d build" } It can be robocopy or cp-r based on the OS(Windows/Linux etc).. We should have our Cordova app ready to be build with cordova build android/ios.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/43336954', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7429255/']}
jdg_379287
stackexchange
llm_judgeable_groundtruth_similarity
3366161
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 had a long discussion in chat over what seems like a simple question: Is $\sin \infty$ an indeterminate form ? What do you think? :) I'm labelling this as (soft-question) to be safe, but it should have a clear answer depending on the definition of indeterminate form used.The term "indeterminate form" is seldom used in post-calculus mathematics, but I believe it has one or more accepted definitions, which are either informal or formal. So any answer which takes a standard definition and argues the case would be interesting to me. How to make a good answer: State the definition of indeterminate form, either from an online or textbook source, or a definition you came up with on your own. Determine, using your stated definition, whether $\sin \infty$ is indeterminate or not. EDIT: What do I mean by $\sin (\infty)$ ? It's not a well-defined expression, but neither are any of the other indeterminate forms: $\frac{0}{0}$ doesn't exist, $1^\infty$ , doesn't exist, and so on. So the question is whether this expression -- which is not well-defined, just like any other indeterminate form -- is an indeterminate form. Now provide the response and nothing else.
Yes. An indeterminate form is an expression such that if you replace the constants appearing in the expression with sequences which approach those values, then the limit of the expression is not uniquely determined. In the case of $\sin(\infty)$ , if we replace $\infty$ by the sequence $a_n=\pi n$ we get a limit $$\lim_{n\to\infty}\sin(\pi n)=0.$$ If we instead take the sequence $b_n=2\pi n+\pi/2$ we get $$\lim_{n\to\infty}\sin(2\pi n+\pi/2)=1.$$ If we instead take the sequence $c_n=n$ then we get a limit $$\lim_{n\to\infty}\sin(n)$$ which does not exist. The point here is that if you are trying to evaluate a limit of the form $$\lim \sin(\text{something})$$ where you know that the "something" is approaching $\infty$ , you cannot tell what the answer is from just this information--the limit could be any number between $-1$ and $1$ , or it could not exist. This is just like the more familiar indeterminate forms like $\frac{0}{0}$ which are taught in calculus: if you have a limit $$\lim\frac{\text{something}}{\text{something else}}$$ where both "something" and "something else" approach $0$ , that is not enough information to determine the limit. It is perhaps worth remarking that with this definition, an indeterminate form is equivalently an expression such that if you replace the constants with variables ranging over the real numbers, then the limit as these variables jointly approach their values does not exist (where "exist" includes the possibility of being $\pm\infty$ ). In other words, to say that $\sin(\infty)$ is an indeterminate form really just means that $\lim\limits_{x\to\infty}\sin(x)$ does not exist (where here $x$ approaches $\infty$ in the real numbers, in contrast to the sequential limits we had before). Indeed, if you can have multiple different sequential limits, then the limit over the real numbers cannot exist. Conversely, if the limit over the real numbers does not exist, then by compactness of $[-\infty,\infty]$ the limit must still accumulate somewhere in $[-\infty,\infty]$ and so must accumulate at two different values, and then you can choose sequences for which the limit approaches two different values in $[-\infty,\infty]$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3366161', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/68107/']}
jdg_379288
stackexchange
llm_judgeable_groundtruth_similarity
631035
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 reading about category theory. So a category has a collection of objects and a collection of morphisms. Denote the set of morphisms from $A$ to $B$ by $Mor(A,B)$ so $f:A\rightarrow B$ has $f \in Mor(A,B)$. I haven't found it stated anywhere but do we take $Mor(A,B)$ to always be a non-empty set? I wonder because I wanted to try to understand the small categories like $\textbf{2}$. I was wondering if I take the collection of objects to be two vertices $a$ and $b$ and the morphisms to just be the identity morphism for $a$ and the identity morphism for $b$ so $Mor(a,b)=Mor(b,a)=\varnothing$ and $Mor(a,a)=\{1_a\}$ and $Mor(b,b)=\{1_b\}$, if this would form a category or if I would need to throw in a morphism $a\rightarrow b$ to form the category. Now provide the response and nothing else.
Every set gives rise to a category. In particular, let $S$ be a set. Then we may form a a category which we may call $disc(S)$ which is called the discrete category of $S$. The objects of $S$ are the elements, and we set $$Mor(s,s')=\emptyset\mbox{ if } s\neq s',$$ and $$Mor(s,s)=\{Id_s\}.$$ A category satisfying the above is called a discrete category. Likewise given any (small) discrete category, we may recover the underlying set by taking the set of objects. Moreover, their is a one to one correspondence between the functors between two discrete categories and the set of functions between the two underlying sets.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/631035', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_379289
stackexchange
llm_judgeable_groundtruth_similarity
591269
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 method that uses the setTimeout function and makes a call to another method. On initial load method 2 works fine. However, after the timeout, I get an error that says method2 is undefined. What am I doing wrong here? ex: test.prototype.method = function(){ //method2 returns image based on the id passed this.method2('useSomeElement').src = "http://www.some.url"; timeDelay = window.setTimeout(this.method, 5000);};test.prototype.method2 = function(name) { for (var i = 0; i < document.images.length; i++) { if (document.images[i].id.indexOf(name) > 1) { return document.images[i]; } }}; Now provide the response and nothing else.
The issue is that setTimeout() causes javascript to use the global scope. Essentially, you're calling the method() class, but not from this . Instead you're just telling setTimeout to use the function method , with no particular scope. To fix this you can wrap the function call in another function call that references the correct variables. It will look something like this: test.protoype.method = function(){ var that = this; //method2 returns image based on the id passed this.method2('useSomeElement').src = "http://www.some.url"; var callMethod = function() { that.method(); } timeDelay = window.setTimeout(callMethod, 5000);}; that can be this because callMethod() is within method's scope. This problem becomes more complex when you need to pass parameters to the setTimeout method, as IE doesn't support more than two parameters to setTimeout . In that case you'll need to read up on closures . Also, as a sidenote, you're setting yourself up for an infinite loop, since method() always calls method() .
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/591269', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/62604/']}
jdg_379290
stackexchange
llm_judgeable_groundtruth_similarity
419801
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Let $C$ be a $\mathbb{Z}$ -linear category, such that $C(x,y)$ is a free abelian group with finite rank, for every $x,y\in\mathrm{Ob}(C)$ . Given a commutative ring with identity $R$ , let $RC$ denote the category with the same objects of $C$ , and morphisms $RC(x,y):=R\otimes_{\mathbb{Z}} C(x,y)$ . Does any isomorphism in $\mathbb{F}_pC(x,y)$ lift to an isomorphism in $\mathbb{Z}^{\wedge}_pC(x,y)$ ? Now provide the response and nothing else.
$\DeclareMathOperator\SL{SL}\DeclareMathOperator\PSL{PSL}\DeclareMathOperator\GL{GL}$ The reason that there are uncountably many irreducible representations is not so bad, and gets at an important point: You shouldn't think of irreducible representations of a group like $\SL_2(\mathbb Z)$ individually, but rather as points in a space of representations, i.e. objects parameterized by a geometric space. This is simplest to see for representations sending $-I \in \SL_2(\mathbb Z)$ to the identity, i.e. representations of $\PSL_2(\mathbb Z)$ . By the presentation YCor gave $\PSL_2(\mathbb Z) = \langle x,y \mid x^2 =y^3 =1 \rangle$ , such a representation is given by a matrix $X$ satisfying $X^2=1$ and a matrix $Y$ satisfying $Y^3=1$ , and representations up to isomorphism are given by pairs of matrices up to conjugation. For $n$ -dimensional representations, say $n$ a multiple of $6$ , it's not so hard to check that the space of matrices $X \in \GL_n(\mathbb C)$ with $X^2=1$ has dimension $n^2/2$ (over $\mathbb C$ ), and the space of matrices $Y \in \GL_n(\mathbb C)$ with $Y^3= 1$ has dimension $2n^2/3$ , so the space of pairs has dimension $n^2/2 + 2n^2/3$ , isomorphism classes of $n$ -dimensional representations have dimension $n^2/2 +2n^2/3 - (n^2-1) = n^2/6+1$ . One can check that irreducible representations are an open subset, and thus that the space of irreducible representations has the same dimension. So certainly there are uncountably many, because they're parameterized by a positive-dimensional manifold! However, it's clear from this analysis that this space should be one of the primary objects of study in the representation theory here, as it is for representations of surface groups and in some other cases of interest.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/419801', 'https://mathoverflow.net', 'https://mathoverflow.net/users/480085/']}
jdg_379291
stackexchange
llm_judgeable_groundtruth_similarity
6593322
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So I've been programming in java for a semester or so, and I've had this problem a few times and finally got around to asking. If I make a JFrame and then set the size, like setSize(400,800) for example. The frame is not actually 800 pixels long. From what I can tell it is actually more like 770 (or maybe 769) pixels long. Also, if you set the vertical size very low (below 30), the frame doesn't even show up, only the top window bar from the OS and the frame doesn't get bigger until you go to a value over 30 (so setSize(400,0) looks the same as setSize(400,20) ). Why is this, it's not hard to fix but its weird and I'm curious why this is? If you need more information about anything just ask and I'll get it to you. Now provide the response and nothing else.
It's probably because size of a frame includes the size of the border. A Frame is a top-level window with a title and a border. The size of the frame includes any area designated for the border. The dimensions of the border area may be obtained using the getInsets method. Since the border area is included in the overall size of the frame, the border effectively obscures a portion of the frame, constraining the area available for rendering and/or displaying subcomponents to the rectangle which has an upper-left corner location of (insets.left, insets.top), and has a size of width - (insets.left + insets.right) by height - (insets.top + insets.bottom). Source: http://download.oracle.com/javase/tutorial/uiswing/components/frame.html
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6593322', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/703518/']}
jdg_379292
stackexchange
llm_judgeable_groundtruth_similarity
30527045
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: My app has ability to select photo from library. Exactly I want file path from this selection. This is the code to create intent for selecting photo: Intent photoPickerIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); photoPickerIntent.setType("image/*"); startActivityForResult(photoPickerIntent, INTENT_REQUEST_CODE_SELECT_PHOTO); This is the code that gets file path from URI: Cursor cursor = null; String path = null; try { String[] projection = { MediaStore.Images.Media.DATA }; cursor = context.getContentResolver().query(contentUri, projection, null, null, null); int columnIndex = cursor.getColumnIndexOrThrow(projection[0]); cursor.moveToFirst(); path = cursor.getString(columnIndex); } finally { if (cursor != null) { cursor.close(); } } return path; Before yesterday's update of Google Photos app everything worked perfectly fine.Now path is null after parsing URI. URI is similar to this: content://com.google.android.apps.photos.contentprovider/0/1/content%3A%2F%2Fmedia%2Fexternal%2Fimages%2Fmedia%2F75209/ACTUAL I also tried to create intent with Intent.ACTION_GET_CONTENT action - no luck. Now provide the response and nothing else.
Below code is working for me to get content URI on latest Google Photos as well. What i have tried is writing to temp file and return temp image URI, if it has authority in content URI. You can try same: private static String getImageUrlWithAuthority(Context context, Uri uri){ InputStream is = null; if (uri.getAuthority() != null) { try { is = context.getContentResolver().openInputStream(uri); Bitmap bmp = BitmapFactory.decodeStream(is); return writeToTempImageAndGetPathUri(context, bmp).toString(); } catch (FileNotFoundException e) { e.printStackTrace(); } finally { try { if (is != null) { is.close(); } } catch (IOException e) { e.printStackTrace(); } } } return null;}private static Uri writeToTempImageAndGetPathUri(Context inContext, Bitmap inImage){ ByteArrayOutputStream bytes = new ByteArrayOutputStream(); inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes); String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null); return Uri.parse(path);}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/30527045', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2957893/']}
jdg_379293
stackexchange
llm_judgeable_groundtruth_similarity
3191132
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: Calculate the map on homology induced by the quotient map $S^3 → \Bbb R {\Bbb P}^3$ I understand the quotient map $q:S^3 → \Bbb R {\Bbb P}^3$ i.e. identifying antipodal points i.e. for $x \in S^3$ consider te corresponding $[x] \in \Bbb R {\Bbb P}^3$ then, $q(x)=q(-x)=[x] , \forall x \in S^3$ . It is a 2-sheeted covering map and hence should give a degree 2 map and hence in the level of homology, it should behave like $n \mapsto 2n$ .But not quite clear to me. I have visited this question but it has a few comments, I want to understand this concept and so if someone vance for help!can write a detailed answer about what is going on here and how to compute it, it will gteatly help my cause ( also to understand similar problems) . Thanks in advance for help! Now provide the response and nothing else.
In general the canonical quotient map $q:S^n\rightarrow\mathbb{R}P^n$ is the attaching map for the top cell of $\mathbb{R}P^{n+1}$ . This means that there is a cofibration sequence $$S^n\xrightarrow{q}\mathbb{R}P^n\rightarrow \mathbb{R}P^{n+1}$$ and in particular a long exact sequence in homology $$\dots\rightarrow H_{k+1}\mathbb{R}P^{n+1}\rightarrow H_kS^n\xrightarrow{q_*}H_k\mathbb{R}P^n \rightarrow H_k\mathbb{R}P^{n+1}\rightarrow H_{k-1}S^n\rightarrow\dots$$ If we put a CW structure on $S^n$ with two cells in each dimension $0\leq r\leq n$ then these cells are permuted by the $\mathbb{Z}_2$ -action of the antipodal map. Hence the structure descends to give a CW structure of the quotient $\mathbb{R}P^n$ which has one cell in each dimension $0\leq r\leq n$ . Then in $S^n$ , the boundary orientation of the two $r$ -cells agrees if $r$ is even, and is opposite in the case that $r$ is odd. This means that the cellular complex $C_*S^n$ (whose homology computes $H_*S^n$ ) is actually exact in degrees $\neq 0,n$ . On the other hand, it means that in $C_*\mathbb{R}P^m$ , where the cells in each dimension are identified, the differentials are either trivial (when the orientations are opposite), or multiplication by $2$ (when the orientations agree). Hence we compute $$\tilde H_k\mathbb{R}P^{2r}\cong\begin{cases}0&k\leq 2r\:\text{even}\\\mathbb{Z}_2&k\leq 2r\:\text{odd}\end{cases}$$ and $$\tilde H_k\mathbb{R}P^{2r+1}\cong\begin{cases}0&k< 2r+1\:\text{even}\\\mathbb{Z}_2&k<2r+1\;\text{odd}\\\mathbb{Z}&k=2r+1\end{cases}$$ This gives us that whenever $n=2r+1$ is odd we have an exact sequence $$H_{2r+2}\mathbb{R}P^{2r+2}\rightarrow H_{2r+1}S^{2r+1}\xrightarrow{q_*} H_{2r+1}\mathbb{R}P^{2r+1}3\rightarrow H_{2r+1}\mathbb{R}P^{2r+2}\rightarrow H_{2r}S^{2r+1}$$ which is exactly $$0\rightarrow \mathbb{Z}\xrightarrow{q_*}\mathbb{Z}\rightarrow \mathbb{Z}_2\rightarrow 0.$$ Hence $q_*:H_{2r+1}S^{2r+1}\rightarrow H_{2r+1}\mathbb{R}P^{2r+1}$ is multiplication by $2$ . In particular this holds for the odd integer $n=3$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3191132', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_379294
stackexchange
llm_judgeable_groundtruth_similarity
2205277
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 was asked to find the largest number $k$ for which the real function $$x \mapsto \sum_{n=1}^\infty \frac{\cos nx}{2^n}$$is in the differentiability class $C^k$. I can't seem to think of a way to approach this question..any help will be gladly accepted! Now provide the response and nothing else.
The series is uniformly convergent on $\mathbb R$ (by the M-test), so the function $$f(x) = \sum_{n=1}^\infty \frac{\cos nx}{2^n} $$ is differentiable on $\mathbb R$ and $$f'(x) =- \sum_{n=1}^\infty n\frac{\sin nx}{2^n} $$ You can apply the same trick to $f'$ and conclude that $f'$ is differentiable. By induction you can work out that $f^{(k)}$ is differentiable for all $k$ and so $f \in C^\infty(\mathbb R)$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2205277', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/401774/']}
jdg_379295
stackexchange
llm_judgeable_groundtruth_similarity
3623890
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I m using the following script to call a onload function but it does not works in IE ("#body").attr({onload : "calFact();"}); Now provide the response and nothing else.
If you are using jQuery you could use the ready() function like so: $(function() { callFact();}); or even more simply, just pass the method to jQuery: $(callFact); That will fire as soon as the DOM is available to manipulate, sometimes earlier than onload .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3623890', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/418232/']}
jdg_379296
stackexchange
llm_judgeable_groundtruth_similarity
36657458
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: All of the service fabric examples depict single-solution service fabric examples. This seems to go counter to the philosophy of microservices, where you want complete dependency isolation between your services. While you can manually follow this pattern, the more common practice is to enforce it by making each service it's own repository and solution/project. How do you manage and deploy service fabric services, and enforce service contracts (ServiceInferfaces) using multiple solutions (in multiple Git repositories)? E.g. Service Fabric Solution App1 - Customers - Service1 [Carts] From Other Solution - Service2 [LocationInfo]From Other Solution - Service3 [REST WebAPI for Admin] From Other Solution App2 - Products - Service4 [Status]From Other Solution - Service5 [Firmware]From Other Solution - Service6 [Event Stream] From Other SolutionExternal Solution - Service1External Solution - Service2External Solution - Service3External Solution - Service4External Solution - Service5External Solution - Service6 1) As a developer, I want to check out and build all the current versions of apps/services. I want to fire up my Service Fabric project that manages all the manifests, and deploy it to my local dev cluster. I want to enforce the same service interfaces between solutions. I don't understand how you'd do this, because the application is external to the services. 2) As a DevOps team, I want to automate pulling down the apps, building them and deploying to Azure. How do we "enforce" isolation via separate solutions, but make it easy to pull them together and deploy into the cluster, while also making it easy to make pipelines to deploy each cluster configured uniquely for DEV, QA, and PROD environments. What is the workflow/process/project structure to enable this? Is it even possible? Now provide the response and nothing else.
Yep, it's possible - I've done something along these lines before. These are the thoughts that spring to mind immediately... In each Service Fabric solution have a "public" project containing just the interfaces that you want to expose from the services in that application. The output from this project could be packaged as a nuget package and pushed onto a private repository. You could call it the "interfaces" project I guess, but you wouldn't have to expose all the interfaces if you wanted to consider some of them internal to your application; these could be defined in a separate, unexposed project. Other solutions that want to reference the services exposed by another application just had to pull down the relevant nuget package to get a reference to the service interfaces. Now this isn't without problems: The consuming application still need to know the addresses for the services in order to construct proxies for them. You could either expose them as constants defined somewhere in the nuget package, or if you're going down the full DI route and don't mind coupling yourself to a DI container everywhere (or fancy trying to abstract it away), you could expose a module from the nuget package that can register the services interfaces as a lambda that does the service proxy creation on behalf of the dependent applications. You are much more vulnerable to breaking contracts. You need to be really careful about updating method signatures as you are now responsible for the granularity and co-ordination of application/service deployments. You can go too granular - as you mention, the Service Fabric tooling guides you toward having multiple services in one solution. Even with the above approach I would still try to logically group my services to some extent, i.e. don't go for a one-to-one mapping between an application and service - that will definitely be more pain than it's worth. Hope that helps. EDIT: An example of registering a service interface in a DI module, (Autofac style)... This would be the DI module you expose from the public nuget package: using System;using Autofac;using Microsoft.ServiceFabric.Services.Remoting.Client;public class MyAppModule : Module{ protected override void Load(ContainerBuilder builder) { builder.Register(component => ServiceProxy.Create<IMyService>(new Uri("fabric:/App/MyService"))).As<IMyService>(); // Other services... }} And in the Program.cs of your consuming application, you'd include something like this: public static void Main(){ try { var container = ConfigureServiceContainer(); ServiceRuntime.RegisterServiceAsync( "MyConsumingServiceType", context => container.Resolve<MyConsumingService>(new TypedParameter(typeof(StatefulServiceContext), context))).GetAwaiter().GetResult(); ServiceEventSource.Current.ServiceTypeRegistered(Process.GetCurrentProcess().Id, typeof(MyConsumingService).Name); Thread.Sleep(Timeout.Infinite); } catch (Exception e) { ServiceEventSource.Current.ServiceHostInitializationFailed(e.ToString()); throw; }}private static IContainer ConfigureServiceContainer(){ var containerBuilder = new ContainerBuilder(); // Other registrations... containerBuilder.RegisterModule<MyAppModule>(); return containerBuilder.Build();} Of course, this approach will only work if you aren't partitioning your services...
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36657458', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/654434/']}
jdg_379297
stackexchange
llm_judgeable_groundtruth_similarity
70760
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 searched around and poored through what references I have available, and haven't been able to find an answer to this question. Regarding 1:1 transformers, I found a website where an audio amplifier electronics guy mentioned that it doesn't seem too much to matter how many winds you put on a 1:1 transformer so long as the reactance/impedance is at least about 4x the circuit impedance. He said "about" as if there was no magic way he calculated it -- it was simply based on his experience building and fixing amplifiers and transformers. I was wondering if someone shed some light on this issue. I'm most interested in a full-load transformer. Here's a circuit showing an inductor and resistor in series with the transformer. What is a practical Z for the primary coil of the transformer to make sure it works properly? And what kinds of problems will arise if my Z is way too low? So for the sake of total extremes. Assume I only had 100 Volts and 0.9amps in the primary circuit, limited mainly by the resistance and impedance of R1 and L1 Let's assume the resistance of the transformer is minor for simplicity. What is going to happen in the secondary circuit if my impedance on the transformer primary is near zero? Will I just get no power at all in the secondary? Will I get some current with very small voltage? And what will happen if the reactance of the transformer primary is 100Ohm making it very similar to the L1? Thanks in advance. EDIT: I should clarify that by "full-load" transformer, I'm meaning the condition that the transformer secondary is dead-shorted. The diagram is showing an amp-meter (A) between the leads. Now provide the response and nothing else.
You should possibly consider looking at the transformer in two ways; one without a load and one with a load on the secondary. Without a load on the secondary, the transformer is just an inductor and if you have components (such as L1 and R1) in series with the primary, the voltage developed on the primary will not be the full AC amount from your generator. It's a simple case of calculating the impedances and volt-drops. This is with the secondary unconnected remember. The primary has inductance like any other coil but, for a transformer to more effective, it is desirable for the primary's self inductance to be high in power applications. If you looked at how much current flowed into the primary (secondary open circuit) you would find that the current was small compared to when driving a load on the secondary and it may have an inductance of several henries. With 10 henries inductance, at 50Hz the impedance is 3142 ohms and from 230VAC would take a current of 73mA - that current through R1 (10 ohm) hardly drops any voltage. It's a different matter when there is a load on the secondary. If the turns ratio is 1:1 and you have 100 ohms on the secondary, it is reasonable to argue that the impedance presented to the primary circuit is also 100 ohms. This assumes power out is close to power in. In fact the impedance relationship between primary and secondary is related to turns ratio squared. For instance if it is a 10:1 step-down transformer with a load of 100 ohms, the equivalent impedance at the primary is 10k ohms i.e. 10 x 10 x 100. In summary, for a power transformer, you'd like the primary inductance to be infinite but that is impractical so you live with something that doesn't take too much current when the secondary is open circuit. The off-load current that flows is real current taken from the AC power and if everyone had low-impedance transformers the electricity companies would be supplying a load of current that doesn't get them revenue. This is a slight exaggeration but not far off the truth. On industrial sites power factor correction is used to minimize this effect but that's a whole new story! And if your transformer primary was 100 ohm impedance you'd be seeing something less than half your AC voltage applied. If R1 was zero then you'd see exactly half. As regards saturation I've shown the equivalent circuit of a transformer below. Note that saturation is caused by the current flowing through the magnetizing inductor which is nothing to do with load current: - Here is a good document from Elliott Sound Products and please note what it says about maximum flux density therefore saturation: Why doesn't the core saturate more under load conditions? Imagine two coils sharing the same magnetic core. Ignore magnetization currents and losses. The primary is 100 turns and the secondary is 10 turns. If the secondary load current is 10A, the primary current must be 1A and the ampere-turns is therefore the same on both coils. Are these ampere-turns additive or subtractive? They are subtractive and this can easily be seen with dot notation.... If current is flowing into the dot on the primary, current is flowing out of the dot on the secondary and this produces opposing fluxes in the magnetic material. When you think about this you have to be consistent and use the right-hand rule to see that the two fluxes oppose and cancel. Because the dots are at the top on both coils, they are wound in the same direction and the currents are flowing in (primary) and out (secondary) therefore due to the RH rule the fluxes (due to ampere-turns) are cancelled.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/70760', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/22874/']}
jdg_379298
stackexchange
llm_judgeable_groundtruth_similarity
1683949
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 connect to DB using the standard JDBC way connection = DriverManager.getConnection(url, username, password); Is there a maximum value of timeout on the connection, how long does a connection live, can I increase the value. I want in cases the connection to be open forever , is it a good idea. Now provide the response and nothing else.
The value is usually DB-controlled. You have no control over it using code. It depends on the DB server used. It is usually around 30 minutes up to one hour. On the other hand, keeping a Connection open forever is a very bad idea. Best practice is to acquire and close Connection , Statement and ResultSet in the shortest possible scope to avoid resource leaks and potential application crashes caused by the leaks and timeouts. True, connecting the DB is an expensive task. If your application is supposed to run a relatively long time and to connect the DB fairly often, then consider using a connection pool to improve connecting performance. If your application is a webapplication, then take a look in the appserver's documentation, it usually provides a connection pooling facility in flavor of a DataSource . If it is a client application, then look for 3rd party connection pooling libraries which have proven their robustness with years, such as Apache Commons DBCP (commonly used, used in lot appservers), C3P0 (known from Hibernate) and Proxool (if you want XA connections). Keep in mind, when using a connection pool, you still have to write proper JDBC code, i.o.w. acquire and close all the resources in the shortest possible scope. The connection pool will on its turn worry about actually closing the connection or just releasing it back to pool for further reuse. You may get some more insights out of this article how to do the JDBC basics the proper way. Hope this helps and happy coding.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1683949', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/43756/']}
jdg_379299
stackexchange
llm_judgeable_groundtruth_similarity
14849010
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 Windows 7, php 5.3.5 and WAMP server. I have two php files: trigger.php and background.php. I want to run background.php as a background process. I have to call this file from trigger.php. To accomplish this I used below method.I included following code in trigger.php to make background.php to process in background. $handle = popen('start /b C:\wamp\bin\php\php5.3.5\php.exe C:\wamp\www\email3.php','r'); in background.php I have the follwing code to connect to database. $conn_string = "host=localhost port=5432 dbname=tagbase user=postgres password=postgres"; now, on parsing this line am getting the follwing error : Fatal error: Call to undefined function pg_connect() in C:\wamp\www\background.php on line 3 Call Stack: 0.0002 322792 1. {main}() C:\wamp\www\background.php:0 By searching in in the internet I found some solutions, and made changes as recommended below in php.ini, uncommented, extension=php_pdo_pgsql.dll,uncommented, extension=php_pgsql.dll,uncommented, extension_dir = "c:/wamp/bin/php/php5.3.5/ext/", also I do have php_pdo_pgsql.dll and php_pgsql.dll files in c:/wamp/bin/php/php5.3.5/ext/ folder. Any suggestions are appreciated. Now provide the response and nothing else.
Apache 2.2.X configuration Add the next line to the Apache 2.2.x httpd.conf configuration: LoadFile "C:/Program Files/PostgreSQL/{version}/bin/libpq.dll" Above line must be entered before the next line. LoadModule php5_module "c:/wamp/bin/php/php5.2.11/php5apache2_2.dll" PHP 5.2.X Configuration Enable the following two lines in the php.ini configuration file. By 'Enable' i mean, remove trailing ; (semicolon). By these, you un-comment the line. extension=php_pdo_pgsql.dllextension=php_pgsql.dll Restart WAMP Test by adding this in your index.php echo extension_loaded('pgsql') ? 'yes':'no'; (source: http://www.plaatsoft.nl/wamp-postgresql-integration/ )
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14849010', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1912474/']}
jdg_379300
stackexchange
llm_judgeable_groundtruth_similarity
2758428
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: This may be a very basic question. Let $R$ be a commutative ring with unity (may be assumed to be an integral domain, if necessary) and $I$ be an ideal of $R$ . Assume that $R/I$ is isomorphic to $R$ . Does this mean $I=(0)$ ? Now provide the response and nothing else.
Counterexample: $R=\Bbb Q [X_1, X_2, \dots , X_n, \dots]$. Define the ring morphism $f: R \to R$ by$$\begin{cases}X_i \mapsto X_{i-1} & i>1 \\ X_1 \mapsto 0\end{cases}$$ and call $I= \ker f$. Then $$R/I \cong \mathrm{Im} f= R$$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2758428', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/327553/']}
jdg_379301
stackexchange
llm_judgeable_groundtruth_similarity
3813340
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to create my own HTML Helper which takes in an expression (similar to the built-in LabelFor<> helper. I have found examples to obtain the value of a property when the expression is similar to this: model => model.Forename However, in some of my models, I want to obtain properties in child elements, e.g. model => mode.Person.Forename In these examples, I cannot find anyway to (easily) obtain the value of Forename. Can anybody advise on how I should be getting this value. Thanks Now provide the response and nothing else.
If you are using the same pattern that the LabelFor<> method uses, then the expression will always be a LambdaExpression and you can just execute it to get the value. var result = ((LambdaExpression)expression).Compile().DynamicInvoke(model); Generally, you can always wrap generic expressions in LambdaExpressions and then compile & invoke them to get the value. If what you want isn't the value of Forename, but the field itself (fx. to print out the string "Forename") then your only option is to use some form of expressionwalking. In C#4 the framework provides a class called ExpressionVisitor that can be used for this, but for earlier versions of the framework you have to implement it yourself - see: http://msdn.microsoft.com/en-us/library/bb882521(VS.90).aspx
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3813340', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/460667/']}
jdg_379302
stackexchange
llm_judgeable_groundtruth_similarity
425487
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've read that you need to put the swap partition on HDD rather than SSD. My questions are the following: When and how is the "checking" done by the distribution (or something else) to find its Swap partition? Does it happen during boot? It just checks all available disks and searches for a partition with 'swap' flag? What happens if there are several partitions like that? Also, how many swap partitions do I need to have if I run, for example, two different distributions on the same disk, let's say Fedora and Ubuntu? Now provide the response and nothing else.
Statically configured swap space (the type that pretty much every distribution uses) is configured in /etc/fstab just like filesystems are. A typical entry looks something like: UUID=21618415-7989-46aa-8e49-881efa488132 none swap sw 0 0 You may also see either discard or nofail specified in the flags field (the fourth field). Every such line corresponds to one swap area (it doesn't have to be a partition, you can have swap files, or even entire swap disks). In some really specific cases you might instead have dynamically configured swap space, although this is rather rare because it can cause problematic behavior relating to memory management. In this case, the configuration is handled entirely by a userspace component that creates and enables swap files as needed at run time. As far as how many you need, that's a complicated question to answer, but the number of different Linux distributions you plan to run has zero impact on this unless you want to be able to run one distribution while you have another in hibernation (and you probably don't want to do this, as it's a really easy way to screw up your system). When you go to run the installer for almost any major distribution (including Fedora, OpenSUSE, Linux Mint, Debian, and Ubuntu), it will detect any existing swap partitions on the system, and add those to the configuration for the distribution you're installing (except possibly if you select manual partitioning), and in most cases this will result in the system being configured in a sensible manner. Even aside from that, I would personally suggest avoiding having multiple swap partitions unless you're talking about a server system with lots of disks, and even then you really need to know what you're doing to get set up so that it performs well.
{}
{'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/425487', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/186014/']}
jdg_379303
stackexchange
llm_judgeable_groundtruth_similarity
8671505
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: #include<stdio.h> int main() { float a; printf("Enter a number:"); scanf("%f",&a); printf("%d",a); return 0; } I am running the program with gcc in Ubuntu.For values-- 3.3 it gives value 1610612736 3.4 it gives value 1073741824 3.5 it gives value 0 3.6 it gives value -1073741824 4 it gives value 0 5 it gives value 0 What is happening? Why are these values printed? I'm doing this intentionally, but would like to understand why this is happening. Details are appreciated! Now provide the response and nothing else.
The printf function does not know the type of format you passed in, because that part is variadic. int printf(const char* format, ...);// ^^^ In the C standard, passing a float will be automatically promoted to a double (C11§6.5.2.2/6), and nothing else will be done in the caller side. Inside printf , since it doesn't know the type of that ... thingie (§6.7.6.3/9), it has to use the hint from elsewhere — the format string. Since you've passed "%d" , it is telling the function that, an int is expected. According to the C standard, this leads to undefined behavior (§7.21.6.1/8–9), which includes the possibility of printing some weird number, end of story. But what is really happening? In most platforms, a double is represented as " IEEE 754 binary64 " format, and a float in binary32 format. The numbers you've entered are converted to a float, which only has 23 bits of significance, which means the numbers will be approximated like this: 3.3 ~ (0b1.10100110011001100110011) × 2¹ (actually: 3.2999999523162842...)3.4 ~ (0b1.10110011001100110011010) × 2¹ (actually: 3.4000000953674316...)3.5 = (0b1.11 ) × 2¹ (actually: 3.5)3.6 ~ (0b1.11001100110011001100110) × 2¹ (actually: 3.5999999046325684...)4 = (0b1 ) × 2² (actually: 4)5 = (0b1.01 ) × 2² (actually: 5) Now we convert this to double, which has 53 bits of significance, which we have to insert 30 binary "0"'s at the end of these numbers, to produce e.g. 3.299999952316284 = 0b1.10100110011001100110011000000000000000000000000000000 ×2¹ These are mainly to derive the actual representation of those numbers, which are: 3.3 → 400A6666 600000003.4 → 400B3333 400000003.5 → 400C0000 000000003.6 → 400CCCCC C00000004 → 40100000 000000005 → 40140000 00000000 I recommend using http://www.binaryconvert.com/convert_double.html to see how this breaks down to the ± m × 2 e format. Anyway, I suppose your system is an x86/x86_64/ARM in normal setting, which means the numbers are laid out in memory using little-endian format , so the arguments passed will be like byte #0 #1 ... #4 ... #8 ....+----+----+----+----+ +----+----+----+----+----+----+----+----+| 08 | 10 | 02 | 00 | | 00 | 00 | 00 | 60 | 66 | 66 | 0A | 40 | ....+----+----+----+----+ +----+----+----+----+----+----+----+----+ address of "%d" content of 3.299999952316284 (just an example) Inside the printf , it consumes the format string "%d" , parses it, and then finds out that an int is needed because of %d, so 4 bytes are taken from the variadic input, which is: byte #0 #1 ... #4 ... #8 ....+ - -+ - -+ - -+ - -+ +====+====+====+====+ - -+ - -+ - -+ - -+: 08 : 10 : 02 : 00 : | 00 | 00 | 00 | 60 | 66 : 66 : 0A : 40 : ....+ - -+ - -+ - -+ - -+ +====+====+====+====+ - -+ - -+ - -+ - -+ address of "%d" ~~~~~~~~~~~~~~~~~~~ this, as an 'int' so, printf will receive 0x60000000, and display it as a decimal integer, which is 1610612736, which is why you see that result. The other numbers can be explained similarly. 3.3 → ... 60000000 = 16106127363.4 → ... 40000000 = 10737418243.5 → ... 00000000 = 03.6 → ... C0000000 = -1073741824 (note 2's complement)4 → ... 00000000 = 05 → ... 00000000 = 0
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8671505', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1121308/']}
jdg_379304
stackexchange
llm_judgeable_groundtruth_similarity
4088
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $G$ be an edge-weighted DAG with a unique source $s$. The question is how to find out a maximum weight arborescence in $G$ rooted at $s$. When all edge weights are positive then the required arborescence is also spanning and so we can use the directed minimum spanning tree algorithm (http://www.ce.rit.edu/~sjyeec/dmst.html) What if negative weights are allowed? Now provide the response and nothing else.
The problem is NP-complete by a reduction from the set cover problem. Set cover Instance : A finite set U , a family C of subsets of U and k ∈ℕ. Question : Is there a cover D of U in C with at most k sets, that is, a subset D of C with | D |≤ k such that the union of D is equal to U ? Given an instance ( U , C , k ) of the set cover problem, let U ={ a 1 , …, a n } and C ={ S 1 , …, S m } ( n =| U |, m =| C |) and construct a DAG G with four layers of vertices: The first layer consists of a single source s . The second layer consists of m vertices x 1 , …, x m , each of which has an incoming edge from s with weight −1. The third layer consists of n vertices y 1 , …, y n . The vertex y i has an incoming edge from the vertex x j with weight 0 for each pair ( i , j ) such that a i ∈ S j . The fourth layer consists of n vertices z 1 , …, z n . Each vertex z i has an incoming edge from the corresponding vertex y i with weight m . Then it is easy to see that there is a cover of U in C with at most k sets if and only if the DAG G has an arborescence rooted at s with total weight at least nm − k .
{}
{'log_upvote_score': 4, 'links': ['https://cstheory.stackexchange.com/questions/4088', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/189/']}
jdg_379305
stackexchange
llm_judgeable_groundtruth_similarity
614665
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 recently got stuck on evaluating the following integral,$$ \int_{0}^{3} \frac{e^{-x^2}}{\sqrt{1-x^2}} \,dx. $$Is it possible to evaluate this integral in a closed form? I am not sure if there is one, but the integrand seems simple enough, so I hope it might exist. Now provide the response and nothing else.
Let's decompose your integral in three terms :\begin{align}I&:=\int_0^3 \frac{e^{-x^2}}{\sqrt{1-x^2}} \,dx=I_1+I_2+I_3\\&=\int_0^1 \frac{e^{-x^2}}{\sqrt{1-x^2}} \,dx+\int_1^\infty \frac{e^{-x^2}}{\sqrt{1-x^2}} \,dx-\int_3^\infty \frac{e^{-x^2}}{\sqrt{1-x^2}} \,dx\\&=\int_0^{\pi/2} \frac{e^{-\sin(t)^2}}{\sqrt{1-\sin(t)^2}} \,d(\sin(t))+\int_0^\infty \frac{e^{-\cosh(u)^2}}{i\sqrt{\cosh(u)^2-1}} \,d\left(\cosh(u)\right)-\int_3^\infty \frac{e^{-x^2}}{\sqrt{1-x^2}} \,dx\\&=\int_0^{\pi/2} e^{\cos(2t)/2-1/2}\,dt-i\int_0^\infty e^{-\cosh(2u)/2-1/2} \,du-\int_3^\infty \frac{e^{-x^2}}{\sqrt{1-x^2}} \,dx\\&=\frac 1{2\,\sqrt{e}}\left(\pi\,\operatorname{I}_0\left(\frac 12\right)-i\operatorname{K}_0\left(\frac 12\right)\right)-\int_3^\infty \frac{e^{-x^2}}{\sqrt{1-x^2}} \,dx\\\end{align} Using the integral for $\operatorname{I}$ , the integral for $\operatorname{K}$ . Wolfram Alpha proposes to simplify this as $\;\displaystyle I=-\frac {i}{2\,\sqrt{e}}\,\operatorname{K}_0\left(-\frac 12\right)-\int_3^\infty \frac{e^{-x^2}}{\sqrt{1-x^2}} \,dx\;$ (probably using this relation for $m=1,n=0$) but there is a sign error in its result for the real part. In summary (for $x>1$ the terms are imaginary since $1-x^2<0$) : the first term is real $\quad\displaystyle I_1=\frac {\pi}{2\,\sqrt{e}}\,\operatorname{I}_0\left(\frac 12\right)\approx 1.013219033$ the second is imaginary $\displaystyle I_2=-\frac {i}{2\,\sqrt{e}}\,\operatorname{K}_0\left(-\frac 12\right)\approx -i\cdot 0.2803442545$ the remaining term is imaginary too and rather small : $$I_3=-\int_3^\infty \frac{e^{-x^2}}{\sqrt{1-x^2}} \,dx=\frac {i}{\sqrt{e}}\int_{\operatorname{arccosh}(3)}^\infty e^{-\cosh(2u)/2} \,du\approx i\cdot 0.000006566431462$$ I dont think it may be written in 'closed-form' except possibly as an 'incomplete modified Bessel function' or something like that (i.e. nearly equivalent to the integral definition...). An approximation is obtained with $\displaystyle I_3\approx \frac {i}{2\,\sqrt{e}}\operatorname{Ei}\left(-\frac{e^{2\,\operatorname{arccosh}(3)}}4\right)$ since $\displaystyle \int_a^\infty e^{-\frac 14 e^{2u}} \,du=\frac 12\operatorname{Ei}\left(-\frac{e^{2a}}4\right)\approx\frac{e^{-e^{2a}/4}}{2\,e^{2a}/4}\;$ (with $\operatorname{Ei}$ the exponential integral ). (btw $\,e^{2\,a}=e^{2\,\operatorname{arccosh}(3)}=17+12\sqrt{2}$) and we may get many better ones but not the asked closed form...
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/614665', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/103391/']}
jdg_379306
stackexchange
llm_judgeable_groundtruth_similarity
1048374
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: Look at this problem: Two individuals, $A$ and $B$, both require kidney transplants. If she does not receive a new kidney, then $A$ will die after an exponential time with rate $\mu_A$, and $B$ after an exponential time with rate $\mu_B$. New kidneys arrive in accordance with a Poisson process having rate $\lambda$. It has been decided that the first kidney will go to $A$ (or to $B$ if $B$ is alive and $A$ is not at that time) and the next one to $B$ (if still living). What is the probability that $B$ obtains a new kidney? The solution that the author has offered for this problem is $$\frac{\lambda}{\lambda+\mu_B}\frac{\lambda+\mu_A}{\lambda+\mu_A+\mu_B}$$ but I have another answer to this problem as below: $$\begin{align*}Pr(B\text{ obtains kidney})&=Pr(B\text{ obtains kidney}\mid\space A\space is \space alive)\cdot Pr(A\space is \space alive)\\[0.2cm]&+Pr(B\text{ obtains kidney}\mid\space A\space is\space not \space alive)\cdot Pr(A\space is\space not \space alive)\\[0.2cm]&=\frac{\lambda}{\lambda+\mu_B}\frac{\mu_A}{\lambda+\mu_A}+\frac{\lambda}{\lambda+\mu_A}Pr(B\text{ obtains kidney}\mid \space A\space is \space alive)\end{align*}$$ Now as when $A$ is alive while the first kidney arrives, $B$ must wait for the second kidney and the distribution of the second kidney arrival time is a Gamma distribution with parameters $n=2,\lambda$ and hence $$Pr(B\text{ obtains kidney}\mid \space A\space is \space alive)=Pr(X_1+X_2<X_B)$$in which $X_1+X_2$ is the time of arrival of the second kidney, and $X_B$ is the death time of $B$, so we have $$Pr(B\text{ obtains kidney}\mid \space A\space is \space alive)=Pr(X_1+X_2<X_B)=\left(\frac{\lambda}{\lambda+\mu_B}\right)^2$$So we have $$\begin{align*}Pr(B\text{ obtains kidney})&=\frac{\lambda}{\lambda+\mu_B}\frac{\mu_A}{\lambda+\mu_A}+\frac{\lambda}{\lambda+\mu_A}Pr(B\text{ obtains kidney}\mid \space A\space is \space alive)\\&=\frac{\lambda}{\lambda+\mu_B}\frac{\mu_A}{\lambda+\mu_A}+\frac{\lambda}{\lambda+\mu_A}\left(\frac{\lambda}{\lambda+\mu_B}\right)^2\end{align*}$$and obviously is different with the answer of the book. Can any one help me to find my mistake? Now provide the response and nothing else.
You have $3$ exponential times ("clocks") running. These are $A$'s lifetime, with rate $μ_Α$, $Β$'s lifetime, with rate $μ_Β$ and the time until the next kidney arrival, with rate $λ$. The author's solution is justified as follows (although there are also faster ways to explain it). $B$ will obtain a kidney if following cases obtain: $A$'s "clock" expires first, which occurs with probability $$\frac{μ_Α}{λ+μ_Α+μ_Β}$$ (minimum of independent exponential random variables) and then from the two remaining "times" ($B$'s lifetime and time for next kidney arrival), the time for the next kidney arrival expires first, which occurs with probability $$\frac{λ}{λ+μ_Β}$$ (here we used the memoryless property of the exponential distribution, to obtain that the remaining times are again exponentially distributed). the time until the first kidney arrival expires first, which occurs with probability $$\frac{λ}{λ+μ_Α+μ_Β}$$ and then from the two remaining times ($B$'s lifetime and time for next kidney arrival, remember that $A$ took the first kidney), the time for the next kidney arrival expires first, which occurs with probability $$\frac{λ}{λ+μ_Β}$$ Bring these together you obtain the solution $$\frac{μ_Α}{λ+μ_Α+μ_Β}\frac{λ}{λ+μ_Β}+\frac{λ}{λ+μ_Α+μ_Β}\frac{λ}{λ+μ_Β}=\frac{λ}{λ+μ_Β}\frac{λ+μ_Α}{λ+μ_Α+μ_Β}$$ The mistake in your approach is that you ignore one "clock". Therefore you never get three terms in the denominators, despite the fact that there are three times (clocks) running. For example when you calculate the probability $Pr(B \text{ obtains a kidney} \mid A\space is\space not \space alive)$ ( where $A$ is not alive when the first kidney arrives) you have apparently ignored the fact that $B$ could have died before $A$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1048374', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/118773/']}
jdg_379307
stackexchange
llm_judgeable_groundtruth_similarity
4888942
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What is the difference between defining View Params like this: <f:metadata> <f:viewParam name="id" value="#{someBean.id}"/></f:metadata> And defining the property in the ManagedBean like this: @Inject @ManagedProperty(value = "#{param.id}")private Integer id; Now provide the response and nothing else.
<f:viewParam> : Sets the value during update model values phase only (since it extends UIInput ). The set value is not available during @PostConstruct , so you need an additional <f:event type="preRenderView" listener="#{bean.init}" /> inside the <f:metadata> to do initialization/preloading based on the set values. Since JSF 2.2 you could use <f:viewAction> for that instead. Allows for nested <f:converter> and <f:validator> for more fine-grained conversion/validation. Even a <h:message> can be attached. Can be automatically included as GET query string in outcome target URLs using includeViewParams attribute of <h:link> or includeViewParams=true request parameter in any URL. Can be used on a @RequestScoped bean, but it requires the bean to be @ViewScoped if you want the view parameters to survive any validation failures caused by forms enclosed in the view, otherwise you need to manually retain all request parameters for the subsequent requests by <f:param> in the UICommand components, because the <f:viewParam> will be set on every request. Example : <f:metadata> <f:viewParam id="user_id" name="id" value="#{bean.user}" required="true" requiredMessage="Invalid page access. Please use a link from within the system." converter="userConverter" converterMessage="Unknown user ID." /></f:metadata><h:message for="user_id" /> with private User user; and an @FacesConverter("userConverter") . Invoking page by http://example.com/context/user.xhtml?id=123 will pass the id parameter through the converter and set the User object as a bean property. @ManagedProperty : Sets the value immediately after bean's construction. Set value is available during @PostConstruct which allows easy initialization/preloading of other properties based on the set value. Does not allow for declarative conversion/validation in view. Does not support being automatically included in outcome target URLs. Can be used on a bean of any scope, but it will be set only during bean's construction instead of on every request. Example : @Inject @ManagedProperty("#{param.id}")private Long id;private User user;@EJBprivate UserService userService;@PostConstructpublic void init() { user = userService.find(id);} Do note that you have to manage conversion and validation yourself whenever user is null by fiddling with FacesContext#addMessage() inside the @PostConstruct method. Also note that when #{param.id} is not a valid number, then an exception will be thrown before @PostConstruct is hit. If you want to deal with it, then you'd probably better make it a private String id . But much better is to use <f:viewParam> . You can use them both when both @PostConstruct and includeViewParams are mandatory. You only won't be able to apply fine-grained conversion/validation anymore. See also: What can <f:metadata>, <f:viewParam> and <f:viewAction> be used for? Communication in JSF 2.0 - Processing GET request parameters
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/4888942', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/392694/']}
jdg_379308
stackexchange
llm_judgeable_groundtruth_similarity
9682942
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have this code: List<Runnable> r = new ArrayList<>(); for(int i = 0; i < 10; i++) { r.add(new Runnable() { @Override public void run() { System.out.println(i); } }); } It obviously does not compile because i would need to be final to be used in the anonymous class. But I can't make it final because it is not. What would you do? A solution is to duplicate it but I thought there might be a better way: List<Runnable> r = new ArrayList<>(); for(int i = 0; i < 10; i++) { final int i_final = i; r.add(new Runnable() { @Override public void run() { System.out.println(i_final); } }); } EDIT just to make it clear, I used a Runnable here for the sake of the example, the question is really about anonymous classes, which could be anything else. Now provide the response and nothing else.
I think your solution is the simplest way. Another option would be to refactor the creation of the inner class into a factory function that does it for you, then your loop itself could be something clean like: List<Runnable> r = new ArrayList<>();for(int i = 0; i < 10; i++) { r.add(generateRunnablePrinter(i));} And the factory function could just declare a final parameter: private Runnable generateRunnablePrinter(final int value) { return new Runnable() { public void run() { System.out.println(value); } };} I prefer this refactored approach because it keeps the code cleaner, is relatively self descriptive and also hides away all the inner class plumbing. Random digression: if you consider anonymous inner classes to be equivalent to closures, then generateRunnablePrinter is effectively a higher order function. Who said you can't do functional programming in Java :-)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9682942', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/829571/']}
jdg_379309
stackexchange
llm_judgeable_groundtruth_similarity
13708179
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: For some reason my form is working in every browser but Internet Explorer. Here is the HTML: This was designed by someone other than me. <label for="name">Name:</label><br /> <input name="name" type="text" /><br /> <label for="address">Address:</label><br /> <input name="address" type="text" /><br /> <label for="phone">Phone:</label><br /> <input name="phone" type="text" /><br /> <label for="email">Email:</label><br /> <input name="email" type="text" /><br /> <input class="button" name="submit" style="margin-top:10px;" type="button" value="Join Club" /></div> Here is the JavaScript: This was designed by someone other than me. <script type="text/javascript"> ///////////////////////////////////////////////ARRAY DUMP FUNCTION function dump(a,b){var c="";if(!b)b=0;var d="";for(var e=0;e<b+1;e++)d+=" ";if(typeof a=="object"){for(var f in a){var g=a[f];if(typeof g=="object"){c+=d+"'"+f+"' ...\n";c+=dump(g,b+1)}else{c+=d+"'"+f+"' => \""+g+'"\n'}}}else{c="===>"+a+"<===("+typeof a+")"}return c} /////////////////////////////////////////////$(document).ready( function() { $('.clubregister input[name="submit"]').click( function(event) { event.preventDefault(); /*alert('This section is under construction, please contact us to get set up!\n Sorry for the inconvenience');return false;*/ //CREATE ARRAY FROM FORM DATA SERIALIZED var $formData = $('.clubregister input[type="text"], .clubregister textarea').serializeArray(); //PUSH ACTION TO ARRAY $formData.push({'name':'action','value':'registerForClub'}); //SEND DATA TO HANDLER $.ajax({ url:'http://torkliftcentralrv.com/club_register_handle.php', dataType:'json', async:false, data:$formData, success: function(data) { //console.log(dump(data)); //CREATE MESSAGE var message = ''; var consolemessage = ''; //IF ERRORS if(typeof data['error'] !== 'undefined') { //APPEND ERRORS TO MESSAGE $.each( data['error'], function( index,data) { message += (data + "\n"); }); } //IF MESSAGES if(typeof data['message'] !== 'undefined') { //APPEND MESSAGES TO MESSAGE $.each( data['message'], function( index,data) { message += (data + "\n"); }); } //IF CONSOLE MESSAGES if(typeof data['console'] !== 'undefined') { //APPEND CONSOLE MESSAGES TO MESSAGE $.each( data['console'], function( index,data) { consolemessage += (data + "\n"); }); } //IF SUCCESS SENT FROM SERVER if(typeof data['success'] !== 'undefined') { //CLEAR FORM $('.clubregister input[type="text"], .clubregister textarea').val(''); } alert(message); console.log(consolemessage); } }); });}); Any Ideas? Now provide the response and nothing else.
Join the table with itself and give it two different aliases ( A and B in the following example). This allows to compare different rows of the same table. SELECT DISTINCT A.IdFROM Address A INNER JOIN Address B ON A.Id = B.Id AND A.[Adress Code] < B.[Adress Code]WHERE A.Address <> B.Address The "less than" comparison < ensures that you get 2 different addresses and you don't get the same 2 address codes twice. Using "not equal" <> instead, would yield the codes as (1, 2) and (2, 1); each one of them for the A alias and the B alias in turn. The join clause is responsible for the pairing of the rows where as the where-clause tests additional conditions. The query above works with any address codes. If you want to compare addresses with specific address codes, you can change the query to SELECT A.IdFROM Address A INNER JOIN Address B ON A.Id = B.IdWHERE A.[Adress Code] = 1 AND B.[Adress Code] = 2 AND A.Address <> B.Address I imagine that this might be useful to find customers having a billing address (Adress Code = 1 as an example) differing from the delivery address (Adress Code = 2) .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13708179', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1264798/']}
jdg_379310
stackexchange
llm_judgeable_groundtruth_similarity
17080099
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 matrix m and a vector v . I would like to multiply first column of matrix m by the first element of vector v , and multiply the second column of matrix m by the second element of vector v , and so on. I can do it with the following code, but I am looking for a way which does not require the two transpose calls. How can I do this faster in R? m <- matrix(rnorm(120000), ncol=6)v <- c(1.5, 3.5, 4.5, 5.5, 6.5, 7.5)system.time(t(t(m) * v))# user system elapsed # 0.02 0.00 0.02 Now provide the response and nothing else.
Use some linear algebra and perform matrix multiplication, which is quite fast in R . eg m %*% diag(v) some benchmarking m = matrix(rnorm(1200000), ncol=6) v=c(1.5, 3.5, 4.5, 5.5, 6.5, 7.5)library(microbenchmark)microbenchmark(m %*% diag(v), t(t(m) * v))## Unit: milliseconds## expr min lq median uq max neval## m %*% diag(v) 16.57174 16.78104 16.86427 23.13121 109.9006 100## t(t(m) * v) 26.21470 26.59049 32.40829 35.38097 122.9351 100
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/17080099', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2034698/']}
jdg_379311
stackexchange
llm_judgeable_groundtruth_similarity
30862162
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 working on an Android App, in which the server sends an OTP and the user needs to enter this OTP in the App, to SignUp for my App. What I want is, that my App should be able to automatically read the OTP sent by the server. How can I achieve this? Any help or guidance in this regard would be highly appreciated. Now provide the response and nothing else.
You can try using a simple library like After installing via gradle and adding permissions initiate SmsVerifyCatcher in method like onCreate activity: smsVerifyCatcher = new SmsVerifyCatcher(this, new OnSmsCatchListener<String>() { @Override public void onSmsCatch(String message) { String code = parseCode(message);//Parse verification code etCode.setText(code);//set code in edit text //then you can send verification code to server }}); Also, override activity lifecicle methods: @Overrideprotected void onStart() { super.onStart(); smsVerifyCatcher.onStart();}@Overrideprotected void onStop() { super.onStop(); smsVerifyCatcher.onStop();}/** * need for Android 6 real time permissions */@Overridepublic void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); smsVerifyCatcher.onRequestPermissionsResult(requestCode, permissions, grantResults);}public String parseCode(String message) { Pattern p = Pattern.compile("\\b\\d{4}\\b"); Matcher m = p.matcher(message); String code = ""; while (m.find()) { code = m.group(0); } return code;}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30862162', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1903022/']}
jdg_379312
stackexchange
llm_judgeable_groundtruth_similarity
47997652
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 Node.js project that I'm testing using Jest. I have several test files that have the same setup requirement. Previously, all these tests were in one file, so I just had a beforeAll(...) that performed the common setup. Now, with the tests split into multiple files, it seems like I have to copy/paste that beforeAll(...) code into each of the files. That seems inelegant - is there a better way to do this, ideally where I can just write my beforeAll(...) /setup logic once, and "require" it from multiple test files? Note that there are other tests in my test suite that don't require this setup functionality, so I don't want to make all my tests run this setup (just a particular subset of test files). Now provide the response and nothing else.
If you're using Jest >=20, you might want to look into creating a custom jest-environment for the tests that require this common setup. This would be a module that extends either jest-environment-node or jest-environment-jsdom , and implements async setup() , async teardown() , and async runScript() to do this setup work. You can then add a @jest-environment my-custom-env directive to those files that require this setup. See the Jest config docs for testEnvironment for details on how to set this up; there's a simple example there.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/47997652', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4451284/']}
jdg_379313
stackexchange
llm_judgeable_groundtruth_similarity
26964139
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to understand how one can utilize Auto Layout to position items relative to other views percentage-wise. For example, I recently learned that you can specify a view's bottom should lie 4% higher than its superview's bottom by using this: self.view.addConstraint(NSLayoutConstraint(item: label, attribute: .Bottom, relatedBy: .Equal, toItem: self.view, attribute: .Bottom, multiplier: 0.96, constant: 0)) This makes sense to me because a multiplier of 1 would align it right at the view's bottom, so you can decrease that amount by 4 percent by changing the multiplier to 0.96. But how can you do the same in the other direction? You want to specify a label's top should begin 4% down from the superview's top. If you use that same line but change the attributes to .Top , that means it would be 4% higher than the superview's top (but it actually doesn't move it off screen). You can't have a negative multiplier I don't think, and I don't believe a value greater than 1 does anything when constant is 0. So how do you get that set up? I have the same question for implementing leading and trailing. Trailing is easy. If you want it 10% from the right: self.view.addConstraint(NSLayoutConstraint(item: label, attribute: .Trailing, relatedBy: .Equal, toItem: self.view, attribute: .Trailing, multiplier: 0.9, constant: 0)) It makes sense because you dial it back 0.1 or 10% instead of aligning fully at 1.0. But how do you do the same for leading? I thought you might be able to set the label's leading relative to the view's trailing, then set the multiplier to 0.1. In my mind that would mean the label would start at the very far right but then be dialed back 90%, therefore obtaining the desired 10% from the left. But that's not the case, I'm not sure why. Can you explain how this is works, how to properly use multiplier to obtain these relative layouts? To make it easy, let's say you'd like to create a label that has top and bottom 10% of the superview's height, and trailing and leading 10% of the superview's width. On an iPhone in portrait there's going to be more padding above and below the label than there is padding to the left and right of it, like so (yes it's drawn to scale): But let's say on the iPad it's going to be shown in a view that's a perfect square. Therefore the padding will be the same amount all around, like so: The question is how do you define such constraints to be dynamic in value, as opposed to setting a fixed value for a constant. I already know how to do bottom and trailing, but top and leading has me stumped. I'm hoping to understand how to use multiplier to do more advanced layouts, for example, specifying a label's top should lie 10% beneath another label's bottom, as opposed to setting it to a fixed constant. Now provide the response and nothing else.
There are a couple ways to do this. In the simplest case, you've already almost got it: if you want the horizontal boundaries to be at 10% and 90%, then you need to specify both constraints with respect to the trailing edge of the superview -- so Subview.Trailing locks to Superview.Trailing with a multiplier of 0.9 , as you say, but then Subview.Leading also locks to Superview.Trailing , just with a multiplier of 0.1 : (and similarly for top / bottom) On the other hand, the case you mention at the end is a little more complicated: "specifying a label's top should lie 10% beneath another label's bottom." For that you probably won't be able to use fixed percentage insets like the previous case. Instead, you can create an invisible spacer view between them: add a constraint with Spacer.Height = 0.1 * Superview.Height and then attach it between the two labels. (You can also handle the previous case with these spacer views, but for that case it isn't really necessary.)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/26964139', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1795356/']}
jdg_379314
stackexchange
llm_judgeable_groundtruth_similarity
55156541
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: this is my angular materiel auto complete code <input type="search" id="setId" name="setId" [attr.list]='collectionType' [(ngModel)]="selValue" class="text-box" placeholder="--Select--" (focus)="ValidateParent()" (keyup.tab)="test()" (keyup)="EmitValues($event)" [id]="setId" [matAutocomplete]="auto" [title]="selValue" [placeholder]='WaterMarkText'><div [hidden]="IsCascading"> <mat-autocomplete [id]="collectionType" #auto="matAutocomplete" (optionSelected)='onChange($event)'> <mat-option *ngFor="let items of codeList" [value]="items.text" [attr.data-text]='items.text' [id]="items.value"> {{items.text}} </mat-option> </mat-autocomplete></div> Angular material had a problem with tab selection.like the materiel auto complete not able to select the value while click the tab button. but it's working while click the enter button. So manually I need to overwrite the enter key event on tab key event. How could possible? Now provide the response and nothing else.
Improve my comment, and based on the response we can create a directive import { Directive, AfterViewInit, OnDestroy, Optional} from '@angular/core';import { MatAutocompleteTrigger} from '@angular/material';@Directive({ selector: '[tab-directive]'})export class TabDirective implements AfterViewInit, OnDestroy { observable: any; constructor(@Optional() private autoTrigger: MatAutocompleteTrigger) {} ngAfterViewInit() { this.observable = this.autoTrigger.panelClosingActions.subscribe(x => { if (this.autoTrigger.activeOption) { this.autoTrigger.writeValue(this.autoTrigger.activeOption.value) } }) } ngOnDestroy() { this.observable.unsubscribe(); }} You use: <input tab-directive type="text" matInput [formControl]="myControl" [matAutocomplete]="auto" > (see stackblitz ) Update We can control only tab.key, else always you close, you get the selected value, so @Directive({ selector: '[tab-directive]'})export class TabDirective { observable: any; constructor(@Optional() private autoTrigger: MatAutocompleteTrigger) {} @HostListener('keydown.tab', ['$event.target']) onBlur() { if (this.autoTrigger.activeOption) { this.autoTrigger.writeValue(this.autoTrigger.activeOption.value) } }} (see a new stackblitz) Update 2 I don't believe this answer has so many upvotes because it's wrong. As @Andrew allen comments, the directive not update the control. Well, It's late, but I try to solve. One Option is use this.autoTrigger._onChange(this.autoTrigger.activeOption.value) Anohter idea is inject the ngControl, so constructor(@Optional() private autoTrigger: MatAutocompleteTrigger, @Optional() private control: NgControl) {}ngAfterViewInit() { this.observable = this.autoTrigger.panelClosingActions.subscribe(x => { if (this.autoTrigger.activeOption) { const value = this.autoTrigger.activeOption.value; if (this.control) this.control.control.setValue(value, { emit: false }); this.autoTrigger.writeValue(value); } })}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/55156541', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2218635/']}
jdg_379315
stackexchange
llm_judgeable_groundtruth_similarity
286803
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Disclaimer : Feel free to downvote or vote to close, if this is again trivial (I seem to have a bad day today; I promise that if this is again a bummer question, I will wait $\geq 1$ day before asking new questions). For any space $(X,\tau)$, let $\text{Cont}(X,X)$ denote the set of continuous self-maps of $X$ and let $X^X$ denote the set of all self-maps of $X$, endowed with the product topology. What is an example of a connected $T_2$-space $(X,\tau)$ such that $\text{Cont}(X,X)$ is not dense in $X^X$? Now provide the response and nothing else.
Pick $X$ such that there are path-components $Y \neq Z$, and $y \in Y$, $z\in Z$ with the conditions: $y$ belongs to the interior of $Y$, $z$ belongs to the interior of $Z$, and $Y$ is not a singleton. Choose $x\in Y\smallsetminus\{y\}$.Then we can't approach with continuous maps a map mapping $x \mapsto z$ and $y \mapsto y$. Indeed, a map close enough should map $y \mapsto y'$, $x \mapsto z'$ with $y'\in Y$, $z'\in Z$. The image of a path joining $x$ to $y$ would thus join $y'$ to $z'$, contradiction. Now it's easy to find a compact connected subset of the plane with these conditions. For instance, the closure of the graph $W$ of the function $[-1,1]\smallsetminus\{0\}\to [-1,1]$ mapping $x\neq 0$ to $\sin(\pi/x)$, which is connected with 3 path-components (the two connected components of $W$, and the segment $\{0\}\times [-1,1]$), with $y=(-1,0)$, $z=(1,0)$.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/286803', 'https://mathoverflow.net', 'https://mathoverflow.net/users/8628/']}
jdg_379316
stackexchange
llm_judgeable_groundtruth_similarity
27139371
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 playing with move constructors and move assignments and i've stumbled on this problem. First code: #include <iostream>#include <utility>class Foo { public: Foo() {} Foo(Foo&& other) { value = std::move(other.value); other.value = 1; //since it's int! } int value; private: Foo(const Foo& other);};void Bar(Foo&& x) { std::cout << "# " << x.value << std::endl;}int main() { Foo foo; foo.value = 5; Bar(std::move(foo)); std::cout << foo.value << std::endl; return 0;} To my mind, when i use: Bar(std::move(foo)); Program should "move" foo object to temp object created using move constructor in Bar function. Doing so would leave foo object's value equal zero. Unfortunatly it seams that object held in Bar function as parameter is some sort of reference, since it doesnt "move" original value but using Bar's parameter i can change it. Would someone mind expalining me why i see in console: #55 instead of #50 //this should be done by move constructor? Now provide the response and nothing else.
An rvalue reference is (surprise:) a reference indeed. You can move from it, but std::move does not move. So, if you don't move from it, you'll actually operate on the rvalue object (through the rvalue reference). The usual pattern would be void foo(X&& x){ X mine(std::move(x)); // x will not be affected anymore} However, when you do void foo(X&& x){ x.stuff(); x.setBooDitty(42);} effectively, X&& is just acting as a traditional reference
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27139371', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1020591/']}
jdg_379317
stackexchange
llm_judgeable_groundtruth_similarity
275050
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 run a website where about 10 million files (book covers) are stored in 3 levels of subdirectories, ranging [0-f]: 0/0/0/0/0/1/...f/f/f/ This leads to around 2400 files per directory, which is very fast when we need to retrieve one file. This is moreover a practice suggested by many questions . However, when I need to backup these files, it takes many days just to browse the 4k directories holding 10m files. So I'm wondering if I could store these files in a container (or in 4k containers), which would each act exactly like a filesystem (some kind of mounted ext3/4 container?). I guess this would be almost as efficient as accessing directly a file in the filesystem, and this would have the great advantage of being copied to another server very efficiently. Any suggestion on how to do this best? Or any viable alternative (noSQL, ...) ? Now provide the response and nothing else.
Options for quickly accessing and backing up millions of files Borrow from people with similar problems This sounds very much like an easier sort of problem that faces USENET news servers and caching web proxies: hundreds of millions of small files that are randomly accessed. You might want to take a hint from them (except they don't typically ever have to take backups). http://devel.squid-cache.org/coss/coss-notes.txt http://citeseer.ist.psu.edu/viewdoc/download;jsessionid=4074B50D266E72C69D6D35FEDCBBA83D?doi=10.1.1.31.4000&rep=rep1&type=pdf Obviously the cyclical nature of the cyclic news filesystem is irrelevant to you, but the lower level concept of having multiple disk files/devices with packed images and a fast index from the information the user provides to look up the location information is very much appropriate. Dedicated filesystems Of course, these are just similar concepts to what people were talking about with creating a filesystem in a file and mounting it over loopback except you get to write your own filesystem code. Of course, since you said your system was read-mostly, you could actually dedicate a disk partition (or lvm partition for flexibility in sizing) to this one purpose. When you want to back up, mount the filesystem read-only and then make a copy of the partition bits. LVM I mentioned LVM above as being useful to allow dynamic sizing of a partition so that you don't need to back up lots of empty space. But, of course, LVM has other features which might be very much applicable. Specifically the "snapshot" functionality which lets you freeze a filesystem at a moment in time. Any accidental rm -rf or whatever would not disturb the snapshot. Depending on exactly what you are trying to do, that might be sufficient for your backups needs. RAID-1 I'm sure you are familiar with RAID already and probably already use it for reliability, but RAID-1 can be used for backups as well, at least if you are using software RAID (you can use it with hardware RAID, but that actually gives you lower reliability because it may require the same model/revision controller to read). The concept is that you create a RAID-1 group with one more disk than you actually need connected for your normal reliability needs (eg a third disk if you use software RAID-1 with two disks, or perhaps a large disk and a hardware-RAID5 with smaller disks with a software RAID-1 on top of the hardware RAID-5). When it comes time to take a backup, install a disk, ask mdadm to add that disk to the raid group, wait until it indicates completeness, optionally ask for a verification scrub, and then remove the disk. Of course, depending on performance characteristics, you can have the disk installed most of the time and only removed to exchange with an alternate disk, or you can have the disk only installed during backups).
{}
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/275050', 'https://serverfault.com', 'https://serverfault.com/users/83039/']}
jdg_379318
stackexchange
llm_judgeable_groundtruth_similarity
10134956
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Could someone please compile and execute the small sample code I provided below? Please let me know if the shift key modifier works properly for you. This example is suppose to demonstrate the key press functionality in gtk. It works fine for simple key presses and even works with the control key modifier, but it does not work with the shift key modifier. /* * * compile command: * * gcc keypress3.c -o keypress3 `pkg-config --libs --cflags gtk+-2.0` * */#include <gtk/gtk.h>#include <gdk/gdkkeysyms.h>gbooleanon_key_press (GtkWidget *widget, GdkEventKey *event, gpointer user_data);int main (int argc, char *argv[]){ GtkWidget *window; gtk_init (&argc, &argv); window = gtk_window_new (GTK_WINDOW_TOPLEVEL); g_signal_connect (G_OBJECT (window), "destroy", G_CALLBACK (gtk_main_quit), NULL); g_signal_connect (G_OBJECT (window), "key_press_event", G_CALLBACK (on_key_press), NULL); gtk_widget_show_all (window); gtk_main (); return 0;}gbooleanon_key_press (GtkWidget *widget, GdkEventKey *event, gpointer user_data){ switch (event->keyval) { case GDK_p: printf("key pressed: %s\n", "p"); break; case GDK_s: if (event->state & GDK_SHIFT_MASK) { printf("key pressed: %s\n", "shift + s"); } else if (event->state & GDK_CONTROL_MASK) { printf("key pressed: %s\n", "ctrl + s"); } else { printf("key pressed: %s\n", "s"); } break; case GDK_m: if (event->state & GDK_SHIFT_MASK) { printf("key pressed: %s\n", "shift + m"); } else if (event->state & GDK_CONTROL_MASK) { printf("key pressed: %s\n", "ctrl + m"); } else { printf("key pressed: %s\n", "m"); } break; default: return FALSE; } return FALSE; } The output I am getting: key pressed: mkey pressed: ctrl + mkey pressed: pkey pressed: ctrl + skey pressed: s I get nothing when I press shift + s or shift + m, so it seems that I am not quite getting how the GDK_SHIFT_MASK should be used even though I have read the documentation and I have seen plenty of other examples where it appears to be used exactly the same way. Now provide the response and nothing else.
The value of event->keyval when shift+s is pressed is GDK_S, not GDK_s. In other words, GDK has already interpreted the keyboard for you, giving you the symbol 'S', not 's'. The shift mask is still set, though. You can see this by adding a case for GDK_S: ...case GDK_S: // add this linecase GDK_s: if (event->state & GDK_SHIFT_MASK) { printf("key pressed: %s\n", "shift + s"); } else if (event->state & GDK_CONTROL_MASK) {....
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10134956', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/813149/']}
jdg_379319
stackexchange
llm_judgeable_groundtruth_similarity
10317691
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 function in a Fortran executable and I need to make it a dll file so I can call it's functions from a C# program FUNCTION TSAT11(P) C ** IGNORE IMPLEMENTATION ** TSAT11 = SX*TSAT2(X) + SXL1*TSAT3-273.15 RETURN END P is a float and the function returns a float The thing here that I don't know anything in fortran nor calling dlls from C#, so please explain a little more. I'm using Compaq Visual Fortran and C# 2008. Thank you for your time. (If you like you can see the full code Here [It's a program to calculate water and steam properties]) Now provide the response and nothing else.
Here is an example using single precision floats. Fortran library contains: FUNCTION TSAT11(P) !DEC$ ATTRIBUTES ALIAS:'TSAT11' :: TSAT11!DEC$ ATTRIBUTES DLLEXPORT :: TSAT11!DEC$ ATTRIBUTES VALUE :: PREAL, INTENT(IN) :: P REAL :: TSAT11 ! Examle calculation TSAT11 = P - 273.15RETURN END FUNCTION With the calling function class Program{ [DllImport("calc.dll")] static extern float TSAT11(float P); static void Main(string[] args) { float p = 300f; float t = TSAT11(p); // returns 26.8500061 } } Similarly for an array (must declare the size) FUNCTION TSAT12(P,N) !DEC$ ATTRIBUTES ALIAS:'TSAT12' :: TSAT12!DEC$ ATTRIBUTES DLLEXPORT :: TSAT12!DEC$ ATTRIBUTES VALUE :: NINTEGER, INTENT(IN) :: NREAL, INTENT(IN) :: P(N)REAL :: TSAT12 ! Examle calculation TSAT12 = SQRT( DOT_PRODUCT(P,P) )RETURN END FUNCTION with calling C# code class Program{ [DllImport("calc.dll")] static extern float TSAT12(float[] P, int N); static void Main(string[] args) { float[] p2=new float[] { 0.5f, 1.5f, 3.5f }; float t2=TSAT12(p2, p2.Length); //returns 3.84057283 } }
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10317691', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1336271/']}
jdg_379320
stackexchange
llm_judgeable_groundtruth_similarity
235307
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 noticed unusual traffic coming from my workstation the last couple of days. I am seeing HEAD requests sent to random character URLs, usually three or four within a second, and they appear to be coming from my Chrome browser. The requests repeat only three or four times a day, but I have not identified a particular pattern. The URL characters are different for each request. Here is an example of the request as recorded by Fiddler 2: HEAD http://xqwvykjfei/ HTTP/1.1Host: xqwvykjfeiProxy-Connection: keep-aliveContent-Length: 0User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.13 (KHTML, like Gecko) Chrome/9.0.597.98 Safari/534.13Accept-Encoding: gzip,deflate,sdchAccept-Language: en-US,en;q=0.8Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 The response to this request is as follows: HTTP/1.1 502 Fiddler - DNS Lookup FailedContent-Type: text/htmlConnection: closeTimestamp: 08:15:45.283Fiddler: DNS Lookup for xqwvykjfei failed. No such host is known I have been unable to find any information through Google searches related to this issue. I do not remember seeing this kind of traffic before late last week, but it may be that I just missed it before. The one modification I made to my system last week that was unusual was adding the Delicious add-in/extension to both IE and Chrome. I have since removed both of these, but am still seeing the traffic. I have run virus scan (Trend Micro) and HiJackThis looking for malicious code, but I have not found any. I would appreciate any help tracking down the source of the requests, so I can determine if they are benign, or indicative of a bigger problem. Thanks. Now provide the response and nothing else.
This is actually legitimate behaviour. Some ISPs improperly respond to DNS queries to non-existent domains with an A record to a page that they control, usually with advertising, as a "did you mean?" kind of thing, instead of passing NXDOMAIN as the RFC requires. To combat this, Chrome makes several HEAD requests to domains which cannot exist to check how the DNS servers resolve them. If they return A records, Chrome knows to perform a search query for the host instead of obeying the DNS record so that you are not affected by the ISPs improper behaviour. [1]
{}
{'log_upvote_score': 7, 'links': ['https://serverfault.com/questions/235307', 'https://serverfault.com', 'https://serverfault.com/users/5162/']}
jdg_379321
stackexchange
llm_judgeable_groundtruth_similarity
3104814
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I came up with a proof for this question, rather simple, that I didn't find here. And I wondered if my proof was correct, and if anyone had a different proof ? Thanks for you time. I will show that only polynomials in $\mathbb{Q}[X]$ work. My proof is based on induction on the degree of the polynomial, For d = 0, it is obvious. Suppose the result true for polynomials of degree $d$ , and let P be a polynomial of degree $d+1$ that satisfies the problem, $P(X) = a_0+\ldots+a_{d+1}X^{d+1}$ . Evaluating at 0, we find $a_0\in \mathbb{Q}$ . Because $Q$ is stable by multiplication and addition, the polynomial $\dfrac{P-a_0}{X}$ is a polynomial of degree d that satisfies the constraints, the result follows by induction. Now provide the response and nothing else.
Pick any $\deg[f]+1$ rational numbers $q_0, q_2, \cdots, q_n$ . Now $f(q_i) \in \mathbb{Q}$ , and thus Lagrange interpolation on $(q_i, f(q_i))$ determines $f$ uniquely; But then $$\displaystyle f(x) = \sum_{0 \leq i \leq n}f(q_i) \frac{\prod_{j \neq i} (x - q_j)}{\prod_{j \neq i} (q_i - q_j)} \in \mathbb{Q}[x]$$ since each terms are so we're done.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3104814', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/631695/']}
jdg_379322
stackexchange
llm_judgeable_groundtruth_similarity
2437893
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: According to page 25 of the book A First Course in Real Analysis , an inductive set is a set of real numbers such that $0$ is in the set and for every real number $x$ in the set, $x + 1$ is also in the set and a natural number is a real number that every inductive set contains. The problem with that definition is that it is circular because the real numbers are constructed from the natural numbers. Now provide the response and nothing else.
Suppose we did start with some notion of "natural number" which we used to construct a model of the real numbers. Then even in this setting, the quoted definition is still not circular, because it's defining a new notion of "natural number" that will henceforth be used instead of the previous notion of "natural number". We could give the new notion a different name, but there isn't really any point; the new version of "natural numbers" has an obvious isomorphism with the old version so it's not really any different from the old one in any essential way. There are a number of reasons why an exposition of real analysis might construct the natural numbers from the real numbers; the two most prominent are: It is technically convenient to have the natural numbers be a subset of the real numbers It makes the exposition somewhat more agnostic about foundations; it simply needs the real numbers as a starting point
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2437893', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/137739/']}
jdg_379323
stackexchange
llm_judgeable_groundtruth_similarity
134462
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: The Law of large numbers addresses the issue of the average result of a large number of random trials. Is there a similar law which addresses the probability of obtaining an unusual result for a large number of trials? For instance, consider a normal probability distribution with mean 10 and standard deviation 2. I am testing a computational method which will run only if the result is above 18 , that is four standard deviations off the mean and so the likelyhood of ever seeing the if condition met is very low. Therefore, to test the method I must run a very large number of trials. Just as one could expect the average value of the trials to approach 10 as more trials are performed, one could also expect that the probability of receiving the unusual result 18 to increase as more trials are performed. Is there a term for this phenomenon? Now provide the response and nothing else.
You can use geometric distribution to reason about such events after several trials. Let $p$ be the probability of obtaining 18 or more ($p = P(X > 18)$). Then the amount of trials $k$ until success (that is, until 18+ is generated) is distributed according to the geometric distribution: $$ k \sim (1-p)^{k-1} p$$ Then you can use quantiles of that distribution to estimate how many trials you need to get this event in, say, 95% of runs. Or, just use the mean of that distribution ($\frac{1}{p}$) as the average number of trials until a rare event.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/134462', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/48409/']}
jdg_379324
stackexchange
llm_judgeable_groundtruth_similarity
28088
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: As usual I expect to be critisised for "duplicating" this question . But I do not! As Gjergji immediatelynotified, that question was from numerology. The one I ask you here(after putting it in my response ) is a mathematicsquestion motivated by Kevin's (O'Bryant) comment to the earlier post. Problem. For any $\epsilon>0$, there exists an $n$ such that $\|n/\log(n)\|<\epsilon$ where $\|\ \cdot\ \|$ denotes thedistance to the nearest integer. In spite of the simple formulation, it is likely thatthe diophantine problem is open. I wonder whether it followsfrom some known conjectures (for example, Schanuel's conjecture). Now provide the response and nothing else.
If $f(x)=\frac{x}{\log x}$, then $f'(x)=\frac{1}{\log x} - \frac{1}{(\log x)^2}$, which tends to zero as $x\rightarrow \infty$. Choose some large real number $x$ for which $f(x)$ is integral. Then the value of $f$ on any integer near $x$ must be very close to integral.
{}
{'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/28088', 'https://mathoverflow.net', 'https://mathoverflow.net/users/4953/']}
jdg_379325
stackexchange
llm_judgeable_groundtruth_similarity
22410254
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have the following code in a category that does rounding of corners. I would also like to draw a border. But the border is not shown on the rounded part of the corner. Here is the code - (void) roundTopCorners:(CGFloat) radius{ self.layer.masksToBounds = YES; CGRect bounds = self.bounds; UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:bounds byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerTopRight) cornerRadii:CGSizeMake(radius, radius)]; CAShapeLayer *maskLayer = [CAShapeLayer layer]; maskLayer.frame = bounds; maskLayer.path = maskPath.CGPath; maskLayer.strokeColor = [UIColor redColor].CGColor; self.layer.mask = maskLayer;} Now provide the response and nothing else.
The mask layer doesn't get drawn, just used to compute the mask. Try: -(void)roundCorners:(UIRectCorner)corners radius:(CGFloat)radius{ CGRect bounds = self.bounds; UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:bounds byRoundingCorners:corners cornerRadii:CGSizeMake(radius, radius)]; CAShapeLayer *maskLayer = [CAShapeLayer layer]; maskLayer.frame = bounds; maskLayer.path = maskPath.CGPath; self.layer.mask = maskLayer; CAShapeLayer* frameLayer = [CAShapeLayer layer]; frameLayer.frame = bounds; frameLayer.path = maskPath.CGPath; frameLayer.strokeColor = [UIColor redColor].CGColor; frameLayer.fillColor = nil; [self.layer addSublayer:frameLayer];}-(void)roundTopCornersRadius:(CGFloat)radius{ [self roundCorners:(UIRectCornerTopLeft|UIRectCornerTopRight) radius:radius];}-(void)roundBottomCornersRadius:(CGFloat)radius{ [self roundCorners:(UIRectCornerBottomLeft|UIRectCornerBottomRight) radius:radius];} The frame you're currently seeing drawn is the UITextField's normal frame, so set the frame style to none. You'll also have to adjust the insets to make up for the fact that with the frame style set to none there's normally no inset.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/22410254', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/717688/']}
jdg_379326
stackexchange
llm_judgeable_groundtruth_similarity
638898
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 recently started learning about micro-electronics, specifically the Arduino. I'm slowly going through the Arduino cookbook and have hit something I don't really understand. The circuit is a simple debounce circuit but I'm having trouble fully understanding what each component is accomplishing and how the current is flowing. In the picture and schematic below, why is the resistor used? Won't the capacitor by itself prevent switch debounce? I don't quite understand the flow of current through this circuit. Won't current always use the other path to get to ground? When would current even flow through the resistor? Is the resistor solely there as a pull-down resistor and nothing more? My goal is to fully understand each project as I work through it and I've been stuck on fully wrapping my head around this one for a week or so. Now provide the response and nothing else.
Adding a parallel capacitor there is a variant on a common method for switch debounce. It works by slowing the fall time of the switch voltage and so requires the MCU to use a Schmitt trigger input for reading this slow-moving switch voltage. The circuit you have is shown on the left below. On the right is the more commonplace form, found on many MCU/FPGA/etc demo' boards. The principles are the same. For your circuit on the left, assuming R1 and C1 are suitable values for the SW1 max. bounce period... At rest, consider Vsw1 to be GND as C1 has discharged through R1. Pressing SW1 charges C1 quickly with the first contact(s). As the contacts bounce apart, C1 will discharge through R1. But Vsw1 will not fall below a good logic HIGH before the contacts bounce together again. That repeats until the pressed contacts stop bouncing. Vsw1 always reads a good logic HIGH in that time i.e. above the VIH(min) of the MCU input pin. Releasing SW1 causes C1 to discharge through R1. Vsw1 falls relatively slowly to GND. As it passes through the indeterminate voltage range, between VIH(min) for a good logic HIGH and VIL(max) for a good logic LOW, the Schmitt trigger on the MCU input pin ensures a clean transition between detecting Vsw1 HIGH and detecting Vsw2 LOW. Without the capacitor, any switch pressed contact bounces would produce a sort of HIGH-LOW-HIGH-LOW... noise waveform on Vsw1. It can be considered is good practice for the MCU to then debounce the switch in software anyway but it's not a requirement. C1 will draw a spike current from the supply as the switch contacts connect. It theory this is an infinite current at t0 but the components and track impedances stop this happening and local circuit decoupling will stop the supply rail dipping. As said, this is a very common circuit, used without problems in very large numbers of boards that I first saw 40 years ago. simulate this circuit – Schematic created using CircuitLab
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/638898', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/324098/']}
jdg_379327
stackexchange
llm_judgeable_groundtruth_similarity
9709088
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The VS2005 documentation Guidelines for Overloading Equals() and Operator == (C# Programming Guide) states in part Overriding operator == in non-immutable types is not recommended. The newer .NET Framework 4 documentation Guidelines for Implementing Equals and the Equality Operator (==) omits that statement, although one post in Community Content repeats the assertion and references the older documentation. It seems that it is reasonable to override Equals() at least for some trivial mutable classes, such as public class ImaginaryNumber{ public double RealPart { get; set; } public double ImaginaryPart { get; set; }} In math, two imaginary numbers that have the same real part and the same imaginary part are in fact equal at the point in time that equality is tested. It is incorrect to assert that they are not equal , which would happen if separate objects with the same RealPart and ImaginaryPart were Equals() not overridden. On the other hand, if one overrides Equals() one should also override GetHashCode(). If an ImaginaryNumber that overrides Equals() and GetHashCode() is placed in a HashSet, and a mutable instance changes its value, that object would no longer be found in the HashSet. Was MSDN incorrect to remove the guideline about not overriding Equals() and operator== for non-immutable types? Is it reasonable to override Equals() for mutable types where "in the real world" equivalence of all properties means that the objects themselves are equal (as with ImaginaryNumber )? If it is reasonable, how does one best deal with potential mutability while an object instance is participating in a HashSet or something else that relies on GetHashCode() not changing? UPDATE Just came across this in MSDN Typically, you implement value equality when objects of the type are expected to be added to a collection of some sort, or when their primary purpose is to store a set of fields or properties. You can base your definition of value equality on a comparison of all the fields and properties in the type, or you can base the definition on a subset. But in either case, and in both classes and structs, your implementation should follow the five guarantees of equivalence: Now provide the response and nothing else.
I came to realize that I wanted Equals to mean two different things, depending on the context. After weighing the input here as well as here , I have settled on the following for my particular situation: I'm not overriding Equals() and GetHashCode() , but rather preserving the common but by no means ubiquitous convention that Equals() means identity equality for classes, and that Equals() means value equality for structs. The largest driver of this decision is the behavior of objects in hashed collections ( Dictionary<T,U> , HashSet<T> , ...) if I stray from this convention. That decision left me still missing the concept of value equality (as discussed on MSDN ) When you define a class or struct, you decide whether it makes sense to create a custom definition of value equality (or equivalence) for the type. Typically, you implement value equality when objects of the type are expected to be added to a collection of some sort, or when their primary purpose is to store a set of fields or properties. A typical case for desiring the concept of value equality (or as I'm terming it "equivalence") is in unit tests. Given public class A{ int P1 { get; set; } int P2 { get; set; }}[TestMethod()]public void ATest(){ A expected = new A() {42, 99}; A actual = SomeMethodThatReturnsAnA(); Assert.AreEqual(expected, actual);} the test will fail because Equals() is testing reference equality. The unit test certainly could be modified to test each property individually, but that moves the concept of equivalence out of the class into the test code for the class. To keep that knowledge encapsulated in the class, and to provide a consistent framework for testing equivalence, I defined an interface that my objects implement public interface IEquivalence<T>{ bool IsEquivalentTo(T other);} the implementation typically follows this pattern: public bool IsEquivalentTo(A other){ if (object.ReferenceEquals(this, other)) return true; if (other == null) return false; bool baseEquivalent = base.IsEquivalentTo((SBase)other); return (baseEquivalent && this.P1 == other.P1 && this.P2 == other.P2);} Certainly, if I had enough classes with enough properties, I could write a helper that builds an expression tree via reflection to implement IsEquivalentTo() . Finally, I implemented an extension method that tests the equivalence of two IEnumerable<T> : static public bool IsEquivalentTo<T> (this IEnumerable<T> first, IEnumerable<T> second) If T implements IEquivalence<T> that interface is used, otherwise Equals() is used, to compare elements of the sequence. Allowing the fallback to Equals() lets it work e.g. with ObservableCollection<string> in addition to my business objects. Now, the assertion in my unit test is Assert.IsTrue(expected.IsEquivalentTo(actual));
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9709088', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/141172/']}
jdg_379328
stackexchange
llm_judgeable_groundtruth_similarity
440399
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: If a person is sitting on a chair his momentum is zero and his uncertainty in position should be infinite. But we can obviously position him at most within few chair lengths. What am I missing? Do we have to invoke earth's motion, motion of the galaxy etc. to resolve the issue? Now provide the response and nothing else.
If a person is sitting on a chair his momentum is zero... How close to zero? The uncertainty principle says that if $\Delta x$ is the uncertainty in position and $\Delta p$ is the uncertainty in momentum, then $\Delta x\,\Delta p\sim \hbar$ . So, consider an object with the mass of a person, say $M = 70\ \mathrm{kg}$ . Suppose the uncertainty in this object's position is roughly the size of a proton, say $\Delta x = 10^{-15}\ \mathrm m$ . The uncertainty principle says that the uncertainty in momentum must be $$ \Delta p\sim\frac{\hbar}{\Delta x}\approx\frac{1 \times 10^{-34}\ \mathrm m^2\ \mathrm{kg/s}}{10^{-15}\ \mathrm m}\approx 1\times 10^{-19}\ \mathrm{m\ kg/s},$$ so the uncertainty in the object's velocity is $$ \Delta v=\frac{\Delta p}{M}\approx \frac{\approx 1\times 10^{-19}\ \mathrm{m\ kg/s}}{70\ \mathrm{kg}}\sim 1\times 10^{-21}\ \mathrm{m/s}.$$ In other words, the uncertainty in the person's velocity would be roughly one proton-radius per month. This shows that the uncertainties in a person's position and momentum can both be zero as far as we can ever hope to tell , and this is not at all in conflict with the uncertainty principle.
{}
{'log_upvote_score': 8, 'links': ['https://physics.stackexchange.com/questions/440399', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/1643/']}
jdg_379329
stackexchange
llm_judgeable_groundtruth_similarity
25482199
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 building a own certificate chain with following componenents: Root Certificate - Intermediate Certificate - User Certificate Root Cert is a self signed certificate, Intermediate Certificate is signed by Root and User by Intermediate. Now I want to verify if a User Certificate has its anchor by Root Certificate. With openssl verify -verbose -CAfile RootCert.pem Intermediate.pem the validation is ok. In the next step I validate the User Cert with openssl verify -verbose -CAfile Intermediate.pem UserCert.pem and the validation shows error 20 at 0 depth lookup:unable to get local issuer certificate What is wrong? Now provide the response and nothing else.
From verify documentation: If a certificate is found which is its own issuer it is assumed to be the root CA. In other words, root CA needs to be self signed for verify to work. This is why your second command didn't work. Try this instead: openssl verify -CAfile RootCert.pem -untrusted Intermediate.pem UserCert.pem It will verify your entire chain in a single command.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/25482199', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3933294/']}
jdg_379330
stackexchange
llm_judgeable_groundtruth_similarity
8662517
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Normally when I create a class, I create a header and a source for that class. I have heard that with a template class, you have to put the function implementation in the header. I tried doing it both ways, and got compilation errors the first way. The second way worked fine. However, I like to organize my code into headers and source files, so is it possible to put the function implementations into a source file? (Maybe it requires special compilation flags or syntax?) Or should I just keep em in the header? Thanks! Now provide the response and nothing else.
Generally, all template code must be in a header file since the compiler needs to know the complete type at the point of instantiation. As Aaron says below it is possible to put the implementation details in a .cpp -file in the specific case where you know on before hand all possible types the template will be instantiated with and explicitly instantiate it with those types. You'll then get a linker error if the template gets instantiated with another type somewhere in your code. A quite common general solution to at least visually separate interface from implementation is to put all implementation in a .inc (or .tcc or .ipp )-file and include it at the end of the header file. Note that the syntax for putting template class members outside the class-definition (whether you use the specific solution or the general) is slightly cumbersome. You'll need to write: // in test.htemplate <class A>class Test{public: void testFunction();};#include "test.inc"// in test.inc template <class A>void Test<A>::testFunction(){ // do something}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8662517', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1064810/']}
jdg_379331
stackexchange
llm_judgeable_groundtruth_similarity
66252924
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 adding a code block to a page where all js is disabled and stripped out. I want to add a recaptcha to a form to cut down on spam. I've nearly got it, but can't get it to work. My questions are: The js code I am using to validate the required fields gets stripped. Is there any way to put the validation back in without using js? I can't figure out how to connect the enable submit to the recapthca checkbox. Here's the code as far as I've got it to work... <!-- Note : - You can modify the font style and form style to suit your website. - Code lines with comments Do not remove this code are required for the form to work properly, make sure that you do not remove these lines of code. - The Mandatory check script can modified as to suit your business needs. - It is important that you test the modified form before going live.--><div id='crmWebToEntityForm' class='zcwf_lblLeft crmWebToEntityForm' style='background-color: white;color: black;max-width: 600px;'> <meta name='viewport' content='width=device-width, initial-scale=1.0'> <META HTTP-EQUIV ='content-type' CONTENT='text/html;charset=UTF-8'> <form action='https://crm.zoho.com/crm/WebToLeadForm' name=WebToLeads2983403000000507130 method='POST' onSubmit='javascript:document.charset="UTF-8"; return checkMandatory2983403000000507130()' accept-charset='UTF-8'> <input type='text' style='display:none;' name='xnQsjsdp' value='d8a8809b8fe787eb5f1520e8345aa1f4461cf539b2b1505c31cd3765336f8089'></input> <input type='hidden' name='zc_gad' id='zc_gad' value=''></input> <input type='text' style='display:none;' name='xmIwtLD' value='da656ccd402f059702a554831941786995278d8da723e570a30ed6c9d5d4a5b5'></input> <input type='text' style='display:none;' name='actionType' value='TGVhZHM='></input> <input type='text' style='display:none;' name='returnURL' value='https://www.monkeytronics.co.nz/' > </input> <!-- Do not remove this code. --><style>/* <!-- Stick in a recaptcha --> */body { margin:0; background-image:url(https://cdn.theculturetrip.com/wp-content/uploads/2020/08/gettyimages-904801296.jpg); background-size:cover; background-position:center; display:flex; justify-content:center; align-items:center; font-family: 'Roboto', sans-serif;}.captcha { background-color:#f9f9f9; border:2px solid #d3d3d3; border-radius:10px; color:#4c4a4b; display:flex; justify-content:center; align-items:center;}@media screen and (max-width: 500px) { .captcha { flex-direction:column; } .text { margin:.5em!important; text-align:center; } .logo { align-self: center!important; } .spinner { margin:2em .5em .5em .5em!important; }}.text { font-size:1em; font-weight:500; margin-right:1em;}.spinner { position:relative; width:2em; height:2em; display:flex; margin:2em 1em; align-items:center; justify-content:center;}input[type="checkbox"] { position: absolute; opacity: 0; z-index: -1; }input[type="checkbox"]+.checkmark { display:inline-block; width:2em; height:2em; background-color:#fcfcfc; border:2.5px solid #c3c3c3; border-radius:3px; display:flex; justify-content:center; align-items:center; cursor: pointer;}input[type="checkbox"]+.checkmark span { content:''; position:relative;/* position:absolute; border-bottom:3px solid; border-right:3px solid; border-color:#029f56;*/ margin-top:-3px; transform:rotate(45deg); width:.75em; height:1.2em; opacity:0;}input[type="checkbox"]+.checkmark>span:after { content:''; position:absolute; display:block; height:3px; bottom:0;left:0; background-color:#029f56;}input[type="checkbox"]+.checkmark>span:before { content:''; position:absolute; display:block; width:3px; bottom:0;right:0; background-color:#029f56;}input[type="checkbox"]:checked+.checkmark { animation:2s spin forwards;}input[type="checkbox"]:checked+.checkmark>span { animation:1s fadein 1.9s forwards;}input[type="checkbox"]:checked+.checkmark>span:after {animation:.3s bottomslide 2s forwards;}input[type="checkbox"]:checked+.checkmark>span:before {animation:.5s rightslide 2.2s forwards;}@keyframes fadein { 0% {opacity:0;} 100% {opacity:1;}}@keyframes bottomslide { 0% {width:0;} 100% {width:100%;}}@keyframes rightslide { 0% {height:0;} 100% {height:100%;}}.logo { display:flex; flex-direction:column; align-items:center; height:100%; align-self:flex-end; margin:0.5em 1em;}.logo img { height:2em; width:2em;}.logo p { color:#9d9ba7; margin:0; font-size:1em; font-weight:700; margin:.4em 0 .2em 0;}.logo small { color:#9d9ba7; margin:0; font-size:.8em;}@keyframes spin { 10% { width:0; height:0; border-width:6px; } 30% { width:0; height:0; border-radius:50%; border-width:1em; transform: rotate(0deg); border-color:rgb(199,218,245); } 50% { width:2em; height:2em; border-radius:50%; border-width:4px; border-color:rgb(199,218,245); border-right-color:rgb(89,152,239); } 70% { border-width:4px; border-color:rgb(199,218,245); border-right-color:rgb(89,152,239); } 90% { border-width:4px; } 100% { width:2em; height:2em; border-radius:50%; transform: rotate(720deg); border-color:transparent; }}::selection { background-color:transparent; color:teal;}::-moz-selection { background-color:transparent; color:teal;}html,body{ margin: 0px;}#crmWebToEntityForm.zcwf_lblLeft { width:100%; padding: 25px; margin: 0 auto; box-sizing: border-box;}#crmWebToEntityForm.zcwf_lblLeft * { box-sizing: border-box;}#crmWebToEntityForm{text-align: left;}#crmWebToEntityForm * { direction: ltr;}.zcwf_lblLeft .zcwf_title { word-wrap: break-word; padding: 0px 6px 10px; font-weight: bold;}.zcwf_lblLeft .zcwf_col_fld input[type=text], .zcwf_lblLeft .zcwf_col_fld textarea { width: 60%; border: 1px solid #ccc; resize: vertical; border-radius: 2px; float: left;}.zcwf_lblLeft .zcwf_col_lab { width: 30%; word-break: break-word; padding: 0px 6px 0px; margin-right: 10px; margin-top: 5px; float: left; min-height: 1px;}.zcwf_lblLeft .zcwf_col_fld { float: left; width: 68%; padding: 0px 6px 0px; position: relative; margin-top: 5px;}.zcwf_lblLeft .zcwf_privacy{padding: 6px;}.zcwf_lblLeft .wfrm_fld_dpNn{display: none;}.dIB{display: inline-block;}.zcwf_lblLeft .zcwf_col_fld_slt { width: 60%; border: 1px solid #ccc; background: #fff; border-radius: 4px; font-size: 16px; float: left; resize: vertical;}.zcwf_lblLeft .zcwf_row:after, .zcwf_lblLeft .zcwf_col_fld:after { content: ''; display: table; clear: both;}.zcwf_lblLeft .zcwf_col_help { float: left; margin-left: 7px; font-size: 16px; max-width: 35%; word-break: break-word;}.zcwf_lblLeft .zcwf_help_icon { cursor: pointer; width: 16px; height: 16px; display: inline-block; background: #fff; border: 1px solid #ccc; color: #ccc; text-align: center; font-size: 14px; line-height: 16px; font-weight: bold; border-radius: 50%;}.zcwf_lblLeft .zcwf_row {margin: 15px 0px;}.zcwf_lblLeft .formsubmit { margin-right: 5px; cursor: pointer; color: #333; font-size: 16px;}.zcwf_lblLeft .zcwf_privacy_txt { color: rgb(0, 0, 0); font-size: 16px; font-family: Arial; display: inline-block; vertical-align: top; color: #333; padding-top: 2px; margin-left: 6px;}.zcwf_lblLeft .zcwf_button_submit { font-size: 16px; color: #00C3E8; border: 2px solid #00C3E8; padding: 10px 20px; border-radius: 10px; cursor: pointer; max-width: 150px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;}.zcwf_lblLeft .zcwf_button { font-size: 16px; color: #333; border: 2px solid #ccc; padding: 10px 23px; border-radius: 10px; cursor: pointer; max-width: 150px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;}.zcwf_lblLeft .zcwf_tooltip_over{ position: relative;}.zcwf_lblLeft .zcwf_tooltip_ctn{ position: absolute; background: #dedede; padding: 3px 6px; top: 3px; border-radius: 4px;word-break: break-all; min-width: 50px; max-width: 150px; color: #333;}.zcwf_lblLeft .zcwf_ckbox{ float: left;}.zcwf_lblLeft .zcwf_file{ width: 55%; box-sizing: border-box; float: left;}.clearB:after{ content:''; display: block; clear: both;}@media all and (max-width: 600px) { .zcwf_lblLeft .zcwf_col_lab, .zcwf_lblLeft .zcwf_col_fld { width: auto; float: none !important; } .zcwf_lblLeft .zcwf_col_help {width: 40%;}}</style><div class='zcwf_title' style='font-size:20px; max-width: 600px;color: #00C3E8;'>Contact Monkeytronics</div><div class='zcwf_row'><div class='zcwf_col_lab' style='font-size:16px; font-family: Arial;'><label for='First_Name'>First Name</label></div><div class='zcwf_col_fld'><input type='text' id='First_Name' name='First Name' maxlength='40'></input><div class='zcwf_col_help'></div></div></div><div class='zcwf_row'><div class='zcwf_col_lab' style='font-size:16px; font-family: Arial;'><label for='Last_Name'>Last Name<span style='color:red;'>*</span></label></div><div class='zcwf_col_fld'><input type='text' id='Last_Name' name='Last Name' maxlength='80'></input><div class='zcwf_col_help'></div></div></div><div class='zcwf_row'><div class='zcwf_col_lab' style='font-size:16px; font-family: Arial;'><label for='Email'>Email<span style='color:red;'>*</span></label></div><div class='zcwf_col_fld'><input type='text' ftype='email' id='Email' name='Email' maxlength='100'></input><div class='zcwf_col_help'></div></div></div><div class='zcwf_row'><div class='zcwf_col_lab' style='font-size:16px; font-family: Arial;'><label for='Company'>Company<span style='color:red;'>*</span></label></div><div class='zcwf_col_fld'><input type='text' id='Company' name='Company' maxlength='100'></input><div class='zcwf_col_help'></div></div></div><div class='zcwf_row'><div class='zcwf_col_lab' style='font-size:16px; font-family: Arial;'><label for='Description'>How can we help?<span style='color:red;'>*</span></label></div><div class='zcwf_col_fld'><textarea id='Description' name='Description'></textarea><div class='zcwf_col_help'></div></div></div><div class='zcwf_row'><div class='zcwf_col_lab'></div><div class='zcwf_col_fld'><input type='submit' id='formsubmit' class='formsubmit zcwf_button_submit' value='Submit' title='Submit'><input type='reset' class='zcwf_button' name='reset' value='Reset' title='Reset'></div></div><div class="captcha"> <div class="spinner"> <label> <input type="checkbox" onclick="$(this).attr('disabled','disabled');"> <span class="checkmark"><span>&nbsp;</span></span> </label> </div> <div class="text"> I'm not a robot </div> <div class="logo"> <img src="https://forum.nox.tv/core/index.php?media/9-recaptcha-png/"/> <p>reCAPTCHA</p> <small>Privacy - Terms</small> </div></div><script> function validateEmail2983403000000507130() { var form = document.forms['WebToLeads2983403000000507130']; var emailFld = form.querySelectorAll('[ftype=email]'); var i; for (i = 0; i < emailFld.length; i++) { var emailVal = emailFld[i].value; if((emailVal.replace(/^\s+|\s+$/g, '')).length!=0 ) { var atpos=emailVal.indexOf('@'); var dotpos=emailVal.lastIndexOf('.'); if (atpos<1 || dotpos<atpos+2 || dotpos+2>=emailVal.length) { alert('Please enter a valid email address. '); emailFld[i].focus(); return false; } } } return true; } function checkMandatory2983403000000507130() { var mndFileds = new Array('Company','Last Name','Email','Description'); var fldLangVal = new Array('Company','Last Name','Email','How can we help?'); for(i=0;i<mndFileds.length;i++) { var fieldObj=document.forms['WebToLeads2983403000000507130'][mndFileds[i]]; if(fieldObj) { if (((fieldObj.value).replace(/^\s+|\s+$/g, '')).length==0) { if(fieldObj.type =='file') { alert('Please select a file to upload.'); fieldObj.focus(); return false; } alert(fldLangVal[i] +' cannot be empty'); fieldObj.focus(); return false; } else if(fieldObj.nodeName=='SELECT') { if(fieldObj.options[fieldObj.selectedIndex].value=='-None-') { alert(fldLangVal[i] +' cannot be none'); fieldObj.focus(); return false; } } else if(fieldObj.type =='checkbox'){ if(fieldObj.checked == false){ alert('Please accept '+fldLangVal[i]); fieldObj.focus(); return false; } } try { if(fieldObj.name == 'Last Name') { name = fieldObj.value; } } catch (e) {} } } if(!validateEmail2983403000000507130()){return false;} document.querySelector('.crmWebToEntityForm .formsubmit').setAttribute('disabled', true); }function tooltipShow2983403000000507130(el){ var tooltip = el.nextElementSibling; var tooltipDisplay = tooltip.style.display; if(tooltipDisplay == 'none'){ var allTooltip = document.getElementsByClassName('zcwf_tooltip_over'); for(i=0; i<allTooltip.length; i++){ allTooltip[i].style.display='none'; } tooltip.style.display = 'block'; }else{ tooltip.style.display='none'; }}</script> </form></div> Now provide the response and nothing else.
In short, &'a mut Chain<'a> is extremely limiting and pervasive. For an immutable reference &T<'a> , the compiler is allowed to shorten the lifetime of 'a when necessary to match other lifetimes or as part of NLL (this is not always the case, it depends on what T is). However, it cannot do so for mutable references &mut T<'a> , otherwise you could assign it a value with a shorter lifetime. So when the compiler tries to reconcile the lifetimes when the reference and the parameter are linked &'a mut T<'a> , the lifetime of the reference is conceptually expanded to match the lifetime of the parameter. Which essentially means you've created a mutable borrow that will never be released. Applying that knowledge to your question: creating a reference-based hierarchy is really only possible if the nested values are covariant over their lifetimes. Which excludes: mutable references trait objects structs with interior mutability Refer to these variations on the playground to see how these don't quite work as expected. See also: Why does linking lifetimes matter only with mutable references? How do I implement the Chain of Responsibility pattern using a chain of trait objects? What are the differences when getting an immutable reference from a mutable reference with self-linked lifetimes?
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/66252924', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9115897/']}
jdg_379332
stackexchange
llm_judgeable_groundtruth_similarity
241726
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: When I run ls on a folder with directories that have a 777 permission, the ls colors are purple text with a green background, which is unreadable: What can I do to make this more pleasant to look at? Now provide the response and nothing else.
If you are using Linux (and not, e.g., using a Mac which does things differently) you can use dircolors with a custom database to specify which colors are used for which file attributes. First, create a dircolors database file. $ dircolors -p > ~/.dircolors Then edit it, you probably want to change the STICKY_OTHER_WRITABLE and OTHER_WRITABLE lines to something more pleasant than 34;42 (34 is blue, 42 is green - dircolors -p helpfully includes comments with the color codes listed). Then run eval $(dircolors ~/.dircolors) Edit your ~/.profile (or ~/.bash_profile etc) and find the line that runs eval $(dircolors) and change it to include the filename as above. Or if there isn't such a line in your .profile (etc) add it. Or, if you want it to work whether there is a ~/.dircolors file or not, change it to: [ -e ~/.dircolors ] && eval $(dircolors -b ~/.dircolors) || eval $(dircolors -b)
{}
{'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/241726', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/141502/']}
jdg_379333
stackexchange
llm_judgeable_groundtruth_similarity
46415
Below is a question asked on the forum politics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Does the US require a House vote to begin an impeachment inquiry? News sources such as this CNN article seem to show a disagreement between the White House saying that a House vote is required, while the Speaker of the House holds that they have the power to declare one on their own. Now provide the response and nothing else.
Some answers look at whether there is a historical precedent. That is irrelevant. The question is what is required and what is not. There is no current requirement that a resolution be voted on by the House in order to initiate a formal, official impeachment inquiry. If a president were caught by eye-witnesses and on video performing blood sacrifices of infants in the Lincoln Bedroom, surely it would be unprecedented to remove a President from office for those actions. The fact that it was unprecedented would really have no bearing on whether such actions should proceed or whether they were authorized. The Constitution doesn’t offer specific guidance on rules for impeachment inquiries and the House determines its own rules of parliamentary conduct. According to the CRS (Congressional Research Service), the House’s rules allow for an impeachment inquiry to go forward without an initial resolution but the matter would move on the Judiciary Committee at some point. National Constitution Center: The House’s role in the impeachment inquiry process and Congressional Research Service: The Impeachment Process in the House ofRepresentatives (referenced in the previous link) As pointed out in a since-deleted answer, part of why, historically, the process of an authorizing resolution was followed, in part, was because that authorizing resolution would create the authorization for subpoena and other investigative powers. Those powers now exist with the House majority on a permanent basis. One of the main reasons why the precedent was to go via resolution no longer exists. In addition, Pelosi doesn't need the House vote authorizing an inquiry because her caucus already has extra legal authority compared to past inquiries. During the Clinton and Nixon impeachment inquiries, the House passed their inquiry resolutions so they could gain tools like more subpoena power and depositions, and included in those resolutions were nods to bipartisanship that gave the minority party subpoena power, too. But the House rules have changed since the last impeachment of a president more than two decades ago. In this Congress, the House majority already has unilateral subpoena power, a rule change that was made when Republicans last controlled the House, so Democrats don't need to pass any resolution to grant those powers. CNN: Why Democrats aren't planning to vote on an impeachment inquiry
{}
{'log_upvote_score': 6, 'links': ['https://politics.stackexchange.com/questions/46415', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/28479/']}
jdg_379334
stackexchange
llm_judgeable_groundtruth_similarity
2838009
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Given prime numbers $p_1, \cdots, p_n$, Define $E:= \mathbb{Q} [\sqrt{p_1}, \cdots, \sqrt{p_n}]$ a Galois extension over $\mathbb{Q}$ with the separable polynomial$$p(x) = \prod(x^2-p_i).$$ I know in general, permuting roots does not always give us a Galois group element. In this case, if I have the permutation $\sqrt p_1 \mapsto -\sqrt p_1$ and fixes other $\sqrt p_i$'s, we want to define an element in $Gal(E/\mathbb{Q})$ from this, what do we need to check? I guess we have to check that $\sqrt p_1 \not\in \mathbb{Q}[\sqrt p_2, \cdots, \sqrt{p_n}]$, and is there anything else that I need to check? Edit : This is the exercise 18.13 from M. Isaacs. The first part is to show $Gal(E/\mathbb{Q}) = \left(Z_2\right)^n$. This is the second part, and the next part is to show $\sqrt p_1, \cdots, \sqrt p_n$ are linearly independent. So maybe showing $\sqrt p_1 \not \in \mathbb{Q}[\sqrt p_2,\cdots \sqrt p_n]$ is not easy. Now provide the response and nothing else.
Compute the norm: $$\|f(x,y)\|=\sqrt{(x^2-y^2)^2+4(xy)^2}=\sqrt{x^4-2(xy)^2+y^4+4(xy)^2}=x^2+y^2$$ so you get: $f(x,y)=f(a,b)\implies (x^2-y^2,2xy,x^2+y^2)=(a^2-b^2,2ab,a^2+b^2)$, use the first and last coordinates to show that $(a,b)=(\pm |x|,\pm |y|)$ (add and subtract them), use $A$ to conclude that $a=x$ ($x,a>0$) and use the second coordinate to get $b=y$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2838009', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/131137/']}
jdg_379335
stackexchange
llm_judgeable_groundtruth_similarity
6430217
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 following code warn? $match is scoped to the if block and not the containing while block. use strict;use warnings;use 5.012;use IO::All;my $file = io($ARGV[0])->tie;my $regex = qr//;while (my $line = <$file>) { if (my ($match) = $line =~ $regex) { ... } elsif (my ($match) = $line =~ $regex) { ... } say $match;} C:\>perl testwarn.pl test.log"my" variable $match masks earlier declaration in same scope at testwarn.pl line 15.Global symbol "$match" requires explicit package name at testwarn.pl line 18.Execution of testwarn.pl aborted due to compilation errors. As expected, it complains that $match is not defined at line 18, but it also complains about the redeclaration of $match in the if blocks. Version is slightly out of date but not horribly so; and it's the most recent Strawberry version: This is perl 5, version 12, subversion 3 (v5.12.3) built for MSWin32-x86-multi-thread Now provide the response and nothing else.
The scope of the first $match declaration is the entire if-elsif-else block. That lets you do things like this: if ( (my $foo = some_value()) < some_other_value() ) { do_something();} elsif ($foo < yet_another_value()) { # same $foo as in the if() above do_something_else();} else { warn "\$foo was $foo\n"; # same $foo} # now $foo goes out of scopeprint $foo; # error under 'use strict' => $foo is now out of scope If we were to declare my $foo anywhere else in this block, including in the elsif (...) clause, that would be a duplicate declaration in the same scope, and we'd get a warning message.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6430217', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/120050/']}
jdg_379336
stackexchange
llm_judgeable_groundtruth_similarity
9521921
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 execute the following code in Chrome 18 beta I get the error: console.log.apply(this, ['message']); TypeError: Illegal invocation. In Firefox 10 it works as expected. In IE9 I get the error: Object doesn't support property or method 'apply' . I'm guessing this has to do with how the browser has implemented console.log . Why does it work in Firefox but not in Chrome and IE? I'm hoping someone can shed some light on the cause of this and its ramifications. Here is an executable sample on JS Bin. Now provide the response and nothing else.
console and log are host objects. Their behavior is implementation dependent, and to a large degree are not required to implement the semantics of ECMAScript. FWIW, your jsBin fails in Chrome as well unless you change it to... console.log.apply(console, ['message']); but that seems to be that log simply anticipates a calling context of console .
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/9521921', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/31308/']}
jdg_379337
stackexchange
llm_judgeable_groundtruth_similarity
18943636
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Following my code: <div onclick="/*Here I would like to select the child element with the class 'vxf'*/"> <div class="abc"></div> <div class="cir"></div> <!--... other elements--> <div class="vxf"></div> <!--... other elements--></div><div onclick="/*Here I would like to select the child element with the class 'vxf'*/"> <div class="abc"></div> <div class="cir"></div> <!--... other elements--> <div class="vxf"></div> <!--... other elements--></div> How to select the child element with the class "vxf" with pure javascript? Now provide the response and nothing else.
Pass this into your handler... onclick="clickHandler(this)" ...and then for maximum browser compatibility, just look in the child nodes: function clickHandler(element) { var child; for (child = element.firstNode; child; child = child.nextSibling) { if (child.className && child.className.match(/\bvxf\b/)) { break; // Found it } } // ...} (Or keep looping and build up an array, if you want all matching children.) On most modern browsers , another alternative is to use querySelector (to find the first) or querySelectorAll (to get a list) of matching child elements. Sadly, this requires a bit of a trick: function clickHandler(element) { var child, needsId; needsId = !element.id; if (needsId) { element.id = "TEMPID____" + (new Date()).getTime(); } child = document.querySelector("#" + element.id + " > .vxf"); if (needsId) { element.id = ""; } // ...} We have to play the id game because we only want direct children (not descendants), and unfortunately you can't use a child combinator without something on the left of it (so element.querySelector("> .vxf"); doesn't work). If you didn't care whether it was a direct child or a descendant, then of course it's a lot easier: function clickHandler(element) { var child = element.querySelector(".vxf"); // ...}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18943636', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2799274/']}
jdg_379338
stackexchange
llm_judgeable_groundtruth_similarity
6117814
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How do I get the current weeknumber of the year, like PHP's date('W') ? It should be the ISO-8601 week number of year, weeks starting on Monday. Now provide the response and nothing else.
You should be able to get what you want here: http://www.merlyn.demon.co.uk/js-date6.htm#YWD . A better link on the same site is: Working with weeks . Edit Here is some code based on the links provided and that posted eariler by Dommer. It has been lightly tested against results at http://www.merlyn.demon.co.uk/js-date6.htm#YWD . Please test thoroughly, no guarantee provided. Edit 2017 There was an issue with dates during the period that daylight saving was observed and years where 1 Jan was Friday. Fixed by using all UTC methods. The following returns identical results to Moment.js. /* For a given date, get the ISO week number * * Based on information at: * * THIS PAGE (DOMAIN EVEN) DOESN'T EXIST ANYMORE UNFORTUNATELY * http://www.merlyn.demon.co.uk/weekcalc.htm#WNR * * Algorithm is to find nearest thursday, it's year * is the year of the week number. Then get weeks * between that date and the first day of that year. * * Note that dates in one year can be weeks of previous * or next year, overlap is up to 3 days. * * e.g. 2014/12/29 is Monday in week 1 of 2015 * 2012/1/1 is Sunday in week 52 of 2011 */function getWeekNumber(d) { // Copy date so don't modify original d = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate())); // Set to nearest Thursday: current date + 4 - current day number // Make Sunday's day number 7 d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay()||7)); // Get first day of year var yearStart = new Date(Date.UTC(d.getUTCFullYear(),0,1)); // Calculate full weeks to nearest Thursday var weekNo = Math.ceil(( ( (d - yearStart) / 86400000) + 1)/7); // Return array of year and week number return [d.getUTCFullYear(), weekNo];}var result = getWeekNumber(new Date());document.write('It\'s currently week ' + result[1] + ' of ' + result[0]); Hours are zeroed when creating the "UTC" date. Minimized, prototype version (returns only week-number): Date.prototype.getWeekNumber = function(){ var d = new Date(Date.UTC(this.getFullYear(), this.getMonth(), this.getDate())); var dayNum = d.getUTCDay() || 7; d.setUTCDate(d.getUTCDate() + 4 - dayNum); var yearStart = new Date(Date.UTC(d.getUTCFullYear(),0,1)); return Math.ceil((((d - yearStart) / 86400000) + 1)/7)};document.write('The current ISO week number is ' + new Date().getWeekNumber()); Test section In this section, you can enter any date in YYYY-MM-DD format and check that this code gives the same week number as Moment.js ISO week number (tested over 50 years from 2000 to 2050). Date.prototype.getWeekNumber = function(){ var d = new Date(Date.UTC(this.getFullYear(), this.getMonth(), this.getDate())); var dayNum = d.getUTCDay() || 7; d.setUTCDate(d.getUTCDate() + 4 - dayNum); var yearStart = new Date(Date.UTC(d.getUTCFullYear(),0,1)); return Math.ceil((((d - yearStart) / 86400000) + 1)/7)};function checkWeek() { var s = document.getElementById('dString').value; var m = moment(s, 'YYYY-MM-DD'); document.getElementById('momentWeek').value = m.format('W'); document.getElementById('answerWeek').value = m.toDate().getWeekNumber(); } <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>Enter date YYYY-MM-DD: <input id="dString" value="2021-02-22"><button onclick="checkWeek(this)">Check week number</button><br>Moment: <input id="momentWeek" readonly><br>Answer: <input id="answerWeek" readonly>
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/6117814', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/508666/']}
jdg_379339
stackexchange
llm_judgeable_groundtruth_similarity
147043
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: TL;DR I am working on a gaming system that uses UnityScript and C# on the client and PHP on the server. A MD5 hash of the data plus a shared secret is used to check that the data has not been modified in transit. Is MD5 good enough for this? What other hash algorithm could I use that works in all three languages? The Problem In More Detail I have come across some code on a widely used community website about the popular Game Development Platform Unity , and I am now working on improving the MySQL, PHP and security of that code. The code uses a "secret key" value that is shared between the client and the server. All messages from the client includes a hash of the data (e.g. name and score) plus the secret key, that the server checks before accepting the data. This is basically an authentication that the data passed has not been tampered with. However, because it's MD5 I think someone who is listening to the network traffic could easily work out the secret key and then post whatever data they want to the server. So my questions are: Does this current state of affairs warrent improvement? Or is this the intended current use of MD5 (as of January 2017)? Is there another hashing algorithm that could further improve/authenticate this communication activity? Please note that the algorithm would need to work in PHP, UnityScript and C#. The Code In UnityScript (client side): var hash=Md5.Md5Sum(name + score + secretKey); In C# (client side): string hash = MD5Test.Md5Sum(name + score + secretKey); In PHP (server side): $secretKey = "mySecretKey"; // Change this value to match the value //stored in the client javascript below $realHash = md5($_GET['name'] . $_GET['score'] . $secretKey); if($realHash == $hash) { //interact with database } Further Criteria Some Unity programmers use UnityScript (a Python-like language with a JavaScript-like syntax on the .NET API) but no library can be assumed to be installed. Game Developers are not PHP / MySQL programmers so complex or 3rd party PHP/C#/Js code would probably not be helpful. BCrypt is apparently unwise to use with C# BCrypt needs a static salt in this instance (perhaps derived from the secret key?) but is intended to work with a random salt. PBKDF2 seems to be prefered over BCrypt but can be very slow particularly on mobile devices without much memory. Dealing with a secured server can not be expected (if only...). I don't know enough about the C# security library to really pick out best options from those listed. While the code outlined is simply to do with highscore updates, this code has been in the past - and will be in the future - taken and used for transporting all sorts of data, public and private to various databases. Dealing with hash algorithm interoperability between PHP, UnityScript, C# is a bigger hurdle than I had anticipated. If it was just PHP I'd use password_hash . Some Thoughts and background to this question: I updated the title as the edited title seemed to suggest that I wasn't sure about changing MD5, whereas knowing I should change MD5 was one of the core reasons of asking the question here in the first place. The original question was that I wanted to update the terrible code suggestions given on (amongst other places) here about how to handle interactions between a game on a client machine and data storage on a remote server. Bare in mind this is code suggestions for beginner programmers in Unity and this site is [now] run by Unity Technologies themselves. If you look, the original question (linked above) was using PHP Mysql_ functions (as well as a rather crappy invalid form of PDO). I felt this would benefit from a rewrite. I saw that the original code had also used an md5 routine to hash the intended data. When it came to the replacement of MD5, I hadn't realised either the vulnerability of compiled project files or the size/scale of the work needed to make this codeblock be actually more secure (on either the interaction with the server or the client side data). My original quest was to find a suitable drop in replacement for the MD5 which could work in the varous languages required (UnityScript, C#, PHP) , as I was aware of it's shortfalls. I hadn't realised (judging by the comments here) how tediously easy it actually is to break into exe's and grab hardcoded data. This question is NOT about a game I'm making, it is not about My project and the code quoted that I am intending to replace was not written by me . I read a lot of the comments that somehow people are having a go at the messenger, but this question came from my own wish to improve an existing shortcoming on a teaching wiki website. I do have the greatest respect for the knowledge shared in answering this question but I am aware that from the last 6 months exploring the Unity documentation and learning sites that there is a significant gap in securing both local applications and multiplayer or other remote interactions. I see a lot of responders in comments stating that the answer given by George is a bad answer - but it answers the specific question I asked, at the time. Thanks. Final Note: This Blob post from comments by Luke Briggs underlined how much of an eye openingly easy process it is to manipulate local Unity Game Application data. I did not at all comprehend how vulnerable local files are.... Now provide the response and nothing else.
This approach is fundamentally flawed. Anything on the client side can and will be tampered with by players. It is the same problem which makes DRM untenable - the user owns the machine and all the data on it, including your executables, data in memory, etc. Keeping algorithms secret doesn't work (see Kerckhoffs's principle ) because it only takes a small amount of reverse engineering work to work out what your code is doing. For example, let's say you've got a routine in your game client which posts the level score up to the server, using some cryptography of whatever form to ensure that it isn't tampered with over the network. There are a whole bunch of ways to get around this: Use a memory editing tool such as Cheat Engine to scan for the current score (pause, search the score, unpause, wait for score to change, search again, repeat until you find the memory address which contains the value) and edit it. When the level completes the score value will be happily treated as legitimate by your code, and uploaded to the server. Modify the game executable on disk so that your "level complete" code ignores the real score value and picks a different one. Modify the game executable on disk so that simple things (e.g. killing one monster) increases your score by 1000x more than it should do. Modify the game executable on disk so that you can never die, or have infinite powerups, or one-hit kills, or any other number of helping things, so that you can easily attain a very high score. Perform any of those modifications in-memory after the game loads so that the original executable stays intact (useful for cases where there are annoying integrity checks) Simply expose the "we finished a level, now upload the score" code externally from the process so that it can be called by anyone's program. In native code you can inject a small stub and add an entry to the export table, or just directly copy the code into your own executable. In .NET it's trivial to just modify the class and method's visibility flags and import it into a new program. Now you can submit whatever score values you like without ever even running the game. Reverse engineer the game and get hold of the "secret" key and write your own app to send the score value to the server. This is just the tip of the iceberg. For more complex games there are all sorts of workarounds to anti-cheat and other problems, but regardless of the defense tricks used there will always be a way to mess with client-side values. The critical feature of a secure approach is that nothing on the player's computer should be trusted . When your server code receives a packet from a player, assume that your game might not even be running - it could be a totally homebrew piece of code that lies about everything. Securing multiplayer games (or any kind of game where verifying game state is a requirement) isn't easy. The problem isn't really even a security one, it's a usability and performance one. The simplest way to secure a multiplayer game is to keep the entire game state on the server side, have all the game logic executed and maintained there, and have the client do nothing but send player input over to the server ("user clicked the mouse, user is holding W key") and present the audio and video back to the player. The problem with doing this is that it doesn't make for a very fun game due to network latency, and it's quite hard to scale on the server side. Instead, you have to find a balance between keeping things client-side and server-side. For example, the logic for "does the player have a key to open this door?" must be checked server side, but the logic of when to show the context icon for "open door" stays on the client side. Again, things like enemy health and position must be kept on the server side, and the player's ability to deal damage to that enemy must also be verified (is it near enough?) which means that AI can't be kept client-side, but things like the choice of which idle animation the enemy is displaying will probably be a client-side thing. We have a few questions on here about game security, so I suggest reading through those: Preventing artificial latency or "Lag Hacking" in multiplayer games Secure Software: How to ensure caller is authentic? Securely sending packets without them being spoofed Checking a locally stored string for tamper I also recommend these questions over at GameDev SE: How can a web game store points online without giving the user the possibility to do the same call but with more points? (almost literally your question) What are some ways to prevent or reduce cheating in online multiplayer games? How should multiplayer games handle authentication? There's also a great paper on multiplayer security from BlackHat EU 2013, and an article on non-authoritative P2P networking , which may both be of use.
{}
{'log_upvote_score': 8, 'links': ['https://security.stackexchange.com/questions/147043', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/82333/']}
jdg_379340