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
21551314
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm using gfortran -std=f2008. I have a function that returns a derived type which contains an allocatable array. The function calls allocate() before it returns. It seems like the array is being automatically deallocated some time after the function that allocated the array has returned, and my program segfaults. When does automatic deallocation occur? Should I be coding this in a different way? Now provide the response and nothing else.
A universal answer: allocatable arrays are automatically deallocated when going out of scope. Function results are automatically deallocated after the result is "used" in the outer scope. Allocatable components are deallocated, when the parent derived type variable is going out of scope, or when it is deallocated. Only pointers , that pointed to the function results are undefined after the deallocation and shall not be used. If you do that, it could cause the problems you describe. Also, when an array is automatically reallocated on assignment, the pointers to it become undefined (but may not change, actually). In other words, problems you describe shouldn't occur when the allocatables are used correctly.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21551314', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/150884/']}
jdg_369741
stackexchange
llm_judgeable_groundtruth_similarity
11685608
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 convention OpenGL follows for cubemaps? I followed this convention (found on a website) and used the correspondent GLenum to specify the 6 faces GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT but I always get wrong Y, so I have to invert Positive Y with Negative Y face. Why? ________ | | | pos y | | | _______|________|_________________ | | | | | | neg x | pos z | pos x | neg z | | | | | | |_______|________|________|________| | | | | | neg y | |________| Now provide the response and nothing else.
but I always get wrong Y, so I have to invert Positive Y with Negative Y face. Why? Ah, yes, this is one of the most odd things about Cube Maps. Rest assured, you're not the only one to fall for it. You see: Cube Maps have been specified to follow the RenderMan specification (for whatever reason), and RenderMan assumes the images' origin being in the upper left, contrary to the usual OpenGL behaviour of having the image origin in the lower left. That's why things get swapped in the Y direction. It totally breaks with the usual OpenGL semantics and doesn't make sense at all. But now we're stuck with it. Take note that upper left, vs. lower left are defined in the context of identity transformation from model space to NDC space
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11685608', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/914693/']}
jdg_369742
stackexchange
llm_judgeable_groundtruth_similarity
7677333
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How can I use In clause in Hive I want to write something like this in Hive select x from y where y.z in (select distinct z from y) order by x;But I am not finding any way of doing it..I tried In clause in Hive 0.7 it was throwing error, Also I tried Find_in_Set ..using find_in_set(y.z,subquery).. but the job is getting failed. I want to do this on Hive. Please help me if anybody knows how to do this in Hive.. Thanks & Regards,Atul Now provide the response and nothing else.
You can use semi join( https://cwiki.apache.org/Hive/languagemanual-joins.html ): LEFT SEMI JOIN implements the correlated IN/EXISTS subquery semantics in an efficient way. Since Hive currently does not support IN/EXISTS subqueries, you can rewrite your queries using LEFT SEMI JOIN. The restrictions of using LEFT SEMI JOIN is that the right-hand-side table should only be referenced in the join condition (ON-clause), but not in WHERE- or SELECT-clauses etc. SELECT a.key, a.value FROM a WHERE a.key in (SELECT b.key FROM B); can be rewritten to: SELECT a.key, a.val FROM a LEFT SEMI JOIN b on (a.key = b.key)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7677333', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/722856/']}
jdg_369743
stackexchange
llm_judgeable_groundtruth_similarity
2508467
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_1 : X_1 \to Y_1 $ and $f_2 : X_2 \to Y_2 $. I'm asked to show that $$f_1 \times f_2 : X_1 \times X_2 \to Y_1 \times Y_2 $$ is proper if and only if $f_i$ are. But I couldn't think of a way to approach since I really couldn't figure out how $f_1 \times f_2$ is defined? Is it just the product of functions? If so, How can I define the inverse of this product? Say $U \subset Y_1 \times Y_2$ is compact, and if I assume the product is proper then does that mean $f_1^{-1} (U) \ f_2^{-1} (U)$ is compact? Any hints? Now provide the response and nothing else.
Let $S_n = \sum\limits_{i=1}^n X_i$ Since for all $j:1\leq j\leq n$, the random variables $X_j$ are independent and identically distributed, then $\mathsf E(X_j\mid S_n)$ all have the same values.   It is a matter of symmetry. $$\begin{align}\mathsf E(X_j\mid S_n) &= \tfrac 1n\sum_{i=1}^n\mathsf E(X_i\mid S_n) &&\text{Symmetry, }\forall j\in\{1..n\}\\[1ex] & = \tfrac 1n\mathsf E(\sum_{i=1}^n X_i\mid S_n) && \text{Linearity of Expectation}\\[1ex] &= \tfrac 1n \mathsf E(S_n\mid S_n) && \text{by definition of } S_n\\[1ex] & = \tfrac 1n S_n &&\text{clearly }\mathsf E(S_n\mid S_n)=S_n \\[2ex]\therefore\quad\mathsf E(X_j\mid \sum_{i=1}^n X_i) & = \tfrac 1n\sum_{i=1}^n X_i&&\text{when }{(X_j)}_{j\in\{1..n\}}\text{ are iid.}\end{align}$$That is all you need.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2508467', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/395613/']}
jdg_369744
stackexchange
llm_judgeable_groundtruth_similarity
53651
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: Twitter user Leonydus Johnson posted the following statistics acquired from the FBI UCR Program website and the Washington Post: For every 10,000 black people arrested for violent crime, 3 are killed For every 10,000 white people arrested for violent crime, 4 are killed" He claims that they show that there is not pervasive racial bias in the way African-Americans are treated by the police in the United States. Are these statistics misleading or potentially inaccurate in any way? Now provide the response and nothing else.
First, the claim is not exactly well defined. The FBI data gives arrest rates per arrest type, while the Washington Post gives deaths per population, so it's not clear if the numbers presented are meaningful or how the author arrived at that conclusion. Additionally, it's unclear how to normalize events that can be repeated vs not; that is, a single person can be arrested multiple times in a year , while they can presumably only be killed once. And additionally, he didn't discuss the impact of race on the likeliness of being arrested in the first place (more on this below). Second, the lead of the Washington Post's "Fatal Force" project (source of the twitter data) responded to the post on twitter saying, Hey. You’re making this argument based on my data. Your conclusions are factually inaccurate Now, for your question: These seem to indicate that there is not pervasive racial bias in the US police force. Are these statistics misleading or potentially inaccurate in any way? While the twitter post linked to the 2018 dataset, the current 2020 version , has this summary at the end Although half of the people shot and killed by police are white, black Americans are shot at a disproportionate rate. They account for less than 13 percent of the U.S. population, but are killed by police at more than twice the rate of white Americans. Hispanic Americans are also killed by police at a disproportionate rate. So, in absolute terms, there are more white people killed by police. This is perhaps not surprising since the dataset lists that population as almost four times larger than any other ethnicity. But as pointed out above, "The rate at which black Americans are killed by police is more than twice as high as the rate for white Americans. [em. original]" For further reading, I would recommend this Washington Post article outlining a number of studies evaluating systemic racism related to the criminal justice system. Of particular concern to some on the right is the term “systemic racism,” often wrongly interpreted as an accusation that everyone in the system is racist. In fact, systemic racism means almost the opposite. It means that we have systems and institutions that produce racially disparate outcomes, regardless of the intentions of the people who work within them. There are some dissenting studies listed above, but the majority of studies point out that non-whites are disproportionately represented at each step of the criminal justice system (being pulled over; arrest; jail; bond disparity; prison sentence harshness; probation being revoked; parole). Are these statistics misleading? Statistics are notoriously difficult to get right, and easily manipulated (lies, damn lies, and statistics). The author's intent seemed to be to challenge whether police killings are racially biased. And there was a study on the list WaPo page that said class (income) was the most important factor when determining police engagement frequency. But with all the other data, and including comments from the original author lead, I'm skeptical that the post on twitter holds merit.
{}
{'log_upvote_score': 4, 'links': ['https://politics.stackexchange.com/questions/53651', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/30919/']}
jdg_369745
stackexchange
llm_judgeable_groundtruth_similarity
131883
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have two lists: x = Range[1, 10, 1]y = Range[2, 10, 2] How can I produce a list consisting of the following elements (first element is the x value, second element the y value and third element some combination of it e.g. here the sum): {{x[[1]], y[[1]], x[[1]] + y[[1]]},...{x[[1]], y[[5]], x[[1]] + y[[5]]},.........{x[[10]], y[[1]], x[[10]] + y[[1]]},...{x[[10]], y[[5]], x[[10]] + y[[5]]}}={{1,2,3},...{1,10,11},.........{10,2,12},...{10,10,20}} Now provide the response and nothing else.
A more Mathematica-ish/functional approach than Do is as follows: x = Range[1, 10, 1];y = Range[2, 10, 2];Flatten[Outer[{#1, #2, #1 + #2} &, x, y], 1]
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/131883', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/43863/']}
jdg_369746
stackexchange
llm_judgeable_groundtruth_similarity
316096
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 noticed that if you drop a flat surface, parallelly from a relatively low height, onto another, the impact is almost cushioned. What is happening here? Is this to do with the air, especially near the centre, not being able to escape, thus applying a repulsive pressure? Now provide the response and nothing else.
What is happening is that there is a volume of air under the thing being dropped, which has to make its way out the sides. As the distance gets smaller, the air pressure under the object increases while the air is escaping. Try a flat board, then drill some holes in the board that account for maybe 10% of its area. Despite being 10% lighter, the board will then land much faster since you have provided a lot more area for the air to escape. Of course in a vacuum, no difference and even a very light flat object would just slam down.
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/316096', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/98739/']}
jdg_369747
stackexchange
llm_judgeable_groundtruth_similarity
39832958
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: As I brought up in this question , gcc is removing (yes, with -O0 ) a line of code _mm_div_ss(s1, s2); presumably because the result is not saved. However, this should trigger a floating point exception and raise SIGFPE, which can't happen if the call is removed. Question : Is there a flag, or multiple flags, to pass to gcc so that code is compiled as-is? I'm thinking something like fno-remove-unused but I'm not seeing anything like that. Ideally this would be a compiler flag instead of having to change my source code, but if that isn't supported is there some gcc attribute/pragma to use instead? Things I've tried: $ gcc --help=optimizers | grep -i remove no results. $ gcc --help=optimizers | grep -i unused no results. And explicitly disabling all dead code/elimination flags -- note that there is no warning about unused code: $ gcc -O0 -msse2 -Wall -Wextra -pedantic -Winline \ -fno-dce -fno-dse -fno-tree-dce \ -fno-tree-dse -fno-tree-fre -fno-compare-elim -fno-gcse \ -fno-gcse-after-reload -fno-gcse-las -fno-rerun-cse-after-loop \ -fno-tree-builtin-call-dce -fno-tree-cselim a.ca.c: In function ‘main’:a.c:25:5: warning: ISO C90 forbids mixed declarations and code [-Wpedantic] __m128 s1, s2; ^$ Source program #include <stdio.h>#include <signal.h>#include <string.h>#include <xmmintrin.h>static void sigaction_sfpe(int signal, siginfo_t *si, void *arg){ printf("%d,%d,%d\n", signal, si!=NULL?1:0, arg!=NULL?1:0); printf("inside SIGFPE handler\nexit now.\n"); exit(1);}int main(){ struct sigaction sa; memset(&sa, 0, sizeof(sa)); sigemptyset(&sa.sa_mask); sa.sa_sigaction = sigaction_sfpe; sa.sa_flags = SA_SIGINFO; sigaction(SIGFPE, &sa, NULL); _mm_setcsr(0x00001D80); __m128 s1, s2; s1 = _mm_set_ps(1.0, 1.0, 1.0, 1.0); s2 = _mm_set_ps(0.0, 0.0, 0.0, 0.0); _mm_div_ss(s1, s2); printf("done (no error).\n"); return 0;} Compiling the above program gives $ ./a.outdone (no error). Changing the line _mm_div_ss(s1, s2); to s2 = _mm_div_ss(s1, s2); // add "s2 = " produces the expected result: $ ./a.outinside SIGFPE handler Edit with more details. This appears to be related to the __always_inline__ attribute on the _mm_div_ss definition . $ cat t.cintdiv(int b){ return 1/b;}int main(){ div(0); return 0;}$ gcc -O0 -Wall -Wextra -pedantic -Winline t.c -o t.out$ (no warnings or errors) $ ./t.outFloating point exception$ vs below (same except for function attributes) $ cat t.c__inline int __attribute__((__always_inline__))div(int b){ return 1/b;}int main(){ div(0); return 0;}$ gcc -O0 -Wall -Wextra -pedantic -Winline t.c -o t.out$ (no warnings or errors) $ ./t.out$ Adding the function attribute __warn_unused_result__ at least gives a helpful message: $ gcc -O0 -Wall -Wextra -pedantic -Winline t.c -o t.outt.c: In function ‘main’:t.c:9:5: warning: ignoring return value of ‘div’, declared with attribute warn_unused_result [-Wunused-result] div(0); ^ edit: Some discussion on the gcc mailing list . Ultimately, I think everything is working as intended. Now provide the response and nothing else.
GCC doesn't "optimize out" anything here. It just doesn't generate useless code. It seems to a very common illusion that there's some pure form of code that the compiler should generate and any changes to that are an "optimization". There is no such thing. The compiler creates some data structure that represents what the code means, then it applies some transformations on that data structure and from that it generates assembler that then gets compiled down to instructions. If you compile without "optimizations" it just means that the compiler will only do the least effort possible to generate code. In this case, the whole statement is useless because it doesn't do anything and is thrown away immediately (after expanding the inlines and what the builtins mean it is equivalent to writing a/b; , the difference is that writing a/b; will emit a warning about statement with no effect while the builtins probably aren't handled by the same warnings). This is not an optimization, the compiler would actually have to expend extra effort to invent meaning to a meaningless statement, then fake a temporary variable to store the result of this statement to then throw it away. What you're looking for is not flags to disable optimizations, but pessimization flags. I don't think any compiler developers waste time implementing such flags. Other than maybe as an April fools joke.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/39832958', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1462295/']}
jdg_369748
stackexchange
llm_judgeable_groundtruth_similarity
38769103
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Browser is Chrome, document.currentScript should be supported but index.html <link href="css/main.css" rel="stylesheet" /><script src="1.js"></script><style> 1.js setInterval(function() { var fullUrl = document.currentScript.src; console.log(fullUrl)},2000) Error : 1.js:4 Uncaught TypeError: Cannot read property 'src' of null Now provide the response and nothing else.
document.currentScript only returns the script that is currently being processed . During callbacks and events, the script has finished being processed and document.currentScript will be null . This is intentional, as keeping the reference alive would prevent the script from being garbage collected if it's removed from the DOM and all other references removed. If you need to keep a reference to the script outside of any callbacks, you can: var thisScript = document.currentScript;setInterval(() => console.log(thisScript.src), 2000);
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/38769103', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1673376/']}
jdg_369749
stackexchange
llm_judgeable_groundtruth_similarity
6409
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have an old computer, an ABC80 from the late seventies or early eighties, in which I have reason to believe one or more of the voltage regulators are broken. Now I wonder, what may be suitable replacement parts? I know that similarly named parts are still produced, but I am not sure about the details. What about this for a 7805 replacement ? Now provide the response and nothing else.
You can replace them with any equivalent regulator, so long as it is better in terms of current rating and in the same package. For example, don't replace a 79M12 with a 79L12, because the M indicates a MEDIUM current level and is about 500mA-1A, while the L indicates a LOW current level which is usually ~100mA. You could replace the 7805 with 7805 in a TO-220 package. The 79M12 could be replaced by any 7912 rated for ~1A. Back in the day when that computer was produced, it was more expensive to produce a regulator which could do 1A vs. one which could do 500mA. It's still the same, but as manufacturing methods have improved, the price gap has shrunk.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/6409', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/1877/']}
jdg_369750
stackexchange
llm_judgeable_groundtruth_similarity
10671602
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I use eval() in my current project like this: if (class_exists($class_name)) //$class_name depends on user input eval($class_name.'::MyStaticMethod()'); eval() is executed if and only if class with the name $class_name exists so it's kinda safe, but I still don't think that this is the best solution. Can I do the same what code above does without eval() ? Now provide the response and nothing else.
I have recently answered this question . The last part of my answer perfectly answers this question and is much more useful for future readers than answers provided here. That's why I am answering my own question. PHP has features that gives possibility to avoid using eval in most cases: PHP is very dynamic language. It has ability to do following stuff with strings : Define and/or get variable (supported from PHP 4.3). For example: $variableName = 'MyVariable';// Create new variable with the name defined in variable $variableName${$variableName} = 'MyValue';//Outputs: string(7) "MyValue"var_dump($MyVariable);//Outputs: string(7) "MyValue"var_dump(${'MyVariable'}); Demo Call function (supported from PHP 4.3). For example: // Create function with the name defined in variable $functionNamefunction MyFunction($argument) { return 'Argument passed is: '.$argument;}$functionName = 'MyFunction';// Outputs:// string(48) "Argument passed is: Calling MyFunction directly."var_dump(MyFunction('Calling MyFunction directly.'));// Outputs:// string(51) "Argument passed is: Calling MyFunction with string."var_dump($functionName('Calling MyFunction with string.')); Demo Create instance of class (supported from PHP 5.0). For example: class MyClass { public function __construct() { echo 'Constructing MyClass'."\n"; }}$className = 'MyClass';$objFromString = new $className();// Outputs: object(MyClass)#1 (0) {}var_dump($objFromString); Demo Call static method (supported from PHP 5.0). For example: class MyClass { public static function staticMethod() { return 'MyClass::staticMethod called'; }}$staticMethodName = 'staticMethod';// Outputs: string(28) "MyClass::staticMethod called"var_dump(MyClass::$staticMethodName()); Demo And from PHP 5.3 class name can also be defined by string. Example: class MyClass { public static function staticMethod() { return 'MyClass::staticMethod called'; }}$className = 'MyClass';$staticMethodName = 'staticMethod';var_dump($className::$staticMethodName());var_dump($className::staticMethod()); Demo Call instance method of object (supported from PHP 5.0). For example: class MyClass { public function instanceMethod() { return 'MyClass::instanceMethod called'; }}$methodName = 'instanceMethod';$obj = new MyClass();// Outputs: string(30) "MyClass::instanceMethod called"var_dump($obj->$methodName()); Demo Access static and instance properties of object (supported from PHP 5.0). For example: class MyClass { public static $myStaticProperty; public $myInstanceProperty;}$staticPropertyName = 'myStaticProperty';$instancePropertyName = 'myInstanceProperty';MyClass::${$staticPropertyName} = 'my static value';$obj = new MyClass();$obj->{$instancePropertyName} = 'my instance value';var_dump(MyClass::${$staticPropertyName});var_dump($obj->{$instancePropertyName}); Demo PHP has two functions: call_user_func and call_user_func_array for dynamic function/method calls. Both are perfectly documented so I won't go in details here. Even if everything above is not enough PHP 5 comes with great Reflection API . Unfortunately, documentation has few examples but reflection is quite large topic to cover here. Basically, It's not a big deal to use reflection after reading how it works.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10671602', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1283847/']}
jdg_369751
stackexchange
llm_judgeable_groundtruth_similarity
25445837
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: ViewController has definesPresentationContext and providesPresentationContextTransitionStyle ,but have no idea about how they work.I watched the WWDC2011, but I'm still confused about these two things. Could anyone explain this, preferably with a simple demo? Now provide the response and nothing else.
Both properties are used for view controller containment, and provide child view controllers the option to override the presentation context or presentation style of the window's root view controller. For reference, here is the relevant WWDC presentation that provides an explanation of both: https://developer.apple.com/videos/play/wwdc2011-102/ definesPresentationContext is used to decide which view controller will determine the size of the presented view controller's view: When a view controller is presented, iOS starts with the presenting view controller and asks it if it wants to provide the presentation context. If the presenting view controller does not provide a context, then iOS asks the presenting view controller's parent view controller. iOS searches up through the view controller hierarchy until a view controller provides a presentation context. If no view controller offers to provide a context, the window's root view controller provides the presentation context. If a view controller returns YES, then it provides a presentation context. The portion of the window covered by the view controller's view determines the size of the presented view controller's view. The default value for this property is NO. providesPresentationContextTransitionStyle is used to decide which modal presentation style should be used when presenting a child view controller: When a view controller’s definesPresentationContext property is YES, it can replace the transition style of the presented view controller with its own. When the value of this property to YES, the current view controller’s transition style is used instead of the style associated with the presented view controller. When the value of this property is NO, UIKit uses the transition style of the presented view controller. The default value of this property is NO. For complex child view controllers such as UISearchController, it's a good idea to have these set to true, the default value is false.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/25445837', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3378775/']}
jdg_369752
stackexchange
llm_judgeable_groundtruth_similarity
46080504
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 created a Development Endpoint in the AWS Glue console and now I have access to SparkContext and SQLContext in gluepyspark console. How can I access the catalog and list all databases and tables? The usual sqlContext.sql("show tables").show() does not work. What might help is the CatalogConnection Class but I have no idea in which package it is. I tried importing from awsglue.context and no success. Now provide the response and nothing else.
I spend several hours trying to find some info about CatalogConnection class but haven't found anything. (Even in the aws-glue-lib repository https://github.com/awslabs/aws-glue-libs ) In my case I needed table names in Glue Job Script console Finally I used boto library and retrieved database and table names with Glue client: import boto3client = boto3.client('glue',region_name='us-east-1')responseGetDatabases = client.get_databases()databaseList = responseGetDatabases['DatabaseList']for databaseDict in databaseList: databaseName = databaseDict['Name'] print '\ndatabaseName: ' + databaseName responseGetTables = client.get_tables( DatabaseName = databaseName ) tableList = responseGetTables['TableList'] for tableDict in tableList: tableName = tableDict['Name'] print '\n-- tableName: '+tableName Important thing is to setup the region properly Reference:get_databases - http://boto3.readthedocs.io/en/latest/reference/services/glue.html#Glue.Client.get_databases get_tables - http://boto3.readthedocs.io/en/latest/reference/services/glue.html#Glue.Client.get_tables
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46080504', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5970602/']}
jdg_369753
stackexchange
llm_judgeable_groundtruth_similarity
343943
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 was working on migrating over a project which uses a static logger, and a static email service. The email service logs emails sent, and the logger service sends an email if there are any logging issues (like DB down, etc.). If the email service fails, it can also log the issue. If the logger fails, it tries to send an email notice, but if the email service fails (which could be why the logger was called in the first place), it just continues on and writes the issue to a log file. Email Service <--statically references--> Logger Service The issue is that both "services" are singletons, and both would need reference to each other as a constructor parameter. My first thought was property based injection, but I quickly found that seems to be a Temporal Coupling situation that is much undesired. The main running idea now is, at the log level, have it call the service provider to create an email service (so it will get the singleton instance), but I was really trying to keep the class library also decoupled from the .Net Core injection system. Anyone have any recommendations in case I'm missing something? Edit: After more thought, does it make sense perhaps to create an abstracted service provider of my own (a basic one) that can have another service injected into it? Then I could perhaps just pass that around instead in such cases. Now provide the response and nothing else.
I suggest you to read a great book about the C# dependency injection by Mark Seemann, with a lot of real world samples for different tasks you can do with it, even with circular dependencies similar to your case. In general, the main design rule is You can't resolve the problem on its level , and in this case it's true too. You really need a mediator here to resolve interactions between two loggers. It easily can save the state for both of them, and notify each other about changes. For example, you can introduce some Target for the messages, like this: GeneralMessage // both loggers got thisEmailMessage // only email logger got thisLoggerMessage // only logger got this So, in case of some trouble with one of your loggers, mediator send the message with corresponding type to notify other about issue. Common approach for such cutting-edge logic is an AOP implementation (personally I prefer the PostSharp , which provides you a general approach, even with conventional techniques to assign the aspects on your classes). As for decoupling your code from the .Net Core injection system, I suggest you to examine the Logger Factory , which is: The new framework creates an abstraction layer or wrapper that enables you to use whichever logging framework you want as a provider. This ensures you have the maximum flexibility in your work as a developer. Furthermore, even though it’s only available with .NET Core , referencing .NET Core NuGet packages like Microsoft.Extensions.Logging for a standard Visual Studio .NET 4.6 project is no problem. With Logger Factory you can even filter the messages to notify the all loggers about problems with other ones, connect to OS event logs and much more.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/343943', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/96377/']}
jdg_369754
stackexchange
llm_judgeable_groundtruth_similarity
48157580
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 interested in downloading my transactions from Chase without using a third party such as Mint, Quicken, Yodlee, Plaid, and so on. I don't trust third parties with handling my data, which is why I want to do it myself. Now provide the response and nothing else.
Works as of 1/8/18 Summary Chase uses OFX to support programmatic interactions with its financial data. It does so somewhat reluctantly however, as this fact isn't widely advertised nor well documented - banks would rather have you use their products directly, rather than go to third parties. That being said, support for desktop products like Quicken still exists, and so one method is to spoof yourself as a desktop product (the other options are to use a third party service or use a screen scraper). Obviously this solution is completely at the mercy of Chase's whims, and as a discouraged access pattern this is not robust. But you're still reading, so let's do this! Solution Set up your account to accept connections from Desktop appsAccount > Profile & Settings > Manage Account Security > Desktop apps > Click enable Generate a Client UID. Chase will use this to verify that the OFX requests it's receiving are intended.Go to https://www.uuidgenerator.net/ and generate a UID. Use ofx-ba-tfb.py to POST the following to https://ofx.chase.com . Comments begin with a # sign, do not include them. Headers: OFXHEADER:100DATA:OFXSGMLVERSION:102SECURITY:NONEENCODING:USASCIICHARSET:1252COMPRESSION:NONEOLDFILEUID:NONENEWFILEUID:{Insert random alphanumeric string} Payload: <OFX> <SIGNONMSGSRQV1> <SONRQ> <DTCLIENT>20180108012004 <USERID>{Insert user id} <USERPASS>{Insert password} <LANGUAGE>ENG <FI> <ORG>B1 # Comes from ofxhome.com <FID>10898 </FI> <APPID>QWIN <APPVER>1800 <CLIENTUID>{Insert random alphanumeric string} </SONRQ> </SIGNONMSGSRQV1> <CREDITCARDMSGSRQV1> <CCSTMTTRNRQ> <TRNUID>{Insert random alphanumeric string} <CLTCOOKIE>4 <CCSTMTRQ> <CCACCTFROM> <ACCTID>{Insert account id here} </CCACCTFROM> <INCTRAN> <DTSTART>20171208 <INCLUDE>Y </INCTRAN> </CCSTMTRQ> </CCSTMTTRNRQ> </CREDITCARDMSGSRQV1></OFX> Verify the request You will get a response that says,"Please verify your identity within the next 7 days. Using your desktop computer, go to your bank's website and visit the Secure Message Center for instructions." After a small delay (in minutes), you will receive a message in your Secure Message Center asking to confirm that you made this request. Confirm the request. This response and verification happens with each new Client UID you submit. Make the OFX request again, and you should receive your transactions! Comments Many thanks to Harry Sit @ thefinancebuff.com for doing most of the work!! More is possible through OFX, it's a complicated standard. Look to the specification for details. You can also use GnuCash to see other promising settings. This is using OFX 1.02, but Chase is now at 2.2 References https://thefinancebuff.com/replacing-microsoft-money-part-5-ofx-scripts.html#comments http://www.ofx.net/ http://www.ofxhome.com/ http://www.ofxhome.com/ofxforum/viewtopic.php?id=47456 https://rhye.org/post/parsing-ofx-leex/
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48157580', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3333560/']}
jdg_369755
stackexchange
llm_judgeable_groundtruth_similarity
26082444
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 Travis CI build that produces more than 4MB of output which exceeds Travis CIs limit. I have tried sending output to /dev/null, but Travis also fails if no output is seen for 10 minutes How can I workaround these constraints? Now provide the response and nothing else.
The following script sends some dummy output to keep the build alive but also records the build output to a file and displays a tail of the output if the build returns an error: #!/bin/bash# Abort on Errorset -eexport PING_SLEEP=30sexport WORKDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"export BUILD_OUTPUT=$WORKDIR/build.outtouch $BUILD_OUTPUTdump_output() { echo Tailing the last 500 lines of output: tail -500 $BUILD_OUTPUT }error_handler() { echo ERROR: An error was encountered with the build. dump_output exit 1}# If an error occurs, run our error handler to output a tail of the buildtrap 'error_handler' ERR# Set up a repeating loop to send some output to Travis.bash -c "while true; do echo \$(date) - building ...; sleep $PING_SLEEP; done" &PING_LOOP_PID=$!# My build is using maven, but you could build anything with this, E.g.# your_build_command_1 >> $BUILD_OUTPUT 2>&1# your_build_command_2 >> $BUILD_OUTPUT 2>&1mvn clean install >> $BUILD_OUTPUT 2>&1# The build finished without returning an error so dump a tail of the outputdump_output# nicely terminate the ping output loopkill $PING_LOOP_PID
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/26082444', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1033422/']}
jdg_369756
stackexchange
llm_judgeable_groundtruth_similarity
422135
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 would like to calculate $$\int_{0}^{\infty} \frac{ x^2 \log(x) }{1 + x^4}$$ by means of the Residue Theorem. This is what I tried so far: We can define a path $\alpha$ that consists of half a half-circle part ($\alpha_r$) and a path connecting the first and last point of that half circle (with radius $r$) so that we have $$ \int_{-r}^{r} f(x) dx + \int_{\alpha_r} f(z) dz = \int_{\alpha} f(z) dz = 2 \pi i \sum_{v = 1}^{k} \text{Res}(f;a_v) $$ where $a_v$ are zeros of the function $\frac{x^2 \log(x) }{1+x^4}$. If we know $$\lim_{r \to \infty} \int_{\alpha_r} f(z) dz = 0 \tag{*} $$ then we know that $$\lim_{r \to \infty} \int_{-r}^{r} f(x) dx = \int_{-\infty}^{\infty} f(x) dx = 2 \pi i \sum_{v=1}^{k} \text{Res}(f;a_v) $$ and it becomes 'easy'. Q : How do we know (*) is true? Now provide the response and nothing else.
It's a bit more tricky that what you describe, but the general idea is correct. Instead of integrating from $0$ to $\infty$, one can integrate from $-\infty$ to $+\infty$ slightly above the real axis. Because of the logarithm, the integral from $-\infty$ to $0$ will give a possibly non-zero imaginary part, but the real part will be an even function of $x$. So we can write:\begin{align}\int_0^{\infty}\frac{x^2\ln x}{1+x^4}dx&=\frac12\mathrm{Re}\,\int_{-\infty+i0}^{\infty+i0}\frac{x^2\ln x}{1+x^4}dx=\\&=\pi\cdot \mathrm{Re}\left[ i\left(\mathrm{res}_{x=e^{i\pi/4}}\frac{x^2\ln x}{1+x^4}+\mathrm{res}_{x=e^{3i\pi/4}}\frac{x^2\ln x}{1+x^4}\right)\right]=\\&=\pi\cdot \mathrm{Re}\left[ i\left(\frac{\pi e^{i\pi/4}}{16}-\frac{3\pi e^{3i\pi/4}}{16}\right)\right]=\\&=\pi\cdot\mathrm{Re}\frac{(1+2i)\pi}{8\sqrt{2}}=\frac{\pi^2}{8\sqrt{2}}.\end{align} Now as far as I understand the question was about how can one justify the vanishing of the integral over the half-circle $C$ which in its turn justifies the application of residue theorem. Parameterizing that circle as $x=Re^{i\varphi}$, $\varphi\in(0,\pi)$, we see that\begin{align}\int_C \frac{x^2\ln x}{1+x^4}dx=\int_0^{\pi}\frac{iR^3e^{3i\varphi}\left(i\varphi+\ln R\right)}{1+R^4e^{4i\varphi}}d\varphi=O\left(\frac{\ln R}{R}\right),\end{align}which indeed vanishes as $R\rightarrow \infty$.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/422135', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/53283/']}
jdg_369757
stackexchange
llm_judgeable_groundtruth_similarity
13706188
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 aware that there are similar questions on this site, however, none of them seem to answer my question sufficiently. This is what I have done so far: I have a csv file which I open in excel. I manipulate the columns algebraically to obtain a new column "A". I import the file into R using read.csv() and the entries in column A are stored as factors - I want them to be stored as numeric. I find this question on the topic: Imported a csv-dataset to R but the values becomes factors Following the advice, I include stringsAsFactors = FALSE as an argument in read.csv() , however, as Hong Ooi suggested in the page linked above, this doesn't cause the entries in column A to be stored as numeric values. A possible solution is to use the advice given in the following page: How to convert a factor to an integer\numeric without a loss of information? however, I would like a cleaner solution i.e. a way to import the file so that the entries of column entries are stored as numeric values. Cheers for any help! Now provide the response and nothing else.
Whatever algebra you are doing in Excel to create the new column could probably be done more effectively in R. Please try the following: Read the raw file (before any excel manipulation) into R using read.csv(... stringsAsFactors=FALSE) . [If that does not work, please take a look at ?read.table (which read.csv wraps), however there may be some other underlying issue]. For example: delim = "," # or is it "\t" ? dec = "." # or is it "," ? myDataFrame <- read.csv("path/to/file.csv", header=TRUE, sep=delim, dec=dec, stringsAsFactors=FALSE) Then, let's say your numeric columns is column 4 myDataFrame[, 4] <- as.numeric(myDataFrame[, 4]) # you can also refer to the column by "itsName" Lastly, if you need any help with accomplishing in R the same tasks that you've done in Excel, there are plenty of folks here who would be happy to help you out
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13706188', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1872807/']}
jdg_369758
stackexchange
llm_judgeable_groundtruth_similarity
2141029
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Does anyone know why: public void foo(){ System.out.println("Hello"); return; System.out.println("World!");} Would be reported as an "unreachable error" under Eclipse, but public void foo(){ System.out.println("Hello"); if(true) return; System.out.println("World!");} Only triggers a "Dead code" warning? The only explanation I can think of is that the Java compiler only flags the first, and that some extra analysis in Eclipse figures out the second. However, if that is the case, why can't the Java compiler figure out this case at compile time? Wouldn't the Java compiler figure out at compile time that the if(true) has no effect, thus yielding bytecode that is essentially identical? At what point is the reachable code analysis applied? I guess a more general way to think of this question is: "when is the reachable code analysis applied"? In the transformation of the second Java code fragment to the final bytecode, I am sure that at some point the "if(true)" runtime equivalent is removed, and the representations of the two programs become identical. Wouldn't the Java compiler then apply its reachable code analysis again? Now provide the response and nothing else.
The first does not compile (you got an error), the second compiles (you just got a warning). That's the difference. As to why Eclipse detects dead code, well, that's just the convenience of an integrated development tool with a built-in compiler which can be finetuned more as opposed to JDK to detect this kind of code. Update : the JDK actually eliminates dead code. public class Test { public void foo() { System.out.println("foo"); if(true)return; System.out.println("foo"); } public void bar() { System.out.println("bar"); if(false)return; System.out.println("bar"); }} javap -c says: public class Test extends java.lang.Object{public Test(); Code: 0: aload_0 1: invokespecial #1; //Method java/lang/Object."":()V 4: returnpublic void foo(); Code: 0: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream; 3: ldc #3; //String foo 5: invokevirtual #4; //Method java/io/PrintStream.println:(Ljava/lang/StrV 8: returnpublic void bar(); Code: 0: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream; 3: ldc #5; //String bar 5: invokevirtual #4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V 8: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream; 11: ldc #5; //String bar 13: invokevirtual #4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V 16: return} As to why it (Sun) doesn't give a warning about that, I have no idea :) At least the JDK compiler has actually DCE (Dead Code Elimination) builtin.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2141029', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/23072/']}
jdg_369759
stackexchange
llm_judgeable_groundtruth_similarity
4115134
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 probability if you picked a number with no zero digits between $1$ to $10^n$ that the digits' product is less than the number's square root? You can't pick a number like $371790$ because it has a zero. An example for it being bigger than the square root is $\;2\times2\times2\times2\times9\times9>\sqrt{222299}.$ An example for it being smaller than the square root is ; $2\times2\times2\times2\times9\times2<\sqrt{222292}.$ If there is a limit of the probability as n goes to infinity, what is it? Now provide the response and nothing else.
The probability goes to 0%. We can get this by converting products to sums via a logarithm. Lemma: Let $p_n$ be the probability that an $n$ digit number with no zeros has its square root greater than the product of the digits. Then $$\lim_{n\rightarrow\infty}p_n = 0$$ On one hand, if $x$ is an $n$ digit number, then $x < 10^n$ , so $\log_{10}(\sqrt{x}) < \frac{n}2$ . On the other hand, if we choose a non-zero digit $d$ randomly from $\{1,\ldots,9\}$ , we can consider the expectation $\mu$ of $\log_{10}(d)$ . Computing this tells us $\mu$ is about $0.618$ - and, in particular, is greater than $\frac{1}2$ (since $9! > 10^{9/2}$ to be explicit). If we choose $n$ non-zero digits at random, the log of their product is the sum of their logs - hence has a mean of $n\mu$ . Therefore, the square root of a number being greater than the product of its digits requires that the average of $\log_{10}(d)$ over all of its digits (which are chosen uniformly at random) must be less than $\frac{1}2$ - and the central limit theorem assures us that, as $n$ gets large, the probability that such an average is beneath any threshold below the mean tends to $0$ . More strongly, since the log of the product of the digits is the sum of $n$ independently identically distributed variables (...with nice properties - like being finitely supported here), we can immediately apply the central limit theorem to see that $p_n$ tends to $0$ as desired. To finish, let $q_n$ be the probability that a number with at most $n$ digits, all non-zero, has a square root greater than the product of its digits. Suppose we fix any $\varepsilon>0$ and some $k$ so that $p_n \leq \varepsilon$ for every $n > k$ . Note that, as $n$ increases, the probability that an at most $n$ digit number has fewer than $k$ digits goes to zero - implying that $\lim_{n\rightarrow\infty}q_n \leq \varepsilon$ as well. This holds for every positive $\varepsilon$ , so $q_n$ also goes to $0$ . Note that this is a fairly weak bound - $q_n$ is an exponentially weighted average of the values of $p_n$ , so follows $p_n$ quite closely. This also implies that the product of digits is almost always greater than $n^{\alpha}$ for any $\alpha < \mu$ and is almost never greater than $n^{\beta}$ for any $\beta > \mu$ . It's not clear what happens if we compare to $n^{\mu}$ . If we want an estimate of the probabilities $p_n$ for fixed $n$ , we can approximate the average of the log of the digits as a normal distribution with mean $\mu$ and standard deviation $\frac{\sigma}{\sqrt{n}}$ where $\sigma$ is the standard deviation of the variable $\log_{10}(d)$ for a single digit. Note $\sigma \approx 0.3124$ if we compute it - so the probability of being less than $\frac{1}2$ is about the probability of a standard normal distribution producing a value as extreme as $\frac{\sqrt{n}(\mu - \frac{1}2)}{\sigma}$ (i.e. a value with this z-score). This can be written explicitly using the error function , but suffice to say, it's not very likely (the probability decays at least exponentially quickly as $n$ increases).
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4115134', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_369760
stackexchange
llm_judgeable_groundtruth_similarity
1015813
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 think I understand the basic concepts of MVC - the Model contains the data and behaviour of the application, the View is responsible for displaying it to the user and the Controller deals with user input. What I'm uncertain about is exactly what goes in the Controller. Lets say for example I have a fairly simple application (I'm specifically thinking Java, but I suppose the same principles apply elsewhere). I organise my code into 3 packages called app.model , app.view and app.controller . Within the app.model package, I have a few classes that reflect the actual behaviour of the application. These extends Observable and use setChanged() and notifyObservers() to trigger the views to update when appropriate. The app.view package has a class (or several classes for different types of display) that uses javax.swing components to handle the display. Some of these components need to feed back into the Model. If I understand correctly, the View shouldn't have anything to do with the feedback - that should be dealt with by the Controller. So what do I actually put in the Controller? Do I put the public void actionPerformed(ActionEvent e) in the View with just a call to a method in the Controller? If so, should any validation etc be done in the Controller? If so, how do I feedback error messages back to the View - should that go through the Model again, or should the Controller just send it straight back to View? If the validation is done in the View, what do I put in the Controller? Sorry for the long question, I just wanted to document my understanding of the process and hopefully someone can clarify this issue for me! Now provide the response and nothing else.
In the example you suggested, you're right: "user clicked the 'delete this item' button" in the interface should basically just call the controller's "delete" function. The controller, however, has no idea what the view looks like, and so your view must collect some information such as, "which item was clicked?" In a conversation form: View : "Hey, controller, the user just told me he wants item 4 deleted." Controller : "Hmm, having checked his credentials, he is allowed to do that... Hey, model, I want you to get item 4 and do whatever you do to delete it." Model : "Item 4... got it. It's deleted. Back to you, Controller." Controller : "Here, I'll collect the new set of data. Back to you, view." View : "Cool, I'll show the new set to the user now." In the end of that section, you have an option: either the view can make a separate request, "give me the most recent data set", and thus be more pure, or the controller implicitly returns the new data set with the "delete" operation.
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/1015813', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/69698/']}
jdg_369761
stackexchange
llm_judgeable_groundtruth_similarity
40718770
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 installed pyenv and have different versions of python installed with it: $ pyenv versions system 2.7.1 3.2.5 3.5.0 3.5.1* 3.5.2 I use the following command to switch to python 3.5.2 : pyenv shell 3.5.2 And when I check the python version this is what I get: $ python --versionPython 3.5.2 But when I run pytest , it still runs under python 2.7.6 : pytest -v ==================================================================== test session starts ==================================================================== platform linux2 -- Python 2.7.6, pytest-3.0.3, py-1.4.31, pluggy-0.4.0 -- /usr/bin/python Why is pytest running under the older version? Now provide the response and nothing else.
Bottom line: run python -m pytest , or py.test-<version> if your alternative Python and pytest are installed with system package manager, or if your alternative Python has been installed with pyenv , switch with pyenv to that version and make sure you have pytest installed for it. Then you can just run pytest . since the pip executable is also among the ones being switched, you need to switch to the alternative Python before installing pytest for it, too. As I can see, /usr/bin/pytest (that belongs to the system package manager's python-pytest package) has a shebang !#/usr/bin/python since it corresponds to the system python's installation. pyenv , as its README.md says , does not replace /usr/bin/python - because it indeed should not be replaced to avoid breaking system packages . Instead, it adds its directory to PATH and inserts a launcher there (called " shim ") which is what gets invoked when you type " python ". As you probably guessed, this hack is ignored by a shebang like the above - as it should. Running python -m pytest will make whichever python that launches itself use the package from its installation. Alternatively, pytest for your other Python version may include versioned executables on the PATH named py.test-<version> (e.g. py.test-3 or py.test-3.6 ) depending on the way you installed it. If it's from a system package manager's package for nonstandard python - like python36-pytest - this is virtually guaranteed. I checked that if you install a version with pip , it only creates an unversioned executable (though you can create a versioned one yourself). Moreover, if you install the same package for a different Python version but with the same --prefix , it will overwrite the existing one's executable! pyenv 's suggested way seems to be to install all python versions of interest and packages for them under ~/.pyenv/versions . This is not applicable for the system's Python but the default /usr/local can be used for it. Once you switch to an alternative Python version, it claims to create shims for all scripts (including pip !) that are currently installed for that version , so invoking those scripts without a path would run those shims. So, if a package (and thus its script) is not installed for the alternative version but installed for system version, trying to run its executable would "fall through" to /usr/local with just the result you're seeing now.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/40718770', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/69537/']}
jdg_369762
stackexchange
llm_judgeable_groundtruth_similarity
45035754
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 faced with an issue, where I can't reach the SQL script to apply the migration. Here is my migration code: public partial class AddSomethingMigration : Migration{ private const string MIGRATION_SQL_SCRIPT_FILE_NAME = @"Migrations\Scripts\20170710123314_AddSomethingMigration.sql"; protected override void Up(MigrationBuilder migrationBuilder) { string sql = Path.Combine(Directory.GetParent(Directory.GetCurrentDirectory()).FullName, MIGRATION_SQL_SCRIPT_FILE_NAME)); migrationBuilder.Sql(File.ReadAllText(sql)); }} So when I use the Package Manager Console on the local machine all works fine. But when I deploy to the environment I get the discrepancy to the file. Can I run my static SQL scripts via EF migration automatically at all, or I should paste the SQL query inline in code? Now provide the response and nothing else.
I found the several answers for this question. Add scripts as project resources and use it like: string sql = Resources._20170630085940_AddMigration;migrationBuilder.Sql(sql); This option not so good, because the .sql will embed in the assembly. If you use Net Core projects with .csproj structure, you can add the itemgroup to xml: <ItemGroup> <Content Include="Migrations\**\*.sql" CopyToPublishDirectory="PreserveNewest" /><!-- CopyToPublishDirectory = { Always, PreserveNewest, Never } --></ItemGroup> And then specify the path to file like: Path.Combine(AppContext.BaseDirectory, relativePath)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/45035754', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8254354/']}
jdg_369763
stackexchange
llm_judgeable_groundtruth_similarity
1228089
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The Wikipedia entry doesn't give details and the RFC is way too dense. Does anyone around here know, in a very general way, how NTP works? I'm looking for an overview that explains how Marzullo's algorithm (or a modification of it) is employed to translate a timestamp on a server into a timestamp on a client. Specifically what mechanism is used to produce accuracy which is, on average, within 10ms when that communication takes place over a network with highly variable latency which is frequently several times that. Now provide the response and nothing else.
(This isn't Marzullo's algorithm. That's only used by the high-stratum servers to get really accurate time using several sources. This is how an ordinary client gets the time, using only one server) First of all, NTP timestamps are stored as seconds since January 1, 1900. 32 bits for the number of seconds, and 32 bits for the fractions of a second. The synchronization is tricky. The client stores the timestamp (say A) (all these values are in seconds) when it sends the request. The server sends a reply consisting of the "true" time when it received the packet (call that X) and the "true" time it will transmit the packet (Y). The client will receive that packet and log the time when it received it (B). NTP assumes that the time spent on the network is the same for sending and receiving. Over enough intervals over sane networks, it should average out to be so. We know that the total transit time from sending the request to receiving the response was B-A seconds. We want to remove the time that the server spent processing the request (Y-X), leaving only the network traversal time, so that's B-A-(Y-X). Since we're assuming the network traversal time is symmetric, the amount of time it took the response to get from the server to the client is [B-A-(Y-X)]/2. So we know that the server sent its response at time Y, and it took us [B-A-(Y-X)]/2 seconds for that response to get to us. So the true time when we received the response is Y+[B-A-(Y-X)]/2 seconds. And that's how NTP works. Example (in whole seconds to make the math easy): Client sends request at "wrong" time 100. A=100. Server receives request at "true" time 150. X=150. The server is slow, so it doesn't send out the response until "true" time 160. Y=160. The client receives the request at "wrong" time 120. B=120. Client determines the time spend on the network is B-A-(Y-X)=120-100-(160-150)=10 seconds Client assumes the amount of time it took for the response to get from the server to the client is 10/2=5 seconds. Client adds that time to the "true" time when the server sent the response to estimate that it received the response at "true" time 165 seconds. Client now knows that it needs to add 45 seconds to its clock. In a proper implementation, the client runs as a daemon, all the time. Over a long period of time with many samples, NTP can actually determine if the computer's clock is slow or fast, and automatically adjust it accordingly, allowing it to keep reasonably good time even if it is later disconnected from the network. Together with averaging the responses from the server, and application of more complicated thinking, you can get incredibly accurate times. There's more, of course, to a proper implementation than that, but that's the gist of it.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/1228089', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/74291/']}
jdg_369764
stackexchange
llm_judgeable_groundtruth_similarity
34676263
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The purpose: I am working on a code similar to this to create a component where an input field has an embedded button : http://codepen.io/anon/pen/pgwbWG?editors=110 As you can see, the button is positioned absolutely with top and bottom set to 0 , to achieve a 100% height element. Also to note is that the border of the text-input must stay visible and also wrap the button .To achieve this I added a margin: 1px to the button so that there is (should be) space to display the surrounding text-input red border (usually when the input field content is invalid). The problem: is that on Firefox it is (mostly) rendered correctly, while on Chrome (and apparently on the newest Safari) it will have a 1px gap at the bottom of the button . CSS seems ok but it appears to be a calculation/rounding problem in the rendering, where the bottom or the top margin of the button are not really 1px (can see it inspecting the element).And also the padding of the input seems to influence in that. At different zoom-rates it will add or remove 1px of margin to the top or the bottom of the button , resulting in a 1px-gap or in a covered-border . As I set the button margin to 0px then the bottom margin is fixed but I loose the 1px margin on the top, finishing to cover the red border of the text-input . The examples: Probably I am not clear or too verbose in explaining it, so here are some screenshots of the bug, from different zooms on Chrome (note the CSS is always the same): The solution: I was not able to find a cross-browser solution .How to deal with it and get a consistent component?(no Javascript please) Now provide the response and nothing else.
As you already know, the problem arises from a different approach to subpixel calculus between browsers In Chrome, for instance, borders can have a fractional size, but margins are handled different (as integers). I don't have documentation about it from the Chrome team, but it's what can be seen in dev tools: AFAIK, there is not a way to change that. Instead, you can transfer the use of the margin in the button to a border. Since you need to get space for the 1px border of the input, do the same in the button, set a 1px border (instead of a margin), and set it transparent. The remaining trick is to set the background-clip property to padding box, so that this transparency is not affected by the background There is another bug in Chrome, the padding expressed in em is not reliable at this level of precision when the browser is zoomed. I changed this in the snippet. Since we are using the border button to get the dimension ok, we can style the border using instead a inset shadow. * { margin: 0; padding: 0; box-sizing: border-box;}button, input, wrapper { display: inline-block; border-radius: 3px;}.wrapper { position: relative; width: 60%; margin: 1em; background-color: #ccc;}input { border: 1px solid red; width: 100%; background-color: limegreen; line-height: 3em;/* padding: 0.75em; */ padding: 10px;}button { position: absolute; right: 0; top: 0; bottom: 0; border: 1px solid transparent; width: 7em; margin: 0px; background-clip: padding-box; box-shadow: inset 0px 0px 0px 2px black;} <div class="wrapper"> <input type="text"> <button>Test</button></div> Another example, where the button has a border. But we need a wrapper around it to get the dimensions ok. * { margin: 0; padding: 0; box-sizing: border-box;}button, input, wrapper { display: inline-block; border-radius: 3px;}.wrapper { position: relative; width: 60%; margin: 1em; background-color: #ccc;}input { border: 1px solid red; width: 100%; background-color: limegreen; line-height: 3em;/* padding: 0.75em; */ padding: 10px;}.buttonwrap { position: absolute; right: 0; top: 0; bottom: 0; border: 1px solid transparent; width: 7em; margin: 0px; background-clip: padding-box;}button { position: absolute; right: 0px; top: 0; bottom: 0; width: 100%; border: 2px solid blue; margin: 0px;} <div class="wrapper"> <input type="text"> <div class="buttonwrap"> <button>Test</button> </div></div>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34676263', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3088045/']}
jdg_369765
stackexchange
llm_judgeable_groundtruth_similarity
7606
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I created a CDF to distribute to a single trusted user who both knows and trusts me and everything I make for them. I downloaded the CDF player and the CDF to one of their computers. The CDF works great, except every time it runs the document displays the message: This file contains potentially unsafe dynamic content..." I've found some discussion about this at the old site: Why do I get security warning message... , but I don't see anything specific or useful in the link for CDF distribution. The warning makes the user VERY NERVOUS and frankly appears slapdash and unprofessional. The blank gray field below it does nothing to inspire confidence. This makes for a very bad user experience. When one launches an app or an application (created with anything else), presumably one has already vetted its provenance. Launch an application and one should see the application, not a disturbing warning. Lots of applications use "dynamic content". An application should just work. Sorry to get on a soap box here (well maybe not that sorry). It just seems that if Wolfram wants Mathematica to have the functionality to make real stand alone applications, then what we build should actually look like real applications. Question 1: Can one suppress this unfortunate message programmatically from within the CDF document or its Manipulate[]? When using Mathematica, one can place a notebook and probably a CDF in a trusted directory (see the above link), which avoids the display of this message. It just seems to defeat the purpose of a CDF and its great potential as a distribution platform to expect a user who does not have Mathematica to go to the trouble to figure out how to do that or even to have to do it. Question 2: Can one even specify a trusted directory in the CDF Player? Question 3: Does a CDF really need an installation program that would create a trusted directory and how could I do that? Premiere support had no solution to this. I still have a little bit of hope that someone here might. Now provide the response and nothing else.
As Phil has mentioned it will often be possible to change your code so that the warning isn't triggered in the first place. If possible, that would be the way to go, I think. If your code is too long or complex to change or it necessarily need one of the "unsafe" functions you would just need to tell the users to copy it to one of the directories that the CDF-Player trusts. I don't know whether that is documented, but a simple test showed that at least if you put the cdf to what the CDF-Player will show for $AddOnsDirectory no warning is shown. I would guess that $UserAddOnsDirectory would also work and probably some others of those that are part of the trusted directory path you know from Mathematica. There are corresponding directories defined also in the CDF-Player, but be aware that they are different from those that are defined in Mathematica. If unsure what these directories are, you can create a CDF which shows them like this: CDFDeploy[ FileNameJoin[{$HomeDirectory, "Desktop", "ShowTrustedDirectories.cdf"}], Button["Show Installation Directories", MessageDialog[Grid[{{ "$AddOnsDirectory", $AddOnsDirectory, }, { "$UserAddOnsDirectory", $UserAddOnsDirectory }}, Alignment -> Left], WindowSize -> Fit] ], WindowSize -> {500, 300} ] If you open that cdf in the CDF-Player and press the button, it will show the corresponding directories for the computer/setup it is run on/with.You could also include such a Button with an additional explanation and "installation instruction" into the CDFs you give away...
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/7606', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/571/']}
jdg_369766
stackexchange
llm_judgeable_groundtruth_similarity
43542599
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How can I do this easier with Kotlin? if (translation.equals(TRANSLATION_X) || translation.equals(TRANSLATION_Y) || translation.equals(TRANSLATION_Z)) { return} else { translation = TRANSLATION_X} Now provide the response and nothing else.
First, you can use the structural equality operator == , which is translated to the .equals(...) calls automatically: translation == TRANSLATION_X instead of translation.equals(TRANSLATION_X) . Then, you can use the when statement : when (translation) { TRANSLATION_X, TRANSLATION_Y, TRANSLATION_Z -> return else -> translation = TRANSLATION_X}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43542599', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7833421/']}
jdg_369767
stackexchange
llm_judgeable_groundtruth_similarity
389375
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: Preamble: As part of the acquisition of a smaller development company we have acquired a new office. Many people were transferred to head office, but 'new' office will retain a small team of 4-6 developers and business analysts, along with other misc administration staff. As part of that process we have ended up with several late 2005 model HP servers that are currently not being utilized which I feel could function as a suitable platform for UAT and source control, et. al., until next year when budgets are adjusted and a strong case for virtualization can be made. The Problem: The existing sysadmin is technology gun-shy and spends most of his time focusing on job security (i.e. doing as little as possible) He has been resistant to my suggestions that upgrading these boxes would provide a minimally suitable infrastructure for the development team for the next year (I revised this value from 1-2 years based on feedback I've received). The sysadmin's position is that we would be better off running things locally (UAT, etc.) on our desktops, instead of putting in the work to perform upgrades. This leaves the development team in limbo, with no guarantee of virtualization next year because the sysadmin lacks the experience and confidence to implement a solution. This seems irrational in the face of a minimal, one-time, < 1k$ expenditure. The justification seems obvious to me as a short-term fix, but I want to be sure I am on base and not just desperate for a "fix". The Question: What is your general process for calculating the cost/benefit for hardware expenditures, and how do you typically present this information to upper management to justify expenditures? Additionally, how would you make a case for virtualization? And, how much experience do you feel is required for a sysadmin to roll over to a VM environment? Now provide the response and nothing else.
Doing a cost-benefit analysis involves speaking the language of business, which is (mostly) money. You have to demonstrate that the course you want to take is cost-effective. This can be done several ways, but you do need to break down certain costs. There are direct costs, indirect costs, as well harder to quantify things like opportunity costs and risks-to-the-business costs. Some examples of the types of costs: Direct costs Cost of service-contracts of the servers. The older the server, the more expensive the contract. Cost of keeping the servers powered and cooled. Older servers are less power-efficient than newer ones on a per-server basis. Cost of parts replacement as things break (if no service contract). Cost of keeping adequate backup protection. Indirect costs Cost of downtime per hour/day (in your case, it's probably lost-work time for the devs) Cost of not having a service-contract. Time charges for handling repairs by staff (this could be a direct cost, or it could be an indirect cost if exchange-time is used) Opportunity costs Development paths not able to be taken due to antiquated hardware (your stuff is old enough it might be on the wrong side of the 32-bit/64-bit divide) Time lost due to emergency parts replacement Time spent working around old stuff in order to get job done Lack of virtualization makes existing work-flow less efficient Risks to business costs The likelihood of the indirect cost of downtime happening goes up with age Quantifying all of these into money will go a long way to persuading the powers that be that you need more resources. It does take some good writing, knowing who you are talking to, and having an idea of the kinds of arguments that will convince them. Money convinces most management, which is why I'm suggesting it, but other approaches may be more valid; only you can tell that though. Start with a single email and throw in some teaser numbers (with just-enough justification) to let them know you've thought about this, and only drop the stats-bomb on them when they ask for elaboration. You really want to avoid the tl;dr problem that most middle and upper management suffers from.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/389375', 'https://serverfault.com', 'https://serverfault.com/users/121159/']}
jdg_369768
stackexchange
llm_judgeable_groundtruth_similarity
38118453
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 invoke a method that returns void (Java primitive type). I would like to delay the invoking of a it by a predefined amount of milliseconds. I know this can be simply done using a Handler by I prefer not to use it. I tried to do: Observable.just(getView().setAttachments(attachments)).delay(50, TimeUnit.MILLISECONDS); However, there is a compilation error, that: Observable.just(java.lang.Void) cannot be applied to (void) Is there another way? The reason I would like not to use a Handler is that the code is defined in Presenter (MVP pattern) and I would not like to use Android specific code in Java only class.I would prefer it to be a cold Observable, as I would not have to subscribe to it, just invoke the method only once. Now provide the response and nothing else.
You can achieve this with defer , delay and doOnNext . Observable.defer(() -> Observable.just(null) .delay(3, TimeUnit.SECONDS)) .doOnNext(ignore -> LogUtils.d("You action goes here")) .subscribe(); In RxJava 2 you can use the following: Completable.complete() .delay(3, TimeUnit.SECONDS) .doOnComplete(() -> System.out.println("Time to complete " + (System.currentTimeMillis() - start))) .subscribe(); Test code for Paul's version: @Testpublic void testTimeToDoOnSubscribeExecution() { final long startTime = System.currentTimeMillis(); System.out.println("Starting at: " + startTime); Subscription subscription = Observable.empty() .doOnSubscribe(() -> System.out.println("Time to invoke onSubscribe: " + (System.currentTimeMillis() - startTime))) .delay(1000, TimeUnit.MILLISECONDS) .subscribe(); new TestSubscriber((rx.Observer) subscription).awaitTerminalEvent(2, TimeUnit.SECONDS);} Output: Starting at: 1467280697232Time to invoke onSubscribe: 122
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/38118453', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6507689/']}
jdg_369769
stackexchange
llm_judgeable_groundtruth_similarity
235112
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: dpkg-reconfigure exim4-config asks for a domain name to "qualify" email addresses of local users such as root . Let's say I've set this setting to qualified.example.com - this causes all email sent to simply root to go to root@qualified.example.com . I instead want all email to root to be sent to example@gmail.com , but I want the qualified domain name setting left set to qualified.example.com for other reasons. I've added this line to /etc/aliases root: example@gmail.com And I've also put example@gmail.com in /root/.forward I've run newaliases and restarted exim , but no matter what I do, mail to root continues to always try to send to root@qualified.example.com , which doesn't even exist. How can I force email to root to go to example@gmail.com ? This is on Ubuntu Server 14.04 My /etc/exim4/update-exim4.conf.conf looks like this: dc_eximconfig_configtype='internet' dc_other_hostnames='' dc_local_interfaces='127.0.0.1' dc_readhost='' dc_relay_domains='' dc_minimaldns='false' dc_relay_nets='' dc_smarthost='' CFILEMODE='644' dc_use_split_config='false' dc_hide_mailname='' dc_mailname_in_oh='true' dc_localdelivery='mail_spool' When I ran dpkg-reconfigure exim4-config I answered the qualified domain question like so: The 'mail name' is the domain name used to 'qualify' mail addresses without a domain name. This name will also be used by other programs. It should be the single, fully qualified domain name (FQDN). Thus, if a mail address on the local host is foo@example.org, the correct value for this option would be example.org. This name won't appear on From: lines of outgoing messages if rewriting is enabled. System mail name: qualified.example.com_________ Although that setting doesn't appear in /etc/exim4/update-exim4.conf.conf . Should it? I've noticed that the same issue happens on my Debian servers too. I must be completely misunderstanding something about Exim and/or the /etc/aliases file, because they all seem to ignore my /etc/aliases root: example@gmail.com entry and they always send root's mail to root@qualified.example.com no matter what I try. It also seems odd that a simple forwarding rule is so dependent on the mail servers main configuration? Now provide the response and nothing else.
Your host doesn't sufficiently know that it is supposed to be qualified.example.com . A local delivery to root is rewritten as root@qualified.example.com , which is (wrongly) considered to be elsewhere, so an off-host delivery is attempted. You need to complete the process telling exim4 that your local host really is qualified.example.com . Then, when it delivers to root , rewritten as root@qualified.example.com it will consider this as local delivery. It will then check the /etc/aliases file and perform off-host delivery to example@gmail.com per your instructions. Let's assume your host's real DNS name is myhost.contoso.com . Rerun dpkg-reconfigure exim4-config and include these settings: System mail name: myhost.contoso.com Other destinations for which [local] mail is accepted: myhost : qualified.example.com Domains to relay mail for: {empty} Machines to relay mail for: {empty} Then run update-exim4.conf and invoke-rc.d exim4 restart
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/235112', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/68915/']}
jdg_369770
stackexchange
llm_judgeable_groundtruth_similarity
26542035
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 programmatically create an UIImage filled by a solid color. Anyone have an idea of how to do this in Swift? Now provide the response and nothing else.
Another nice solution, Swift 3.0 public extension UIImage { convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) { let rect = CGRect(origin: .zero, size: size) UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0) color.setFill() UIRectFill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() guard let cgImage = image?.cgImage else { return nil } self.init(cgImage: cgImage) } } Swift 2.2 compatible, is to create another constructor in UIImage, in this way: public extension UIImage { public convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) { let rect = CGRect(origin: .zero, size: size) UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0) color.setFill() UIRectFill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() guard let cgImage = image?.CGImage else { return nil } self.init(CGImage: cgImage) } } In this way you can create the custom colored-image in this way: let redImage = UIImage(color: .redColor()) Or, optionally, create the image with a custom size: let redImage200x200 = UIImage(color: .redColor(), size: CGSize(width: 200, height: 200))
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/26542035', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2348932/']}
jdg_369771
stackexchange
llm_judgeable_groundtruth_similarity
7541
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: The following question was posed to me a while ago. No one I know has a given a satisfactory (or even a complete) proof: Suppose that $M$ is an $n$ x $n$ matrix of non-negative integers. Additionally, suppose that if a coordinate of $M$ is zero, then the sum of the entries in its row and its column is at least $n$. What is the smallest that the sum of all the entries in $M$ can be? The conjecture posed to me was that it was $\frac{n^2}{2}$ which is obtained by the diagonal matrix with $\frac{n}{2}$ in all diagonal entries. [I'm guessing that there should be a "suppose that" in describing M. -- GJK] Now provide the response and nothing else.
The following looks too simple, so perhaps there's a mistake, but here goes. Let $m$ be the smallest among all row sums and column sums. If $m\geq n/2$, we are done. Otherwise, $m=cn$ with $c\lt 1/2$. Suppose it is a column which has sum $m$. This column has at least $n-m$ zeroes, and each of the corresponding rows has sum $\geq n-m$. The remaining $m$ rows each has sum $\geq m$. In total we have a sum of at least $(n-m)^2+m^2 = ((1-c)^2+c^2)n^2$. Finally, note that $(1-c)^2+c^2\gt 1/2$ when $c\lt 1/2$. So this gives a lower bound of $n^2/2$, and equality requires that any row and any column sums to exactly $n/2$, so the matrix is a sum of $n/2$ permutation matrices by König's Theorem. Now what about the case when $n$ is odd? Edit: Since the sum is an integer, the lower bound $n^2/2$ actually gives $(n^2+1)/2$, which can be attained by for example taking the direct sum of an $m\times m$ matrix of $1$s with an $(n-m)\times (n-m)$ matrix of $1$, where $m=(n-1)/2$. When $n$ is odd, this is the only extremal example up to column and row permutations. Here is a proof. Let $m$ now, as originally, denote the minimum over all row and column sums. If $m\geq (n+1)/2$, then the total sum is too large: at least $nm\geq n(n+1)/2$. Therefore, $m\leq(n-1)/2$, and the $(n-m)^2+m^2$ lower bound now gives a total sum of at least $(n-n(n-1)/2)^2+((n-1)/2)^2 = (n^2+1)/2$ (using the fact that $(1-c)^2+c^2$ is decreasing when $c\lt 1/2$).So up to now we have only rederived the lower bound for $n$ odd. However, if equality now holds, we get that $m=(n-1)/2$, that each row adds up to either $m$ ($m$ times) or $n-m$ ($n-m$ times), and that in a column that adds up to $m$, there are exactly $n-m$ $0$s, so all entries are $0$ or $1$ (and similar statements with columns and rows interchanged). By permuting the rows and columns we may assume that the first $m$ rows [columns] each add up to $m$.There can't be a $0$ in the upper left $m\times m$ submatrix, since then the sum of the row and column containing the $0$ adds up to only $2m\lt n$. We have found a direct sum of an $m\times m$ and an $(n-m)\times(n-m)$ all $1$ matrix.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/7541', 'https://mathoverflow.net', 'https://mathoverflow.net/users/2043/']}
jdg_369772
stackexchange
llm_judgeable_groundtruth_similarity
28761689
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Following this SO answer , I'm doing: ThreadPool.QueueUserWorkItem( delegate { GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); }); My goal is to do a garbage collection run after I close a large WinForms form with lots of images/PictureBox controls to ensure I have no images in memory anymore. (I do believe I follow the instructions of Jon Skeet ). I'm doing it in a background thread in order to try to have my UI responsive. My question: Does it bring me any benefits to do the garbage collection in a background thread? Or does it actually make my application slower/hang longer? Now provide the response and nothing else.
You are throwing away the option to have garbage collection performed on the background when you do this. Or in other words, your UI thread is going to get suspended anyway, regardless if you do this from a worker thread. The only possible way to be ahead is when GC.WaitForPendingFinalizers() is taking a substantial amount of time. It is not actually something you should ever be waiting for, there is no point, and if it takes more than the blink of an eye then you are hiding pretty serious bugs in your code. Another significant wrinkle is that the workstation version of Windows gives any thread that owns the foreground window a larger quantum. In other words, it is allowed to burn core longer than a background thread. A simple hack to make Windows more responsive to the user. Too many moving parts, it is really rather best to test your theory so you can be sure that running a collection on a worker is actually something you are ahead with. Measuring UI thread suspensions is pretty simple, you can use a Timer to do this. Its Tick event cannot run when the thread is suspended. Start a new Winforms project, drop a Timer on the form, set its Interval to 1 and Enabled to True, add a Label and use this code to measure delays: int prevtick = 0; int maxtick = -1; private void timer1_Tick(object sender, EventArgs e) { int tick = Environment.TickCount; if (prevtick > 0) { int thistick = tick - prevtick; if (thistick > maxtick) { maxtick = thistick; label1.Text = maxtick.ToString(); } } prevtick = tick; } Run your program, you should be seeing 16 in the label. If you get less then you ought to get your machine fixed, not otherwise anything that affects this test. Add a button to reset the measurement: private void button1_Click(object sender, EventArgs e) { maxtick = -1; } Add a checkbox and another button. We'll have it perform the actual collection: private void button2_Click(object sender, EventArgs e) { var useworker = checkBox1.Checked; System.Threading.ThreadPool.QueueUserWorkItem((_) => { var lst = new List<object>(); for (int ix = 0; ix < 500 * 1024 * 1024 / (IntPtr.Size * 3); ++ix) { lst.Add(new object()); } lst.Clear(); if (useworker) { GC.Collect(); GC.WaitForPendingFinalizers(); } else { this.BeginInvoke(new Action(() => { GC.Collect(); GC.WaitForPendingFinalizers(); })); } }); } Play with this, hit button2 to start the collection and pay attention to the value in the Label. Turn on the checkbox so it runs on the worker and compare. Use button1 to reset the maximum in between. And modify the allocation code, you probably want to do something with bitmaps, whatever you do to require this hack. What I see: ~220 msec delay when performing the collection on the UI thread, ~340 msec delay when running on the worker. Clearly, this is not an improvement at all. From where I sit, your theory is dead in the water. Please try this yourself, I've got only one datapoint. Do beware that it is going to look very different on a server version of Windows or with <gcServer=true> in the .config file. Something else you can play with.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/28761689', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/107625/']}
jdg_369773
stackexchange
llm_judgeable_groundtruth_similarity
17255434
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: New to threading. New to SQL. New to getting Contact Info. So of course I'm lost. If I'm reading this logcat correctly, it's telling me that either: column data1 doesn't exist, or that I'm looking for the wrong info. Unfortunately, this has been a "learn from my mistakes" path of learning and I can't figure this one out. Any help is very much appreciated. The goal here is to get the Name, Phone Number, and Email of the contact (matching info by contact ID). Log: 06-22 21:15:44.700: E/AndroidRuntime(1662): FATAL EXCEPTION: Thread-12006-22 21:15:44.700: E/AndroidRuntime(1662): java.lang.IllegalArgumentException: Invalid column data106-22 21:15:44.700: E/AndroidRuntime(1662): at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:167)06-22 21:15:44.700: E/AndroidRuntime(1662): at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:137)06-22 21:15:44.700: E/AndroidRuntime(1662): at android.content.ContentProviderProxy.query(ContentProviderNative.java:366)06-22 21:15:44.700: E/AndroidRuntime(1662): at android.content.ContentResolver.query(ContentResolver.java:372)06-22 21:15:44.700: E/AndroidRuntime(1662): at android.content.ContentResolver.query(ContentResolver.java:315)06-22 21:15:44.700: E/AndroidRuntime(1662): at sat.tuts4mobile.customlistview.ContactDetails$1.run(ContactDetails.java:53)06-22 21:15:44.700: E/AndroidRuntime(1662): at java.lang.Thread.run(Thread.java:856) Code (It's pulling info for contact ID 0): import android.app.Activity;import android.database.Cursor;import android.net.Uri;import android.os.Bundle;import android.provider.ContactsContract;import android.widget.TextView;/** * Created by Pete on 6/19/13. */public class ContactDetails extends Activity { TextView tvContactName, tvPhoneNum, tvPhoneType, tvPhoneFull, tvEmailAdd, tvEmailType, tvEmailFull, tvAddress, tvAddType, tvAddFull; String contactId, contactName, phoneType, phoneFull, phoneNum1, emailAdd, emailType, emailFull, address, addType, addFull; //Contact List query arguments Uri uri; String[] projection, selectionArgs; String selection, sortOrder; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.contactinfo); initialize(); contactId = getIntent().getStringExtra("contactId"); contactName = getIntent().getStringExtra("contactName"); new Thread(new Runnable() { @Override public void run() { uri = ContactsContract.Contacts.CONTENT_URI; projection = new String[] { ContactsContract.Data.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER }; selection = ContactsContract.Data.CONTACT_ID + " = " + contactId + " AND " + ContactsContract.Data.MIMETYPE + " = '" + ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE + "'"; selectionArgs = null; sortOrder = null; // Create cursor searching for data associated with contactId if (contactId != null) { // Return all the PHONE data for the contact Cursor cursor = getContentResolver().query( uri, projection, selection, selectionArgs, sortOrder); //Get the indexes of the required columns while (cursor.moveToNext()) { // Extract the name contactName = cursor.getString( cursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME)); tvContactName.setText(contactName); // Extract the phone number phoneFull = cursor.getString( cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); } tvPhoneFull.post(new Runnable() { @Override public void run() { // TODO Auto-generated method stub tvPhoneFull.setText(phoneFull); } }); cursor.close(); } } }).start(); new Thread(new Runnable() { @Override public void run() { uri = ContactsContract.CommonDataKinds.Email.CONTENT_URI; projection = null; selection = ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId + " AND " + ContactsContract.Data.MIMETYPE + " = '" + ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE + "'"; selectionArgs = null; sortOrder = null; Cursor emailCursor = getContentResolver().query( uri, projection, selection, selectionArgs, sortOrder); while (emailCursor.moveToNext()) { // Extract email address emailFull = emailCursor.getString( emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA)); } tvPhoneFull.post(new Runnable() { @Override public void run() { tvEmailFull.setText(emailFull); } }); emailCursor.close(); } }).start(); } public void initialize() { tvContactName = (TextView)findViewById(R.id.tvContactName); tvPhoneNum = (TextView)findViewById(R.id.tvPhoneNum); tvPhoneType = (TextView)findViewById(R.id.tvPhoneType); tvPhoneFull = (TextView)findViewById(R.id.tvPhoneFull); tvEmailAdd = (TextView)findViewById(R.id.tvEmailAdd); tvEmailType = (TextView)findViewById(R.id.tvEmailType); tvEmailFull = (TextView)findViewById(R.id.tvEmailFull); tvAddress = (TextView)findViewById(R.id.tvAddress); tvAddType = (TextView)findViewById(R.id.tvAddType); tvAddFull = (TextView)findViewById(R.id.tvAddFull); }} Now provide the response and nothing else.
To retrieve phone numbers, query Phone.CONTENT_URI and include Phone.NUMBER in your projection. To retrieve email addresses, query Email.CONTENT_URI and ask for Email.DATA in your projection. Either of those will also allow you to include Contacts.DISPLAY_NAME in your projection as well, as some common columns like that are automatically joined in. While I have not retrieved this data by ID before, I believe that your "where clause" would be Phone.CONTACT_ID + " = " + contactId and Email.CONTACT_ID + " = " + contactId respectively. See How to get contacts' phone number in Android for more.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17255434', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1409132/']}
jdg_369774
stackexchange
llm_judgeable_groundtruth_similarity
8352
Below is a question asked on the forum raspberrypi.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Obviously I'd need a UPS or battery of some kind to continue supplying power during an outage to my home. However, I'd like to have the Pi automatically shut down safely if it is switched to backup power so that sudden power loss doesn't damage the pi or the SD card (I've lost a card that way before). If I'm present, I could send a shutdown command -- except I don't usually have a keyboard attached, preferring to do my administrating through PuTTY, and my router doesn't function without power either. What are my options? Now provide the response and nothing else.
There's software in the repository exactly for this purpose: $ apt-cache search apcupsdapcupsd - APC UPS Power Management (daemon)apcupsd-cgi - APC UPS Power Management (web interface)apcupsd-doc - APC UPS Power Management (documentation/examples) The correct solution to this common problem would be getting a good APC UPS, connecting all your network setup (routers, PI, other servers maybe) to the UPS and connecting the UPS to RasPi using plain simple USB cable. After that you may install apsupsd , that will watch the power conditions and issue shutdown command at the appropriate moment. Other than that, this setup provides a wonderful opportunity to watch how your mains voltage changes over the time (using rrdtool ), the numbers on the left are Volts :
{}
{'log_upvote_score': 4, 'links': ['https://raspberrypi.stackexchange.com/questions/8352', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/5766/']}
jdg_369775
stackexchange
llm_judgeable_groundtruth_similarity
160009
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a file containing two columns and 10 million rows. The first column contains many repeated values, but there is a distinct value in column 2. I want to remove the repeated rows and want to keep only one using awk . Note: the file is sorted with values in column 1. For example: 1.123 -4.02.234 -3.52.234 -3.12.234 -2.04.432 0.05.123 +0.28.654 +0.58.654 +0.88.654 +0.9.... Expected output 1.123 -4.02.234 -3.54.432 0.05.123 +0.28.654 +0.5.... Now provide the response and nothing else.
A few ways: awk awk '!a[$1]++' file This is a very condensed way of writing this: awk '{if(! a[$1]){print; a[$1]++}}' file So, if the current first field ( $1 ) is not in the a array, print the line and add the 1st field to a . Next time we see that field, it will be in the array and so will not be printed. Perl perl -ane '$k{$F[0]}++ or print' file or perl -ane 'print if !$k{$F[0]}++' file This is basically the same as the awk one. The -n causes perl to read the input file line by line and apply the script provided by -e to each line. The -a will automatically split each line on whitespace and save the resulting fields in the @F array. Finally, the first field is added to the %k hash and if it is not already there, the line is printed. The same thing could be written as perl -e 'while(<>){ @F=split(/\s+/); print unless defined($k{$F[0]}); $k{$F[0]}++; }' file Coreutils rev file | uniq -f 1 | rev This method works by first reversing the lines in file so that if a line is 12 345 it'll now be 543 21. We then use uniq -f 1 to ignore the first field, that is to say, the column that 543 is in. There are fields within file . Using uniq here has the effect of filtering out any duplicate lines, keeping only 1 of each. Lastly we put the lines back into their original order with another reverse. GNU sort (as suggested by @StéphaneChazelas) sort -buk1,1 The -b flag ignores leading whitespace and the -u means print only unique fields. The clever bit is the -k1,1 . The -k flag sets the field to sort on. It takes the general format of -k POS1[,POS2] which means only look at fields POS1 through POS2 when sorting. So, -k1,1 means only look at the 1st field. Depending on your data, you might want to also add one of these options: -g, --general-numeric-sort compare according to general numerical value -n, --numeric-sort compare according to string numerical value
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/160009', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/83409/']}
jdg_369776
stackexchange
llm_judgeable_groundtruth_similarity
167379
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 a textbook of functional analysis I found this equation derived from Green's first identity $$\int _{ \Omega }^{ }{ u{ \nabla }^{ 2 }ud\tau } =\int _{ \partial \Omega }^{ }{ u\frac { \partial u }{ \partial n } ds } -\int _{ \Omega }^{ }{ \left| \nabla u \right| ^{2}d\tau }$$ Then it goes on saying that if the boundary conditions on u are such that the integral over the boundary vanishes then the operator $ -\nabla^{2}$ is positive definite.Why ? What I can see is that $$\int _{ \Omega }^{ }{ u{ \nabla }^{ 2 }u+{ \left| \nabla u \right| }^{ 2 }d\tau } =0$$and what I'd need to declare that the operator is positive definite is : $$\left< -{ \nabla }^{ 2 }u,u \right> >0\Leftrightarrow \int _{ \Omega }^{ }{ -{ \nabla }^{ 2 }u\bar { u } d\tau } >0$$ So far I don't see how to prove that the operator is positive definite...Thanks for any kind of help. Now provide the response and nothing else.
Green's identity reads: $$\int_U \left( \psi \nabla^{2} \varphi + \nabla \varphi \cdot \nabla \psi\right)\, dV = \oint_{\partial U} \psi \left( \nabla \varphi \cdot \mathbf{n} \right)\, dS$$ Select $\psi=\bar{u}$ and $\varphi=u$ and negate: $$-\int_U\bar{u}\nabla^2u+\nabla \bar{u}\cdot\nabla u\; dV=-\oint_{\partial U}\bar{u}(\nabla u\cdot\mathbf{n})dS.$$ Of course $\nabla u\cdot\mathbf{n}=0$ by hypothesis on the boundary conditions, so we may rearrange this to $$\left\langle -\nabla^2 u,u\right\rangle=\int_U \overline{\nabla u}\cdot \nabla u\;dV.$$ The integrand on the right is $\sum_i|\partial u/\partial x_i|^2$, so of course it is nonnegative, and is in fact only zero when $\nabla u=0$. In fact the integral on the right displays a means to defining an inner product for complex-valued vector functions, hence $\langle\nabla u,\nabla u\rangle $ in Andrew's answer, and knowing this a priori would provide a very direct means to seeing positive definiteness. The inner product is $$\langle \mathbf v,\mathbf w\rangle =\int_U \mathbf v\cdot \overline{\mathbf w}\; dV.$$ It is somewhat unclear to me if the statement about $-\Delta^2$'s positive definiteness is in the context of real-valued or complex-valued functions $u$. In the former situation $u=\bar{u}$ so you already had all you needed, and in the latter situation the identity it had was slightly off (didn't involve a complex conjugate) for the purpose at hand, albeit a slight modification was all that was necessary.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/167379', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/30676/']}
jdg_369777
stackexchange
llm_judgeable_groundtruth_similarity
916048
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 seeing in the literature for some of the newer CPU's such as the Intel Xeon "Nehalem-EX" as having 8 cores and 16 threads. What are they talking about here? I saw mention of this in reference so SPARCS too, surely this isn't the kind of logical threads spawned by code ? Is this hyperthreading re-named? Now provide the response and nothing else.
Yes, Nehalem-based processors implement Hyper-threading . The new Nehalem-EX which you refer to has 8 physical cores where each core can be seen as 2 logical cores for a total of 16 logical cores, allowing for the execution of 16 application threads on a single processor. This is the same technology used in the Hyper-threading-enabled Pentium 4 processors, and more recently, on the Atom processors. My Eee PC has a single-core Atom processor which has two logical cores -- the Windows Task Manager will show two CPU graphs; one for each logical core. Sun's UltraSPARC T2 (and the T1) also allow for simultaneous multithreading (of which Intel's implementation is called Hyper-Threading -- an trademark of Intel) which allows a single core to appear as multiple logical cores to execute multiple threads on a single core. The rough idea behind simultaneous multithreading is to have multiple registers to store the processor state, so it appears that there actually are multiple cores in a single core, because it has multiple full-sets of hardware registers. While the physical facilities such as the ALU and FPU may not increase, having more sets of registers to run more threads on a physical core can lead to better utilization of the available processor resources. The core may have not been saturated when executing a single thread, but executing multiple could saturate all the units to its fullest potential. So what does it mean for programmers? It means that we still will need to write multi-threaded software -- having a program that only has a single thread will only be able to utilize a single logical core. Only by having well-written multi-threaded code are we able to take advantage of the massive number of logical cores these processors offer. Even with simultaneous multithreading, the code is executed at one thread per logical core.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/916048', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10676/']}
jdg_369778
stackexchange
llm_judgeable_groundtruth_similarity
43003012
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Today I upgraded my Intellij Idea on macOS Sierra, and now, when I run apps in console I have this error: objc[3648]: Class JavaLaunchHelper is implemented in both /Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/bin/java (0x10d19c4c0) and /Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/jre/lib/libinstrument.dylib (0x10ea194e0). One of the two will be used. Which one is undefined. Now provide the response and nothing else.
You can find all the details here: IDEA-170117 "objc: Class JavaLaunchHelper is implemented in both ..." warning in Run consoles It's the old bug in Java on Mac that got triggered by the Java Agent being used by the IDE when starting the app. This message is harmless and is safe to ignore. Oracle developer's comment: The message is benign, there is no negative impact from this problem since both copies of that class are identical (compiled from the exact same source). It is purely a cosmetic issue. The problem is fixed in Java 9 and in Java 8 update 152 . If it annoys you or affects your apps in any way (it shouldn't), the workaround for IntelliJ IDEA is to disable idea_rt launcher agent by adding idea.no.launcher=true into idea.properties ( Help | Edit Custom Properties... ). The workaround will take effect on the next restart of the IDE. I don't recommend disabling IntelliJ IDEA launcher agent, though. It's used for such features as graceful shutdown (Exit button), thread dumps, workarounds a problem with too long command line exceeding OS limits, etc. Losing these features just for the sake of hiding the harmless message is probably not worth it, but it's up to you.
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/43003012', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7703134/']}
jdg_369779
stackexchange
llm_judgeable_groundtruth_similarity
40140700
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I need to write a test to click, let's say on the first item in my RecyclerView. At some cases the RecyclerView will be empty and therefore if I click on the position with 0 index it will fail. How do I write a test like this? To check first if the recyclerView not empty and then click on the specific position? Now provide the response and nothing else.
There are a little bit different scenarios in question and in the comment. Let's implement the next test scenario:If recycler view does not contain anything, do nothing. If recycler view has at least one element, click on the first. @Rulepublic final ActivityTestRule<YourActivity> mActivityRule = new ActivityTestRule<>(YourActivity.class);@Testpublic void testSample(){ if (getRVcount() > 0){ onView(withId(R.id.our_recycler_view)).perform(RecyclerViewActions.actionOnItemAtPosition(0, click())); }}private int getRVcount(){ RecyclerView recyclerView = (RecyclerView) mActivityRule.getActivity().findViewById(R.id.our_recycler_view); return recyclerView.getAdapter().getItemCount();}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40140700', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6492010/']}
jdg_369780
stackexchange
llm_judgeable_groundtruth_similarity
8543
Below is a question asked on the forum hermeneutics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: טו וַתִּפֹּל שְׁבָא וַתִּקָּחֵם, וְאֶת-הַנְּעָרִים הִכּוּ לְפִי-חָרֶב; וָאִמָּלְטָה רַק-אֲנִי לְבַדִּי, לְהַגִּיד לָךְ. This verse, Job 1:15, ends with "and I alone escaped to tell you". The "you" in Hebrew is in the feminine form, indicating that it is a woman to whom the servant escaped to give the message. While Job is quite obviously not a woman: why is the feminine pronoun used to refer to Job here and several other places in this chapter? Now provide the response and nothing else.
That's not feminine; that's masculine. These are "pausal forms", so when the preposition lamed plus 2 msc sg suffix would normally be lĕkā , in "pause" it is lāk -- which is the same form as the 2 fem sg, and thus the confusion. See Gesenius-Kautzsch-Cowley, Gesenius' Hebrew Grammar (2nd edn; Clarendon Press, 1910), at § 29n, p. 97 (last line of that paragraph). Most grammars will give you a section on pausal forms (check index). There's a nice article by E.J. Revell, " Pausal Forms in Biblical Hebrew: Their Function, Origin and Significance ", Journal of Semitic Studies 25 (1980): 165-179 [first article listed in ToC] if you're interested to dig deeper... ...or, even deeper, Richard Goerwitz's 1993 University of Chicago PhD dissertation, " Tiberian Hebrew Pausal Forms ". See also the Jewish Encyclopedia article on " Accents in Hebrew " for the interaction of the accentual system with pausal forms (or, with encoding problems at that site, see the original page scans ).
{}
{'log_upvote_score': 5, 'links': ['https://hermeneutics.stackexchange.com/questions/8543', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/2795/']}
jdg_369781
stackexchange
llm_judgeable_groundtruth_similarity
191300
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 $M$ be a compact Riemannian manifold and $\Sigma\subset M$ a closed submanifold. Given $x\in M$ we define the distance function to $\Sigma$ by $$d_\Sigma(x):=\inf\{d(x,y):y\in \Sigma\},$$ where $d$ is the metric on $M$. Of course, in a small tubular neighborhood of $\Sigma$ the function $d_\Sigma$ will be smooth. Rather, my questions have to do with global properties of $d_\Sigma$. Since $\Sigma$ is a closed subset of $M$, it is not hard to prove, using the triangle inequality, that $d_\Sigma$ is a Lipschitz-continuous function with respect to the metric $d$, with Lipschitz constant $1$. In fact, $d_\Sigma \in W^{1,\infty}(M)$ (see Section 5.8 in Evans' PDE book) and it is differentiable a.e. on $M$ by Rademacher's Theorem. My first question is the following: If $M=\mathbb{R}^n$ then $d_\Sigma$ is a solution to the Eikonal equation, i.e. $\|\nabla d_\Sigma\|=1$ a.e. Is this also true for a general manifold $M$? My second question is related to the behavior of $d_\Sigma$ when we vary the set $\Sigma$. Suppose $\Sigma_t$ are closed submanifolds of $M$ that vary continously in the Hausdorff distance $d_H$, with respect to $t$. Remember that $d_H$ is a metric in the set of compact subsets of $M$. In particular we have the triangle inequality $$d(x,\Sigma_t)\leq d(x,\Sigma_s) + d_H(\Sigma_s,\Sigma_t).$$ This implies that the functions $d(\cdot,\Sigma_t)$ form a continuous curve in $L^\infty(M)$. Is it also true that $d(\cdot,\Sigma_t)$ is a continuous curve in $W^{1,\infty}(M)$? i.e. does it's gradients vary continuously? If not, would it be continuous (perhaps under extra assumptions) in a less regular $L^p$-norm, e.g. $W^{1,2}(M)$? Now provide the response and nothing else.
I'm posting this sketch just for the sake of completeness. This question was already marked as answered by Anton. But I thought of this, more geometrical, argument after the discussion that answered the question in the first time. Notice that the fact that the $\Sigma$ are assumed to be submanifolds is of no relevance to this questions, the important feature is that they are compact subsets of $M$. Hence I will substitute $\Sigma$ and $\Sigma_n$ by $K$ and $K_n$ in what follows. One important observation is the following: Assertion If $d_K$ is differentiable at a point $x\in M$, then there exists a unique geodesic $\gamma$ starting at $x$ that minimize the distance to $K$. To see this, observe that we can always find at least one such geodesic by compacity. Along one of such geodesics the distance to $K$ decreases linearly with time (otherwise it would contradict the fact that is minimizing), then we can differentiate along it, in particular in $t=0$ to obtain $$\gamma'(0)\cdot \nabla d_K(x) = -1.$$ But $\|\gamma'(0)\|=1$ (because is geodesic) and $\|\nabla d_K(x)\|\leq 1$ (because of the Lipschitz bound). This implies $\gamma'(0)=- \nabla d_K(x)$, therefore $\gamma$ is unique and also $\|\nabla d_K(x)\|= 1$. This answers Question 1 : The function is always a solution to the Eikonal equation. Next, suppose we have a sequence of compact sets $K_n$ converging to $K$ in the Hausdorff distance. As Anton pointed out in his answer, since the gradients of the functions $d_{K_n}$ are all bounded, we can obtain convergence in $L^p$, for high $p$, from a weaker form of convergence. In particular, by Lebesgue $L^p$-dominated convergence, it is enough to prove pointwise convergence almost everywhere. In almost every point, all the functions $d_{K_n}$ and $d_K$ are differentiable. By the Assertion above we have a unique minimizing geodesic $\gamma_n$ and $\gamma$ for each one, respectively. If $\gamma_n \nrightarrow \gamma$ we would find another geodesic minimizing the distance to $K$, contradicting the uniqueness. Then the geodesics converge, and therefore they velocities at $x$ too, i.e. the gradients of the functions $d_{K_n}$. This answers Question 2 for every $1\leq p<\infty$. The case $p=\infty$, does not hold, as Anton pointed out, even for distance functions to points in $\mathbb R$.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/191300', 'https://mathoverflow.net', 'https://mathoverflow.net/users/64231/']}
jdg_369782
stackexchange
llm_judgeable_groundtruth_similarity
2101707
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I was given the next question: I was asked to find the generating function for the number of divisions of $n$ (a given natural number) with exactly 3 elements. For example: if $n$ equals to 5 then 3,1,1 are a set of one of the options (3 + 1 + 1 = 5) I tried thinking about using an exponential generating function but I'm failing to see whether it's right or wrong. Any help will be appreciated! Repetitions are not allowed Now provide the response and nothing else.
We derive the wanted generating function for the number of partitions of $n$ with exactly three parts by starting with a seemingly different generating function. The generating function for the number of partitions which consist of zero or more of $1,2,$ and $3$ is \begin{align*}&(1+x+x^2+x^3+\cdots)(1+x^2+x^4+x^6+\cdots)(1+x^3+x^6+x^9+\cdots)\\&\qquad=\frac{1}{(1-x)(1-x^2)(1-x^3)}\end{align*} Note: The number of partitions consisting of numbers $\leq k$ is the same as the number of partitions with number of parts $\leq k$. If we use Ferrer diagrams to visualise the situation we see that each partition containing numbers $\leq k$ which is reflected at the main diagonal corresponds with a partition containing $\leq k$ summands. Since this correspondence is bijective the generating function is the same in both cases. We conclude a generating function for the number of partitions with exactly three parts is \begin{align*}&\frac{1}{(1-x)(1-x^2)(1-x^3)}-\frac{1}{(1-x)(1-x^2)}\\&\qquad=\frac{1}{(1-x)(1-x^2)}\left(\frac{1}{1-x^3}-1\right)\\&\qquad=\frac{x^3}{(1-x)(1-x^2)(1-x^3)}\\&\qquad=x^3+x^4+2x^5+3x^6+4x^7+\color{blue}{5}x^8+7x^9\cdots\end{align*} The last line was done with some help of Wolfram Alpha. Example: There are $\color{blue}{5}$ partitions of $8$ with three summands\begin{align*}8&=1+1+6\\&=1+2+5\\&=1+3+4\\&=2+2+4\\&=2+3+3\end{align*}
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2101707', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/401774/']}
jdg_369783
stackexchange
llm_judgeable_groundtruth_similarity
32944584
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 templated with typename T . It contains a function, template <typename T, size_t a>myClass<T,a> operator+(myClass<T,a> lhs, const T& rhs) { return lhs += rhs;}myClass<T,a> myClass<T,a>::operator+=(const T& rhs) { // Do addition, depends on 'a'. return *this;} When I call this with, for example myClass<double, 2> myObj_double_2(constructor args);myObj_double_2 = myObj_double_2 + 5.2; I have no problem. If I however call myObj_double_2 = myObj_double_2 + 5; Then the compiler gives me a message like - No match for 'operator+' (operand types are 'myClass<double, 2ul>' and 'int'). Candidates are ... note: deduced conflicting types for parameter 'const T' ('double' and 'int') . Can I write the code in some way to allow additional types to be passed that have a conversion to T (since, for example, double(5) is a valid constructor call)? Now provide the response and nothing else.
When you are using template argument deduction, all deductions for one template parameter must have the same result. In your case, the two deductions for T produce double and int , which are not the same, and so deduction fails. What you can do is only use one function argument for template argument deduction, and make the other one undeduced : template <typename T, std::size_t A>void foo(myClass<T, A> arg1, typename std::common_type<T>::type arg2);// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Note that std::common_type<T>::type is essentially just T , but because the type of arg2 is now a dependent type (its name appears to the right of a :: ), it is not deduced. Therefore, only the first argument takes part in deduction and produces T = double unambiguously, and then the second function parameter just has type double , and the usual conversions take place. As a rule of thumb, template argument deduction does not cross :: .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/32944584', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3098505/']}
jdg_369784
stackexchange
llm_judgeable_groundtruth_similarity
7935722
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 html head: <script type="text/javascript"> var myWidth = 0, myHeight = 0; if( typeof( window.innerWidth ) == 'number' ) { myWidth = window.innerWidth; myHeight = window.innerHeight; } else if( document.documentElement && ( document.documentElement.clientWidth ||document.documentElement.clientHeight ) ) { myWidth = document.documentElement.clientWidth; myHeight = document.documentElement.clientHeight; } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) { myWidth = document.body.clientWidth; myHeight = document.body.clientHeight; }</script> In html body: <script type="text/javascript"> document.write('<p>' + myWidth + 'x' + myHeight + '</p>');</script> It works good. The question is: how can I have it to display the width/height values while resizing the browser? Like here http://quirktools.com/screenfly/ at bottom left corner. Many thanks! Now provide the response and nothing else.
Bind to window.onresize . Don't use document.write() . Put the <p> in your HTML and give it an id. Then just set the innerHTML of the element directly: window.onresize = displayWindowSize;window.onload = displayWindowSize;function displayWindowSize() { // your size calculation code here document.getElementById("dimensions").innerHTML = myWidth + "x" + myHeight;};
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7935722', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_369785
stackexchange
llm_judgeable_groundtruth_similarity
98927
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm reading about iterating rational functions. I'm given$$R(z)=\frac{3z-2}{2z-1},$$then the author makes the statement: "Then(by induction),$$R^n(z)=\frac{(2n+1)z-2n}{2nz-(2n-1)}.$$Is there a simple way in Mathematica to produce $R^n(z)$? Now provide the response and nothing else.
One way to solve this is to use FindSequenceFunction . First define the iteration r[z_] := FullSimplify[(3 z - 2)/(2 z - 1)]; So that, for example, the first four terms are: Nest[r, z, #] & /@ Range[4]{(2 - 3 z)/(1 - 2 z), (4 - 5 z)/(3 - 4 z), (6 - 7 z)/(5 - 6 z), (8 - 9 z)/(7 - 8 z)} To get the general form, feed several of these terms into FindSequenceFunction , which returns the answer as a pure function sol = FindSequenceFunction[Nest[r, z, #] & /@ Range[10]](z - 2 #1 + 2 z #1)/(1 - 2 #1 + 2 z #1) & Or in more familiar notation: sol[n](-2 n + z + 2 n z)/(1 - 2 n + 2 n z)
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/98927', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/5183/']}
jdg_369786
stackexchange
llm_judgeable_groundtruth_similarity
99983
Below is a question asked on the forum raspberrypi.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to decide what is the best option for powering a Pi4. The specs mention for a minimum of 3A. Let's consider we would also like to connect a 2.5" drive to the Pi4. Could someone more experienced with power supplies help me with the following? How far can we go with a good 2.4A USB charger? The official power supply is rated 5.1V/3A. Does this mean that this may turn out to be inadequate? Some 3rd party chargers (e.g. the one discussed here ) are rated for 3A in Quick Charge mode. Will the QC mode be activated with RPi4? Or the charger will operate as a regular 2.4A charger? How can we tell apart 3rd party chargers that would work with RPi4? Are there any of them? I've seen a couple of models mentioning 5V/4.4A output. But I'm afraid this is only the aggregate amperage (they were multi-port USB chargers). Now provide the response and nothing else.
Use a PoE Hat: Third-party USB-C charging devices can be cheaply wired, potentially destroying connected devices as well as starting fires . A safer alternative is to power your Pi using PoE which beyond reducing these risks, offer additional benefits: Benefits : Using a PoE Hat is easy to setup and enables you to: Emplace a Pi at a much greater distance from a PoE switch than the 1.5 meter length of a standard charging cable. One cable for both data AND power; very elegant solution. A Pi can be started from a down state from across a network by simply toggling the PoE port it's connected to on "off" and "on" again. UPDATE: The dodgy non-compliant USB-C power port issue described in this link which has been now been fixed . Additional Requirements : In addition to a PoE Hat, you'll require a PoE switch and some decent Ethernet cables. Some suggestions for which I've had great results with my own PoE Hat use are: PoE Switch : ZyXEL GS1900-8HP-GB0102F : Lots of bells & whistles at a reasonable price. To restart your PoE powered Pi from cold just turn the port off and back on at the PoE switch. Ethernet Cables : Tripp Lite Cat6 Gigabit Snagless Molded Patch Cable . They're quality 24 AWG Ethernet cables at a value price. The link is for a 5 foot length cable which should suit an average use case, but Tripp sell much longer 24 AWG cables if you need more reach. NOTE: the LOWER the AWG cable rating then the BETTER the PoE performance . I use a minimum 24 AWG cable for PoE devices and avoid more common 26 and 28 AWG cables. Cost Comparison: Mains vs PoE: Total cost of a PoE Hat + 5 ft Tripp Cat6 24 AWG Ethernet cable = £20, versus £8/each for a "official" (genuine; not third-party) Raspberry Pi USB-C mains power supply unit. But for the £12 difference the additional benefits described above I feel are worth the small premium. Pi 4 Compatibility: Haven't myself yet been able to get a Pi 4 (vendors I tried were out of stock unsurprisingly) but found this link to a Register article about the Pi 4 which notes the PoE Hat IS compatible in their report on the new Pi
{}
{'log_upvote_score': 4, 'links': ['https://raspberrypi.stackexchange.com/questions/99983', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/104688/']}
jdg_369787
stackexchange
llm_judgeable_groundtruth_similarity
64842739
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 pods with two replicas, does it make sense that k8s will reschedule both replicas in the same time ?if yes is there a way to avoid it ? I guess(according to the replies from @Henry) that I need to use https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/#affinity-and-anti-affinity or topology https://kubernetes.io/blog/2020/05/introducing-podtopologyspread/ But not sure how to configure following: 1 application with 2 replicas that for example Replica A runs on nodeFoo and Replica B run in NodeBar Now provide the response and nothing else.
To configure the replicas to run on different nodes podAntiAffinity can be used. For example in the deployment spec: spec: template: metadata: labels: name: my-app-label spec: affinity: podAntiAffinity: requiredDuringSchedulingIgnoredDuringExecution: - labelSelector: matchLabels: name: my-app-label topologyKey: kubernetes.io/hostname This basically means, all pods matched by the label name=my-app-label should run on hosts where the node label kubernetes.io/hostname is different.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/64842739', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10817276/']}
jdg_369788
stackexchange
llm_judgeable_groundtruth_similarity
43767866
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to understand what the difference is between SLURM's srun and sbatch commands. I will be happy with a general explanation, rather than specific answers to the following questions, but here are some specific points of confusion that can be a starting point and give an idea of what I'm looking for. According to the documentation , srun is for submitting jobs, and sbatch is for submitting jobs for later execution, but the practical difference is unclear to me, and their behavior seems to be the same. For example, I have a cluster with 2 nodes, each with 2 CPUs. If I execute srun testjob.sh & 5x in a row, it will nicely queue up the fifth job until a CPU becomes available, as will executing sbatch testjob.sh . To make the question more concrete, I think a good place to start might be: What are some things that I can do with one that I cannot do with the other, and why? Many of the arguments to both commands are the same. The ones that seem the most relevant are --ntasks , --nodes , --cpus-per-task , --ntasks-per-node . How are these related to each other, and how do they differ for srun vs sbatch ? One particular difference is that srun will cause an error if testjob.sh does not have executable permission i.e. chmod +x testjob.sh whereas sbatch will happily run it. What is happening "under the hood" that causes this to be the case? The documentation also mentions that srun is commonly used inside of sbatch scripts. This leads to the question: How do they interact with each other, and what is the "canonical" usecase for each them? Specifically, would I ever use srun by itself? Now provide the response and nothing else.
The documentation says srun is used to submit a job for execution in real time while sbatch is used to submit a job script for later execution. They both accept practically the same set of parameters. The main difference is that srun is interactive and blocking (you get the result in your terminal and you cannot write other commands until it is finished), while sbatch is batch processing and non-blocking (results are written to a file and you can submit other commands right away). If you use srun in the background with the & sign, then you remove the 'blocking' feature of srun , which becomes interactive but non-blocking. It is still interactive though, meaning that the output will clutter your terminal, and the srun processes are linked to your terminal. If you disconnect, you will loose control over them, or they might be killed (depending on whether they use stdout or not basically). And they will be killed if the machine to which you connect to submit jobs is rebooted. If you use sbatch , you submit your job and it is handled by Slurm ; you can disconnect, kill your terminal, etc. with no consequence. Your job is no longer linked to a running process. What are some things that I can do with one that I cannot do with the other, and why? A feature that is available to sbatch and not to srun is job arrays . As srun can be used within an sbatch script, there is nothing that you cannot do with sbatch . How are these related to each other, and how do they differ for srun vs sbatch? All the parameters --ntasks , --nodes , --cpus-per-task , --ntasks-per-node have the same meaning in both commands. That is true for nearly all parameters, with the notable exception of --exclusive . What is happening "under the hood" that causes this to be the case? srun immediately executes the script on the remote host, while sbatch copies the script in an internal storage and then uploads it on the compute node when the job starts. You can check this by modifying your submission script after it has been submitted; changes will not be taken into account (see this ). How do they interact with each other, and what is the "canonical" use-case for each of them? You typically use sbatch to submit a job and srun in the submission script to create job steps as Slurm calls them. srun is used to launch the processes. If your program is a parallel MPI program, srun takes care of creating all the MPI processes. If not, srun will run your program as many times as specified by the --ntasks option. There are many use cases depending on whether your program is paralleled or not, has a long-running time or not, is composed of a single executable or not, etc. Unless otherwise specified, srun inherits by default the pertinent options of the sbatch or salloc which it runs under (from here ). Specifically, would I ever use srun by itself? Other than for small tests, no. A common use is srun --pty bash to get a shell on a compute job.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/43767866', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2593878/']}
jdg_369789
stackexchange
llm_judgeable_groundtruth_similarity
30271965
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 having a bit of trouble having a slider change the opacity value of my div. Here is a fiddle of what I've been working with: https://jsfiddle.net/yfmLk1ad/1/ $('#bgopacity').on('slide', function(value) { $('.background-color').css({ opacity: value * '.01' });}); .background-color { width: 500px; height: 500px; background: red; opacity: .5;} <div class="background-color"></div><form> <label>Color Opacity</label> <input type="range" name="bgopacity" id="bgopacity" value="50" min="0" max="100" step="1" onchange="rangevalue.value=value"> <output id="rangevalue">50</output></form> Now provide the response and nothing else.
You have to make use of change event. And to take the value of the slider like this ($(this).val() , not passing as parameter. This update the rectangle when you finished to choose the value. // Opacity Slider$('#bgopacity').on('change', function (value) { $('.background-color').css({ opacity: $(this).val() * '.01' });}); .background-color { width: 500px; height: 500px; background: red; opacity: .5;} <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><form> <label>Color Opacity</label> <input type="range" name="bgopacity" id="bgopacity" value="50" min="0" max="100" step="1" onchange="rangevalue.value=value"> <output id="rangevalue">50</output></form><div class="background-color"></div> For real time update you can use input event. This is updated when the value is changing. // Opacity Slider$('#bgopacity').on('input', function (value) { $('.background-color').css({ opacity: $(this).val() * '.01' });}); .background-color { width: 500px; height: 500px; background: red; opacity: .5;} <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><form> <label>Color Opacity</label> <input type="range" name="bgopacity" id="bgopacity" value="50" min="0" max="100" step="1" onchange="rangevalue.value=value"> <output id="rangevalue">50</output></form><div class="background-color"></div>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30271965', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1693705/']}
jdg_369790
stackexchange
llm_judgeable_groundtruth_similarity
29266622
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 an easy way to run a process with different privileges from the same user without asking or knowing his/her password. A dialog is okay if necessary. I would prefer not to launch a PowerShell sub-process to accomplish this. Scenario 1: PowerShell script is running in admin-mode. I want to launch a script or an .exe without admin privileges but on the same user. Scenario 2: PowerShell script is running in normal mode. I want to launch a script or an .exe with admin privileges on the same user. Now provide the response and nothing else.
Let's split this into three parts. First determine if current session is running with admin privileges: $CurrentID = [System.Security.Principal.WindowsIdentity]::GetCurrent()$CurrentPrincipal = new-object System.Security.Principal.WindowsPrincipal($CurrentID)$adminRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator# Check to see if session is currently with admin privilegesif ($CurrentPrincipal.IsInRole($adminRole)) { write-host "Yes we are running elevated."}else{ write-host "No this is a normal user session."} Now, if we are running with or without elevation, you can start a new process with elevated privileges like this: $newProc = new-object System.Diagnostics.ProcessStartInfo "PowerShell"# Specify what to run$newProc.Arguments = "powershell.exe"# If you set this, process will be elevated$newProc.Verb = "runas"[System.Diagnostics.Process]::Start($newProc) And lastly, if we have elevated privileges, but would like to start a new process without... I have no idea. Will have to try to find the answer to this, but as it is not a common scenario, I had no luck so far. EDIT: I have now seen a couple of “solutions” for this scenario. There is no native way to do this in .NET/PowerShell. Some are quite complicated (Calls to some 12 COM objects). This vista-7-uac-how-to-lower-process-privileges is a good reference. The one that seems most elegant to me, is exploiting a “bug” in explorer.exe. Just launch you .exe using explorer.exe and the resulting process runs without privilege elevation again. $newProc = new-object System.Diagnostics.ProcessStartInfo "PowerShell"# Specify what to run, you need the full path after explorer.exe$newProc.Arguments = "explorer.exe C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"[System.Diagnostics.Process]::Start($newProc) EDIT #2: Another way I have just found to start a new non-elevated process from an already elevated environment is to use the runas.exe with the 0x20000 (Basic User) trust level: C:\> runas /showtrustlevels The following trust levels are available on your system: 0x20000 (Basic User) C:\> runas /trustlevel:0x20000 devenv
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29266622', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/510994/']}
jdg_369791
stackexchange
llm_judgeable_groundtruth_similarity
393954
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 program which takes an SDL_Surface , converts it to an IplImage , uses the cvBlobsLib to find blobs, paints the blobs as spots back over the image, then converts the output IplImage back to an SDL_Surface . I'm almost done: only converting the IplImage back to an SDL_Surface hasn't been done yet. This IplImage has 3 image channels and is 8 bits per pixel. I think I have two calls I can use: SDL_Surface *SDL_CreateRGBSurface(Uint32 flags, int width, int height, int depth, Uint32 Rmask, Uint32 Gmask, Uint32 Bmask, Uint32 Amask);SDL_Surface *SDL_CreateRGBSurfaceFrom(void *pixels, int width, int height, int depth, int pitch, Uint32 Rmask, Uint32 Gmask, Uint32 Bmask, Uint32 Amask); I'm currently trying with SDL_CreateRGBsurfaceFrom . I have no idea, however, what the correct values of pitch, Rmask, Gmask and Bmask are. (Amask is 0, because there is no alpha channel.) Could anybody help me out by explaining how to do this? Thanks! Edit : For example, this is code I tried to use: SDL_Surface *ipl_to_surface (IplImage *opencvimg){ int pitch = opencvimg->nChannels*opencvimg->width; printf("Depth %d, nChannels %d, pitch %d\n", opencvimg->depth, opencvimg->nChannels, pitch); SDL_Surface *surface = SDL_CreateRGBSurfaceFrom((void*)opencvimg->imageData, opencvimg->width, opencvimg->height, opencvimg->depth, pitch, 0x0000ff, 0x00ff00, 0xff0000, 0 ); return surface;} (SDL Documentation writes "Pitch is the size of the scanline of the surface, in bytes, i.e. widthInPixels*bytesPerPixel.")This outputs "Depth 8, nChannels 3, pitch 1920" and displays a completely red image.I think a solution would be to convert my 8-bits image to 24-bits (1 byte per channel), but I don't know how to do that. Any ideas? Now provide the response and nothing else.
Ok, I got it working! I think I was confused by the fact that an OpenCV depth of 8 means a pixel has 8 bits per channel, so in a 3-channel image, a pixel has 24 bits . So when converting that to the SDL meaning of depth, we get 8 * 3 = 24 bits. The image was 24 bits after all, which SDL supports. So converting the image to SDL is as simple as: SDL_Surface *surface = SDL_CreateRGBSurfaceFrom((void*)opencvimg->imageData, opencvimg->width, opencvimg->height, opencvimg->depth*opencvimg->nChannels, opencvimg->widthStep, 0xff0000, 0x00ff00, 0x0000ff, 0 );return surface; Sorry for the confusion, I hope this helps anybody searching for the same answer. Other links of interest: http://www.libsdl.org/cgi/docwiki.cgi/Pixel_Access And the complete subroutine at: http://paster.dazjorz.com/?p=3714
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/393954', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13104/']}
jdg_369792
stackexchange
llm_judgeable_groundtruth_similarity
16793
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: In the field of Chemical Kinetics, terms like Molecularity and Order Of Reaction are often used. I am a bit confused between these two terms. Can someone explain to me about these two terms and their origins? Now provide the response and nothing else.
In fact, molecularity and order of reaction are identical if the reaction is elementary . They may become different when the reaction is complex and has a mechanism. The molecularity of a reaction is defined as the number of molecules or ions that participate in the rate determining step . A mechanism in which two reacting species combine in the transition state of the rate-determining step is called bimolecular. If a single species makes up the transition state, the reaction would be called unimolecular. The relatively improbable case of three independent species coming together in the transition state would be called termolecular. The order of a reaction is an experimentally derived number. Let's consider the general reaction: $\ce{A + B-> C + D}$ The reaction rate$=\ce{k[A]^n.[B]^m}$ where the rate constant $k$ is a proportionality constant that reflects the nature of the reaction, $\ce{[A]}$ is the concentration of reactant $\ce{A}$, $\ce{[B]}$ is the concentration of reactant $\ce{B}$, and $n$ & $m$ are the exponents used to fit the rate equation to the experimental data. Chemists refer to the sum $n + m $ as the kinetic order of a reaction. In a simple bimolecular reaction $n$ and $m$ would both be $1$, and the reaction would be termed second order, supporting a mechanism in which a molecule of reactant $\ce{A}$ and one of $\ce{B}$ are incorporated in the transition state of the rate-determining step. A bimolecular reaction in which two molecules of reactant $\ce{A}$ (and no $\ce{B}$) are present in the transition state would be expected to give a kinetic equation in which $n=2$ and $m=0$ (also second order).
{}
{'log_upvote_score': 5, 'links': ['https://chemistry.stackexchange.com/questions/16793', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/670/']}
jdg_369793
stackexchange
llm_judgeable_groundtruth_similarity
89850
Below is a question asked on the forum datascience.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a non-negative variable and I'd like to plot it, log-scaled I'm trying to understand how to deal with 0 -values. One naive idea I had in mind is just to add 1 to all values (or some very low number greater than 1 ) What other options are available? Thanks Now provide the response and nothing else.
Well, there are a few ways to do the job. Here are some I thought of: Scatterplots with noise: Normally, if you try to use a scatter plot to plot two categorical features, you would just get a few points, each one containing a lot of instances from the data. So, to get a sense of how many there really are in each point, we can add some random noise to each instance: import numpy as npimport seaborn as snsimport matplotlib.pyplot as plt%matplotlib inline# This is to encode the data into numbers that can be used in our scatterplotfrom sklearn.preprocessing import OrdinalEncoderord_enc = OrdinalEncoder()enc_df = pd.DataFrame(ord_enc.fit_transform(df), columns=list(df.columns))categories = pd.DataFrame(np.array(ord_enc.categories_).transpose(), columns=list(df.columns))# Generate the random noisexnoise, ynoise = np.random.random(len(df))/2, np.random.random(len(df))/2 # The noise is in the range 0 to 0.5# Plot the scatterplotplt.scatter(enc_df["Playing_Role"]+xnoise, enc_df["Bought_By"]+ynoise, alpha=0.5)# You can also set xticks and yticks to be your category names:plt.xticks([0.25, 1.25, 2.25], categories["Playing_Role"]) # The reason the xticks start at 0.25# and go up in increments of 1 is because the center of the noise will be around 0.25 and ordinal# encoded labels go up in increments of 1.plt.yticks([0.25, 1.25, 2.25], categories["Bought_By"]) # This has the same reason explained for xticks# Extra unnecessary styling...plt.grid()sns.despine(left=True, bottom=True) 2. Scatterplots with noise and hues: Instead of having both axis being feature we can have the $x$ axis be one feature andthe $y$ axis be random noise. Then, to incorporate the other feature, we can "colourin" instances based on the other feature: import numpy as npimport seaborn as snsimport matplotlib.pyplot as plt%matplotlib inline# Explained in approach 1from sklearn.preprocessing import OrdinalEncoderord_enc = OrdinalEncoder()enc_df = pd.DataFrame(ord_enc.fit_transform(df), columns=list(df.columns))categories = pd.DataFrame(np.array(ord_enc.categories_).transpose(), columns=list(df.columns))xnoise, ynoise = np.random.random(len(df))/2, np.random.random(len(df))/2sns.relplot(x=enc_df["Playing_Role"]+xnoise, y=ynoise, hue=df["Bought_By"]) # Notice how for hue# we use the original dataframe with labels instead of numbers.# We can also set the x axis to be our categoriesplt.xticks([0.25, 1.25, 2.25], categories["Playing_Role"]) # Explained in approach 1# Extra unnecessary styling...plt.yticks([])sns.despine(left=True) Catplots with hues: Finally, we can use catplots, and colour in fractions of it based on the other feature: import seaborn as snsimport matplotlib.pyplot as plt%matplotlib inlinesns.histplot(binwidth=0.5, x="Playing_Role", hue="Bought_By", data=df, stat="count", multiple="stack")
{}
{'log_upvote_score': 4, 'links': ['https://datascience.stackexchange.com/questions/89850', 'https://datascience.stackexchange.com', 'https://datascience.stackexchange.com/users/43268/']}
jdg_369794
stackexchange
llm_judgeable_groundtruth_similarity
50196282
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 angular 5.2.x for http get and post I had this code: post(url: string, model: any): Observable<boolean> {return this.http.post(url, model) .map(response => response) .do(data => console.log(url + ': ' + JSON.stringify(data))) .catch(err => this.handleError(err)); } get(url: string): Observable<any> {return this.http.get(url) .map(response => response) .do(data => console.log(url + ': ' + JSON.stringify(data)) ) .catch((error: any) => Observable.throw(this.handleError(error))); } In angular 6 it doesn't work. How can we make an HTTP post or get request? Now provide the response and nothing else.
Update :In angular 7, they are the same as 6 In angular 6 the complete answer found in live example /** POST: add a new hero to the database */ addHero (hero: Hero): Observable<Hero> { return this.http.post<Hero>(this.heroesUrl, hero, httpOptions) .pipe( catchError(this.handleError('addHero', hero)) );} /** GET heroes from the server */ getHeroes (): Observable<Hero[]> {return this.http.get<Hero[]>(this.heroesUrl) .pipe( catchError(this.handleError('getHeroes', [])) );} it's because of pipeable/lettable operators which now angular is able to use tree-shakable and remove unused imports and optimize the app some rxjs functions are changed do -> tapcatch -> catchErrorswitch -> switchAllfinally -> finalize more in MIGRATION and Import paths For JavaScript developers, the general rule is as follows: rxjs: Creation methods, types, schedulers and utilities import { Observable, Subject, asapScheduler, pipe, of, from, interval, merge, fromEvent } from 'rxjs'; rxjs/operators: All pipeable operators: import { map, filter, scan } from 'rxjs/operators'; rxjs/webSocket: The web socket subject implementation import { webSocket } from 'rxjs/webSocket'; rxjs/ajax: The Rx ajax implementation import { ajax } from 'rxjs/ajax'; rxjs/testing: The testing utilities import { TestScheduler } from 'rxjs/testing'; and for backward compatability you can use rxjs-compat
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/50196282', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5131929/']}
jdg_369795
stackexchange
llm_judgeable_groundtruth_similarity
31508923
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am currently developing custom application(company specific) integrated with LinkedIn. I have received data with basic profile access to fetch and fill some fields on my application and now I need full profile permission. But as answered in this question it is not allowed anymore. I see that there are partner programs are there. So I have following questions with me. How to get permission to access full profile data. Do I need to contact them? If so how to contact them. Is there any criterias to be completed ? if so if so criterias should I completed to be eligible. Is it involve any price? if so how much ? Thanks in advance. Now provide the response and nothing else.
QUESTION-1: For getting permission to access r_fullprofile , you will have to apply to become a member of a relevant Partner Program . Apply for partner status with LinkedIn, explaining what your integration is and how it works. If it meets the criteria of "we feel that they’re providing value to members, developers and LinkedIn," then r_fullprofile endpoint will remain open for that app, and ONLY that app. QUESTION-2: Yes, i think you would need to contact them apart from filling the relevant Partner Program form. They should reply to you about the status of the submitted application in about 15 business days. QUESTION-3: There are multiple conditions on which Linkedin reviews an application. If your application does not satisfy any of the conditions, then Linkedin rejects your application. Make sure you are satisfying their eligibility criteria. I have listed the various criterias which must be satisfied in order to become member of a relevant Linkedin Partner Program. Eligibilty Criteria for Linkedin Partner Program: (Taken from this linkedin page. ) You can use their APIs if: You are developing an Application designed to help LinkedIn members be more productive and successful across the web; for example, by augmenting their profile and professional brand in an Application for publishing, discussing and sharing content with like-minded professionals. Your Application is NOT expected to: have more than 250,000 lifetime members; make more than 500,000 daily calls to an API; make more than 500,000 lifetime people search calls to an API; or serve greater than 1 million daily plugin impressions. Your Application DOES NOT rely on access to the APIs as a fundamental aspect of your business. Your Application WILL NOT store or export any data from LinkedIn other than the LinkedIn Profile Data for the LinkedIn member that requested the data. “Profile Data” means the name, photo, headline, contact information, experience, education, summary, and location of a LinkedIn member. Profile Data excludes connections, network updates, job listings, groups, companies, and any other content. Your Application DOES NOT target current or potential paying customers of LinkedIn products or people engaging in activities related to those products—in other words, Applications used for hiring, marketing, or selling. Here are some examples (and exceptions) of what we mean by hiring, marketing and selling: Hiring: Applications to find a job or fill a job, such as ones used to advertise, post, apply for, search for, recommend, refer, suggest, enhance listings for, or fill permanent jobs, contract positions, or volunteer opportunities, or for anything with a similar functionality (you can, however, use the APIs to develop an Application to let people apply for a job on your company’s career site, as long as it abides by the specification set forth here). Marketing: Applications used by marketers or their customers for marketing campaigns, lead generation, campaign analysis, or for anything with similar functionality (you can, however, use the APIs to develop an Application to let companies manage their social media presence on LinkedIn, as long as it abides by Section 4.5(“Social Media Management: Company Profile and Statistics Data”)). Selling: Applications used by sales or other outbound professionals for generating or finding prospects or leads, for sales intelligence or training, for relationship management, for systematic matching of individuals with their LinkedIn profiles, or for anything with similar functionality. QUESTION-4: I don't think there is any such price for using their APIs. Taken from LinkedIn API usage terms of use : If you agree to and follow these terms, you are free to use our APIs. Hope this helps!
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/31508923', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/851514/']}
jdg_369796
stackexchange
llm_judgeable_groundtruth_similarity
39137
Below is a question asked on the forum arduino.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I want my C# application to automatically select the correct COM port by way of a string equality check against a 'GetInfo'-type request to the Arduino board. I know the Arduino IDE can get info from the board; Tools > GetBoardInfo But I don't know how to get it using a sketch or if it is even possible for that matter. Is this something that can be read from the board, or is it a USB-thing. If it's a USB thing, I'd have to get the info from GetUSBDevices.DeviceID or whatever, then get the serial port used by the USB Device, which would probably work, but I'd rather do it all via a serialPort . Now provide the response and nothing else.
Looking at the source code of the Arduino IDE on github, it looks like they call an executable (listComPorts.exe). So I would guess you can't get that info through serial. Here's a C# app using WMI that can get port, vid, and pid: namespace PortTest{ class Program { // Helper function to handle regex search static string regex(string pattern, string text) { Regex re = new Regex(pattern); Match m = re.Match(text); if (m.Success) { return m.Value; } else { return null; } } static void Main(string[] args) { // Use WMI to get info ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_PnPEntity WHERE ClassGuid=\"{4d36e978-e325-11ce-bfc1-08002be10318}\""); // Search all serial ports foreach (ManagementObject queryObj in searcher.Get()) { // Parse the data if (null != queryObj["Name"]) { Console.WriteLine("Port = " + regex(@"(\(COM\d+\))", queryObj["Name"].ToString())); } //PNPDeviceID = USB\VID_1A86&PID_7523\5&1A63D808&0&2 if (null != queryObj["PNPDeviceID"]) { Console.WriteLine("VID = " + regex("VID_([0-9a-fA-F]+)", queryObj["PNPDeviceID"].ToString())); Console.WriteLine("PID = " + regex("PID_([0-9a-fA-F]+)", queryObj["PNPDeviceID"].ToString())); } } Console.WriteLine("Done"); int c = Console.Read(); } }} From there, it looks like it searches an online database for more info. See: getBoardWithMatchingVidPidFromCloud() function.
{}
{'log_upvote_score': 4, 'links': ['https://arduino.stackexchange.com/questions/39137', 'https://arduino.stackexchange.com', 'https://arduino.stackexchange.com/users/34308/']}
jdg_369797
stackexchange
llm_judgeable_groundtruth_similarity
26736793
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 demo , first image automatically slides but each image that i put mouse on them must slide. I have added onmouseover event in html and gave a name to the main function like below but it didn't work. How can i do jQuery image slider with mouse over? HTML: <ul onmouseover="imageSlider()" id="exampleSlider"> <li><img src="http://placehold.it/500x250" alt="" /></li> <li><img src="http://placehold.it/500x260" alt="" /></li> <li><img src="http://placehold.it/500x270" alt="" /></li> <li><img src="http://placehold.it/500x280" alt="" /></li></ul><ul onmouseover="imageSlider()" id="exampleSlider"> <li><img src="http://placehold.it/500x250" alt="" /></li> <li><img src="http://placehold.it/500x260" alt="" /></li> <li><img src="http://placehold.it/500x270" alt="" /></li> <li><img src="http://placehold.it/500x280" alt="" /></li></ul> Javascript: function imageSlider () { /* SET PARAMETERS */ var change_img_time = 3000; var transition_speed = 300; var simple_slideshow = $("#exampleSlider"), listItems = simple_slideshow.children('li'), listLen = listItems.length, i = 0, changeList = function () { listItems.eq(i).fadeOut(transition_speed, function () { i += 1; if (i === listLen) { i = 0; } listItems.eq(i).fadeIn(transition_speed); }); }; listItems.not(':first').hide(); setInterval(changeList, change_img_time);}; Now provide the response and nothing else.
I'd redesign this to act streaming, instead of on a block. A simpler approach would be: std::ifstream ifs("input.txt");std::vector<uint64_t> parsed(std::istream_iterator<uint64_t>(ifs), {}); If you know roughly how many values are expected, using std::vector::reserve up front could speed it up further. Alternatively you can use a memory mapped file and iterate over the character sequence. How to parse space-separated floats in C++ quickly? shows these approaches with benchmarks for floats. Update I modified the above program to parse uint32_t s into a vector. When using a sample input file of 4.5GiB [1] the program runs in 9 seconds [2] : sehe@desktop:/tmp$ make -B && sudo chrt -f 99 /usr/bin/time -f "%E elapsed, %c context switches" ./test smaller.txtg++ -std=c++0x -Wall -pedantic -g -O2 -march=native test.cpp -o test -lboost_system -lboost_iostreams -ltcmallocparse successtrailing unparsed: ''data.size(): 4026531840:08.96 elapsed, 6 context switches Of course it allocates at least 402653184 * 4 * byte = 1.5 gibibytes. So whenyou read a 45 GB file, you will need an estimated 15GiB of RAM to just storethe vector (assuming no fragmentation on reallocation): The 45GiB parsecompletes in 10min 45s : make && sudo chrt -f 99 /usr/bin/time -f "%E elapsed, %c context switches" ./test 45gib_uint32s.txt make: Nothing to be done for `all'.tcmalloc: large alloc 17570324480 bytes == 0x2cb6000 @ 0x7ffe6b81dd9c 0x7ffe6b83dae9 0x401320 0x7ffe6af4cec5 0x40176f (nil)Parse successTrailing unparsed: 1 charactersData.size(): 4026531840Time taken by parsing: 644.64s10:45.96 elapsed, 42 context switches By comparison, just running wc -l 45gib_uint32s.txt took ~12 minutes (without realtime priority scheduling though). wc is blazingly fast Full Code Used For Benchmark #include <boost/spirit/include/qi.hpp>#include <boost/iostreams/device/mapped_file.hpp>#include <chrono>namespace qi = boost::spirit::qi;typedef std::vector<uint32_t> data_t;using hrclock = std::chrono::high_resolution_clock;int main(int argc, char** argv) { if (argc<2) return 255; data_t data; data.reserve(4392580288); // for the 45 GiB file benchmark // data.reserve(402653284); // for the 4.5 GiB file benchmark boost::iostreams::mapped_file mmap(argv[1], boost::iostreams::mapped_file::readonly); auto f = mmap.const_data(); auto l = f + mmap.size(); using namespace qi; auto start_parse = hrclock::now(); bool ok = phrase_parse(f,l,int_parser<uint32_t, 10>() % eol, blank, data); auto stop_time = hrclock::now(); if (ok) std::cout << "Parse success\n"; else std::cerr << "Parse failed at #" << std::distance(mmap.const_data(), f) << " around '" << std::string(f,f+50) << "'\n"; if (f!=l) std::cerr << "Trailing unparsed: " << std::distance(f,l) << " characters\n"; std::cout << "Data.size(): " << data.size() << "\n"; std::cout << "Time taken by parsing: " << std::chrono::duration_cast<std::chrono::milliseconds>(stop_time-start_parse).count() / 1000.0 << "s\n";} [1] generated with od -t u4 /dev/urandom -A none -v -w4 | pv | dd bs=1M count=$((9*1024/2)) iflag=fullblock > smaller.txt [2] obviously, this was with the file cached in the buffer cache on linux - the large file doesn't have this benefit
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26736793', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1075846/']}
jdg_369798
stackexchange
llm_judgeable_groundtruth_similarity
128788
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 been trying to work through Mac Lane's "Categories for the Working Mathematician" on my own, but I seem to be struggling with the concept of universality (arrows and elements). In particular, I seem unable to do one of the exercises in the book, which amounts to proving the familiar last 2 isomorphism theorems for groups: "Use only universality (of projections) to prove the following isomorphisms of group theory: (a) For normal subgroups $M$ and $N$ of $G$, with $M\subset N$, $(G/M)/(N/M)\cong G/N.$ (I believe there is a typo in the book, as it says $(G/M)/(N/M)\cong G/M$.) (b) For subgroups $S$ and $N$ of $G$, $N\lhd G$, $SN/N\cong S/(S\cap N)$." Any help with these two problems (or any info that would shed some light on the whole concept of universality) would be appreciated. Now provide the response and nothing else.
You could write the total using sigma notation as $$\sum_{k=0}^{20}(18+2k)\,$$ among many other ways, but I’m pretty sure that what’s wanted here is the actual total. You can add everything up by hand, which is a bit tedious, or you can use the standard formula for the sum of an arithmetic progression , if you know it, or you can be clever and arrange the sizes of the rows like this: $$\begin{array}{}18&20&22&24&26&28&30&32&34&36&38\\58&56&54&52&50&48&46&44&42&40\\ \hline76&76&76&76&76&76&76&76&76&76&38\end{array}$$ The bottom row is the sum of the top two, so adding it up gives you the total number of seats. And that’s easy: it’s $10\cdot 76+38=760+38=798$. This calculation is actually an adaptation to this particular problem of the usual derivation of the formula for the sum of an arithmetic progression, which in this particular case looks like this: $$\begin{array}{}18&20&22&24&26&\dots&50&52&54&56&58\\58&56&54&52&50&\dots&26&24&22&20&18\\ \hline76&76&76&76&76&\dots&76&76&76&76&76\end{array}$$ The top row is the original set of row sizes; the second consists of the same numbers in reverse order; and the bottom row is again the sum of the top two. That now counts each seat twice , so the total number of seats is $$\frac12(21\cdot 76)=798\;.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/128788', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/18121/']}
jdg_369799
stackexchange
llm_judgeable_groundtruth_similarity
16323776
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there any way to copy an array reference in VBA (or VB6)? In VBA, arrays are value types. Assigning one array variable to another copies the entire array. I want to get two array variables to point to the same array. Is there any way to accomplish this, perhaps using some API memory functions and/or the VarPtr function, which does in fact return the address of a variable in VBA? Dim arr1(), arr2(), ref1 As LongPtrarr1 = Array("A", "B", "C")' Now I want to make arr2 refer to the same array object as arr1' If this was C#, simply assign, since in .NET arrays are reference types:arr2 = arr1' ...Or if arrays were COM objects:Set arr2 = arr1' VarPtr lets me get the address of arr1 like this:ref1 = VarPtr(arr1)' ... But I don't know of a way to *set* address of arr2. Incidentally, it is possible to get multiple references to the same array by passing the same array variable ByRef to multiple parameters of a method: Sub DuplicateRefs(ByRef Arr1() As String, ByRef Arr2() As String) Arr2(0) = "Hello" Debug.Print Arr1(0)End SubDim arrSource(2) As StringarrSource(0) = "Blah"' This will print 'Hello', because inside DuplicateRefs, both variables' point to the same array. That is, VarPtr(Arr1) == VarPtr(Arr2)Call DuplicateRefs(arrSource, arrSource) But this still does not allow one to simply manufacture a new reference in the same scope as an existing one. Now provide the response and nothing else.
Yes, you can , if both variables are of type Variant. Here's why: The Variant type is itself a wrapper. The actual bit content of a Variant is 16 bytes. The first byte indicates the actual data type currently stored. The value corresponds exactly the VbVarType enum. I.e if the Variant is currently holding a Long value, the first byte will be 0x03 , the value of vbLong . The second byte contains some bit flags. For exampe, if the variant contains an array, the bit at 0x20 in this byte will be set. The use of the remaining 14 bytes depends on the data type being stored. For any array type, it contains the address of the array . That means if you directly overwrite the value of one variant using RtlMoveMemory you have in effect overwritten the reference to an array. This does in fact work! There's one caveat: When an array variable goes out of scope, the VB runtime will reclaim the memory that the actual array elements contained. When you have manually duplicated an array reference via the Variant CopyMemory technique I've just described, the result is that the runtime will try to reclaim that same memory twice when both variants go out of scope, and the program will crash. To avoid this, you need to manually "erase" all but one of the references by overwriting the variant again, such as with 0s, before the variables go out of scope. Example 1: This works, but will crash once both variables go out of scope (when the sub exits) Private Declare PtrSafe Sub CopyMemory Lib "kernel32" _ Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)Sub CopyArrayRef_Bad() Dim v1 As Variant, v2 As Variant v1 = Array(1, 2, 3) CopyMemory v2, v1, 16 ' Proof: v2(1) = "Hello" Debug.Print Join(v1, ", ") ' ... and now the program will crashEnd Sub Example 2: With careful cleanup, you can get away with it! Private Declare PtrSafe Sub CopyMemory Lib "kernel32" _ Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)Private Declare PtrSafe Sub FillMemory Lib "kernel32" _ Alias "RtlFillMemory" (Destination As Any, ByVal Length As Long, ByVal Fill As Byte)Sub CopyArrayRef_Good() Dim v1 As Variant, v2 As Variant v1 = Array(1, 2, 3) CopyMemory v2, v1, 16 ' Proof: v2(1) = "Hello" Debug.Print Join(v1, ", ") ' Clean up: FillMemory v2, 16, 0 ' All good!End Sub
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16323776', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/842685/']}
jdg_369800
stackexchange
llm_judgeable_groundtruth_similarity
16707
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 graphic is produced by running DominantColors (new in Mathematica 9) with different values, using the Lena image as the source: Each row is a list of the dominant colours in an image, when asking for between 2 and 60. However I'm surprised that the order of the colors keeps changing: why would the order depend on how many you asked for? Have I done something daft in my code? Or I have failed to grasp something obvious in the online documentation? (Either is likely.) With[{l = ExampleData[{"TestImage", "Lena"}]}, Graphics[ Table[{colorList = DominantColors[l, d]; {Table[{ colorList[[x]], Rectangle[{x - 1, 10 - d},{x, 10 - (d + 0.7)}] }, {x, 1, Length@colorList}]}}, {d, 2, 60}]]] Now provide the response and nothing else.
It's not just the order, the actual colours themselves can change depending on how many you ask for. Sometimes, these colours might not even be in your image! The reason is because DominantColors does a clustering operation and returns the mean of the n clusters in the LAB space and doesn't necessarily pick the colours that appear common to the eye (although, they coincide more often than not). To see what I mean, consider the following example: img = Image[{Blue, Green, Yellow, Orange, Red, Pink, Cyan} /. RGBColor -> ({{##}} &) // Transpose, ImageSize -> {300, 50}] Image[{List @@@ DominantColors[img, #]}, ImageSize -> {Automatic, 50}] & /@ Range@7 // Column Until you get to 5 dominant colours, there's always one colour in the list that's not in the original image. So to answer your question, just as you might expect a clustering operation on some random data to give you a centroid that's not an actual point in your data, DominantColors might return colours that are not in your image (but are close). This is the reason why you see some shuffling of the orders (the centroid for 2 clusters need not necessarily be the same for 3), although you can see that in general, they are roughly in the same normalized position.
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/16707', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/61/']}
jdg_369801
stackexchange
llm_judgeable_groundtruth_similarity
520113
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 reason we don't have any perpetual motion machines because of the first law of thermodynamics? Would it be possible to create one if (for example) there was a wheel, and it had a push– if it was frictionless, and in a vacuum, would it spin forever? Also, would gravity matter if friction wasn't in the equation? Now provide the response and nothing else.
Is the reason we don't have any perpetual motion machines because of the first law of thermodynamics? That's one of the reasons, and it applies to a perpetual motion machine of the first kind, a machine that can produce work without any energy input in violation of the first law (conservation of energy). There is also a perpetual motion machine of the second type, which is a machine that can operate in a cycle exchanging heat with only one temperature reservoir completely converting 100% of the heat into work. This machine violates the second law of thermodynamics. Would it be possible to create one if (for example) there was a wheel, and it had a push– if it was frictionless, and in a vacuum, would it spin forever? What you are describing is sometimes call a perpetual motion machine of the third kind. It is based on the idea that motion, once started, can continue forever. This requires the complete elimination of any and all forms of friction, which is not possible, even when operating in a vacuum (which in practice is never perfect). Even space is not completely free of particles. Also, would gravity matter if friction wasn't in the equation? Not quite sure what you mean by "would gravity matter". As the range of gravity is essentially infinite, it is impossible to completely isolate the machine from gravity and gravitational forces (Newtonian gravity). Hope this helps.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/520113', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/249382/']}
jdg_369802
stackexchange
llm_judgeable_groundtruth_similarity
119573
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: Just studying the paper PRIMES is in P , although I've tried great efforts, some proofs are still not so clear(or obvious) to me, especially the proof of Lemma 4.3 . The problem is by choosing r the smallest number that does not divide the product $n^{\lfloor logB \rfloor}\prod_{i=1}^{\lfloor log^2n\rfloor}{(n^i-1)}$, why the fact $(r, n)$ cannot be divisible by all the prime divisors of r holds? And why if violated, r will divide $n^{\lfloor logB \rfloor}$? Any relation with the observation "the largest value of $k$ for any number of the form $m^k \leq B$ , for $m > 2$ is $\lfloor logB \rfloor$"? And finally, the conclude of this proof, I cannot find trivial relation between $r$ and $B$, any theorem or fact I miss? Thanks and Best Regards! EDIT: Follow Will's advice below, I found the article linked above is a draft and referred to the published version . Much more clear indeed! However, there is still one point I'm not sure: At nearly the end of proof to lemma 4.3, the authors say "If $(s,n)>1$, then since $s$ does not divide $n$ and $(s,n)\in {r_1,r_2,…,r_t }$" then "$r=\frac{s}{(s,n)}\not\in {r_1,r_2,…,r_t }$". Where $r_i$ is defined as numbers either $o_r(n)\leq \log^{2} n$(which is the bound we want to approach, I think) or $r_i$ divides $n$ and $s$ is a number $\leq \lceil \log^{5}n\rceil$ such that $s\neq r_i$(previous lemma shows we can always find such an $s$ under the hypothesis). Why there is no pobability $o_r(n)\leq \log^{2}n$? In which case, seems no assumptions are voilated. Thank you! Now provide the response and nothing else.
Actually, the first paper ( version 6 ) you read is the more recent version; the annals of mathematics version was published first and contains an mistake in Lemma 4.3 (there's an acknowledgment in the version 6 paper noting the error). The problem is with the last line of the proof, which is exactly where you got stuck. Mistake in Lemma 4.3 of AKS (Annals of Math version) Given that $s \not \in \{r_1,\ r_2,\ ...,\ r_t\}$ and $(s,n) > 1$, it is not necessarily true that $\frac{s}{(s,n)} \not \in \{r_1,\ r_2,\ ...,\ r_t\}$. Consider the following: Since $s \not \in \{r_1,\ r_2,\ ...,\ r_t\}$, we know that $s$ doesn't divide $n$, and either $o_s(n) > \log_2^2(n)$ or $o_s(n)$ doesn't exist. If $(s,n) > 1$, then $o_s(n)$ doesn't exist, but that doesn't imply that the order of $n$ modulo $\frac{s}{(s,n)}$ is greater than $\log_2^2(n)$. Suppose $n = 8$. Then 6 is the first number we encounter that is not in $\{r_1,\ r_2,\ ...,\ r_t\}$, because $o_6(8)$ doesn't exist, and 6 doesn't divide 8. However, $\frac{6}{(6,8)} = \frac{6}{2} = 3$, and $3 \in \{r_1,\ r_2,\ ...,\ r_t\}$, because $o_3(8) = 2$, and $2 \leq \log_2^2(8) = 9$. My proof of Lemma 4.3 It turns out that the $n^{\lfloor\log(B)\rfloor}$ introduced in the newer version of the paper is necessary to address this kind of counterexample. I also found the version 6 proof rather difficult to understand; a lot of steps were left out. So below is an expanded proof I wrote myself! Hopefully it is more clear; let me know if anything doesn't make sense :) It breaks the proof down into three steps: finding a small enough $r$, proving that $o_r(n)$ exists, and finally showing that $o_r(n) > \log^2{n}$. Claim: There exists an $r \leq$ max$\{3,\lceil\log^5{n}\rceil\}$ such that $o_r(n) > \log^2{n}$. Proof: We know $n>1$. If $n=2$, we can let $r=3$, and since $2^2 = 4 \equiv 1 \text{ mod } 3$, $o_3(2) = 2$, while $\log^2{2} = 1$, so the statement holds. From here on, assume $n>2$. Note that $\lceil \log^5 3 \rceil = 11$, and since the logarithm function is monotonically increasing, we know that $\lceil \log^5 n \rceil > 10$ for all $n>2$. Let $B = \lceil \log^5 n \rceil$. Applying lemma 3.1, we have that $LCM(B) \geq 2^{B}$. First we will prove that there exists a number $r\leq B$ that doesn't divide the product$$N=n^{\lfloor\log{B}\rfloor} \cdot \displaystyle\prod_{i=1}^{\lfloor\log^2(n)\rfloor}(n^i-1)$$Suppose, by contradiction, that for all $1\leq r \leq B$, $r$ divides $N$. Then clearly $LCM(B) \leq N$, because $N$ itself is a common multiple of all numbers less than or equal to $B$. Notice that \begin{align*}N&=n^{\lfloor\log{B}\rfloor} \cdot \displaystyle\prod_{i=1}^{\lfloor\log^2(n)\rfloor}(n^i-1) \\&< n^{\lfloor\log{B}\rfloor} \cdot \displaystyle\prod_{i=1}^{\log^2(n)}(n^i) \\&= n^{\lfloor\log{B}\rfloor+1+2+...+\log^2(n)} \\&= n^{\lfloor\log{B}\rfloor+\frac{1}{2}(\log^2(n)((\log^2(n)+1))} \\&= n^{\lfloor\log{B}\rfloor+\frac{1}{2}(\log^4(n)+\log^2(n))} \\&< n^{\log^4(n)} \\&= (2^{\log(n)})^{\log^4(n)} \\&= 2^{\log(n)\cdot \log^4(n)}\\&= 2^{\log^5(n)}\\&\leq 2^{B}\end{align*}Therefore $N < 2^{B}$. Recall that $LCM(B) \geq 2^{B}$, so we have $LCM(B) > N$. However, we saw above that $LCM(B) \leq N$; a contradiction. Therefore the set of numbers between 1 and $B$ that do not divide $N$ is non-empty; let $r$ be the smallest element of this set. We've found an $r\leq B$; now we need to prove that $o_r(n)$ exists, and that $o_r(n) > \log^2{n}$. Recall that the order of $n$ modulo $r$ only exists if $(r,n) = 1$. We shall prove that this is the case. Write $r=ab$, where the prime factors of $a$ are precisely the prime factors of $r$ which divide $n$, and $b$ is made up of the remaining prime factors. Clearly $(b,n) = 1$, since $n$ and $b$ have no common prime factors. Notice that the highest power any prime could be raised to in the prime factorization of $a$ is $\lfloor \log{B}\rfloor$, since otherwise $a \leq r$ would be greater than $B$ (this is from the observation that "the largest value of $k$ for any number of the form $m^k \leq B$ , for $m\geq2$ is $\lfloor \log{B}\rfloor$" from the AKS paper). Therefore, every prime factor in $a$ is raised to a smaller exponent than the same factor in $n^{\lfloor\log{B}\rfloor}$, and since every prime factor of $a$ is present in $n$, it must be the case that $a$ divides $n^{\lfloor\log{B}\rfloor}$. It follows that $b$ does not divide $\displaystyle\prod_{i=1}^{\lfloor\log^2(n)\rfloor}(n^i-1)$, because if it did, then $r = ab$ would divide $N$, and we chose $r$ such that this isn't the case. However, it is also true that $b$ does not divide $n^{\lfloor\log{B}\rfloor}$, since $(b,n) = 1$. Therefore $b$ doesn't divide $N$. But we know $r$ is the smallest number that doesn't divide $N$ and $b \leq r$, so it must be the case that $r = b$. So since $(b,n) = 1$, we have $(r,n) = 1$. Therefore, the order of $n$ modulo $r$ exists. All that remains to be shown is that $o_r(n) > \log^2{n}$. This, fortunately, is almost trivial. Suppose by contradiction that $o_r(n) = d \leq \log^2{n}$. Then by definition, $n^d \equiv 1$ mod $r$, which implies $n^d -1 \equiv 0$ mod $r$, and so $r | (n^d -1)$, for a value of $d$ which is less than or equal to $\log^2{n}$. But then $r$ would divide one of the factors within the product of $N$, and we know that $r$ does not divide $N$. Therefore, $o_r(n) > \log^2{n}$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/119573', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/1294/']}
jdg_369803
stackexchange
llm_judgeable_groundtruth_similarity
26234361
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Just wondering is it possible to do something like this with d3? http://jsfiddle.net/8T7Ew/ Where when you click on a certain pie slice the slice moves on click? Have the pie created up to this point just wondering if I can add this feature <!DOCTYPE html><meta charset="utf-8"><style>body { font: 10px sans-serif;}.arc path { stroke: #fff;}</style><body><script src="http://d3js.org/d3.v3.min.js"></script><script>var width = 960, height = 500, radius = Math.min(width, height) / 2;var color = d3.scale.ordinal() .range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);var arc = d3.svg.arc() .outerRadius(radius - 10) .innerRadius(0);var pie = d3.layout.pie() .sort(null) .value(function(d) { return d.population; });var svg = d3.select("body").append("svg") .attr("width", width) .attr("height", height) .append("g") .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");d3.csv("data.csv", function(error, data) { data.forEach(function(d) { d.population = +d.population; }); var g = svg.selectAll(".arc") .data(pie(data)) .enter().append("g") .attr("class", "arc"); g.append("path") .attr("d", arc) .style("fill", function(d) { return color(d.data.age); }); g.append("text") .attr("transform", function(d) { return "translate(" + arc.centroid(d) + ")"; }) .attr("dy", ".35em") .style("text-anchor", "middle") .text(function(d) { return d.data.age; });});</script> Data is coming from a csv file. Thanks Now provide the response and nothing else.
You can increase the arc radius of pie for highlighting. JSFiddle var arcOver = d3.svg.arc() .outerRadius(r + 10);g.append("path") .attr("d", arc) .style("fill", function(d) { return color(d.data.age); }) .on("mouseenter", function(d) { d3.select(this) .attr("stroke","white") .transition() .duration(1000) .attr("d", arcOver) .attr("stroke-width",6); }) .on("mouseleave", function(d) { d3.select(this).transition() .attr("d", arc) .attr("stroke","none"); });
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26234361', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3213111/']}
jdg_369804
stackexchange
llm_judgeable_groundtruth_similarity
3325081
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to write a batch file that performs the following operations: Check if a service is running If is it running, quit the batch If it is not running, start the service The code samples I googled so far turned out not to be working, so I decided not to post them. Starting a service is done by: net start "SERVICENAME" How can I check if a service is running, and how to make an if statement in a batchfile? I'm a bit confused. What is the argument I have to pass onto the net start? The service name or its display name? Now provide the response and nothing else.
To check a service's state, use sc query <SERVICE_NAME> . For if blocks in batch files, check the documentation . The following code will check the status of the service MyServiceName and start it if it is not running (the if block will be executed if the service is not running): for /F "tokens=3 delims=: " %%H in ('sc query "MyServiceName" ^| findstr " STATE"') do ( if /I "%%H" NEQ "RUNNING" ( REM Put your code you want to execute here REM For example, the following line net start "MyServiceName" )) Explanation of what it does: Queries the properties of the service. Looks for the line containing the text "STATE" Tokenizes that line, and pulls out the 3rd token, which is the one containing the state of the service. Tests the resulting state against the string "RUNNING" As for your second question, the argument you will want to pass to net start is the service name, not the display name.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/3325081', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/225808/']}
jdg_369805
stackexchange
llm_judgeable_groundtruth_similarity
2929450
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I want to find the limit $$\lim_{x\rightarrow 0} \frac{5^x-3^x}{3^x-2^x}$$ My efforts: $$\lim_{x\rightarrow 0} \frac{5^x-3^x}{3^x-2^x}=\lim_{x\rightarrow 0}\frac{5^x((3/5)^x-1)}{3^x((2/3)^x-1)}$$ Multiplying and dividing numerator and denominator by $x$ we get, $$\lim_{x\rightarrow 0}\frac{5^x\frac{((3/5)^x-1)}{x-0}}{3^x\frac{((2/3)^x-1)}{x-0}}\tag{1}$$ Let, $$f(x)=(3/5)^x-1, g(x)=(2/3)^x-1$$ Now $$\lim_{x\rightarrow 0}\frac{f(x)-f(0)}{x-0}=f'(x)$$ and similarly for $g$ , we can rewrite $(1)$ as $$\lim_{x\rightarrow 0} \frac{5^x}{3^x}\times \frac{f'(0)}{g'(0)}\tag{2}$$ We know if $h(x)=a^x,$ then $h'(x)=a^x \log(a)$ Computing and putting everything in piece, we write $(2)$ as $$\lim_{x\rightarrow 0}\frac{\log(3/5)}{\log(2/3)}$$ So we get limit equal to $\frac{\log(3/5)}{\log(2/3)}$ . Is my computation correct? Now provide the response and nothing else.
or, for $A > 1,$ $$ A^x = e^{x \log A} = 1 + x \log A + O( x^2) $$ so you have $$ \frac{1 + x \log 5 -1 - x \log 3 + O(x^2)}{1 + x \log 3 -1 - x \log 2 + O(x^2)} = \frac{x (\log 5 - \log 3) + O(x^2)}{x (\log 3 - \log 2) + O(x^2)} = \frac{ \log 5 - \log 3 + O(x)}{ \log 3 - \log 2 + O(x)} $$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2929450', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/581242/']}
jdg_369806
stackexchange
llm_judgeable_groundtruth_similarity
344860
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Let's say I have the three following lists A1 A2 A3 B1 B2 C1 C2 C3 C4 C5 I'd like to combine them into a single list, with the items from each list as evenly distributed as possible sorta like this: C1 A1 C2 B1 C3 A2 C4 B2 A3 C5 I'm using .NET 3.5/C# but I'm looking more for how to approach it then specific code. EDIT: I need to keep the order of elements from the original lists. Now provide the response and nothing else.
Take a copy of the list with the most members. This will be the destination list. Then take the list with the next largest number of members. divide the destination list length by the smaller length to give a fractional value of greater than one. For each item in the second list, maintain a float counter. Add the value calculated in the previous step, and mathematically round it to the nearest integer (keep the original float counter intact). Insert it at this position in the destination list and increment the counter by 1 to account for it. Repeat for all list members in the second list. Repeat steps 2-5 for all lists. EDIT: This has the advantage of being O(n) as well, which is always nice :)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/344860', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1786/']}
jdg_369807
stackexchange
llm_judgeable_groundtruth_similarity
54511330
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: We can cast Span<T> and ReadOnlySpan<T> to another using MemoryMarshal.Cast method overloads. Like : Span<byte> span = stackalloc byte[4];var singleIntSpan = MemoryMarshal.Cast<byte, int>(span); But is there any way to cast Memory<T> to another? for example cast Memory<byte> to Memory<ushort> . Now provide the response and nothing else.
You can't do it directly ; however, if you really need , you can create a custom MemoryManager<T> (presumably actually a MyMemoryManager<TFrom, TTo> : MemoryManager<TTo> that performs the cast as part of the GetSpan() override. This is slightly non-trivial, and demands another allocation - unlike a Span<T> cast, which is allocation-free. If you need a concrete example of that, I can whip one up (I actually do exactly this in some existing code), but: to be honest, you probably want to reconsider the scenario instead. Edit: something like this: using System;using System.Buffers;using System.Runtime.InteropServices;class Program{ static void Main() { Memory<byte> bytes = new byte[1024]; Memory<ushort> typed = Utils.Cast<byte, ushort>(bytes); Console.WriteLine(typed.Length); // 512 // note CPU endianness matters re the layout typed.Span[0] = 0x5432; Console.WriteLine(bytes.Span[0]); // 50 = 0x32 Console.WriteLine(bytes.Span[1]); // 84 = 0x54 }}static class Utils{ public static Memory<TTo> Cast<TFrom, TTo>(Memory<TFrom> from) where TFrom : unmanaged where TTo : unmanaged { // avoid the extra allocation/indirection, at the cost of a gen-0 box if (typeof(TFrom) == typeof(TTo)) return (Memory<TTo>)(object)from; return new CastMemoryManager<TFrom, TTo>(from).Memory; } private sealed class CastMemoryManager<TFrom, TTo> : MemoryManager<TTo> where TFrom : unmanaged where TTo : unmanaged { private readonly Memory<TFrom> _from; public CastMemoryManager(Memory<TFrom> from) => _from = from; public override Span<TTo> GetSpan() => MemoryMarshal.Cast<TFrom, TTo>(_from.Span); protected override void Dispose(bool disposing) { } public override MemoryHandle Pin(int elementIndex = 0) => throw new NotSupportedException(); public override void Unpin() => throw new NotSupportedException(); }} If you really want to support pin/unpin, that should be possible - you'll just need to compute the relative ranges and offsets from the competing TFrom / TTo , though - presumably using Unsafe.SizeOf<T> etc, and using MemoryMarshal.TryGetMemoryManager to get the underlying memory manager (if one - note that naked arrays don't have a memory manager). Unless you're going to extensively test that option, throwing is probably safer than getting it wrong.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/54511330', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5592276/']}
jdg_369808
stackexchange
llm_judgeable_groundtruth_similarity
7744912
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 away to make a javascript string being passed to NodeJS friendly for MySQL? I'm trying to pass an email address to my NodeJS server and query into MySQL database. When doing regular text such as a username works fine, but the email address doesn't. Using escape clearly is not the right answer as it is not meant for SQL insertion. I'm assuming I need something on the lines of the PHP function mysql_real_escape_string() . Now provide the response and nothing else.
It turns out that mysql_real_escape_string() is pretty trivial. According to the documentation : mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, which prepends backslashes to the following characters: \x00, \n, \r, \, ', " and \x1a. Sounds pretty simple, actually. You could do something like this: function mysql_real_escape_string (str) { return str.replace(/[\0\x08\x09\x1a\n\r"'\\\%]/g, function (char) { switch (char) { case "\0": return "\\0"; case "\x08": return "\\b"; case "\x09": return "\\t"; case "\x1a": return "\\z"; case "\n": return "\\n"; case "\r": return "\\r"; case "\"": case "'": case "\\": case "%": return "\\"+char; // prepends a backslash to backslash, percent, // and double/single quotes default: return char; } });} NOTE : I haven't run this through any sort of unit test or security test, but it does seem to work -- and, just as an added bonus, it escapes tabs, backspaces, and '%' so it can also be used in LIKE queries, as per OWASP's recommendations (unlike the PHP original). I do know that mysql_real_escape_string() is character-set-aware, but I'm not sure what benefit that adds. There's a good discussion of these issues over here .
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7744912', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/673648/']}
jdg_369809
stackexchange
llm_judgeable_groundtruth_similarity
76706
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to use Group Policy Preferences to manage user connections to shared printers. The print server is Windows Server 2003 R2 Std edition. Several printers are installed, and I've added x64 editions of all the drivers to the print server as well. I've created a new GPO containing the printer preference settings. Printer mappings are targeted based on AD security group membership. I log on to a Windows XP PC with the Group Policy CSEs installed and the printer maps perfectly. I log on to a Windows 7 x64 PC and it doesn't map. If I manually connect to the shared printer, I get a prompt which asks me to confirm if I trust the server before installing the driver, and then it works perfectly. I have domain admin rights and my UAC settings have not been changed from the default, i.e. UAC is enabled and the default level is selected. Is the printer mapping failing because it's unable to prompt me to install the driver, or is there something else afoot? Now provide the response and nothing else.
OK I managed to get this working. For Vista there is a Group Policy setting (more info here ): User Configuration/Policies/Admin Templates/Control Panel/Printers Configuring the "Point and Print Restrictions" policy setting to "Disabled" will allow for silent printer driver installation, and thus allow the printer to be mapped successfully. After struggling for the better part of this morning trying to figure out why this didn't work on Windows 7, I eventually discovered that Windows 7 and Server 2008 R2 ignore this policy setting. There is an equivalent setting under: Computer Configuration/Policies/Admin Templates/Printers This is honoured by Windows 7 and Server 2008 R2 See TechNet for more info.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/76706', 'https://serverfault.com', 'https://serverfault.com/users/4487/']}
jdg_369810
stackexchange
llm_judgeable_groundtruth_similarity
7562653
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 a snippet class T{ int y; public static void main(String... s){ int x; System.out.println(x); System.out.println(y); }} Here there are two error, but on compilation why only one error is shown? The error shown is: non-static variable y cannot be referenced from a static context System.out.println(y); ^ But what about the error variable x might not have been initialized System.out.println(x); ^ Now provide the response and nothing else.
The Java compiler compiles your code in several passes . In each pass, certain kinds of errors are detected. In your example, javac doesn't look to see whether x may be initialised or not, until the rest of the code actually passes the previous compiler pass.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7562653', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/725306/']}
jdg_369811
stackexchange
llm_judgeable_groundtruth_similarity
3843171
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 do unit testing when you have some general unit tests more sophisticated tests checking edge cases, depending on the general ones To give an example, imagine testing a CSV-reader (I just made up a notation for demonstration), def test_readCsv(): ...@dependsOn(test_readCsv)def test_readCsv_duplicateColumnName(): ...@dependsOn(test_readCsv)def test_readCsv_unicodeColumnName(): ... I expect sub-tests to be run only if their parent test succeeds. The reason behind this is that running these tests takes time. Many failure reports that go back to a single reason wouldn't be informative, either. Of course, I could shoehorn all edge-cases into the main test, but I wonder if there is a more structured way to do this. I've found these related but different questions, How to structure unit tests that have dependencies? Unit Testing - Is it bad form to have unit test calling other unit tests UPDATE: I've found TestNG which has great built-in support for test dependencies. You can write tests like this, @Test{dependsOnMethods = ("test_readCsv"))public void test_readCsv_duplicateColumnName() { ...} Now provide the response and nothing else.
Personally, I wouldn't worry about creating dependencies between unit tests. This sounds like a bit of a code smell to me. A few points: If a test fails, let the others fail to and get a good idea of the scale of the problem that the adverse code change made. Test failures should be the exception rather than the norm, so why waste effort and create dependencies when the vast majority of the time (hopefully!) no benefit is derived? If failures happen often, your problem is not with unit test dependencies but with frequent test failures. Unit tests should run really fast. If they are running slow, then focus your efforts on increasing the speed of these tests rather than preventing subsequent failures. Do this by decoupling your code more and using dependency injection or mocking.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3843171', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/380587/']}
jdg_369812
stackexchange
llm_judgeable_groundtruth_similarity
1130713
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I want to find the non-negative integer solutions of the diophantine equation $$x^2+2y^2=z^2 \ \ \ \ , \ \ \ \ \gcd(x,y,z)=1$$ It holds that $(x,y)=(y,z)=(x,z)=1$. That's what I have tried: $$2y^2=z^2-x^2=(z-x)(z+x)$$ $$2 \mid (z-x)(z+x) \Rightarrow (z-x)(z+x)=2k, k \in \mathbb{Z}$$ Let $(z-x,z+x)=d>1$ Then $d$ has a prime divisor, let $p$. $p \mid d, d \mid z-x, d \mid z+x \Rightarrow p \mid z-x \text{ and } p \mid z+x \Rightarrow p \mid 2z \text{ and } p \mid 2x \Rightarrow p \mid 2(x,y)=2 \Rightarrow p=2$ So:$$2 \mid z-x \Rightarrow z-x=2x_1, x_1 \in \mathbb{Z}$$ $$2 \mid z+x \Rightarrow z+x=2z_1, z_1 \in \mathbb{Z}$$ So $2y^2=2x_1 \cdot 2z_1 \Rightarrow y^2=2x_1 z_1$. So it has to hold $x_1=2l, z_1=l, l \in \mathbb{Z}$. So $z=x+2x_1=x+4l \text{ and } z=2x_1-x=4l-x \Rightarrow x+4l=4l-x \Rightarrow x=0$. $$z=4l$$ $$y=2l$$ Could you tell me if it is right? Now provide the response and nothing else.
I know it has been answered, but i will give an algorithm to find explicitly those permutations. Observe that the result of the conjugation by $\sigma$ in the centralizer may give $(12)(34)$ written in a different but equivalent way, with its integers and cycle order interchanged (in fact, the only permutation in the centralizer which does not change the way of expression is $(1)$ ). For example, $\sigma = (13)(24)$ in the centralizer gives us $\sigma(12)(34) \sigma^{-1} = (34)(12)$ (which is indeed equal to $(12)(34)$ ) when calculating via the application of $\sigma$ to the integers of $(12)(34)$. Using this idea, we just have to find then all the equivalent ways to express $(12)(34)$. Those ways are exactly: $$(12)(34),(12)(43),(21)(34),(21)(43),(34)(12),(43)(12),(43)(21),(34)(21)$$ which are $8$ in total. Now to find those permutations you can simply use the fact that the result of the conjugation is just the application of $\sigma$ to the integers of $(12)(34)$. For example, to find for $(43)(12)$, $\sigma$ must satisfy: $\sigma(1)=4,\sigma(2)=3,\sigma(3)=1,\sigma(4)=2;$ which is $\sigma =(1423). $
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1130713', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/75843/']}
jdg_369813
stackexchange
llm_judgeable_groundtruth_similarity
160689
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm sorry if this is a ABSOLUTELY sophomoric question, but I'm curious what the best practices are out there, and I can't seem to find a good answer on Google. In Python, I usually use an empty class as a super-catchall data structure container (sort of like a JSON file), and add attributes along the way: class DataObj: "Catch-all data object" def __init__(self): passdef processData(inputs): data = DataObj() data.a = 1 data.b = "sym" data.c = [2,5,2,1] This gives me a tremendous amount of flexibility, because the container object can essentially store anything. So if new requirements crop up, I'll just add it as another attribute to the DataObj object (which I pass around in my code). However, recently it has been impressed upon me (by FP programmers) that this is an awful practice, because it makes it very hard to read the code. One has to go through all the code to figure out what attributes DataObj actually has. Question : How can I rewrite this for greater maintainability without sacrificing flexibility? Are there any ideas from functional programming that I can adopt? I'm looking for best-practices out there. Note : one idea is to pre-initialize the class with all the attributes that one expects to encounter, e.g. class DataObj: "Catch-all data object" def __init__(self): data.a = 0 data.b = "" data.c = []def processData(inputs): data = DataObj() data.a = 1 data.b = "sym" data.c = [2,5,2,1] Is this actually a good idea? What if I don't know what my attributes are a priori? Now provide the response and nothing else.
How can I rewrite this for greater maintainability without sacrificing flexibility? You don't. The flexibility is precisely what causes the problem. If any code anywhere may change what attributes an object has, maintainability is already in pieces. Ideally, every class has a set of attributes that's set in stone after __init__ and the same for every instance. Not always possible or sensible, but it should the case whenever you don't have really good reasons for avoiding it. one idea is to pre-initialize the class with all the attributes that one expects to encounter That's not a good idea. Sure, then the attribute is there, but may have a bogus value, or even a valid one that covers up for code not assigning the value (or a misspelled one). AttributeError is scary, but getting wrong results is worse. Default values in general are fine, but to choose a sensible default (and decide what is required) you need to know what the object is used for. What if I don't know what my attributes are a priori? Then you're screwed in any case and should use a dict or list instead of hardcoding attribute names. But I take it you meant "... at the time I write the container class". Then the answer is: "You can edit files in lockstep, duh." Need a new attribute? Add a frigging attribute to the container class. There's more code using that class and it doesn't need that attribute? Consider splitting things up in two separate classes (use mixins to stay DRY), so make it optional if it makes sense. If you're afraid of writing repetive container classes: Apply metaprogramming judiciously, or use collections.namedtuple if you don't need to mutate the members after creation (your FP buddies would be pleased).
{}
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/160689', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/17205/']}
jdg_369814
stackexchange
llm_judgeable_groundtruth_similarity
59139211
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 simple Declarative Pipeline with function inside. How to correctly use named arguments for a function? def getInputParams(param1='a', param2='b') { echo "param1 is ${param1}, param2 is ${param2}"}pipeline {...... stages { stage('Test') { steps { getInputParams(param1='x', param2='y') } } }} I cannot understand why named params become null in function? [Pipeline] echoparam1 is null, param2 is null... Well, I'm able to call function like getInputParams('x', 'y') , but it's not human readable (arguments amount may increase in future) Now provide the response and nothing else.
Groovy is executed inside the Jenkinsfile so you have to follow its syntax for named arguments. foo(name: 'Michael', age: 24)def foo(Map args) { "${args.name}: ${args.age}" } Quote from Groovy's named arguments : Like constructors, normal methods can also be called with namedarguments. They need to receive the parameters as a map. In the methodbody, the values can be accessed as in normal maps (map.key). def getInputParams(Map map) { echo "param1 is ${map.param1}, param2 is ${map.param2}"}pipeline {... stages { stage('Test') { steps { getInputParams(param1: 'x', param2: 'y') } } }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/59139211', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5980797/']}
jdg_369815
stackexchange
llm_judgeable_groundtruth_similarity
46968185
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 create a Uri using the UriBuilder like this: var rootUrl = new UriBuilder("http", "example.com", 50000).Uri; then the AbsoluteUri of rootUrl always contain a trailing slash like this: http://example.com:50000/ What I would like, is to create a Uri object without the trailing slash, but it seems impossible. My workaround is to store it as a string instead, and do something ugly like this: var rootUrl = new UriBuilder("http", "example.com", 50000).Uri.ToString().TrimEnd('/'); I have heard people say that without the trailing slash, the Uri is invalid. I don't think that is true. I have looked through RFC 3986, and in section 3.2.2 it says: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character. It doesn't say that the trailing slash has to be there. Now provide the response and nothing else.
The trailing slash is not required in an arbitrary URI, but it is the part of the canonical representation of an absolute URI for requests in HTTP : Note that the absolute path cannot be empty; if none is present in the original URI, it MUST be given as "/" (the server root). To adhere to the spec , the Uri class outputs a URI in the form with a trailing slash: In general, a URI that uses the generic syntax for authority with an empty path should be normalized to a path of "/". This behavior is not configurable on a Uri object in .NET. Web browsers and many HTTP clients perform the same rewriting when sending requests for URLs with an empty path. If we want to internally represent our URL as a Uri object, not a string, we can create an extension method that formats the URL without the trailing slash, which abstracts this presentation logic in one location instead of duplicating it every time we need to output the URL for display: namespace Example.App.CustomExtensions { public static class UriExtensions { public static string ToRootHttpUriString(this Uri uri) { if (!uri.IsHttp()) { throw new InvalidOperationException(...); } return uri.Scheme + "://" + uri.Authority; } public static bool IsHttp(this Uri uri) { return uri.Scheme == "http" || uri.Scheme == "https"; } }} Then: using Example.App.CustomExtensions;...var rootUrl = new UriBuilder("http", "example.com", 50000).Uri; Console.WriteLine(rootUrl.ToRootHttpUriString()); // "http://example.com:50000"
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46968185', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5360099/']}
jdg_369816
stackexchange
llm_judgeable_groundtruth_similarity
382128
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: The LHC is much larger than its predecessors, and proposed successors much larger still. Today, particle accelerators seem to be the main source of new discoveries about the fundamental nature of the world. My lay interpretation is that particle accelerators like the LHC are essentially the only viable apparatus for performing experiments in particle physics, passive detectors of naturally energized particles notwithstanding. Experiments vary by configuration, sensors and source material, but the need for an accelerator is constant, and more powerful accelerators are able to perform experiments which are out of reach to less powerful accelerators. For the most powerful accelerators, "more powerful" seems to imply "physically larger". In these ring-shaped accelerators, for a given type of particle, its maximum power appears to be (very) roughly proportionate to circumference. I use the word "power" in a loose sense here, reflecting my loose grasp of its meaning. Technology upgrades can make an accelerator more powerful without making it larger, e.g. the planned High Luminosity upgrade to the LHC. One imagines that an upgrade would be cheaper to build than a colossal new accelerator, yet larger accelerators are still built, so it would seem to follow that the upgrade potential of a given accelerator is limited in some way - that there is, in fact, a relationship between the size of an accelerator and its maximum power. The first part of my question is this: what is the nature of the relationship between the size and power of a modern particle accelerator? Are there diminishing returns to the operating cost of making an accelerator more powerful? Or are there fundamental physical constraints placing a hard limit on how powerful an accelerator of a given size can be? Or is technology the main limiting factor - is it conceivable that orders-of-magnitude power increases could be efficiently achieved in a small accelerator with more advanced technology? Is it likely? The basic premise of these experiments seems to be that we observe the collision byproducts of energetic particles, where "energetic" presumably refers to kinetic energy, since we used an "accelerator" to energize them. To create interesting collision byproducts, the kinetic energy in the collision (measured in eV) must be at least as large as the mass of the particle (also measured in eV) we wish to create. Thus, we can observe particles of higher mass with a higher powered accelerator. The second part of my question is this: are particle accelerators the only way of pushing the boundaries of experimental particle physics? Is it conceivable that there is a way to produce these interesting byproducts in an experimental setting without using high-energy collisions? If not, is it conceivable that there is a way to energize particles other than by accelerating them around a track? If not, is it impossible by definition or for some physical reason? If either of these alternatives are conceivable, then assuming they're not practical replacements for large accelerators today, is it possible that they will be in the future? Is it likely? In a sentence, my question is this: is the future of experimental particle physics now just a matter of building larger and larger particle accelerators? Now provide the response and nothing else.
There are many competing limits on the maximum energy an accelerator like the LHC (i.e. a synchrotron, a type of circular accelerator) can reach. The main two are energy loss due to bremsstrahlung (also called synchrotron radiation in this context, but that's a much less fun name to say) and the bending power of the magnets. The bending power of the magnets isn't that interesting. There's a maximum magnetic field that we can acquire with current technology, and the strength of it fundamentally limits how small the circle can be. Larger magnetic fields means the particles curve more and let you build a collider at higher energy with the same size. Unfortunately, superconducting magnets are limited in field: a given material has a maximum achievable field strength. You can't just make a larger one to get a larger field - you need to develop a whole new material to make them from. Bremsstrahlung Bremsstrahlung is German for "braking radiation." Whenever a charged particle is accelerated, it emits some radiation. For acceleration perpendicular to the path (for instance, if its traveling in a circle), the power loss is given by: $$P=\frac{q^2 a^2\gamma^4}{6\pi\epsilon_0c^3}$$ $q$ is the charge, $a$ is the acceleration, $\gamma$ is the Lorentz factor, $\epsilon_0$ is the permittivity of free space, and $c$ is the speed of light. In high energy, we usually simplify things by setting various constants equal to one. In those units, this is $$ P=\frac{2\alpha a^2\gamma^4}{3}$$ This is instantaneous power loss. We're usually more interested in power loss over a whole cycle around the detector. The particles are going essentially at the speed of light, so the time to go around once is just $\frac{2\pi r}{c}$. We can simplify some more: $\gamma=\frac{E}{m}$, and $a=\frac{v^2}{r}$. All together, this gives: $$ E_{\rm loop} = \frac{4\pi\alpha E^4}{3m^4r}$$ The main things to note from this are: As we increase the energy, the power loss increases very quickly Increasing the mass of the particles is very effective at decreasing the power loss Increasing the radius of the accelerator helps, but not as much as increasing the energy hurts. To put these numbers in perspective, if the LHC were running with electrons and positrons instead of protons, at the same energy and everything, each $6.5~\rm TeV$ electron would need to have $37\,000~\rm TeV$ of energy added per loop. All told, assuming perfect efficiency in the accelerator part, the LHC would consume about $20~\rm PW$, or about 1000 times the world's energy usage just to keep the particles in a circle (this isn't even including the actually accelerating them part). Needless to say, this is not practical. (And of course, even if we had the energy, we don't have the technology.) Anyway, this is the main reason particle colliders need to be large: the smaller we make them, the more energy they burn just to stay on. Naturally, the cost of a collider goes up with size. So this becomes a relatively simple optimization problem: larger means higher-up front costs but lower operating costs. For any target energy, there is an optimal size that costs the least over the long run. This is also why the LHC is a hadron collider. Protons are much heavier than electrons, and so the loss is much less. Electrons are so light that circular colliders are out of the question entirely on the energy frontier. If the next collider were to be another synchrotron, it would probably either collide protons or possibly muons. The problem with using protons is that they're composite particles, which makes the collisions much messier than using a lepton collider. It also makes the effective energy available less than it would be for an equivalent lepton collider. The next collider There are several different proposals for future colliders floating around in the high-energy physics community. A sample of them follows. One is a linear electron-positron collider. This would have allow us to make very high-precision measurements of Higgs physics, like previous experiments did for electroweak physics, and open up other precision physics as well. This collider would need to be a linear accelerator for the reasons described above. A linear accelerator has some significant downsides to it: in particular, you only have one chance to accelerate the particles, as they don't come around again. So they tend to need to be pretty long. And once you accelerate them, most of them miss each other and are lost. You don't get many chances to collide them like you do at the LHC. Another proposal is basically "the LHC, but bigger." A $100~\rm TeV$ or so proton collider synchrotron. One very interesting proposal is a muon collider. Muons have the advantage of being leptons, so they have clean collisions, but they are much heavier than electrons, so you can reasonably put them in a synchrotron. As an added bonus, muon collisions have a much higher chance of producing Higgs bosons than electrons do. The main difficulty here is that muons are fairly short-lived (around $2.2~\rm\mu s$), so they would need to be accelerated very quickly before they decay. But very cool, if it can be done! The Future If we want to explore the highest energies, there's really no way around bigger colliders: For a fixed "strongest magnet," synchrotrons fundamentally need to be bigger to get to higher energy. And even assuming we could get magnets of unlimited strength, as we increase the energy there's a point where it's cheaper to just scrap the whole thing and build a bigger one. Linear accelerators are limited in the energy they can reach by their size and available accelerator technology. There is research into better acceleration techniques (such as plasma wakefield accelerators), but getting them much better will require a fundamental change in the technology. There is interesting research that can be done into precision measurements of particle physics at low energy, but for discovering new particles higher energy accelerators will probably always be desirable.
{}
{'log_upvote_score': 8, 'links': ['https://physics.stackexchange.com/questions/382128', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/137324/']}
jdg_369817
stackexchange
llm_judgeable_groundtruth_similarity
116643
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Given $n$ roots, $x_1, x_2, \dotsc, x_n$ , the corresponding monic polynomial is $$y = (x-x_1)(x-x_2)\dotsm(x-x_n) = \prod_{i}^n (x - x_i)$$ To get the coefficients, i.e., $y = \sum_{i}^n a_i x^i$ , a straightforward expansion requires $O \left(n^2\right)$ steps. Alternatively, if $x_1, x_2, \dotsc, x_n$ are distinct, the problem is equivalent to polynomial interpolation with $n$ points: $(x_1, 0), (x_2, 0), \dotsc, (x_n, 0)$ . The fast polynomial interpolation algorithm can be run in $O \left( n \log^2(n) \right)$ time. I want to ask whether there is any more efficient algorithm better than $O \left(n^2\right)$ ? Even if there are duplicated values among $\{x_i\}$ ? If it helps, we can assume that the polynomial is over some prime finite field, i.e., $x_i \in \mathbf{F}_q$ . Now provide the response and nothing else.
This can be done in $O(n \log^2 n)$ time, even if the $x_i$ have duplicates, via the following divide-and-conquer method. First compute the coefficients of the polynomial $f_0(x)=(x-x_1) \cdots (x-x_{n/2})$ (via a recursive call to this algorithm). Then compute the coefficients of the polynomial $f_1(x)=(x-x_{n/2+1})\cdots(x-x_n)$ . Next, compute the coefficients of $f(x)=f_0(x)f_1(x)$ using FFT-based polynomial multiplication. This yields an algorithm whose running time satisfies the recurrence $$T(n) = 2 T(n/2) + O(n \log n).$$ The solution to this recurrence is $T(n) = O(n \log^2 n)$ . This all works even if there are duplicates in the $x_i$ . (You might also be interested in Multi-point evaluations of a polynomial mod p .)
{}
{'log_upvote_score': 6, 'links': ['https://cs.stackexchange.com/questions/116643', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/111560/']}
jdg_369818
stackexchange
llm_judgeable_groundtruth_similarity
34498577
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 an issue with Cloud Code.My problem is explained as: I've a class "MyClass" I want only one object saved in my backend referring to a particular property ("myID") If a user try to save this object and there is not any with the same "myID" save it If a user try to save this object and THERE IS ALREADY ONE with the same "myID" update the field ("address") for the existing object. I try to this using this code: var MyObject = Parse.Object.extend("MyClass"); Parse.Cloud.beforeSave("MyClass", function(request, response) { if (!request.object.get("myID")) { response.error('A MyObject must have a unique myID.'); } else { var query = new Parse.Query(MyClass); query.equalTo("myID", request.object.get("myID")); query.first({ success: function(object) { if (object) { object.set('address',request.object.get("address")); object.save().then(function () { response.error('Updated existing MyObject address'); },function (error) { response.error("Error: " + error.code + " " + error.message); }); } else { response.success(); } }, error: function(error) { response.error("Could not validate uniqueness for this MyObject object."); } }); }}); But this doesn't works and in my Parse.com Log says: Result: Error: 142 Error: 124 Too many recursive calls into Cloud Code I know can I achieve what I want? Now provide the response and nothing else.
First, you should read all about Null Safety in Kotlin which covers the cases thoroughly. In Kotlin, you cannot access a nullable value without being sure it is not null ( Checking for null in conditions ), or asserting that it is surely not null using the !! sure operator , accessing it with a ?. Safe Call , or lastly giving something that is possibly null a default value using the ?: Elvis Operator . For your 1st case in your question you have options depending on the intent of the code you would use one of these, and all are idiomatic but have different results: val something: Xyz? = createPossiblyNullXyz()// access it as non-null asserting that with a sure callval result1 = something!!.foo()// access it only if it is not null using safe operator, // returning null otherwiseval result2 = something?.foo()// access it only if it is not null using safe operator, // otherwise a default value using the elvis operatorval result3 = something?.foo() ?: differentValue// null check it with `if` expression and then use the value, // similar to result3 but for more complex cases harder to do in one expressionval result4 = if (something != null) { something.foo() } else { ... differentValue }// null check it with `if` statement doing a different actionif (something != null) { something.foo() } else { someOtherAction() } For the "Why does it work when null checked" read the background information below on smart casts . For your 2nd case in your question in the question with Map , if you as a developer are sure of the result never being null , use !! sure operator as an assertion: val map = mapOf("a" to 65,"b" to 66,"c" to 67)val something = map.get("a")!!something.toLong() // now valid or in another case, when the map COULD return a null but you can provide a default value, then Map itself has a getOrElse method : val map = mapOf("a" to 65,"b" to 66,"c" to 67)val something = map.getOrElse("z") { 0 } // provide default value in lambdasomething.toLong() // now valid Background Information: Note: in the examples below I am using explicit types to make the behavior clear. With type inference, normally the types can be omitted for local variables and private members. More about the !! sure operator The !! operator asserts that the value is not null or throws an NPE. This should be used in cases where the developer is guaranteeing that the value will never be null . Think of it as an assert followed by a smart cast . val possibleXyz: Xyz? = ...// assert it is not null, but if it is throw an exception:val surelyXyz: Xyz = possibleXyz!! // same thing but access members after the assertion is made:possibleXyz!!.foo() read more: !! Sure Operator More about null Checking and Smart Casts If you protect access to a nullable type with a null check, the compiler will smart cast the value within the body of the statement to be non-nullable. There are some complicated flows where this cannot happen, but for common cases works fine. val possibleXyz: Xyz? = ...if (possibleXyz != null) { // allowed to reference members: possiblyXyz.foo() // or also assign as non-nullable type: val surelyXyz: Xyz = possibleXyz} Or if you do a is check for a non-nullable type: if (possibleXyz is Xyz) { // allowed to reference members: possiblyXyz.foo()} And the same for 'when' expressions that also safe cast: when (possibleXyz) { null -> doSomething() else -> possibleXyz.foo()}// orwhen (possibleXyz) { is Xyz -> possibleXyz.foo() is Alpha -> possibleXyz.dominate() is Fish -> possibleXyz.swim() } Some things do not allow the null check to smart cast for the later use of the variable. The example above uses a local variable that in no way could have mutated in the flow of the application, whether val or var this variable had no opportunity to mutate into a null . But, in other cases where the compiler cannot guarantee the flow analysis, this would be an error: var nullableInt: Int? = ...public fun foo() { if (nullableInt != null) { // Error: "Smart cast to 'kotlin.Int' is impossible, because 'nullableInt' is a mutable property that could have been changed by this time" val nonNullableInt: Int = nullableInt }} The lifecycle of the variable nullableInt is not completely visible and may be assigned from other threads, the null check cannot be smart cast into a non-nullable value. See the "Safe Calls" topic below for a workaround. Another case that cannot be trusted by a smart cast to not mutate is a val property on an object that has a custom getter. In this case, the compiler has no visibility into what mutates the value and therefore you will get an error message: class MyThing { val possibleXyz: Xyz? get() { ... }}// now when referencing this class...val thing = MyThing()if (thing.possibleXyz != null) { // error: "Kotlin: Smart cast to 'kotlin.Int' is impossible, because 'p.x' is a property that has open or custom getter" thing.possiblyXyz.foo()} read more: Checking for null in conditions More about the ?. Safe Call operator The safe call operator returns null if the value to the left is null, otherwise continues to evaluate the expression to the right. val possibleXyz: Xyz? = makeMeSomethingButMaybeNullable()// "answer" will be null if any step of the chain is nullval answer = possibleXyz?.foo()?.goo()?.boo() Another example where you want to iterate a list but only if not null and not empty, again the safe call operator comes in handy: val things: List? = makeMeAListOrDont()things?.forEach { // this loops only if not null (due to safe call) nor empty (0 items loop 0 times):} In one of the examples above we had a case where we did an if check but have the chance another thread mutated the value and therefore no smart cast . We can change this sample to use the safe call operator along with the let function to solve this: var possibleXyz: Xyz? = 1public fun foo() { possibleXyz?.let { value -> // only called if not null, and the value is captured by the lambda val surelyXyz: Xyz = value }} read more: Safe Calls More about the ?: Elvis Operator The Elvis operator allows you to provide an alternative value when an expression to the left of the operator is null : val surelyXyz: Xyz = makeXyzOrNull() ?: DefaultXyz() It has some creative uses as well, for example throw an exception when something is null : val currentUser = session.user ?: throw Http401Error("Unauthorized") or to return early from a function: fun foo(key: String): Int { val startingCode: String = codes.findKey(key) ?: return 0 // ... return endingValue} read more: Elvis Operator Null Operators with Related Functions Kotlin stdlib has a series of functions that work really nicely with the operators mentioned above. For example: // use ?.let() to change a not null value, and ?: to provide a defaultval something = possibleNull?.let { it.transform() } ?: defaultSomething// use ?.apply() to operate further on a value that is not nullpossibleNull?.apply { func1() func2()}// use .takeIf or .takeUnless to turn a value null if it meets a predicateval something = name.takeIf { it.isNotBlank() } ?: defaultNameval something = name.takeUnless { it.isBlank() } ?: defaultName Related Topics In Kotlin, most applications try to avoid null values, but it isn't always possible. And sometimes null makes perfect sense. Some guidelines to think about: in some cases, it warrants different return types that include the status of the method call and the result if successful. Libraries like Result give you a success or failure result type that can also branch your code. And the Promises library for Kotlin called Kovenant does the same in the form of promises. for collections as return types always return an empty collection instead of a null , unless you need a third state of "not present". Kotlin has helper functions such as emptyList() or emptySet() to create these empty values. when using methods which return a nullable value for which you have a default or alternative, use the Elvis operator to provide a default value. In the case of a Map use the getOrElse() which allows a default value to be generated instead of Map method get() which returns a nullable value. Same for getOrPut() when overriding methods from Java where Kotlin isn't sure about the nullability of the Java code, you can always drop the ? nullability from your override if you are sure what the signature and functionality should be. Therefore your overridden method is more null safe. Same for implementing Java interfaces in Kotlin, change the nullability to be what you know is valid. look at functions that can help already, such as for String?.isNullOrEmpty() and String?.isNullOrBlank() which can operate on a nullable value safely and do what you expect. In fact, you can add your own extensions to fill in any gaps in the standard library. assertion functions like checkNotNull() and requireNotNull() in the standard library. helper functions like filterNotNull() which remove nulls from collections, or listOfNotNull() for returning a zero or single item list from a possibly null value. there is a Safe (nullable) cast operator as well that allows a cast to non-nullable type return null if not possible. But I do not have a valid use case for this that isn't solved by the other methods mentioned above.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/34498577', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5147193/']}
jdg_369819
stackexchange
llm_judgeable_groundtruth_similarity
43020491
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 spring boot application that I can package in a war that I want to deploy to different environments. To automate this deployment it'd be easier to have the configuration file externalized. Currently everything works fine with a application.properties file in src/main/resources. Then I use ´mvn install´ to build a war deployable to tomcat.But I would like to use a .yml file that does not need to be present on mvn install but that would be read from during deployment of the war and is in the same or a directory relative to my war. 24. externalized configuration shows where spring boot will look for files and 72.3 Change the location of external properties of an application gives more detail on how to configure this but I just do not understand how to translate this to my code. My application class looks like this: package be.ugent.lca; Updated below Do I need to add a @PropertySource to this file? How would I refer to a certain relative path? I feel like it's probably documented in there as most spring boot documentation but I just don't understand how they mean me to do this. EDIT Not sure if this should be a separate issue but I think it's still related. Upon setting the os variable the error of yaml file not found went away. Yet I still get the same error again as when I had no application .properties or .yml file. Application now looks like this: @Configuration**@PropertySource("file:${application_home}/application.yml")**@ComponentScan({"be.ugent.lca","be.ugent.sherpa.configuration"})@EnableAutoConfiguration@EnableSpringDataWebSupportpublic class Application extends SpringBootServletInitializer{ public static void main(String[] args) { SpringApplication.run(Application.class, args); } The application_home OS variable $ echo $application_home C:\Masterproef\clones\la15-lca-web\rest-service\target My application.yml file(part it complains about): sherpa: package: base: be.ugent.lca Error upon java -jar *.warAll variations upon: Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'sherpa.package.base' in string value "${sherpa.package.base}" at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:174) at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:126) at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:204) at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:178) at org.springframework.context.support.PropertySourcesPlaceholderConfigurer$2.resolveStringValue(PropertySourcesPlaceholderConfigurer.java:172) at org.springframework.beans.factory.support.AbstractBeanFactory.resolveEmbeddedValue(AbstractBeanFactory.java:808) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1027) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:545) ... 142 more Now provide the response and nothing else.
Using external properties files The answer lies in the Spring Boot Docs, I'll try to break it down for you. First of all, no you should not use @PropertySource when working with Yaml configuration, as mentioned here under the Yaml shortcomings : YAML files can’t be loaded via the @PropertySource annotation. So in the case that you need to load values that way, you need to use a properties file. So, how to load propery files? That is explained here Application Property Files One is loaded for you: application.yml , place it in one of the directories as mentioned in the link above. This is great for your general configuration. Now for your environment specific configuration (and stuff like passwords) you want to use external property files, how to do that is also explained in that section : If you don’t like application.properties as the configuration file name you can switch to another by specifying a spring.config.name environment property. You can also refer to an explicit location using the spring.config.location environment property (comma-separated list of directory locations, or file paths). So you use the spring.config.location environment property.Imagine you have an external config file: application-external.yml in the conf/ dir under your home directory, just add it like this: -Dspring.config.location=file:${home}/conf/application-external.yml as a startup parameter of your JVM.If you have multiple files, just seperate them with a comma. Note that you can easily use external properties like this to overwrite properties, not just add them. I would advice to test this by getting your application to work with just your internal application.yml file , and then overwrite a (test) property in your external properties file and log the value of it somewhere. Bind Yaml properties to objects When working with Yaml properties I usually load them with @ConfigurationProperties , which is great when working with for example lists or a more complex property structure. (Which is why you should use Yaml properties, for straightforward properties you are maybe better of using regular property files). Read this for more information: Type-Safe Configuration properties Extra: loading these properties in IntelliJ, Maven and JUnit tests Sometimes you want to load these properties in your maven builds or when performing tests. Or just for local development with your IDE If you use IntelliJ for development you can easily add this by adding it to your Tomcat Run Configuration : "Run" -> "Edit Configurations" , select your run configuration under "Tomcat Server" , check the Server tab and add it under "VM Options". To use external configuration files in your Maven build : configure the maven surefire plugin like this in your pom.xml: <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <configuration> <argLine>-Dspring.config.location=file:${home}/conf/application-external.yml</argLine> </configuration></plugin> When running JUnit tests in IntelliJ: Run → Edit Configurations Defaults → JUnit add VM Options -> -ea -Dspring.config.location=file:${home}/conf/application-external.yml
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/43020491', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3681671/']}
jdg_369820
stackexchange
llm_judgeable_groundtruth_similarity
233320
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm running Python 2.6 on Unix and when I run the interactive prompt ( SQLite is supposed to be preinstalled) I get: [root@idev htdocs]# pythonPython 2.6 (r26:66714, Oct 23 2008, 16:25:34)[GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> import sqliteTraceback (most recent call last):File "<stdin>", line 1, in <module>ImportError: No module named sqlite>>> How do I resolve this? Now provide the response and nothing else.
The error: ImportError: No module named _sqlite3 means that SQLite 3 does not find the associated shared library. On Mac OS X it's _sqlite3.so and it should be the same on other Unix systems. To resolve the error you have to locate the _sqlite3.so library on your computer and then check your PYTHONPATH for this directory location. To print the Python search path enter the following in the Python shell: import sysprint sys.path If the directory containing your library is missing you can try adding it interactively with sys.path.append('/your/dir/here') and try import sqlite3 again. If this works you have to add this directory permanently to your PYTHONPATH environment variable. PS: If the library is missing you should (re-)install the module.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/233320', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3404/']}
jdg_369821
stackexchange
llm_judgeable_groundtruth_similarity
9472361
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 color the bars in highcharts with a gradient. What I have is coloring them, but the problem is, the gradient is spreading through the other data groups rather than each individual bar, here's an example of what I mean: If you notice, the gradient is being spread between the bars, rather than creating a new one for each. To gradient them, I'm using: colors: [ { linearGradient: [500, 0], stops: [ [0, 'rgb(247, 111, 111)'], [1, 'rgb(220, 54, 54)'] ] }, { linearGradient: [500, 0], stops: [ [0, 'rgb(120, 202, 248)'], [1, 'rgb(46, 150, 208)'] ] }, { linearGradient: [500, 0], stops: [ [0, 'rgb(136, 219, 5)'], [1, 'rgb(112, 180, 5)'] ] },], Now provide the response and nothing else.
There are two ways of specifying gradients in current version of highcharts. Previously you only had the option of using an array with four coordinates like linearGradient: [x1, y1, x2, y2] . This would make the gradient coordinates apply to pixels and therefor be used for all bars (as in your example). The new option is to use a configuration object instead: linearGradient: { x1: 0, y1: 0, x2: 1, y2: 0} The coordinates here are numbers between 0 and 1 which corresponds to each individual bar. So, if you change the array you used to be a config option (and use normalized coordinates) you will get gradients in each bar. Example on jsfiddle Screenshot: Edit: And as a bar chart have the x-axis going from top to bottom you should let x1 be 0 and x2 be 1, instead of changing y1 and y2.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9472361', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1171553/']}
jdg_369822
stackexchange
llm_judgeable_groundtruth_similarity
30557
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have been looking for a simple h bridge for high power applications (say ~2kW total--whether that be 2kV at one amp or 2kA at 1V I really do not care. I figure I can always use a transformer to switch between the two). Anyway, the point is, I just want take a lot of DC power (two leads), and switch it across a load (two leads). In order to determine which way you want to switch it, you need two inputs (two leads).Here are just a few examples of full bridge h bridges with redundant leads and/or leads that should be tied together but are not: http://www.vishay.com/docs/94546/19mt050x.pdf http://ixapps.ixys.com/DataSheet/MIXA81H1200EH.pdf http://www.vishay.com/docs/93754/p100.pdf Note the redundant leads on the first two. For example, in the second link, {13, 21}, {2, 19}, {10, 15}, and {4, 12, 14, 20} are clearly connected by wires. What is the point of having multiple pins if they are directly connected by wires? Furthermore, the last link, the only way I know how to use that design is with {G1, G4} on and {G2, G3} off or vica versa. Why not just tie gates together so that is the case? Then you have two inputs (each connected to two gates) two outputs, and two leads for power. Although I would not mind some examples of what I am looking for, I am just as interested in knowing how to take full advantage of these seemingly incomplete or redundantly wired h bridges. Now provide the response and nothing else.
There are two functions that these "redundant" pins provide. Using your first datasheet as a reference, the grouping of pins helps to show their function. Groups (9,10) (13,14) (15,16) and (11,12) are tied together to reduce resistance and inductance. The pins directly connected to the source of each transistor (1,3,6,8) are lower resistance, lower inductance connections to the sources which is better for the gate drive circuit. Keep in mind that some gate drivers can drive over 9A peak gate current, so minimizing inductance is a must. In terms of tying control pins together, that isn't possible with power devices due to dead time switching requirements and gate drive voltages.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/30557', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/7661/']}
jdg_369823
stackexchange
llm_judgeable_groundtruth_similarity
382136
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm working on implementing my first clean architecture and CQRS application, I've stumbled across a bit of logic that's leaving me a bit stumped. I'm working on integrating authorization and authentication into my application, but I'm having some trouble trying to figure out how to architect a portion of my application that will handle command validation. My system is multitenant and currently shares a database across all of my clients, and I need to implement some sort of system that will enable me to perform all of my verification in a way that is straightforward and not too tightly coupled. In my system, I have a implementations for both Users and Clients . Users can belong to any number clients. These users also have varying levels of permissions granted to them (but this is managed by my roles systems and mostly irrelevant here). My WebAPI is designed in such a way that I limit authorization based on a fixed number of Roles and Claims . These largely remain static, so I don't need much flexibility here. My main source of headache is determining "User-Client" interaction permissions. Namely, I want to determine if a user has access to client that they're attempted to update records for. One approach would be to add UserId to all of my commands and to individually check the permissions during each command and query. This seems tedious and prone to issues. Another approach I considered was to define an interface or base class that merely added the client and user Ids to any object in which they were required, but this had the adverse affect of exposing those implementations to my WebAPIs (via swagger and the UserId/ClientId being a portion of the Request/Command object). One final approach would be to make my underlying commands still implement those interfaces, but have my controller contain minimal logic to map an API request into one of my command objects. Again, this would be tedious and would start leaking my logic into my controllers. Overall, it's as if I need some additional structure in my application in which I can pipe any object containing a ClientId into so that I can keep the Authentication and Authorization logic out of my core app. However, I'm mostly stumped, and I'm looking for ways that I can simplify my application by minimizing the overhead of adding client-dependent commands and queries. If it's of any relevance, some of the core tools and technologies I'm leveraging are: .Net Core 2.1 Mediatr Entity Framework And my core application implements commands in a similar fashion to: public class CreateProductCommand : IRequest{ public int ClientId { get;set; } public int ParentProductId { get; set; } public string ProductName { get; set; } // other creation specific props here}public class CreateProductCommandHandler : IHandler<CreateProductCommand>{ public async Task<Unit> Handle(CreateProductCommand command) { // check parent permissions, make sure parent product // belongs to client who is entered. // ----- // rest of logic to save // -- Ideally the User-Client check would happen before // -- the command is ever sent to the handler, so that // -- only client-specific logic and permissions are checked. // -- As long as the user can edit the specific client, anything // -- that happens to the client is determined by standard business // -- and domain logic. } } Now provide the response and nothing else.
Looks to me like your issue is: I have a thread acting on behalf of a user. I don't wish to pollute my nice clean business logic with authorisation details. But my data store needs authorisation details to enforce control of the data. From your description it sounds pretty critical that User A does/does not have access to Client B. That sounds very much like a Business Concern . So the first answer is its pretty obvious: Your business logic should care about which user is doing what . Passing the user details through the appropriate business logic directly is the clean way to handle this. This gives many positives: its clear, its clean, its easily tested, and the API is not coupled to the Data Store. If need be there will be a point in your Business Logic where you can translate from talking about a User , to specifically talking about Authorised to do X . Also there is no reason why this User information could not be made more anemic, or enriched in different parts of your Business Logic. Pragmatically, if the thread only serves one User at a time, use Thread Local storage and shove a reference to the user there. Later in your data store (aka wherever you need it) access that reference. This is a dreadful solution. It enforces direct coupling between API and Data Store (the recipient location), the Business Concern is not in the Business Logic, and you have a non-intuitive, indirect argument, that may not be set or cleaned up properly affecting future calls on the thread. In short what you make back from tedium, you will pay back over and over again in bugs and change resistance. Added extra answer Possible Solutions Attribute with some Aspect-Orientated programming. an Abstract Class/interface with some Aspect-Orientated programming. A Generic class that wraps a lambda/interface. a Meta Program that constructs an Abstract class for derivation. a Meta Program that constructs a tailored class which wraps a lambda/interface. Solutions 1 and 2 uses your languages aspect orientation (C# attributes) to detect the "authorisation required" functions, and intercept calls to them. It will throw an exception on unauthorised, but permit the call if authorised. class command{ public command(User user); public User user {get; } [AuthorisedFor("xyz")] public void action(object a); [AuthorisedFor("xyz")] public void action(User user, object a);} Solution 1 requires you to directly decorate the authorisation required functions, and provide an properties/arguments for user information. Solution 2 allows you to pre-specify the authorisation required for the standard functions, and provide the properties/arguments for user information. Solution 3 is a decorator and captures through its constructor the knowledge about authority required, the permit and deny functions. The only issue is that the Command interface will either force you to use Object arguments, a Generic Type and a limit on arguments, or require copies per downstream command interface. class command<T>{ public command(User user, Authority[] required, Action<T> permit, Action<T> deny); public void action(T arguments);}class command2{ public command(Authority[] required, SomeInterface permit, SomeInterface2 deny); public void action();} Solutions 4 and 5 are just not easily achieved in C#. You would essential need to write code that JIT's a new Base Class and derivations, or decorator classes for the various interfaces. I only include them for completeness. The run-time flexible options are 3 or 5. The other solutions 1, 2 or 4 are more reasonable for compile time. User and Authorisation Passing Orthogonal to which solution you pick for handling permit/deny, those solutions will need access to the user/authorisations. These could be stored in various forms of storage: global thread local object property function argument Picking Global or thread local is going to give you the implicit user passing you desire, it will however complicate testing and be a source of non-intuitive bugs. Picking an Object property or a function argument is going to require that you pass the user/authorisation information through your commands. It will make the information requirement explicit, simplify testing, and reduce the capacity for non-intuitive bugs. It will require more typing. My preference is for explicitly passing the user/authorisations down. However there may be a reason that makes the implicit Global/Thread local option the better choice.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/382136', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/204600/']}
jdg_369824
stackexchange
llm_judgeable_groundtruth_similarity
310870
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's the difference between var A = function () { this.x = function () { //do something };}; and var A = function () { };A.prototype.x = function () { //do something}; Now provide the response and nothing else.
The examples have very different outcomes. Before looking at the differences, the following should be noted: A constructor's prototype provides a way to share methods and values among instances via the instance's private [[Prototype]] property. A function's this is set by how the function is called or by the use of bind (not discussed here). Where a function is called on an object (e.g. myObj.method() ) then this within the method references the object. Where this is not set by the call or by the use of bind , it defaults to the global object (window in a browser) or in strict mode, remains undefined. JavaScript is an object-oriented language, i.e. most values are objects, including functions. (Strings, numbers, and booleans are not objects.) So here are the snippets in question: var A = function () { this.x = function () { //do something };}; In this case, variable A is assigned a value that is a reference to a function. When that function is called using A() , the function's this isn't set by the call so it defaults to the global object and the expression this.x is effective window.x . The result is that a reference to the function expression on the right-hand side is assigned to window.x . In the case of: var A = function () { };A.prototype.x = function () { //do something}; something very different occurs. In the first line, variable A is assigned a reference to a function. In JavaScript, all functions objects have a prototype property by default so there is no separate code to create an A.prototype object. In the second line, A.prototype.x is assigned a reference to a function. This will create an x property if it doesn't exist, or assign a new value if it does. So the difference with the first example in which object's x property is involved in the expression. Another example is below. It's similar to the first one (and maybe what you meant to ask about): var A = new function () { this.x = function () { //do something };}; In this example, the new operator has been added before the function expression so that the function is called as a constructor. When called with new , the function's this is set to reference a new Object whose private [[Prototype]] property is set to reference the constructor's public prototype . So in the assignment statement, the x property will be created on this new object. When called as a constructor, a function returns its this object by default, so there is no need for a separate return this; statement. To check that A has an x property: console.log(A.x) // function () { // //do something // }; This is an uncommon use of new since the only way to reference the constructor is via A.constructor . It would be much more common to do: var A = function () { this.x = function () { //do something };};var a = new A(); Another way of achieving a similar result is to use an immediately invoked function expression: var A = (function () { this.x = function () { //do something };}()); In this case, A assigned the return value of calling the function on the right-hand side. Here again, since this is not set in the call, it will reference the global object and this.x is effective window.x . Since the function doesn't return anything, A will have a value of undefined . These differences between the two approaches also manifest if you're serializing and de-serializing your Javascript objects to/from JSON. Methods defined on an object's prototype are not serialized when you serialize the object, which can be convenient when for example you want to serialize just the data portions of an object, but not it's methods: var A = function () { this.objectsOwnProperties = "are serialized";};A.prototype.prototypeProperties = "are NOT serialized";var instance = new A();console.log(instance.prototypeProperties); // "are NOT serialized"console.log(JSON.stringify(instance)); // {"objectsOwnProperties":"are serialized"} Related questions : What does it mean that JavaScript is a prototypal language? What is the scope of a function in JavaScript? How does the "this" keyword work? Sidenote: There may not be any significant memory savings between the two approaches, however using the prototype to share methods and properties will likely use less memory than each instance having its own copy. JavaScript isn't a low-level language. It may not be very valuable to think of prototyping or other inheritance patterns as a way to explicitly change the way memory is allocated.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/310870', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/39864/']}
jdg_369825
stackexchange
llm_judgeable_groundtruth_similarity
1113345
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: sending mail along with embedded image using asp.net I have already used following but it can't work Dim EM As System.Net.Mail.MailMessage = New System.Net.Mail.MailMessage(txtFrom.Text, txtTo.Text) Dim A As System.Net.Mail.Attachment = New System.Net.Mail.Attachment(txtImagePath.Text) Dim RGen As Random = New Random() A.ContentId = RGen.Next(100000, 9999999).ToString() EM.Attachments.Add(A) EM.Subject = txtSubject.Text EM.Body = "<body>" + txtBody.Text + "<br><img src='cid:" + A.ContentId +"'></body>" EM.IsBodyHtml = True Dim SC As System.Net.Mail.SmtpClient = New System.Net.Mail.SmtpClient(txtSMTPServer.Text) SC.Send(EM) Now provide the response and nothing else.
If you are using .NET 2 or above you can use the AlternateView and LinkedResource classes like this: string html = @"<html><body><img src=""cid:YourPictureId""></body></html>";AlternateView altView = AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html);LinkedResource yourPictureRes = new LinkedResource("yourPicture.jpg", MediaTypeNames.Image.Jpeg);yourPictureRes.ContentId = "YourPictureId";altView.LinkedResources.Add(yourPictureRes);MailMessage mail = new MailMessage();mail.AlternateViews.Add(altView); Hopefully you can deduce the VB equivalent.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1113345', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/103344/']}
jdg_369826
stackexchange
llm_judgeable_groundtruth_similarity
1393
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 already asked if there are more rationals than integers here... Are there more rational numbers than integers? However, there is one particular argument that I didn't give before which I still find compelling... Every integer is also a rational. There exist (many) rationals that are not integers. Therefore there are more rationals than integers. Obviously, in a sense, I am simply choosing one particular bijection, so by the definition of set cardinality this argument is irrelevant. But it's still a compelling argument for "size" because it's based on a trivial/identity bijection. EDIT please note that the above paragraph indicates that I know about set cardinality and how it is defined, and accept it as a valid "size" definition, but am asking here about something else. To put it another way, the set of integers is a proper subset of the set of rationals. It seems strange to claim that the two sets are equal in size when one is a proper subset of the other. Is there, for example, some alternative named "size" definition consistent with the partial ordering given by the is-a-proper-subset-of operator? EDIT clearly it is reasonable to define such a partial order and evaluate it. And while I've use geometric analogies, clearly this is pure set theory - it depends only on the relevant sets sharing members, not on what the sets represent. Helpful answers might include a name (if one exists), perhaps for some abstraction that is consistent with this partial order but defined in cases where the partial order is not. Even an answer like "yes, that's valid, but it isn't named and doesn't lead to any interesting results" may well be correct - but it doesn't make the idea unreasonable. Sorry if some of my comments aren't appropriate, but this is pretty frustrating. As I said, it feels like I'm violating some kind of taboo. EDIT - I was browsing through random stuff when I was reminded this was here, and that I actually ran into an example where "size" clearly can't mean "cardinality" fairly recently (actually a very long time ago and many times since, but I didn't notice the connection until recently). The example relates to closures of sets. Please forgive any wrong terminology, but if I have a seed set of {0} and an operation $f x = x+2$ , the closure of that set WRT that operation is the "smallest" set that is closed WRT that operation, meaning that for any member $x$ of the set, $x+2$ must also be a member. So obviously the closure is {0, 2, 4, 6, 8, ...} - the even non-negative integers. However, the cardinality of the set of even non-negative integers is equal to the cardinality of the set of all integers, or even all rationals. So if "smallest" means "least cardinality", the closure isn't well-defined - the set {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...} is no larger than the set {0, 2, 4, 6, 8, ...}. Therefore, the meaning of "smallest" WRT set closures refers to some measure of size other than cardinality. I'm not adding this as a late answer because it's already covered by the answers below - it's just a particular example that makes sense to me. Another addition - while skimming the first chapter of a topology textbook in a library some time ago, IIRC I spotted a definition of the set closure which did not use the word "smallest", and made no direct reference to "size". That led me to think maybe the common "definition" of closures I'm familiar with is just a stopgap for those of us who aren't ready for a formally precise definition. However, while searching for another source, I instead found this answer to a topology question that uses the word "smallest" in its definition of closure (and "largest" in its "dual definition of interior"). And then I found this answer which describes a concept of size based on partial ordering of topological embeddings. I think that's another example to add to those in answers below. Now provide the response and nothing else.
Of course, there are other notions of size. In particular, your notion of "a partial order based on inclusion of sets" is a very fruitful concept which has been used frequently. As a quick example, there is a technique in mathematical logic/set theory called "forcing" which is used to show that certain mathematical statements are unprovable. Forcing often starts with a partial ordered set where the order is given by inclusion of subsets. In terms of the everyday world interpretation of the word "size", there are (at least) two problems with the using the partial order given by inclusion of subsets. The first is, as you said, a partial order: there are two sets which cannot be compared, i.e., there are 2 sets where you cannot say one is bigger than the other. The second is that two things will have the same size precisely when the two things are absolutely the same. There is no notion of different things which happen to be the same size - that can't happen in this partial order. For example, lets say we're looking at subsets of the integers. You pull out your favorite subset: all the odd integers and I pull out mine: all the even integers. Using the partial order definition of size, these two sets are incomparable. Mine is neither bigger than, smaller than, or the same size as yours. To contrast that, using the cardinality notion of size, they have the same size. This is evidenced by simply taking everything in your set and adding 1 to it to get everything in my set. For an even more absurd example, consider the set {0} and the set {1}. One would expect these two sets to have the same notion of "size" (for any notion of "size"!), but using the partial order notion, one cannot compare these two sets. By contrast, cardinality (or, the way I used "size" in the previous link) is defined on ALL sets (assuming the axiom of choice), even those which a priori have no subset relation. And there are many examples of sets which have the same cardinality, but which are not equal. (For example, the set of evens and odds, or the sets {0} and {1}).
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1393', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_369827
stackexchange
llm_judgeable_groundtruth_similarity
4178249
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Does anyone know if there's a standard class for an infinitely nestable dictionary in Python? I'm finding myself repeating this pattern: d = defaultdict(lambda: defaultdict(lambda: defaultdict(int)))d['abc']['def']['xyz'] += 1 If I want to add "another layer" (e.g. d['abc']['def']['xyz']['wrt'] ), I have to define another nesting of defaultdicts. To generalize this pattern, I've written a simple class that overrides __getitem__ to automatically create the next nested dictionary. e.g. d = InfiniteDict(('count',0),('total',0))d['abc']['def']['xyz'].count += 0.24d['abc']['def']['xyz'].total += 1d['abc']['def']['xyz']['wrt'].count += 0.143d['abc']['def']['xyz']['wrt'].total += 1 However, does anyone know of a pre-existing implementation of this idea? I've tried Googling, but I'm not sure what this would be called. Now provide the response and nothing else.
You can derive from defaultdict to get the behavior you want: class InfiniteDict(defaultdict): def __init__(self): defaultdict.__init__(self, self.__class__)class Counters(InfiniteDict): def __init__(self): InfiniteDict.__init__(self) self.count = 0 self.total = 0 def show(self): print "%i out of %i" % (self.count, self.total) Usage of this class would look like this: >>> d = Counters()>>> d[1][2][3].total = 5>>> d[1][2][3].show()0 out of 5>>> d[5].show()0 out of 0
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4178249', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/247542/']}
jdg_369828
stackexchange
llm_judgeable_groundtruth_similarity
396654
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: Custom Sort based on subject column order should be Maths, English, Science when I use this below command awk -F',' '{if (NR!=1) {print $2,$3,$5,$4}}' myfile.csv on my myfile.csv I am getting like this but I want some other way "101" "Anna" "Maths" "V""102" "Bob" "Maths" "V""103" "Charles" "Science" "VI""104" "Darwin" "Science" "VI""105" "Eva" "English" "VII" sort based on subject column order should be Maths, English, Science removed double quotes and joined by underscore like this 101_Anna_Maths_V102_Bob_Maths_V105_Eva_English_VII103_Charles_Science_VI104_Darwin_Science_VI Original file: output of cat myfile.csv Sl.No,RollNo,Names,Class,Subject1,101,Anna,V,Maths2,102,Bob,V,Maths3,103,Charles,VI,Science4,104,Darwin,VI,Science5,105,Eva,VII,English Now provide the response and nothing else.
Your original command: awk -F',' '{if (NR!=1) {print $2,$3,$5,$4}}' myfile.csv Your command written in the idiomatic awk way: awk -F',' 'NR > 1 { print $2, $3, $5, $4 }' myfile.csv Above command, modified to remove all double quotes for every line of input for which NR > 1 : awk -F',' 'NR > 1 { gsub(/"/, ""); print $2, $3, $5, $4 }' myfile.csv Above command, modified to output with _ as the output field separator ( OFS ): awk -F',' -vOFS='_' 'NR > 1 { gsub(/"/, ""); print $2, $3, $5, $4 }' myfile.csv
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/396654', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/254487/']}
jdg_369829
stackexchange
llm_judgeable_groundtruth_similarity
40456314
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Below is a linear model output for a dataset consisting of a response variable and three explanatory variables. How do I get the RSS of the original regression? Call: lm(formula = y ~ x1 + x2 + x3)Residuals: Min 1Q Median 3Q Max -4.9282 -1.3174 0.0059 1.3238 4.4560 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) -7.056057 1.963805 -3.593 0.000481 *** x1 3.058592 0.089442 34.196 < 2e-16 *** x2 -5.763410 0.168072 -34.291 < 2e-16 *** x3 0.000571 0.165153 0.003 0.997247 --- Signif. codes: 0 *** 0.001 ** 0.01 * 0.05 . 0.1 1 Residual standard error: 1.928 on 116 degrees of freedomMultiple R-squared: 0.9546,Adjusted R-squared: 0.9535F-statistic: 814 on 3 and 116 DF, p-value: < 2.2e-16 Now provide the response and nothing else.
Here are some ways of computing the residual sum of squares (RSS) using the built-in anscombe data set: fm <- lm(y1 ~ x1+x2+x3, anscombe)deviance(fm)## [1] 13.76269sum(resid(fm)^2)## [1] 13.76269anova(fm) # see the Residuals row of the Sum Sq column## Analysis of Variance Table#### Response: y1## Df Sum Sq Mean Sq F value Pr(>F) ## x1 1 27.510 27.5100 17.99 0.00217 **## Residuals 9 13.763 1.5292 ## ---## Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1anova(fm)["Residuals", "Sum Sq"]## [1] 13.76269with(summary(fm), df[2] * sigma^2)## [1] 13.76269 Regarding the last one, note that summary(fm)$df[2] and summary(fm)$sigma are shown in the summary(fm) output in case you want to calculate RSS using only a printout from summary . In particular, for the output shown in the question df[2] = 116 and sigma = 1.928 so RSS = df[2] * sigma^2 = 116 * 1.928^2 = 431.1933 .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40456314', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4100716/']}
jdg_369830
stackexchange
llm_judgeable_groundtruth_similarity
3695017
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: A three digit number was decreased by the sum of its digits .Then the same operation was carried out with the resulting number,et cetera ,100 times in all .Prove that the final number is zero . One method is very computational - where we look at the number of times 27,18,9 are removed from the original number (within certain ranges) and find a pattern etc.But this is tedious .Can someone suggest a more elegant proof. Now provide the response and nothing else.
The result is a number divisible by $9$ , because $$(100x+10y+z)-(x+y+z)=9(11x+y).$$ Being a decreasing process, we "jump" from a multiple of $9$ to a smaller multiple of $9$ . Doing it a hundred times, we necessarily fall on $0$ ... ... Under the condition that we have started from a number less that $900$ (thanks to Empy2 and quasi for pointing it). It remains the cases in interval $[900,999]$ . Here is a special treatment for them. Let us denote the interval $[k*100,(k+1)*100)$ as being the slice $S_k$ . Indeed, in fact, the "jumps" are not always from a multiple of $9$ to the immediate multiple of $9$ below it ("small jumps"), but happen to be multiples of $18$ ("large jumps"). Here is in particular what happens when we take a number in the slice $S_9$ . It is included in one of the two sequences "coalescent" in $891$ : $$\begin{cases}994 \rightarrow 972 \rightarrow 954 \rightarrow 936 \rightarrow 918 \rightarrow 900 \searrow \\\text{} \\\ \ \ \ \ \ \ \ \ \ \ \ \ 981 \rightarrow 963 \rightarrow 945 \rightarrow 927 \rightarrow 909 \nearrow \end{cases} 891 \rightarrow 873 \rightarrow 855 \rightarrow 837 \rightarrow 819 \rightarrow \ \text{etc.}$$ In slices $S_{9}$ and $S_{8}$ , using almost always "large jumps" instead of small jumps, we already "spare" ten small jumps which is what was needed to arrive at $0$ with at most a hundred jumps. It looks me not necessary to explain it with more words, but a graphic will help to capture in a single glance what happens in the cases of three numbers and the associated sequence of "jumps": $999$ , the extreme case (already a multiple of $9$ , with an exceptional initial jump of $-27$ ). [blue points], $971$ [red points], $943$ [black points]. We see in particular that the slopes are either $-18$ or $-9$ , with a dominance of $-18$ on the left and $-9$ on the right. This is why the numbers of the last slice $S_9=[900,999]$ need not that much steps to reach value 0 (at most $80$ in fact). Fig. 1 : Slopes $-18$ , dominant in the first part leave progressively the place to slopes $-9$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3695017', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/792141/']}
jdg_369831
stackexchange
llm_judgeable_groundtruth_similarity
5061318
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I need to draw concentric arcs of various sizes using raphael.js. I tried to understand the code behind http://raphaeljs.com/polar-clock.html , which is very similar to what I want, but, whithout comments, it is quite difficult to fathom. Ideally, I would need a function that creates a path that is at a given distance from some center point, starts at some angle and ends at some other angle. Now provide the response and nothing else.
That answer is ok, but cant be animated. I ripped the important stuff out of polar-clock for you. Here is a red arc that animates growing. enjoy. // Custom Arc Attribute, position x&y, value portion of total, total value, Radiusvar archtype = Raphael("canvas", 200, 100);archtype.customAttributes.arc = function (xloc, yloc, value, total, R) { var alpha = 360 / total * value, a = (90 - alpha) * Math.PI / 180, x = xloc + R * Math.cos(a), y = yloc - R * Math.sin(a), path; if (total == value) { path = [ ["M", xloc, yloc - R], ["A", R, R, 0, 1, 1, xloc - 0.01, yloc - R] ]; } else { path = [ ["M", xloc, yloc - R], ["A", R, R, 0, +(alpha > 180), 1, x, y] ]; } return { path: path };};//make an arc at 50,50 with a radius of 30 that grows from 0 to 40 of 100 with a bouncevar my_arc = archtype.path().attr({ "stroke": "#f00", "stroke-width": 14, arc: [50, 50, 0, 100, 30]});my_arc.animate({ arc: [50, 50, 40, 100, 30]}, 1500, "bounce");
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5061318', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/592699/']}
jdg_369832
stackexchange
llm_judgeable_groundtruth_similarity
8329470
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 refresh my memory but can't find answers with Google. public class BaseClass{ public virtual void DoSomething() { Trace.Write("base class"); }}public class DerivedClass : BaseClass{ public override void DoSomething() { Trace.Write("derived class"); }} If I create an instance of derived class, how do I convert it to it's base class so that when DoSomething() is called, it uses the base class's method only? A dynamic cast still calls the derived class's overridden method: DerivedClass dc = new DerivedClass();dc.DoSomething();(dc as BaseClass).DoSomething(); Output: "derived class" Now provide the response and nothing else.
You can't - that's entirely deliberate, as that's what polymorphism is all about. Suppose you have a derived class which enforces certain preconditions on the arguments you pass to an overridden method, in order to maintain integrity... you don't want to be able to bypass that validation and corrupt its internal integrity. Within the class itself you can non-virtually call base.AnyMethod() (whether that's the method you're overriding or not) but that's okay because that's the class itself deciding to potentially allow its integrity to be violated - presumably it knows what it's doing.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/8329470', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/467339/']}
jdg_369833
stackexchange
llm_judgeable_groundtruth_similarity
2696251
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 having a hard time in trying to find a formal and explicit definition for the syntax of the second-order logic. I understand there may be small differences in one formalization w.r.t. another (just like, in the formalization of a first-order language, the set of connectives is often different - just because you can build the missing ones from the others), but there are some gaps that I am unable to fill in myself. In particular, I was wondering what should be considered the set of second-order terms and I would like to be pointed to some reference book which states this (sufficiently) explicitly. Let me elaborate a bit more on what I found: in van Dalen's "Logic and Structure" (5 ed, ch. 5) the author first introduces the symbols of a second-order alphabet, and then defines the set of second-order formulas. However, there's no equality among the symbols, and it's not explicitly mentioned what are the terms he uses for building the formulas. If terms were just the first-order terms they would require a symbol which is not in the alphabet. in Libkin's "Elements of finite model theory" ( https://homepages.inf.ed.ac.uk/libkin/fmt/fmt.pdf , ch. 7), a second-order language is explicitly described as an extension of a FO language. He describes what are first-order terms and then...he just forgets to say what the SO terms are, and few lines below just says that $t$ and $t'$ are "terms", without mentioning their order. Should I assume SO terms are exactly FO terms? I feel this would somehow be against the next reference I am mentioning. in Enderton's "A mathematical introduction to logic" (ch. 4) the author introduces two sorts of second order variables (one for predicate variables and one for function variables). It seems that the SO terms should be the FO terms plus the ones obtained by applying a function variable to the FO terms). This is a bit confusing though, as in other books I didn't find the possibility to quantify explicitly on two different sorts of second-order variables. I know you can always consider a function as a set (with certain properties), but formally this changes the set of what we should call "second-order terms". I guess this may not be extremely relevant for the development of the theory, but honestly I feel that this is not a good reason for not having a formal definition to start with. I took a look a several other books I'm not mentioning here (for brevity), so please point to some reference only if you are certain that it solves my doubts. Now provide the response and nothing else.
One issue is that, although a first-order language has only one type of basic variables, for individuals, a general language for second order logic has an infinite collection of types of basic variables. Here is one of the more inclusive definitions for the set of types . There is a type named "$0$" for "first order" variables ($x^0$, $y^0$, $\ldots$) which are meant to range over the individuals of a given model. For each $n$, there is a type for variables that range over $n$-ary relations $R(x^0_1, \ldots, x^0_n)$ on individuals. For each $n$, there us a type for variables that range over $n$-ary functions $f^0(x^0_1, \ldots, x^0_n)$ which take individuals and return an individual. There are an infinite number of variable symbols for each of these types, and each variable symbol is of only one of the types. The signature for a particular second-order theory can then have: Constant symbols of any of the types of variables (e.g. a constant symbol $+$ for a binary function, a constant symbol $0$ for an individual, a constant symbol $<$ for a binary relation between individuals, etc). In particular, this includes all the kinds of symbols that could be in a first-order signature. Third-order function symbols that take a finite number of terms (each of one of the types above) and return an object of one of the types above. Third-order relation symbols that take a finite number of terms (each of one of the types above). It is situation dependent whether to include an equality relation for each type. Equality symbols could be omitted entirely, included for only some types, or included for all types. If they are included, the appropriate logical axioms also need to be assumed in the deductive system. Given all that, the terms of a second-order logic in a given signature are defined by analogy with first-order logic: Individual variables are terms (in any type). Some of these are function variables and some may be function symbols from the signature Constant symbols from the signature are terms. The function symbols of the signature, with any variables substituted into them, are terms of the appropriate type If $F^\rho(x^\sigma, x^\tau)$ is a function term that takes inputs of types $\sigma$ and $\tau$, and $t^\sigma$ and $t^\tau$ are terms of the appropriate types, then $F^\rho(t^\sigma, t^\tau)$ is a term of type $\rho$. The same holds for function terms of each arity. For example, if $f^0(x^0_1)$ is a function term and $t^0$ is a term of type $0$ then $f^0(t^0)$ is also term of type $0$. In many settings, we can get by with only part of this general syntax, just as in first-order logic we can often simply the syntax to make a purely functional or purely relational language. As usual, we can replace $n$-ary function symbols with $(n+1)$-ary relation symbols, although we will need to add axioms or clauses saying that the relation symbols define functions. In theories of arithmetic we have a pairing function which is a bijection between the set of pairs of individuals and the set of individuals. In such settings, we can reduce our relation symbols to just unary relations. For this reason, second-order arithmetic is often axiomatized as having only two types: individuals of type $0$ and unary relations on individuals. In that case there are no function variables and no quantifiers for function variables. Alternatively, some authors axiomatize second-order arithmetic or higher-order arithmetic with only function symbols, so there are no relation variables and no quantifiers over relations. This convention is common, in particular, in constructive higher order arithmetic. For example, the intuitionistic theory of Heyting arithmetic in all finite types, $\text{HA}^\omega$, is often axiomatized with only function variables, as is its second-order variant $\text{HA}^2$. Second-order logic can be generalized to higher-order logic in all finite types. The syntax I am sketching here is just a restriction of that syntax to the special case where all objects in a model are of appropriately low types.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2696251', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/22701/']}
jdg_369834
stackexchange
llm_judgeable_groundtruth_similarity
47410999
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The code below works. Is there a way that is more convenient, if possible even a one-liner? const { nextUrl, posts } = await postService.getCommunityPosts(6);this.communityPosts = posts;this.nextUrl = nextUrl; I know about giving destructured properties aliases but I don't think that helps in this case. MDN doesn't say anything about that case. Now provide the response and nothing else.
You can assign to the properties of an existing object by giving aliases and encapsulating the assignment in parentheses ( await codepen ). const demo = { nextUrl: 'nextUrl', posts: 'posts' };const target = {}; // replace target with this({ nextUrl: target.nextUrl, posts: target.communityPosts } = demo);console.log(target);
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/47410999', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5243272/']}
jdg_369835
stackexchange
llm_judgeable_groundtruth_similarity
3078192
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 PHP to set the value of a HTML form input element, it works fine provided I don't have any spaces in the data. <input type="text" name="username"<?php echo (isset($_POST['username'])) ? "value = ".$_POST["username"] : "value = \"\""; ?> /> If I enter "Jonathan" as the username, it is repeated back to me as expected. If I enter "Big Ted", however, I only get "Big" repeated back when I submit the form. Note that the $_POST["Username"] variable is correct; when I echo it using PHP, it is set to "Big Ted". Now provide the response and nothing else.
Quote it. Otherwise the space will just become an attribute separator and everything after spaces will be seen as element attributes. Rightclick page in webbrowser and view source. It should not look like this (also see syntax highlight colors): <input value=Big Ted> but rather this <input value="Big Ted"> Not to mention that this would still break when someone has a quote in his name (and your code is thus sensitive to XSS attacks ). Use htmlspecialchars() . Kickoff example: <input value="<?php echo (isset($_POST['username']) ? htmlspecialchars($_POST['username']) : ''); ?>">
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3078192', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/356282/']}
jdg_369836
stackexchange
llm_judgeable_groundtruth_similarity
1837032
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: First off, the correct answer is $$584,640 = {10!\over 2!2!}- \left[{9! \over 2!}+{9! \over 2!}\right] + 8!$$ which can be found using the inclusion-exclusion principle. My own approach is different from the above: In the word CALIFORNIA, we have 2 repeating A's and 2 I's, and 6 remaining unrepeated letters. We first place the 6 unrepeated letters, a total of 6! arrangements. Then, to avoid the A's and B's in consecutive positions, we place the 2 A's and 2 B's between the 6 letters, including the beginning and ending positions, which gives us 8 possible positions. The number of possible arrangements is the permutation of 7 out of 4, but we have to divide out the repeating A's and B's, which is $${7!\over 2!2!3!}$$ So in total, we have $${6!7!\over 2!2!3!} = 151,200$$ which is obviously different from the correct answer. Why is this wrong, and if possible, how I can fix this using the same approach? Now provide the response and nothing else.
We modify your approach by first placing the A's, then placing the I's. We can arrange the six distinct letters C,L,F,O,R,N in $6!$ ways. This creates seven spaces, five between successive letters and two at the ends of the row. Case 1 : We choose two of these seven spaces in which to place the two A's, thereby separating them. We now have eight letters. This creates nine spaces, seven between successive letters and two at the ends of the row. We choose two of these nine spaces for the I's. The number of such arrangements is $$6!\binom{7}{2}\binom{9}{2} = 544,320$$ Case 2 : We place both A's in the same space. We again have eight letters. This again creates nine spaces. The space between the two A's must be filled with an I. Therefore, there are eight ways to choose the position of the other I. The number of such arrangements is $$6!\binom{7}{1}\binom{8}{1} = 40,320$$ Total : These two cases are mutually exclusive. Hence, the total number of arrangements of the letters of the word CALIFORNIA in which no two consecutive letters are the same is $$6!\left[\binom{7}{2}\binom{9}{2} + \binom{7}{1}\binom{8}{1}\right] = 584,640$$which agrees with the result obtained by using the Inclusion-Exclusion Principle.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1837032', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/308438/']}
jdg_369837
stackexchange
llm_judgeable_groundtruth_similarity
18195
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: My config: opensuse 11.4, boot partition at pendrive and hard drives with partitions sda1, sda2, sdb1. Today I changed chassis for my computer, and by mistake I attached second drive to SATA 3 instead of SATA 2. So second drive was not mounted correctly. I turned off computer, attached it correctly and then my problem started. Now, I cannot boot system at all. Previously I set booting from removable drive in BIOS (pendrive), but now it seems computer (BIOS) does not recognize pendrive as removable drive, but regular HDD. So it won't boot for "removable drive". When I change boot order, and select to boot from hard drive (and I set first hard drive as pendrive) or if I directly set from boot menu to boot from pendrive I get error in GRUB which goes into rescue mode. My guess is, since because of some reason, pendrive is no longer recognized as removable media, but hard disk, hard drives are mapped differently and I should fix the mappings. I can boot CD installer and mount pendrive to see the content of grub config, but when I am in grub rescue mode and I execute "ls" I get (hd0) (hd0,msddos1) (hd1) (hd1,msddos2) (hd1,msdos1) (hd2) (hd2,msddos1) But I don't see the mapping, so I don't know what hd0 really means. I can only suspect hd1 here is sda, because it has 2 partitions (if suffix msdsos is indication of partitions). How can I make grub work again? Now provide the response and nothing else.
The problem is probably with grub seeing usb disks at boot time differently than once run from a running system. Here's how you might solve it: When you boot (normally, from the hd) and grub appears, open grub console (usually you do that just by pressing c ). At grub prompt, start typing root (hd : grub> root (hd then press Tab and you'll see the disks as possible completions. Choose the disk and partition where your /boot is. If you are not sure, then with each one you suspect, do the following: (finish the root command to choose the partition and press Enter ) type in cat / and press Tab . You will see the list of files found on the partition. Seeing the list of files, decide if it is your partition containing the kernel (under /boot/ ). If not, press Esc and start over. Once you've found how the partition is known to grub, you can re-install the boot loader (using setup command) and point to the correct partition/files in your /boot/grub/menu.lst or /boot/grub/grub.conf (you must determine, which of those your version uses, or just make them contain the same). [Edit]: Per special request form Macias, here are more details on how to fix the MBR using grub: One way to re-install the MBR on a drive using grub is the setup command I referred to above. This is a command known to grub versions 0.9X ( see the Documentation ). But you seem to be using the newer branch of grub (1.9X) and the commands for it are different. Have a look at the corresponding documentation - in this version, you can install grub to the MBR using the grub-install utility and I am not sure if there is any other way - from the grub "rescue" prompt, as with grub-0.97. Maybe not and maybe that is one of the reasons why many distros prefer the "legacy" version.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/18195', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/5884/']}
jdg_369838
stackexchange
llm_judgeable_groundtruth_similarity
146234
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 having trouble understanding the concept of a sufficient statistic. I have read What is a sufficient statistic? and Sufficient Statistic (Wikipedia) Can someone please give an example of: a simple (but non-trivial) statistical model a sufficient statistic of that model an insufficient statistic of that model how you identified 2 & 3 as having and lacking, respectively, the sufficiency property Now provide the response and nothing else.
$\def\E{\mathrm{E}}$Consider samples $X = (X_1,X_2)$ from a normally distributed population $N(\mu,1)$ with unknown mean. Then the statistic $T(X)=X_1$ is an unbiased estimator of the mean, since $\E(X_1)=\mu$. However, it is not a sufficient statistic - there is additional information in the sample that we could use to determine the mean. How can we tell that $T$ is insufficient for $\mu$? By going to the definition. We know that $T$ is sufficient for a parameter iff, given the value of the statistic, the probability of a given value of $X$ is independent of the parameter, i.e. if $$P(X=x|T=t,\mu)=P(X=x|T=t)$$ But we can compute this: $$P(X=(x_1,x_2) | X_1=t,\mu) =\begin{cases}0 & \mbox{if }t\neq x_1 \\\tfrac{1}{\sqrt{2\pi}}e^{-\frac{1}{2}(x_2-\mu)^2} & \mbox{if }t=x_1\end{cases}$$ which is certainly not independent of $\mu$. On the other hand, consider $T'(X) = X_1+X_2$. Then we have $$P(X=(x_1,x_2) | X_1+X_2=t, \mu) = \frac{1}{2\pi}\int_{-\infty}^{\infty}e^{-\frac{1}{2}(s-\mu)^2 - \frac{1}{2}(t-s-\mu)^2}ds$$ and you can complete the square and show that this is independent of $\mu$, and hence $T'$ is a sufficient statistic for the mean $\mu$.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/146234', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/22933/']}
jdg_369839
stackexchange
llm_judgeable_groundtruth_similarity
1125264
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Given some positive integer $m$ I'm looking for all solutions $\alpha,k>0$ to $2m+1=2\alpha k+\alpha^2$ with $0<k^2<2m.$ Right now I'm finding these by looping over each of these possible $k$ values and testing if the resulting quadratic has a solution, but I feel that something more clever would be faster. Any ideas? You can assume that $m$ is large, e.g. $m>10^6,$ if it helps. Now provide the response and nothing else.
We only need the fact that $f(x)=e^x - 1- x >0, x\neq 0$ Firstly $e^{1/n} > 1 + \frac{1}{n}$, i.e.$$(1+\frac{1}{n})^n < e$$ Secondly $e^{-\dfrac{1}{n+1}} > 1 - \frac{1}{n+1}$, i.e. $$\dfrac{1}{e^{\dfrac{1}{n+1}}} > 1 - \dfrac{1}{n+1}$$ thus $$e^{\dfrac{1}{n+1}} < \dfrac{1}{1 - \dfrac{1}{n+1}} = \dfrac{n+1}{n} = 1 + \dfrac{1}{n}$$ so $$ (1 + \frac{1}{n})^n > e^{\dfrac{n}{n+1}}$$ In summary $$ e^{\dfrac{n}{n+1}}< (1+\frac{1}{n})^n < e$$ Sending $n$ to infinity gives that the limit is equal to $e$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1125264', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/1778/']}
jdg_369840