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
228579
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm interested in whether the scale of processes that occur in the brain is small enough to be affected by quantum mechanics. For instance, we ignore quantum mechanics when we analyze a game of tennis because a tennis ball is much too large to be affected by quantum mechanics. However, signals in the brain are mostly (all?) electrical, carried by electrons, and electrons are definitely 'small' enough to be affected by quantum mechanics. Does that mean the only way we will be able to further understand how the mind works is through an application of quantum mechanics? Now provide the response and nothing else.
Quantum mechanics has almost no bearing on the operation of the brain, except insofar as it explains the existence of matter. You say that signals are carried by electrons, but this is very imprecise. Rather, they are carried by various kinds of chemical signals, including ions. Those signals are released into a warm environment that they interact with over a very short timescale. Quantum mechanical processes like interference and entanglement only continue to show effects that differ from classical physics when the relevant information does not leak into the environment. This issue has been explained the context of the brain by Max Tegmark in The importance of quantum decoherence in brain processes . In the brain, the leaking of information should take place over a time of the order $10^{-13}-10^{-20}$s. The timescale over which neurons fire etc. is $0.001-0.1$s. So your thoughts are not quantum computations or anything like that. The brain is a classical computer.
{}
{'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/228579', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/60080/']}
jdg_79141
stackexchange
llm_judgeable_groundtruth_similarity
91168
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have just downloaded a Polish program Passtool Password Reader (written by Rafał Jelitto ), unpacked it from .rar archive and run it. I have hit the bottom-left button ( Pokaż wszystko ) and this small piece of software has immediately punched me with all my passwords ever used in Mozilla Firefox and Mozilla Thunderbird. A passwords, that up until now I considered safe, since stored in Password Manager. My world has just collapsed (or I was that naive). It was that simple ? I run that program on my office computer. During my summer break, when my boss has access to my computer (inner regulations), he can do the same and get all my passwords. What am I missing? How can Mozilla product's creators claim, that their software is safe, if it only require to take four steps and thirty seconds to reveal all passwords stored in it? Now provide the response and nothing else.
Have you set a master password? If not you don't even need third party software to view the passwords. Just go to options->security->stored passwords and click show passwords and there they are. Try setting a master password in the security settings and see if the software is still able to list your credentials Since I can't yet comment on the other answers due to my reputation, the reason why the tool only works for firefox is likly that it's just developed for firefox. There are tools for viewing passwords for other browsers too.Ohter browsers store there data in different locations in different ways. If a software doesn't check these loactions and files it obviously can't display the contents of this files. +the software must know the decryption algorithm for those files. Mozilla at least gives you the option to set a master password. That is then used for de/encrypting key3.db which contains the key to de/encrypt your stored passwords. With a master password set key3.db can no longer be decrypted with the default key used by those tools and without the key stored in key3.db your stored passwords can't be decrypted as well.
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/91168', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/11996/']}
jdg_79142
stackexchange
llm_judgeable_groundtruth_similarity
21029313
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 write a batch file that installs a windows service using installutil.exe. I would like to use the installutil.exe that is in the latest version of the .Net Framework (located in C:\Windows\Microsoft.NET\Framework\v4.0.30319 on my machine). Is there an easy way to change the directory in the command line to the latest .NET Framework directory? For example, I know using cd %WINDIR% will give me C:\Windows . What would I type to get to the latest .Net Framework Directory? Now provide the response and nothing else.
Using Reed Copseys advice about inspecting the registry I found a sample on another post about how to read the registry from a batch file. Here is my batch file that finds the install directory for the .Net 4 Framework and installs my service: @SET INSTALLUTILDIR=@for /F "tokens=1,2*" %%i in ('reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full" /v "InstallPath"') DO ( if "%%i"=="InstallPath" ( SET "INSTALLUTILDIR=%%k" ))%INSTALLUTILDIR%\installutil MyService.exe And here is the link where you can find the registry key for the specific version of the framework you are looking for: http://msdn.microsoft.com/en-us/kb/kbarticle.aspx?id=318785
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21029313', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1523851/']}
jdg_79143
stackexchange
llm_judgeable_groundtruth_similarity
269363
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: If $e:=\lim_{n\to\infty} (1 + \frac{1}{n})^n$, prove that $$ \lim_{n\to\infty} \left(1-\frac{1}{n}\right)^{-n} = e $$ without using the property that says: if $\lim_{n\to\infty} a_n = \infty$, $\lim_{n\to\infty} x_n = x$, then $\lim{n\to\infty}(1+\frac{x_n}{a_n})^{a_n} = e^x$... I've tried rewriting $1-\frac{1}{n}$, and operating $\lim_{n\to\infty}(1-\frac{1}{n})^n = 1 / \lim_{n\to\infty}(1+\frac{1}{n})^n $ but I couldn't prove it. Any hint? Thanks in advance. Now provide the response and nothing else.
\begin{gather}\lim\limits_{n\to\infty}\left(1-\dfrac{1}{n}\right)^{-n}=\lim\limits_{n\to\infty}\left(\dfrac{n-1}{n}\right)^{-n}= \\=\lim\limits_{n\to\infty}\left(\dfrac{n}{n-1}\right)^{n}=\lim\limits_{n\to\infty}\left[\left(1+\dfrac{1}{n-1}\right)^{n-1}\left(1+\dfrac{1}{n-1}\right)\right]=e\end{gather}
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/269363', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/54087/']}
jdg_79144
stackexchange
llm_judgeable_groundtruth_similarity
32795998
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 would be useful solutions for hiding true database object ID in URL for security purposes? I found that one of the solutions would be: 1) Using hashids open source project 2) Using something like same old md5 on creation of the object to generate hash and store it in database, then use it in url's and querying by them, but the drawback is that querying by auto-incremented primary keys (IDs) is faster than hashes. So I believe the possibility to hash/unhash would be better? Also as I'm on Symfony, are there maybe bundles that I could not find or built in functionalities that would help? Please tell me what you found useful based on your experiences. Now provide the response and nothing else.
This question has been asked a lot, with different word choice (which makes it difficult to say, "Just search for it!"). This fact prompted a blog post titled, The Comprehensive Guide to URL Parameter Encryption in PHP . What People Want To Do Here What People Should Do Instead Explanation Typically, people want short random-looking URLs. This doesn't allow you much room to encrypt then authenticate the database record ID you wish to obfuscate. Doing so would require a minimum URL length of 32 bytes (for HMAC-SHA256), which is 44 characters when encoded in base64. A simpler strategy is to generate a random string (see random_compat for a PHP5 implementation of random_bytes() and random_int() for generating these strings) and reference that column instead. Also, hashids are broken by simple cryptanalysis. Their conclusion states: The attack I have described is significantly better than a brute force attack, so from a cryptographic stand point the algorithm is considered to be broken, it is quite easy to recover the salt; making it possible for an attacker to run the encoding in either direction and invalidates property 2 for an ideal hash function. Don't rely on it.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32795998', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2697561/']}
jdg_79145
stackexchange
llm_judgeable_groundtruth_similarity
426292
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: What is the next number in the sequence: $24, 30, 33 , 39 , 51,...$ Here all numbers are divisible by $3$,difference between numbers are $6,3,6,12,...$but I can't find common relationship in the sequence. Now provide the response and nothing else.
Looks to me like each term is the preceding term, plus the preceding term's sum of digits. The sequence would then be: $24, 30, 33, 39, 51, 57, 69, 84, 96,...$ Note that if a number is divisible by 3, then the sum of its digits is also divisible by 3, resulting in all of the numbers in the sequence being divisible by 3. Because of this, there are probably many other ways to define the sequence, but I find the one I gave to be fairly natural. Edit: Just noticed @DavidMitra's earlier comment which links to an OEIS page which includes the answer I gave, but I'll leave my answer here as reference.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/426292', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/54373/']}
jdg_79146
stackexchange
llm_judgeable_groundtruth_similarity
5047366
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 ♥ git stash -p . But sometimes, after a satisfying session of y , n , and s , I get this: Saved working directory and index state WIP on foo: 9794c1a lorum ipsumerror: patch failed: spec/models/thing_spec.rb:65error: spec/models/thing_spec.rb: patch does not applyCannot remove worktree changes Why? Now provide the response and nothing else.
This happens for me any time I try to split a hunk into smaller hunks that are too close together (less than 3 lines between changes). The short explanation is that the patch has context lines in it that conflict with your local changes. More complete explanation below. Suppose I have a git repo with these uncommitted changes: --- a/pangram+++ b/pangram@@ -1,8 +1,8 @@ The-quick+relatively quick brown fox-jumps+walks over the lazy If I stash the first change, I get: --- a/pangram+++ b/pangram@@ -1,5 +1,5 @@ The-quick+relatively quick brown fox jumps The git stash command actually does succeed in saving the patch (check git stash list ), but then git uses that patch in reverse to remove the stashed changes from my working dir. The context after the hunk has "jumps", which doesn't match the "walks" still in my working dir. So git bails out with error: patch failed: pangram:1error: pangram: patch does not applyCannot remove worktree changes and leaves all the changes in my working dir, and the stash becomes pretty much worthless. I would call this a bug in git's hunk splitting support. If it knows it's splitting the changes too close, it could shave off a few lines of context from the patch, or jimmy the patch to have the modified context lines instead of the pristine ones. Alternatively, if splitting hunks this close is officially unsupported, it should actually refuse to split hunks that close.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5047366', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/168143/']}
jdg_79147
stackexchange
llm_judgeable_groundtruth_similarity
42573
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: In my gnome GUI desktop of Ubuntu 12.04, Ctrl + Alt + Delete will log out instead of rebooting. But I was told that Switching to a text-based virtual console and pressing Ctrl+Alt+Delete will reboot the machine. It will shut down cleanly and reboot, which is much better than Alt+SysRq+REISUB. So I wonder if the above two different meanings of Ctrl + Alt + Delete are right? What commands Ctrl + Alt + Delete is binded to in these two cases? Now provide the response and nothing else.
Ctrl + Alt + Delete is actually a "magic" keystroke for the IBM PC-compatible hardware architecture that would call a BIOS reset. Since this kind of thing is dangerous for a system like Linux the decision was made to hook those keystrokes and do something else instead. This is controlled by init and you can see what it does by looking in /etc/inittab . On my Debian Squeeze system: ca:12345:ctrlaltdel:/sbin/shutdown -t1 -a -r now Windows NT later followed suit and turned Ctrl + Alt + Delete into the secure key entry mode*. In the case of X, it is similarly hooking the keystrokes but it simply kill s the display server (which will automatically respawn if you're using a display manager). Some systems (perhaps all, I haven't tried in a while) you can still press Ctrl + Alt + Delete before the OS loads to trigger a BIOS reset. *I'm not sure what they actually call it.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/42573', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/674/']}
jdg_79148
stackexchange
llm_judgeable_groundtruth_similarity
4209382
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: SDK level 8 (Froyo) has introduced the native capability for the MediaPlayer to connect to a streaming source, like Shoutcast. Previous SDK versions were able to do workarounds, such as run a local proxy on the device (see NPR ). I took the same approach as NPR and am using a StreamProxy. However, NPR first checks if the currently running SDK is less than 8. If so, it uses the proxy. Otherwise, it connects directly. My StreamProxy requests metadata from the Shoutcast server, so it does not simply route the data from Shoutcast to my client. Instead, it parses out metadata and uses it accordingly, and only routes the music data. When trying to use the StreamProxy at SDK level 8 or above, the MediaPlayer fails to prepare. My StreamProxy receives the connection and accepts it, but after successfully writing out the status line and headers to the client, the next write produces java.net.SocketException: Connection reset by peer . This results in the client's mediaplayer throwing an Error(1,-1007) . I am trying to figure out why the MediaPlayer is unable to connect to my local proxy. It should be the same as connecting to the original source without the metadata, which does work. I am forwarding on all headers from the external source, through my proxy, which includes content-type. I will continue looking into it, but I feel like I'm at a dead-end. Let me know if more details are needed. Now provide the response and nothing else.
EDIT: Ok I now believe I have the answer! Stagefright is strict when it comes to line-endings in the HTTP-header; They have to be CR,LF and not just LF which has worked earlier. So if you build your own headers, replace any "\n" with "\r\n" and you should be fine. (If you want to check this for yourself, look at receive_line() in media/libstagefright/HTTPStream.cpp ) I can now stream shoutcast with Metadata on 2.2/Stagefright phones... ... I have been running into the same problem; First I tried writing the streamed data to a fixed length file and wrapping - and playing it with setLooping(true). This causes glitches when the MP3 loops, even though I extract whole MP3 frames and tried to pad the uneven bytes at the end with both 0xff and 0x00. This might still be an acceptable solution if you have a big enough file. Then I did the proxy thing which works on my Samsung Galaxy S (v2.2) but not in the emulator and apparently not on the Desire (Not working = Error -1007 as mentioned above).One hint may be that the Galaxy S Mediaplayer asks for HTTP1.0, while it is 1.1 in the emulator. The brute-force method would be to open 2 streams in parallel, reading meta-data from one and streaming from the other ;) Anyway, I also want to hear if anyone else has had more luck...
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4209382', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/499610/']}
jdg_79149
stackexchange
llm_judgeable_groundtruth_similarity
6474278
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm getting a bug report that some functionality in some music-playing code in an external DLL (SDL_Mixer, in case it helps) that my program uses is raising EPrivilege. The DLL is written in C, so I can't get useful stack trace information out of it with MadExcept, and the problem is not reproducible on my end. And just to make things worse, I don't even know what EPrivilege is . I've never seen it come up in my own code, there's very little information about it available online, and what there is is contradictory. (One explanation says it's raised by the OS if you try to do something with a limited account that requires privileges that aren't available, another says that it's raised by the CPU if you try to execute an instruction that's above your privilege level.) Does anyone have an authoritative explanation for what causes EPrivilege? And does anyone have any idea how it could be raised by music-playing code on one Windows 7 64-bit machine under a non-admin account but not be raised when running the same code on my Windows 7 64-bit machine under a non-admin account? Now provide the response and nothing else.
EPrivilege is raised when the hardware objects to you trying to run a privileged instruction in user mode. These privileged instructions are restricted to supervisor mode, a.k.a. ring 0 . The hardware raises the error and then the RTL catches it and maps it to a RTL exception, just like all the EExternal exceptions, e.g. EAccessViolation , EStackOverflow etc. Admin rights are not relevant here. That is something that is enforced by the OS software. Instruction privilege is controlled at the hardware level. You see such an error if you attempt to execute garbage (i.e. corrupted function pointer) which just happens to spell a privileged instruction. Memory corruption is the only sane explanation. Only compilers that target kernel mode code will emit privileged instructions.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6474278', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/32914/']}
jdg_79150
stackexchange
llm_judgeable_groundtruth_similarity
36500723
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 try to unit test the getElement function class BarFoo { getElement() { return document.querySelector('#barfoo'); }} mocha doesn't know anything about document , so I figured that you might do something like this: beforeEach(() => { global.document = { querySelector: () => { ... } }} Although this works, I'm wondering if this is the correct approach and maybe there is a package available to solve this issue, because my approach can get laborious if more browser API's are used ? Now provide the response and nothing else.
There are a few options available to you: Option 1: Use JSDOM By adding a DOM to your code, you can unit test much of your client-side code within node.js Option 2: Use MOCHA on the client Mocha does run inside the client and you can use separate client-side unit tests. This tends to be my preferred approach as I can test against specific browsers and not a specific JS implantation. Option 3: Use PhantomJS PhantomJS allows you to control a headless browser within your testing environment. Option 4: Headless Chrome Now that Headless Chrome is out, the PhantomJS maintainer has retired.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36500723', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/419425/']}
jdg_79151
stackexchange
llm_judgeable_groundtruth_similarity
141143
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: Is the following state entangled? $\left| \psi \right> = \alpha_0 \beta_0 \left| 00 \right> + \alpha_0 \beta_1 \left| 01 \right> + 0 \left| 10 \right>+ \alpha_1 \beta_1 \left| 11 \right>$ I 'know' it is an NOT an entangled state, but I here's where I am a bit confused. It says $ \alpha_1 \beta_0 = 0$ which implies either $ \alpha_1 = 0$ or $\beta_0 =0$ , but that would be a contradiction. (since we assume $\left| 00 \right>$ and $\left| 11 \right>$ have non-zero probability amplitudes) Also, if this is NOT an entangled state, how can I factor it to $\left| \phi_1 \right> \otimes \left| \phi_2 \right> $? Now provide the response and nothing else.
It is an entangled state, as you concluded yourself it cannot be written as a direct tensor product. To recap again: $$\left(\begin{array}{c}\alpha_0\\\alpha_1\\\end{array}\right)\otimes\left(\begin{array}{c}\beta_0\\\beta_1\\\end{array}\right) = \left(\begin{array}{c}\alpha_0 \beta_0\\\alpha_0 \beta_1\\\alpha_1 \beta_0\\\alpha_1 \beta_1\\\end{array}\right)$$ If $\alpha_1 \beta_0$ is set to 0, and the rest kept non-zero, writing $\left| \psi \right>$ as a direct tensor product fails, as there no $\alpha$ or $\beta$ satisfying these conditions at the same times. More generally, when it comes to questions of type "is this state entangled or separable", it is much simpler to tackle it at the level of density matrices. For instance, given any pure 2-qubit state, such as yours, a simple criterion indicating a separable state would be to calculate the density matrix $\rho$ , trace out (integrating out undesired degrees of freedom) $\rho$ w.r.t. the basis of one of the qubits to obtain the reduced density matrix of the other qubit, then calculate $\operatorname{Tr}(\rho_{\rm reduced}^2).$ The state is separable iff the latter is equal to $1,$ otherwise it is entangled. In other words, if the reduced density matrix has rank $1,$ then it is a pure state (as opposed to mixed), and thus the composite 2-qubit state must be a separable one. Let's take a separable state and verify the above scheme. Suppose we have $|\psi\rangle=|\phi_1\rangle|\phi_2\rangle,$ then $\rho=|\psi\rangle \langle \psi|.$ The reduced density matrix of the first qubit is then obtained by tracing out in the basis of the second: $\rho_1=\operatorname{Tr_2}(\rho)=|\phi_1\rangle \langle \phi_1|.$ Squaring and tracing $\operatorname{Tr}(\rho_1^2)=1,$ thus, confirming that $\psi$ is indeed a separable state. Specifically for your example, the normalization condition gives you a relation between the coefficients, namely, $|\alpha_0\beta_0|^2+|\alpha_0\beta_1|^2+|\alpha_1\beta_1|^2=1$ $:(1).$ Then by performing the above calculation (well-encouraged exercise), you should get to an equation of type $Tr(\rho_1^2)=|\alpha_0|^2|\beta_0|^2+|\alpha_1|^2|\beta_2|^2 <1,$ clearly smaller than $1,$ which directly follows from the normalization criterion $(1).$ Hence, $|\psi\rangle$ describes indeed an entangled state of the 2-qubit system.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/141143', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/62045/']}
jdg_79152
stackexchange
llm_judgeable_groundtruth_similarity
95212
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm working on a dataset with 200,000+ samples and approximately 50 features per sample: 10 continuous variables and the other ~40 are categorical variables (countries, languages, scientific fields etc.). For these categorical variables, you have for example 150 different countries, 50 languages, 50 scientific fields etc... So far my approach is: For each categorical variable with many possible value, take only the one having more than 10000 sample that takes this value. This reduces to 5-10 categories instead of 150. Build dummy variable for each categorical one (if 10 countries then for each sample add a binary vector of size 10). Feed a random forest classifier (cross-validate the parameters etc...) with this data. Currently with this approach, I only manage to get 65% accuracy and I feel like more can be done. Especially I'm not satisfied with my 1) since I feel like I shouldn't arbitrarily remove the "least relevant values" according the the number of sample they have, because these less represented values could be more discriminative. On the other hand, my RAM can't afford adding 500 columns * 200000 rows to the data by keeping all possible values. Would you have any suggestion to cope with this much categorical variables? Now provide the response and nothing else.
Random forests should be able to handle categorical values natively so look for a different implementation so you don't have to encode all of those features and use up all your memory. The problem with high cardinality categorical features is that it is easy to over fit with them. You may have enough data that this isn't an issue but watch out for it. I suggest looking into random forest based feature selection using either the method Breiman proposed or artificial contrasts . The artificial contrasts method (ACE) is interesting because it compares the importance of the feature to the importance of a shuffled version of itself which fights some of the high cardinality issues. There is a new paper "Module Guided Random Forests" which might be interesting if you had many more features as it uses a feature selection method that is aware of groups of highly correlated features. Another sometime used option is to tweak the algorithm so it uses the out of bag cases to do the final feature selection after fitting the splits on the in bag cases which sometimes helps fight overfitting. There is an almost complete ace implementation here and I have a more memory efficient/fast RF implementation that handles categorical variables natively here ...the -evaloob option supports option 4 I'm working on adding support for ACE and a couple of other RF based feature selection methods but it isn't done yet.
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/95212', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/29139/']}
jdg_79153
stackexchange
llm_judgeable_groundtruth_similarity
44209924
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to create a custom Permission Evaluator in order to @PreAuthorize a REST Endpoint with a custom method.I use Spring Boot 1.5.3 with the web and security starter. My further use case would be to check, if the logged in user is authorized to view the specified id. Upon calling the REST endpoint I get the following error: org.springframework.expression.spel.SpelEvaluationException: EL1004E: Method call: Method hasPermission(null) cannot be found on org.springframework.security.access.expression.method.MethodSecurityExpressionRoot type My Custom Permission Evaluator: @Componentclass CustomPermissionsEvaluator implements PermissionEvaluator { public boolean hasPermission(String id) { return id.equals("correct"); } @Override public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) { return false; } @Override public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) { return false; }} My Security Configuration: @Configuration@EnableGlobalMethodSecurity(prePostEnabled = true)class SecurityConfig extends GlobalMethodSecurityConfiguration { @Override public MethodSecurityExpressionHandler createExpressionHandler() { DefaultMethodSecurityExpressionHandler methodSecurityExpressionHandler = new DefaultMethodSecurityExpressionHandler(); methodSecurityExpressionHandler.setPermissionEvaluator(new CompanyPermissionsEvaluator()); return methodSecurityExpressionHandler; }} My Rest Controller: @RestControllerclass RestControllerToProtect { @PreAuthorize("hasPermission(#id)") @GetMapping public String methodToProtect(String id) { return "Authenticated"; }} Stacktrace: org.springframework.expression.spel.SpelEvaluationException: EL1004E:Method call: Method hasPermission(null) cannot be found onorg.springframework.security.access.expression.method.MethodSecurityExpressionRoot type Now provide the response and nothing else.
You can't use overloaded method which is not member of PermissionEvaluator without additional configuration (see this answer if you want to reconfigure PermissionEvaluator pattern). hasPermission calls should match one of the following signatures by default: hasPermission(Authentication authentication, Object targetDomainObject, Object permission);hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission); Example: public class CustomPermissionEvaluator implements PermissionEvaluator { private Logger log = LoggerFactory.getLogger(CustomPermissionEvaluator.class); @Override public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) { CustomUserDetails customUserDetails = (CustomUserDetails) authentication.getPrincipal(); AbstractEntity abstractEntity = (AbstractEntity) targetDomainObject; log.debug("User {} trying to access {}-{} with permission {}", customUserDetails.getUsername(), abstractEntity.getClass().getSimpleName(), abstractEntity.getId(), permission.toString()); return false; } @Override public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) { CustomUserDetails customUserDetails = (CustomUserDetails) authentication.getPrincipal(); log.debug("User {} trying to access {}-{} with permission {}", customUserDetails.getUsername(), targetType, targetId, permission.toString()); return false; }} Controller: @RestControllerpublic class RestControllerToProtect { // passing targetDomainObject and permission, authentication is detected by SecurityExpressionRoot @PreAuthorize("hasPermission(#abstractEntity, 'create')") public String methodToProtect(@RequestBody AbstractEntity abstractEntity) { return "Authenticated"; }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44209924', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8072260/']}
jdg_79154
stackexchange
llm_judgeable_groundtruth_similarity
2440865
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: Evaluate $$\lim_{x\to 0}\frac{(\tan x)^{2008}-(\arctan x)^{2008}}{x^{2009}}$$ without using Taylor series. I have a solution using $\lim_{x\to 0}\frac{\tan x-\arctan x}{x^2}=0$, but I would really like to see a different idea. Now provide the response and nothing else.
You can define $$f(x) = \left(\frac{\tan(x)}{x}\right)^{2008}\qquad g(x) = \left(\frac{\arctan(x)}{x}\right)^{2008}$$ then use$$\frac{f(x)-g(x)}{x} \longrightarrow f^\prime(0) - g^\prime(0)$$ Remark The following useful inequalities hold $$|\tan(x) -x| = \int_0^{|x|}\tan^2(t)dt\le \tan^2(x)\int_0^{|x|}dt\le |x| \tan^2(x) \quad \text{for }|x|<\frac{\pi}{2}$$ and$$|\arctan(x) - x| = \int_0^{|x|}\frac{t^2}{1+t^2}dt\le\int_0^{|x|}t^2dt\le \frac{|x|^3}{3}\quad\text{for } x\in{\mathbb R}$$They imply that $\frac{\tan(x)}{x} - 1 = o(x)$ and $\frac{\arctan(x)}{x}-1 = o(x)$, hence $f^\prime(0)$ and $g^\prime(0)$ exist and are $0$.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2440865', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/327725/']}
jdg_79155
stackexchange
llm_judgeable_groundtruth_similarity
455356
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 own a cheap oscilloscope Hantek DSO4102C. It's rated bandwidth is 100 MHz, and sample rate is 1 GSa/s. Some info about the tool can be found here: http://hantek.com/en/ProductDetail_3_4163.html Now I have an Atmega328P MCU running from an external quartz at 16 MHz, without any code it it (chip erased by usbasp), only CKOUT fuse bit is set. So I supposed to see a square wave at PB0 pin, but my scope shows it quite distorted: MCU's datasheet doesn't mention a pin rise time, which was a big surprise to me, so I cannot check if measured 9.5 ns is a valid value. But judging by Pk-Pk voltage exceeding 6 volts (and even going below zero for a good 560 mV), I believe there's a problem with the scope. Am I right? ADDED LATER, AFTER GETTING SOME ADVICE I've assembled everything on a breadboard, rather then using Arduino Uno. I've connected ground clip from the scope to the ATMega's ground pin with a wire through breadboard. I'm measuring directly at the output pin (see photo of my layout below). Now I'm getting better results, also with 20 MHz oscillator. Obviously, Pk-Pk values are now more close to reality, as well as signal shape. So thanks everybody for the help! Now provide the response and nothing else.
I believe there's a problem with the scope. Am I right? Don't think so. Overshoot is a perfectly normal phenomenon when measuring a fast-edge signal with a high-impedance probe. (Also, these signals look about as sharp as I'd expect them to be.) There's many tutorials on sensing high-speed signals: this is the perfect time to read one! Oh, and there's Gibb's phenomenon, which says that any band-limited observation of a theoretical perfect (or far less band-limited) edge will have some 9% of overshoot; to understand that, I'd recommend looking at the cosine series representation of the square wave and consider what you'll cut off when you get rid of anything above 5× 16 MHz (=the fundamental frequency of your square wave).
{}
{'log_upvote_score': 6, 'links': ['https://electronics.stackexchange.com/questions/455356', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/190680/']}
jdg_79156
stackexchange
llm_judgeable_groundtruth_similarity
359275
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am writing some test units using googletest and googlemock and I am stuck in a problem related to C++11 smart pointers and polymorphism. Suppose you have those classes: class A {public: virtual void doThings() {...};};class B {private: B(std::unique_ptr<A> a): a_(std::move(a)) {} std::unique_ptr<A> a_;}; I want to test class B and so I create a mock for A and pass it in constructor: class MockA: public A {public: virtual ~MockA() {} MOCK_METHOD0(doThings, void());};TEST(...) { auto ma = std::make_unique<MockA>(); B b(std::move(ma)); // Set expectation on mock // call B method} The problem is this: the mock in moved inside B instance and so expectation verification throws exception because ma is null. My first attempt to solve it has been to change B as follows: class B {private: B(std::unique_ptr<A>& a): a_(a) {} std::unique_ptr<A>& a_;}; Now B handles unique pointer references and does not use std::move . The test also changed (no more use of std::move ): TEST(...) { auto ma = std::make_unique<MockA>(); B b(ma); // Set expectation on mock // call B method} Now the code does not compile because (if I understand correctly the error) references are not polymorphic (the unique pointer of MockA cannot be casted to unique pointer of A ). Am I missing any basics about smart pointers? Or is this the expected behaviour with unique pointers and so I have to rethink my classes (maybe using shared pointers)? Now provide the response and nothing else.
The easiest way would be to keep class B exactly the same as it was before, but grab the pointer from ‘ma’ before you pass it to ‘b’ in the test case.Like so… TEST(...){ auto ma = std::make_unique<MockA>(); //this will be valid even after the current unique_ptr transfers ownership //It will be invalidated, however, if a smart pointer deletes it auto ( or MockA*) rawPtr = ma.get(); B b(ma); //ma now points to NULL, but rawptr is still valid //Run analysis on mock via rawPtr} Changing the signature of B in such a way would not be wise. Remember, if you want a class to have exclusive ownership of a pointer, it should have its own unique_ptr for that pointer. If you change B’s unique_ptr to a reference, then B no longer technically owns the pointer even though you likely wrote the class in such a way that it acts like it owns the pointer. This could lead to some really odd behavior/crashes. If you expect both B and A to have ownership of the pointer, meaning that the pointer NEEDS to be valid while B and another class/function are alive/running, then you should use a shared_ptr. If the pointer only needs to be valid while ONLY B is alive, then you should use a unique_ptr and make it a member of B. Without seeing the rest of your code, I can’t say with total certainty, but I’m pretty sure you want to keep on using a unique_ptr as a member of B in this case. EDIT As Caleth brought out, the entire purpose of B having a unique_ptr is that it has ownership of the pointer. So if B decides it's time to delete the ptr, that memory is now invalid and any attempt to access it via the rawPtr will lead to very bad things (Undefined behaviour, crashes, etc) Only do this if you know how B handles the unique_ptr. Only access rawPtr up until B deletes the ptr or allows its unique_ptr to go out of scope.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/359275', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/263163/']}
jdg_79157
stackexchange
llm_judgeable_groundtruth_similarity
1390913
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: If I have something like class Base { static int staticVar;}class DerivedA : public Base {}class DerivedB : public Base {} Will both DerivedA and DerivedB share the same staticVar or will they each get their own? If I wanted them to each have their own, what would you recommend I do? Now provide the response and nothing else.
They will each share the same instance of staticVar . In order for each derived class to get their own static variable, you'll need to declare another static variable with a different name. You could then use a virtual pair of functions in your base class to get and set the value of the variable, and override that pair in each of your derived classes to get and set the "local" static variable for that class. Alternatively you could use a single function that returns a reference: class Base { static int staticVarInst;public: virtual int &staticVar() { return staticVarInst; }}class Derived: public Base { static int derivedStaticVarInst;public: virtual int &staticVar() { return derivedStaticVarInst; }} You would then use this as: staticVar() = 5;cout << staticVar();
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1390913', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/65387/']}
jdg_79158
stackexchange
llm_judgeable_groundtruth_similarity
471859
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How do you edit items and subitems in a listview? Let's say I have a listview with 3 columns,and subitems, Car Brand | Car Name | Car YearFord | Mustang | 2000Dodge | Charger | 2007 How would I Add items like that to listview and how would I edit let's say the Car Name on which ever row by index[] if I needed to edit at runtime at firing of an event? Now provide the response and nothing else.
If you're looking for "in-place" editing of a ListView 's contents (specifically the subitems of a ListView in details view mode), you'll need to implement this yourself, or use a third-party control. By default, the best you can achieve with a "standard" ListView is to set it's LabelEdit property to true to allow the user to edit the text of the first column of the ListView (assuming you want to allow a free-format text edit). Some examples (including full source-code) of customized ListView 's that allow "in-place" editing of sub-items are: C# Editable ListView In-place editing of ListView subitems
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/471859', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_79159
stackexchange
llm_judgeable_groundtruth_similarity
1100506
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've got a class which inherits from a List<MagicBean> . It works well and as expected in all respects except one: when I add the [DebuggerDisplay] attribute. Even though looking at List has its as [DebuggerDisplay("Count = {Count}")] , if I so much as copy and paste that onto mine, I lose the ability to look directly at all of the MagicBeans I have without drilling into base->private members while debugging. How do I get the best of both worlds? IE: Custom value in the value column, and Visual Studio not hiding my magic beans from me? Now provide the response and nothing else.
You can get the effect you need by using the DebuggerTypeProxy attribute. You need to create a class to make a debug "visualisation" of your inherited list: internal sealed class MagicBeanListDebugView{ private List<MagicBean> list; public MagicBeanListDebugView(List<MagicBean> list) { this.list = list; } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public MagicBean[] Items{get {return list.ToArray();}}} You can then declare this class to be used by the debugger for displaying your class, along with the DebuggerDisplay attribute: [DebuggerDisplay("Count = {Count}")][DebuggerTypeProxy(typeof(MagicBeanListDebugView))]public class MagicBeanList : List<MagicBean>{} This will give you the "Count = 3" message when you hover over an instance of your inherited list in Visual Studio, and a view of the items in the list when you expand the root node, without having to drill down into the base properties. Using ToString() to specifically get debug output is not a good approach, unless of course you are already overriding ToString() for use in your code elsewhere, in which case you can make use of it.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1100506', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/52806/']}
jdg_79160
stackexchange
llm_judgeable_groundtruth_similarity
12544
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: Can $n!$ be a perfect square when $n$ is an integer greater than $1$ ? Clearly, when $n$ is prime, $n!$ is not a perfect square because the exponent of $n$ in $n!$ is $1$ . The same goes when $n-1$ is prime, by considering the exponent of $n-1$ . What is the answer for a general value of $n$ ? (And is it possible, to prove without Bertrand's postulate. Because Bertrands postulate is quite a strong result.) Now provide the response and nothing else.
Assume, $n\geq 4$ . By Bertrand's postulate there is a prime, let's call it $p$ such that $\frac{n}{2}<p<n$ . Suppose, $p^2$ divides $n$ . Then, there should be another number $m$ such that $p<m\leq n$ such that $p$ divides $m$ . So, $\frac{m}{p}\geq 2$ , then, $m\geq 2p > n$ . This is a contradiction. So, $p$ divides $n!$ but $p^2$ does not. So, $n!$ is not a perfect square. Bertrand's postulate That leaves two more cases. We check directly that, $2!=2$ and $3!=6$ are not perfect squares.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/12544', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/2938/']}
jdg_79161
stackexchange
llm_judgeable_groundtruth_similarity
40491893
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 ASP.NET Core 1.0.1. I have the following A class library that uses "Microsoft.AspNetCore.Mvc": "1.0.1" in order to develop my controllers: using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Microsoft.AspNetCore.Mvc;namespace CoreAPIsLibrary.Controllers{ [Route("api/[controller]")] public class ValuesContoller : Controller { public string Get() { return "value"; } // GET api/values/5 [HttpGet("{id}")] public string Get(int id) { return "value"; } // POST api/values [HttpPost] public void Post([FromBody]string value) { } // PUT api/values/5 [HttpPut("{id}")] public void Put(int id, [FromBody]string value) { } }} This is my class libray's project.json: { "version": "1.0.0-*", "dependencies": { "Microsoft.AspNetCore.Mvc": "1.0.1", "NETStandard.Library": "1.6.0" }, "frameworks": { "netstandard1.6": { "imports": "dnxcore50" } }} Asp.net core application (Web API Template) that will host my controllers and referencethat class library. However, It never hits the break point in thecontroller. Here is my startup class in the web application: using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Microsoft.AspNetCore.Builder;using Microsoft.AspNetCore.Hosting;using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Logging;using System.Reflection;using CoreAPIsLibrary.Controllers;namespace APIsHost{ public class Startup { public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc() .AddApplicationPart(typeof(ValuesContoller).GetTypeInfo().Assembly).AddControllersAsServices(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseMvc(routes => { routes.MapRoute("default", "{controller}/{action}/{id}"); }); //app.UseMvc(); } }} I also checked if the controller was injected: So, what is missing? Now provide the response and nothing else.
Maybe you're doing something wrong. So, here are the steps to make this work. Create a new project: ASP.NET Core Web Application (.NET Core); Choose the Web API template; Run the project and access the "api/values" to make sure it's working; Add a new project to the solution named ClassLibrary: Class Library (.NET Core); Delete the Class1.cs and create a TestController.cs class; Add the MVC dependency in the project.json from the ClassLibrary project: "dependencies": { "NETStandard.Library": "1.6.0", "Microsoft.AspNetCore.Mvc": "1.0.0"}, Update your TestController.cs to be like this: [Route("api/[controller]")]public class TestController : Controller{ [HttpGet] public IEnumerable<string> Get() { return new string[] { "test1", "test2" }; }} Add the reference to ClassLibrary in your WebAPI Project: right-click on "References"->"Add Reference..." or update your project.json like this: "dependencies": { "Microsoft.NETCore.App": { "version": "1.0.0", "type": "platform" }, "Microsoft.AspNetCore.Mvc": "1.0.0", "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0", "Microsoft.AspNetCore.Server.Kestrel": "1.0.0", "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0", "Microsoft.Extensions.Configuration.FileExtensions": "1.0.0", "Microsoft.Extensions.Configuration.Json": "1.0.0", "Microsoft.Extensions.Logging": "1.0.0", "Microsoft.Extensions.Logging.Console": "1.0.0", "Microsoft.Extensions.Logging.Debug": "1.0.0", "Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0", "ClassLibrary": "1.0.0-*"}, Update your Startup.cs ConfigureServices method: public void ConfigureServices(IServiceCollection services) { services.AddMvc().AddApplicationPart(Assembly.Load(new AssemblyName("ClassLibrary")));} Run the project again and access "api/test";
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/40491893', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1682401/']}
jdg_79162
stackexchange
llm_judgeable_groundtruth_similarity
6752013
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 property on one of my objects that is a nullable boolean, I want my logic to have true represent Yes, false to be No and null to be N/A. Now because I am going to have multiple properties like this on many different objects it makes the most sense to make an editor and display templates for these properties. I am going to use jQuery UI to apply a visual element of buttonset after this is all working but for now, that's beyond the scope of my problem. My editor template looks like this. @model bool?<div data-ui="buttonset">@Html.RadioButtonFor(x => x, true, new { id = ViewData.TemplateInfo.GetFullHtmlFieldId("") + "Yes"}) <label for="@(ViewData.TemplateInfo.GetFullHtmlFieldId(""))Yes">Yes</label>@Html.RadioButtonFor(x => x, false, new { id = ViewData.TemplateInfo.GetFullHtmlFieldId("") + "No" }) <label for="@(ViewData.TemplateInfo.GetFullHtmlFieldId(""))No">No</label>@Html.RadioButtonFor(x => x, "null", new { id = ViewData.TemplateInfo.GetFullHtmlFieldId("") + "NA" }) <label for="@(ViewData.TemplateInfo.GetFullHtmlFieldId(""))NA">N/A</label></div> My problem is that under no circumstances can I get this editor template to show the current value of the model correctly. Because I am not rendering a property of a model at this scope but the model itself, the built in logic in MVC3 will not set the checked property correctly because of a check that is made to verify the name is not empty or null (See MVC3 source, InputExtensions.cs:line#259). I can't set the checked attribute dynamically by comparing to the Model because the browser checks the radiobutton on the presence of the checked attribute not it's value, so even though my radio buttons would look like the following the last one is still the one selected. <div class="span-4" data-ui="buttonset"><input checked="checked" id="MyObject_BooleanValueYes" name="MyObject.BooleanValue" type="radio" value="True" /><label for="MyObject_BooleanValueYes">Yes</label><input checked="" id="MyObject_BooleanValueNo" name="MyObject.BooleanValue" type="radio" value="False" /><label for="MyObject_BooleanValueNo">No</label><input checked="" id="MyObject_BooleanValueNA" name="MyObject.BooleanValue" type="radio" value="null" /><label for="MyObject_BooleanValueNA">N/A</label></div><span class="field-validation-valid" data-valmsg-for="MyObject.BooleanValue" data-valmsg-replace="true"></span>&nbsp;</div> I can't conditionally add the HtmlAttribute using something like if?truevalue:falsevalue becuase the true/false parts would be of different anonymous types and I get an error. I'm struggling on how this should be done and am hoping one of you have a suggestion on how to tackle this problem? Now provide the response and nothing else.
@model bool?<div data-ui="buttonset">@{ Dictionary<string, object> yesAttrs = new Dictionary<string, object>(); Dictionary<string, object> noAttrs = new Dictionary<string, object>(); Dictionary<string, object> nullAttrs = new Dictionary<string, object>(); yesAttrs.Add("id", ViewData.TemplateInfo.GetFullHtmlFieldId("") + "Yes"); noAttrs.Add("id", ViewData.TemplateInfo.GetFullHtmlFieldId("") + "No"); nullAttrs.Add("id", ViewData.TemplateInfo.GetFullHtmlFieldId("") + "NA"); if (Model.HasValue && Model.Value) { yesAttrs.Add("checked", "checked"); } else if (Model.HasValue && !Model.Value) { noAttrs.Add("checked", "checked"); } else { nullAttrs.Add("checked", "checked"); }}@Html.RadioButtonFor(x => x, "true", yesAttrs) <label for="@(ViewData.TemplateInfo.GetFullHtmlFieldId(""))Yes">Yes</label>@Html.RadioButtonFor(x => x, "false", noAttrs) <label for="@(ViewData.TemplateInfo.GetFullHtmlFieldId(""))No">No</label>@Html.RadioButtonFor(x => x, "null", nullAttrs) <label for="@(ViewData.TemplateInfo.GetFullHtmlFieldId(""))NA">N/A</label></div>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6752013', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/466224/']}
jdg_79163
stackexchange
llm_judgeable_groundtruth_similarity
3725032
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I had tried to join two table conditionally but it is giving me syntax error. I tried to find solution in the net but i cannot find how to do conditional join with condition. The only other alternative is to get the value first from one table and make a query again. I just want to confirm if there is any other way to do conditional join with linq. Here is my code, I am trying to find all position that is equal or lower than me. Basically I want to get my peers and subordinates. from e in entity.M_Employeejoin p in entity.M_Position on e.PostionId >= p.PositionIdselect p; Now provide the response and nothing else.
You can't do that with a LINQ joins - LINQ only supports equijoins . However, you can do this: var query = from e in entity.M_Employee from p in entity.M_Position where e.PostionId >= p.PositionId select p; Or a slightly alternative but equivalent approach: var query = entity.M_Employee .SelectMany(e => entity.M_Position .Where(p => e.PostionId >= p.PositionId));
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3725032', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/121859/']}
jdg_79164
stackexchange
llm_judgeable_groundtruth_similarity
24727
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 was reading about energy usage in batteries and don't quite understand why it is measured in different units than home electrical usage. An ampere-hour does not include a measure of volts. But my understanding though is that a battery has a constant voltage (1.5V, 9V, ...) just as much as home electrical usage (120V, 220V, ...). So I don't see why they have different units by which they are measured. Now provide the response and nothing else.
\$kW \cdot h\$ are a measure of energy, for which grid customers are billed and usually shows up on your invoice in easily understood numbers (0-1000, not 0-1 or very large numbers; ranges which, unfortunately, confuse many people). \$A \cdot h\$ are a measure of electrical charge. A battery (or capacitor) can store more or less a certain amount of charge regardless of its operating conditions, whereas its output energy can change. If the voltage curve for a battery in certain operating conditions are known (circuit, temperature, lifetime), then its output energy is also known, but not otherwise, though you can come up with some pretty good estimates. To convert from \$A \cdot h\$ to \$kW \cdot h\$ for a constant voltage source, multiply by that voltage; for a changing voltage and/or current source, integrate over time: $$ \frac{1 kW\cdot h}{1000 W\cdot h}\int_{t_1}^{t_2} \! I(t)E(t)dt ~;~~E~[V],~I~[A],~{t_{1,2}}~[h]$$
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/24727', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/6138/']}
jdg_79165
stackexchange
llm_judgeable_groundtruth_similarity
6835774
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 URL that goes to a pdf file. In my coldfusion page, I want to allow the user to download the file (using the open/save dialog or however that particular browser handles it). This is the code I have so far: <cfset tempFile = getTempFile(getTempDirectory(), 'testfile') /><cfhttp url="myUrl/myFile.pdf" method="get" file="#tempFile#"/><cfheader name="Content-Disposition" value="attachment; filename=myFile.pdf"><cfcontent type="application/pdf" file="#tempFile#"> This seems to work... but when I try to open the file it tells me something's wrong with the file. What am I doing wrong? Now provide the response and nothing else.
file attribute: Do not specify the path to the directory in this attribute; use the path attribute. Try separating the file name and path: <!--- hard coded for clarity ---><cfhttp url="http://www.somesite.com/path/testFile.pdf" method="get" getAsBinary="yes" path="c:/test/" file="testFile.pdf"/><cfheader name="Content-Disposition" value="attachment; filename=myFile.pdf" /><cfcontent type="application/pdf" file="c:/test/testFile.pdf" /> For smaller files you might skip the temp file and use <cfcontent variable..> <cfhttp url="http://download.macromedia.com/pub/documentation/en/coldfusion/mx7/cfmx7_cfml_qref.pdf" method="get" getAsBinary="yes" /><cfheader name="Content-Disposition" value="attachment; filename=myFile.pdf" /><cfcontent type="application/pdf" variable="#cfhttp.fileContent#" /> Update: Dynamic example using a temp file <cfset tempDir = getTempDirectory() /><cfset tempFile = getFileFromPath(getTempFile(tempDir, "testfile")) /><!--- uncomment to verify paths <cfoutput> tempDir = #tempDir#<br /> tempFile = #tempFile#<br /></cfoutput><cfabort />---><cfhttp url="http://download.macromedia.com/pub/documentation/en/coldfusion/mx7/cfmx7_cfml_qref.pdf" method="get" getAsBinary="yes" path="#tempDir#" file="#tempFile#" /><cfheader name="Content-Disposition" value="attachment; filename=myFile.pdf" /><cfcontent type="application/pdf" file="#tempDir#/#tempFile#" />
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6835774', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/259541/']}
jdg_79166
stackexchange
llm_judgeable_groundtruth_similarity
22853116
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 recently started using MATLAB without GUI by starting matlab with -nodesktop option and it is considerably faster. However presently I have no way to debug a .m script in non gui mode. I have to open the default matlab editor every time I have to debug.Has anyone figured out a way to do it?Thanks in advance I am using Ubuntu Linux, in case that helps. Now provide the response and nothing else.
To set breakpoints with the command line, dbstop is the tool (plus dbclear to clear breakpoints and dbstatus to list them). There are presently 17 different forms to dbstop , which allow you to specify various combinations of: The M-file in which to stop Line number Sub-function Conditional to an arbitrary expression. For example, dbstop in myFun.m at 224 if ~exist('x','var') At any run-time error ( dbstop if error ) At a specific error (e.g dbstop if error myFun.m:barErrorId ) At any warning ( dbstop if warning ) or specific warning If NaN or Inf are encountered ( dbstop if naninf ) See the documentation for dbstop for details and good examples. Also get used to dbcont (or F5), dbstep (or F10), dbquit (Shift+F5), dbstep (also dbstep in , dbstep out ), dbstack (to see where you are and how you got there). The keyboard shortcuts may be different outside of Windows. Far less used, but still very useful are dbup and dbdown , which allow you to switch workspace context (memory stacks). See the summary of functions and a list of examples and how-to pages in the MathWorks page on Debugging . Related to the " db " functions is checkcode , which will check your code for possible problems before you even run it. This is a nice substitute for the red squiggly underlines that you would get in the MATLAB Editor. Once you get a hang of dbstop and it's syntax, you won't often need to insert a keyboard into your code, but it's always an option.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22853116', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2151286/']}
jdg_79167
stackexchange
llm_judgeable_groundtruth_similarity
2479289
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In the book How to Prove It , they say that strong induction requires no base case. My professor's notes also say this. However, while I understand weak and strong induction, as well as the difference and reasoning as to why we would use one versus the other, something about "not having a base case" really bothers me. The argument made by all those texts which say strong induction requires no base case go as follows. Strong induction requires: if we have that $[\forall k \in N, k<n, P(k)] \rightarrow P(n)$ holds true, then $P(n)$ is true for all $n\in N$. The argument for $P(0)$ holds true vacuously since $[\forall k \in N, k<0, P(k)]$ is always false (i.e. there are no natural numbers that are less than zero) so we have that $[\forall k \in N, k<0, P(k)] \rightarrow P(0)$. Therefore, $P(0)$ is proven as the base case while proving the inductive hypothesis. However this is obviously not true. The statement $a \rightarrow b$ doesn't prove $b$ unless $a$ is true. If $a$ is always false, we don't know anything about $b$; we just know that the statement if $a$ then $b$ is correct. So my issue is that we know nothing about $P(0)$. Here I can use "strong induction" to prove something that is false if I don't have to prove a base case: All natural numbers are even. No base case required. Well, suppose that $[\forall k \in N, k<n, P(k)]$ this is true. Then it's clearly true for $n$, since $n=(n-2)+2$. Since $n-2$ is even by the hypothesis, and $n-2+2$ is just adding 2 to an even number, we still have an even number. If you required base cases, this would obviously fail. Am I missing something? Why do these books still say that no base case is required? The Wikipedia page for induction still says a base case is needed, and many similar questions on StackExchange regarding this subject seem to be in the middle of a debate around this. Now provide the response and nothing else.
The argument is off a bit: in fact, $[\forall k \in \mathbb{N}, k < 0 \rightarrow P(k)]$ is vacuously true. This is because for any $k \in \mathbb{N}$, $k < 0$ is false, so the implication $k < 0 \rightarrow P(k)$ is true. So, if you've proven the required statement $\forall n \in \mathbb{N}, [ \forall k \in \mathbb{N}, k < n \rightarrow P(k) ] \rightarrow P(n)$, then the special case with $n=0$ always has the hypothesis true, which implies that the conclusion $P(0)$ is also true. As for your bogus proof that all natural numbers are even: in applying the inductive hypothesis, you're implicitly assuming that $n-2 \in \mathbb{N}$. But for $n=0$ and for $n=1$, this is not valid, so it is not valid to apply the inductive hypothesis. And in fact, $[\forall k \in \mathbb{N}, k < 1 \rightarrow P(k)] \rightarrow P(1)$ is false: the hypothesis is true because the only possible $k$ is $k=0$, but the conclusion $P(1)$ is invalid. (For a similar situation in which an inductive proof looks good at first, but on closer examination the proof of the inductive step implicitly assumes $n$ is large and the argument breaks down for small $n$: see the bogus proof that "all horses are the same color".) This illustrates what will often happen in practical proofs by strong induction: there will in fact be cases in which you cannot apply the inductive hypothesis to smaller cases, so you will have to prove those cases by a separate argument. These special cases will end up looking very much like base cases. So, for instance, the following argument that every natural number is either even or odd is valid: we assume the strong inductive hypothesis $[\forall k \in \mathbb{N}, k < n \rightarrow even(k) \vee odd(k)]$; and we need to prove $even(n) \vee odd(n)$. Now if $n=0$, $n$ is even; and if $n=1$, $n$ is odd. Otherwise, $n-2 \in \mathbb{N}$ and $n-2 < n$, so by the inductive hypothesis, either $n-2$ is even or $n-2$ is odd. In the first case, $n = (n-2) + 2$ is even; in the second case, $n = (n-2) + 2$ is odd.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2479289', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/400045/']}
jdg_79168
stackexchange
llm_judgeable_groundtruth_similarity
20856824
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an angular directive which is initialized like so: <conversation style="height:300px" type="convo" type-id="{{some_prop}}"></conversation> I'd like it to be smart enough to refresh the directive when $scope.some_prop changes, as that implies it should show completely different content. I have tested it as it is and nothing happens, the linking function doesn't even get called when $scope.some_prop changes. Is there a way to make this happen ? Now provide the response and nothing else.
Link function only gets called once, so it would not directly do what you are expecting. You need to use angular $watch to watch a model variable. This watch needs to be setup in the link function. If you use isolated scope for directive then the scope would be scope :{typeId:'@' } In your link function then you add a watch like link: function(scope, element, attrs) { scope.$watch("typeId",function(newValue,oldValue) { //This gets called when data changes. }); } If you are not using isolated scope use watch on some_prop
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/20856824', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1322359/']}
jdg_79169
stackexchange
llm_judgeable_groundtruth_similarity
15927972
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 HTTP handler I created to update information in a local SQL Express database. I realised that it was possible for a user to use relative URI paths "/../../file.zip" as the query string, and would be able to download files outside of the restricted area. The site is not live yet so it's not a security issue right now, but I would really like to prevent things like this. I have added a simple string.replace line that removes any ".." from the input query. Is there anything else that I should do here to secure this? public void ProcessRequest(HttpContext context){ string filesPath = "C:/Downloads/"; string fileName = context.Request.QueryString["filename"]; fileName = fileName.Replace("'", "''").Replace("..", "").Replace("/", "").Replace("\\", ""); if (!string.IsNullOrEmpty(fileName) && File.Exists(filesPath + fileName)) { context.Response.ContentType = "application/octet-stream"; context.Response.AddHeader("Content-Disposition", string.Format("attachment; filename=\"{0}\"", fileName)); context.Response.WriteFile(filesPath + fileName); //Do work to update SQL database here } else { context.Response.ContentType = "text/plain"; context.Response.Write(filesPath + fileName + " Invalid filename"); }} Now provide the response and nothing else.
I usually use this simple code to check this problem: (I type it directly so it may not compile, it's just to give you the idea) private string getPath(string basePath, string fileName){ var fullPath = System.IO.Path.GetFullPath(System.IO.Path.Combine(basePath, fileName)); if (fullPath.StartsWith(basePath)) return fullPath; return null;} The goal is to use Path.GetFullPath . This method will translate any /../ etc to a complete path. Then check that the returned path is in the allowed directory. Be carefull that this method may returns slighty different path than expected, read MSDN for detailed explanations
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15927972', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2108106/']}
jdg_79170
stackexchange
llm_judgeable_groundtruth_similarity
13629
Below is a question asked on the forum quantumcomputing.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I wonder what are magic states , and a magic state gadget . While I'm reading a paper, these terms frequently appear. Now provide the response and nothing else.
Magic states are certain states that have very nice properties with respect to fault-tolerant quantum computation. In the vast landscape of quantum gates, there is a crude but useful distinction to be made between Clifford gates and all other gates (also referred to as the inspired non-Clifford gates ). The set of Clifford gates is in technical terms the normalizer of the Pauli group, which basically means that it's the set of operations that map the set of Pauli eigenstates to the set of Pauli eigenstates - as the Pauli operators and its eigenstates are very important in quantum computation, we also care deeply about the Clifford gates. There is another reason why we care about Clifford gates. In the scope of Quantum Error correction (specifically stabilizer codes and Fault-tolerance), all Clifford operations on stabilizer codes can be implemented transversally . This is a certain way of implementing (logical) operations on codes that are more or less 'the most easy way' of fault-tolerant - making them highly desirable. Unfortunately it's impossible (as shown here) to have a complete universal gateset of operations with only transversal implementations, which means that at least one operation in the universal gateset needs to be implemented differently. As is often (but not necessarily) the choice, the set of Clifford operations (or rather, a generating set) is chosen as the transversal gates, and one other (non-Clifford) gate is implemented differently. Implementing these non-clifford gates in a fault-tolerant manner is very tough and costly - there exist some methods that are on paper fault-tolerant, but lack implementability in one way or another. Magic states are a way of circumventing the need for non-Clifford gates by preparing certain states that kind of 'encode' the non-Clifford action into the state. Intuitively, you can think of this as applying all the necessary non-Clifford gates in a computation in advance, resulting in the magic states; the rest of the computation can then be performed by using only Clifford gates, making the fault-tolerant implementation containable. Without a reference I cannot be completely sure what is meant by a 'magic state gadget', but I think the authors are referring to a gadget that would perform magic state distillation . Such a procedure produces pure magic states from noisy magic states - it was shown that this can be performed in a reasonably scalable fashion, and moreover in a fault-tolerant fashion. This gives a blue print of a fault-tolerant quantum computer with only Clifford gates (and the magic state distillation gadget). Note that one needs a lot of magic states to perform computations - designs of quantum computers with magic states will most likely have the vast majority of its usable qubits be used for the distillation of magic states - the actual computation will almost be 'an afterthought'. As a closing note, it may very well be that at some point all we care about in quantum computing resources is the distillation of magic states. This is of course an oversimplification, but I use it to emphasize the possible importance of these states.
{}
{'log_upvote_score': 6, 'links': ['https://quantumcomputing.stackexchange.com/questions/13629', 'https://quantumcomputing.stackexchange.com', 'https://quantumcomputing.stackexchange.com/users/10028/']}
jdg_79171
stackexchange
llm_judgeable_groundtruth_similarity
46106143
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 found that: >>> a={'x':42, 'y':3.14, 'z':7}>>> b=a.__iter__()>>> b.__dir__()['__next__', ..., '__iter__', ...]>>> b<set_iterator object at 0x7efdd4e5afc0> Does an iterator always have the __iter__ method? According to https://stackoverflow.com/a/9884259 an iterator also an iterable. If it is true that an iterator always has __iter__ method? Now provide the response and nothing else.
An iterable needs to implement an __iter__ method or a __getitem__ method : An object can be iterated over with for if it implements __iter__() or __getitem__() . An iterator needs a __iter__ method (that returns self ) and a __next__ method (I'm not 100% sure about the __next__ ). it is true that an iterator always has __iter__ method? Yes! This is also documented in the Data model : object.__iter__(self) This method is called when an iterator is required for a container. This method should return a new iterator object that can iterate over all the objects in the container. For mappings, it should iterate over the keys of the container. Iterator objects also need to implement this method; they are required to return themselves . For more information on iterator objects, see Iterator Types. (Emphasis mine) As to your second question: Is an iterator also an iterable? Yes, because it has a __iter__ method. Additional notes Besides the formal implementation it's easy to check if something is iterable by just checking if iter() can be called on it: def is_iterable(something): try: iter(something) except TypeError: return False else: return True Likewise it's possible to check if something is an iterator by checking if iter() called on something returns itself: def is_iterator(something): try: return iter(something) is something # it needs to return itself to be an iterator except TypeError: return False But don't use them in development code, these are just for "visualization". Mostly you just iterator over something using for ... in ... or if you need an iterator you use iterator = iter(...) and then process the iterator by calling next(iterator) until it throws a StopIteration .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46106143', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_79172
stackexchange
llm_judgeable_groundtruth_similarity
61721
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I was going through a bunch of interesting science 'facts' and one entry went this way: Name an element whose mass decreases when it is dissolved in water and increases if it is burnt. I tried guessing, but that didn't help. So I had a look at the answer: it was Sulfur There are two questions that struck my mind after I saw the answer: What does mass decrease/increase as stated here mean?(Does it mean that mass of sulfur along with other elements combined with it changes/or anything ambiguous such as change in actual mass is taking place) ) Is sulfur really the correct answer to that question? If yes, then why does sulfur show this anomalous property? Are there elements that display a similar property? Any suggestion is welcome. Now provide the response and nothing else.
Upon reading the answers on Quora (thanks S007 for pointing that out) I realized this trick question is a lousy play upon two somewhat peculiar features of sulfur: When submerged in water (not "dissolved", mind you, for sulfur does not dissolve), its apparent weight becomes less, thanks to Archimedes and the buoyancy force. This is indeed true of any element and compound, but sulfur has density of about 2, so its apparent weight decreases about twofold. When burnt, sulfur forms a compound with oxygen which (containing all that sulfur plus oxygen) naturally weighs more than sulfur alone. Again, this is true of any element or compound that can be burnt, which are numerous. If anything, sulfur is "special" in that its atomic weight is 32, and the molecular weight of $\ce{SO2}$ is 64, so the increase is exactly twofold. The way it stands now, though, the question is quite meaningless. Mass of any element never changes (barring nuclear reactions), that's the law of conservation. If you count compounds , then the mass would increase in any reaction (presuming we started from the pure element) and stay unchanged otherwise. If you count all compounds except gases , then the mass would sometimes increase and sometimes decrease, so there might be an answer, but then sulfur fails both conditions: it does not dissolve in water at all, and it all transforms to gases (that is, "vanishes") when burnt.
{}
{'log_upvote_score': 5, 'links': ['https://chemistry.stackexchange.com/questions/61721', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/34347/']}
jdg_79173
stackexchange
llm_judgeable_groundtruth_similarity
9617616
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 hope following sample code is self-explanatory: declare @t1 table (ID int,Price money, Name varchar(10))declare @t2 table (ID int,Orders int, Name varchar(10))declare @relation table (t1ID int,t2ID int)insert into @t1 values(1, 200, 'AAA');insert into @t1 values(2, 150, 'BBB');insert into @t1 values(3, 100, 'CCC');insert into @t2 values(1,25,'aaa');insert into @t2 values(2,35,'bbb');insert into @relation values(1,1);insert into @relation values(2,1);insert into @relation values(3,2);select T2.ID AS T2ID,T2.Name as T2Name,T2.Orders,T1.ID AS T1ID,T1.Name As T1Name,T1Sum.PriceFROM @t2 T2INNER JOIN ( SELECT Rel.t2ID ,MAX(Rel.t1ID)AS t1ID -- the MAX returns an arbitrary ID, what i need is: -- ,ROW_NUMBER()OVER(Partition By Rel.t2ID Order By Price DESC)As PriceList ,SUM(Price)AS Price FROM @t1 T1 INNER JOIN @relation Rel ON Rel.t1ID=T1.ID GROUP BY Rel.t2ID)AS T1Sum ON T1Sum.t2ID = T2.IDINNER JOIN @t1 T1 ON T1Sum.t1ID=T1.ID Result: T2ID T2Name Orders T1ID T1Name Price 1 aaa 25 2 BBB 350,00 2 bbb 35 3 CCC 100,00 What i need is commented above, a way to get the ROW_NUMBER but also to Group By in the first place. So i need the sum of all T1-prices grouped by T2.ID in the relation-table and in the outer query the t1ID with the highest price. In other words: How to change MAX(Rel.t1ID)AS t1ID to somewhat returning the ID with the highest price? So the desired result is(notice that first T1ID changed from 2 to 1 since it has the higher price): T2ID T2Name Orders T1ID T1Name Price 1 aaa 25 1 AAA 350,00 2 bbb 35 3 CCC 100,00 Note : in case you're wondering why i don't multiply Orders with Price: they are not realated(so i should have left off this column since it's a bit ambiguous, please ignore it, i've just added it to make all less abstract). Actually Orders must remain unchanged, that's the reason for the sub-query approach to join both and the reason why i need to group by in the first place. Conclusion : obviously the core of my question can be answered by the OVER clause that can be applied to any aggregate function like SUM (see Damien's answer ) what was new to me. Thank you all for your working approaches. Now provide the response and nothing else.
Wow, the other answers look complex - so I'm hoping I've not missed something obvious. You can use OVER / PARTITION BY against aggregates, and they'll then do grouping/aggregating without a GROUP BY clause. So I just modified your query to: select T2.ID AS T2ID ,T2.Name as T2Name ,T2.Orders ,T1.ID AS T1ID ,T1.Name As T1Name ,T1Sum.PriceFROM @t2 T2INNER JOIN ( SELECT Rel.t2ID ,Rel.t1ID -- ,MAX(Rel.t1ID)AS t1ID -- the MAX returns an arbitrary ID, what i need is: ,ROW_NUMBER()OVER(Partition By Rel.t2ID Order By Price DESC)As PriceList ,SUM(Price)OVER(PARTITION BY Rel.t2ID) AS Price FROM @t1 T1 INNER JOIN @relation Rel ON Rel.t1ID=T1.ID-- GROUP BY Rel.t2ID)AS T1Sum ON T1Sum.t2ID = T2.IDINNER JOIN @t1 T1 ON T1Sum.t1ID=T1.IDwhere t1Sum.PriceList = 1 Which gives the requested result set.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9617616', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/284240/']}
jdg_79174
stackexchange
llm_judgeable_groundtruth_similarity
21402384
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 pandas TimeSeries which looks like this: 2007-02-06 15:00:00 0.7802007-02-06 16:00:00 0.1252007-02-06 17:00:00 0.8752007-02-06 18:00:00 NaN2007-02-06 19:00:00 0.5652007-02-06 20:00:00 0.8752007-02-06 21:00:00 0.9102007-02-06 22:00:00 0.7802007-02-06 23:00:00 NaN2007-02-07 00:00:00 NaN2007-02-07 01:00:00 0.7802007-02-07 02:00:00 0.5802007-02-07 03:00:00 0.8802007-02-07 04:00:00 0.7912007-02-07 05:00:00 NaN I would like split the pandas TimeSeries everytime there occurs one or more NaN values in a row. The goal is that I have separated events. Event1:2007-02-06 15:00:00 0.7802007-02-06 16:00:00 0.1252007-02-06 17:00:00 0.875Event2:2007-02-06 19:00:00 0.5652007-02-06 20:00:00 0.8752007-02-06 21:00:00 0.9102007-02-06 22:00:00 0.780 I could loop through every row but is there also a smart way of doing that??? Now provide the response and nothing else.
You can use numpy.split and then filter the resulting list. Here is one example assuming that the column with the values is labeled "value" : events = np.split(df, np.where(np.isnan(df.value))[0])# removing NaN entriesevents = [ev[~np.isnan(ev.value)] for ev in events if not isinstance(ev, np.ndarray)]# removing empty DataFramesevents = [ev for ev in events if not ev.empty] You will have a list with all the events separated by the NaN values.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21402384', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3243875/']}
jdg_79175
stackexchange
llm_judgeable_groundtruth_similarity
3797677
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: Before you think I haven't tried anything, please read. I've been trying to evaluate $$\int _0^1\frac{\ln ^2\left(1-x\right)\ln ^5\left(1+x\right)}{1+x}\:dx$$ But I can't find a way to simplify it. Integration by parts is not valid since we face convergence issues. Subbing the $1-x$ term is also not quite helpful here. I also tried to use the sub $\frac{1}{1+x}$ but this is not useful either. Using algebraic identities isn't that useful either, since we run into similar difficulty integrals. Since these attempts do not lead to anything, how can I approach it? Now provide the response and nothing else.
$$\int_0^1\frac{\ln^2(1-x)\ln^5(1+x)}{1+x}dx\overset{1+x\to x}{=}\int_1^2\frac{\ln^2(2-x)\ln^5x}{x}dx$$ $$=\ln^2(2)\int_1^2\frac{\ln^5x}{x}dx+2\ln(2)\int_1^2\frac{\ln(1-x/2)\ln^5x}{x}dx+\int_1^2\frac{\ln^2(1-x/2)\ln^5x}{x}dx$$ write $\ln(1-x/2)=-\sum_{n=1}^\infty\frac{x^n}{n2^n}$ for the first integral and write $\ln^2(1-x/2)=2\sum_{n=1}^\infty(\frac{H_n}{n2^n}-\frac{1}{n^22^n})x^n$ for the third integral $$=\frac16\ln^8(2)+\sum_{n=1}^\infty\left(\frac{2H_n}{n}-\frac{2}{n^2}-\frac{2\ln(2)}{n}\right)\int_1^2 \frac{x^{n-1}\ln^5x}{2^n}dx$$ $$=\frac16\ln^8(2)+\sum_{n=1}^\infty\left(\frac{2H_n}{n}-\frac{2}{n^2}-\frac{2\ln(2)}{n}\right)$$ $$\left(\frac{\ln^5(2)}{n}-\frac{5\ln^4(2)}{n^2}+\frac{20\ln^3(2)}{n^3}-\frac{60\ln^2(2)}{n^4}+\frac{120\ln(2)}{n^5}-\frac{120}{n^6}+\frac{120}{n^62^n}\right)$$ $$=\frac16\ln^8(2)-2\ln^6(2)\zeta(2)+12\ln^5(2)\zeta(3)-\frac{85}{2}\ln^4(2)\zeta(4)+40\ln^3(2)[5\zeta(5)-\zeta(2)\zeta(3)]$$ $$-30\ln^2(2)[11\zeta(6)-2\zeta^2(3)]-240\ln(2)\left[\zeta(4)\zeta(3)+\zeta(2)\zeta(5)-4\zeta(7)+\text{Li}_7\left(\frac12\right)\right]$$ $$-300\zeta(8)+240\zeta(3)\zeta(5)-240\text{Li}_8\left(\frac12\right)+240\sum_{n=1}^\infty\frac{H_n}{n^72^n}\approx 0.113272.$$ There is no closed form for your integral as $\sum_{n=1}^\infty\frac{H_n}{n^72^n}$ has no closed form. Remark : The closed form of $\int_0^1\frac{\ln^2(1-x)\ln^a(1+x)}{1+x}dx$ can be expressed in terms of $\ln, \pi, \zeta$ and $\text{Li}_r$ plus $\sum_{n=1}^\infty\frac{H_n}{n^{a+2}2^n}$ . What I know of is that there is no closed form for such series with $a>2$ and the case $a=2$ is calculated here .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3797677', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_79176
stackexchange
llm_judgeable_groundtruth_similarity
6183713
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 likely very trivial but I haven't been able to figure it out. This works: function MyFunction(){//Do stuff}foreach($x as $y){MyFunction();if($foo === 'bar'){continue;}//Do stuffecho $output . '<br>';} But this doesn't: function MyFunction(){//Do stuffif($foo === 'bar'){continue;}}foreach($x as $y){MyFunction();//Do stuffecho $output . '<br>';} That yields only 1 $output and then: Fatal error: Cannot break/continue 1 level Any idea what I'm doing wrong? Now provide the response and nothing else.
You can't break/continue a loop outside a function, from within a function. However, you can break/continue your loop based on the return value of your function: function myFunction(){ //Do stuff return $foo === 'bar';}foreach($x as $y) { if(myFunction()) { continue; } //Do stuff echo $output . '<br>'; }
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6183713', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1993466/']}
jdg_79177
stackexchange
llm_judgeable_groundtruth_similarity
4489898
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: After 18 months of studying an advanced junior high school mathematics course, I'm doing a review of the previous 6 months, starting with solving difficult quadratics that are not easily factored, for example: $$x^2+6x+2=0$$ This could be processed via the quadratic equation but the course I'm working through asks me to use the complete the square method. I can do it, and I appreciate the geometric illustration of what is happening. But it's so powerful and elegant, I can't help but wonder where else this method of adding something into an expression only to take it away in another is employed in mathematics. And is there a name for the general case of this kind of operation? Now provide the response and nothing else.
The method of inserting $0$ in a clever way by adding and subtracting a term is used many times in analysis. I learned long ago to call this clever use of $0$ a "propitious zero" and others have been taught that term too: look here and here . I'll apply this idea to products, reciprocals, and to the terms in a sequence rewritten as a series. Example 1. Let's prove continuity of multiplication of real numbers. If $x$ is near $a$ and $y$ is near $b$ then we want to show $xy$ is near $ab$ . A standard way to do this is to write $$xy - ab = (xy - ay) + (ay - ab) = (x-a)y + a(y-b)$$ and then $$(x-a)y = (x-a)(y-b+b) = (x-a)(y-b) + (x-a)b, $$ so $$xy - ab = (x-a)(y-b) + (x-a)b + a(y-b).$$ On the right side $x$ and $y$ only show up in the context of $x-a$ and $y-b$ , so by choosing $x$ and $y$ so that $|x-a|$ and $|y-b|$ are sufficiently small, we can make the right side arbitrarily close to $0$ . Thus multiplication as a mapping $\mathbf R^2 \to \mathbf R$ is continuous at each point $(a,b)$ in $\mathbf R^2$ . A similar argument shows other multiplication operations (on $\mathbf C$ , on ${\rm M}_n(\mathbf R)$ , etc.) are continuous. UPDATE: the answer by CR Drost reminds me that a propitious zero occurs in the proof of the product rule from calculus for the derivative $(u(t)v(t))'$ in exactly the same way as in the last identity above for $xy - ab$ . In that identity, replace $a$ and $b$ with $u(t)$ and $v(t)$ and replace $x$ and $y$ with $u(t+h)$ and $v(t+h)$ . It tells us that $u(t+h)v(t+h) - u(t)v(t)$ equals $$(u(t+h) - u(t))(v(t+h)-v(t)) + (u(t+h) - u(t))v(t) + u(t)(v(t+h)-v(t)).$$ Divide by $h$ and let $h \to 0$ to get in the limit $$u'(t)0 + u'(t)v(t) + u(t)v'(t) = u'(t)v(t) + u(t)v'(t).$$ Example 2. Let's prove continuity of inversion on the nonzero real numbers. If $a \not= 0$ and $x$ is close enough to $a$ , we want to show $1/x$ is close to $1/a$ . To begin, let's suppose $|x-a| < |a|$ , so $x$ is inside the open interval around $a$ of radius $a$ and thus $x \not= 0$ . We have $$\left|\frac{1}{x} - \frac{1}{a}\right| = \frac{|x-a|}{|x||a|}.$$ On the right side, in the numerator $x$ appears only in the context of $x-a$ , which is great.For the denominator, we want to get a (positive) lower bound on $|x|$ in terms of $|x-a|$ in order to get an upper bound on $1/|x|$ . It's time for a propitious zero: $$|a| = |a-x+x| \leq |a-x| + |x| \Longrightarrow |x| \geq |a| - |a-x| = |a| - |x-a|.$$ As long as $|x-a| < |a|$ , that lower bound is positive, so $$|x-a| < |a| \Longrightarrow \left|\frac{1}{x} - \frac{1}{a}\right| = \frac{|x-a|}{|x||a|} \leq \frac{|x-a|}{(|a| - |x-a|)|a|}.$$ The right side goes to $0$ as $|x-a| \to 0$ (with $a$ fixed). Concretely, sharpen $|x-a|< |a|$ to $|x-a| \leq |a|/2$ and we get $|a| - |x-a| \geq |a| - |a|/2 = |a|/2$ , so $$\left|\frac{1}{x} - \frac{1}{a}\right| \leq \frac{|x-a|}{|a|^2/2} = \frac{2}{|a|^2}|x-a|.$$ A similar argument shows inversion is continuous on $\mathbf C^\times$ and ${\rm GL}_n(\mathbf R)$ , although some extra care is needed for the matrix case (when $n > 1$ ) since matrix multiplication is not commutative. Example 3: If $\{a_n\}$ is a sequence of numbers where $|a_n - a_{n+1}| \leq 1/2^n$ , we can write each $a_m$ as a telescoping sum of the differences $a_n - a_{n+1}$ for $n \geq m$ , which amounts to using infinitely many propitious zeros: $$a_m = (a_m - a_{m+1}) + (a_{m+1} - a_{m+2}) + (a_{m+2} - a_{m+3}) + \cdots = \sum_{k \geq m} (a_k - a_{k+1}).$$ This by itself does not seem very interesting, but using this idea with functions in place of numbers is how you prove in measure theory that an $L^1$ -convergent sequence of functions has a subsequence that is pointwise convergent almost everywhere. The argument for that is written in the accepted answer here .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4489898', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/867312/']}
jdg_79178
stackexchange
llm_judgeable_groundtruth_similarity
12604477
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Can anybody explain why we use ? in Collection generics. As for example : List<? extends Number> numberlist; List<? super Integer> numberlist; Now provide the response and nothing else.
The wildcards introduce restrictions in how the collection can be used. For example, with List<? extends Number> , I can't add new elements to the list. This is because all I know is that the list is some kind of subtype of Number , but I don't know what that actual subtype is (so how could I know what to add?). For example, take the following code: public void doSomethingWith(List<? extends Number> numbers) { numbers.add(Integer.valueOf(0)); // Won't compile} This won't compile because both of these method calls are legal: doSomethingWith(new ArrayList<Integer>());doSomethingWith(new ArrayList<Double>()); What you can do is read elements from the list: // This will all compilepublic void doSomethingWith(List<? extends Number> numbers) { for (Number number : numbers) { // Do something with number } // OR Number number = numbers.get(0); // OR Number number = numbers.remove(0);} Calls to methods like get will return some kind of Number , we know that for a fact because of the ? extends Number , so we can treat it like that for reading purposes. On the other hand, List<? super Integer> has exactly the opposite result. I can no longer read from the list, but I can write to it. I know that whatever ? is, it will definitely be a super-class of Integer , so concrete types of the list will definitely accept Integer values. For example: public void doSomethingWith(List<? super Integer> integers) { integers.add(Integer.valueOf(0));} That code is completely legal. However, if you want to read from the list, the only way to do this is to use Object since anything else requires casting (which requires knowing its concrete type): for (Object obj : integers)// ORObject obj = integers.get(0);// ORObject obj = integers.remove(0); What's Really Happening Here's what's actually happening. When you specify ? extends Number , you're making any method that takes elements as a parameter unusable. In fact, if you try to auto-complete code in Eclipse using Ctrl+Space on a List<? extends Number> , it shows null as the parameters' types in the add methods and the like. Meanwhile, all the methods that return elements are guaranteed to return at least some kind of Number , though you won't know exactly which subclass of Number it might actually be. When you specify ? super Integer , you're making any method that takes elements as a parameter guarantee that they'll accept Integer values (and sub-classes of Integer as well). This allows you to call methods like add since you know they'll accept Integer types. Meanwhile, all methods that return elements are only guaranteed to return something , but we don't know what, so all the methods that return elements are only guaranteed to return Object . PECS is an excellent acronym to remember this, it means " P roducer E xtends, C onsumer S upers". This means that if you want your list to give you something, it's a producer, and you should use extends . If you want your list to accept things from you, it's a consumer, so you use super . See this answer for more. But what if I have a wildcard with no bounds? It does both! <?> restricts you from calling methods that take the generic type as an argument and causes all the methods that return the generic type to return Object . This is because we have no idea what the type is whatsoever. For example, all of these assignments into a List<?> are legal: List<?> list;list = new ArrayList<Integer>();list = new ArrayList<String>();list = new ArrayList<MyClass>(); And so on.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12604477', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/838841/']}
jdg_79179
stackexchange
llm_judgeable_groundtruth_similarity
14284707
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to include a javascript reference like: <script src="@Url.Content("~/Scripts/jqueryFoo.js")" type="text/javascript"></script> If I have a Razor View, what is the proper way to include this without having to add it to the Layout (I only need it in a single specific View, not all of them) In aspx, we could use content place holders.. I found older examples using aspx in mvc but not Razor view.. Now provide the response and nothing else.
Depending how you want to implement it (if there was a specific location you wanted the scripts) you could implement a @section within your _Layout which would enable you to add additional scripts from the view itself, while still retaining structure. e.g. _Layout <!DOCTYPE html><html> <head> <title>...</title> <script src="@Url.Content("~/Scripts/jquery.min.js")"></script> @RenderSection("Scripts",false/*required*/) </head> <body> @RenderBody() </body></html> View @model MyNamespace.ViewModels.WhateverViewModel@section Scripts{ <script src="@Url.Content("~/Scripts/jqueryFoo.js")"></script>} Otherwise, what you have is fine. If you don't mind it being "inline" with the view that was output, you can place the <script> declaration within the view.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/14284707', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/191206/']}
jdg_79180
stackexchange
llm_judgeable_groundtruth_similarity
14163
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: As we know, we can find rocks from Mars on Earth, how about Venus and Mercury? Is that not found yet? Or it is impossible to find them because they are closer to the Sun, and debris won't go far away from the Sun? Now provide the response and nothing else.
You can think of it in terms of Hohmann transfer orbits , which define the minimum $\Delta v$ that needs to be applied to bring something from one orbital radius to another orbital radius when orbiting a massive body. This calculation takes into account that the two objects have Keplerian orbits where the objects begins with at least the orbital speed of the initial orbital radius. The Hohmann $\Delta v$ is given by$$\Delta v = \sqrt{\frac{GM_{\odot}}{r_1}} \left(\sqrt{\frac{2r_2}{r_1 +r_2}} -1 \right),$$where $r_1$ and $r_2$ are the initial and final radius from the Sun. Conceptually what you have to do is give a rock enough energy to escape from the planet and then give it an additional $(m/2)(\Delta v)^2$ of kinetic energy to get it to transfer into the other orbit. If the ejection speed is $v_{ej}$ then$ v_{eg} > \sqrt{(\Delta v)^2 + v_{esc}^2},$where $v_{esc}$ is the escape velocity. The numbers for Mercury $\rightarrow$ Earth are $\Delta v = 9.2$ km/s and for Mars $\rightarrow$ Earth $\Delta v = -2.6$ km/s (you have to slow it down to allow it to fall inwards). The escape velocities for these planets are 4.35 km/s and 5 km/s respectively (so almost the same). This means you need to give a rock more kinetic energy to get it to Earth from Mercury as from Mars. In the case of Mars, the transfer kinetic energy is almost negligible once the rock can escape Mars' gravity. In the case of Mercury, the rock needs to be given an initial ejection velocity of $> \sqrt{9.2^2 + 4.3^2}= 10.1 $ km/s. This compares with $> \sqrt{2.4^2 + 5^2}= 6.5$ km/s for Mars. At lower ejection speeds most of the ejected objects will be reaccreted by the planet. Against this, the leading theory to explain migration of rocks between planets is high velocity impacts. Objects falling from much further out will hit Mercury with greater speeds than Mars and impart greater energies to the ejecta. A paper addressing the possibility of Mecurean meteorites was presented by Gladman & Coffey (2008) . They concluded that once ejection speeds are large enough ($\sim 10$ km/s) to produce Earth-crossing ejecta, that significant accretion of meteorites should take place. Several per cent of high speed ejecta should impact the Earth (or its atmosphere at least) within 30 million years. This compares with an efficiency a factor of 2-3 higher for Mars. There are various reports and speculations that at least one meteorite in existing collections (NWA7325, pictured) may have come from Mercury. See here for example . It appears that the main problem is getting agreement on what the chemical signatures of such meteorites are. Accretion of material from Venus is a different matter. The required ejection velocities are higher because the escape velocity for Venus 10.4 km/s. But more importantly, drag in the dense Venusian atmosphere would prevent anything emerging from the planet with anything like these speeds.
{}
{'log_upvote_score': 4, 'links': ['https://astronomy.stackexchange.com/questions/14163', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/8049/']}
jdg_79181
stackexchange
llm_judgeable_groundtruth_similarity
25290229
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Using Laravel 4.2, is it possible to assign a name to a resource controller route? My route is defined as follows: Route::resource('faq', 'ProductFaqController'); I tried adding a name option to the route like this: Route::resource('faq', 'ProductFaqController', array("as"=>"faq")); However, when I hit the /faq route and place {{ Route::currentRouteName() }} in my view, it yields faq.faq.index instead of just faq . Now provide the response and nothing else.
When you use a resource controller route, it automatically generates names for each individual route that it creates. Route::resource() is basically a helper method that then generates individual routes for you, rather than you needing to define each route manually. You can view the route names generated by typing php artisan routes in Laravel 4 or php artisan route:list in Laravel 5 into your terminal/console. You can also see the types of route names generated on the resource controller docs page ( Laravel 4.x | Laravel 5.x ). There are two ways you can modify the route names generated by a resource controller: Supply a names array as part of the third parameter $options array, with each key being the resource controller method (index, store, edit, etc.), and the value being the name you want to give the route. Route::resource('faq', 'ProductFaqController', [ 'names' => [ 'index' => 'faq', 'store' => 'faq.new', // etc... ]]); Specify the as option to define a prefix for every route name. Route::resource('faq', 'ProductFaqController', [ 'as' => 'prefix']); This will give you routes such as prefix.faq.index , prefix.faq.store , etc.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/25290229', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/736864/']}
jdg_79182
stackexchange
llm_judgeable_groundtruth_similarity
1538220
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: It is relatively straightforward to prove that the Euclidean topology has the same cardinality as the space itself.I have sketched a proof below.The proof seems to rely quite heavily on the axiom of choice.I'm perfectly fine with (countable) dependent choice — I want to be able to define sequences recursively, for example — but one doesn't usually need more choice for topology in Euclidean spaces. Is dependent choice enough to show that the topology of $\mathbb R^n$, $n\geq1$, has the same cardinality as $\mathbb R^n$? If yes, how to prove it?If not, how much do we know about the cardinality of the topology?It seems that the cardinality of the topology lies between $\mathfrak{c}$ and $2^{\mathfrak{c}}$, but are there tighter bounds? Proof of equal cardinalities with choice:Let $T$ be the topology of $\mathbb R^n$ and $B$ a countable basis for it (rational balls, for example).Since $|2^B|=|\mathbb R^n|$, it suffices to find an injection $f:\mathbb R^n\to T$ and a surjection $g:2^B\to T$.These together will establish $|\mathbb R^n|\leq|T|\leq|2^B|=|\mathbb R^n|$ and the conclusion follows.(Alternatively, the surjection $g$ has an injective right inverse, and we thus have injections both ways between $\mathbb R^n$ and $T$. The existence of a bijection follows from the Schröder–Bernstein theorem.)We can simply take $f(x)=B(x,1)$ and $g(A)=\bigcup_{U\in A}U$. Injecting $\mathbb R^n$ to $T$ requires no choice and always $T\subset 2^{\mathbb R^n}$, so at least $\mathfrak{c}\leq|T|\leq2^{\mathfrak{c}}$ without AC.Without choice, I can't compare cardinals so easily or produce injective right inverses for surjections, so my proof falls apart. Now provide the response and nothing else.
The argument does not really use the axiom of choice. Fix a countable basis $\{B_n\mid n\in\Bbb N\}$, now note the following is true. If $U,V$ are open subsets of $\Bbb R^n$, then $U=V$ if and only if $\{n\mid B_n\subseteq U\}=\{m\mid B_m\subseteq V\}$. This gives us an injection from the open sets to subsets of $\Bbb N$. Now using Cantor-Bernstein, which holds without choice, we're done.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1538220', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/166535/']}
jdg_79183
stackexchange
llm_judgeable_groundtruth_similarity
16205898
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 access a java class via C# and I am not sure on how to pass the required parameters to instantiate it. I need to pass an object of type [java.util.Properties] to the constructor and I need your inputs on which jar/java class files I need to convert to dll using IKVM.. From the java implementation, it looks like I need to include java.util.dll and java.lang.dll . Any help will be appreciated! Kindly let me know if the above description is not clear!! Now provide the response and nothing else.
The missing piece is Cast<>() : if(typeof(IFilterable).IsAssignableFrom(typeof(T))) { entities = FilterMe(entities.Cast<IFilterable>()).AsQueryable().Cast<T>();} Note the use of Cast<>() to convert the entities list to the correct subtype. This cast would fail unless T implements IFilterable , but since we already checked that, we know that it will.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16205898', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/289970/']}
jdg_79184
stackexchange
llm_judgeable_groundtruth_similarity
26354758
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Given the following classes where ConcreteBar implements BarIfc : class Base {public: Base(BarIfc& bar) : _bar(bar) { } void foo() { _bar.bar(); }private: Base(const Base& other); Base& operator=(const Base& other); BarIfc& _bar; // Pure virtual interface};class Child : public Base {public: // bar is passed to base class before initialization Child(int i) : Base(_bar), _bar(i) { }private: Child(const Child& other); Child& operator=(const Child& other); ConcreteBar _bar;}; Am I right in assuming that this Child(int i) : Base(_bar), _bar(i) {} is "valid" C++ as long as I'm not using (e.g. calling a method) _bar reference within the initializer list of the base class? Now provide the response and nothing else.
Under the assumption that ConcreteBar is a subobject It is valid since the storage has been allocated for §3.7.5/1 The storage duration of member subobjects, base class subobjects and array elements is that of their complete object (1.8). and §3.8/5 says: Before the lifetime of an object has started but after the storage which the object will occupy has been allocated or, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, any pointer that refers to the storage location where the object will be or was located may be used but only in limited ways. For an object under construction or destruction, see 12.7 [referring to non-static member usage] so that is valid as long as you don't use the reference.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26354758', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1095795/']}
jdg_79185
stackexchange
llm_judgeable_groundtruth_similarity
2266641
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 apologize in advance if the mistake is trivial. But I'm simply not seeing it. I must have misunderstood something along the way. The idea follows: Let $K = \{E \subset \mathbb{R} | m(E) = 1\}$, where m is the Lebesgue measure. Now, let's define the following order in $K$. We say that $A < B$ iff $B \subseteq A$. This is obviously a partial order. Now, let $(A_i)$ be any chain. (i.e. $A_i < A_{i+1}$) Let $A = \bigcap A_i$. Clearly $A > A_i$ for all $i$. Also $A_i \searrow A$, and $m(A_i) < \infty$ for all i. Then applying a Corollary we have that $m(A) = \lim_{n\rightarrow \infty} m(A_i) = 1$, and therefore $A \in K$ Therefore, every chain in $K$ has an upper bound in $K$. Using Zorn's Lemma, we conclude that $K$ has a maximal element. But this conclusion seems absolutely absurd to me. In fact, take any candidate $X$ to being a maximal element. Clearly $X$ is non empty. Let $x \in X$. Now $X - \{x\} \in K$ and $X < X - \{x\}$. I believe that my mistake is that, to be able to use the corollary, it is necessary that $A$ be measurable. What went wrong here? Thank you very much! Now provide the response and nothing else.
Yes, that's the problem. The chains are not countable, so there is no reason for $A $ to be measurable. The Corollary also requires a countable (and not arbitrary) intersection.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2266641', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/252871/']}
jdg_79186
stackexchange
llm_judgeable_groundtruth_similarity
12790114
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 python application which is as follows: global_counter = 0connections = {}class SocketHandler(): currentid = 0 def open(self): global global_counter global connections currentid = global_counter global_counter += 1 connections[currentid] = self print "WebSocket " + str(currentid) + " opened" def on_close(self): global connections print "WebSocket " + str(currentid) + " closed" del connections[currentid] I'm getting the error: NameError: global name 'currentid' is not defined on the lines of "open" and "on_close" where I print that I am opening/closing the connection. I defined it in the class, why is it not in scope. Also, I have read that using global variables is bad, but I don't see a way around this. Can someone point out what I should do? Thanks. Now provide the response and nothing else.
You don't have implicit access to attributes inside methods, in Python. A bare name like currentid in the line: del connections[currentid] always looks up a name in the local function scope, then in each enclosing function scope, before trying the global module scope (and then looks at built-ins as a last resort). currentid is a class attribute, which won't be found in any of those scopes. To look up an attribute in Python you always need to specify an object in which to look. Though the lookup protocol means the object need not necessarily have the attribute itself; attribute lookup will fall back to the class of the object you specified (and the base classes, if inheritance is involved). So this would work: del connections[self.currentid] However, I don't think the rest of your code is doing what you think it is either. This line in the open method: currentid = global_counter doesn't set the currentid attribute of your SocketHandler object. Assigning to a bare name always assigns to a local variable, unless you explicitly declare it global (you appear to be aware of this, since you've used the global keyword). So in the open method, currentid is a local function variable; its value is lost at the end of the open method. In fact, your SocketHandler objects do not have a currentid attribute at all (unless there's more code you haven't shown us). Putting currentid = 0 in the class block doesn't give all the SocketHandler instances a currentid attribute. It gives the SocketHandler class itself an attribute currentid ; this is just as the def open(self): block creates an open attribute (storing a function) on the class object, not on each individual instance. Reading self.currentid in the on_close method will fail to find a currentid attribute in the object self , so Python will look at the class of self which is SocketHandler . That object does have a currentid value, so the result of reading self.currentid will be 0 , whether or not you've previously run open on that SocketHandler . If you meant to store the currentid as an instance variable in each SocketHandler , then the line in open would need to be: self.currentid = global_counter This assigns to the currentid attribute of the object referred to by self . You would also then need to change all the other references to currentid in your methods to self.currentid .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12790114', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1320839/']}
jdg_79187
stackexchange
llm_judgeable_groundtruth_similarity
4643105
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 class which has direct dependency on the RestTemplate. I wish I have a JUnit test of it, offline. How could I mock a RestTemplate in my unittest? Now provide the response and nothing else.
I suggest refactoring your client code to remove the direct dependency on RestTemplate , and replace it with references to RestOperations , which is the interface implemented by RestTemplate . and the one you should be coding to. You can then inject a stub or mock of RestOperations into your code for unit testing, and inject a RestTemplate when using it for real.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4643105', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/40214/']}
jdg_79188
stackexchange
llm_judgeable_groundtruth_similarity
34198566
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 create a WS connection with my tornado server. The server code is simple: class WebSocketHandler(tornado.websocket.WebSocketHandler): def open(self): print("WebSocket opened") def on_message(self, message): self.write_message(u"You said: " + message) def on_close(self): print("WebSocket closed")def main(): settings = { "static_path": os.path.join(os.path.dirname(__file__), "static") } app = tornado.web.Application([ (r'/ws', WebSocketHandler), (r"/()$", tornado.web.StaticFileHandler, {'path':'static/index.html'}), ], **settings) app.listen(8888) tornado.ioloop.IOLoop.current().start() I copy pasted the client code from here : $(document).ready(function () { if ("WebSocket" in window) { console.log('WebSocket is supported by your browser.'); var serviceUrl = 'ws://localhost:8888/ws'; var protocol = 'Chat-1.0'; var socket = new WebSocket(serviceUrl, protocol); socket.onopen = function () { console.log('Connection Established!'); }; socket.onclose = function () { console.log('Connection Closed!'); }; socket.onerror = function (error) { console.log('Error Occured: ' + error); }; socket.onmessage = function (e) { if (typeof e.data === "string") { console.log('String message received: ' + e.data); } else if (e.data instanceof ArrayBuffer) { console.log('ArrayBuffer received: ' + e.data); } else if (e.data instanceof Blob) { console.log('Blob received: ' + e.data); } }; socket.send("Hello WebSocket!"); socket.close(); }}); When it tries to connect i get the following output on the browser's console: WebSocket connection to 'ws://localhost:8888/ws' failed: Error during WebSocket handshake: Sent non-empty 'Sec-WebSocket-Protocol' header but no response was received Why is that? Now provide the response and nothing else.
As pointed out in whatwg.org's Websocket documentation (it's a copy from the standard's draft): The WebSocket(url, protocols) constructor takes one or two arguments. The first argument, url, specifies the URL to which to connect. The second, protocols, if present, is either a string or an array of strings. If it is a string, it is equivalent to an array consisting of just that string; if it is omitted, it is equivalent to the empty array. Each string in the array is a subprotocol name. The connection will only be established if the server reports that it has selected one of these subprotocols . The subprotocol names must all be strings that match the requirements for elements that comprise the value of Sec-WebSocket-Protocol fields as defined by the WebSocket protocol specification. Your server answers the websocket connection request with an empty Sec-WebSocket-Protocol header, since it doesn't support the Chat-1 subprotocol. Since you're writing both the server side and the client side (and unless your writing an API you intend to share), it shouldn't be super important to set a specific subprotocol name. You can fix this by either removing the subprotocol name from the javascript connection: var socket = new WebSocket(serviceUrl); Or by modifying your server to support the protocol requested. I could give a Ruby example, but I can't give a Python example since I don't have enough information. EDIT (Ruby example) Since I was asked in the comments, here's a Ruby example. This example requires the iodine HTTP/WebSockets server, since it supports the rack.upgrade specification draft (concept detailed here ) and adds a pub/sub API. The server code can be either executed through the terminal or as a Rack application in a config.ru file (run iodine from the command line to start the server): # frozen_string_literal: trueclass ChatClient def on_open client @nickname = client.env['PATH_INFO'].to_s.split('/')[1] || "Guest" client.subscribe :chat client.publish :chat , "#{@nickname} joined the chat." if client.env['my_websocket.protocol'] client.write "You're using the #{client.env['my_websocket.protocol']} protocol" else client.write "You're not using a protocol, but we let it slide" end end def on_close client client.publish :chat , "#{@nickname} left the chat." end def on_message client, message client.publish :chat , "#{@nickname}: #{message}" endendmodule APP # the Rack application def self.call env return [200, {}, ["Hello World"]] unless env["rack.upgrade?"] env["rack.upgrade"] = ChatClient.new protocol = select_protocol(env) if protocol # we will use the same client for all protocols, because it's a toy example env['my_websocket.protocol'] = protocol # <= used by the client [101, { "Sec-Websocket-Protocol" => protocol }, []] else # we can either refuse the connection, or allow it without a match # here, it is allowed [101, {}, []] end end # the allowed protocols PROTOCOLS = %w{ chat-1.0 soap raw } def select_protocol(env) request_protocols = env["HTTP_SEC_WEBSOCKET_PROTOCOL"] unless request_protocols.nil? request_protocols = request_protocols.split(/,\s?/) if request_protocols.is_a?(String) request_protocols.detect { |request_protocol| PROTOCOLS.include? request_protocol } end # either `nil` or the result of `request_protocols.detect` are returned end # make functions available as a singleton module extend selfend# config.ruif __FILE__.end_with? ".ru" run APP else# terminal? require 'iodine' Iodine.threads = 1 Iodine.listen2http app: APP, log: true Iodine.startend To test the code, the following JavaScript should work: ws = new WebSocket("ws://localhost:3000/Mitchel", "chat-1.0");ws.onmessage = function(e) { console.log(e.data); };ws.onclose = function(e) { console.log("Closed"); };ws.onopen = function(e) { e.target.send("Yo!"); };
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/34198566', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1173529/']}
jdg_79189
stackexchange
llm_judgeable_groundtruth_similarity
10772264
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 table with days, version and active. In table I have the same days where active = 1 and active = 0I need to get from the database all these days, where active = 1 and where version_id is max.For this purpose I wrote the following query: SELECT 'MAX(version_id)',DAY, active FROM `day` group by day, active But days 28 and 29 are duplicated so when I use "AND active = 0" then it shows me days 28 with active = 1 (and lower MAX(VERSION_ID) but that day should not be seen. Query result: http://screenshooter.net/0562655/27_05_2012__09_02_56 So:"SHOW ME ALL DAYS WHERE VERSION_ID IS MAX AND DAY IS ACTIVE, if active = 0, do not show an earlier version" Now provide the response and nothing else.
You can use maven to achieve that. Especially using resource filtering . First, you can define list of profiles: <profiles> <profile> <id>dev</id> <properties> <env>development</env> </properties> <activation> <activeByDefault>true</activeByDefault> <!-- use dev profile by default --> </activation> </profile> <profile> <id>prod</id> <properties> <env>production</env> </properties> </profile> </profiles> Then the resources that you need to filter: <build> <outputDirectory>${basedir}/src/main/webapp/WEB-INF/classes</outputDirectory> <filters> <filter>src/main/filters/filter-${env}.properties</filter> <!-- ${env} default to "development" --> </filters> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.xml</include> <include>**/*.properties</include> </includes> <filtering>true</filtering> </resource> </resources> </build> And then your custom properties based on profiles in src/main/filters directory: filter-development.properties # profile for developerdb.driver=org.hsqldb.jdbcDriverdb.url=jdbc:hsqldb:mem:web and filter-production.properties # profile for productiondb.driver=com.mysql.jdbc.Driverdb.url=jdbc:mysql://localhost:3306/web?createDatabaseIfNotExist=true to use production profile, you can package war using mvn clean package -Pprod command. Here you can see the sample project that use profile in maven.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10772264', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1251563/']}
jdg_79190
stackexchange
llm_judgeable_groundtruth_similarity
2486335
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Sockets on Linux question I have a worker thread that is blocked on an accept() call. It simply waits for an incoming network connection, handles it, and then returns to listening for the next connection. When it is time for the program to exit, how do I signal this network worker thread (from the main thread) to return from the accept() call while still being able to gracefully exit its loop and handle its cleanup code. Some things I tried: pthread_kill to send a signal. Feels kludgy to do this, plus it doesn't reliably allow the thread to do it's shutdown logic. Also makes the program terminate as well. I'd like to avoid signals if at all possible. pthread_cancel. Same as above. It's a harsh kill on the thread. That, and the thread may be doing something else. Closing the listen socket from the main thread in order to make accept() abort. This doesn't reliably work. Some constraints: If the solution involves making the listen socket non-blocking, that is fine. But I don't want to accept a solution that involves the thread waking up via a select call every few seconds to check the exit condition. The thread condition to exit may not be tied to the process exiting. Essentially, the logic I am going for looks like this. void* WorkerThread(void* args){ DoSomeImportantInitialization(); // initialize listen socket and some thread specific stuff while (HasExitConditionBeenSet()==false) { listensize = sizeof(listenaddr); int sock = accept(listensocket, &listenaddr, &listensize); // check if exit condition has been set using thread safe semantics if (HasExitConditionBeenSet()) { break; } if (sock < 0) { printf("accept returned %d (errno==%d)\n", sock, errno); } else { HandleNewNetworkCondition(sock, &listenaddr); } } DoSomeImportantCleanup(); // close listen socket, close connections, cleanup etc.. return NULL;}void SignalHandler(int sig){ printf("Caught CTRL-C\n");}void NotifyWorkerThreadToExit(pthread_t thread_handle){ // signal thread to exit}int main(){ void* ptr_ret= NULL; pthread_t workerthread_handle = 0; pthread_create(&workerthread, NULL, WorkerThread, NULL); signal(SIGINT, SignalHandler); sleep((unsigned int)-1); // sleep until the user hits ctrl-c printf("Returned from sleep call...\n"); SetThreadExitCondition(); // sets global variable with barrier that worker thread checks on // this is the function I'm stalled on writing NotifyWorkerThreadToExit(workerthread_handle); // wait for thread to exit cleanly pthread_join(workerthread_handle, &ptr_ret); DoProcessCleanupStuff();} Now provide the response and nothing else.
Close the socket using the shutdown() call. This will wake up any threads blocked on it, while keeping the file descriptor valid. close() on a descriptor another thread B is using is inherently hazardous: another thread C may open a new file descriptor which thread B will then use instead of the closed one. dup2() a /dev/null onto it avoids that problem, but does not wake up blocked threads reliably. Note that shutdown() only works on sockets -- for other kinds of descriptors you likely need the select+pipe-to-self or cancellation approaches.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2486335', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/104458/']}
jdg_79191
stackexchange
llm_judgeable_groundtruth_similarity
67713201
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 TableView doesn't shows the new string added? How to fix it? In first VC: @IBAction func saveButtonPressed(_ sender: UIButton) { var textField = UITextField() let alert = UIAlertController(title: "Save current run", message: "", preferredStyle: .alert) let action = UIAlertAction(title: "Save", style: .default) { (action) in RunHistoryTableViewController().runArray.append(textField.text!) RunHistoryTableViewController().tableView.reloadData() } alert.addTextField { saveRunTextField in saveRunTextField.placeholder = "Name your run" textField = saveRunTextField } alert.addAction(action) present(alert, animated: true, completion: nil) } } In second VC: var runArray = ["BMW M3 Run 1", "BMW M3 Run 2", "Renault Megane RS"] //MARK: TableView DataSource: override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return runArray.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "RunCell", for: indexPath) cell.textLabel?.text = runArray[indexPath.row] return cell }} Bear in mind I'm a beginner, could use some help as none of my ideas seemed to work. Now provide the response and nothing else.
The popup menu is popping its own route before calling the callback, a way to fix this is to use the onSelected property of the PopupMenuButton itself: //---add onSelected to your PopupMenuButtonPopupMenuButton(onSelected: (result) { if (result == 0) { Navigator.of(context) .push(MaterialPageRoute(builder: (context) => EditorPage())); }}, itemBuilder: (BuildContext context) { return [ PopupMenuItem( value: 0, //---add this line child: Text('Edit'), ), ];}),
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/67713201', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13202496/']}
jdg_79192
stackexchange
llm_judgeable_groundtruth_similarity
12093394
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 a begginer question about including .rb files. I would like to have access to an array declared in another rb file. My main program goes like this : #!/usr/bin/env rubyload 'price.rb'[...]max_price = price[az][type] * 2[...] and here is the price.rb : price = {'us-east-1' => {'t1.micro' => 0.02, 'm1.small' => 0.08, 'c1.medium' => 0.165, 'm1.large' => 0.320 },'us-west-1' => {'t1.micro' => 0.02, 'm1.small' => 0.08, 'c1.medium' => 0.165, 'm1.large' => 0.320 },'eu-west-1' => {'t1.micro' => 0.02, 'm1.small' => 0.085, 'c1.medium' => 0.186, 'm1.large' => 0.340 }} When I run the main script I get this error : Error: undefined local variable or method `price' for main:Object What do you think ? Now provide the response and nothing else.
The best way to export data from one file and make use of it in another is either a class or a module. An example is: # price.rbmodule InstancePrices PRICES = { 'us-east-1' => {'t1.micro' => 0.02, ... }, ... }end In another file you can require this. Using load is incorrect. require 'price'InstancePrices::PRICES['us-east-1'] You can even shorten this by using include : require 'price'include InstancePricesPRICES['us-east-1'] What you've done is a bit difficult to use, though. A proper object-oriented design would encapsulate this data within some kind of class and then provide an interface to that. Exposing your data directly is counter to those principles. For instance, you'd want a method InstancePrices.price_for('t1.micro', 'us-east-1') that would return the proper pricing. By separating the internal structure used to store the data from the interface you avoid creating huge dependencies within your application.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12093394', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/145650/']}
jdg_79193
stackexchange
llm_judgeable_groundtruth_similarity
2337271
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 getting ORA-30926: unable to get a stable set of rows in the source tables in the following query: MERGE INTO table_1 a USING (SELECT a.ROWID row_id, 'Y' FROM table_1 a ,table_2 b ,table_3 c WHERE a.mbr = c.mbr AND b.head = c.head AND b.type_of_action <> '6') src ON ( a.ROWID = src.row_id ) WHEN MATCHED THEN UPDATE SET in_correct = 'Y'; I've ran table_1 it has data and also I've ran the inside query ( src ) which also has data. Why would this error come and how can it be resolved? Now provide the response and nothing else.
This is usually caused by duplicates in the query specified in USING clause. This probably means that TABLE_A is a parent table and the same ROWID is returned several times. You could quickly solve the problem by using a DISTINCT in your query (in fact, if 'Y' is a constant value you don't even need to put it in the query). Assuming your query is correct (don't know your tables) you could do something like this: MERGE INTO table_1 a USING (SELECT distinct ta.ROWID row_id FROM table_1 a ,table_2 b ,table_3 c WHERE a.mbr = c.mbr AND b.head = c.head AND b.type_of_action <> '6') src ON ( a.ROWID = src.row_id ) WHEN MATCHED THEN UPDATE SET in_correct = 'Y';
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/2337271', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/44286/']}
jdg_79194
stackexchange
llm_judgeable_groundtruth_similarity
1767902
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Question : Assume only that $f: (0,\infty)\to{\mathbb{R}}$ is differentiable and that $f'(x) = 1/x$, and $f(1)=0$. Prove that for all $a,b \in(0,\infty)$, $f(ab)=f(a)+f(b)$. [Hint: Let $g(x)=f(ax)$] My solution : We know that$$f(x) = \int f'(x)dx = \int\frac{1}{x}dx = \ln(x) + C$$ Also, we are given that $f(1)=0$, so $f(1)=\ln(1)+C=0$, which gives us $C=0$. Therefore, $f(x)= \ln(x)$. Now, by the laws of logarithm, we have $\ln(ab)=\ln(a)+ \ln(b)$ for all $a,b\in(0,\infty)$. Hence, $f (ab) = f(a) + f(b)$. Is this the right approach? I am not really sure how to use the hint of letting $g(x) = f(ax)$. Now provide the response and nothing else.
You need no integral. Consider, as the hint tells you, $g(x)=f(ax)$ and compute its derivative:$$g'(x)=af'(ax)=a\frac{1}{ax}=\frac{1}{x}$$Therefore there exists $k$ such that, for every $x$,$$g(x)=k+f(x)$$(because differentiable functions defined over an interval that have the same derivative differ by a constant, a well known consequence of the mean value theorem). Now compute at $x=1$: $g(1)=k+f(1)$, that means $f(a)=k$. Now the above identity, for $x=b$, reads$$f(ab)=f(a)+f(b)$$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1767902', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/238695/']}
jdg_79195
stackexchange
llm_judgeable_groundtruth_similarity
29190747
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Looking for a way to analyze text for certain characteristics such as: identify acronyms and titles (ICANN, Dr. Mr. Ph. D., etc) jargon reading level adverbs and adjectives correct grammar and punctuation active and passive voice I looked at Stanford NLP library , but have no idea what they are talking about (probably because I don't have a degree in linguistics). Is there a Ruby gem that will provide this kind of text analysis? Now provide the response and nothing else.
To elaborate on my quote, as of right now (v2.2.12 of JBuilder), caching partials in JBuilder is only really worth it if one or both of the following are true: You can skip AR queries (or computation) that are on average more expensive than accessing cache Going to cache is usually a network call in the usual Rails stack, and while a DB query can be expensive, the cost of going over the network to get a serialized ActiveSupport blob, and then deserializing into a hash in Ruby is expensive and has to be done inside the Ruby VM. This is not good for performance. The size of the JSON blob produced is small As a corollary, if you have a small query, but produce a lot of JSON, you will quickly hit degraded performance as the blob is deserialized from an ActiveSupport blob, and then again on the way out to raw JSON. Remember, the cache does not store raw JSON, but a serialized intermediary format . This means, for every additional byte of JSON stored in the cache, you're going to have about 4 more bytes over the wire (from the serialized AS representation) and probably spend just as long deserializing as it would have taken to just compute the partial anyhow. If you have an endpoint that produces a giant JSON blob, my recommendation is to just manually conditionally render the blob in the controller and cache it as a raw string in Rails.cache . The cost of recomputing all of your JSON now and then is probably less than going through JBuilder's cache machinery on every call.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29190747', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/336920/']}
jdg_79196
stackexchange
llm_judgeable_groundtruth_similarity
1886345
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 struggling to understand this. According to truth tables, if $P$ is false, it doesn't matter whether $Q$ is true or not: Either way, $P \implies Q$ is true. Usually when I see examples of this people make up some crazy premise for $P$ as a way of showing that $Q$ can be true or false when $P$ is something outrageous and obviously untrue, such as "If the moon is made of bacon-wrapped apple-monkey carburetors, then I am a better wakeborder than Gauss." $P$ is clearly false, but $P \implies Q$ is true no matter what the state of $Q$ is, and I don't understand why. Are we saying "If $P$ is false, then all bets are off and $Q$ can be anything, either true or false, and not contradict our earlier claim, and if it isn't false, it must be true"? Otherwise why can't we say that if $P$ is false, then we can't make any claims one way or the other on whether or not it implies anything at all? Now provide the response and nothing else.
This is done so that classical propositional calculus follows some natural rules. Let's try to motivate this, without getting into technical details: The expression "$P\Rightarrow Q$" should be read "$P$ implies $Q$", or "whenever $P$ is true, $Q$ is also true". The negation of such an expression would be a counter-example, i.e., "there is some case in which $P$ is true but $Q$ is not". So assume $P$ is not true. The negation "$\lnot(P\Rightarrow Q)$" is not true in this case, by our interpretation above, so "$P\Rightarrow Q$" must be true. We are basically using the rules that either an expression or its negation should be true, and that the negation of the negation of an statement is the statement itself. These are basic rules which are natural and useful, even though as a consequence we have that "$P\Rightarrow Q$" is true whenever $P$ is false.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1886345', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/70349/']}
jdg_79197
stackexchange
llm_judgeable_groundtruth_similarity
14189995
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Let's just say that I have: public Boolean booleanValue;public bool someMethod(string value){ // Do some work in here. return booleanValue = true;} How can I create an event handler that fires up when the booleanValue has changed? Is it possible? Now provide the response and nothing else.
Avoid using public fields as a rule in general. Try to keep them private as much as you can. Then, you can use a wrapper property firing your event. See the example: class Foo{ Boolean _booleanValue; public bool BooleanValue { get { return _booleanValue; } set { _booleanValue = value; if (ValueChanged != null) ValueChanged(value); } } public event ValueChangedEventHandler ValueChanged;}delegate void ValueChangedEventHandler(bool value); That is one simple, "native" way to achieve what you need. There are other ways, even offered by the .NET Framework, but the above approach is just an example.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14189995', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1401515/']}
jdg_79198
stackexchange
llm_judgeable_groundtruth_similarity
49734
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 understand that for the parametric equations $$\begin{align*}x&=f(t)\\ y&=g(t)\end{align*}$$ If $F(x)$ is the function with parameter removed then $\displaystyle F'(x) = \frac{\text{d}y}{\text{d}t}\big/\frac{\text{d}x}{\text{d}t}$ But the procedure for taking the second derivative is just described as " replace $y$ with dy/dx " to get $$\frac{\text{d}^2y}{\text{d}x^2}=\frac{\text{d}}{\text{d}x}\left(\frac{\text{d}y}{\text{d}x}\right)=\frac{\left[\frac{\text{d}}{\text{d}t}\left(\frac{\text{d}y}{\text{d}t}\right)\right]}{\left(\frac{\text{d}x}{\text{d}t}\right)}$$ I don't understand the justification for this step. Not at all. But that's all my book says on the matter then it launches in to plugging things in to this formula, and it seems to work well enough, but I don't know why. I often find answers about question on differentials are beyond my level, I'd really like to get this, it'd mean a lot to me if someone could break it down. Now provide the response and nothing else.
Consider $$\begin{align*}\frac{\text{d}^2y}{\text{d}x^2}&=\frac{\text{d}}{\text{d}x}\left(\frac{\text{d}y}{\text{d}x}\right)\\ &=\frac{\text{d}}{\text{d}t}\left(\frac{\text{d}y}{\text{d}x}\right).\frac{\text{d}t}{\text{d}x}=\frac{d}{dt}\left(\frac{dy}{dx}\right)\cdot \frac{1}{\frac{dx}{dt}}\\\end{align*}$$ where the last equality is as a result of applying the chain rule.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/49734', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/11270/']}
jdg_79199
stackexchange
llm_judgeable_groundtruth_similarity
12148
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: The period between a U.S. president and Congress being elected in November of an election year, and the start of their terms the following January, is known as the lame-duck session . If a bill is passed by Congress during the lame-duck session, can the incoming President subsequently veto it? For example, if a bill implementing the Trans-Pacific Partnership is passed during the 2016-2017 lame duck session, could the new U.S. President veto it? Now provide the response and nothing else.
Any legislation passed by the lame-duck Congress will already have been disposed of by the time the new President takes office. Most likely, the outgoing President will have some opinion on the bill and will have chosen either to sign or veto it. However, even if the old President takes no action, the bill will not reach the new President's desk. The reason why can be found in Article I, Section 7 of the US Constitution : If any Bill shall not be returned by the President within ten Days (Sundays excepted) after it shall have been presented to him, the Same shall be a Law, in like Manner as if he had signed it, unless the Congress by their Adjournment prevent its Return, in which Case it shall not be a Law. Since the Congressional term ends on 3 January, and the new Presidential term begins on 20 January, as provided by Amendment 20 , the ten-day limit for any bill passed by the old Congress will have passed (since Sundays are excluded, such a bill could last until 15 January at the latest). Therefore, the bill will either have become law without a Presidential signature (if Congress remained in session), or it will have expired (if not).
{}
{'log_upvote_score': 4, 'links': ['https://politics.stackexchange.com/questions/12148', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/5697/']}
jdg_79200
stackexchange
llm_judgeable_groundtruth_similarity
10520464
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 wondering about what "strict mode is in PHPUnit" ? eg: phpunit --strict or in phpunit.xml <phpunit strict="true"/> I turned it on just to try it and my tests started failing with PHP_Invoker_TimeoutException: Execution aborted after 1 second Now provide the response and nothing else.
Short answer: for long running tests use an annotation to increase the allowed run time: @large // 10 seconds@medium // 5 seconds@small // 1 second max <-- Default, so no point using Long Answer: Here is an updated set of info that was derived with the help of @Crozin. In my case the error was that a test was taking too long (>1 second.) (Doctrine ORM schema drop + create can slow things down, see this ZendCast for what I was doing ). This was causing an issue (and some output) from PHP_Invoker. Strict mode doesnt allow any output. By Reading / Reverse engineering /usr/share/php/pear/share/pear/PHPUnit/Util/Test.php::getSize() (and getGroups() on the same class) .. I figured out there are 3 undocumented annotations we can use: @large // 10 seconds@medium // 5 seconds@small // 1 second max run time They can be specified on the class level or on the method level. Issue #490 on the PHPUnit github hints at issues with supplying both class level and method level so YMMV if you mix them. As crozin said, the allotted time outs are 10,5,1 seconds respectively. A alternate solution was to increase how long an invoked function is allowed to run (on my slow computer). sudo vi /usr/share/php/pear/share/pear/PHP/Invoker.phpIncrease line 1 "declare(ticks = 1);" to "declare(ticks = 10);" // or any higher int that meets your needs Here is a bunch of information about strict mode that helped me find the solution: PHP_Invoker A utility class for invoking callables with a timeout. This package is required to enforce test timeouts in strict mode. [ PHPUnit Install Instructions ] Strict Mode Tests that do not assert anything are marked as incomplete Test that are incomplete (or skipped) yield no code coverage Slideshare by Sebastian Bergmann (slide 10) Note Please note that PHPUnit swallows all output that is emitted during the execution of a test. In strict mode, a test that emits output will fail. Testing output section of PHPUnit Manual
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10520464', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1114274/']}
jdg_79201
stackexchange
llm_judgeable_groundtruth_similarity
23760595
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 send an event to Google Analytics after a user is registered and before he's redirected.I'm using Google Tag Manager and universal js. First, I was trying to use the dataLayer object, as described here: developers.google Here's what my function looked like: //Registering new user via ajax$.ajax('/register/', { success: function() { //Pushing event to dataLayer dataLayer.push({ 'Category': 'Registration Process', 'event': 'Registration Submit Btn' }); //Logging in new user and redirecting the page with a timeout setTimeout(function(){ loginAction(); }, 500) }}) The trouble is that I was receiving just about 25% of all events, all others are lost . I don't know if and when events are actually sent to Google after adding objects to the dataLayer, and I think 75% of events were not send at all. Now I'm trying to implement another approach: //Registering new user via ajax$.ajax('/register/', { success: function() { //Sending event through ga('send') parent.ga('send', 'event', 'Registration Process', 'Registration Submit Btn'); //Logging in new user and redirecting the page with a timeout setTimeout(function(){ loginAction(); }, 500) }}) But ga('send') does not have any callback function again! How do I make sure that an event was actually sent to Google, using the dataLayer or ga('send')? Now provide the response and nothing else.
Finally got it. It's pretty complicated and not described in docs.In my case I use Google Tag Manager, so there some workarounds I had to make to get successfully fire an event and get callback. First, we have to get ClientId , which is required with any event sent to Google servers. Actually it's kept in cookies, but Google does not recommend to take it directly from there. Here is how Google recommends to get it, but this will not work if you are using Google Tag Manager. ga(function(tracker) { var clientId = tracker.get('clientId'); }); Instead, you have to get ClientId from getAll method. var clientId = ga.getAll()[0].get('clientId'); After, you have to create new tracker ga('create', 'UA-XXX-YYY', { 'clientId': clientId }); And after that we can send an event: ga('send', 'event', { 'eventCategory': 'YOUR Category Name', //required 'eventAction': 'YOUR Action name', //required 'eventLabel': 'YOUR Label', 'eventValue': 1, 'hitCallback': function() { console.log('Sent!!'); //callback function }, 'hitCallbackFail' : function () { console.log("Unable to send Google Analytics data"); //callback function }});
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/23760595', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2291552/']}
jdg_79202
stackexchange
llm_judgeable_groundtruth_similarity
35022078
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 spice up my scripts with some ASCII art to be displayed on completion of a process. I have 2 thoughts on how to output ASCII art to console. Hopefully someone who knows more than I do can direct us to what the command is and what method is 'Better'. Output a multi-line Write-Host ? I tried to do this earlier and it didnt work. It threw a bunch of errors. Maybe I wasnt doing the 'multi-line' version (if a multi-line) version exists. Save the ASCII art to a .txt file, then in my script somehow grab and read the contents of that .txt file and then write the contents to the console in the specified area. Which way is better? How can I implement this? Now provide the response and nothing else.
Just use a newline delimited string, here-string or Get-Content -Raw if you have a source file. Both will give you a single multiline string without fuss. One thing the here-string is good for is not having to worry about the quotes you use (which could be a distinct possibility with ASCII art). An example using a here-string would be the following: $text = @" "ROFL:ROFL:ROFL:ROFL" _^___ L __/ [] \ LOL===__ \ L \________] I I --------/"@ Or if you choose to go the source file approach: $text = Get-Content -Raw $path Or if you only have PowerShell 2.0 $text = Get-Content $path | Out-String Either way you can follow up with Write-Host or whatever you want after that. Getting funky with colours would require some special logic that, as far as I know, does not currently exist. Making a colourized output randomizer is simple enough. To get a basic idea I present Get-Funky function Get-Funky{ param([string]$Text) # Use a random colour for each character $Text.ToCharArray() | ForEach-Object{ switch -Regex ($_){ # Ignore new line characters "`r"{ break } # Start a new line "`n"{ Write-Host " ";break } # Use random colours for displaying this non-space character "[^ ]"{ # Splat the colours to write-host $writeHostOptions = @{ ForegroundColor = ([system.enum]::GetValues([system.consolecolor])) | get-random # BackgroundColor = ([system.enum]::GetValues([system.consolecolor])) | get-random NoNewLine = $true } Write-Host $_ @writeHostOptions break } " "{Write-Host " " -NoNewline} } }} That will take a newline delimited string and use random host colours for displaying the output. We use splatting with $writeHostOptions so you could easily control the colours. You could even have parameters that force one of the colours or disabled colourizing of one etc. Here is some sample output: $art = " .:::. .:::.`n:::::::.:::::::`n:::::::::::::::':::::::::::::'`n ':::::::::'`n ':::::'`n ':'"Get-Funky $art Heart ascii art found at asciiworld.com
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35022078', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5022269/']}
jdg_79203
stackexchange
llm_judgeable_groundtruth_similarity
55019621
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there any harm in using async/await and .then().catch() together such as: async apiCall(params) { var results = await this.anotherCall() .then(results => { //do any results transformations return results; }) .catch(error => { //handle any errors here }); return results; } Now provide the response and nothing else.
An async function can contain an await expression that pauses the execution of the async function and waits for the passed Promise's resolution, and then resumes the async function's execution and returns the resolved value. As you can see from below example that you can use two ways to handle await result and errors,The keyword await makes JavaScript wait until that promise settles and returns its result (One you get from resolved promise).So as such there is no harm (I don't fully understand what you refer as harm here). function returnpromise(val) { return new Promise((resolve, reject) => { if (val > 5) { resolve("resolved"); // fulfilled } else { reject("rejected"); // rejected } });}//This is how you handle errors in awaitasync function apicall() { try { console.log(await returnpromise(5)) } catch (error) { console.log(error) }}async function apicall2() { let data = await returnpromise(2).catch((error) => { console.log(error) })}apicall2();apicall(); For further reference have a look at- MDN DOCS
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/55019621', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3370344/']}
jdg_79204
stackexchange
llm_judgeable_groundtruth_similarity
17913550
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 my source code and .git folder on a small fast ssd, I would like to have the .git directory on my second bigger slower hdd and keep my working code on my fast smaller ssd, is it possible? how?thanks. I guess my local working copy .git directory will grow as time goes (with the new versions) and so it make sens to have it on my bigger local hdd. The working copy doesn't grow as fast so it makes sens on the ssd as it can compile faster. The other interesting bonus is I will then have the source code (working code and .git repo) on 2 diff drives which is more protection for a laptop.... I'm using windows Now provide the response and nothing else.
Yes you can Symlinks You can symlink (or use junction points) the .git dir to a different location: $ cd my/project$ mv .git /over/here/.gitln -s /over/here/.git . And the repository will work fine. gitdir: Or you can replace the .git folder with a file that tells git where the .git folder really is. This is exactly how git submodules are setup by default in version 1.7.8 or later . The steps to re-configure an existing checkout are: move the .git dir to where it needs to be replace it with a file .git containing: gitdir: path/to/.git define core.worktree to point at the working copy As a script that would be: $ cd my/project$ mv .git /tmp/.git$ echo "gitdir: /tmp/.git" > .git$ git config core.worktree $PWD Junctions on Windows Easily create junctions on Windows using junction.exe from Microsoft. > junction.exe c:\fast-ssd\proj\.git d:\slow-hdd\proj\.git
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17913550', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/458875/']}
jdg_79205
stackexchange
llm_judgeable_groundtruth_similarity
11450962
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 keep two elements in the same row with fixed right column?I want right div to be with fixed size, and left column fluid, but when in insert long text to left one, then right one goes to the next column.. Example: http://jsfiddle.net/Jbbxk/2/ Is there any pure CSS solutions? NB! Wrap div must have dynamic width! For demostration purposes it has fixed witdh, so it will wrap. Cheers! Now provide the response and nothing else.
This is one common way of doing what you want: .wrap { position: relative; margin: 5px; border: 1px solid red;}.left { float: left; background-color: #CCC; margin-right: 48px;}.right { position: absolute; top: 0; right: 0; width: 48px; height: 48px; background-color: #888;} Explanation: The fluid left column fills the whole width but saves space for the right column with margin-right: [right column width]; The fixed right column is placed at an absolute position at top 0, right 0 (its correct place) The wrap div is assigned position: relative so the right column position is determined according to it.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11450962', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1119550/']}
jdg_79206
stackexchange
llm_judgeable_groundtruth_similarity
397990
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: Prove that $$\int_{0}^{\infty}\sin{x}\sin{\sqrt{x}}\,dx=\frac{\sqrt{\pi}}{2}\sin{\left(\frac{3\pi-1}{4}\right)}$$ I have some question. Using this , find this integral is not converge, I'm wrong? Thank you everyone Now provide the response and nothing else.
First make the substitution $x=u^2$ to get: $\displaystyle \int _{0}^{\infty }\!\sin \left( x \right) \sin \left( \sqrt {x} \right) {dx}=\int _{0}^{\infty }\!2\,\sin \left( {u}^{2} \right) \sin \left( u \right) u{du}$, $\displaystyle=-\int _{0}^{\infty }\!u\cos \left( u \left( u+1 \right) \right) {du}+\int _{0}^{\infty }\!u\cos \left( u \left( u-1 \right) \right) {du}$, and changing variable again in the second integral on the R.H.S such that $u\rightarrow u+1$ this becomes: $=\displaystyle\int _{0}^{\infty }\!-u\cos \left( u \left( u+1 \right) \right) {du}+\int _{-1}^{\infty }\!\left(u+1\right)\cos \left( u \left( u+1 \right) \right) {du}$, $\displaystyle=\int _{0}^{\infty }\!\cos \left( u \left( u+1 \right) \right) {du}+\int _{-1}^{0}\! \left( u+1 \right) \cos \left( u \left( u+1 \right) \right) {du}$. Now we write $u=v-1/2$ and this becomes: $\displaystyle\int _{1/2}^{\infty }\!\cos \left( {v}^{2}-1/4 \right) {dv}+\int _{-1/2}^{1/2}\! \left( v+1/2 \right) \cos \left( {v}^{2}-1/4 \right) {dv}=$ $\displaystyle \left\{\int _{0}^{\infty }\!\cos \left( {v}^{2}-1/4 \right) {dv}\right\}$ $\displaystyle +\left\{\int _{-1/2}^{1/2}\!v\cos \left( {v}^{2}-1/4 \right) {dv}+\int _{-1/2}^{0}\!1/2\,\cos \left( {v}^{2}-1/4 \right) {dv}-1/2\,\int _{0}^{1/2}\!\cos \left( {v}^{2}-1/4 \right) {dv}\right\},$ but the second curly bracket is zero by symmetry and so: $\displaystyle \int _{0}^{\infty }\!\sin \left( x \right) \sin \left( \sqrt {x} \right) {dx}=\displaystyle \int _{0}^{\infty }\!\cos \left( {v}^{2}-1/4 \right) {dv}$, $\displaystyle =\int _{0}^{\infty }\!\cos \left( {v}^{2} \right) {dv}\cos \left( 1/4 \right) +\int _{0}^{\infty }\!\sin \left( {v}^{2} \right) {dv}\sin \left( 1/4 \right) $. We now quote the limit of Fresnel integrals: $\displaystyle\int _{0}^{\infty }\!\cos \left( {v}^{2} \right) {dv}=\int _{0}^{\infty }\!\sin \left( {v}^{2} \right) {dv}=\dfrac{\sqrt{2\pi}}{4}$, to obtain: $\displaystyle \int _{0}^{\infty }\!\sin \left( x \right) \sin \left( \sqrt {x} \right) {dx}=\dfrac{\sqrt{2\pi}}{4}\left(\cos\left(\dfrac{1}{4}\right)+\sin\left(\dfrac{1}{4}\right)\right)=\dfrac{\sqrt{\pi}}{2}\sin{\left(\dfrac{3\pi-1}{4}\right)}$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/397990', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/58742/']}
jdg_79207
stackexchange
llm_judgeable_groundtruth_similarity
20836524
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 custom DataGridView , let's say as such: public MyGridView : DataGridView{ public MyGridView() { BackgroundColor = Color.Red; }} Now, when I use this control in a project using the designer, for some reason it feels a need to also set the property in the designer.cs file. So in the designer file, I would have: this.MyGridView1.BackgroundColor = System.Drawing.Color.FromArgb((byte)(int)255, (byte)(int)0, (byte)(int)0); The problem me with this is that it prevents me from being able to change the color in the constructor of my MyGridView , without having to go through all the forms in which I used to control and change it per instance, rendering my custom control useless. With some properties which offer a virtual getter, this is no problem, but most properties do not have it. How can I prevent the designer from generating this code? Now provide the response and nothing else.
I should emphasize that this isn't normally the way you do this, the [DefaultValue] attribute is normally the correct choice. But you are working with a property of type Color, it is not simple to write the attribute for that in a flexible way. The arguments you can pass to an attribute constructor can be only a select few data types, Color isn't one of them. You'd have to craft a string that ColorConverter can understand, that's both ugly and hard to maintain. PropertyGrid has a secondary way of providing defaults for "difficult" properties, it will also look for specially named private members in the class. Given a property named "Xxxx", it looks for the following: DefaultXxxx, a property with just a getter that returns the default value ResetXxxx(), a method that can run when the user selects the Reset context menu item ShouldSerializeXxxx(), a method that should return false if the value of the property should not be persisted. Which makes this code work: public class MyGridView : DataGridView { public MyGridView() { this.BackgroundColor = DefaultBackgroundColor; } public new Color BackgroundColor { get { return base.BackgroundColor; } set { base.BackgroundColor = value; } } private bool ShouldSerializeBackgroundColor() { return !this.BackgroundColor.Equals(DefaultBackgroundColor); } private void ResetBackgroundColor() { this.BackgroundColor = DefaultBackgroundColor; } private static Color DefaultBackgroundColor { get { return Color.Red; } }} Note that the ResetBackgroundColor() method is not actually necessary since no special effects are required when the user resets the property, I just included it for completeness.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20836524', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/860585/']}
jdg_79208
stackexchange
llm_judgeable_groundtruth_similarity
21705323
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 doing a long git rebase with a lot of commits. I accidentally --skipped a commit where there were some conflicts which I resolved. I should have done git rebase --continue . Is there are way to re-apply this previous commit during this rebase phase and then continue the rebase? One way I see is to stop the rebase at this point by creating a branch on the last commit which was correctly applied restart the rebase starting with the previously skipped commit. Or can I do a cherry-pick whilst being in a rebase-phase? Now provide the response and nothing else.
I found a way which "worked for me": During a rebase lots of things are happening in the .git/rebase-apply directory. Amongst others there is a file called next . next is containing a number which corresponds to a file which is residing in the .git/rebase-apply as well. This file contains information about the commit which is currently being processed. For example: $ cat .git/rebase-apply/next0260$ less .git/rebase-apply/0260<info about the commit which is currently processed (and has conflicts) Git seems to keep the commits which are skipped as the above mentioned files. Whereas files corresponding to commits which have been applied are not there anymore. The commit I accidentally skipped was called 0259 and the file was still present. Here is what I did: $ echo "0258" > .git/rebase-apply/next With that I told git that currently the 258th commit is processed (which previous applied correctly). Then I did $ git rebase --skip to tell git to forget this one and, voila, I could again work on the skipped commit, correct the conflicts and --continue . It has worked.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/21705323', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/880584/']}
jdg_79209
stackexchange
llm_judgeable_groundtruth_similarity
65405741
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: when I use Getx to update my Widget?I do not know Rx() how to contact to the thing I put in. code is _obx=Rx() .but I send data is "".obs . that is not Rx() but this is RxString() .when I use "".obs.value="newString" . why Rx() can know that who updates data. just like : import 'package:flutter/material.dart';import 'package:get/get.dart';class GetIncrementPage extends StatefulWidget { GetIncrementPage({Key key}) : super(key: key); @override _GetIncrementPageState createState() => _GetIncrementPageState();}class _GetIncrementPageState extends State<GetIncrementPage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('get'), ), body: Container( alignment: Alignment.center, child: _body(), ), ); } Widget _body() { return Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ OutlineButton( child: Text('get 数字加减'), onPressed: c.increment, ), OutlineButton( child: Text('get log 变化'), onPressed: c.change, ), Obx(() { printInfo(info: '刷新了页面 get_example'); return Text(c.count.toString()); }), ObxValue((v) { printInfo(info: '刷新了页面 get_ObxValue_log1 '); return Text('logValue:' + v.toString()); }, ObjectKey('key').obs), Obx(() { printInfo(info: '刷新了页面 get_obx_log1'); return Text('logObx:' + c.log.toString()); }), Obx(() { printInfo(info: '刷新了页面 get_obx_log2'); return Text(c.log2.toString()); }), // ObxValue((var value) => Text('${value.toString()}'), c), ], ); } @override void dispose() { Get.delete<Controller2>(); super.dispose(); } final Controller2 c = Get.put(Controller2());}////// Created by fgyong on 2020/10/22.///class Controller2 extends GetxController { var count = 0.obs; var count2 = 0.obs; final log = ''.obs; final log2 = ''.obs; increment() => count++; @override void onClose() { printInfo(info: 'Controller close'); super.onClose(); } void change() { log.value += ' ${log.value.length}'; }} when i change log.value to new String,why log2 do not fresh. class Obx extends StatefulWidget { final WidgetCallback builder; const Obx(this.builder); _ObxState createState() => _ObxState();}class _ObxState extends State<Obx> { RxInterface _observer; StreamSubscription subs; _ObxState() { _observer = Rx(); } @override void initState() { subs = _observer.subject.stream.listen((data) => setState(() {})); super.initState(); } @override void dispose() { subs.cancel(); _observer.close(); super.dispose(); } Widget get notifyChilds { final observer = getObs; getObs = _observer; final result = widget.builder(); if (!_observer.canUpdate) { throw """ [Get] the improper use of a GetX has been detected. You should only use GetX or Obx for the specific widget that will be updated. If you are seeing this error, you probably did not insert any observable variables into GetX/Obx or insert them outside the scope that GetX considers suitable for an update (example: GetX => HeavyWidget => variableObservable). If you need to update a parent widget and a child widget, wrap each one in an Obx/GetX. """; } getObs = observer; return result; } @override Widget build(BuildContext context) => notifyChilds;} Why can rx() establish contact with the log, please help me. When I updateHow can Rx() know when logging? just help me. Now provide the response and nothing else.
You can use Obx or GetX widgets from Get to "listen" to changes to observable variables you declare in a GetxController. I think you are also confusing Rx as an ObserVER vs. ObservABLE. Rx is an observable, i.e. you watch it for changes using Obx or GetX widgets, (I guess you can call these two widgets "Observers".) Basic Example class Log2Page extends StatelessWidget { @override Widget build(BuildContext context) { Controller c = Get.put(Controller()); // ↑ declare controller inside build method return Scaffold( body: SafeArea( child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Obx( () => Text('${c.log2.value}') ), RaisedButton( child: Text('Add +1'), onPressed: c.change, ) ], ), ), ), ); }}class Controller extends GetxController { RxInt log2 = 0.obs; void change() => log2.value++;} You likely don't need a StatefulWidget when using GetX. A GetxController lives outside the lifecycle of widgets. State is stored in a GetX Controller (instead of in a StatefulWidget). GetX takes care of streams & subscriptions through variables you declare as obs , like count.obs and log2.obs . When you want to "listen" or "observe", use Obx or GetX widgets. These automatically listen to obs changes of its child and rebuild when it changes. Obx vs. GetBuilder vs. GetX class Log2Page extends StatelessWidget { @override Widget build(BuildContext context) { Controller c = Get.put(Controller()); return Scaffold( body: SafeArea( child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Obx( () => Text('Obx: ${c.log2.value}') ), // ↓ requires manual controller.update() call GetBuilder<Controller>( builder: (_c) => Text('GetBuilder: ${_c.log2.value}'), ), // ↓ controller instantiated by Get widget GetX<Controller>( init: Controller(), builder: (_c) => Text('GetX: ${_c.log2.value}'), ), RaisedButton( child: Text('Add +1'), onPressed: c.change, ), RaisedButton( child: Text('Update GetBuilder'), onPressed: c.update, // rebuild GetBuilder widget ), ], ), ), ), ); }}class Controller extends GetxController { RxInt log2 = 0.obs; void change() => log2.value++;} Obx Listens to observable ( obs ) changes. Controller needs to already be declared/initialized elsewhere to use. GetX Listens to observable ( obs ) changes. Can initialize controller itself using init: constructor argument, if not done elsewhere. Optional argument. Safe to use init: if Controller already instantiated. Will connect to existing instance. GetBuilder Does not listen to obs changes. Must be rebuilt manually by you, calling controller.update() . Similar to a setState() call. Can initialize controller itself using init: argument, if not done elsewhere. Optional.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/65405741', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12564479/']}
jdg_79210
stackexchange
llm_judgeable_groundtruth_similarity
117959
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 $R$ be a commutative ring with identity. Is there any characterization for invertible elements of $R[x,x^{-1}]$ ? Now provide the response and nothing else.
Thinking geometrically in terms of the map ${\rm{Spec}}(R[x,1/x]) \rightarrow {\rm{Spec}}(R)$ and noting that being a unit amounts to being nonzero in the residue field at every prime, an element $f = \sum a_i x^i \in R[x,1/x]$ is a unit if and only if it has unit restriction to every fiber, which is to say that for every prime ideal $P$ of $R$ (with residue field $k(P)$) the image $f(P) := \sum a_i(P) x^i$ in $k(P)[x,1/x]$ is a unit. But since $k(P)$ is a field, this latter condition is exactly that $f(P)$ is a $k(P)^{\times}$-multiple of a power of $x$. That is, there is exactly one $i$ (depending perhaps on $P$) such that $a_i(P) \ne 0$, which can be equivalently expressed as the condition that $a_i(P)a_j(P) = 0$ in $k(P)$ for all $i \ne j$ and $\sum a_i(P) \ne 0$ in $k(P)$. Varying over all $P$, this necessary and sufficient condition says exactly that (1) $a_i a_j$ is nilpotent in $R$ when $i \ne j$ and (2) $\sum a_i \in R^{\times}$. In the presence of (1), squaring the sum in (2) (which has no effect on whether or not it is a unit) and noting that adding a nilpotent element has no effect on being a unit shows that (2) can be replaced with (2') $\sum a_i^2 \in R^{\times}$ (thereby recovering the formulation in shatich's answer).
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/117959', 'https://mathoverflow.net', 'https://mathoverflow.net/users/30356/']}
jdg_79211
stackexchange
llm_judgeable_groundtruth_similarity
4083356
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to do an ArrayList in Delphi 5.0. So I found a solution doing this code: var arr: array of String; OK, but every time I add something I do this: var Form1: TForm1; var arr : array of String;procedure TForm1.Button1Click(Sender: TObject);var aux :string;var len:integer;begin len := Length(arr) + 1; SetLength(arr, len); arr[len-1] := 'abc' + IntToStr(len); Button1.Caption := arr[len-1]; // just to writeout somethingend; I'm a C++ programmer, and I do not know anything about Pascal. I always heard a Pascal index begins from 1, not 0. As in the above procedure I do arr[len-1] because of 0 index begin. Is there a better way than Pascal arrays? Like with C++'s std::vector ? Now provide the response and nothing else.
Dynamic arrays' indexes begin with zero var a: array of Integer;begin SetLength(a, 500); a[0] := 0; Static arrays can have arbitrary indexes var i: Integer; b: array [50..100] of Integer; c: array[-10..10] of Integer; begin for i := 50 to 100 do b[i] := i * i; // Note negative starting index above in declaration for i := -10 to 10 do c[i] := i * i; Strings' indexes begin with one var c: String;begin c := 'Zap!'; c[1] := 'W'; ShowMessage(c); /// shows 'Wap!' Anyway you can always use Low() and High() functions which return the lower and higher index of an array. For handling a list of strings the most commonly used class is TStringList which is found in unit Classes .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4083356', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/715757/']}
jdg_79212
stackexchange
llm_judgeable_groundtruth_similarity
3584288
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I need a method to monitor user edit sessions, and one of the solutions I'm reviewing will have me using an unload event to send an ajax request to inform the server of the end of the edit session. (See: Monitoring User Sessions to Prevent Editing Conflict ) My (rather limited) reading on the unload event indicate that the codes attached to this handler has to run quickly, and as such is usually used for clearing objects to prevent memory leaks. My question is, can this work reliably enough for this purpose? PS. I know about the async: false option. Now provide the response and nothing else.
This method is fairly reliable, if your server is fast enough to respond. Something to really watch out for though. If you close the browser and send AJAX request on unload event, there's a very good chance that the response isn't going to come back from the server in time before the window object is destroyed. What happens in this case (at least with IE) is that it will orphan your connection object and not terminate it correctly until the connection timeout is hit. If your server doesn't have connection keep-alive turned on, after you close 2 windows (while still having another window open), you will run out of open connections to the server (for IE6-7, for IE8 - 6 windows) and you will not be able to open your website until your connection timeout is hit. I ran into a situation like that before were I was opening a popup window that was sending an AJAX request on unload, it was very reliable, but it was plagued by the issued described above, and it took really long time for me to track it down and understand what's going on. After that, what I did, is I made sure that opening window would have the same code to call server, and on every unload checked for the opener and ran the code there if it was present. It seems that if you close the very last browser window, IE will destroy connection properly, but if one other window is open, it will not. P.S. And just to comment on the answer above, AJAX is not really async. At least JS implementation of it isn't. After you send a request, you JS code is still going to be waiting for response from the server. It's not going to block your code execution, but since the server might take a while to response (or long enough for Windows to terminate IE window object) you might and probably will run into the problem described above.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3584288', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/313758/']}
jdg_79213
stackexchange
llm_judgeable_groundtruth_similarity
2310483
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 used unions earlier comfortably; today I was alarmed when I read this post and came to know that this code union ARGB{ uint32_t colour; struct componentsTag { uint8_t b; uint8_t g; uint8_t r; uint8_t a; } components;} pixel;pixel.colour = 0xff040201; // ARGB::colour is the active member from now on// somewhere down the line, without any edit to pixelif(pixel.components.a) // accessing the non-active member ARGB::components is actually undefined behaviour I.e. reading from a member of the union other than the one recently written to leads to undefined behaviour. If this isn't the intended usage of unions, what is? Can some one please explain it elaborately? Update: I wanted to clarify a few things in hindsight. The answer to the question isn't the same for C and C++; my ignorant younger self tagged it as both C and C++. After scouring through C++11's standard I couldn't conclusively say that it calls out accessing/inspecting a non-active union member is undefined/unspecified/implementation-defined. All I could find was §9.5/1: If a standard-layout union contains several standard-layout structs that share a common initial sequence, and if an object of this standard-layout union type contains one of the standard-layout structs, it is permitted to inspect the common initial sequence of any of standard-layout struct members. §9.2/19: Two standard-layout structs share a common initial sequence if corresponding members have layout-compatible types and either neither member is a bit-field or both are bit-fields with the same width for a sequence of one or more initial members. While in C, ( C99 TC3 - DR 283 onwards) it's legal to do so ( thanks to Pascal Cuoq for bringing this up). However, attempting to do it can still lead to undefined behavior , if the value read happens to be invalid (so called "trap representation") for the type it is read through. Otherwise, the value read is implementation defined. C89/90 called this out under unspecified behavior (Annex J) and K&R's book says it's implementation defined. Quote from K&R: This is the purpose of a union - a single variable that can legitimately hold any of one of several types. [...] so long as the usage is consistent: the type retrieved must be the type most recently stored. It is the programmer's responsibility to keep track of which type is currently stored in a union; the results are implementation-dependent if something is stored as one type and extracted as another. Extract from Stroustrup's TC++PL (emphasis mine) Use of unions can be essential for compatness of data [...] sometimes misused for "type conversion ". Above all, this question (whose title remains unchanged since my ask) was posed with an intention of understanding the purpose of unions AND not on what the standard allows E.g. Using inheritance for code reuse is, of course, allowed by the C++ standard, but it wasn't the purpose or the original intention of introducing inheritance as a C++ language feature . This is the reason Andrey's answer continues to remain as the accepted one. Now provide the response and nothing else.
The purpose of unions is rather obvious, but for some reason people miss it quite often. The purpose of union is to save memory by using the same memory region for storing different objects at different times. That's it. It is like a room in a hotel. Different people live in it for non-overlapping periods of time. These people never meet, and generally don't know anything about each other. By properly managing the time-sharing of the rooms (i.e. by making sure different people don't get assigned to one room at the same time), a relatively small hotel can provide accommodations to a relatively large number of people, which is what hotels are for. That's exactly what union does. If you know that several objects in your program hold values with non-overlapping value-lifetimes, then you can "merge" these objects into a union and thus save memory. Just like a hotel room has at most one "active" tenant at each moment of time, a union has at most one "active" member at each moment of program time. Only the "active" member can be read. By writing into other member you switch the "active" status to that other member. For some reason, this original purpose of the union got "overridden" with something completely different: writing one member of a union and then inspecting it through another member. This kind of memory reinterpretation (aka "type punning") is not a valid use of unions. It generally leads to undefined behavior is described as producing implementation-defined behavior in C89/90. EDIT: Using unions for the purposes of type punning (i.e. writing one member and then reading another) was given a more detailed definition in one of the Technical Corrigenda to the C99 standard (see DR#257 and DR#283 ). However, keep in mind that formally this does not protect you from running into undefined behavior by attempting to read a trap representation.
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/2310483', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/183120/']}
jdg_79214
stackexchange
llm_judgeable_groundtruth_similarity
96408
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am writing simple car simulation. Assume non friction, then in straight line the car doesn't lose speed. But what if the car is turning, there should be some kinetic energy loses to change the direction of the car, so I should subtract some speed based on changing direction, isn't it right? Deeper explanation is welcome. Now provide the response and nothing else.
Assuming non friction, we must assume the car turns because it is held by a rope or chain to a point. The turning itself will not take energy from the system, what you have now is a constant speed that is tangent to the circle the car is following at the current car position.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/96408', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/25343/']}
jdg_79215
stackexchange
llm_judgeable_groundtruth_similarity
54531425
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Due to the floating point "approx" nature, its possible that two different sets of values return the same value. Example : #include <iostream>int main() { std::cout.precision(100); double a = 0.5; double b = 0.5; double c = 0.49999999999999994; std::cout << a + b << std::endl; // output "exact" 1.0 std::cout << a + c << std::endl; // output "exact" 1.0} But is it also possible with subtraction? I mean: is there two sets of different values (keeping one value of them) that return 0.0 ? i.e. a - b = 0.0 and a - c = 0.0 , given some sets of a,b and a,c with b != c ?? Now provide the response and nothing else.
The IEEE-754 standard was deliberately designed so that subtracting two values produces zero if and only if the two values are equal, except that subtracting an infinity from itself produces NaN and/or an exception. Unfortunately, C++ does not require conformance to IEEE-754, and many C++ implementations use some features of IEEE-754 but do not fully conform. A not uncommon behavior is to “flush” subnormal results to zero. This is part of a hardware design to avoid the burden of handling subnormal results correctly. If this behavior is in effect, the subtraction of two very small but different numbers can yield zero. (The numbers would have to be near the bottom of the normal range, having some significand bits in the subnormal range.) Sometimes systems with this behavior may offer a way of disabling it. Another behavior to beware of is that C++ does not require floating-point operations to be carried out precisely as written. It allows “excess precision” to be used in intermediate operations and “contractions” of some expressions. For example, a*b - c*d may be computed by using one operation that multiplies a and b and then another that multiplies c and d and subtracts the result from the previously computed a*b . This latter operation acts as if c*d were computed with infinite precision rather than rounded to the nominal floating-point format. In this case, a*b - c*d may produce a non-zero result even though a*b == c*d evaluates to true. Some C++ implementations offer ways to disable or limit such behavior.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/54531425', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/365251/']}
jdg_79216
stackexchange
llm_judgeable_groundtruth_similarity
532912
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $f(x)$ be continuous except at $x = 0$ and let $a > 0$. Assume that the improper integral $$\int_{0}^{a}f(x)\,dx = \lim_{\epsilon \to 0+}\int_{\epsilon}^{a}f(x)\,dx$$ exists and let $$g(x) = \int_{x}^{a}\frac{f(t)}{t}\,dt$$ Show that $$\int_{0}^{a}g(x)\,dx = \int_{0}^{a}f(x)\,dx$$ I tried integration by parts noting that $g'(x) = -f(x)/x$ and obtained for $0 < \epsilon < a$ the following $$\int_{\epsilon}^{a}g(x)\,dx = [xg(x)]_{x = \epsilon}^{x = a} - \int_{\epsilon}^{a}xg'(x)\,dx$$ or $$\int_{\epsilon}^{a}g(x)\,dx = -\epsilon g(\epsilon) + \int_{\epsilon}^{a}f(x)\,dx$$ The problem is solved if we can somehow show that $\lim_{\epsilon \to 0+}\epsilon g(\epsilon) = 0$. Looking at the definition $g(x)$ we see that we have no information of the behavior of $f(t)$ at $t = 0$ and the $t$ in denominator complicates the analysis of $g(\epsilon)$. Please suggest some hints which can lead to the solution. Note: This problem is taken from G. H. Hardy's "A Course of Pure Mathematics" 10th ed. Page 397. Now provide the response and nothing else.
Hint: Define $$h(x)=\int_x^af(t)dt,\ \forall x\in[0,a].$$Then for every $x\in(0,a]$,$$g(x)=-\int_x^a\frac{h'(t)}{t}dt=\frac{h(x)}{x}-\int_x^a\frac{h(t)}{t^2}dt=\frac{h(x)}{a}+\int_x^a\frac{h(x)-h(t)}{t^2}dt.$$ Given $\delta\in(0, a]$, denote $$M_\delta=\max_{x,y\in[0,\delta]}|h(x)-h(y)|.$$When $x\in(0,\delta)$, $$|g(x)-\frac{h(x)}{a}|\le \int_x^\delta\frac{|h(x)-h(t)|}{t^2}dt+\int_\delta^a\frac{|h(x)-h(t)|}{t^2}dt\le \frac{M_\delta}{x}+\frac{M_a}{\delta}.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/532912', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/72031/']}
jdg_79217
stackexchange
llm_judgeable_groundtruth_similarity
29942
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: You can map whole numbers to combinations when taking them in order. For example, 13 choose 3 would look like: 0 --> (0, 1, 2)1 --> (0, 1, 3)2 --> (0, 1, 4)etc... Given a particular combination, such as (0, 3, 9) , is there a way to determine which whole number maps to it (26, in this case), short of writing out all the combinations in order until I hit upon the proper one? Furthermore, is there a way of doing this when counting combinations with repetitions? If anyone is wondering, this isn't homework, but for a personal programming project. Now provide the response and nothing else.
Let $N(n;a_1,\dots,a_k)$ where $0\leq a_1 < a_2 < \dots < a_k < n$ be the order number of $(a_1,\dots,a_k)$ as a combination from ($n$ choose $k$). Since there are exactly $\binom{n-1}{k-1}$ combinations with $a_1 = 0$, we have a recurrence: if $a_1 = 0$, then$$ N(n;a_1,\dots,a_k) = N(n-1;a_2-1,\dots,a_k-1)$$ if $a_1 > 0$, then$$N(n;a_1,\dots,a_k) = \binom{n-1}{k-1} + N(n-1;a_1-1,a_2-1,\dots,a_k-1).$$ with initial condition $N(n;)=0$ (i.e., when $k=0$) for any $n$. For example, $$N(13;0,1,4) = N(12;0,3) = N(11;2) = \binom{10}{0} + N(10;1)$$ $$= \binom{10}{0} + N(10;1) = \binom{10}{0} + \binom{9}{0} + N(9;0)$$$$=\binom{10}{0} + \binom{9}{0} + N(8;) = 1 + 1 + 0 = 2$$as required. UPDATE . In fact, there is a simpler way to enumerate combinations, using combinatorial number system of degree $k$. A $k$-combination $0\leq a_1 < a_2 < \dots < a_k < n$ here gets the order number:$$\binom{a_1}{1} + \binom{a_2}{2} + \dots + \binom{a_k}{k}.$$ The properties of combinatorial number system ensure that this representation is a bijective mapping between $k$-combinations of $n$ and the integers in the interval $[0,\tbinom{n}{k}-1]$. In particular, given an integer $m$ in this interval, its representation in the combinatorial number system of degree $k$:$$m = \binom{a_1}{1} + \binom{a_2}{2} + \dots + \binom{a_k}{k}$$uniquely defines numbers $0\leq a_1 < a_2 < \dots < a_k < n$ (the last inequality follows from $m<\tbinom{n}{k}$), i.e., a $k$-combination of $n$.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/29942', 'https://mathoverflow.net', 'https://mathoverflow.net/users/1646/']}
jdg_79218
stackexchange
llm_judgeable_groundtruth_similarity
55178486
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Javascript and Jquery is not loading on normal page refresh, but loads correctly on hard refresh (CTRL+SHIFT+R) and Incognito. I'm calling the functions through window.onload: window.onload = function() { adddata(); adddata_pages(); adddata_views7(); adddata_pages7(); adddata_views1(); adddata_pages1(); }; And I'm including the Jquery files in this order in the head of html: jquery.min.js , bootstrap.min.js , Chart.min.js , jquery.dataTables.js . And in the end (before closing body tag) I'm calling my external js file which has all my functional code. Can please anyone help as where I'm going wrong or what is the solutions for this? Now provide the response and nothing else.
I'm adding a second answer because I think there could be a different issue. I think the MIME Type error could be due to the css path not being correct. I think it is trying to serve up an error instead of the css file which is not matching the MIME type. Try removing the following line from your HTML Template and allowing the HtmlWebPackPlugin to inject it automatically. <link rel="stylesheet" href="./style.css" /> Below is my own webpack.config and index.html template which I hope will help. webpack.config const MiniCssExtractPlugin = require("mini-css-extract-plugin");const HtmlWebpackPlugin = require('html-webpack-plugin');const LinkTypePlugin = require('html-webpack-link-type-plugin').HtmlWebpackLinkTypePlugin;const CopyPlugin = require('copy-webpack-plugin');module.exports = { entry: './src/index.tsx', output: { filename: 'app/main.js' }, devServer: { contentBase: './', watchContentBase: true }, module: { rules: [ { test: /\.scss$/, use: [{ loader: MiniCssExtractPlugin.loader, options: { } }, "css-loader", "resolve-url-loader", { loader: "sass-loader?sourceMap", options: { includePaths: [ ], sourceMap: true } } ], exclude: /node_modules/ }, { test: /\.tsx?$/, use: { loader: 'babel-loader' }, exclude: /node_modules/ }, { test: /\.(eot|svg|ttf|woff|woff2)$/, loader: 'file-loader', options: { publicPath: "./", outputPath: "app" } } ] }, resolve: { extensions: ['.tsx', '.ts', '.js'] }, plugins: [ new MiniCssExtractPlugin({ filename: './app/style.css', }), new HtmlWebpackPlugin({ template: 'index.html' }), new LinkTypePlugin({ '**/*.css' : 'text/css' }), new CopyPlugin([ { from: 'assets', to: 'assets' } ]) ]}; index.html <!DOCTYPE html><html><head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>My Site</title> <meta name="viewport" content="width=device-width, initial-scale=1"></head><body> <div id="home_container"></body></html>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/55178486', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4911440/']}
jdg_79219
stackexchange
llm_judgeable_groundtruth_similarity
529482
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 coding and trying to get up to speed with Objective-C.Came across some code I did not understand. I was hoping someone couldclarify it for me. In the case below, I am not sure how *foo2 is working and why it is not being released? ClassOne *pointer = [[ClassOne alloc]init];ClassTwo *foo = [[ClassTwo alloc]init], *foo2; foo2 = [foo add: pointer]; [foo release]; foo = foo2[pointer release];[foo release]; Now provide the response and nothing else.
With Objective-C Cocoa, we're working with semi-automatic reference-counting memory management. When allocating memory for an object, retaining an object, or calling a copy method on an object, the retain count (reference count) increments by 1. When calling release on an object, it decrements the retain count by one. When calling autorelease on an object, release will be called on the object at some point in the future (during the main run loop, when none of your own code is executing, so it won't pull the reference out from under you as you're trying to use it). When the retain count reaches 0, the object can be deallocated. In general, if you're calling retain on an object, you're signalling your interest in it, and you are responsible for making a release or autorelease call at some point when you're no longer interested in the object. Likewise, if you call alloc or a copy method on an object, you have signalled your interest in the object and must match it with a release or autorelease somewhere down the line. This link pretty much covers the guidelines Apple uses (and you should use) for memory management: Simple rules for memory management in Cocoa Let's go through the code line by line: ClassOne *pointer = [[ClassOne alloc]init]; pointer points to a newly allocated ClassOne object, with a retain count of 1, since we called alloc on it. We have a responsibility to call release or autorelease on pointer at some point in the future. ClassTwo *foo = [[ClassTwo alloc]init], *foo2; foo points to a newly allocated ClassTwo object, with a retain count of 1, since we called alloc on it. We have a responsibility to call release or autorelease on foo at some point in the future. foo2 doesn't point to anything in particular right now. It's not safe to use. foo2 = [foo add: pointer]; pointer has been added to foo (whatever that means; we don't know the implementation). foo might have called retain on pointer to signal its interest in it, and added it as a field, or it might have added pointer to a collection (in which case it's the collection's responsibility to call retain on it when an object is added, and release when an object is removed). In any case, it doesn't affect our code block, so we don't care what's going on under the hood The reference returned by this method might be pointer itself, or it might be an autoreleased copy of pointer ; we don't have access to the API or the implementation to tell us which. In either case, it is not our responsibility to call release on this object. If the method had copy in the name, or if we had called retain on the returned reference (like foo2 = [[foo add:pointer] retain]; ), then the retain count would have been incremented by 1, and it would have been our responsibility to call release or autorelease on it. [foo release]; The object referenced by foo has been released, meaning its retain count has been decremented by 1. For this example, this pairs with the alloc call we made in line 2, so the retain count will drop to 0, making foo eligible to be freed. In general, though, we don't care if the object has been deallocated or not; we just need to make sure we pair up any alloc , copy , or retain calls with the same number of release or autorelease calls. If we register an interest in an object at any time, it's our responsibility to release our interest, otherwise we'll have memory leaks. foo = foo2; foo now points to the same object referenced by foo2 . Remember, we haven't called an alloc or copy method when we got foo2 , nor did we register an interest in it by calling retain . Since we don't have a responsibility to call release on foo2 , we don't have a responsibility to call release on foo . [pointer release]; pointer 's retain count has been decremented by 1. This may have brought its retain count to 0 or not, it depends on what foo did with it when we added it. Still, we don't care; we have finished our responsibility to pointer by calling release on it to match with the alloc call we made at the beginning. Although pointer might still be around after this call, we can't make that assumption, and trying to do anything with the object previously referenced by pointer would be a mistake (though we could change pointer to point at something else freely). [foo release]; If the author of this code has been following Apple's memory management conventions, then this is unnecessary. We don't have a responsibility to call release on foo or foo2 (they point to the same object, remember). This won't cause the code to break; calling anything on a nil reference is essentially a no-op. However, it may cause confusion for anyone reviewing the code. Now, the author of this code may have broken the memory management conventions. He might have made that add call return a copy of pointer without calling autorelease on it, in which case it makes the caller responsible for calling release on it. This is very bad form, and if you should run into code which breaks the memory management convention, document where you use it and how it breaks the convention to avoid confusion in the future.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/529482', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/54836/']}
jdg_79220
stackexchange
llm_judgeable_groundtruth_similarity
1784262
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've read many times that the derivative of a function $f(x)$ for a certain $x$ is the best linear approximation of the function for values near $x$. I always thought it was meant in a hand-waving approximate way, but I've recently read that: " Some people call the derivative the “best linear approximator” because of how accurate this approximation is for $x$ near $0$ (as seen in the picture below). In fact, the derivative actually is the “best” in this sense – you can’t do better ." (from http://davidlowryduda.com/?p=1520 , where $0$ is a special case in the context of Taylor Series). This seems to make it clear that the idea of "best linear approximation" is meant in a literal, mathematically rigorous way. I'm confused because I believe that for a differentiable function, no matter how small you make the interval $\epsilon$ around $x$, there will always be for any $a$ near $x$ in that interval a line going through $x$ that is either as good an approximation of $f(a)$ as the one given by $f'(x)$ (in case the function is actually linear over that interval), or a better approximation (the case in which the line going through $(x, f(x))$ also goes through (a, f(a)) and any line between this line and the tangent at $x$). What am I missing? Now provide the response and nothing else.
As some people on this site might be aware I don't always take downvotes well . So here's my attempt to provide more context to my answer for whoever decided to downvote. Note that I will confine my discussion to functions $f: D\subseteq \Bbb R \to \Bbb R$ and to ideas that should be simple enough for anyone who's taken a course in scalar calculus to understand. Let me know if I haven't succeeded in some way. First, it'll be convenient for us to define a new notation. It's called "little oh" notation. Definition : A function $f$ is called little oh of $g$ as $x\to a$, denoted $f\in o(g)$ as $x\to a$, if $$\lim_{x\to a}\frac {f(x)}{g(x)}=0$$ Intuitively this means that $f(x)\to 0$ as $x\to a$ "faster" than $g$ does. Here are some examples: $x\in o(1)$ as $x\to 0$ $x^2 \in o(x)$ as $x\to 0$ $x\in o(x^2)$ as $x\to \infty$ $x-\sin(x)\in o(x)$ as $x\to 0$ $x-\sin(x)\in o(x^2)$ as $x\to 0$ $x-\sin(x)\not\in o(x^3)$ as $x\to 0$ Now what is an affine approximation? (Note: I prefer to call it affine rather than linear -- if you've taken linear algebra then you'll know why.) It is simply a function $T(x) = A + Bx$ that approximates the function in question. Intuitively it should be clear which affine function should best approximate the function $f$ very near $a$. It should be $$L(x) = f(a) + f'(a)(x-a).$$ Why? Well consider that any affine function really only carries two pieces of information: slope and some point on the line. The function $L$ as I've defined it has the properties $L(a)=f(a)$ and $L'(a)=f'(a)$. Thus $L$ is the unique line which passes through the point $(a,f(a))$ and has the slope $f'(a)$. But we can be a little more rigorous. Below I give a lemma and a theorem that tell us that $L(x) = f(a) + f'(a)(x-a)$ is the best affine approximation of the function $f$ at $a$. Lemma : If a differentiable function $f$ can be written, for all $x$ in some neighborhood of $a$, as $$f(x) = A + B\cdot(x-a) + R(x-a)$$ where $A, B$ are constants and $R\in o(x-a)$, then $A=f(a)$ and $B=f'(a)$. Proof : First notice that because $f$, $A$, and $B\cdot(x-a)$ are continuous at $x=a$, $R$ must be too. Then setting $x=a$ we immediately see that $f(a)=A$. Then, rearranging the equation we get (for all $x\ne a$) $$\frac{f(x)-f(a)}{x-a} = \frac{f(x)-A}{x-a} = \frac{B\cdot (x-a)+R(x-a)}{x-a} = B + \frac{R(x-a)}{x-a}$$ Then taking the limit as $x\to a$ we see that $B=f'(a)$. $\ \ \ \square$ Theorem : A function $f$ is differentiable at $a$ iff, for all $x$ in some neighborhood of $a$, $f(x)$ can be written as $$f(x) = f(a) + B\cdot(x-a) + R(x-a)$$ where $B \in \Bbb R$ and $R\in o(x-a)$. Proof : "$\implies$": If $f$ is differentiable then $f'(a) = \lim_{x\to a} \frac{f(x)-f(a)}{x-a}$ exists. This can alternatively be written $$f'(a) = \frac{f(x)-f(a)}{x-a} + r(x-a)$$ where the "remainder function" $r$ has the property $\lim_{x \to a} r(x-a)=0$. Rearranging this equation we get $$f(x) = f(a) + f'(a)(x-a) -r(x-a)(x-a).$$ Let $R(x-a):= -r(x-a)(x-a)$. Then clearly $R\in o(x-a)$ (confirm this for yourself). So $$f(x) = f(a) + f'(a)(x-a) + R(x-a)$$ as required. "$\impliedby$": Simple rearrangement of this equation yields $$B + \frac{R(x-a)}{x-a}= \frac{f(x)-f(a)}{x-a}.$$ The limit as $x\to a$ of the LHS exists and thus the limit also exists for the RHS. This implies $f$ is differentiable by the standard definition of differentiability. $\ \ \ \square$ Taken together the above lemma and theorem tell us that not only is $L(x) = f(a) + f'(a)(x-a)$ the only affine function who's remainder tends to $0$ as $x\to a$ faster than $x-a$ itself (this is the sense in which this approximation is the best ), but also that we can even define the concept differentiability by the existence of this best affine approximation.
{}
{'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/1784262', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/118169/']}
jdg_79221
stackexchange
llm_judgeable_groundtruth_similarity
9220901
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 query that looks like this: using (MyDC TheDC = new MyDC()){ foreach (MyObject TheObject in TheListOfMyObjects) { DBTable TheTable = new DBTable(); TheTable.Prop1 = TheObject.Prop1; ..... TheDC.DBTables.InsertOnSubmit(TheTable); } TheDC.SubmitChanges();} This query basically inserts a list into the database using linq-to-sql. Now I've read online that L2S does NOT support bulk operations.Does my query work by inserting each element at a time or all of them in one write? Thanks for the clarification. Now provide the response and nothing else.
I modified the code from the following link to be more efficient and used it in my application. It is quite convenient because you can just put it in a partial class on top of your current autogenerated class. Instead of InsertOnSubmit add entities to a list, and instead of SubmitChanges call YourDataContext.BulkInsertAll(list) . http://www.codeproject.com/Tips/297582/Using-bulk-insert-with-your-linq-to-sql-datacontex partial void OnCreated(){ CommandTimeout = 5 * 60;}public void BulkInsertAll<T>(IEnumerable<T> entities){ using( var conn = new SqlConnection(Connection.ConnectionString)) { conn.Open(); Type t = typeof(T); var tableAttribute = (TableAttribute)t.GetCustomAttributes( typeof(TableAttribute), false).Single(); var bulkCopy = new SqlBulkCopy(conn) { DestinationTableName = tableAttribute.Name }; var properties = t.GetProperties().Where(EventTypeFilter).ToArray(); var table = new DataTable(); foreach (var property in properties) { Type propertyType = property.PropertyType; if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Nullable<>)) { propertyType = Nullable.GetUnderlyingType(propertyType); } table.Columns.Add(new DataColumn(property.Name, propertyType)); } foreach (var entity in entities) { table.Rows.Add( properties.Select( property => property.GetValue(entity, null) ?? DBNull.Value ).ToArray()); } bulkCopy.WriteToServer(table); } }private bool EventTypeFilter(System.Reflection.PropertyInfo p){ var attribute = Attribute.GetCustomAttribute(p, typeof(AssociationAttribute)) as AssociationAttribute; if (attribute == null) return true; if (attribute.IsForeignKey == false) return true; return false;}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9220901', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/565968/']}
jdg_79222
stackexchange
llm_judgeable_groundtruth_similarity
384479
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 prove the following using integration and elementary functions ? Prove that: $$\sum_{n=1}^{\infty} \frac{\sin(n\theta)}{n} = \frac{\pi}{2} - \frac{\theta}{2}$$ $0 < \theta < 2\pi$ Now provide the response and nothing else.
Let,$$S_1 = \sum_{n=1}^{\infty}\frac{\cos n\theta}{n}\\S_2 = \sum_{n=1}^{\infty}\frac{\sin n\theta}{n}$$ Then $$S_1 + iS_2 = \sum_{n=1}^{\infty}\frac{\cos(n\theta)+i\sin(n\theta)}{n}=\sum_{n=1}^{\infty}\frac{e^{in\theta}}{n}$$ Now, from the Taylor expansion, $\ln (1+x) = x -\frac{x^2}{2}+\frac{x^3}{3} ...$$$\implies -\ln(1-x) = x+ \frac{x^2}{2}+\frac{x^3}{3} ... = \sum_{n=1}^{\infty}\frac{x^n}{n}$$$$\begin{align} \therefore S_1+iS_2 &= -\ln(1-e^{i\theta})\\&=-\ln(1-\cos\theta-i\sin \theta)\\&=-\ln(2\sin^2\theta/2 - 2i\sin(\theta/2)\cos(\theta/2))\\&=-\ln(2\sin\theta/2)-\ln(\sin\theta/2-i\cos\theta/2)\\&=-\ln(2\sin\theta/2)+\ln(\sin\theta/2+i\cos\theta/2)\\&=-\ln(2\sin\theta/2)+\ln(e^{i(\pi/2-\theta/2)})\\&=-\ln(2\sin\theta/2)+i(\pi/2-\theta/2)\end{align}$$ Taking the imaginary part of both sides,$$S_2 = \frac{\pi}{2} - \frac{\theta}{2}$$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/384479', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/74645/']}
jdg_79223
stackexchange
llm_judgeable_groundtruth_similarity
23020
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 was just thnking of how to model the voltage decay from a fully charged capacitor through a constant current source (CCS). A good approximation to this would be to model the constant current source as a resistor sized by the initial voltage divided by the current of the CCS, giving the formula: $$ V(t) = V(0) * e ^{\frac{-t}{RC}} $$ ... but is there a closed form analytical formula for the CCS case? +------------+ V(0) | | | C | --+-- /\ --+-- CCS (I) | \/ | | +------------+ | -+- GND Some ASCII circuit art for good measure... Obviously I'm only interested in the model up to the point where the current that the capacitor is able to supply is still above the demand of the current source, and that the voltage is greater than GND (i.e. the realizable time). Now provide the response and nothing else.
In general voltage on the capacitor with respect to the current is governed by the equation: \$v(t)= \frac{q(t)}{C} = \frac{1}{C}\int_{t_0}^t i(\tau) \mathrm{d}\tau+v(t_0)\$, By the definition for CCS: \$ i(\tau) = I \$, from this we can derive that: \$v(t)= \frac{1}{C}(I t - It_0) + v(t_0)\$ now assuming \$t_0 = 0\$ this simplifies to: \$v(t)= \frac{1}{C}I t + v(0)\$. What this means is simple! The voltage across capacitor will change linearly with time. The "rate" of change (or "slope") depends on the current magnitude and the capacitance: The bigger the capacitance the slower voltage changes. The bigger the current the faster voltage changes. The sign of the change (voltage rising or falling) depends on the sign or direction of the current. Obviously if current is flowing into capacitor voltagwe will rise if flowing out of capacitor voltage will fall.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/23020', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/771/']}
jdg_79224
stackexchange
llm_judgeable_groundtruth_similarity
16121269
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 been trying to do Convolution of a 2D Matrix using SciPy, and Numpy but have failed. For SciPy I tried, sepfir2d and scipy.signal.convolve and Convolve2D for Numpy. Is there a simple function like conv2 in Matlab for Python? Here is an example: A= [ 5 4 5 4; 3 2 3 2; 5 4 5 4; 3 2 3 2 ] I want to convolve it with [0.707 0.707] And the result as by conv2 from Matlab is 3.5350 6.3630 6.3630 6.3630 2.82802.1210 3.5350 3.5350 3.5350 1.41403.5350 6.3630 6.3630 6.3630 2.82802.1210 3.5350 3.5350 3.5350 1.4140 Some function to compute this output in Python? I will be grateful for a response. Now provide the response and nothing else.
There are a number of different ways to do it with scipy , but 2D convolution isn't directly included in numpy . (It's also easy to implement with an fft using only numpy, if you need to avoid a scipy dependency.) scipy.signal.convolve2d , scipy.signal.convolve , scipy.signal.fftconvolve , and scipy.ndimage.convolve will all handle a 2D convolution (the last three are N-d) in different ways. scipy.signal.fftconvolve does the convolution in the fft domain (where it's a simple multiplication). This is much faster in many cases, but can lead to very small differences in edge effects than the discrete case, and your data will be coerced into floating point with this particular implementation. Additionally, there's unnecessary memory usage when convolving a small array with a much larger array. All in all, fft-based methods can be dramatically faster, but there are some common use cases where scipy.signal.fftconvolve is not an ideal solution. scipy.signal.convolve2d , scipy.signal.convolve , and scipy.ndimage.convolve all use a discrete convolution implemented in C, however, they implement it in different ways. scipy.ndimage.convolve keeps the same data type, and gives you control over the location of the output to minimize memory usage. If you're convolving uint8 's (e.g. image data), it's often the best option. The output will always be the same shape as the first input array, which makes sense for images, but perhaps not for more general convolution. ndimage.convolve gives you a lot of control over how edge effects are handled through the mode kwarg (which functions completely differently than scipy.signal 's mode kwarg). Avoid scipy.signal.convolve if you're working with 2d arrays. It works for the N-d case, but it's suboptimal for 2d arrays, and scipy.signal.convolve2d exists to do the exact same thing a bit more efficiently. The convolution functions in scipy.signal give you control over the output shape using the mode kwarg. (By default, they'll behave just like matlab's conv2 .) This is useful for general mathematical convolution, but less useful for image processing. However, scipy.signal.convolve2d is generally slower than scipy.ndimage.convolve . There are a lot of different options partly due to duplication in the different submodules of scipy and partly because there are different ways to implement a convolution that have different performance tradeoffs. If you can give a bit more detail about your use case, we can recommend a better solution. If you're convolving two arrays of roughly the same size, and they're already floats, fftconvolve is an excellent choice. Otherwise, scipy.ndimage.convolve may beat it.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16121269', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1343318/']}
jdg_79225
stackexchange
llm_judgeable_groundtruth_similarity
17806737
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a table which contains columns of numbers and NA. <tr> <td>NA</td></tr><tr> <td>1024</td></tr><tr> <td>100</td></tr><tr> <td>200</td></tr><tr> <td>300</td></tr><tr> <td>2096</td></tr> I'm trying to use jQuery dataTable to sort the column to produce the following: NA, 100, 200, 300, 1024, 2096 and 2096, 1024, 300, 200, 100, NA but can't figure out how to do it from reading the sorting and plugins docs. I've created a Fiddle of the code here: http://jsfiddle.net/stowball/rYtxh/ and would really appreciate some assistance. Now provide the response and nothing else.
By looking at the Numbers with HTML plugin you can take the existing code and modify the regex to look for negative numbers instead of stripping everything. Using that you can put together a HTML tag around the "NA" and use the HTML5 data-internalid to store the lowest number of the collection. so it becomes: <td><a data-internalid="-1">NA</a></td> and (notice the regex) jQuery.extend( jQuery.fn.dataTableExt.oSort, {"num-html-pre": function ( a ) { var x = String(a).replace(/(?!^-)[^0-9.]/g, ""); return parseFloat( x );},"num-html-asc": function ( a, b ) { return ((a < b) ? -1 : ((a > b) ? 1 : 0));},"num-html-desc": function ( a, b ) { return ((a < b) ? 1 : ((a > b) ? -1 : 0));}}); Then in the datatable, set the type to num-html $('table').dataTable({ "aoColumns": [{ "sType": "num-html" }], "aaSorting": [[ 0, "desc" ]],}); You can see my full solution here: http://jsfiddle.net/rYtxh/4/
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17806737', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1390770/']}
jdg_79226
stackexchange
llm_judgeable_groundtruth_similarity
34717492
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 made the following tile, with an hover-effect that increases the font-size with an CSS- transition : body { font-family: 'Segoe UI', sans-serif;}.website { width: 180px; height: 73px; text-align: center; line-height: 80px; margin: 1px; color: white; border-bottom: 5px solid darkslateblue; background-color: darkslateblue; white-space: nowrap; overflow: hidden; transition: border-color 0.66s ease-out, font-size 0.3s ease-out;}.website:hover { font-size: 16pt; cursor: pointer; transition: border-color 0s; border-color: black;} <div class="website">Blog 1</div><div class="website">Blog 2</div><div class="website">Blog 3</div> When you hover them you can see that the transition of the font-size is not smooth at all. In other words it wiggles up and down when changing size. Does anyone have an Idea how to fix or work around it? Now provide the response and nothing else.
You can use CSS transform:scale instead for a smoother transition like so: .website:hover { cursor: pointer; transition: border-color 0.4s; border-color: black;}.website div { transition: transform 0.3s ease-out;}.website:hover div { transform: scale(1.5); transition: transform 0s;} Here is the JSFiddle demo Also note that I added the texts within a div and the scaling was done on the div so that the whole box is not scaled :)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/34717492', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4339170/']}
jdg_79227
stackexchange
llm_judgeable_groundtruth_similarity
125795
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: This is I think an already asked question but I at the margin there are some new points I have this file found on internet and now I want to recognize the table with the following commands img = Rasterize[Import["http://i.stack.imgur.com/Ricz2.png"]] p = StringReplace[ TextRecognize[ImageResize[img, Scaled[4]], "SegmentationMode" -> 6], {"Ell~20" -> "EU-28", "1.M" -> "1.80", "2N3" -> "2003", "enigma" -> "Bulgaria"}]; 1) I wonder why a higher scale than 4 degrades completely the recognition.2) if there is an other way to reconstruct the table than to give a substitution table for the badly recognize texts.3) Finally, I wonder if there is a way to ameliorate the recognition of the table Now provide the response and nothing else.
Here's a way to augment @georg279's approach. We can use ImageLines to subdivide the image. First we use a derivative filter to highlight the horizontal lines. The parameters need to be tweaked by hand. img = Import@"http://i.stack.imgur.com/Ricz2.png"i2 = Binarize[DerivativeFilter[img, {1, 0}, 0.2], 0.09] Then we can get the lines and inspect them: lines = ImageLines[i2, 0.19, 0.008];HighlightImage[img, {Orange, Line /@ lines}] We got every row entry, plus a block below the table, which we can discard later. We can use the coordinates in lines to subdivide the image and apply TextRecognize to the pieces: tdata = TextRecognize[ImageResize[#, Scaled[8]]] & /@ Reverse@Rest[ ImageTake[img, -Reverse@#] & /@ Partition[Round@Sort@lines[[All, 1, 2]], 2, 1]] We can then convert the numerals in the last ten columns to numeric data. There's a problem with the missing data in the columns and the spaces in the names in the first column. By padding with "XXX" , the entries last column were all converted, but removing the Xs took inspection. Replace[ ToExpression[(StringSplit[tdata] /. "X" | "XX" | "XXX" | "xxx" :> Sequence[])[[All, -11 ;;]]], {x_Real :> x, n_Integer :> n, I | $Failed -> Missing["NotAvailable"]}, 2](* {{2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013}, {1.76, 1.76, 1.78, 1.78, 1.85, 1.94, 1.93, 1.97, 2.01, 2.01}, ... {2.49, 2.68, 2.79, 3.01, 3.21, 3.36, 3.56, 3.74, 4.04, Missing["NotAvailable"], Missing["NotAvailable"]}, {2.55, 2.49, 2.51, 2.55, 2.63, 2.77, 2.82, 2.74, 2.77, 2.81, Missing["NotAvailable"]}}*)
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/125795', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/38721/']}
jdg_79228
stackexchange
llm_judgeable_groundtruth_similarity
45778702
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 developing an attendance manager app. To take attendance , I've to create layout like this I want to make it programatically. In the below layout I've used to add FAB using xml. Now provide the response and nothing else.
Asp.Net Core 2.0 definitely support multiple authentication schemes.Rather than a hacking with authenticate middleware, you can try to specify the schema in Authorize attribute: [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] I gave a try and it worked fine. Assuming you have added both Identity and JWT as below: services.AddIdentity<ApplicationUser, ApplicationRole>()services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) Since AddIdentity() already set cookie authentication as the default schema, we have to specify schema in Authorize attribute of controllers. For now, I have no idea how to overwrite the default schema set by AddIdentity() , or maybe we'd better not to do that. A work around is to compose a new class (you can call it JwtAuthorize) that derives from Authorize and have Bearer as the default schema, so you don't have to specify it every time. UPDATE Found the way to override Identity default authentication scheme! Instead of below line: services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) Use below overload to set default schema: services.AddAuthentication(option => { option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options =>.... UPDATE 2 As mentioned in comments, you can enable both Identity and JWT auth by join them together. [Authorize(AuthenticationSchemes = "Identity.Application" + "," + JwtBearerDefaults.AuthenticationScheme)]
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/45778702', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6452937/']}
jdg_79229
stackexchange
llm_judgeable_groundtruth_similarity
291632
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 know it sounds like a newbie question but I can't wrap my mind around it. An electromagnetic field is electric + magnetic field. So this means that when shielding an equipment offensively, for example from avoiding causing interference with other electronics, we need to shield the electromagnetic waves, that means both electric and magnetic shielding. So if we put say a radio inside an aluminium box, aluminium is pretty much the most cost effective material you can find. Some may use copper but aluminum is more cost effective. Now an aluminum box will shield the electrical field very efficiently given if the box has no holes or seams, or if the cables coming out of holes are properly shielded and grounded. But what about the magnetic field? Aluminum has very low permeability. So how can the aluminum box shield nearby equipment from the magnetic field of the radio inside it? It does shield the electrical field, but not the magnetic? Can somebody explain to me how shielding works with electrical/magnetic waves? Because I can't wrap my head around it how can it shield the electrical part but not the magnetic? Does magnetic field leakage pose any noise danger to the nearby equipment from this theory perspective? Now provide the response and nothing else.
You would not be alone in this one. This is an often misunderstood phenomenon. Static magnetic fields can not be shielded. They can be re-directed using ferrous materials but even those will not block them. Electric fields on the other hand can be. Since an electric field is basically a voltage in space, they can not pass through a conductive plate that is held at a fixed potential. Space is shorted out as it were. Alternating magnetic fields of sufficient frequency however, will not pass through a metal plate. The alternating field generates an eddy current in the plate which generates a cancelling magnetic field. This is all explained in much better detail here.. Wikipedia
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/291632', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/138887/']}
jdg_79230
stackexchange
llm_judgeable_groundtruth_similarity
29786413
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 got a error when i run android espresso test: com.google.android.apps.common.testing.ui.espresso.PerformException: Error performing 'single click' on view 'with id: is <2131034173>'. My code is easy: onView(withId(R.id.btn)).perform(click()); But there is no error with this code: onView(withId(R.id.btn)).check(matches(isDisplayed())); I can not find the cause why it happen. Now provide the response and nothing else.
The trick is to read the full stack-trace of the error. In the middle, there is some crucial piece of information like this: Caused by: java.lang.RuntimeException: Action will not be performed because the target view does not match one or more of the following constraints:at least 90 percent of the view's area is displayed to the user.Target view: "ImageView{id=2131492903, res-name=button_hamburger, desc=opens the side drawer, visibility=VISIBLE, width=64, height=64, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=true, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=6.0, y=6.0}" which explains the error in detail.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/29786413', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4757252/']}
jdg_79231
stackexchange
llm_judgeable_groundtruth_similarity
1068840
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 of doing \1 as opposed to $1 if any, or are they interchangeable in all situations. Example: s/([a-z]+),afklol/$1,bck/;#againsts/([a-z]+),afklol/\1,bck/; They both give the same result but is there any difference? Now provide the response and nothing else.
Straight from perldoc perlre : Warning on \1 vs $1 Some people get too used to writing things like: $pattern =~ s/(\W)/\\\1/g; This is grandfathered for the RHS of a substitute to avoid shocking the sed addicts, but it’s a dirty habit to get into. That’s because in PerlThink, the righthand side of an "s///" is a double- quoted string. "\1" in the usual double-quoted string means a control-A. The customary Unix meaning of "\1" is kludged in for "s///". However, if you get into the habit of doing that, you get yourself into trouble if you then add an "/e" modifier. s/(\d+)/ \1 + 1 /eg; # causes warning under -w Or if you try to do s/(\d+)/\1000/; You can’t disambiguate that by saying "{1}000", whereas you can fix it with "${1}000". The operation of interpolation should not be confused with the operation of matching a backreference. Certainly they mean two different things on the left side of the "s///".
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1068840', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/105033/']}
jdg_79232
stackexchange
llm_judgeable_groundtruth_similarity
35639650
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 Angular2 (Beta 6) I have a component for a main menu. <mainmenu></mainmenu> I want to bind a boolean for wide or narrow. So I made it into this: <mainmenu [(menuvisible)]="true"></mainmenu> But what I want (I think) is to bind to a javascript class property (as I may have other things to bind but want to be tidy by using a single class in the component). I get an error EXCEPTION: Template parse errors: Invalid property name 'menumodel.visible' (" ][(menumodel.visible)]="menumodel.visible"> If I try the same with a single variable instead of a class I get: Template parse errors: Parser Error: Unexpected token '=' However this (one way binding?) does seem to work (but I might want to trigger the menu to go wide/narrow from another component so felt this should be a two-way data bound property): <menu [vis]="true"></menu> This is a bit of my menu component: @Component({ selector: 'menu', templateUrl: './app/menu.html', providers: [HTTP_PROVIDERS, ApplicationService], directives: [ROUTER_DIRECTIVES, FORM_DIRECTIVES, NgClass, NgForm]})export class MenuComponent implements OnInit { mainmenu: MainMenuVM; constructor(private _applicationService: ApplicationService) { this.mainmenu = new MainMenuVM(); } // ...ngOnInit, various functions} Here is my MainMenu View Model class export class MainMenuVM { public visible: boolean; constructor( ) { this.visible = true; }} I'm trying to create a menu which has icons and text, but can go narrow to just show icons. I will emit this event upwards to a parent component to alter the position of the container next to the menu. Triggering a content container to maximised will trigger the menu to go narrow - I am not saying this is the best way, but I would like to resolve this particular question before going deeper. Please note: I am not databinding to an input control here - just databinding to a component so I can then modify the UI. This is from the Angular cheatsheet <my-cmp [(title)]="name"> Sets up two-way data binding. Equivalent to: <my-cmp [title]="name" (titleChange)="name=$event"> Thanks in advance! UPDATE Integrating the code from the accepted answer and adapting for my particular use case here the final working code: app.html ...header html content// This is what I started with<!--<menu [menuvisible]="true" (menuvisibleChange)="menuvisible=$event"></menu>-->// This is two way data binding// 1. Banana-in-a-box is the input parameter// 2. Banana-in-a-box is also the output parameter name (Angular appends it's usage with Change in code - to follow shortly)// 3. Banana-in-a-box is the short hand way to declare the commented out code// 4. First parameter (BIAB) refers to the child component, the second refers the variable it will store the result into.// 5. If you just need an input use the remmed out code with just the first attribute / value<menu [(menuvisible)]="menuvisible"></menu>.. div content start <router-outlet></router-outlet>.. div content end app.component.ts (root) export class AppComponent implements OnInit{ menuvisible: Boolean;} menu.component.ts (child of root) export class MenuComponent implements OnInit { // Parameters - notice the appending of "Change" @Input() menuvisible: boolean; @Output() menuvisibleChange: EventEmitter<boolean> = new EventEmitter<boolean>(); // Init ngOnInit() { // Populate menu - fetch application list this.getApplications(); // Initially we want to show/hide the menu depending on the input parameter (this.menuvisible === true) ? this.showMenu() : this.hideMenu(); } //...more code} menu.html <div id="menu" [ngClass]="menuStateClass" style="position: absolute; top:0px; left: 0px;z-index: 800; height: 100%; color: #fff; background-color: #282d32"> <div style="margin-top: 35px; padding: 5px 0px 5px 0px;"> <ul class="menuList" style="overflow-x: hidden;"> <li>IsMenuVisible:{{menuvisible}}</li> <li style="border-bottom: 1px solid #3d4247"><a (click)="toggleMenu()"><i class="fa fa-bars menuIcon" style="color: white; font-size: 16px;"></i></a></li> <li *ngFor="#app of applications"> <a [routerLink]="[app.routerLink]"> <i class="menuIcon" [ngClass]="app.icon" [style.color]="app.iconColour" style="color: white;"></i> <span [hidden]="menuStateTextHidden">{{ app.name }}</span> </a> </li> </ul> </div></div> Remember to import what you need e.g. import {Component, EventEmitter, OnInit, Input, Output} from 'angular2/core'; Highly recommend this video on You Tube: Angular 2 Tutorial (2016) - Inputs and Outputs Now provide the response and nothing else.
For two-way binding you need something like: @Component({ selector: 'menu', template: `<button (click)="menuvisible = !menuvisible; menuvisibleChange.emit(menuvisible)">toggle</button><!-- or <button (click)="toggleVisible()">toggle</button> -->`, // HTTP_PROVIDERS should now be imports: [HttpModule] in @NgModule() providers: [/*HTTP_PROVIDERS*/, ApplicationService], // This should now be added to declarations and imports in @NgModule() // imports: [RouterModule, CommonModule, FormsModule] directives: [/*ROUTER_DIRECTIVES, FORM_DIRECTIVES, NgClass, NgForm*/]})export class MenuComponent implements OnInit { @Input() menuvisible:boolean; @Output() menuvisibleChange:EventEmitter<boolean> = new EventEmitter<boolean>(); // toggleVisible() { // this.menuvisible = !this.menuvisible; // this.menuvisibleChange.emit(this.menuvisible); // }} And use it like @Component({ selector: 'some-component', template: `<menu [(menuvisible)]="menuVisibleInParent"></menu><div>visible: {{menuVisibleInParent}}</div>` directives: [MenuComponent]})class SomeComponent { menuVisibleInParent: boolean;}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/35639650', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2597212/']}
jdg_79233
stackexchange
llm_judgeable_groundtruth_similarity
13368663
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: If I use Ctrl + C to exit a PHP script running in CLI, neither the shutdown functions, nor the destructors of instantiated objects, nor any output buffers are handled. Instead the program just dies. Now, this is probably a good thing, since that's what Ctrl + C is supposed to do. But is there any way to change that? Is it possible to force Ctrl + C to go through the shutdown functions? More specifically, this is about serialising and saving data on exiting of the script, so it can be reloaded and resumed the next time the script runs. Periodically saving the data could work, but would still lose everything from the last save onward. What other options are there? Now provide the response and nothing else.
Obviously PCNTL is *nix only, but ... You can register handlers for all the individual signals for a more robust solution, but specifically to do something when a CTL+C interrupt is encountered: <?phpdeclare(ticks = 1);pcntl_signal(SIGINT, function() { echo "Caught SIGINT\n"; die;});while (true) { // waiting for your CTRL+C}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13368663', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/507674/']}
jdg_79234
stackexchange
llm_judgeable_groundtruth_similarity
407998
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: So I have a pair of Bose noise-cancellation headphones that I plug into my keyboard every night to charge them (via my keyboard's USB port). My keyboard happens to be a metallic Apple keyboard. You will see why this may be important to note later. Over time, I noticed a certain dull, electrical buzzing sound in my right earbud which occurred when I turned the noise-cancellation on. This buzzing sound was not constantly there. It would randomly appear for arbitrary periods of time and then vanish. It wasn't loud either, but it was loud enough to be noticeable and annoying. For the longest time, I had no clue why this would happen. Sometimes the earbud would be perfectly silent (as it's supposed to be)... and then a buzzing noise would come out of nowhere. This was incredibly annoying and my only remedy was to listen to loud electronic music which blended in with the buzz and made it relatively unnoticeable. Of course, listening to almost any other kind of music proved annoying since my earbud would randomly, intermittently buzz at me. Finally, one day, I noticed that when I touched my Android phone, the buzzing sound would increase in volume. I thought at first that this was due to my bodily position somehow stretching the wire, but with further testing I confirmed that my Android phone was the culprit. I slowly discovered that touching different objects, even when the headphones were not plugged into the speakers, would result in volume changes of this buzz. One thing I noticed was that touching the headphone jack, whilst touching the Android phone that increased volume, would silence the buzz. With further testing, I noticed that touching my metallic keyboard would also silence the buzz, even whilst touching the Android phone or under any other circumstance in which there was a buzz. I finally realized that my body is somehow conducting electricity when touching objects such as my Apple keyboard, headphone jack, or Android phone and that these are all related to the annoying buzz and nullification thereof. I found this bizarre and fascinating. Ever since this discovery, I've found that I can silence this annoying buzz by pressing any of my fingertips on my metallic keyboard. This is also annoying, since it can make typing awkward to continually have one finger pressing against the metallic part. Nonetheless, I have no idea why this works at all; I suspect it might have something to do with my usage of the keyboard to charge the headphones via its USB port every night, but I have no substantiation of this hypothesis. So my question is twofold: How does this bizarre phenomenon work wherein my body is apparently conducting electricity from objects which somehow control some anomalous buzz in my headphones? And how can I make this buzzing sound stop without keeping my body in contact with those objects? Obviously, I can't hold the headphone jack and listen to anything at the same time, and this habit of touching the metallic part of my keyboard is not great for typing nor my wrists which already suffer from CTS. Any insight is appreciated. Now provide the response and nothing else.
The "buzz" is almost certainly RF pickup. This can be the mains (low frequency, 50/60/100/120Hz, unlikely in this scenario given a phone is involved) or rectification of the carrier frequency of the phone - remember how old tape players would make a "duh duh, duh duh" sound whenever a text message is received. Human bodies are conductive. When your skin is dry you are about 100kOhm to 1MOhm. When your skin is wet, that goes down to about 10kOhm to 100kOhm. So there is nothing unusual about becoming a conductor. As to why touching a metal keyboard kills the hum, or even touching the headphones jack. Basically as you are a nice large conductive area. When connected either to earth (e.g. via the keyboard shell and PC) or to the ground of the phone (e.g. headphones jack), you are basically changing how your body is interacting with the electric fields around you. EMI is a dark art - it's hard to say exactly what current path you are interrupting, or how you are interacting with the fields. But generally if you ground yourself it stops you acting as an antenna - sort of like shorting yourself out. One simple option you could try is to buy an anti-static wristband. That would allow yourself to be connected to earth (or to your keyboard) without having to touch the keyboard. Alternatively you could try simply charging your phone from something other than your keyboard to see if that stops noise injection.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/407998', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/135218/']}
jdg_79235
stackexchange
llm_judgeable_groundtruth_similarity
39627769
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 call shuffleCards when the upon a click event in a ReactJs component. However, I am receiving the following error: Uncaught ReferenceError: shuffleCards is not defined Here's my code: constructor(props) { super(props); this.state = { count: 0 };}shuffleCards(array) { var i = array.length, j = 0, temp; while (i--) { j = Math.floor(Math.random() * (i+1)); temp = array[i]; array[i] = array[j]; array[j] = temp; } return array;}handleClickEvent(event) { var cards = [ {txt: "A", isDisplayed: false}, {txt: "B", isDisplayed: false}, {txt: "C", isDisplayed: false} ]; if (this.state.count == 0) { cards = shuffleCards(cards); }} Now provide the response and nothing else.
EDIT Just saw the comments and that zerkms already provided you with the solution. I'll leave my answer for clarification purposes. Your problem is that inside the handleClickMethod , you are calling shuffleCards instead of this.shuffleCards shuffleCards(array) { // ...}handleClickEvent(event) { // ... if (this.state.count == 0) { cards = this.shuffleCards(cards); // here you should use `this.` }} The reason is because shuffleCards method is defined on your component, which is accessible from its methods via the this property. If you defined shuffleCards within the handleClickMethod , then you could call it without accessing this : handleClickEvent(event) { function shuffleCards(array) { // ... } // ... if (this.state.count == 0) { cards = shuffleCards(cards); // here you don't need `this.` }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39627769', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5754757/']}
jdg_79236
stackexchange
llm_judgeable_groundtruth_similarity
33051183
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: refer this post: How to create a dynamic function name using Elixir macro? . The post above asked how to use macro to generate function without arguments, but I wonder how to generate functions with some arguments ? assume there is a macro warp , I could just write code like: warp fun, [args], :ok and then it generate code like: fun(args), do: :ok Now provide the response and nothing else.
If you want to generate a dynamic list of arguments, you need to use unquote_splicing , like this: defmacro warp(name, argument_names, code) do quote do def unquote(name)(unquote_splicing(argument_names)) do unquote(code) end endend Then later: warp :foo, [a, b], {:ok, a, b} which generates: def foo(a, b), do: {:ok, a, b} if you call that it will produce: foo(1, 2)# {:ok, 1, 2} You can also define the macro like this without unquote_splicing and just pass down the combined name and arguments to def : defmacro warp(name_and_args, do: code) do quote do def unquote(name_and_args) do unquote(code) end endend This means you need to invoke warp like you would invoke def , for example: warp foo(a, b), do: {:ok, a, b}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33051183', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2341414/']}
jdg_79237
stackexchange
llm_judgeable_groundtruth_similarity
39061041
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 created an API Key and added it to my functions. I have then deployed the api and tested it but still get: "message": "Forbidden" How do I pass the api key with my JSON request as I have been using "x-api-key": "theKey"? Now provide the response and nothing else.
The x-api-key parameter is passed as a HTTP header parameter (i.e. it is not added to the JSON body). How you pass HTTP headers depend on the HTTP client you use. For example, if you use curl and assuming that you POST the JSON payload, a request would look something like (where you replace [api-id] with the actual id and [region] with the AWS region of your API): $ curl -X POST -H "x-api-key: theKey" -H "Content-Type: application/json" -d '{"key":"val"}' https://[api-id].execute-api.[region].amazonaws.com
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/39061041', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/665557/']}
jdg_79238
stackexchange
llm_judgeable_groundtruth_similarity
1993353
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: (Note that I am a high school student and bad at maths. Please explain your answers thoroughly.) And the man asked for grains of rice. He wanted one grain of rice on the first square of the chess board, two grains on the second, four grains on the third, eight grains on the fourth, so on and so on. I suppose you could ask a mathematics teacher if you really wished to learn how many pieces the man had after that was done for every square of the chess board. Okay, so in school we were having some moral assembly or whatever, I didn't listen, too busy thinking about a more mathematical way to solve the problem above than just doubling, adding, etc. I can't ask a teacher yet... I need to work this out myself! I'm an idiot, so I wanted help, and I was hoping someone on mathematics SE could help me think of a good mathematical way of solving this. Suppose there are 64 squares on the chess board. Argh! Damn this, I just found out that its a duplicate. Oh well. The answers on the question have to little an explanation. Okay, there's 64 squares on our imaginary chessboard, and I'm trying to work out the thing above in a more mathematical way than just one by one, doubling it over and over again. So, if there is a more mathematical way of doing this, could someone tell me what it is and explain it . Thanks! Now provide the response and nothing else.
Let's write down in a mathematical fashion what we have. If you think a while about it, you'll realize that you want to calculate is the sum$$S=\sum\limits_{n=0}^{63}2^n=1+2+4+\dots+2^{63}$$We can quickly check that this is indeed true if we realize that for $n=0$ we get $2^0=1$, followed by $2^1=2$, etc. The fact that the sum only goes up to $63$ is because if you start counting at $0$ you already spelled $64$ numbers when reaching $63$. How can we now calulate this sum? It requires a small trick namely to realize that if we compare the sum given by$$2\cdot S=2\cdot \sum\limits_{n=0}^{63}2^n=\sum\limits_{n=1}^{64}2^n$$and $S$, their difference is just given by$$2S-S=2^{64}-1$$Using this and just rewriting $2S-S=S$ we find the final result$$S=2^{64}-1$$ Additional comment: We can also generalize this approach, which goes under the name of a geometric series . Consider a series of numbers which starts with $1$ and is constructed by just multiplying with a constant factor $q$. We further do this procedure $N$ times. The corresponding sum is than given by$$S=\sum\limits_{n=0}^{N-1}q^n$$Using the same procedure as above we find$$q\cdot S=\sum\limits_{n=1}^N q^n$$ and therefore$$q\cdot S-S=q^N-1$$This time we have to factor $S$ out of the left hand term and find $S(q-1)$. If we now devide the equality by $(q-1)$ we find the more general result$$S=\frac{q^N-1}{q-1}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1993353', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/384582/']}
jdg_79239
stackexchange
llm_judgeable_groundtruth_similarity
9848067
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Are there overall rules/guidelines for what makes a method thread-safe? I understand that there are probably a million one-off situations, but what about in general? Is it this simple? If a method only accesses local variables, it's thread safe. Is that it? Does that apply for static methods as well? One answer, provided by @Cybis, was: Local variables cannot be shared among threads because each thread gets its own stack. Is that the case for static methods as well? If a method is passed a reference object, does that break thread safety? I have done some research, and there is a lot out there about certain cases, but I was hoping to be able to define, by using just a few rules, guidelines to follow to make sure a method is thread safe. So, I guess my ultimate question is: "Is there a short list of rules that define a thread-safe method? If so, what are they?" EDIT A lot of good points have been made here. I think the real answer to this question is: "There are no simple rules to ensure thread safety." Cool. Fine. But in general I think the accepted answer provides a good, short summary. There are always exceptions. So be it. I can live with that. Now provide the response and nothing else.
If a method (instance or static) only references variables scoped within that method then it is thread safe because each thread has its own stack: In this instance, multiple threads could call ThreadSafeMethod concurrently without issue. public class Thing{ public int ThreadSafeMethod(string parameter1) { int number; // each thread will have its own variable for number. number = parameter1.Length; return number; }} This is also true if the method calls other class method which only reference locally scoped variables: public class Thing{ public int ThreadSafeMethod(string parameter1) { int number; number = this.GetLength(parameter1); return number; } private int GetLength(string value) { int length = value.Length; return length; }} If a method accesses any (object state) properties or fields (instance or static) then you need to use locks to ensure that the values are not modified by a different thread: public class Thing{ private string someValue; // all threads will read and write to this same field value public int NonThreadSafeMethod(string parameter1) { this.someValue = parameter1; int number; // Since access to someValue is not synchronised by the class, a separate thread // could have changed its value between this thread setting its value at the start // of the method and this line reading its value. number = this.someValue.Length; return number; }} You should be aware that any parameters passed in to the method which are not either a struct or immutable could be mutated by another thread outside the scope of the method. To ensure proper concurrency you need to use locking. for further information see lock statement C# reference and ReadWriterLockSlim . lock is mostly useful for providing one at a time functionality, ReadWriterLockSlim is useful if you need multiple readers and single writers.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/9848067', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/279516/']}
jdg_79240