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 | 40358827 |
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 iterate through a range of numbers (0-100) in steps(3) with IntStream? I tried iterate , but this never stops executing. IntStream.iterate(0, n -> n + 3).filter(x -> x > 0 && x < 100).forEach(System.out::println)
Now provide the response and nothing else.
| Actually range is ideal for this. IntStream.range(0, 100).filter(x -> x % 3 == 0); //107,566 ns/op [Average] Edit: Holgers's solution is the fastest performing solution. Since the following lines of code IntStream.range(0, 100).filter(x -> x % 3 == 0).forEach((x) -> x = x + 2); IntStream.range(0, 100 / 3).map(x -> x * 3).forEach((x) -> x = x + 2); int limit = ( 100 / 3 ) + 1; IntStream.iterate(0, n -> n + 3).limit(limit).forEach((x) -> x = x + 2); show these benchmark results Benchmark Mode Cnt Score Error UnitsBenchmark.intStreamTest avgt 5 485,473 ± 58,402 ns/opBenchmark.intStreamTest2 avgt 5 202,135 ± 7,237 ns/opBenchmark.intStreamTest3 avgt 5 280,307 ± 41,772 ns/op | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40358827', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1530093/']} | jdg_74441 |
stackexchange | llm_judgeable_groundtruth_similarity | 81880 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I want a different color for terminal returns: Example: $ pwd //when return key is hit $ /home/user/tools //return value printed in different color, say: grey color This requirement is not specific to pwd , command but for any command thrown to the terminal, my log will: $black //input $grey //output hope it is clear.
Now provide the response and nothing else.
| Method #1: ssh-keyscan One method would be to use the command ssh-keyscan to see if a ssh daemon is up and functioning. Just loop through the IP addresses and ssh-keyscan <ip> | grep -v ... each server. If the server is there, the status returned by running the ssh-keyscan ... | grep -v ... command will be a 0, anything else (1 or higher) means there isn't a server there. Example $ for IP_ADDRESS in `cat $IP_FILE` ; do ssh-keyscan $IP_ADDRESS 2>&1 | grep -v "^$" > /dev/null [ $? == 0 ] && echo $IP_ADDRESS >> $LOGFILE 2>&1 done Just to break this down a little bit more so it's crystal clear what's going on, the ssh-keyscan $IP_ADDRESS 2>&1 will run, any output returned (both stderr & stdout is merged together). All this output is then piped to the grep -v "^$" which will return a 0 for lines that return output (ssh servers running) and a 1 for servers that don't (the "^$" is a blank line). Quick tangent on loops (for vs. while & how they parse) The looping mechanism above (for loop) works because the file only contains a string of characters of which none are a space and that each "string" is terminated by a new line character. By default a space is the special separation character that's used to designate to the for loop how to parse the arguments being passed to it. This character is defined by the variable $IFS and can be overridden so that it's the new line character ( IFS='^M' ) for example. You can make this a little more efficient by replacing the cat $IP_FILE with $( < $IP_FILE ) . For example: $ for IP_ADDRESS in $( < $IP_FILE ) ; do ssh-keyscan $IP_ADDRESS 2>&1 | grep -v "^$" > /dev/null [ $? == 0 ] && echo $IP_ADDRESS >> $LOGFILE 2>&1 done If the lines in the file $IP_FILE included spaces you could either override the $IFS as discussed a moment ago so that it was set to ^M or a while loop could be used instead, i.e. ( while read -ra line ; do ... ; done < $IP_FILE ). $ while read -ra IP_ADDRESS ; do ssh-keyscan $IP_ADDRESS 2>&1 | grep -v "^$" > /dev/null [ $? == 0 ] && echo $IP_ADDRESS >> $LOGFILE 2>&1 done < $IP_FILE Your example touch logfile_$(date "+%Y%m%d%T")IP_FILE="ip.txt"LOGFILE="logfile_$(date "+%Y%m%d%T")"if [[ ! -f ${IP_FILE} ]]; then echo "Cannot find IP address!" exit 1fifor IP_ADDRESS in `cat $IP_FILE` ; do #ssh $IP_ADDRESS >> $LOGFILE 2>&1 ssh-keyscan $IP_ADDRESS 2>&1 | grep -v "^$" > /dev/null [ $? == 0 ] && echo $IP_ADDRESS >> $LOGFILE 2>&1done Method #2: nmap You can also do something with the tool nmap . $ nmap -A -iL ip.txt -p T:22 This will go through the file, ip.txt which can contain hostnames and IP addresses and will scan each one's TCP port # 22, returning results similar to the following: Nmap scan report for somehost.somedom.local (192.168.1.200)Host is up (0.012s latency).PORT STATE SERVICE VERSION22/tcp open ssh OpenSSH 4.3 (protocol 2.0)| ssh-hostkey: 1024 2e:32:85:a2:56:23:01:f1:c2:8f:df:aa:83:7a:1e:ad (DSA)|_2048 f6:a1:23:1d:aa:44:4a:ce:b4:d3:f4:fe:e1:00:47:b7 (RSA) References Nmap Network Probing Cheatsheet Top 30 Nmap Command Examples For Sys/Network Admins | {} | {'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/81880', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/42408/']} | jdg_74442 |
stackexchange | llm_judgeable_groundtruth_similarity | 42238484 |
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 can we put in a setup.py file to prevent pip from collecting and attempting to install a package when using an unsupported Python version? For example magicstack is a project listed with the trove classifier: Programming Language :: Python :: 3 :: Only So I expect the following behaviour if pip --version is tied to python 2.7: $ pip install magicstackCollecting magicstack Could not find a version that satisfies the requirement magicstack (from versions: )No matching distribution found for magicstack But the actual behavior is that pip collects a release, downloads it, attempts to install it, and fails. There are other Python3-only releases, curio for example, which actually install fine - because the setup.py didn't use anything Python 3 specific - only to fail at import time when some Python 3 only syntax is used. And I'm sure there are packages which install OK, import OK, and maybe only fail at runtime! What is the correct method to specify your supported Python versions in a way that pip will respect? I've found a workaround, involving uploading only a wheel file, and refusing to uploading a .tar.gz distribution, but I would be interested to know the correct fix. Edit: How does pip know not to download the wheel distribution if the Python/os/architecture is not matching? Does it just use the .whl filename convention or is there something more sophisticated than that happening behind the scenes? Can we somehow give the metadata to a source distribution to make pip do the right thing with .tar.gz uploads?
Now provide the response and nothing else.
| There is a correct way to do this, but unfortunately pip only started supporting it in version 9.0.0 (released 2016-11-02), and so users with older versions of pip will continue to download packages willy-nilly regardless of what Python version they're for. In your setup.py file, pass setup() a python_requires argument that lists your package's supported Python versions as a PEP 440 version specifier . For example, if your package is for Python 3+ only, write: setup( ... python_requires='>=3', ...) If your package is for Python 3.3 and up but you're not willing to commit to Python 4 support yet, write: setup( ... python_requires='~=3.3', ...) If your package is for Python 2.6, 2.7, and all versions of Python 3 starting with 3.3, write: setup( ... python_requires='>=2.6, !=3.0.*, !=3.1.*, !=3.2.*, <4', ...) And so on. Once you've done that, you will need to upgrade your version of setuptools to at least 24.2.0 in order for the python_requires argument to be processed; earlier versions will just ignore it with a warning. All of your project's sdists and wheels built afterwards will then contain the relevant metadata that tells PyPI to tell pip what Python versions they're for. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42238484', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/674039/']} | jdg_74443 |
stackexchange | llm_judgeable_groundtruth_similarity | 14474513 |
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 question boils down to this code: // setupString str1 = "some string";String str2 = new String(str1);assert str1.equals(str2);assert str1 != str2;String str3 = str2.intern();// question casesboolean case1 = str1 == "some string";boolean case2 = str1 == str3; Does Java standard give any guarantees about values of case1 and case2 ?Link to relevant part of Java spec would be nice, of course. Yes, I looked at all the "Similar Questions" found by SO, and found no duplicates, as none I found answered the question this way. And no, this is not about the misguided idea of "optimizing" string comparisons by replacing equals with == .
Now provide the response and nothing else.
| Here is your JLS quote, Section 3.10.5 : Each string literal is a reference (§4.3) to an instance (§4.3.1, §12.5) of class String (§4.3.3). String objects have a constant value. String literals-or, more generally, strings that are the values of constant expressions (§15.28)-are "interned" so as to share unique instances, using the method String.intern. Thus, the test program consisting of the compilation unit (§7.3): package testPackage;class Test { public static void main(String[] args) { String hello = "Hello", lo = "lo"; System.out.print((hello == "Hello") + " "); System.out.print((Other.hello == hello) + " "); System.out.print((other.Other.hello == hello) + " "); System.out.print((hello == ("Hel"+"lo")) + " "); System.out.print((hello == ("Hel"+lo)) + " "); System.out.println(hello == ("Hel"+lo).intern()); }}class Other { static String hello = "Hello"; } and the compilation unit: package other;public class Other { static String hello = "Hello"; } produces the output: true true true true false true This example illustrates six points: Literal strings within the same class (§8) in the same package (§7) represent references to the same String object (§4.3.1). Literal strings within different classes in the same package represent references to the same String object. Literal strings within different classes in different packages likewise represent references to the same String object. Strings computed by constant expressions (§15.28) are computed at compile time and then treated as if they were literals. Strings computed by concatenation at run time are newly created and therefore distinct. The result of explicitly interning a computed string is the same string as any pre-existing literal string with the same contents. Combined with the JavaDoc for intern, and you have enough information to deduce that both of your cases will return true. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14474513', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1717300/']} | jdg_74444 |
stackexchange | llm_judgeable_groundtruth_similarity | 456523 |
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 querying information from Active Directory . I have code that works, but it's really slow. This is the code I currently use: static void Main(string[] args) { SearchResultCollection sResults = null; try { //modify this line to include your domain name string path = "LDAP://EXTECH"; //init a directory entry DirectoryEntry dEntry = new DirectoryEntry(path); //init a directory searcher DirectorySearcher dSearcher = new DirectorySearcher(dEntry); //This line applies a filter to the search specifying a username to search for //modify this line to specify a user name. if you want to search for all //users who start with k - set SearchString to "k" dSearcher.Filter = "(&(objectClass=user))"; //perform search on active directory sResults = dSearcher.FindAll(); //loop through results of search foreach (SearchResult searchResult in sResults) { if (searchResult.Properties["CN"][0].ToString() == "Adit") { ////loop through the ad properties //foreach (string propertyKey in //searchResult.Properties["st"]) //{ //pull the collection of objects with this key name ResultPropertyValueCollection valueCollection = searchResult.Properties["manager"]; foreach (Object propertyValue in valueCollection) { //loop through the values that have a specific name //an example of a property that would have multiple //collections for the same name would be memberof //Console.WriteLine("Property Name: " + valueCollection..ToString()); Console.WriteLine("Property Value: " + (string)propertyValue.ToString()); //["sAMAccountName"][0].ToString(); } //} Console.WriteLine(" "); } } } catch (InvalidOperationException iOe) { // } catch (NotSupportedException nSe) { // } finally { // dispose of objects used if (sResults != null) sResults.Dispose(); } Console.ReadLine(); } What would faster code look like to get user information from AD?
Now provide the response and nothing else.
| The reason why your code is slow is that your LDAP query retrieves every single user object in your domain even though you're only interested in one user with a common name of "Adit": dSearcher.Filter = "(&(objectClass=user))"; So to optimize, you need to narrow your LDAP query to just the user you are interested in. Try something like: dSearcher.Filter = "(&(objectClass=user)(cn=Adit))"; In addition, don't forget to dispose these objects when done: DirectoryEntry dEntry DirectorySearcher dSearcher | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/456523', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/23491/']} | jdg_74445 |
stackexchange | llm_judgeable_groundtruth_similarity | 307348 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I understand intuitively that this is true, but I'm embarrassed to say I'm having a hard time constructing a rigorous proof that $|a+b| \leq |a|+|b|$. Any help would be appreciated :)
Now provide the response and nothing else.
| From your definition of the absolute value, establish first $|x| = \max\{x,-x\}$ and $\pm x ≤ |x|$ . Then you can use \begin{align*}a + b &≤ |a| + b ≤ |a| + |b|,\quad\text{and}\\-a - b &≤ |a| -b ≤ |a| + |b|.\end{align*} | {} | {'log_upvote_score': 8, 'links': ['https://math.stackexchange.com/questions/307348', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/62561/']} | jdg_74446 |
stackexchange | llm_judgeable_groundtruth_similarity | 1029959 |
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 was writing some C code to sort an array of structs using quicksort with a custom comparator function to determine their ordering. At first I wrote it with the call to the comparator function hard-coded into the quicksort function. Then I thought perhaps it would be nicer to pass that function as an argument to a generic quicksort function. In my original code, I had declared the comparator function inline . In my new code, I kept the inline declaration, even though that didn't really make much sense to me, given that the function was being passed as a parameter. However, the compiler didn't complain! My question is: is the inline declaration having any effect here, or is it merely a recommendation to the compiler which is being ignored? Original code: typedef struct _CGRect { CGPoint origin; CGSize size;} CGRect;typedef enum _NSComparisonResult { NSOrderedAscending = -1, NSOrderedSame, NSOrderedDescending} NSComparisonResult;static inline NSComparisonResult CGRectCompareRowsFirst(CGRect r1, CGRect r2){ if (r1.origin.y < r2.origin.y) return NSOrderedAscending; else if (r1.origin.y > r2.origin.y) return NSOrderedDescending; else { if (r1.origin.x < r2.origin.x) return NSOrderedAscending; else if (r1.origin.x > r2.origin.x) return NSOrderedDescending; else return NSOrderedSame; }}static void CGRectQuicksortRowsFirst(CGRect *left, CGRect *right){ if (right > left) { CGRect pivot = left[(right-left)/2]; CGRect *r = right, *l = left; do { while (CGRectCompareRowsFirst(*l, pivot) == NSOrderedAscending) l++; while (CGRectCompareRowsFirst(*r, pivot) == NSOrderedDescending) r--; if (l <= r) { CGRect t = *l; *l++ = *r; *r-- = t; } } while (l <= r); CGRectQuicksortRowsFirst(left, r); CGRectQuicksortRowsFirst(l, right); }}static void CGRectSortRowsFirst(CGRect *array, int length){ CGRectQuicksortRowsFirst(array, array+length-1);} New code: static inline NSComparisonResult CGRectCompareRowsFirst(const void *s1, const void *s2){ CGRect r1 = *(CGRect *)s1, r2 = *(CGRect *)s2; if (r1.origin.y < r2.origin.y) return NSOrderedAscending; else if (r1.origin.y > r2.origin.y) return NSOrderedDescending; else { if (r1.origin.x < r2.origin.x) return NSOrderedAscending; else if (r1.origin.x > r2.origin.x) return NSOrderedDescending; else return NSOrderedSame; }}static void quick(CGRect *left, CGRect *right, NSComparisonResult(*f)(const void *, const void *)){ if (right > left) { CGRect pivot = left[(right-left)/2]; CGRect *r = right, *l = left; do { while (f(&*l, &pivot) == NSOrderedAscending) l++; while (f(&*r, &pivot) == NSOrderedDescending) r--; if (l <= r) { CGRect t = *l; *l++ = *r; *r-- = t; } } while (l <= r); quick(left, r, f); quick(l, right, f); }}static void CGRectSortRowsFirst(CGRect *array, int length){ quick(array, array+length-1, CGRectCompareRowsFirst);}
Now provide the response and nothing else.
| Inline is just a recommendation to the compiler, and can be ignored. This can happen for several reasons, such as if the function is too complex to be safely inlined. If you pass it as a parameter to a function like above, the compiler will create the non-inlined version whose address will be passed to the function. It may be possible that the compiler could still inline the function - for instance, during code generation the compiler could utilize the inline function hint replacing the call via a function pointer to just the expanded function; I am not sure if any current compiler would do that. Inlined and non-inlined versions can and often do co-exist within one compiled program. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1029959', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/107392/']} | jdg_74447 |
stackexchange | llm_judgeable_groundtruth_similarity | 17314996 |
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 read the other subjects but it doesn't solve my problem so: I've got this ->add('role', 'choice', array( 'label' => 'I am:', 'mapped' => true, 'expanded' => true, 'multiple' => false, 'choices' => array( 'ROLE_NORMAL' => 'Standard', 'ROLE_VIP' => 'VIP', ) )) And whatever I do, I get this error: Notice: Array to string conversion in C:\xampp\htdocs\xxx\vendor\symfony\symfony \src\Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceList.php line 458 In my form type the setRole method is not even called (when I rename it to some garbage the error still occurs). Why is this happening? // EDIT Full stack trace: in C:\xampp\htdocs\xxx\vendor\symfony\symfony\src\Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceList.php at line 458 - */ protected function fixIndex($index) { if (is_bool($index) || (string) (int) $index === (string) $index) { return (int) $index; } at ErrorHandler ->handle ('8', 'Array to string conversion', 'C:\xampp\htdocs \xxx\vendor\symfony\symfony\src\Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceList.php', '458', array('index' => array()))in C:\xampp\htdocs\xxx\vendor\symfony\symfony\src\Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceList.php at line 458 +at ChoiceList ->fixIndex (array())in C:\xampp\htdocs\xxx\vendor\symfony\symfony\src\Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceList.php at line 476 +at ChoiceList ->fixIndices (array(array()))in C:\xampp\htdocs\xxx\vendor\symfony\symfony\src\Symfony\Component\Form\Extension\Core\ChoiceList\SimpleChoiceList.php at line 152 +at SimpleChoiceList ->fixChoices (array(array()))in C:\xampp\htdocs\xxx\vendor\symfony\symfony\src\Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceList.php at line 204 +at ChoiceList ->getIndicesForChoices (array(array()))in C:\xampp\htdocs\xxx\vendor\symfony\symfony\src\Symfony\Component\Form\Extension\Core\DataTransformer\ChoiceToBooleanArrayTransformer.php at line 63 +at ChoiceToBooleanArrayTransformer ->transform (array())in C:\xampp\htdocs\xxx\vendor\symfony\symfony\src\Symfony\Component\Form\Form.php at line 1019 +at Form ->normToView (array())in C:\xampp\htdocs\xxx\vendor\symfony\symfony\src\Symfony\Component\Form\Form.php at line 332 +at Form ->setData (array())in C:\xampp\htdocs\xxx\vendor\symfony\symfony\src\Symfony\Component\Form\Extension\Core\DataMapper\PropertyPathMapper.php at line 59 +at PropertyPathMapper ->mapDataToForms (object(User), object(RecursiveIteratorIterator))in C:\xampp\htdocs\xxx\vendor\symfony\symfony\src\Symfony\Component\Form\Form.php at line 375 +at Form ->setData (object(User))in C:\xampp\htdocs\xxx\vendor\friendsofsymfony\user-bundle\FOS\UserBundle\Controller\RegistrationController.php at line 49 +at RegistrationController ->registerAction (object(Request))at call_user_func_array (array(object(RegistrationController), 'registerAction'), array(object(Request)))in C:\xampp\htdocs\xxx\app\bootstrap.php.cache at line 2770 +at HttpKernel ->handleRaw (object(Request), '1')in C:\xampp\htdocs\xxx\app\bootstrap.php.cache at line 2744 +at HttpKernel ->handle (object(Request), '1', true)in C:\xampp\htdocs\xxx\app\bootstrap.php.cache at line 2874 +at ContainerAwareHttpKernel ->handle (object(Request), '1', true)in C:\xampp\htdocs\xxx\app\bootstrap.php.cache at line 2175 +at Kernel ->handle (object(Request))in C:\xampp\htdocs\xxx\web\app_dev.php at line 29 +
Now provide the response and nothing else.
| Symfony's trying to convert your $role(array property) to not multiple choice field(string). There's several ways to deal with this problem: Set multiple to true in your choice form widget. Change mapping from array to string for $role property in your entity. If you insist to have above options unchanged, you can create DataTransformer. That's not the best solution because you will lose data if your array have more than 1 element . Example: <?phpnamespace Acme\DemoBundle\Form\DataTransformer;use Symfony\Component\Form\DataTransformerInterface;use Symfony\Component\Form\Exception\TransformationFailedException;class StringToArrayTransformer implements DataTransformerInterface{ /** * Transforms an array to a string. * POSSIBLE LOSS OF DATA * * @return string */ public function transform($array) { return $array[0]; } /** * Transforms a string to an array. * * @param string $string * * @return array */ public function reverseTransform($string) { return array($string); }} And then in your form class: use Acme\DemoBundle\Form\DataTransformer\StringToArrayTransformer;/* ... */$transformer = new StringToArrayTransformer();$builder->add($builder->create('role', 'choice', array( 'label' => 'I am:', 'mapped' => true, 'expanded' => true, 'multiple' => false, 'choices' => array( 'ROLE_NORMAL' => 'Standard', 'ROLE_VIP' => 'VIP', ) ))->addModelTransformer($transformer)); You can read more about DataTransformers here: http://symfony.com/doc/current/cookbook/form/data_transformers.html | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17314996', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2394156/']} | jdg_74448 |
stackexchange | llm_judgeable_groundtruth_similarity | 30284693 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm working on a python project that runs for a couple hours before it's finished all it's calculations. I would like to hold the top 10 results of the calculation as it progresses. There's the obvious way of doing: if calc > highest_calc: second_calc = highest_calc highest_calc = calcif calc < highest_calc and calc > second_calc: third_calc = second_calc second_calc = calcif calc < second_calc and calc > third_calc: fourth_calc = third_calc third_calc = calcetc. But is there a better, more dynamic and pythonic way? Bonus For my project, each calcultion has three coresponding names with it: name_a name_b name_c . What I don't want is more then one of the top 10 values to have the same three names. But, if the last calc has the same names, I want to keep the highest of the two. What's the best way to do this? For example, lets say 2.3 is the value of calc , using MCD SBUX and CAT to calculate calc . But what if I had already made a calc using MCD SBUX and CAT and it made it to the top to? How do I find the value of this calc so I can see if it is less than or greater then the new calc . If it is greater than, remove the old calc with the same and add the new calc . If it is less than, pass new calc. Hopefully that makes sense: If name_a in top10 and name_b in top10 and name_c in top10: if calc > old_calc_with_same_names: add_calc = calc, name_a, name_b, name_c top10.insert(bisect.bisect(calc, top10[0]), add_calc)else: add to top10 Finished Code csc = []top_ports = []add_sharpe = [sharpe, name_a, weight_a, exchange_a, name_b, weight_b, exchange_b, name_c, weight_c, exchange_c] if init__calc == 0: csc.append(add_sharpe) if init__calc > 1: if name_a == prev_name_a and name_b == prev_name_b and name_c == prev_name_c: csc.append(add_sharpe) if name_a != prev_name_a or name_b != prev_name_b or name_c != prev_name_c: if csc: hs = max(csc, key=lambda x: x[0]) if top_ports: ls = min(top_ports, key=lambda x: x[0]) if hs[0] > ls[0]: hsi = csc.index(hs) top_ports.append(csc[hsi]) else: hsi = csc.index(hs) top_ports.append(csc[hsi]) csc = [] csc.append(add_sharpe) Later on in the script... top_ports = sorted(top_ports, key=itemgetter(0), reverse=True)print "The highest sharpe is: {0}".format(top_ports[0])print " ==============================================="print " ==============================================="print datetime.now() - startTimeprint "Second: {0}".format(top_ports[1])print "Third: {0}".format(top_ports[2])print "Fourth: {0}".format(top_ports[3])print "Fifth: {0}".format(top_ports[4]) etc.
Now provide the response and nothing else.
| Use the heapq module. Instead of needlessly storing all results, at every step it adds the new result and then efficiently removes the lowest—which may be the one just added—effectively keeping the top 10. Storing all results is not necessarily bad though; it can be valuable to collect statistics, and make it easier to determine what to keep afterwards. from heapq import heappush, heappushpopheap = []for x in [18, 85, 36, 57, 2, 45, 55, 1, 28, 73, 95, 38, 89, 15, 7, 61]: calculation_result = x + 1 # Dummy calculation if len(heap) < 10: heappush(heap, calculation_result) else: heappushpop(heap, calculation_result)top10 = sorted(heap, reverse=True) # [96, 90, 86, 74, 62, 58, 56, 46, 39, 37] Note that this module has more useful functions to only request the highest/lowest value, et cetera. This may help you to add the behavior concerning names. Actually this construct is so common that it is available as heapq.nlargest . However, to not store all your results after all, you'd have to model the calculator as a generator, which is a bit more advanced. from heapq import nlargestdef calculate_gen(): for x in [18, 85, 36, 57, 2, 45, 55, 1, 28, 73, 95, 38, 89, 15, 7, 61]: yield x + 1 # Dummy calculationtop10 = nlargest(10, calculate_gen()) # [96, 90, 86, 74, 62, 58, 56, 46, 39, 37] Bonus Here is some idea to make the results unique for each combination of associated names. Using a heap is not going to cut it anymore, because a heap is not good at locating any item that is not the absolute minimum/maximum, and what we are interested in here is some kind of local minimum given the criteria of a name combination. Instead, you can use a dict to keep the highest value for each name combination. First you need to encode the name combination as an immutable value for it to work as a key, and because the order of the names shouldn't matter, decide on some order and stick with it. I'm going with alphabetical strings to keep it simple. In the code below, each result is put in the dict at a place that is unique for its name combination—therefore normalization might be needed—as long as there isn't a better result already. Later the top n is compiled from the highest results for each combination. from heapq import nlargestcalculations = [('ABC', 18), ('CDE', 85), ('BAC', 36), ('CDE', 57), ('ECD', 2), ('BAD', 45), ('EFG', 55), ('DCE', 1)]highest_per_name_combi = dict()for name_combi, value in calculations: normal_name_combi = ''.join(sorted(name_combi)) # Slow solution current = highest_per_name_combi.get(normal_name_combi, float('-inf')) highest_per_name_combi[normal_name_combi] = max(value, current)top3 = nlargest(3, highest_per_name_combi.iteritems(), key=lambda x: x[1]) The only problem with this approach might be the amount of memory used. Since with 150 names there can be 551300 (150 choose 3) combinations, you may have to decide to clean up the dict every now and then, which is simple. In the loop, check for the size of the dict and if it exceeds some (still large) number, compose the current top n and create a new, minimal dict from it. Also, some micro optimizations could be applied by reducing the number of lookups/calls, e.g. not using get and/or max . All of this would be a lot easier if you'd have control over the order in which calculations are performed. If you'd know that the next 1000 calculations are all for the same name combination, you could just find the best of those first before adding it to the overall results. Also, with a truly massive amount of results, the simplest way may actually be the best. Just write them to a file in a convenient format, sort them there (first by name combination, then reversely by value), take only the first occurrence for each name combination (easy when they are grouped) and sort the result again, just by value. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30284693', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3478500/']} | jdg_74449 |
stackexchange | llm_judgeable_groundtruth_similarity | 65125885 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Can you have an array as a dependancy for the useMemo hook? I know this would be fine: const dep1 : string = '1'const thing = useMemo(()=>{ // stuff},[dep1]) But what about this?: const dep2 : string[] = ['1', '2']const thing2 = useMemo(()=>{ // stuff},[dep2]) I thought that I read once that objects and arrays will always return false for the equality check, effectively meaning thing2 will never be memoized. However I can't see this in the docs: https://reactjs.org/docs/hooks-reference.html#usememo This is a contrived example as dep1 and dep2 are constant variables but imagine they were a prop where the value would change.
Now provide the response and nothing else.
| I think I was getting confused by React.memo , from the docs: By default it will only shallowly compare complex objects in the props object. If you want control over the comparison, you can also provide a custom comparison function as the second argument. function MyComponent(props) { /* render using props */}function areEqual(prevProps, nextProps) { /* return true if passing nextProps to render would return the same result as passing prevProps to render, otherwise return false */}export default React.memo(MyComponent, areEqual); useMemo appears to work fine with an array as a dependancy: https://codesandbox.io/s/mystifying-cori-jr0vi?file=/src/App.js:0-647 import React, { useState, useMemo } from "react";import "./styles.css";export default function App() { console.log("App rendered"); const [st, setStr] = useState("0"); const [arr, setArr] = useState([1]); const thingToRender = useMemo(() => { console.log("thingToRender ran"); return `Array length is ${arr.length}`; }, [arr]); return ( <div className="App"> <button onClick={() => setStr(`${Math.random()}`)}>Change str</button> <h1>{st}</h1> <p>{thingToRender}</p> <button onClick={() => setArr([...arr, Math.round(Math.random() * 10)])}> Change arr </button> </div> );} However it's worth being aware that it wont work if you map (or other methods that create a new array): https://codesandbox.io/s/silent-silence-91j8s?file=/src/App.js import React, { useState, useMemo } from "react";import "./styles.css";export default function App() { console.log("App rendered"); const [st, setStr] = useState("0"); const [arr, setArr] = useState([1]); const arr2 = arr.map((item) => item); const thingToRender = useMemo(() => { console.log("thingToRender ran"); return `Array length is ${arr2.length}`; }, [arr2]); return ( <div className="App"> <button onClick={() => setStr(`${Math.random()}`)}>Change str</button> <h1>{st}</h1> <p>{thingToRender}</p> <button onClick={() => setArr([...arr, Math.round(Math.random() * 10)])}> Change arr </button> </div> );} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/65125885', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/467875/']} | jdg_74450 |
stackexchange | llm_judgeable_groundtruth_similarity | 2665331 |
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:
Here is the problem: If $f$ is a nonnegative Lebesgue measurable function and $\{E_n\}_{n=1}^{\infty}$ is a sequence of Lebesgue measurable sets with $E_1\subset E_2\subset ...$, then $\int_{\bigcup_{n=1}^{\infty}E_n}f{\rm d}\lambda = \lim_{n\to\infty}\int_{E_n}f{\rm d}\lambda$. I know that $\int_{\bigcup \limits_{n=1}^{\infty} E_{n}} f \,d\lambda = \int \limits_{\Bbb R} f \chi_{\bigcup \limits_{n=1}^{\infty} E_{n}} \,d\lambda$. I'm also thinking that I should apply the Monotone Convergence Theorem. However, I don't know where to go from here. Any help would be appreciated.
Now provide the response and nothing else.
| Write $\displaystyle\int_{\bigcup_{n=1}^{\infty}E_{n}}fd\lambda=\int_{X}\chi_{\bigcup_{n=1}^{\infty}E_{n}}fd\lambda$ and $\displaystyle\int_{E_{n}}fd\lambda=\int_{X}\chi_{E_{n}}fd\lambda$ and now observe that $f\chi_{E_{n}}\uparrow f\chi_{\bigcup_{n=1}^{\infty}E_{n}}$ so Monotone Convergence Theorem applies here. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2665331', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/534658/']} | jdg_74451 |
stackexchange | llm_judgeable_groundtruth_similarity | 26356777 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Why write Try without a Catch or Finally as in the following example? protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet tryse</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet tryse at " + request.getContextPath() + "</h1>"); out.println("</body>"); out.println("</html>"); }}
Now provide the response and nothing else.
| As explained above this is a feature in Java 7 and beyond. try with resources allows to skip writing the finally and closes all the resources being used in try-block itself. As stated in Docs Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource. See this code example static String readFirstLineFromFile(String path) throws IOException { try (BufferedReader br = new BufferedReader(new FileReader(path))) { return br.readLine(); }} In this example the resource is BufferReader object as the class implements the interface java.lang.AutoCloseable and it will be closed whether the try block executes successfully or not which means that you won't have to write br.close() explicitly. Another important thing to notice here is that if you are writing the finally block yourself and both your try and finally block throw exception then the exception from try block is supressed. While on the other hand if you are using try-with-resources statement and exception is thrown by both try block and try-with-resources statement then in this case the exception from try-with-resources statement is suppressed. As the @Aaron has answered already above I just tried to explain you. Hope it helps. Source: http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/26356777', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4060613/']} | jdg_74452 |
stackexchange | llm_judgeable_groundtruth_similarity | 6770649 |
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 recently upgraded to OSX 10.7, at which point my rails installation completely borked when trying to connect to the psql server. When I do it from the command line using psql -U postgres it works totally fine, but when I try to run the rails server or console with the same username and password, I get this error ...activerecord-3.0.9/lib/active_record/connection_adapters/postgresql_adapter.rb:950:in `initialize': could not connect to server: Permission denied (PGError) Is the server running locally and accepting connections on Unix domain socket "/var/pgsql_socket/.s.PGSQL.5432"? Any ideas what might be going on would be super helpful! Thanks!
Now provide the response and nothing else.
| It's a PATH issue. Mac OSX Lion includes Postgresql in the system now. If you do a which psql you'll likely see usr/bin/psql instead of usr/local/bin/psql which is HomeBrew's correct one. If you run brew doctor you should get a message stating that you need to add usr/local/bin to the head of your PATH env variable. Editing your .bash_profile or .profile, or whichever shell you're using and adding: export PATH=/usr/local/bin:$PATH as the first export for the PATH then either quit you shell session or source your file with source ~/.bash_profile and it should now be OK again. | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/6770649', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/434498/']} | jdg_74453 |
stackexchange | llm_judgeable_groundtruth_similarity | 47527529 |
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 following menu in angular 4 <button mat-button [matMenuTriggerFor]="menu" style="display:none;">Menu</button> <mat-menu #menu="matMenu"> <button mat-menu-item *ngFor="let item of items" (click)="select(item)"> {{ item }} </button> </mat-menu> I am opening the menu when user selects text on screen using matMenuTrigger.openMenu(); but I want to open menu wherever user selects text.I have X and Y coordinates of user selection but how can I change position of menu? I have tried giving Id to mat-menu and changing it's position using element.style.position = 'absolute'element.style.left = screenX + 'px'element.style.top = screenY + 'px' but it's not changing position of menu. EDIT: I have changed position of menu by this.matMenuTrigger.openMenu();var element = document.getElementsByClassName('cdk-overlay-pane');menu.style.position = "absolute";menu.style.left = evt.pageX + 5 + 'px';menu.style.top = evt.pageY + 5 + 'px'; where evt is mouseup event which gives co-ordinates(X,Y) of user text selection. But, when I scroll the page , opened menu again goes back to it's original position.How can I keep menu to it's changed position on scroll??
Now provide the response and nothing else.
| I have implemented opening mat-menu where ever user selectes text. I have added hidden button which on click opens menu.On user text selection, I have changed style="display:none;" of that button to style="display:'';" and after showing that button, I have changed position of that button to where user has selected the text by x and y co-ordinates and then opened menu programatically by this.menuTrigger.openMenu(); DEMO menu-example.ts export class MenuIconsExample {@ViewChild(MatMenuTrigger) private menuTrigger: MatMenuTrigger; addTextToOpns: Array<String> = ["option 1", "option 2", "option 3"]; selectedOption: string = "no Option selected"; onTextSelection(event: any):void{ if(window.getSelection && window.getSelection().toString()){ var menu = document.getElementById('menuBtn'); menu.style.display = ''; menu.style.position = 'absolute'; menu.style.left = event.pageX + 5 + 'px'; menu.style.top = event.pageY + 5 + 'px'; this.menuTrigger.openMenu(); } } onMenuClosed():void { var menu = document.getElementById('menuBtn'); if (menu) { menu.style.display = 'none'; } } addTextTo(selectedOpn): void { this.selectedOption = selectedOpn + ' selected'; }} menu-example.html <div (mouseup)="onTextSelection($event)"> <button mat-button [matMenuTriggerFor]="menu" id="menuBtn" style="display:none;">Menu</button> <mat-menu #menu="matMenu" (close)="onMenuClosed()"> <button class="menuOpnBtn" mat-menu-item *ngFor="let opn of addTextToOpns" (click)="addTextTo(opn)"> {{ opn }} </button> </mat-menu> <p> text for selection </p></div><br/><br/><div><span>selected option : </span> <span>{{selectedOption}}</span></div> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47527529', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2585827/']} | jdg_74454 |
stackexchange | llm_judgeable_groundtruth_similarity | 37633 |
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:
Is a NN with no hidden layer is behave like a regression? What we could say that NN without hidden layer can say us? If we have for instance 20 input and 4 output and I have no true label, is it similar to regression? If it is a regression then it will be a supervised learning however there is no true label! What is wrong inside this clarification? more clarification: Also, I have a dqn ( a deep learning structure inside q-learning approach)! Unfortunately I do not have the optimal answer of it! I am looking for a way to compare my results, Maybe I can compare by putting a un/supervised learning approach instead of DNN! For instance, you can put a DNN without hidden layer and as it behaves like the linear regression then you can put every supervised learning instead of it! As there is no True label I have problem with training section and estimate the DNN section with supervised learning! Also,as it is MDP, I can not estimate the DNN section with unsupervised learning!
Now provide the response and nothing else.
| Out of the two pipelines you mentioned, I'd recommend the second (i.e. real-time augmentation). This is better than the first, because by performing random augmentations the network sees different images at each epoch. I'd recommend imgaug , which is a python library for performing data augmentation. I've found it very helpful as it can work with keras' ImageDataGenerator very well. The way can do this is: from imgaug import augmenters as iaaseq = iaa.Sequential([...]) # list of desired augmentorsig = ImageDataGenerator(preprocessing_function=seq.augment_image) # pass this as the preprocessing functiongen = ig.flow_from_directory(data_dir) # nothing else changes with the generator One final note I'd like to make is that $7 \cdot 50 = 350$ images are very few for deep learning, even with augmentation. Make sure you use a pre-trained network or else you will have a serious overfitting problem. | {} | {'log_upvote_score': 4, 'links': ['https://datascience.stackexchange.com/questions/37633', 'https://datascience.stackexchange.com', 'https://datascience.stackexchange.com/users/58433/']} | jdg_74455 |
stackexchange | llm_judgeable_groundtruth_similarity | 51256318 |
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 experiencing a strange issue in React. I think probably I have not fully grasped how React works and I really appreciate your help. Please find below my React component: class myComponent extends Component { state = { value: '' } updateValue = e => { this.setState({ value: e.target.value }) } render() { return ( <form> <input type="text" onChange={this.updateValue} defaultValue={this.state.value} /> </form> ) }} Then, now if I type something in the text field, I will get following warning and errors: Warning: This synthetic event is reused for performance reasons. If you're seeing this, you're accessing the property target on a released/nullified synthetic event. This is set to null. If you must keep the original synthetic event around, use event.persist(). Uncaught TypeError: Cannot read property 'value' of null But if I change the 'updateValue' method to: updateValue = e => { const newValue = e.target.value this.setState({ value: newValue }) } It will work without any issue.
Now provide the response and nothing else.
| Updated answer As @FelixKling pointed out, my answer wasn't entirely correct. My answer is only valid if you pass a function as a parameter to setState , not if you pass an object like done in the question. If you pass an object to setState , the parameter will be evaluated immediately, that is, before the event has been nullified. As such, the mentioned error won't occur. If you pass a function to setState , the parameter will be evaluated within that function, which happens after updateValue has completed/returned and the event has been nullified. If you pass a function to setState , you must store the e.target.value in a variable (or call e.persist() ) before setState . Old (slightly wrong) answer This problem occurs because (as the error message says) the event is set to null when the callback (your updateValue function) is completed. Because this.setState() is an asynchronous function , it will not be executed immediately. As a result, this.setState() is actually executed after your updateValue is finished, and hence after the event has been nullified. Your solution is actually the proposed way from the React docs ! | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51256318', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3690904/']} | jdg_74456 |
stackexchange | llm_judgeable_groundtruth_similarity | 43256472 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
$query = mysqli_query($mysqli, "SELECT product_name ,MIN(product_price) product_price,link FROM(select jumia.product_name,jumia.product_price,jumia.product_image,jumia.link from jumia INNER JOINjumia ON jumia.id = olx.id where product.name like '%{$search}%'UNIONselect olx.product_name,olx.product_price,olx.product_image, olx.link from olx INNER JOINolx ON olx.id = jumia.idwhere product.name like '%{$search}%')MinimGROUP BY product_name,product_image"); I am trying to create a query from two tables with similar column names as displayed above that will allow me to display the rows between the two tables that have the lowest price. For example, if product_name called mattresses is searched the matching item in my database whose price is lower between the two table names should be displayed. Some help would be appreciated
Now provide the response and nothing else.
| The pedantically correct way to check that a .so exports a symbol is nm --demangle --dynamic --defined-only --extern-only <lib.so> | grep <symbol> . Without --defined-only your command also shows undefined symbols. Without --extern-only it also shows symbols with internal linkage which are unavailable for linking. It looks like you need to link another library because Gps_Ephemeris::Gps_Ephermeris() is not resolved by linking libgnss_system_parameters_dyn.so . A good way to start is that library's documentation and examples. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/43256472', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7827029/']} | jdg_74457 |
stackexchange | llm_judgeable_groundtruth_similarity | 6204511 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In my application, I need to talk to multiple databases. I am handling this in NHibernate by creating one SessionFactory per database (I assume this is the correct thing to do). So I have two sets of models (one per database), and two sets of Fluent NHibernate ClassMap<> mappings. Both are in the same project (separated by namespace) and I'd like to keep it that way. The problem comes when creating the SessionFactory. As far as I can see, Fluent NHibernate has basically two methods for adding mappings: .Mappings(m => m.FluentMappings.AddFromAssemblyOf<UserClassMap>()) .Mappings(m => m.FluentMappings.Add<UserClassMap>() If I use the first overload, then my session factories get all the mappings for both databases. If I use the second, I have to specify each individual ClassMap. I'd like something like FluentMappings.AddFromNamespace() . Is there a way to do this?
Now provide the response and nothing else.
| It's odd that FluentNHibernate supports this type of filtering for automapping, but not for ClassMap s. It shouldn't be too hard to add this feature yourself, though, via the magic of extension methods. Try this: public static FluentMappingsContainer AddFromAssemblyOf<T>( this FluentMappingsContainer mappings, Predicate<Type> where){ if (where == null) return mappings.AddFromAssemblyOf<T>(); var mappingClasses = typeof(T).Assembly.GetExportedTypes() .Where(x => (typeof(IMappingProvider).IsAssignableFrom(x) || typeof(IExternalComponentMappingProvider).IsAssignableFrom(x)) && where(x)); foreach (var type in mappingClasses) { mappings.Add(type); } return mappings;} ... and use it like this: m.FluentMappings.AddFromAssemblyOf<UserClassMap>(t => t.Namespace.StartsWith("One.Of.The.Two.Namespaces")); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6204511', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13356/']} | jdg_74458 |
stackexchange | llm_judgeable_groundtruth_similarity | 5650 |
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:
If one were to dissolve magnesium citrate (about $100~\mathrm{mg}$) in water (about $70~\mathrm{ml}$) and let the solution sit for 48 hours, would the solution be exactly the same as one dissolved and consumed right away? How does one explain the difference in taste from a 48-hour solution and a 5-minute solution?
Now provide the response and nothing else.
| The only reactions that I would expect to occur to any significant extent with pure water are acid-base reactions between the citrate and water, where water, being amphiprotic, could act as either an acid or a base: $$\ce{C6H6O7^2- + H2O <=> C6H7O7- + OH-}$$$$\ce{C6H6O7^2- + H2O <=> C6H5O7^3- + H3O+}$$ Citrate, being the conjugate base of a weak acid, is itself a weak base (according to the citric acid Wikipedia page , the $\mathrm pK_\mathrm a$ for the dissociation of the second proton is 4.75, and for the third between 5.41 and 6.40). Citrate is tripotic, and in the magnesium salt citrate possesses one undissociated acidic proton, which makes it an amphiprotic molecule as well. Given that the $\mathrm pK_\mathrm a$ of water is approximately 15.7, and the $\mathrm pK_\mathrm a$ of hydronium ($\ce{H3O+}$) is −1.74, both reactions above favor the reactants over the products by many orders of magnitude, though the second reaction is favored above the first (i.e., the dibasic magnesium citrate salt should still be very slightly acidic, overall). Acid-base reactions typically reach equilibrium quite quickly, so there should be very little change in pH and no pH-attributable differences in taste over time. If any change does occur, I would expect it to be the result of a change in concentration as the water gradually evaporates. Another possibility is that, if the water is impure (which tap water certainly is), additional side-reactions might occur. What those are would depend on the exact composition of the water as well as environmental conditions. It's possible for the magnesium to form a precipitate, for example, in combination with other anions dissolved in the water (unlikely given the quantity in your example, but possible). If the magnesium citrate is part of a commercial product containing other ingredients, then it may well be that other agents are responsible for any effects you observe. | {} | {'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/5650', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/861/']} | jdg_74459 |
stackexchange | llm_judgeable_groundtruth_similarity | 16192321 |
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 developing app, where I need to display suggestions in ListView and when orientation changed I want that list to be hidden. But it appears on the screen anyway. I tried this:1) Get list adapter and clear it.2) Set visibility GONE before orientation changed (but it becomes visible again after onCreate)3) Set visibility GONE in onCreate, but the list still appears on the screen (I think that maybe android saves old list, because I initialize list view again and it looks like empty, but the list on the screen isn't).So, how can i get rid of the list?
Now provide the response and nothing else.
| Instead of using something global like android:configChanges which affect ALL the views in the Activity, what about using the method setSaveEnabled(boolean) or the equivalent xml attribute android:saveEnabled ? Controls whether the saving of this view's state is enabled (that is, whether its onSaveInstanceState() method will be called). If you set it to false it should always go back to the default state when changing orientation because its state won't be saved. You could, for example, put this in the layout file: <ListView .... android:visibility="invisible" android:saveEnabled="false"></ListView> and then set the visibility to VISIBLE when you start typing. Or if you prefer put the visibility and the method setSaveEnabled in the onCreate method. I tried with a simple ListView and a Button that changes the visibility to true. On rotation the ListView became invisibile(its default state) Also note that: This flag can only disable the saving of this view; any child views may still have their state saved. so you should have to clear the list during onStop() or whatever method you want but if even if you don't, the ListView will still be invisible on rotation Source: http://developer.android.com/reference/android/view/View.html#attr_android:saveEnabled http://developer.android.com/reference/android/view/View.html#setSaveEnabled%28boolean%29 | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16192321', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2285617/']} | jdg_74460 |
stackexchange | llm_judgeable_groundtruth_similarity | 14328115 |
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 CRUD page which shows data from a query (a List of domain objects) in a Primefaces datatable. <p:dataTable id="negozi" var="n" value="#{nController.theListFromQuery}" rowKey="#{n.id}" selection="#{nController.selected}" selectionMode="single"> <p:column headerText="Field1"> <h:outputText value="#{n.f1}" /> </p:column> <p:column headerText="Field2"> <h:outputText value="#{n.f2}" /> </p:column><p:column style="width:4%"> <p:commandButton actionListener="#{nController.prepareEdit(n)}" update=":editDialogId" oncomplete="editDialog.show()" value="Edit" /> </p:column>... By clicking on the edit button a dialog will be shown: <p:dialog header="Edit N" widgetVar="editDialog" id="editDialogId"> <h:form id="formDialog"> <h:panelGrid id="editDialogTable" columns="2" cellpadding="10" style="margin:0 auto;"> <p:outputLabel for="field1" value="F1:" /> <p:inputText id="field1" value="#{nController.selected.f1}" /> <p:outputLabel for="field2" value="F2:" /> <p:inputText id="field2" value="#{nController.selected.f2}" /><p:commandButton value="Confirm" actionListener="#{nController.doEdit}" update=":form" oncomplete="editDialog.hide()" rendered="#{nController.selected.id!=null}" /> ... It works. Now I want to make F1 a required field. I add the "required" attribute to the inputText field and what happens? When I try to confirm the form without the required field, the entity is not edited (that's right) but the dialog is closed (that's NOT right!) When I reopen the dialog I can see the red highlight on the required (and invalid) field. What I want is to prevent the dialog closing if the form is invalid. Do I have to write some JS or will JSF help me?
Now provide the response and nothing else.
| The PrimeFaces ajax response puts an args object in the scope which has a validationFailed property. You could just make use of it. oncomplete="if (args && !args.validationFailed) PF('editDialog').hide()" (the args precheck is necessary to not cause a JS error when an exception is thrown during request) You could refactor it to a reusable JS function as follows. oncomplete="hideDialogOnSuccess(args, 'editDialog')" function hideDialogOnSuccess(args, dialogWidgetVar) { if (args && !args.validationFailed) { PF(dialogWidgetVar).hide(); }} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14328115', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/494826/']} | jdg_74461 |
stackexchange | llm_judgeable_groundtruth_similarity | 421532 |
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In Classical Mechanics it is "easy", if some system has some angular momentum at the beginning then conservation of angular momentum means that no matter what happens, the angular momentum vector at the end will be the same. In Quantum Mechanics it is different because we cannot even know the angular momentum of a system. We can only know its magnitude $L^2$ and one of its components, say $L_z$. So we cannot talk about the conservation of angular momentum as implying that the initial vector must be the same as the final vector. We don't know such vector. So how do we apply the conservation of angular momentum? The mean value of the vector $\langle \vec{L} \rangle$, of which we know exactly the three components, is the magnitude that is conserved? What about other quantities related to angular momentum, such as its dispersion $\sigma_L$? Is the angular momentum ket of a system the thing that is conserved? I mean, if a system is in some eigenstate of angular momentum $|j,m\rangle$, is this property of the system the one that does not change due to conservation?
Now provide the response and nothing else.
| In QM, angular momentum is conserved as an operator. Deal with it. This is best seen in the Heisenberg picture , where the equation of motion for $\hat{\mathbf L}$ in a spherically-symmetric hamiltonian $\hat H$,$$i\hbar\frac{\mathrm d}{\mathrm dt}\hat{\mathbf L} = [\hat{\mathbf L},\hat H] = 0,$$so $\hat{\mathbf L}$ is conserved as an operator as $t$ goes from $t=0$ onwards. In particular, this means that: If the system is in an eigenstate of a function of $\hat{\mathbf L}$ (including the magnitude $\hat{L}^2$ or any components) then it stays in that eigenspace for all time. If the system is in a superposition of such eigenstates, then the weights and relative phases of that superposition are maintained. This then implies that all moments of all distributions of observables that are a function of $\hat{\mathbf L}$ are constant in time. These conclusions also hold equally well in the Schrödinger picture. (On the other hand, if you know that the system is in some eigenstate $|\psi⟩$ of $\hat L^2$ and $\hat L_z$ and it evolves under a spherically symmetric hamiltonian $\hat H$ in the Schrödinger picture, you can conclude that it will remain as an eigenstate of $\hat L^2$ and $\hat L_z$ with its same eigenvalues, but you cannot conclude that the state does not change, as there is typically radial motion which can obviously change.) | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/421532', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/171780/']} | jdg_74462 |
stackexchange | llm_judgeable_groundtruth_similarity | 1442 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The identity $\displaystyle (n+1) \text{lcm} \left( {n \choose 0}, {n \choose 1}, ... {n \choose n} \right) = \text{lcm}(1, 2, ... n+1)$ is probably not well-known. The only way I know how to prove it is by using Kummer's theorem that the power of $p$ dividing ${a+b \choose a}$ is the number of carries needed to add $a$ and $b$ in base $p$. Is there a more direct proof, e.g., by showing that each side divides the other?
Now provide the response and nothing else.
| Consider Leibniz harmonic triangle — a table that is like «Pascal triangle reversed»: on it's sides lie numbers $\frac{1}{n}$ and each number is the sum of two beneath it (see the picture ). One can easily proove by induction that m-th number in n-th row of Leibniz triangle is $\frac{1}{(n+1)\binom{n}{m}}$. So LHS of our identity is just lcd of fractions in n-th row of the triangle. But it's not hard to see that any such number is an integer linear combination of fractions on triangle's sides (i.e. $1/1,1/2,\dots,1/n$) — and vice versa. So LHS is equal to $lcd(1/1,\dots,1/n)$ — and that is exactly RHS. | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/1442', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/232/']} | jdg_74463 |
stackexchange | llm_judgeable_groundtruth_similarity | 24595 |
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 would like to use Compile with functions defined outside Compile . For example if I have the two basic functions F and G F[x_] := x + 2G[x_] := x And I want to compute F[G[x]] in Compile compiledFunction = Compile[{{x, _Real, 0}}, F[G[x]] ] The resulting compiled function calls MainEvaluate FastCompiledFunctionQ[function_CompiledFunction]:=( Needs["CompiledFunctionTools`"]; StringFreeQ[CompiledFunctionTools`CompilePrint@function,"MainEvaluate"])compiledFunction // FastCompiledFunctionQ This returns False , where FastCompiledFunctionQ[] checks if a compiled function calls MainEvaluate in order to use normal Mathematica code instead of compiled code, which is usually slower than compiled code. Is there a way around this? More generally I want to compile almost any numerical Mathematica code that calls user-defined functions (which themselves can call other user-defined functions) and doesn't use symbolic computations.
Now provide the response and nothing else.
| Yes there is a way to use functions that use external non compiled functions. It uses the step function of Mr.Wizard defined in the post How do I evaluate only one step of an expression? , in order to recursively expand the code that we want to compile until it uses only functions that Mathematica can compile. The technique discussed in the post How to inject an evaluated expression into a held expression? is also used. The function ExpandCode needs two functions that tell it when a function should be expanded and when a function should be evaluated during the expansion. Using the functions defined below we can do to solve the question code = Hold[F[G[x]]]codeExpand = ExpandCode[code]compiledFunction2 = Function[codeExpanded, Compile[{{x, _Real}}, codeExpanded], HoldFirst] @@ codeExpand The $CriteriaFunction used here is that a function name (symbol) should have upper case letters only. Note the use of pure function with HoldFirst attribute in order to avoid evaluation leaks. And now the function compiledFunction2 doesn't call MainEvaluate and returns the right answer compiledFunction2 // FastCompiledFunctionQcompiledFunction2[2] A more streamlined version of this for common cases using a function defined below CompileExpand[{{x, _Real}}, F[G[x]]] // FastCompiledFunctionQ Here's the main code and some advice are after it. SetAttributes[STEP, {Flat, OneIdentity, HoldFirst}];STEP[expr_] := Module[{P}, P = (P = Return[# (*/. HoldForm[x_] :> Defer[STEP[x]]*), TraceScan] &) &; TraceScan[P, expr, TraceDepth -> 1] ];ReleaseAllHold[expr_,firstLevel_:0,lastLevel_:Infinity] := Replace[expr, (Hold|HoldForm|HoldPattern|HoldComplete)[e___] :> e, {firstLevel, lastLevel}, Heads -> True];SetAttributes[EVALUATE,HoldFirst];EVALUATE[x_]:=x;$CriteriaFunction =Function[symbol,UpperCaseQ@SymbolName@symbol,HoldFirst];$FullEvalFunction=Function[symbol,symbol===EVALUATE,HoldFirst];ExpandCode[code_]:=ReleaseAllHold[Quiet@ExpandCodeAux[code,$CriteriaFunction ,$FullEvalFunction], 1];ExpandCodeAux[code_,criteria_,fullEval_]:= code /. (expr:(x_Symbol[___]) /; criteria@x :> RuleCondition[ If[fullEval@x, expr , With[{oneStep = HoldForm@Evaluate@STEP@expr}, If[oneStep===HoldForm@expr, oneStep , ExpandCodeAux[oneStep,criteria,fullEval] ] ] ] ] );SetAttributes[CompileExpand,HoldAll]; CompileExpand[variables_,code_,otherVariables___]:= Function[ codeExpanded , Compile[variables,codeExpanded,otherVariables] , HoldFirst ] @@ ExpandCode[Hold@code];FastCompiledFunctionQ[function_CompiledFunction]:=( Needs["CompiledFunctionTools`"]; StringFreeQ[CompiledFunctionTools`CompilePrint@function,"MainEvaluate"])(*Example*)SetAttributes[{F,G},HoldAll];F[x_] := G[x] + 2;G[x_] := 3 x;compiledFunction3=CompileExpand[{{x,_Real}},F[G[x]]+EVALUATE@Range@5,CompilationTarget->"WVM"]compiledFunction3//FastCompiledFunctionQcompiledFunction3[2] Comments You need to specify the type of the variables even if they are Realnumbers (for example {{x,_Real}} and not x for a function of just one variable). Works with any type of values : DownValues , UpValues , SubValues ... which means you can use auxiliary functions that use the pattern matcher in their definitions instead of just already compiled functions that sometimes don't mix well together, and still be able to compile without calls to MainEvaluate . A function to be expanded can contain calls to other functions that will be expanded. In order to avoid problems the functions that you want to expand should have a HoldAll attribute ( SetAttributes[F,HoldAll] for example). Some useful Compile arguments for speed {Parallelization->True,RuntimeAttributes->{Listable},CompilationTarget->"WVM",RuntimeOptions->"Speed",CompilationOptions->{"ExpressionOptimization"->True,"InlineCompiledFunctions"->True,"InlineExternalDefinitions"->True} If you call many times a same relatively big function (for example an interpolation function that you have written), it can be best to use a CompiledFunctionCall as explained in this answer in order to avoid an exploding code size after code expansion. It can be best to avoid "ExpressionOptimization" when the CompilationTarget target is "WVM" (the compilation is faster, especially as the size of the expanded code can be very big). When it's "C" it's better to optimize the expression. Numeric functions don't have a HoldAll attribute and pose problems if you want to expand a function that is inside a numeric one. You can use InheritedBlock to circumvent this. For example blockedFunctions={Abs,Log,Power,Plus,Minus,Times,Max,UnitStep,Exp};With[{blockedFunctions=blockedFunctions}, Internal`InheritedBlock[blockedFunctions, SetAttributes[#,HoldAll]&/@blockedFunctions; ExpandCode[....] ]] If you use constant strings in your code you can replace them inside the code expanded with Real numbers (in order to return them together with a Real result in a List which will compile correctly, as you can't mix types in the result of a compiled function).For example Module[{cacheString,stringIndex=0.,codeExpandWithStringsReplaced}, c:cacheString[s_] := c = ++stringIndex; codeExpandWithStringsReplaced=codeExpand/.s_String:>RuleCondition[cacheString[s]]; ... ] And then cacheString can be used to convert the results returned by the compiled function back into strings. You need to access the keys and the values of cacheString , see here , or you can use and manipulate an Association in V10 instead of a symbol for cacheString . A simple way to fully evaluate an expression during the code expansion is to enclose the expression between an EVALUATE function equal to the identity function. SetAttributes[EVALUATE,HoldFirst];EVALUATE[x_]:=x;$FullEvalFunction = Function[symbol,symbol===EVALUATE,HoldFirst]; for example EVALUATE[Range@5] EVALUATE also lets you avoid using With in order to insert constant parameters into the compiled code. This code expansion can be used in order to have a fast compiled DSL (Domain Specific Language). If you modify the $CriteriaFunction you can use Apply. This is an easier way to use Apply with Compile than in this question: Using Apply inside Compile . $CriteriaFunction=Function[symbol,UpperCaseQ@SymbolName@symbol||symbol===Apply,HoldFirst]; f=Compile[{{x,_Real}},F@@{x}] f // FastCompiledFunctionQ (*False*)f=CompileExpand[{{x,_Real}},F@@{x}] f // FastCompiledFunctionQ (*True*) You can also use this syntax instead of redefining $CriteriaFunction. f = CompileExpand[{{x, _Real}}, STEP[F @@ {x}]] f // FastCompiledFunctionQ (*True*) | {} | {'log_upvote_score': 6, 'links': ['https://mathematica.stackexchange.com/questions/24595', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/66/']} | jdg_74464 |
stackexchange | llm_judgeable_groundtruth_similarity | 35237278 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Look at the following sql. CREATE SCHEMA IF NOT EXISTS `scheduler`;USE `scheduler` ;CREATE TABLE IF NOT EXISTS `scheduler`.`JobHistory` ( `Id` INT NOT NULL AUTO_INCREMENT, `Job` INT NOT NULL, `StartTime` TIMESTAMP NOT NULL, `FinishTime` TIMESTAMP NOT NULL, PRIMARY KEY (`Id`), INDEX `fk_JobHistory_Job_idx` (`Job` ASC)); It is throwing ErrorCode: 1067. Invalid default value for 'Finish Time' But I'm not giving any default value for finish time, also there is another time stamp StartTime which is exactly same and I'm not getting any exception for that one.
Now provide the response and nothing else.
| Although @jsnplank is right that timestamps are treated differently and you should consider using datetime datatype for these 2 particular columns, however, he fails to explain the error message. The error message is most likely the result of a combination of how mysql treats timestamp fields when no default value is provided and your sql mode settings. You define both timestamp columns as not null, without any specific default value set. This means that the 1st timestamp column's default value will be current_timestamp() and will also be updated to current_timestamp() whenever the record changes. This is why the 1st timestamp field does not generate an error message, no matter which of the 2 is the 1st one. However, the 2nd not null timestamp column's default value will be '0000-00-00 00:00:00' if you do not explicitly define a default value. See this blog post for more details . Probably no_zero_date sql mode is also enabled on your server either explicitly or as part of strict sql mode. This sql mode generates an error if you want set '0000-00-00 00:00:00' as a default value or would like to insert this value into any date field. So, you can use timestamp data type in your table, but make the 2nd one either nullable or provide 0 or any valid date (such as the epoch) as an explicit default value. Since you are marking start and end dates with these fields, uding datetime instead of timestamp as datatype may be a good idea. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35237278', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1521049/']} | jdg_74465 |
stackexchange | llm_judgeable_groundtruth_similarity | 49547016 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Google Cloud SQL advertises that it's only $0.0150 per hour for the smallest machine type, and I'm being charged for every hour, not just hours that I'm connected. Is this because I'm using a pool? How do I setup my backend so that it queries the cloud db only when needed so I don't get charged for every hour of the day? const mysql = require('mysql');const pool = mysql.createPool({ host : process.env.SQL_IP, user : 'root', password : process.env.SQL_PASS, database : 'mydb', ssl : { [redacted] }});function query(queryStatement, cB){ pool.getConnection(function(err, connection) { // Use the connection connection.query(queryStatement, function (error, results, fields) { // And done with the connection. connection.destroy(); // Callback cB(error,results,fields); }); });}
Now provide the response and nothing else.
| This is not so much about the pool as it is about the nature of Cloud SQL. Unlike App Engine, Cloud SQL instances are always up. I learned this the hard way one Saturday morning when I'd been away from the project for a week. :) There's no way to spin them down when they're not being used, unless you explicitly go stop the service. There's no way to schedule a service stop, at least within the GCP SDK. You could alway write a cron job, or something like that, that runs a little gcloud sql instances patch [INSTANCE_NAME] --activation-policy NEVER command at, for example, 6pm local time, M-F. I was too lazy to do that, so I just set a calendar reminder for myself to shut down my instance at the end of my workday. Here's the MySQL Instance start/stop/restart page for the current SDK's docs: https://cloud.google.com/sql/docs/mysql/start-stop-restart-instance On an additional note, there is an ongoing ' Feature Request ' in the GCP Platform to start/stop the Cloud SQL (2nd Gen), according to the traffic as well. You can also visit the link and provide your valuable suggestions/comments there as well. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49547016', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4418836/']} | jdg_74466 |
stackexchange | llm_judgeable_groundtruth_similarity | 432907 |
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm fairly new to statistics. I'm not clear on the meaning of independent and dependent variables and the relationship to what's being predicted. In my text, as an example there is a data set containing many instances of the following: a person's salary a person's age the year they earned that salary their education level The book mentions trying to predict their salary from the other three variables. Does this mean the other three are the independent variables and salary is the dependent variable? When this data is arranged in a spreadsheet, with rows being people and columns being variables, something interesting appears. There is symmetry between all the variables. None of them holds a special place in the spreadsheet, they each have their own column. Which then leads me to ask, could we pick another one, say age, and predict that from salary/year/education? Is age now the dependent variable? In high school statistics I learned that independent variables have some degree of independence... say the weather is independent from what I have for dinner. There's not much effect that one has on the other. But in statistics, can the independent variables be regarded as the "things we are using to make the prediction," while the dependent variable is the "thing being predicted?" Is there still a need for independent variables to really be independent in a real-world sense?
Now provide the response and nothing else.
| The questions "What do you want to predict?" and "What is the outcome or result here?" often have the same answer, but not always. The terminology of independent variables is widely considered overloaded in statistical sciences. Numerous writers and researchers -- over at least the last several decades -- have suggested using other terms, although there is little consensus on what the best terms are. Some terms are predictors , explanatory variables , controlling variables , regressors , covariates , inputs , .... The term dependent variable similarly is often substituted with something more evocative. For some time response seemed to lead the field of alternatives, but outcome and output have been among frequent recent terms. I note without enthusiasm the existence of regressand . DV and IV are common abbreviations in some fields, sometimes seeming to tag initiates engaged by mutual consent in regression rituals. An objection to DV is that Deo volente remains a standard expansion for many people. A bigger objection to IV is that it is bespoke (by many economists in particular) for instrumental variable. Still, the old terms linger on, and my impression (no names here) is that they are still often recommended in textbooks which on other grounds I regard as poor or incompetent. Terminology aside: There is no absolute implication that so-called independent variables in a regression are statistically independent of each other, and indeed that fact is one of several objections to the terminology. There are even situations in which predictors are deliberately introduced that are highly correlated with each other. Fitting a quadratic in $X$ and $X^2$ is a case in point, as $X$ and $X^2$ are not mutually independent. It's, however, foolish to include two predictors with essentially the same message, as say Fahrenheit and Celsius temperatures. In practice, good software has traps to detect that situation and drop predictors as needed, but the researcher still needs to be careful and thoughtful about their choice of predictors. The ideal -- easier to advise as a principle than to ensure in practice -- is for predictors to have a clear rationale and to use no more predictors than are needed for the purpose, and that are reasonable given the size of the dataset. Your example is instructive. Usually salary depends on age, sometimes directly if an individual moves up a salary scale, but more often indirectly through salary being affected by promotion or moves to a different job and those being affected by greater experience, expertise, reputation, and so forth. Conversely, sometimes older people are less attractive to employ (e.g. sports people past their peak). But the crux is that a salary raise doesn’t affect age, whereas a change in age may affect salary (on average, which is what we care about here). Causal paths can exist in indirect ways. All that said, in different problems age is unknown and the goal is to predict it. This is standard in archaeology, forensic sciences, and several Earth and environmental sciences. EDIT 3 August 2022 Although it may surprise many readers, yet another objection to dependent and independent as terminology for variables is that many beginners get them the wrong way round. This could be -- especially for people without English as their first language -- that the words can seem so similar, or that independence is an abstract statistical concept for those not yet familiar with it. | {} | {'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/432907', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/263584/']} | jdg_74467 |
stackexchange | llm_judgeable_groundtruth_similarity | 21805166 |
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 the PowerShell script located on a USB drive can be started the moment the drive is inserted in PC? It has to copy all PDF files from PC to the USB drive, but that's not the question. The only thing I don't know is how to start the script as soon as the USB drive is inserted. Can anyone help?
Now provide the response and nothing else.
| You can use Windows Management Instrumentation (WMI) events to detect when a USB flash drive is inserted. You can create a temporary event registration using the Register-WmiEvent cmdlet. Let's say that you have a script file called c:\test\script.ps1 . This script will be used to respond to events when they occur. Add-Content -Path $PSScriptRoot\test.txt -Value 'USB Flash Drive was inserted.'; Then, you need to register for WMI events using the Register-WmiEvent cmdlet in a separate script. You will need to specify the -Action and -Query parameters at a minimum. The PowerShell ScriptBlock that is passed to the -Action parameter will be invoked when an event occurs. The -Query parameter contains the WMI event query that will be used to poll WMI for events. I have provided a sample below. # Define a WMI event query, that looks for new instances of Win32_LogicalDisk where DriveType is "2"# http://msdn.microsoft.com/en-us/library/aa394173(v=vs.85).aspx$Query = "select * from __InstanceCreationEvent within 5 where TargetInstance ISA 'Win32_LogicalDisk' and TargetInstance.DriveType = 2";# Define a PowerShell ScriptBlock that will be executed when an event occurs$Action = { & C:\test\script.ps1; };# Create the event registrationRegister-WmiEvent -Query $Query -Action $Action -SourceIdentifier USBFlashDrive; Since you mentioned that you wanted to launch a PowerShell script file on the USB drive , when this event occurs, you can change the -Action ScriptBlock to this: $Action = { & ('{0}\ufd.ps1' -f $event.SourceEventArgs.NewEvent.TargetInstance.Name); }; The above code will dynamically execute the ufd.ps1 script file on the root of the USB drive that was just inserted. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21805166', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3236528/']} | jdg_74468 |
stackexchange | llm_judgeable_groundtruth_similarity | 1674898 |
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 currently in high school and is writing a maths research paper on a calculus problem. In the conclusion, I would like to include a 3D plot of a function I found. It goes something like this: a, b, are constants and m is the first positive solution to the equation. So far I have Matlab available though I've never used it before. Just looking for some pointers into how would I plot this function.
Now provide the response and nothing else.
| Let $$y=\left(\frac{\sqrt[n]{a}+\sqrt[n]{b}}{2}\right)^n$$$$\implies \log y= n\log \frac{\sqrt[n]{a}+\sqrt[n]{b}}{2}$$Let $n=\frac{1}{p}$ as $ n \rightarrow \infty, p\rightarrow 0$$$\implies \log y= \lim_{p \to 0}\frac{\log \frac{a^p+b^p}{2}}{p}$$Applying L.H rule, we get$$\log y=\lim_{p \to 0} \frac{a^p\log a+b^p\log b}{a^p+b^p}$$$$\implies \log y=\frac {1}{2}\log ab$$$$\implies y=\sqrt {ab}$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1674898', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/265087/']} | jdg_74469 |
stackexchange | llm_judgeable_groundtruth_similarity | 2302593 |
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 currently running my Django 1.1.1 site with PostgreSQL 8.4.2 both on the live server and locally. When I try to restore one of my backup from the live server on my local box, I get the following error while accessing my site locally( http://localhost:8000 ): Exception Type: ProgrammingError at /Exception Value: permission denied for relation django_session I also get a similar error while accessing all the contents of one of my models: $ python manage.py shellPython 2.6.4 (r264:75706, Dec 7 2009, 18:45:15) [GCC 4.4.1] on linux2Type "help", "copyright", "credits" or "license" for more information.(InteractiveConsole)>>> from myapp.models import MyModel>>> MyModel.objects.all()...ProgrammingError: permission denied for relation myapp_mymodel I used pg_dump for backup on the live server and dropping my local db followed by psql dbname < infile for restore. Does anyone know what's wrong?
Now provide the response and nothing else.
| Do you get the same error when connecting with psql as the same user (the user Django connects as)? Or do you have the same PostgreSQL users on your live site and your local machine? If not, you should dump/reload with the -Ox (or --no-owner) option to skip the ownership commands. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2302593', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/117642/']} | jdg_74470 |
stackexchange | llm_judgeable_groundtruth_similarity | 9822363 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have the following code: _container = new UnityContainer();_container.RegisterType<IDownloader, Downloader>();_container.RegisterType<INewObject, NewObject>();_container.RegisterType<SearchViewModel>(); SearchViewModel class with constructor injection: class SearchViewModel{ private readonly Func<IDownloader> _downloaderFactory; private readonly INewObject _newObject; private IDownloader _downloader; public SearchViewModel(Func<IDownloader> downloaderFactory, INewObject newObject) { _downloaderFactory = downloaderFactory; _newObject = newObject; } } The question: How to register SearchViewModel that has Fun<> as parameter? _container.RegisterType<SearchViewModel>(new InjectionConstructor(DownloaderFactory())); The code above works only without INewObject . The goal: Resolve factory with InjectionConstructor and resolve INewObject, INewObject2, INewObject3 automatically (like without parameters: RegisterType<SearchViewModel>() ). Is it possible? Maybe alternates?
Now provide the response and nothing else.
| I have solved the problem: _container.RegisterType<Func<IDownloader>>(new InjectionFactory(i => new Func<IDownloader> (() => _container.Resolve<IDownloader>())));_container.RegisterType<SearchViewModel>(); new Func is a key, because before I tried: _container.RegisterType<Func<IDownloader>>(new InjectionFactory(i => _container.Resolve<IDownloader>())); Also the better way to use IDownloaderFactory instead of Func<IDownloader> downloaderFactory . IDownloaderFactory can encapsulate the delegate. Also I think that using a delegate as dependency inside factory is better solution than broken Composition Root. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9822363', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/927030/']} | jdg_74471 |
stackexchange | llm_judgeable_groundtruth_similarity | 55272598 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Symptoms: ASP.NET Web Forms website on Azure sporadically crashes and all .aspx page requests fail with this error. The problem seems random and only happens once in a great while. The site may run for months with no issues then out of the blue it will stop serving any .aspx pages and gives the error on every .aspx page request. A restart of the website is the only solution (or redeploy, which causes the same thing). This was a very difficult problem to debug since it was so sporadic and none of the other answers I found helped, they did not address the problem where the site would deploy and run for long periods of time then crash with this error seemingly randomly. In the end I got some help from Microsoft.
Now provide the response and nothing else.
| According to Microsoft this is caused by a known bug with the .Net Framework versions 4.7.x triggered by memory pressure in the web server worker process. It is fixed in .Net framework 4.8 (not yet released at this time). My solution was simply to check "allowed precompiled site to be updatable" and check the "Do not merge" option. Details from Microsoft: The root cause of the issue is relating to the memory pressure on the worker process (w3wp.exe) address space. In ASP.net, when the .Net Framework detects that we have exceeded a certain memory pressure threshold, it will proceed to try and eject items from the internal caching structures in order to relieve space. Upon such a cache trim, assemblies belonging to your application are removed from the memory cache. This triggers a callback delegate that will try and reflect that changes in memory cache onto the cache of assemblies on disk – and will try and delete the .dll assembly ejected from the in-memory cache. However, the worker process is still keeping a reference to this file (an open handle) and as such, the delete fails. When this occurs, the .Net Framework creates a .delete file next to the assembly to mark it as stale. This will prevent the worker process from loading the file back into memory cache and causes the compilation error you are seeing. The cause of all of this cache processing is an incorrect insertion into the ASP.net memory cache of dynamic assemblies issued from the pre-compilation process with non-updatable UI. In this process of compilation, the names of the dynamic assemblies cannot be changed, as the .compiled resource files which indicate to the ASP.net Runtime where a compiled resource is located (in what binary) do not change if changes are made to the site – contrary to the pre-compilation with updatable UI, where the markup for pages can be subject to change, and this generates changes to the .compiled files and then to the names of the dynamic assemblies, thus preventing the re-usage of the old names. For assemblies that have come from the pre-compilation of an ASP.net application with non-updatable UI, the standard was to insert them into the ASP.net memory cache in the worker process with a special attribute that would indicate to the cache manager that these entries cannot be removed. This attribute is missing in the .Net Framework 4.7.x release builds and is the cause of the error. Without it, when the cache is trimmed, the assemblies can be removed, and since they are still in usage, they cannot be deleted from the Temporary ASP.net Files folder (the shadow copy folder). As such, this results in the creation of the .delete files. This was not an issue in builds of the .Net Framework prior to 4.7. The product group has also confirmed that they have resolved this issue in the upcoming .Net Framework 4.8 release. There are a couple of solutions around this issue: Remove the 4.7.x .Net Framework and re-install the 4.6.x Framework. The caching error is only present in builds of the .Net Framework of 4.7 and above, thereby reverting to a 4.6.x version would allow you to continue working without facing the problem. They can remain in the 4.6.x distribution until the .Net Framework 4.8 is released later this year. I do not have a timeline from the product group for this release as of now. Increase RAM and private bytes recycling limitations. (Does not apply to Azure webapps) The cache is trimmed in ASP.net when we see that the memory pressure is too great inside the worker process. This memory pressure is evaluated as follows: if you do not have a recycling condition set in the application’s application pool in IIS, ASP.net will consider the threshold to be 60 % of the total RAM available to the machine. When the private bytes of the worker process exceed this threshold, the internal cache will be trimmed, and the assemblies will be ejected, causing the appearance of the .delete files. I advise you work with the customer to increase the RAM memory available to their most impacted servers if possible, and also set a memory recycling based on private bytes on the app pool hosting the impacted application. We can set this recycling limitation to a higher value than the RAM so that we can ensure the threshold is high enough not to be reached by the worker process. To set the private bytes recycling on the application pool: Start the IIS Manager console on the impacted servers. Right click the impacted application pool and chose ‘Recycling’ from the context menu that is displayed. In the recycling properties window that is displayed, introduce a value for the ‘Private Memory Usage (KB)’ textbox. The value should be 1.2 * available RAM expressed in KB. This is a temporary workaround, and should be rolled back once the new version of the .Net Framework is released and installed. Install the .Net Framework 4.8 Preview You can try to install the preview version of the .Net Framework 4.8 which is available for download online now. However, this is a preview version and you may run into other issues which will not be supported until the Framework is released. You can also opt to install a private fix from Microsoft (reach out to me if you want this nand I will request it), which will change the malfunctioning assemblies from the .Net Framework 4.7.x to allow correct insertion of assemblies into the cache. However, this private fix is not signed, and will hence require us to disable assembly sign checking on the server which may expose the customer to other security risks. In project precompile options, check "Allowed precompiled site to be updatable" and "Do not merge" options. The bug only affects non-updatable precompiled binaries, so this avoids the bug, but startup times are obviously greatly affected. For me, this solution was simple and works fine until 4.8 rolls out for Azure web services. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/55272598', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/765303/']} | jdg_74472 |
stackexchange | llm_judgeable_groundtruth_similarity | 37869963 |
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 working on using a custom camera, and I recently upgraded to Xcode 8 beta along with Swift 3. I originally had this: var stillImageOutput: AVCaptureStillImageOutput? However, I am now getting the warning: 'AVCaptureStillImageOutput' was deprecated in iOS 10.0: Use AVCapturePhotoOutput instead As this is fairly new, I have not seen much information on this. Here is my current code: var captureSession: AVCaptureSession?var stillImageOutput: AVCaptureStillImageOutput?var previewLayer: AVCaptureVideoPreviewLayer?func clickPicture() { if let videoConnection = stillImageOutput?.connection(withMediaType: AVMediaTypeVideo) { videoConnection.videoOrientation = .portrait stillImageOutput?.captureStillImageAsynchronously(from: videoConnection, completionHandler: { (sampleBuffer, error) -> Void in if sampleBuffer != nil { let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer) let dataProvider = CGDataProvider(data: imageData!) let cgImageRef = CGImage(jpegDataProviderSource: dataProvider!, decode: nil, shouldInterpolate: true, intent: .defaultIntent) let image = UIImage(cgImage: cgImageRef!, scale: 1, orientation: .right) } }) }} I have tried to look at AVCapturePhotoCaptureDelegate , but I am not quite sure how to use it. Does anybody know how to use this? Thanks.
Now provide the response and nothing else.
| Updated to Swift 4 Hi it's really easy to use AVCapturePhotoOutput . You need the AVCapturePhotoCaptureDelegate which returns the CMSampleBuffer . You can get as well a preview image if you tell the AVCapturePhotoSettings the previewFormat class CameraCaptureOutput: NSObject, AVCapturePhotoCaptureDelegate { let cameraOutput = AVCapturePhotoOutput() func capturePhoto() { let settings = AVCapturePhotoSettings() let previewPixelType = settings.availablePreviewPhotoPixelFormatTypes.first! let previewFormat = [kCVPixelBufferPixelFormatTypeKey as String: previewPixelType, kCVPixelBufferWidthKey as String: 160, kCVPixelBufferHeightKey as String: 160] settings.previewPhotoFormat = previewFormat self.cameraOutput.capturePhoto(with: settings, delegate: self) }func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photoSampleBuffer: CMSampleBuffer?, previewPhoto previewPhotoSampleBuffer: CMSampleBuffer?, resolvedSettings: AVCaptureResolvedPhotoSettings, bracketSettings: AVCaptureBracketedStillImageSettings?, error: Error?) { if let error = error { print(error.localizedDescription) } if let sampleBuffer = photoSampleBuffer, let previewBuffer = previewPhotoSampleBuffer, let dataImage = AVCapturePhotoOutput.jpegPhotoDataRepresentation(forJPEGSampleBuffer: sampleBuffer, previewPhotoSampleBuffer: previewBuffer) { print("image: \(UIImage(data: dataImage)?.size)") // Your Image } } } For more information visit https://developer.apple.com/reference/AVFoundation/AVCapturePhotoOutput Note: You have to add the AVCapturePhotoOutput to the AVCaptureSession before taking the picture. So something like: session.addOutput(output) , and then: output.capturePhoto(with:settings, delegate:self) Thanks @BigHeadCreations | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/37869963', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5143847/']} | jdg_74473 |
stackexchange | llm_judgeable_groundtruth_similarity | 27221332 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script><link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" /><div class="form-group"> <a for="collapseOne" data-toggle="collapse" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne" class="btn btn-primary">+ addInfo </a> <textarea class="form-control collapse" id="collapseOne" rows="4"></textarea></div><div class="form-group"> <a for="collapseTwo" data-toggle="collapse" href="#collapseTwo" aria-expanded="true" aria-controls="collapseOne" class="btn btn-info">+ subtitle </a> <input type="text" class="form-control collapse" id="collapseTwo"></div> The problem is when clicking the addInfo tab, you could find a jump in expanding the text_area , namely, the animation is not smooth.
Now provide the response and nothing else.
| In case anybody else comes across this problem, as I just have, the answer is to wrap the content which you want to collapse inside a div and collapse the wrapper div rather than the content itself. <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script><link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" /><div class="form-group"> <a for="collapseOne" data-toggle="collapse" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne" class="btn btn-primary">+ addInfo</a> <div id="collapseOne" class="collapse"> <textarea class="form-control" rows="4"></textarea> </div></div><div class="form-group"> <a for="collapseTwo" data-toggle="collapse" href="#collapseTwo" aria-expanded="true" aria-controls="collapseOne" class="btn btn-info">+ subtitle</a> <input type="text" class="form-control collapse" id="collapseTwo"></div> | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/27221332', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1177952/']} | jdg_74474 |
stackexchange | llm_judgeable_groundtruth_similarity | 13753665 |
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 thought this was a simple google search, but apparently I'm wrong on that. I've seen that you should supply: Accept-Encoding: gzip;q=0,deflate;q=0 in the request headers. However, the article that suggested it also noted that proxies routinely ignore that header. Also, when I supplied it to nginx, it still compressed the response message body. http://forgetmenotes.blogspot.ca/2009/05/how-to-disable-gzip-compression-in.html So, how do I tell a web server to disable compression on the response message body?
Now provide the response and nothing else.
| Do you wish encoding to be disabled altogether? Then skip the Accept-Encoding header itself within http request headers. Do you wish only gzip compression to be absent in the http response? Then skip gzip from the values list in the http request header. Do you wish to prioritize different compression techniques that servers support? then use different values between 0 and 1 along-with q argument for each value in the Accept-Encoding http request header. (Currently you are using conflicting value and indicating by weight=0 that you don't know how you'll manage, but you want response to be encoded anyhow) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13753665', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/278976/']} | jdg_74475 |
stackexchange | llm_judgeable_groundtruth_similarity | 4345464 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $a<b\in\mathbb{R}$ and $f:[a,b]\to (0,\infty)$ be continuous. Show the inequality $$\left(\int_a^b f(x)\,dx\right)\left(\int_a^b \frac{1}{f(y)}\,dy\right)\geq (b-a)^2$$ As a hint is given to first prove that $\frac{f(x)}{f(y)}+\frac{f(y)}{f(x)}\geq 2$ . This is easy. I wonder if this "hint" is actually needed.I would have argued that $g:[a,b]^2\to (0,\infty)$ , $(x,y)\mapsto \frac{f(x)}{f(y)}$ is a continuous map on a compact set, hence takes it minimum $m$ . An easy calculation then shows $$\iint_{[a,b]^2} \frac{f(x)}{f(y)}d^2(x,y)\geq (b-a)^2$$ by estimating below with the minimum $m$ , and calculating the double integral. Every comment is helpful.Thanks in advance.
Now provide the response and nothing else.
| From the hint: apply $\displaystyle \int_{a}^b dx$ to both sides yields: $\dfrac{1}{f(y)}\displaystyle \int_{a}^bf(x)dx+f(y)\displaystyle \int_{a}^b \dfrac{1}{f(x)}dx =\displaystyle \int_{a}^b \left(\dfrac{f(x)}{f(y)}+\dfrac{f(y)}{f(x)}\right) dx \ge \displaystyle \int_{a}^b 2dx = 2(b-a)$ . Apply again $\displaystyle \int_{a}^b dy$ to both sides of this new inequality yields: $2\displaystyle \int_{a}^bf(x)dx\displaystyle \int_{a}^b \dfrac{1}{f(y)}dy \ge 2(b-a)^2$ . Upon canceling out the factor of $2$ both sides leads to the desire inequality. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4345464', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/439383/']} | jdg_74476 |
stackexchange | llm_judgeable_groundtruth_similarity | 2404565 |
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 been using GROUP BY for all types of aggregate queries over the years. Recently, I've been reverse-engineering some code that uses PARTITION BY to perform aggregations. In reading through all the documentation I can find about PARTITION BY , it sounds a lot like GROUP BY , maybe with a little extra functionality added in. Are they two versions of the same general functionality or are they something different entirely?
Now provide the response and nothing else.
| They're used in different places. GROUP BY modifies the entire query, like: select customerId, count(*) as orderCountfrom Ordersgroup by customerId But PARTITION BY just works on a window function , like ROW_NUMBER() : select row_number() over (partition by customerId order by orderId) as OrderNumberForThisCustomerfrom Orders GROUP BY normally reduces the number of rows returned by rollingthem up and calculating averages or sums for each row. PARTITION BY does not affect the number of rows returned, but itchanges how a window function's result is calculated. | {} | {'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/2404565', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/203479/']} | jdg_74477 |
stackexchange | llm_judgeable_groundtruth_similarity | 3267064 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I was asked to find the area between two curves: $y=x^2$ and $x=y^2$ . I used the interval $[0,1]$ , which I found by substituting $x$ in one of the equations. I came up with this: $2\displaystyle\int_0^1\sqrt{x}dx - \int_0^1x^2 dx = 1$ . However, the book says the answer is $\frac{1}{3}.$ What did I do wrong?
Now provide the response and nothing else.
| $\max(x^2, \sqrt{x}) = \sqrt{x}$ on the interval $[0,1]$ . Take $\int_{0}^{1} \sqrt{x} dx - \int_{0}^1 x^2 dx$ $$=\int_{0}^1 \sqrt{x} - x^2 dx$$ $\int x^{1/2} dx = x^{1/2+1} \frac{1}{\frac{1}{2}+1} = x^{3/2} \frac{2}{3}$ and $\int x^2 dx = x^{2+1} \frac{1}{3} = \frac{1}{3} x^3$ $$=\frac{2}{3} 1^{3/2} - \frac{1}{3} 1^3 - (\frac{2}{3} 0^{3/2} - \frac{1}{3} 0^3)$$ $$=\frac{2}{3}-\frac{1}{3} = \frac{1}{3}$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3267064', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/641014/']} | jdg_74478 |
stackexchange | llm_judgeable_groundtruth_similarity | 38136856 |
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 the following serializer: class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = get_user_model() fields = ( 'url', 'username', 'email', 'password', ) write_only_fields = ('password',) I also implemented the create and update methods.Now, if I try to create a user with the following data: { "username": "foo", "email": "[email protected]", "password": "foo2016"} I would get the following json response: { "url": "http://someurl.com/catalog/api/users/11/", "username": "foo", "email": "[email protected]"} What I would like to have is a JSON response that has an attribute indicating whether the operation is successful, as follows: { "success": true, "data": { "url": "http://someurl.com/foo/users/11/", "username": "foo", "email": "[email protected]" }} If an error occurred, the response would look like this: { "success": false, "data": { "username": [ "This field is required." ] }} and shouldn't be like this: { "username": [ "This field is required." ]} The reason I'm doing this is to improve the error handling on the front-end side.
Now provide the response and nothing else.
| Per the other comments the second Common Table Expression [CTE] is preceded by a comma not a WITH statement so WITH cte1 AS (SELECT...), cte2 AS (SELECT...)SELECT *FROM cte1 c1 INNER JOIN cte2 c2 ON ........ In terms of your actual query this syntax should work in PostgreSql, Oracle, and sql-server, well the later typically you will proceed WITH with a semicolon ( ;WTIH ), but that is because typically sql-server folks (myself included) don't end previous statements which need to be ended prior to a CTE being defined... Note however that you had a second syntax issue in regards to your WHERE statement. WHERE date IN table_2 is not valid because you never actually reference a value/column from table_2. I prefer INNER JOIN over IN or Exists so here is a syntax that should work with a JOIN : WITH table_1 AS (SELECT GENERATE_SERIES('2012-06-29', '2012-07-03', '1 day'::INTERVAL) AS date), table_2 AS (SELECT GENERATE_SERIES('2012-06-30', '2012-07-13', '1 day'::INTERVAL) AS date)SELECT * FROM table_1 t1 INNER JOIN table_2 t2 ON t1.date = t2.date; If you want to keep the way you had it which typically EXISTS would be better than IN but to to use IN you need an actual SELECT statement in your where. SELECT * FROM table_1 t1WHERE t1.date IN (SELECT date FROM table_2); IN is very problematic when date could potentially be NULL so if you don't want to use a JOIN then I would suggest EXISTS . AS follows: SELECT * FROM table_1 t1WHERE EXISTS (SELECT * FROM table_2 t2 WHERE t2.date = t1.date); | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/38136856', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3506447/']} | jdg_74479 |
stackexchange | llm_judgeable_groundtruth_similarity | 39214084 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
So I'm working on a Chrome extension to help me on my job. I need to autocomplete some fields but for some reason I cant pass the info from HTML to the .js file.I have a list for the input and a script to make you able to search among any part of the given words. For example, if you type 'la' it should suggest New Zealand, England and Ireland.Well, when I run the html to test it does not work. Could you give me some light on this? Thank you! HTML <!doctype html><html lang="en"><head></head><body> <input data-list="Brazil, United States, New Zealand, Canada, England, Ireland" data-multiple /> <script src="popup.js" async></script</body></html> .JS file new Autocomplete('input[data-multiple]', { filter: function(text, input) { return Autocomplete.FILTER_CONTAINS(text, input.match(/[^,]*$/)[0]); }, replace: function(text) { var before = this.input.value.match(/^.+,\s*|/)[0]; this.input.value = before + text + ", "; }});
Now provide the response and nothing else.
| The full power of RxJava is visible when you use it on Java 8, preferably with a library like Retrofit. It allows you to trivially chain operations together, with full control of error handling. For example, consider the following code given id : an int that specifies the order and apiClient: a Retrofit client for the order management microservice: apiClient.getOrder(id).subscribeOn(Schedulers.io()).flatMapIterable(Order::getLineItems).flatMap(lineItem -> apiClient.getProduct(lineItem.getProductId()) .subscribeOn(Schedulers.io()) .map(product -> product.getCurrentPrice() * lineItem.getCount()), 5).reduce((a,b)->a+b).retryWhen((e, count) -> count<2 && (e instanceof RetrofitError)).onErrorReturn(e -> -1).subscribe(System.out::println); This will asynchronously calculate the total price of an order, with the following properties: at most 5 requests against the API in flight at any one time (and you can tweak the IO scheduler to have a hard cap for all requests, not just for a single observable chain) up to 2 retries in case of network errors -1 in case of failure (an antipattern TBH, but that's an other discussion) Also, IMO the .subscribeOn(Schedulers.io()) after each network call should be implicit - you can do that by modifying how you create the Retrofit client. Not bad for 11+2 lines of code, even if it's more backend-ish than Android-ish. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39214084', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4987838/']} | jdg_74480 |
stackexchange | llm_judgeable_groundtruth_similarity | 1290189 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $f(x,y)$ be a function defined in some disk that is centered at $(x_0,y_0)$. Suppose that $L$ is some real number. Then in this case, what does it mean that:$$\lim_{(x,y)\to (x_0,y_0)} f(x,y)=L$$So basically I want the definition of limit in this case. I want it in a way that doesn't use non-mathematical words such as "approaches", "close", etc. Instead I want it to be in a mathematical context that is understandable to someone taking multivariable calculus for the first time with only the knowledge from multivariable calculus and calculus 1 and 2.
Now provide the response and nothing else.
| The definition of the limit is as follows: $\lim_{(x,y)\to (x_0,y_0)}f(x,y)=L\,$ if and only if for all $\epsilon>0$ there exists a $\delta >0$ such that $$|f(x,y)-L|<\epsilon$$ whenever $0<\sqrt{(x-x_0)^2+(y-y_0)^2}<\delta$. NOTE: Alternatively, $\lim_{(x,y)\to (x_0,y_0)}f(x,y)=L\,$ if and only if for all $\epsilon>0$ there exists a $\delta >0$ such that $$|f(x,y)-L|<\epsilon$$ whenever $0<|x-x_0|<\delta$ and $0<|y-y_0|<\delta$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1290189', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/241950/']} | jdg_74481 |
stackexchange | llm_judgeable_groundtruth_similarity | 11318933 |
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 listen to the event of volume change on Android, without just taking over the volume buttons? The only thing I've found that works is here , but it works only after the volume control has disappeared. Not all devices have volume buttons, and I need to capture the volume changes as soon as they occur, and not after the volume dialog is gone.
Now provide the response and nothing else.
| Better, you can register a ContentObserver as follows: getApplicationContext().getContentResolver().registerContentObserver(android.provider.Settings.System.CONTENT_URI, true, new ContentObserver(){...} ); Your ContentObserver might look like this: public class SettingsContentObserver extends ContentObserver { private AudioManager audioManager; public SettingsContentObserver(Context context, Handler handler) { super(handler); audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); } @Override public boolean deliverSelfNotifications() { return false; } @Override public void onChange(boolean selfChange) { int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC); Log.d(TAG, "Volume now " + currentVolume); }} When done: getApplicationContext().getContentResolver().unregisterContentObserver(mContentObserver); One caution, though - sometimes the notifications seem to be delayed if there are lots of button presses quickly. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11318933', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/878126/']} | jdg_74482 |
stackexchange | llm_judgeable_groundtruth_similarity | 6558129 |
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 (now defunct) page http://stream.twitter.com/1/statuses/sample.json used to return a continuous and endless stream of JSON data. I'd like to process it using jQuery (or JavaScript, but preferably jQuery) inside my own web page to be able to display visual effects based on the live feed of tweets. Since as far as I know the jQuery parseJSON function will only execute the callback function after all the data has been sent by the server, but this is actually a continuous stream of data. How can I process the data "as it happens" but still keep the connection running?
Now provide the response and nothing else.
| This sort of thing is best done using WebSockets now, which according to CanIUse.Com is available in all major browsers except Opera Mini (see that link for more details about older or all browsers, and click the Resources tab to see even more links). As an overview, websockets are supported in IE 10+, Edge 12+, Firefox 11+ (38+ if within a WebWorker context), Chrome 16+, Opera 12.1+, Safari 7+, Android 4.4+, Opera Mobile 12.1+. Note: you will likely want to learn about Service Workers and Web Workers as well, though those have different use cases and different abilities. It looks like this: var connection = new WebSocket( 'ws://html5rocks.websocket.org/echo', ['soap', 'xmpp']); Attaching some event handlers immediately to the connection allows you to know when the connection is opened, when you've received incoming messages, or if an error has occurred. Sending messages becomes as easy as this: connection.send('your message');connection.send(binaryData); See Introducing WebSockets: Bringing Sockets to the Web for a full explanation on how to do this. ASP.Net developers: if for some reason you need to support older browsers and don't want to figure out for yourself how to deal with those that don't support WebSockets, consider using a library such as SignalR . The Old EventSource API Answer For Older Browsers Most browsers now implement the EventSource API , which makes long polling really easy, as long as the stream can be delivered with content-type text/event-stream . Older browsers or those developers who for any reason can't engineer the stream to have that content-type can use some helper script to do the same thing. Here's an example: var jsonStream = new EventSource('https://example.com/yourstreamingservice')jsonStream.onmessage = function (e) { var message = JSON.parse(e.data); // handle message}; This is basically a full-fledged version of the exact thing that I outline below. The Even Older Service Streaming Answer For REALLY OLD Browsers What you want is called long polling. You'll need a custom AJAX onreadystatechange handling function. Instead of waiting until the entire stream has completed (since it never will), you'll need to examine the contents periodically. Note that you'll need to do some heavy lifting for this to work in IE 9 and lower, using an iframe . Roughly: Respond to each onreadystatechange event and examine the stream you've been given up to the current character to see if there is enough data to consume one or more discrete events. You'll need to parse the stream yourself with javascript string-handling functions. A combination of split, indexOf, regular expressions, looping, and so on can be used to accomplish this task. If there's not enough content yet, then exit and wait for the next event. I am pretty sure that each time the onreadystatechange handler fires, the responseText will be all the data that has been received so far. Define a persistent variable that will hold the position of the first character that hasn't been properly processed yet. Once there is enough content for one or more discrete events to appear in the stream, take them out one at a time and pass them to your JSON parser to actually render the text as objects. Use them normally. Check out this HTTP Streaming gist for one resource, or Streaming as an alternative to polling the server at SoftwareAs. If you must support IE 9 or older, then you'll need to use the iframe method for that. Here is a quote from the book Ajax Design Patterns: Creating Web 2.0 Sites with Programming and Usability Patterns : In summary, Service Streaming makes the HTTP Streaming approach more flexible, because you can stream arbitrary content rather than Javascript commands, and because you can control the connection's lifecycle. However, it combines two technologies that aren't consistent across browsers, with predictable portability issues. Experiments suggest that the Page Streaming technique does work on both IE [9 and older] and Firefox, but Service Streaming only works on Firefox, whether XMLHTTPRequest or IFrame is used. In the first case IE [9 and older] suppresses the response until its complete, with the IFrame it works if a workaround is used: The IE [9 and older] accepts a message from the server after the first 256 bytes so the only thing to do is to send 256 dummy Bytes before sending the messages. After this all messages will arrive as expected. So a full Service Streaming is possible in IE [9 and older], too! Mind you that it is from 2006, so it is definitely out of date, but if you have to support older browsers, it's still relevant. Security Issues Normal AJAX cannot go cross-domain, meaning (now that I pay attention to the fact that you want to stream from twitter) that you won't be able to do what you're asking. This can be worked around with JSONP, but JSONP by nature can't be service streamed and moreover isn't offered by twitter anyway. There is also Cross-Origin Resource Sharing (CORS) but twitter's not going to set that up for you--that's the kind of thing they'd only do for domains affiliated with them. And CORS requires a modern browser. Your only option is thus to create a proxy service on your web server that performs the requests to twitter for you and then hands out the data. This can only be done from the same domain as the main page was served from. Doing this would also allow you to create a version that will work for IE using the iframe technique. If you don't care about old IE versions, you can implement CORS yourself to defeat the domain restriction, if you know the domain that will be making the requests. If you have full control of the client software (like if this is for a corporate intranet) there is another option: hosting the web browser inside of a compiled locally-executed application's user form. I have only done this using C# but I imagine it's possible from other languages. When you use the right browser object, because it's hosted inside a C# application, the C# application can defeat the cross-domain security restrictions, reading and writing all page content no matter what domain it comes from. I doubt your situation is this one but I wanted to put the option here for others who might appreciate it. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6558129', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/151377/']} | jdg_74483 |
stackexchange | llm_judgeable_groundtruth_similarity | 78813 |
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:
Recently I was talking to a friend about solid state rectifiers in tube amps. He told me that solid state rectifiers induces noise in the power supply, because the breakdown current of the silicon diodes, something like switching spikes. Is this noise a really concern? How could I reduce, or even eliminate that problem?
Now provide the response and nothing else.
| Diodes can be noisy when used as rectifiers due to reverse recovery induced spikes. Certain types of diodes perform better (schottky and so-called 'soft-recovery' diodes) or are essentially immune (silicon carbide) to this effect. A well-designed circuit can address reverse recovery via the use of appropriate diodes (i.e schottkys and/or silicon carbide where appropriate) and by snubber networks, which absorb and dissipate the spike energy. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/78813', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/-1/']} | jdg_74484 |
stackexchange | llm_judgeable_groundtruth_similarity | 268766 |
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:
So, I thought I had a good understanding of this, but just ran a test (in response to a conversation where I disagreed with someone) and found that my understanding is flawed... In as much detail as possible what exactly happens when I execute a file in my shell? What I mean is, if I type: ./somefile some arguments into my shell and press return (and somefile exists in the cwd, and I have read+execute permissions on somefile ) then what happens under the hood? I thought the answer was: The shell make a syscall to exec , passing the path to somefile The kernel examines somefile and looks at the magic number of the file to determine if it is a format the processor can handle If the magic number indicates that the file is in a format the processor can execute, then a new process is created (with an entry in the process table) somefile is read/mapped to memory. A stack is created and execution jumps to the entry point of the code of somefile , with ARGV initialized to an array of the parameters (a char** , ["some","arguments"] ) If the magic number is a shebang then exec() spawns a new process as above, but the executable used is the interpreter referenced by the shebang (e.g. /bin/bash or /bin/perl ) and somefile is passed to STDIN If the file doesn't have a valid magic number, then an error like "invalid file (bad magic number): Exec format error" occurs However someone told me that if the file is plain text, then the shell tries to execute the commands (as if I had typed bash somefile ). I didn't believe this, but I just tried it, and it was correct. So I clearly have some misconceptions about what actually happens here, and would like to understand the mechanics. What exactly happens when I execute a file in my shell? (in as much detail is reasonable...)
Now provide the response and nothing else.
| The definitive answer to "how programs get run" on Linux is the pair of articles on LWN.net titled, surprisingly enough, How programs get run and How programs get run: ELF binaries . The first article addresses scripts briefly. (Strictly speaking the definitive answer is in the source code, but these articles are easier to read and provide links to the source code.) A little experimentation show that you pretty much got it right, and that the execution of a file containing a simple list of commands, without a shebang, needs to be handled by the shell. The execve(2) manpage contains source code for a test program, execve; we'll use that to see what happens without a shell. First, write a testscript, testscr1 , containing #!/bin/shpstree and another one, testscr2 , containing only pstree Make them both executable, and verify that they both run from a shell: chmod u+x testscr[12]./testscr1 | less./testscr2 | less Now try again, using execve (assuming you built it in the current directory): ./execve ./testscr1./execve ./testscr2 testscr1 still runs, but testscr2 produces execve: Exec format error This shows that the shell handles testscr2 differently. It doesn't process the script itself though, it still uses /bin/sh to do that; this can be verified by piping testscr2 to less : ./testscr2 | less -ppstree On my system, I get |-gnome-terminal--+-4*[zsh] | |-zsh-+-less | | `-sh---pstree As you can see, there's the shell I was using, zsh , which started less , and a second shell, plain sh ( dash on my system), to run the script, which ran pstree . In zsh this is handled by zexecve in Src/exec.c : the shell uses execve(2) to try to run the command, and if that fails, it reads the file to see if it has a shebang, processing it accordingly (which the kernel will also have done), and if that fails it tries to run the file with sh , as long as it didn't read any zero byte from the file: for (t0 = 0; t0 != ct; t0++) if (!execvebuf[t0]) break; if (t0 == ct) { argv[-1] = "sh"; winch_unblock(); execve("/bin/sh", argv - 1, newenvp); } bash has the same behaviour, implemented in execute_cmd.c with a helpful comment (as pointed out by taliezin ): Execute a simple command that is hopefully defined in a disk file somewhere. fork () connect pipes look up the command do redirections execve () If the execve failed, see if the file has executable mode set. If so, and it isn't a directory, then execute its contents as a shell script. POSIX defines a set of functions, known as the exec(3) functions , which wrap execve(2) and provide this functionality too; see muru 's answer for details. On Linux at least these functions are implemented by the C library, not by the kernel. | {} | {'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/268766', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/1974/']} | jdg_74485 |
stackexchange | llm_judgeable_groundtruth_similarity | 2626163 |
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 read the number of line in a binary file using readObject, but I get IOException EOF. Am I doing this the right way? FileInputStream istream = new FileInputStream(fileName); ObjectInputStream ois = new ObjectInputStream(istream); /** calculate number of items **/ int line_count = 0; while( (String)ois.readObject() != null){ line_count++; }
Now provide the response and nothing else.
| readObject() doesn't return null at EOF. You could catch the EOFException and interpret it as EOF, but this would fail to detect distinguish a normal EOF from a file that has been truncated. A better approach would be to use some meta-data. That is, rather than asking the ObjectInput how many objects are in the stream, you should store the count somewhere. For example, you could create a meta-data class that records the count and other meta-data and store an instance as the first object in each file. Or you could create a special EOF marker class and store an instance as the last object in each file. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2626163', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/69514/']} | jdg_74486 |
stackexchange | llm_judgeable_groundtruth_similarity | 30608 |
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 a list of $\{x,y,z\}$ pairs representing points in $R^3$. For every unique value of $z$ there are many $\{x,y\}$ pairs defining a polygon/contour in that particular $z$-plane. My dataset looks like this: Take[ptv, 3](*{{61.52, -217.26, -80}, {63.48, -217.64, -80}, {65.43, -217.64, -80}}*) These are coordinates of points residing on the $z=-80$ plane. There are other pairs for $z=-75$, $z=-70$, etc. Therefore ptv is of the form: ptv : {{$x_1,y_1,-80$}, {$x_2,y_2,-80$}, ..., {$x_k,y_k,-80$}, ..., {$x_1,y_1,-75$}, ..., {$x_m,y_m,-75$}, ...} My goal is to create a 3D surface where: (1). the points in every $z$-plane are connected into a polygon/contour and(2). the points in every $z$-plane are connected with their neighbors in the immediately above and below plane. I have achieved (1) , via: Graphics3D[{Line[ptv], Point /@ ptv}] The result looks like this: If I, instead, use: ListSurfacePlot3D[ptv, AxesLabel -> {"x","y","z"}] Then I get some ugly artifacts (edges at the boundaries of the volume) as shown here: Whereas, I was expecting a more "smooth" surface without any "openings". Any hints on: Whether ListSurfacePlot3D[] is the proper function to use (i.e. in the documentation it is mentioned that ListSurfacePlot3D[] may "fold" over; perhaps this is why I'm experiencing these ruffles?) or What other alternatives are there to consider ? EDIT 1 :Minimally working example: ClearAll["Global`*"];ptv = Import["http://leaf.dragonflybsd.org/~beket/ptvgeom/ag1", "Table"]ListSurfacePlot3D[ptv, AxesLabel -> {"x", "y", "z"}] EDIT 2 :I excluded random $z$-planes to explore the dependence of the produced surfaces on my dataset. There is considerable visual variability in the output, including some very irregular images. Here is the code: (* Identify the values of z-planes *)planes = ({x, y, z} = #; z)& /@ ptv // Union;(* Generate some random sequences with z-planes-to-be-excluded *)excludedPlanes = Table[ RandomSample[planes, RandomInteger@{1, 4}], {k, 1, 20}]] // Union // Reverse;(* Filter data by discarding points residing on excluded planes *)FilterData[p_] := Select[ptv, Function[v, And@@(Unequal[v, #]& /@ p)][Last[#]]&](* Generate the 3D surfaces *)ListSurfacePlot3D[#, AxesLabel->{"x","y","z"}]& /@ FilterData/@ excludedPlanes And here is a screenshot: Problem Although Dr.belisarius has given a solution, however, which lost the geometry continuty . In addition, the contour didn't pass the interpolating points. f = BSplineFunction[Most /@ t[[1]]]Show[{ListPlot[Most /@ gb[[1]], PlotTheme -> "Classic"], ParametricPlot[f[t], {t, 0, 1}, PlotTheme -> "Classic"]}]
Now provide the response and nothing else.
| The natural way to go is BSplineFunction[] . The problem is that it needs a rectangular array of data as input and you collected a different number of points for each z plane. So what we will do is to get an interpolating function for each z == const plane and generate an equal number of points at each plane. To be somewhat more clever, we could generate evenly spaced points along each curve , but that small modification is left as an exercise. Please note that the Spline Degree determines if the curve pass along your points exactly, or is just a smoothed approximation. ClearAll["Global`*"];ptv = Import["http://leaf.dragonflybsd.org/~beket/ptvgeom/ag1", "Table"];Needs["DifferentialEquations`InterpolatingFunctionAnatomy`"]; gb = GatherBy[ptv, Last];f[k_InterpolatingFunction, p_] := k[p (Length @@ InterpolatingFunctionCoordinates[k] - 1) + 1]t = Append[#, First@#] & /@ Transpose@ Table[{f[Interpolation[#[[All, 1]]], p], f[Interpolation[#[[All, 2]]], p], #[[1, 3]]}& /@ gb, {p, 0, 1, 0.005}];s = BSplineFunction[t];ParametricPlot3D[s[u, v], {u, 0, 1}, {v, 0, 1}, PlotStyle -> {Orange, Specularity[White, 10]}, Axes -> None, Mesh -> None] | {} | {'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/30608', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/9083/']} | jdg_74487 |
stackexchange | llm_judgeable_groundtruth_similarity | 19539 |
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 was at uni a few days ago when I attempted to cut and paste a 500Mb file (a 3gp video recording) into my H drive on one of the uni network's Linux (Debian KDE 3.5) computers. I did not see any error messages indicating the cut-and-paste job had failed, but when I looked at the resulting pasted file, it appears now as a 60Mb file (that's a 440Mb discrepancy!). My file was somehow shrunk! Did the file get broken up in the process of pasting it and this is the fragment of an incompletely copied file? I suspect what happened was the file transfer was interrupted due to H drive size-allocation limitations imposed on users by administrators. But you'd think Linux would anticipate that the file was bigger than would be possible to move to the intended destination and abort the transfer before it begun, not wait till it reached some forbidden limit then cancel discretely without notifying me. Also in the event of an interrupted file transfer, one normally expects the original file to be remain intact (i.e. not deleted) the original USB drive? The file appears in the destination, but is now much smaller and is non-functional. The original file in the source location on the external drive has disappeared, suggesting the job was completed successfully. This resizing is rather bizarre and now I don't seem to have access to the original file. After cutting and pasting the original may have been removed from it's source location. The computer has mishandled this task, apparently causing me to lose my file, and I would like you to help me to retrieve my file. I have tried recovering the file on my phone's SD card using PhotoRec and Sleuthkit forensic tool. No luck. Deleted sections of the disk may have been overwritten by new data. So zero progress on the source end. Any way to recover on the destination end (i.e. my uni network)? peter@peter-deb:/media/E0FD-1813$ cd DCIM/peter@peter-deb:/media/E0FD-1813/DCIM$ cd ..peter@peter-deb:/media/E0FD-1813$ cd LOST.DIR/peter@peter-deb:/media/E0FD-1813/LOST.DIR$ lspeter@peter-deb:/media/E0FD-1813/LOST.DIR$ ls -a. ..peter@peter-deb:/media/E0FD-1813/LOST.DIR$
Now provide the response and nothing else.
| First, never move a file across the network, only copy. You can always delete the original after the copy has been successfully completed. Secondly, your local system might not even be aware that a filesystem quota exists on remote storage - don't assume that it's even possible to guess ahead of time whether a copy operation would fail due to a remote quota. As far as the "sending" process is concerned, all bytes were sent to and received by the remote end, and you wanted to move the file so now the original can be deleted - poof file gone. "Any way to recover on the destination end?" - not a chance. OK, maybe a small one. Check with the network admin to see if just maybe the system actually received the full file but only reports back to you the size within your quota. Don't hold your breath. And I apologize if I'm sounding a bit harsh, but it seems like some new habits are in order. :-) | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/19539', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/7826/']} | jdg_74488 |
stackexchange | llm_judgeable_groundtruth_similarity | 40999025 |
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 C you can scope a variable to a switch case, like this . With javascript I get unexpected token using the following: const i = 1switch (i) { // variables scoped to switch var s var x = 2342 case 0: s = 1 + x break case 1: s = 'b' break} Is there another way to do this or should I just declare my variables outside the switch? EDIT: This is a workaround I considered but it didn't end up working. The reason being that each case has its own scope. const i = 1switch (i) { case i: // variables scoped to switch var s var x = 2342 case 0: s = 1 + x break case 1: s = 'b' break}
Now provide the response and nothing else.
| some alternative: /* curly braces inside the case */const i = 1switch (i) { case 0: { let x = 2342; let s = 1 + x; console.log(x+' & '+s+' from inside'); } break; case 1: { let x = 2342; let s = 'b'; console.log(x+' & '+s+' from inside'); /* 2342 & b from inside */ } break;}console.log(x+' & '+s+' from outside'); /* Uncaught ReferenceError */ or /* curly braces outside the switch */const i = 1{ let x = 2342; let s; switch (i) { case 0: s = 1 + x; break; case 1: s = 'b'; break; } console.log(x+' & '+s+' from inside'); /* 2342 & b from inside */}console.log(x+' & '+s+' from outside'); /* Uncaught ReferenceError */ | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/40999025', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/773263/']} | jdg_74489 |
stackexchange | llm_judgeable_groundtruth_similarity | 1907923 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Calculate E|Y| where Y is the standard normal. (Hints: (1) Calculate the integrals for positive and negative values of Y separately. (2) The answer must be bigger than 0.) Not sure how to approach this since no number were given. What am I supposed to be taking the integral of? I know that $E(X) = \int_0^1 x_iP(X=x_i)$ but I'm not too entirely sure how this would help me finding out the expectation of the absolute value? Is it just $E(X) = \int_0^1 |x_i|P(X=x_i)$ ?(I'm assuming not since the hint told me to integrate).
Now provide the response and nothing else.
| \begin{align*}E[|Y|] &= \int_{-\infty}^\infty |y| \dfrac{1}{\sqrt{2\pi}} e^{-y^2/2} \; dy \\&= \int_{-\infty}^0 -y \dfrac{1}{\sqrt{2\pi}} e^{-y^2/2} \; dy + \int_0^\infty y \dfrac{1}{\sqrt{2\pi}} e^{-y^2/2} \; dy \\&=\dots\\&= \sqrt{2/\pi}\end{align*} and others have given the general form of $E[g(Y)]$, which is how I got this. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1907923', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/358184/']} | jdg_74490 |
stackexchange | llm_judgeable_groundtruth_similarity | 6717056 |
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 problem regarding with add an image URL within a database.I'm using fileupload method within formview in ASP.Net.And I have a table called duyurularwhich can be record a image URL.BTW,I'm using SQL Server Database.My question is;I'm doing the process update,delete and to make an announcement in the FormView.I can upload those images within folder called "img" with FileUpload.However,I want to record it within database as well.when to add within database another those infos,there are no the image URL.Finally,I can't add the image URL within database. Here is my code; public partial class panel_yoneticipaneli : System.Web.UI.Page{FileUpload dosya, dosya1;//TextBox t1, t2, t3;//Button btn;SqlConnection con;static string str = "Data Source=SERT;Initial Catalog=Mmakina;Integrated Security=True";string yol = "";protected void Page_Load(object sender, EventArgs e){ dosya = (FileUpload)FormView2.FindControl("FileUpload1"); dosya1 = (FileUpload)FormView2.FindControl("FileUpload2"); // btn = (Button)FormView2.FindControl("ResimKaydetButonu"); //t1 = (TextBox)FormView2.FindControl("DuyuruBaslikTextBox"); //t2 = (TextBox)FormView2.FindControl("DuyuruIcerikTextBox"); //t3 = (TextBox)FormView2.FindControl("DuyuruTarihiTextBox"); Label1.Visible = false; if (Session["KullaniciID"]!=null) { con = new SqlConnection(str); SqlCommand sorgu = new SqlCommand("SELECT * FROM Kullanici WHERE KullaniciAdi=@KullaniciAdi", con); sorgu.Parameters.Add("@KullaniciAdi", SqlDbType.VarChar).Value = Session["KullaniciAdi"]; con.Open(); SqlDataReader oku = sorgu.ExecuteReader(CommandBehavior.CloseConnection); Label1.Visible = true; while (oku.Read()) { Label1.Text = oku["KullaniciAdi"].ToString(); } } else { Response.Redirect("error.aspx"); }}protected void Button1_Click(object sender, EventArgs e){ FormsAuthentication.SignOut(); Roles.DeleteCookie(); Session.Clear(); Response.Redirect("giris.aspx");}protected void btn_Click(object sender,EventArgs e) { try { if (dosya.HasFile) { dosya.SaveAs(Server.MapPath("~/img/") + dosya.FileName); System.Drawing.Image resim = System.Drawing.Image.FromFile(Server.MapPath("~/img/") + dosya.FileName); yol = "img/" + dosya.FileName; resim.Dispose(); DbUpload(); } } catch (Exception ex) { }}public void DbUpload() { try { SqlConnection sc = new SqlConnection("Data Source=SERT;Initial Catalog=Mmakina;Integrated Security=True"); SqlCommand scom = new SqlCommand("insert into Duyuru(DuyuruResmi) values(@DuyuruResmi)", sc); scom.Parameters.AddWithValue("@DuyuruResmi", dosya.FileName); scom.ExecuteNonQuery(); sc.Close(); }catch(Exception p){ p.Message.ToString(); }} protected void UpdateButton_Click(object sender, EventArgs e){try { if (dosya.HasFile) { dosya.SaveAs(Server.MapPath("~/img/") + dosya.FileName); yol = "img/" + dosya.FileName; Response.Write("Fileupload çalışıyor..."); DbUpload(); } } catch (Exception ex) { } } thanks in advance for all comments you can share.
Now provide the response and nothing else.
| There is no way to do this other than configuring the following registry settings: HKLM\Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION or if it's a 32 bit app on 64 bit Windows: HKLM\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer\MAIN\FeatureControl\FEATURE_BROWSER_EMULATION` These settings aren't surfaced in the WebBrowser control. For more information please see: What IE compatibility mode does the webbrowser control use? In case the link dies: You create a DWORD value matching the name of your executable and set this value to one of: 7000: Pages containing standards-based <!DOCTYPE> directives are displayed in IE7 mode. 8000: Pages containing standards-based <!DOCTYPE> directives are displayed in IE8 mode 8888: Pages are always displayed in IE8 mode, regardless of the <!DOCTYPE> directive. (This bypasses the exceptions listed earlier.) 9000: Use IE9 settings! 9999: Force IE9 For example: From my own experiments with IE9: 9000 - inherits the compatibility mode set in IE9's global compatibility mode setting. i.e.: 9999 - forces IE9 out of compatibility mode in the host application regardless of the globally configured compatibility mode setting Your application would probably need to detect which underlying IE version is available to determine which value to use: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Version or if it's a 32 bit app on 64 bit Windows: HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer\Version There's also this older article from when IE8 came out which is worth a look: More IE8 Extensibility Improvements You can also configure these settings on a per user basis under: HKCU\Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6717056', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/769829/']} | jdg_74491 |
stackexchange | llm_judgeable_groundtruth_similarity | 6754935 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How do I use javascript or jQuery to close an iframe within iframe itself? I've tried <a href="javascript:self.close()"> but it didn't work.
Now provide the response and nothing else.
| "Closing" the current iFrame is not possible but you can tell the parent to manipulate the dom and make it invisible. In IFrame: parent.closeIFrame(); In parent: function closeIFrame(){ $('#youriframeid').remove();} | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6754935', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/248430/']} | jdg_74492 |
stackexchange | llm_judgeable_groundtruth_similarity | 3161445 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
My application uses Spring auto-wiring to configure the beans. I have just tried adding @Transactional and the expected proxies do not seem to be called. I want the PersonalController to call UpdatePublicMapService with the UpdatePublicMapService wrapped by the transaction proxy. What I see is that the PersonalController is instantiated twice. The first time it gets the proxy but the second time it gets the un-proxied target. What am I doing wrong? Many thanks in advance for your help. web.xml ...<context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext.xml, /WEB-INF/applicationContext-security.xml</param-value> </context-param>... applicationContext.xml ... <tx:annotation-driven transaction-manager="txManager"/> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> ... applicationContext-security.xml ... <context:component-scan base-package="com.th"/> <context:component-scan base-package="org.springframework.security.core.userdetails"/> ... PersonalController @Controller@RequestMapping("/personal")public class PersonalController { @Autowired public void setUpdatePublicMapService(UpdatePublicMapService updatePublicMapService) { this.updatePublicMapService = updatePublicMapService; }} UpdatePublicMapService @Service@Transactionalpublic class UpdatePublicMapService { ...} Log snippet 13:14:40,268 DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Creating shared instance of singleton bean 'personalController'13:14:40,268 DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Creating instance of bean 'personalController'...13:14:40,293 DEBUG [org.springframework.beans.factory.annotation.InjectionMetadata] - Found injected element on class [com.th.rest.personal.trailsegment.PersonalController]: AutowiredMethodElement for public void com.th.rest.personal.trailsegment.PersonalController.setUpdatePublicMapService(com.th.service.UpdatePublicMapService)13:14:40,325 DEBUG [org.springframework.beans.factory.annotation.InjectionMetadata] - Processing injected method of bean 'personalController': AutowiredMethodElement for public void com.th.rest.personal.trailsegment.PersonalController.setUpdatePublicMapService(com.th.service.UpdatePublicMapService)13:14:40,326 DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Creating shared instance of singleton bean 'updatePublicMapService'13:14:40,326 DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Creating instance of bean 'updatePublicMapService'13:14:40,380 DEBUG [org.springframework.beans.factory.annotation.InjectionMetadata] - Found injected element on class [com.th.service.UpdatePublicMapService]: AutowiredMethodElement for public void com.th.service.UpdatePublicMapService.setPersonalRouteDataGateway(com.th.data.personal.PersonalRouteDataGateway)...13:14:40,420 DEBUG [org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor] - Autowiring by type from bean name 'updatePublicMapService' to bean named 'publicTrailJunctionDataGatewayImpl'13:14:40,420 DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Returning cached instance of singleton bean 'org.springframework.transaction.config.internalTransactionAdvisor'13:14:40,430 DEBUG [org.springframework.transaction.annotation.AnnotationTransactionAttributeSource] - Adding transactional method [updateToPublicMap] with attribute [PROPAGATION_REQUIRED,ISOLATION_DEFAULT]13:14:40,459 DEBUG [org.springframework.aop.framework.autoproxy.InfrastructureAdvisorAutoProxyCreator] - Creating implicit proxy for bean 'updatePublicMapService' with 0 common interceptors and 1 specific interceptors13:14:40,500 DEBUG [org.springframework.aop.framework.Cglib2AopProxy] - Creating CGLIB2 proxy: target source is SingletonTargetSource for target object [com.th.service.UpdatePublicMapService@6abe6abe]13:14:40,849 DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Returning cached instance of singleton bean 'org.springframework.transaction.interceptor.TransactionInterceptor#0'13:14:40,877 DEBUG [org.springframework.aop.framework.Cglib2AopProxy] - Unable to apply any optimisations to advised method: public void com.th.service.UpdatePublicMapService.updateToPublicMap(long)13:14:40,878 DEBUG [org.springframework.aop.framework.Cglib2AopProxy] - Unable to apply any optimisations to advised method: java.util.Map com.th.service.UpdatePublicMapService.copySegments(com.th.data.personal.PersonalRoute,java.util.Map)13:14:40,878 DEBUG [org.springframework.aop.framework.Cglib2AopProxy] - Unable to apply any optimisations to advised method: java.util.Map com.th.service.UpdatePublicMapService.makePrivateTrailsPublic(com.th.data.personal.PersonalRoute)13:14:40,878 DEBUG [org.springframework.transaction.annotation.AnnotationTransactionAttributeSource] - Adding transactional method [copyTrailJunctions] with attribute [PROPAGATION_REQUIRED,ISOLATION_DEFAULT]13:14:40,879 DEBUG [org.springframework.aop.framework.Cglib2AopProxy] - Unable to apply any optimisations to advised method: public void com.th.service.UpdatePublicMapService.copyTrailJunctions(com.th.data.personal.PersonalRoute)13:14:40,880 DEBUG [org.springframework.transaction.annotation.AnnotationTransactionAttributeSource] - Adding transactional method [junctionHasSegmentToUpdatePublicMap] with attribute [PROPAGATION_REQUIRED,ISOLATION_DEFAULT]13:14:40,880 DEBUG [org.springframework.aop.framework.Cglib2AopProxy] - Unable to apply any optimisations to advised method: public boolean com.th.service.UpdatePublicMapService.junctionHasSegmentToUpdatePublicMap(com.th.data.personal.PersonalTrailJunction,java.util.List)13:14:40,881 DEBUG [org.springframework.transaction.annotation.AnnotationTransactionAttributeSource] - Adding transactional method [linkPersonalTrailSegmentsAndJunctions] with attribute [PROPAGATION_REQUIRED,ISOLATION_DEFAULT]13:14:40,881 DEBUG [org.springframework.aop.framework.Cglib2AopProxy] - Unable to apply any optimisations to advised method: public void com.th.service.UpdatePublicMapService.linkPersonalTrailSegmentsAndJunctions(com.th.data.personal.PersonalRoute,java.util.Map)13:14:40,881 DEBUG [org.springframework.transaction.annotation.AnnotationTransactionAttributeSource] - Adding transactional method [createTrailJunction] with attribute [PROPAGATION_REQUIRED,ISOLATION_DEFAULT]13:14:40,882 DEBUG [org.springframework.aop.framework.Cglib2AopProxy] - Unable to apply any optimisations to advised method: public com.th.service.SplitResult com.th.service.UpdatePublicMapService.createTrailJunction(java.lang.String,long)13:14:40,882 DEBUG [org.springframework.transaction.annotation.AnnotationTransactionAttributeSource] - Adding transactional method [copyPersonalPublicTrailSegments] with attribute [PROPAGATION_REQUIRED,ISOLATION_DEFAULT]13:14:40,882 DEBUG [org.springframework.aop.framework.Cglib2AopProxy] - Unable to apply any optimisations to advised method: public void com.th.service.UpdatePublicMapService.copyPersonalPublicTrailSegments(java.util.Collection,java.util.List)13:14:40,883 DEBUG [org.springframework.transaction.annotation.AnnotationTransactionAttributeSource] - Adding transactional method [deleteReplacedPublicTrailSegments] with attribute [PROPAGATION_REQUIRED,ISOLATION_DEFAULT]13:14:40,883 DEBUG [org.springframework.aop.framework.Cglib2AopProxy] - Unable to apply any optimisations to advised method: public void com.th.service.UpdatePublicMapService.deleteReplacedPublicTrailSegments(java.util.Collection)13:14:40,883 DEBUG [org.springframework.transaction.annotation.AnnotationTransactionAttributeSource] - Adding transactional method [setPersonalRouteDataGateway] with attribute [PROPAGATION_REQUIRED,ISOLATION_DEFAULT]13:14:40,885 DEBUG [org.springframework.aop.framework.Cglib2AopProxy] - Unable to apply any optimisations to advised method: public void com.th.service.UpdatePublicMapService.setPersonalRouteDataGateway(com.th.data.personal.PersonalRouteDataGateway)13:14:40,886 DEBUG [org.springframework.transaction.annotation.AnnotationTransactionAttributeSource] - Adding transactional method [setPersonalTrailSegmentDataGateway] with attribute [PROPAGATION_REQUIRED,ISOLATION_DEFAULT]13:14:40,886 DEBUG [org.springframework.aop.framework.Cglib2AopProxy] - Unable to apply any optimisations to advised method: public void com.th.service.UpdatePublicMapService.setPersonalTrailSegmentDataGateway(com.th.data.personal.PersonalTrailSegmentDataGateway)13:14:40,887 DEBUG [org.springframework.transaction.annotation.AnnotationTransactionAttributeSource] - Adding transactional method [setPersonalTrailDataGateway] with attribute [PROPAGATION_REQUIRED,ISOLATION_DEFAULT]13:14:40,887 DEBUG [org.springframework.aop.framework.Cglib2AopProxy] - Unable to apply any optimisations to advised method: public void com.th.service.UpdatePublicMapService.setPersonalTrailDataGateway(com.th.data.personal.PersonalTrailDataGateway)13:14:40,888 DEBUG [org.springframework.transaction.annotation.AnnotationTransactionAttributeSource] - Adding transactional method [setPersonalTrailJunctionDataGateway] with attribute [PROPAGATION_REQUIRED,ISOLATION_DEFAULT]13:14:40,888 DEBUG [org.springframework.aop.framework.Cglib2AopProxy] - Unable to apply any optimisations to advised method: public void com.th.service.UpdatePublicMapService.setPersonalTrailJunctionDataGateway(com.th.data.personal.PersonalTrailJunctionDataGateway)13:14:40,889 DEBUG [org.springframework.transaction.annotation.AnnotationTransactionAttributeSource] - Adding transactional method [setPublicTrailDataGateway] with attribute [PROPAGATION_REQUIRED,ISOLATION_DEFAULT]13:14:40,889 DEBUG [org.springframework.aop.framework.Cglib2AopProxy] - Unable to apply any optimisations to advised method: public void com.th.service.UpdatePublicMapService.setPublicTrailDataGateway(com.th.data.pub.PublicTrailDataGateway)13:14:40,890 DEBUG [org.springframework.transaction.annotation.AnnotationTransactionAttributeSource] - Adding transactional method [setPublicTrailSegmentDataGateway] with attribute [PROPAGATION_REQUIRED,ISOLATION_DEFAULT]13:14:40,890 DEBUG [org.springframework.aop.framework.Cglib2AopProxy] - Unable to apply any optimisations to advised method: public void com.th.service.UpdatePublicMapService.setPublicTrailSegmentDataGateway(com.th.data.pub.PublicTrailSegmentDataGateway)13:14:40,891 DEBUG [org.springframework.transaction.annotation.AnnotationTransactionAttributeSource] - Adding transactional method [setPersonalPublicTrailSegmentDataGateway] with attribute [PROPAGATION_REQUIRED,ISOLATION_DEFAULT]13:14:40,891 DEBUG [org.springframework.aop.framework.Cglib2AopProxy] - Unable to apply any optimisations to advised method: public void com.th.service.UpdatePublicMapService.setPersonalPublicTrailSegmentDataGateway(com.th.data.personal.PersonalPublicTrailSegmentDataGateway)13:14:40,891 DEBUG [org.springframework.transaction.annotation.AnnotationTransactionAttributeSource] - Adding transactional method [setPublicTrailJunctionDataGateway] with attribute [PROPAGATION_REQUIRED,ISOLATION_DEFAULT]13:14:40,892 DEBUG [org.springframework.aop.framework.Cglib2AopProxy] - Unable to apply any optimisations to advised method: public void com.th.service.UpdatePublicMapService.setPublicTrailJunctionDataGateway(com.th.data.pub.PublicTrailJunctionDataGateway)13:14:40,892 DEBUG [org.springframework.aop.framework.Cglib2AopProxy] - Unable to apply any optimisations to advised method: protected native java.lang.Object java.lang.Object.clone() throws java.lang.CloneNotSupportedException13:14:40,892 DEBUG [org.springframework.aop.framework.Cglib2AopProxy] - Found 'equals' method: public boolean java.lang.Object.equals(java.lang.Object)13:14:40,892 DEBUG [org.springframework.aop.framework.Cglib2AopProxy] - Found finalize() method - using NO_OVERRIDE13:14:40,892 DEBUG [org.springframework.aop.framework.Cglib2AopProxy] - Found 'hashCode' method: public native int java.lang.Object.hashCode()13:14:40,893 DEBUG [org.springframework.aop.framework.Cglib2AopProxy] - Unable to apply any optimisations to advised method: public java.lang.String java.lang.Object.toString()13:14:40,893 DEBUG [org.springframework.aop.framework.Cglib2AopProxy] - Method is declared on Advised interface: public abstract boolean org.springframework.aop.framework.Advised.isFrozen()13:14:40,893 DEBUG [org.springframework.aop.framework.Cglib2AopProxy] - Method is declared on Advised interface: public abstract boolean org.springframework.aop.framework.Advised.isProxyTargetClass()13:14:40,893 DEBUG [org.springframework.aop.framework.Cglib2AopProxy] - Method is declared on Advised interface: public abstract java.lang.Class[] org.springframework.aop.framework.Advised.getProxiedInterfaces()13:14:40,893 DEBUG [org.springframework.aop.framework.Cglib2AopProxy] - Method is declared on Advised interface: public abstract boolean org.springframework.aop.framework.Advised.isInterfaceProxied(java.lang.Class)13:14:40,894 DEBUG [org.springframework.aop.framework.Cglib2AopProxy] - Method is declared on Advised interface: public abstract void org.springframework.aop.framework.Advised.setTargetSource(org.springframework.aop.TargetSource)13:14:40,894 DEBUG [org.springframework.aop.framework.Cglib2AopProxy] - Method is declared on Advised interface: public abstract org.springframework.aop.TargetSource org.springframework.aop.framework.Advised.getTargetSource()13:14:40,895 DEBUG [org.springframework.aop.framework.Cglib2AopProxy] - Method is declared on Advised interface: public abstract void org.springframework.aop.framework.Advised.setExposeProxy(boolean)13:14:40,895 DEBUG [org.springframework.aop.framework.Cglib2AopProxy] - Method is declared on Advised interface: public abstract boolean org.springframework.aop.framework.Advised.isExposeProxy()13:14:40,896 DEBUG [org.springframework.aop.framework.Cglib2AopProxy] - Method is declared on Advised interface: public abstract void org.springframework.aop.framework.Advised.setPreFiltered(boolean)13:14:40,896 DEBUG [org.springframework.aop.framework.Cglib2AopProxy] - Method is declared on Advised interface: public abstract boolean org.springframework.aop.framework.Advised.isPreFiltered()13:14:40,896 DEBUG [org.springframework.aop.framework.Cglib2AopProxy] - Method is declared on Advised interface: public abstract org.springframework.aop.Advisor[] org.springframework.aop.framework.Advised.getAdvisors()13:14:40,897 DEBUG [org.springframework.aop.framework.Cglib2AopProxy] - Method is declared on Advised interface: public abstract void org.springframework.aop.framework.Advised.addAdvisor(org.springframework.aop.Advisor) throws org.springframework.aop.framework.AopConfigException13:14:40,897 DEBUG [org.springframework.aop.framework.Cglib2AopProxy] - Method is declared on Advised interface: public abstract void org.springframework.aop.framework.Advised.addAdvisor(int,org.springframework.aop.Advisor) throws org.springframework.aop.framework.AopConfigException13:14:40,897 DEBUG [org.springframework.aop.framework.Cglib2AopProxy] - Method is declared on Advised interface: public abstract boolean org.springframework.aop.framework.Advised.removeAdvisor(org.springframework.aop.Advisor)13:14:40,898 DEBUG [org.springframework.aop.framework.Cglib2AopProxy] - Method is declared on Advised interface: public abstract void org.springframework.aop.framework.Advised.removeAdvisor(int) throws org.springframework.aop.framework.AopConfigException13:14:40,898 DEBUG [org.springframework.aop.framework.Cglib2AopProxy] - Method is declared on Advised interface: public abstract int org.springframework.aop.framework.Advised.indexOf(org.springframework.aop.Advisor)13:14:40,898 DEBUG [org.springframework.aop.framework.Cglib2AopProxy] - Method is declared on Advised interface: public abstract boolean org.springframework.aop.framework.Advised.replaceAdvisor(org.springframework.aop.Advisor,org.springframework.aop.Advisor) throws org.springframework.aop.framework.AopConfigException13:14:40,898 DEBUG [org.springframework.aop.framework.Cglib2AopProxy] - Method is declared on Advised interface: public abstract void org.springframework.aop.framework.Advised.addAdvice(org.aopalliance.aop.Advice) throws org.springframework.aop.framework.AopConfigException13:14:40,898 DEBUG [org.springframework.aop.framework.Cglib2AopProxy] - Method is declared on Advised interface: public abstract void org.springframework.aop.framework.Advised.addAdvice(int,org.aopalliance.aop.Advice) throws org.springframework.aop.framework.AopConfigException13:14:40,900 DEBUG [org.springframework.aop.framework.Cglib2AopProxy] - Method is declared on Advised interface: public abstract boolean org.springframework.aop.framework.Advised.removeAdvice(org.aopalliance.aop.Advice)13:14:40,904 DEBUG [org.springframework.aop.framework.Cglib2AopProxy] - Method is declared on Advised interface: public abstract int org.springframework.aop.framework.Advised.indexOf(org.aopalliance.aop.Advice)13:14:40,904 DEBUG [org.springframework.aop.framework.Cglib2AopProxy] - Method is declared on Advised interface: public abstract java.lang.String org.springframework.aop.framework.Advised.toProxyConfigString()13:14:40,907 DEBUG [org.springframework.aop.framework.Cglib2AopProxy] - Method is declared on Advised interface: public abstract java.lang.Class org.springframework.aop.TargetClassAware.getTargetClass()13:14:44,767 DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Finished creating instance of bean 'updatePublicMapService'13:14:44,768 DEBUG [org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor] - Autowiring by type from bean name 'personalController' to bean named 'updatePublicMapService'...13:15:50,637 DEBUG [org.springframework.beans.factory.annotation.InjectionMetadata] - Processing injected method of bean 'personalController': AutowiredMethodElement for public void com.th.rest.personal.trailsegment.PersonalController.setUpdatePublicMapService(com.th.service.UpdatePublicMapService)13:15:50,638 DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Creating shared instance of singleton bean 'updatePublicMapService'13:15:50,638 DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Creating instance of bean 'updatePublicMapService'13:15:50,646 DEBUG [org.springframework.beans.factory.annotation.InjectionMetadata] - Found injected element on class [com.th.service.UpdatePublicMapService]: AutowiredMethodElement for public void com.th.service.UpdatePublicMapService.setPersonalRouteDataGateway(com.th.data.personal.PersonalRouteDataGateway)13:15:50,646 DEBUG [org.springframework.beans.factory.annotation.InjectionMetadata] - Found injected element on class [com.th.service.UpdatePublicMapService]: AutowiredMethodElement for public void com.th.service.UpdatePublicMapService.setPersonalTrailSegmentDataGateway(com.th.data.personal.PersonalTrailSegmentDataGateway)13:15:50,646 DEBUG [org.springframework.beans.factory.annotation.InjectionMetadata] - Found injected element on class [com.th.service.UpdatePublicMapService]: AutowiredMethodElement for public void com.th.service.UpdatePublicMapService.setPersonalTrailDataGateway(com.th.data.personal.PersonalTrailDataGateway)13:15:50,646 DEBUG [org.springframework.beans.factory.annotation.InjectionMetadata] - Found injected element on class [com.th.service.UpdatePublicMapService]: AutowiredMethodElement for public void com.th.service.UpdatePublicMapService.setPersonalTrailJunctionDataGateway(com.th.data.personal.PersonalTrailJunctionDataGateway)13:15:50,647 DEBUG [org.springframework.beans.factory.annotation.InjectionMetadata] - Found injected element on class [com.th.service.UpdatePublicMapService]: AutowiredMethodElement for public void com.th.service.UpdatePublicMapService.setPublicTrailDataGateway(com.th.data.pub.PublicTrailDataGateway)13:15:50,647 DEBUG [org.springframework.beans.factory.annotation.InjectionMetadata] - Found injected element on class [com.th.service.UpdatePublicMapService]: AutowiredMethodElement for public void com.th.service.UpdatePublicMapService.setPublicTrailSegmentDataGateway(com.th.data.pub.PublicTrailSegmentDataGateway)13:15:50,647 DEBUG [org.springframework.beans.factory.annotation.InjectionMetadata] - Found injected element on class [com.th.service.UpdatePublicMapService]: AutowiredMethodElement for public void com.th.service.UpdatePublicMapService.setPersonalPublicTrailSegmentDataGateway(com.th.data.personal.PersonalPublicTrailSegmentDataGateway)13:15:50,647 DEBUG [org.springframework.beans.factory.annotation.InjectionMetadata] - Found injected element on class [com.th.service.UpdatePublicMapService]: AutowiredMethodElement for public void com.th.service.UpdatePublicMapService.setPublicTrailJunctionDataGateway(com.th.data.pub.PublicTrailJunctionDataGateway)13:15:50,648 DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Eagerly caching bean 'updatePublicMapService' to allow for resolving potential circular references13:15:50,648 DEBUG [org.springframework.beans.factory.annotation.InjectionMetadata] - Processing injected method of bean 'updatePublicMapService': AutowiredMethodElement for public void com.th.service.UpdatePublicMapService.setPersonalRouteDataGateway(com.th.data.personal.PersonalRouteDataGateway)13:15:50,649 DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Returning cached instance of singleton bean 'personalRouteDataGatewayImpl'13:15:50,649 DEBUG [org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor] - Autowiring by type from bean name 'updatePublicMapService' to bean named 'personalRouteDataGatewayImpl'13:15:50,649 DEBUG [org.springframework.beans.factory.annotation.InjectionMetadata] - Processing injected method of bean 'updatePublicMapService': AutowiredMethodElement for public void com.th.service.UpdatePublicMapService.setPersonalTrailSegmentDataGateway(com.th.data.personal.PersonalTrailSegmentDataGateway)13:15:50,650 DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Returning cached instance of singleton bean 'personalTrailSegmentDataGatewayImpl'13:15:50,650 DEBUG [org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor] - Autowiring by type from bean name 'updatePublicMapService' to bean named 'personalTrailSegmentDataGatewayImpl'13:15:50,650 DEBUG [org.springframework.beans.factory.annotation.InjectionMetadata] - Processing injected method of bean 'updatePublicMapService': AutowiredMethodElement for public void com.th.service.UpdatePublicMapService.setPersonalTrailDataGateway(com.th.data.personal.PersonalTrailDataGateway)13:15:50,651 DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Returning cached instance of singleton bean 'personalTrailDataGatewayImpl'13:15:50,652 DEBUG [org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor] - Autowiring by type from bean name 'updatePublicMapService' to bean named 'personalTrailDataGatewayImpl'13:15:50,652 DEBUG [org.springframework.beans.factory.annotation.InjectionMetadata] - Processing injected method of bean 'updatePublicMapService': AutowiredMethodElement for public void com.th.service.UpdatePublicMapService.setPersonalTrailJunctionDataGateway(com.th.data.personal.PersonalTrailJunctionDataGateway)13:15:50,652 DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Returning cached instance of singleton bean 'personalTrailJunctionDataGatewayImpl'13:15:50,653 DEBUG [org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor] - Autowiring by type from bean name 'updatePublicMapService' to bean named 'personalTrailJunctionDataGatewayImpl'13:15:50,653 DEBUG [org.springframework.beans.factory.annotation.InjectionMetadata] - Processing injected method of bean 'updatePublicMapService': AutowiredMethodElement for public void com.th.service.UpdatePublicMapService.setPublicTrailDataGateway(com.th.data.pub.PublicTrailDataGateway)13:15:50,654 DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Returning cached instance of singleton bean 'publicTrailDataGatewayImpl'13:15:50,654 DEBUG [org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor] - Autowiring by type from bean name 'updatePublicMapService' to bean named 'publicTrailDataGatewayImpl'13:15:50,654 DEBUG [org.springframework.beans.factory.annotation.InjectionMetadata] - Processing injected method of bean 'updatePublicMapService': AutowiredMethodElement for public void com.th.service.UpdatePublicMapService.setPublicTrailSegmentDataGateway(com.th.data.pub.PublicTrailSegmentDataGateway)13:15:50,655 DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Returning cached instance of singleton bean 'publicTrailSegmentDataGatewayImpl'13:15:50,655 DEBUG [org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor] - Autowiring by type from bean name 'updatePublicMapService' to bean named 'publicTrailSegmentDataGatewayImpl'13:15:50,655 DEBUG [org.springframework.beans.factory.annotation.InjectionMetadata] - Processing injected method of bean 'updatePublicMapService': AutowiredMethodElement for public void com.th.service.UpdatePublicMapService.setPersonalPublicTrailSegmentDataGateway(com.th.data.personal.PersonalPublicTrailSegmentDataGateway)13:15:50,656 DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Returning cached instance of singleton bean 'personalPublicTrailSegmentDataGatewayImpl'13:15:50,656 DEBUG [org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor] - Autowiring by type from bean name 'updatePublicMapService' to bean named 'personalPublicTrailSegmentDataGatewayImpl'13:15:50,656 DEBUG [org.springframework.beans.factory.annotation.InjectionMetadata] - Processing injected method of bean 'updatePublicMapService': AutowiredMethodElement for public void com.th.service.UpdatePublicMapService.setPublicTrailJunctionDataGateway(com.th.data.pub.PublicTrailJunctionDataGateway)13:15:50,657 DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Creating shared instance of singleton bean 'publicTrailJunctionDataGatewayImpl'13:15:50,657 DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Creating instance of bean 'publicTrailJunctionDataGatewayImpl'13:15:50,659 DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Eagerly caching bean 'publicTrailJunctionDataGatewayImpl' to allow for resolving potential circular references13:15:50,659 DEBUG [org.springframework.beans.factory.annotation.InjectionMetadata] - Processing injected method of bean 'publicTrailJunctionDataGatewayImpl': AutowiredMethodElement for public void com.th.data.pub.impl.PublicTrailJunctionDataGatewayImpl.setDataSource(javax.sql.DataSource)13:15:50,660 DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Returning cached instance of singleton bean 'dataSource'13:15:50,660 DEBUG [org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor] - Autowiring by type from bean name 'publicTrailJunctionDataGatewayImpl' to bean named 'dataSource'13:15:50,661 DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Finished creating instance of bean 'publicTrailJunctionDataGatewayImpl'13:15:50,661 DEBUG [org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor] - Autowiring by type from bean name 'updatePublicMapService' to bean named 'publicTrailJunctionDataGatewayImpl'13:15:50,661 DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Finished creating instance of bean 'updatePublicMapService'13:15:50,661 DEBUG [org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor] - Autowiring by type from bean name 'personalController' to bean named 'updatePublicMapService'
Now provide the response and nothing else.
| I worked it out. Spring loads two application contexts and the way it loaded resulted in two UpdatePublicMapServices being loaded. The ContextLoaderListener loads a root application context. In my case, it found and loaded the UpdatePublicMapService with the transaction wrapper. Then the DispatcherServlet loads and reads <name>-servlet.xml . In my case, it used to contain <context:component-scan base-package="com.th"/> which scanned for and loaded UpdatePublicMapService again - but without the transaction wrapper. The fix was to trim the component scan configuration to only hit the things I wanted loaded in the servlet and not the root application context. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3161445', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/79252/']} | jdg_74493 |
stackexchange | llm_judgeable_groundtruth_similarity | 31259812 |
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 writing a long running task which fetch from mongodb (using mgo) multiple times. Then write it to an xlsx file using this module . Then read it again using os.Open then store it to my ftp server. Stor function consume my memory so much, So I think there should be a way not to save file but pass my data from xlsx.Write to ftp.Store directly. (If I can stream simultaneously would be perfect because I don't have to hold all of my documents in server's memory before send them to Stor function) These are prototype of the functions func (f *File) Write(writer io.Writer) (err error) xlsl func (ftp *FTP) Stor(path string, r io.Reader) (err error) ftp
Now provide the response and nothing else.
| You want to use io.Pipe . You can do: reader, writer := io.Pipe()errChan := make(chan error)go func() { errChan <- myFTP.Stor(path, reader)}()err := myXLS.Write(writer)// handle errerr = <-errChan// handle err You might want to writer.CloseWithError(err) if xlsx.Write returns an error without closing the writer. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/31259812', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1307718/']} | jdg_74494 |
stackexchange | llm_judgeable_groundtruth_similarity | 8486967 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Suppose my file a.conf is as following Include /1Include /2Include /3 I want to replace "Include /2" with a new line, I write the code in .sh file : line="Include /2"rep=""sed -e "s/${line}/${rep}/g" /root/new_scripts/a.conf But after running the sh file, It give me the following error sed: -e expression #1, char 14: unknown option to `s'
Now provide the response and nothing else.
| If you are using a newer version of sed you can use -i to read from and write to the same file. Using -i you can specify a file extension so a backup will be made, incase something went wrong. Also you don't need to use the -e flag unless you are using multiple commands sed -i.bak "s/${line}/${rep}/g" /root/new_scripts/a.conf I have just noticed that as the variables you are using are quoted strings you may want to use single quotes around your sed expression. Also your string contains a forward slash, to avoid any errors you can use a different delimiter in your sed command (the delimiter doesn't need to be a slash): sed -i.bak 's|${line}|${rep}|g' /root/new_scripts/a.conf | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8486967', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1044804/']} | jdg_74495 |
stackexchange | llm_judgeable_groundtruth_similarity | 60224456 |
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 check if a variable exists on a template file using terraform template syntax, but I get error that This object does not have an attribute named "proxy_set_header . $ cat nginx.conf.tmpl%{ for location in jsondecode(locations) }location ${location.path} { %{ if location.proxy_set_header } proxy_set_header ${location.proxy_set_header}; %{ endif }}%{ endfor } I tried with if location.proxy_set_header != "" and if location.proxy_set_header without success. How to check if a variable exists with the String Templates?
Now provide the response and nothing else.
| If you are using Terraform 0.12.20 or later then you can use the new function can to concisely write a check like this: %{ for location in jsondecode(locations) }location ${location.path} { %{ if can(location.proxy_set_header) } proxy_set_header ${location.proxy_set_header}; %{ endif }}%{ endfor } The can function returns true if the given expression could evaluate without an error. The documentation does suggest preferring try in most cases, but in this particular situation your goal is to show nothing at all if that attribute isn't present, and so this equivalent approach with try is, I think, harder to understand for a future reader: %{ for location in jsondecode(locations) }location ${location.path} { ${ try("proxy_set_header ${location.proxy_set_header};", "") }}%{ endfor } As well as being (subjectively) more opaque as to the intent, this ignores the recommendation in the try docs of using it only with attribute lookup and type conversion expressions. Therefore I think the can usage above is justified due to its relative clarity, but either way should work. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/60224456', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3653092/']} | jdg_74496 |
stackexchange | llm_judgeable_groundtruth_similarity | 4247450 |
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 tried to prove this but my proof did not match with my book's. So I want to verify whether my proof is correct or not. Theorem: Every Cauchy sequence in $\mathbb R$ has a limit. Let us assume the contrary that there is a sequence $(a_n)$ which is Cauchy but not convergent. 1.Since the sequence is not convergent,for all real $a$ , there must be an $\epsilon$ such that for all $n \in \mathbb N$ , $\exists n_0 \geq n$ such that $|a_{n_0}-a|\geq \epsilon$ . 2.Since $(a_n)$ is Cauchy, we can show that that particular $\epsilon$ we talked above,there is a natural $N$ such that for all $n,m\geq N$ , $|a_n-a_m|<\epsilon$ . 3.Go and look $(1)$ . I can thus find $m_0 \geq N$ such that $|a_{m_0}-a| \geq \epsilon >|a_{m_0}-a_n|$ for all $n \geq N$ . Since $a$ is arbitrary, putting $a=a_n$ ,we get contradiction.Thus, the proof.
Now provide the response and nothing else.
| In step 1, you're fixing $n_0$ which has the property $|a_{n_0} - a| \geq \epsilon$ , but in step 3, you're using that $|a_{m_0} - a| \geq \epsilon$ for your $m$ large enough. You can't first fix $n_0$ and then replace it. That's already assuming that your sequence $a_n$ converges to $a$ , which is what you're trying to prove. The standard argument constructs (using Bolzano-Weierstrass) a convergent subsequence of $a_n$ . It can then be shown that any Cauchy sequence with a convergent subsequence is convergent. A quicker way to see that your argument doesn't work is the following: it doesn't rely on the "completeness" of $\mathbb{R}$ . You will learn that - in more general settings - convergent sequences are always Cauchy, but not all Cauchy sequences converge. For this you really need the completeness (which is used in the proof of Bolzano Weierstrass). | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4247450', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']} | jdg_74497 |
stackexchange | llm_judgeable_groundtruth_similarity | 605664 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
This is a fairly simple dimming circuit using a dual opamp (IC1) as a comparator to control the brightening and dimming of a light bulb. The switch (pin 2 IC1a) is a contact connection to ground. Trimpot 3 controls the speed of the brightening when the switch is connected to ground. Trimpot 2 controls the speed of dimming. The issue is that when using a 10 W bulb, transistor (Q1) gets warm during the brightening/dimming time. The longer the times are (based on TM2/TM3), the warmer it gets. It gets very hot when testing with a 25 W bulb. Even if the trimmers are set to 0 ohms (thus only R5, R6 resistance) and there is virtually no brightening/dimming happening, the transistor gets extremely hot almost immediately. Should there be a current limiting resistor from the transistor's emitter to ground? What else could allow the transistor to function cooler? Is it even possible to operate a D2PAK form factor that is meant to switch up to 40 W (3.3 A) without a heatsink and only PCB heatsinking?
Now provide the response and nothing else.
| You've got at least a couple of problems. One is that you've greatly changed the circuit from the one you were following. The example uses one LM358 op-amp as an oscillator and a second op-amp as a comparator to drive a MOSFET with a pulse width modulated signal. The modifications you've made appear to have changed the circuit from PWM to a linear regulator. In that case, even the MOSFET would get warm or hot. The second problem is that you are using a NPN bipolar junction transistor instead of the specified N-channel MOSFET. The NJVMJB44H11 has a collector to emitter saturation voltage of 1V. At 1A of current, that'd be at least 1W of power dissipated in the transistor. That's a lot more than the the 200mW mentioned on the web site you referred to. MOSFETs have a certain minimum resistance when fully on (conducting.) That can be very low, resulting in low switching losses. BJTs have a certain minimum collector to emitter voltage when fully switched on. The product of the voltage from collector to emitter and the current through the collector tells you how much power the transistor itself will waste as heat. Saturation in the NJVMJB44H11 is rated at a base current of 0.4A. Your LM358 can't deliver the current needed to push the transistor into saturation, so you will have a higher voltage drop across the transistor and therefore more power loss - the transistor will get hotter. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/605664', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/62474/']} | jdg_74498 |
stackexchange | llm_judgeable_groundtruth_similarity | 455155 |
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 this scenario first_arg="$1";if foo; then shift 1; node foo.js "$@"elif bar; then shift 1; node bar.js "$@"elif baz; then shift 1; node baz.js "$@"else node default.js "$@"fi I would like to turn the above into this: first_arg="$1";shift 1;if foo; then node foo.js "$@"elif bar; then node bar.js "$@"elif baz; then node baz.js "$@"else unshift 1; node default.js "$@"fi but I am not sure if there is an operator like unshift, which I just made up. One workaround might be this: node default.js "$first_arg" "$@" but when I tried that, I got weird behavior.
Now provide the response and nothing else.
| You could save your arguments in an array: args=( "$@" ) # use double quotesshift 1if foo; then node foo.js "$@"elif bar; then node bar.js "$@"elif baz; then node baz.js "$@"else node default.js "${args[@]}"fi | {} | {'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/455155', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/113238/']} | jdg_74499 |
stackexchange | llm_judgeable_groundtruth_similarity | 38667445 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it true that " ApiController will get deprecated in .NET Core"? Asking since I'm planning to use it in new projects.
Now provide the response and nothing else.
| Update ASP.NET Core 2.1 Since ASP.NET Core 2.1 a new set of types is available to create Web API controllers. You can annotate your controllers with the [ApiController] attribute which enables a few new features such as automatic model state validation and binding source parameter inference. See the docs for more information: https://learn.microsoft.com/en-us/aspnet/core/web-api/index?view=aspnetcore-2.1#annotate-class-with-apicontrollerattribute . There is indeed no particular ApiController class anymore since MVC and WebAPI have been merged in ASP.NET Core. However, the Controller class of MVC brings in a bunch of features you probably won't need when developing just a Web API, such as a views and model binding. You've got two options if you want something different: Use the ControllerBase class in the Microsoft.AspNetCore.Mvc.Core package. Or Create your ApiController base class. The key here is to add the [ActionContext] attribute which injects the current ActionContext instance into the property: [Controller]public abstract class ApiController{ [ActionContext] public ActionContext ActionContext { get; set; }} Also, add the [Controller] attribute to the class to mark it as a controller for the MVC controller discovery. See more details in my “Web API in MVC 6” blogpost . | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/38667445', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2779615/']} | jdg_74500 |
stackexchange | llm_judgeable_groundtruth_similarity | 40431674 |
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 run a script on a target OS built by Yocto. This script needs to be ran as part of the install and thus must be ran only once (either after the entire OS install or on the first boot). It cannot be ran on the host system, as it depends on the hardware IO which exists only on the target. An additional, minor, constraint is that the rootfs is mounted as read only, but I guess that can be avoided by having the script re-mount as rw and again remount as r after the execution or something along those lines. Any help is appreciated.
Now provide the response and nothing else.
| I ended up doing what shibley had written. Here's a detailed howto: Create a new layer Put the desired layer wherever your other layers are. Mine are in stuff directory, next to the build directory. Make the following files/directories: meta_mylayer├── conf│ └── layer.conf└── recipes-core └── mylayer-initscript ├── initscript.bb └── files ├── initscript.service └── initscript.sh meta_mylayer is the name of your new layer. Let's define the layer in conf/layer.conf and tell it where to search for the recipes: BBPATH .= ":${LAYERDIR}"BBFILES += "${LAYERDIR}/recipes-*/*/*.bb ${LAYERDIR}/recipes-*/*/*.bbappend"BBFILE_COLLECTIONS += "meta-mylayer"BBFILE_PATTERN_meta-mylayer := "^${LAYERDIR}/"BBFILE_PRIORITY_meta-mylayer = "99" The recipes are defined by the name of the .bb file. This layer only has one recipe, named initscript . initscript.bb contains the recipe information. The following recipe will add our initscript service and put the actual install script, initscript.sh , into /usr/sbin/ SUMMARY = "Initial boot script"DESCRIPTION = "Script to do any first boot init, started as a systemd service which removes itself once finished"LICENSE = "CLOSED"PR = "r3"SRC_URI = " \ file://initscript.sh \ file://initscript.service \"do_compile () {}do_install () { install -d ${D}/${sbindir} install -m 0755 ${WORKDIR}/initscript.sh ${D}/${sbindir} install -d ${D}${systemd_unitdir}/system/ install -m 0644 ${WORKDIR}/initscript.service ${D}${systemd_unitdir}/system}NATIVE_SYSTEMD_SUPPORT = "1"SYSTEMD_PACKAGES = "${PN}"SYSTEMD_SERVICE_${PN} = "initscript.service"inherit allarch systemd install -d will create any directories needed for the specified path, while install -m 0644 will copy the specified file with 644 permissions. ${D} is the destination directory, by default it's ${WORKDIR}/image Create the systemd service definition I won't go into much details about how systemd works, but will rather paste the service definition: [Unit]Description=start initscript upon first boot[Service]Type=simpleExecStart=/bin/sh -c 'sleep 5 ; /usr/sbin/initscript.sh' Do note the script location at /usr/sbin/ - that's where it will be copied by the last line of our do_install function above. Lastly, our initscript.sh script itself: #!/bin/shlogger "starting initscript"# do some work here. Mount rootfs as rw if needed.logger "initscript work done"#job done, remove it from systemd servicessystemctl disable initscript.servicelogger "initscript disabled" Register the layer We need to register our new layer, so that bitbake knows it's there.Edit the build/conf/bblayers.conf file and add the following line to the BASELAYERS variable: ${TOPDIR}/../stuff/meta-mylayer \ Now that the bitbake recognizes our layer, we need to add our recipe to the image.Edit the build/conf/local.conf and add the initscript recipe to the IMAGE_INSTALL_append variable. Here's how it looks like when added next to the python. IMAGE_INSTALL_append = " python initscript" Run the build Run the build like you usually do. For example: bitbake angstrom-lxde-image After you install the build and boot for the first time, your initscript.sh will be executed. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40431674', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4943977/']} | jdg_74501 |
stackexchange | llm_judgeable_groundtruth_similarity | 24967089 |
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 know how to replace ALL non alphanumeric chars in a string but how to do it from just beginning and end of the string? I need this string: "theString," to be: theString replace ALL non alphanumeric chars in a string: s = s.replaceAll("[^a-zA-Z0-9\\s]", "");
Now provide the response and nothing else.
| Use ^ (matches at the beginning of the string) and $ (matches at the end) anchors: s = s.replaceAll("^[^a-zA-Z0-9\\s]+|[^a-zA-Z0-9\\s]+$", ""); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24967089', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/517733/']} | jdg_74502 |
stackexchange | llm_judgeable_groundtruth_similarity | 36760489 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
try { } catch (ex: MyException1, MyException2 ) { logger.warn("", ex)} or try { } catch (ex: MyException1 | MyException2 ) { logger.warn("", ex)} As a result, a compilation error: Unresolved reference: MyException2 . How can I catch many exceptions at the same time on Kotlin?
Now provide the response and nothing else.
| Update:Vote for the following issue KT-7128 if you want this feature to land in Kotlin. Thanks @Cristan According to this thread this feature is not supported at this moment. abreslav - JetBrains Team Not at the moment, but it is on the table You can mimic the multi-catch though: try { // do some work} catch (ex: Exception) { when(ex) { is IllegalAccessException, is IndexOutOfBoundsException -> { // handle those above } else -> throw ex }} | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/36760489', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6233653/']} | jdg_74503 |
stackexchange | llm_judgeable_groundtruth_similarity | 623090 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Since Asp.net 2.0, there is the Provider Model. On the implementation detail, a provider is class derived from ProviderBase which is an abstract class rather than an interface, but anyway the Provider Model is there so that we can have different implementation to swap in the out by just editing the web.config. For example if you create a blog app, you may have a BlogProvider : ProviderBase, then you can have implementations of BlogProvider like: SqlBlogProvider, OracleBlogProvider and even MockBlogProvider for testing. Now, Repository Pattern is getting popular, and I feel it is to satisfy the same need, though in the implementation detail, you normally use interfaces, so IBlogProvider, and you'd inject different implementations through constructors rather than properties, but essentially I don't see the difference in what these 2 patterns gave us. Personally, I feel Provider Model is more natural for me in the implementation. So, is there a difference between them or they are just the same thing with different names given by different communities? I'd appreciate any comments on this,Thanks,Ray.
Now provide the response and nothing else.
| The Repository and Provider patterns overlap, but they don't formally describe the same thing. I would almost say the Repository is a subset of Provider. In practice, I think the Repository pattern was borne out of a specific need - abstracting repositories - and evolved in the community into a more generic abstraction pattern. In that respect, they have come to be different terms that describe the same concept. However, from the original definitions, they are different in scope: The purpose of the Repository pattern is to abstract the specifics of a repository of data away from the application. The purpose of the Provider model is to abstract the specifics of anything away from the application. This may be a data repository, but it is just as often some kind of logic. For example, in our application we have a ContextFactoryProvider, which contains different kinds of logic for determining which ContextFactory to use. There is no repository of data in this case; it's purely application logic that needs to change arbitrarily; the Provider model allows us to use the Single Responsibility Principle to isolate each kind of logic into its own class and swap out that logic easily. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/623090', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/32240/']} | jdg_74504 |
stackexchange | llm_judgeable_groundtruth_similarity | 15516168 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Unfortunately, I am having difficulty cross-compiling Git for the ARMv6 architecture. But before I begin describing the steps I've taken and commands I've entered, I should briefly describe the build environment: I am cross-compiling on Ubuntu 12.10 64-bit. The cross compiler is installed to /home/my_name/cctoolchain (this directory contains bin/ , lib/ , etc.). I began by grabbing Git 1.8.2 from here . After extracting the directory I ran: export PATH=$PATH:/home/my_name/cctoolchain/bin I also ran autoconf to make sure that ./configure was up to date. Then I invoked ./configure as follows: ./configure --prefix=/home/my_name/git-arm --build=x86_64-linux-gnu --host=arm-linux-androideabi This ran for a couple of seconds and then aborted with: checking whether system succeeds to read fopen'ed directory...configure: error: in `/home/my_name/git-1.8.2':configure: error: cannot run test program while cross compiling I cracked open configure.ac and removed lines 806-825, disabling the test. After doing that, I also had to remove lines 806-839 for a similar reason. At this point, the ./configure script was able to complete. I then excitedly ran make to build Git and after a few more moments, ran into this error: fetch-pack.c: In function 'fetch_pack':fetch-pack.c:928:16: error: 'struct stat' has no member named 'st_mtim'make: *** [fetch-pack.o] Error 1 Somehow I get the feeling I'm "doing it wrong". This sounds like something that should be a lot easier than manually removing tests from configure.ac . What am I missing?
Now provide the response and nothing else.
| The macro that's failing is ST_MTIME_NSEC in git-compat-util.h . This macro is controlled by the macros USE_NSEC , NO_NSEC and USE_ST_TIMESPEC , which are provided on the build commandline or by config.mak.uname , not by configure. It should be that if no options are provided, git doesn't attempt to use nanosecond timestamps (or st_mtim ) at all, but it looks like a bug slipped through. Try make NO_NSEC=1 and see if that resolves your problem. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15516168', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/193619/']} | jdg_74505 |
stackexchange | llm_judgeable_groundtruth_similarity | 13599201 |
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 capture image using camera and want image path. I try following code but I get Error. (I follow this link Get Path of image from ACTION_IMAGE_CAPTURE Intent ) Here is my code. MainActivity.java public class MainActivity extends Activity { private static final int CAMERA_REQUEST = 1888; private ImageView imageView; private Uri mCapturedImageURI; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); this.imageView = (ImageView)this.findViewById(R.id.imageView1); Button photoButton = (Button) this.findViewById(R.id.button1); photoButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String fileName = "temp.jpg"; ContentValues values = new ContentValues(); values.put(MediaStore.Images.Media.TITLE, fileName); mCapturedImageURI = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI); startActivityForResult(intent, CAMERA_REQUEST); } }); } protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) { String[] projection = { MediaStore.Images.Media.DATA}; Cursor cursor = managedQuery(mCapturedImageURI, projection, null, null, null); int column_index_data = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); String capturedImageFilePath = cursor.getString(column_index_data); Toast.makeText(getApplicationContext(), capturedImageFilePath.toString(), Toast.LENGTH_LONG).show(); } } } activity_main.xml <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="photo" > </Button> <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_launcher" > </ImageView></LinearLayout> AndroidManifest.xml <uses-feature android:name="android.hardware.camera"></uses-feature><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> Error java.lang.RuntimeException: Unable to resume activity {com.example.cameraupload/com.example.cameraupload.MainActivity}: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1888, result=-1, data=null} to activity {com.example.cameraupload/com.example.cameraupload.MainActivity}: java.lang.NullPointerException
Now provide the response and nothing else.
| If I understand you correctly, what you want could be accomplished by a simple BufferBlock , which would be linked to all your target blocks with predicates. You would also (unconditionally) link it to a NullTarget block , to discard items that didn't match. Something like: var forwarder = new BufferBlock<SomeType>();forwarder.LinkTo(target1, item => matchesTarget1(item));forwarder.LinkTo(target2, item => matchesTarget2(item));forwarder.LinkTo(DataflowBlock.NullTarget<SomeType>()); This way, each item will be sent to the first target that matches, if there is any. BroadcastBlock can be useful if you want to send each item to multiple targets, or if you want to discard items if the target block is not fast enough. With BroadcastBlock , items may be dropped if no block accepts them (even though they may be able to accept it later). But it doesn't drop items at random, so if your target blocks don't have BoundedCapacity set, I think you can be sure that they will get all items that they don't decline (e.g. by using predicate in LinkTo() ). | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13599201', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1686001/']} | jdg_74506 |
stackexchange | llm_judgeable_groundtruth_similarity | 4084495 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What would be the best solution to find top N (say 10) elements in an unordered list (of say 100). The solution which came in my head was to 1. sort it using quick sort, 2. get top 10. But is there any better alternative?
Now provide the response and nothing else.
| The time could be reduced to linear time: Use the selection algorithm , which effectively find the k-th element in a un-sorted array in linear time. You can either use a variant of quick sort or more robust algorithms. Get the top k using the pivot got in step 1. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4084495', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/231917/']} | jdg_74507 |
stackexchange | llm_judgeable_groundtruth_similarity | 707495 |
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:
Gravitational potential inside a hollow sphere is given by $$V(r)=\frac{-Gm}{R}$$ Why is it the same as the gravitational potential on the surface of the hollow sphere, which is given by $\frac{-Gm}{R}$ too? Where as in the case of a solid sphere the gravitational potential is not constant inside thesolid sphere, Why is it so?
Now provide the response and nothing else.
| TL; DR you measure the redshift of the host galaxy, not the supernova. Indeed, the intrinsic blue-shifts or complicated P-Cygni profiles of expanding supernova matter do not make for precise or accurate redshift determination. If you look at some of the early Type Ia supernovae discovery papers of (relatively) low redshift supernovae, you will see that the redshifts used in the redshift-distance relationship are the redshifts of the host galaxies, often resolved from the supernova itself, and have uncertainties $<0.001$ (e.g. Perlmutter et al. 1997 ). i.e. When a supernova goes off in a (relatively) nearby galaxy, you can easily spatially distinguish the SN from the rest of the galaxy and get a separate spectrum of the galaxy. The process is similar in principle for very high redshift ( $z>1$ , and therefore very faint) supernovae that are spatially unresolved from their host galaxies, but there you might be looking for distinct absorption features/edges or Lyman alpha emission (type Ia SNe don't have hydrogen) due to gas in the host galaxy, superimposed on the supernova spectrum, to provide the redshift. The example below (from Curtin et al. 2019 ) illustrates this. The top panel shows a full spectrum (in black) with observed wavelelength on the x-axis. (The red line is the 1-sigma error in each spectral point.) The supernova features are mainly on the red side of the spectrum. Ihe blue part of the spectrum contains various absorption features caused by the host galaxay that are in the rest-frame ultra-violet part of the spectrum. The lower panel shows a zoom-in of this, now labelled in rest-frame wavelength, using a redshift of $z=2.399$ , and with various absorption features from the host galaxy labelled. The blue line is a template spectrum of an absorbing galaxy component that can be (roughly speaking) cross-correlated with the observed spectrum to yield the redshift of the host galaxy. The full modelling process is a little more complex and results in a redshift of $z=2.399 \pm 0.004$ in the case shown. There will be some additional source of error because you don't know how fast the supernova progenitor was moving as part of its host galaxy. There is also some uncertainty because the host galaxy gas might be moving within the galaxy,but these are going to be fairy negligible contributors (hundreds of km/s at most) at high redshift. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/707495', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/334931/']} | jdg_74508 |
stackexchange | llm_judgeable_groundtruth_similarity | 413395 |
Below is a question asked on the forum meta.stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
My question was closed for needing more debugging details. As you can see, I'm a new user here so don't know much about how this site works. In my question, I've provided every piece of code that might be helpful and every error message. The only strange thing is that I didn't get any comments about my question or how my question could be improved. So I guess they closed the question because a low user rep has asked a question but they can't answer it. Here is my question: Failed to load resource: net::ERR_REQUEST_RANGE_NOT_SATISFIABLE - Audio recorder API Error How can I make my question more helpful? I've asked for clarity about this, but no comment was given.
Now provide the response and nothing else.
| Quoting from your question: I don't have much to say since there isn't any other information that I can provide. Here's the other information that you can provide, which would help somebody to understand your issue: What actions are you taking for the error to be produced? As it is, if I run your code I see three buttons and no error. Presumably the error occurs when I click one of the buttons, or maybe more than one of the buttons in some specific order. Perhaps I could figure out which button(s) to press by playing around, but if I get an error by some different sequence of button presses then maybe I will write an answer that doesn't actually resolve your issue. Or if the error is specific to your browser then I might not be able to reproduce it, but I won't know whether the code is working for me or I'm just not testing it properly. Alternatively, if the error is caused by using your code in an unintended way, then it might just be an issue of how to make sure the user can't press the wrong button at the wrong time. We don't know! What do you intend for the code to do when the error is fixed? If the only way of judging a proposed answer is the absence of an error, then I could just delete parts of the code until there is no error. Obviously it would be silly to delete all of your code and say "there, no error!", but without knowing what the intended behaviour of your code is, I can't know whether I have made it work properly. I could guess, but I might guess wrong and then waste effort writing an answer which makes your code successfully do the wrong thing. It's far better to be explicit in the question about what the code is supposed to do when it works. Include the full stack trace of the error The error message alone says what the error was, but not where it occurred. For errors which occur at runtime, please include a full stack trace with line numbers. | {} | {'log_upvote_score': 6, 'links': ['https://meta.stackoverflow.com/questions/413395', 'https://meta.stackoverflow.com', 'https://meta.stackoverflow.com/users/17047169/']} | jdg_74509 |
stackexchange | llm_judgeable_groundtruth_similarity | 34548355 |
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 calculate the difference between 2 times.start_time: 22:00 (Rails interprets this as 2015-12-31 22:00:00 +0100)second_time: 02:00 (Rails interprets this as 2015-12-31 02:00:00 +0100). The second time is 4 hours later, so in the next day. Is there a way to calculate this difference? I can not simply do this: second_time - first_time, because this gives me a difference of 22 hours instead of 4 hours. Edit: Some background information: A job is starting at 22:00 and ending the next day at 02:00. Because i fill in the form of this job only times, this times for the above 2 values are 2015-12-31 22:00:00 +0100 and 2015-12-31 02:00:00 +0100. I don't want the user to fill in the time including the date. The real difference between the times should be 4 hours. So what i actually want is calculate the difference between 22:00 and 02:00 (in the next day).
Now provide the response and nothing else.
| I don't understand why you think it should return 4 hours or why it does return 22 hours. 20 hours would be correct for your example: require 'time'a = Time.parse('2015-12-31 22:00:00 +0100')b = Time.parse('2015-12-31 02:00:00 +0100')a - b#=> 72000.0 # difference in seconds(a - b) / 3600#=> 20.0 # difference in hours Update : It seems like you are dealing only with the time portion and not with the actual date. And I assume the maximum difference you will have to deal with is 24 hours: def time_difference(time_a, time_b) difference = time_b - time_a if difference > 0 difference else 24 * 3600 + difference endenda = Time.parse('2015-12-31 22:00:00 +0100')b = Time.parse('2015-12-31 02:00:00 +0100')time_difference(a, b) / 3600# => 4 # hoursa = Time.parse('2015-12-31 02:00:00 +0100')b = Time.parse('2015-12-31 22:00:00 +0100')time_difference(a, b) / 3600# => 20 # hours | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34548355', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1777106/']} | jdg_74510 |
stackexchange | llm_judgeable_groundtruth_similarity | 10473932 |
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 generating a image on client side and I display it with HTML like this: <img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgICAgM...."/> I want to offer the possibility to download the generated Image. How can I realize that the browser is opening a file save dialoge (or just download the image like chrome or firefox to the download folder would do) which allows the user to save the image without doing right click and save as on the image? I would prefer a solution without server interaction. So I am aware that it would be possible if I first upload the Image and then start the download. Thanks a lot!
Now provide the response and nothing else.
| Simply replace image/jpeg with application/octet-stream . The client would not recognise the URL as an inline-able resource, and prompt a download dialog. A simple JavaScript solution would be: //var img = reference to imagevar url = img.src.replace(/^data:image\/[^;]+/, 'data:application/octet-stream');window.open(url);// Or perhaps: location.href = url;// Or even setting the location of an <iframe> element, Another method is to use a blob: URI: var img = document.images[0];img.onclick = function() { // atob to base64_decode the data-URI var image_data = atob(img.src.split(',')[1]); // Use typed arrays to convert the binary data to a Blob var arraybuffer = new ArrayBuffer(image_data.length); var view = new Uint8Array(arraybuffer); for (var i=0; i<image_data.length; i++) { view[i] = image_data.charCodeAt(i) & 0xff; } try { // This is the recommended method: var blob = new Blob([arraybuffer], {type: 'application/octet-stream'}); } catch (e) { // The BlobBuilder API has been deprecated in favour of Blob, but older // browsers don't know about the Blob constructor // IE10 also supports BlobBuilder, but since the `Blob` constructor // also works, there's no need to add `MSBlobBuilder`. var bb = new (window.WebKitBlobBuilder || window.MozBlobBuilder); bb.append(arraybuffer); var blob = bb.getBlob('application/octet-stream'); // <-- Here's the Blob } // Use the URL object to create a temporary URL var url = (window.webkitURL || window.URL).createObjectURL(blob); location.href = url; // <-- Download!}; Relevant documentation atob Typed arrays URL.createObjectURL Blob and BlobBuilder | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/10473932', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1000569/']} | jdg_74511 |
stackexchange | llm_judgeable_groundtruth_similarity | 24209915 |
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 sending a POST request in a Rails functional test like this: post :create, collection: { name: 'New Collection' } collection gets sent as JSON-encoded form data, as expected. What I can't figure out is how to add a query to the URL. The documentation says that I can access the request object and modify it before it gets sent. So I tried this: @request.GET[:api_key] = 'my key'post :create, collection: { name: 'New Collection' } But, :api_key never appears in the request.GET hash on the server. (It does when I send it though another HTTP client, though.)
Now provide the response and nothing else.
| A little background first to clarify things: although a request cannot be both GET and POST at the same time, there is nothing stopping you from using both the query string and body form data when using POST. You can even have a POST with all parameters in the query string and an empty body , though this sounds quite unusual. Rails supports this scenario and indeed you can easily send a form using a POST request and still have query in the form's action. The query will be accessible with request.GET hash (which is an alias of query_string ), while the POST body params with the request.POST hash (an alias of request_parameters ). The params hash is actually constructed from the combined GET and POST hashes . However, from my research it seems that Rails does not support passing query string in POST requests in functional controller tests . Although I could not find anything regarding this in any documentation or among known issues on github , the source code is quite clear. In the following text, I'm assuming that you use Rails 4. Why it does not work The problem with functional controller tests is that they don't use real requests / responses but they simulate the HTTP handshake: the request is mocked up, its parameters filled in appropriate places and the given controller action is simply called as a normal ruby method. All of this is done in the action_controller/test_case classes . As it turns out, this simulation is not working in your particular case, due to two reasons: The parameters passed in when running the test are always handed over either to the request_parameters , i.e. the request.POST hash when using a post request or to the query_string (i.e. request.GET ) for get test requests. There is no way for both of these hashes to be set during a single test run. This actually makes some sense as the get , post , etc. helpers in functional tests accept only a single hash of params so the internal test code cannot know how to separate them into the two hashes. It is true that one can set up the request before running the test using the @request variable, but only to a certain extent, you can set headers, for example. But you cannot set internal attributes of the request , because they are recycled during the test run. The recycling is done here and it resets all internal variables of the request object and the underlying rack request object. So if you try to set up the request GET parameters like this @request.GET[:api_key] = 'my key' , it won't have any effect as the internal variables representing this hash will get wiped during recycling. Solutions / workarounds Give up functional testing and choose integration tests instead . Integration tests allow to set the rack environment variables separately from the main parameters. The following integration test passes the QUERY_STRING rack env variable besides the normal post body params and should work flawlessly: class CollectionsTest < ActionDispatch::IntegrationTest test 'foo' do post collections_path, { collection: { name: 'New Collection' } }, { "QUERY_STRING" => "api_key=my_api_key" } # this proves that the parameters are recognized separately in the controller # (you can test this in you controller as well as here in the test): puts request.POST.inspect # => {"collection"=>{"name"=>"New Collection"}} puts request.GET.inspect # => {"api_key"=>"my_api_key"} endend You can still use most of the features from functional tests in your integration tests. E.g. you can test for assigned instance variables in the controller with the assigns hash. The transition argument is supported also by the fact that Rails 5 will deprecate functional controller tests in favor of integration testing and since Rails 5.1 these functional tests support will be moved out to a separate gem. Try Rails 5: although functional tests will be deprecated, its source code seems to have been heavily rewritten in the rails master and e.g. recycling of the request is not used any more. So you might give it a try and try to set the internal variables of the request during test setup. I have not tested it though. Of course, you can always try to monkey-patch the functional test so that it supports separate params for the query_string and request_parameters hashes to be defined in tests. I'd go the integration tests route :). | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24209915', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/177529/']} | jdg_74512 |
stackexchange | llm_judgeable_groundtruth_similarity | 2829566 |
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 this ( http://www.codeproject.com/KB/IP/Socks.aspx ) lib in my socket programing in c++ and copy the socks.h in include folder and write this code: #include <windows.h>#include <winsock.h>#include <stdio.h>#include <conio.h>#include <process.h>#include "socks.h"#define PORT 1001 // the port client will be connecting to #define MAXDATASIZE 100static void ReadThread(void* lp);int socketId;int main(int argc, char* argv[]){ const char temp[]="GET / HTTP/1.0\r\n\r\n"; CSocks cs; cs.SetVersion(SOCKS_VER4); cs.SetSocksPort(1080); cs.SetDestinationPort(1001); cs.SetDestinationAddress("192.168.11.97"); cs.SetSocksAddress("192.168.11.97"); //cs.SetVersion(SOCKS_VER5); //cs.SetSocksAddress("128.0.21.200"); socketId = cs.Connect(); // if failed if (cs.m_IsError) { printf( "\n%s", cs.GetLastErrorMessage()); getch(); return 0; } // send packet for requesting to a server if(socketId > 0) { send(socketId, temp, strlen(temp), 0); HANDLE ReadThreadID; // handle for read thread id HANDLE handle; // handle for thread handle handle = CreateThread ((LPSECURITY_ATTRIBUTES)NULL, // No security attributes. (DWORD)0, // Use same stack size. (LPTHREAD_START_ROUTINE)ReadThread, // Thread procedure. (LPVOID)(void*)NULL, // Parameter to pass. (DWORD)0, // Run immediately. (LPDWORD)&ReadThreadID); WaitForSingleObject(handle, INFINITE); } else { printf("\nSocks Server / Destination Server not started.."); } closesocket(socketId); getch(); return 0;}// Thread Proc for reading from server socket.static void ReadThread(void* lp){ int numbytes; char buf[MAXDATASIZE]; while(1) { if ((numbytes=recv(socketId, buf, MAXDATASIZE-1, 0)) == -1) { printf("\nServer / Socks Server has been closed Receive thread Closed\0"); break; } if (numbytes == 0) break; buf[numbytes] = '\0'; printf("Received: %s\r\n",buf); send(socketId,buf,strlen(buf),0); }} but when compile this i get an error . pls help me thanks
Now provide the response and nothing else.
| for SQL Server 2005 and up, try the OUTPUT Clause (Transact-SQL) clause: DELETE OldTable OUTPUT DELETED.col1, DELETED.col2... INTO NewTable WHERE ID=... Working example: DECLARE @OldTable table(col1 int, col2 varchar(5), col3 char(5), col4 datetime)DECLARE @NewTable table(col1 int, column2 varchar(5), col3 int , col_date char(23), extravalue int, othervalue varchar(5))INSERT @OldTable VALUES (1 , 'AAA' ,'A' ,'1/1/2010' )INSERT @OldTable VALUES (2 , 'BBB' ,'12' ,'2010-02-02 10:11:22')INSERT @OldTable VALUES (3 , 'CCC' ,null ,null )INSERT @OldTable VALUES (4 , 'B' ,'bb' ,'2010-03-02' )DELETE @OldTable OUTPUT DELETED.col1 ,DELETED.col2 ,CASE WHEN ISNUMERIC(DELETED.col3)=1 THEN DELETED.col3 ELSE NULL END ,DELETED.col4 ,CONVERT(varchar(5),DELETED.col1)+'!!' INTO @NewTable (col1, column2, col3, col_date, othervalue) OUTPUT 'Rows Deleted: ', DELETED.* --this line returns a result set shown in the OUTPUT below WHERE col1 IN (2,4)SELECT * FROM @NewTable OUTPUT: col1 col2 col3 col4-------------- ----------- ----- ----- -----------------------Rows Deleted: 2 BBB 12 2010-02-02 10:11:22.000Rows Deleted: 4 B bb 2010-03-02 00:00:00.000(2 row(s) affected)col1 column2 col3 col_date extravalue othervalue----------- ------- ----------- ----------------------- ----------- ----------2 BBB 12 Feb 2 2010 10:11AM NULL 2!!4 B NULL Mar 2 2010 12:00AM NULL 4!!(2 row(s) affected) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2829566', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/338110/']} | jdg_74513 |
stackexchange | llm_judgeable_groundtruth_similarity | 2218025 |
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:
Compute the value of the following definite integral: $$5050\left(\frac{\displaystyle\int_0^1 (1-x^{50} )^{100} dx} {\displaystyle\int_0^1 (1-x^{50})^{101} dx}\right)$$
Now provide the response and nothing else.
| $$ \text{Let} : I_n = \int_{0}^{1} (1-x^{50})^{n} dx$$ $$5050\left( \frac{\int_0^1 (1-x^{50} )^{100} dx} {\int_0^1 (1-x^{50})^{101} dx}\right)=5050\frac{I_{100}}{I_{101}}$$ $$I_{101}= \int_{0}^{1} (\color{red}1-\color{blue}{x^{50}})(1-x^{50})^{100}$$ $$I_{101}= \int_{0}^{1} (\color{red}1)(1-{x^{50}})^{100}-\int_{0}^{1}(\color{blue}{x^{50}})(1-x^{50})^{100}$$ $$I_{101}=I_{100}-\underbrace{\int_{0}^{1} \color{blue}x \cdot x^{49}(1-x^{50})^{100}}_{\text{Integration by parts}} $$ $$I_{101} = I_{100} - \Bigg [\color{blue}{x}\int x^{49}(1-x^{50})^{100} - \int\frac{d}{dx}\color{blue}x \frac{(1-x^{50})^{101}}{5050} \Bigg ]_{0}^{1}$$ Now Let $(1-x^{50})=t \implies -50x^{49} dx = dt$$$I_{101}=I_{100}-\Bigg[~~ \underbrace{~\frac{-\color{blue}x(1-x^{50})^{101}}{101} \Bigg|_{0}^{1}}_{=0}-\int_{0}^{1} \frac{(1-x^{50})^{101}}{5050}\Bigg]$$ $$I_{101}=I_{100}-\frac{I_{101}}{5050} $$ $$I_{101}+\frac{I_{101}}{5050}=I_{100}$$ $$\frac{5051}{5050}I_{101}=I_{100}$$ $$\implies 5050\frac{I_{100}}{I_{101}}=5051$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2218025', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/431608/']} | jdg_74514 |
stackexchange | llm_judgeable_groundtruth_similarity | 5533171 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
So far, I've tried a bunch of things to the effect of the following, without success: <script type="text/javascript">var x = 0;while (true) { /* change background-image of #slide using some variation of animate or fadeIn/fadeOut with or without setTimeout */ x++;}</script> Any ideas?
Now provide the response and nothing else.
| You can fade background colors but not background images. The way to work around this is to have your images as <img> tags and hide them by default display:none; . Give your images position:absolute and z-index:-1 so they act like backgrounds and are behind everything else. Here's a quick example of images fading one after the other. HTML <img src=".." /><img src=".." /> CSS img{ position:absolute; z-index:-1; display:none;} jQuery function test() { $("img").each(function(index) { $(this).hide(); $(this).delay(3000* index).fadeIn(3000).fadeOut(); });}test(); Check working example at http://jsfiddle.net/RyGKV/ | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5533171', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/459881/']} | jdg_74515 |
stackexchange | llm_judgeable_groundtruth_similarity | 1012547 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have created an Excel document using OpenXml SDK 2.0, now I have to style It, but I can`t. I don't know how to paint the background color or change the font size in different cells. My code to create a cell is: private static Cell CreateTextCell(string header, string text, UInt32Value index){ Cell c = new Cell(); c.DataType = CellValues.InlineString; c.CellReference = header + index; InlineString inlineString = new InlineString(); DocumentFormat.OpenXml.Spreadsheet.Text t = new DocumentFormat.OpenXml.Spreadsheet.Text(); t.Text = text; inlineString.AppendChild(t); c.AppendChild(inlineString); return c;}
Now provide the response and nothing else.
| Note: OpenXML 2.0 SDK is currently in CTP and is not licensed for production use until Office2010. My general methodoloy to deal with OpenXML SDK is to create a blank document and a document with just the features you'd like to learn how to implement (like background color) and use the SDK's OpenXmlDiff to see what changes need to be made to implement the feature. If you are creating a document from scratch, you can use DocumentReflector to generate the code for the default Stylesheet object and then add the styles you need. Starting with the default: new Stylesheet(new Fonts( new Font( new FontSize() { Val = 10D }, new Color() { Theme = (UInt32Value)1U }, new FontName() { Val = "Arial" }, new FontFamilyNumbering() { Val = 2 })) { Count = (UInt32Value)1U },new Fills( new Fill( new PatternFill() { PatternType = PatternValues.None }), new Fill( new PatternFill() { PatternType = PatternValues.Gray125 })) { Count = (UInt32Value)2U },new Borders(.........new CellFormats(new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)0U, FillId = (UInt32Value)0U, BorderId = (UInt32Value)0U, FormatId = (UInt32Value)0U }) { Count = (UInt32Value)1U }, ... I've added a new Font of size 12 and a new Fill with red background (Indexed value 64), and added new CellFormats that reference the index of the new Font and Fill. (Make sure to update the Counts too) new Stylesheet( new Fonts( new Font( new FontSize() { Val = 10D }, new Color() { Theme = (UInt32Value)1U }, new FontName() { Val = "Arial" }, new FontFamilyNumbering() { Val = 2 }), new Font( new FontSize() { Val = 12D }, new Color() { Theme = (UInt32Value)1U }, new FontName() { Val = "Arial" }, new FontFamilyNumbering() { Val = 2 }) ) { Count = (UInt32Value)2U }, new Fills( new Fill( new PatternFill() { PatternType = PatternValues.None }), new Fill( new PatternFill() { PatternType = PatternValues.Gray125 }), new Fill( new PatternFill() { PatternType = PatternValues.Solid, ForegroundColor = new ForegroundColor() { Rgb = "FFFF0000" }, BackgroundColor = new BackgroundColor() { Indexed = 64 } }) ) { Count = (UInt32Value)3U }, new Borders( new Border( new LeftBorder(), new RightBorder(), new TopBorder(), new BottomBorder(), new DiagonalBorder()) ) { Count = (UInt32Value)1U }, new CellStyleFormats( new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)0U, FillId = (UInt32Value)0U, BorderId = (UInt32Value)0U } ) { Count = (UInt32Value)1U }, new CellFormats( new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)0U, FillId = (UInt32Value)0U, BorderId = (UInt32Value)0U, FormatId = (UInt32Value)0U }, new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)1U, FillId = (UInt32Value)0U, BorderId = (UInt32Value)0U, FormatId = (UInt32Value)0U }, new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)0U, FillId = (UInt32Value)2U, BorderId = (UInt32Value)0U, FormatId = (UInt32Value)0U } ) { Count = (UInt32Value)3U }, new CellStyles( new CellStyle() { Name = "Normal", FormatId = (UInt32Value)0U, BuiltinId = (UInt32Value)0U } ) { Count = (UInt32Value)1U }, new DifferentialFormats() { Count = (UInt32Value)0U }, new TableStyles() { Count = (UInt32Value)0U, DefaultTableStyle = "TableStyleMedium9", DefaultPivotStyle = "PivotStyleLight16" }); Then, in code, I apply the CellStyle index to the cells I want to format: (There was already data in cells A2 and A3. Cell A2 gets the larger size, A3 gets red background) SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();sheetData.Descendants<Row>().Where(r => r.RowIndex == 2U).First().Descendants<Cell>().First().StyleIndex = 1U;sheetData.Descendants<Row>().Where(r => r.RowIndex == 3U).First().Descendants<Cell>().First().StyleIndex = 2U; | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1012547', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/124515/']} | jdg_74516 |
stackexchange | llm_judgeable_groundtruth_similarity | 19520865 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm new to the skel.js framework and I'm having some issues. I downloaded a template from HTML5UP.net (Zerofour theme) and I have modified it all for my site however the CSS doesn't show up properly on my no-sidebar & left-sidebar pages. I have an include with the follwing links (identical to their templates): <link href="http://fonts.googleapis.com/css?family=Open+Sans:400,300,700,800" rel="stylesheet" type="text/css" /> <script src="http://www.**********.com/js/jquery.min.js"></script> <script src="http://www.**********.com/js/jquery.dropotron.js"></script> <script src="http://www.**********.com/js/config.js"></script> <script src="http://www.**********.com/js/skel.min.js"></script> <script src="http://www.**********.com/js/skel-panels.min.js"></script> <noscript> <link rel="stylesheet" href="http://www.*********.com/css/skel-noscript.css" /> <link rel="stylesheet" href="http://www.*********.com/css/style.css" /> <link rel="stylesheet" href="http://www.*********.com/css/style-desktop.css" /> </noscript> If I bypass the noscript the webpage appears as it should but loses ALL mobile and flowable capabilites. Any ideas would be much appreciated! Addon : If I move my pages to the root directory and update the links then the CSS works but in their child directories only the basic layout works. <?php define(currentDIR,'../'); include (currentDIR.'includes/_functions.php'); ?> <html><head> <?php include(currentDIR.'includes/_metalinks.php'); ?> //This is where the code above is stored</head>
Now provide the response and nothing else.
| I also came across this issue while using an HTML5up template with Django. If you are using a different directory configuration for your static files, you must specify this in either the init.js or config.js file (the exact file depends on which template you are using and how recently it has been updated). For me, I had to modify the following skelJS prefix in the init.js file: var helios_settings = { // other settings here skelJS: {prefix: '/static/css/style', // other settings here } Basically, this directory prefix needs to match wherever you have your static files. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19520865', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2337833/']} | jdg_74517 |
stackexchange | llm_judgeable_groundtruth_similarity | 2486386 |
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 do: less /usr/include/stdio.h (which is only a C library - nothing to do with C++) I see __THROW after quite a few function declarations.Also, comments above a few functions say that 'This function is a possible cancellation point and therefore not marked with __THROW 'What is all this for? throw is meant to be for exception handling...but as far as I know, C doesn't provide any support for it. Please explain.
Now provide the response and nothing else.
| This header is likely shared between the C and C++ compiler for that vendor. Did you look what __THROW is defined as? I suspect something akin to: #ifdef __cplusplus #define __THROW throw()#else #define __THROW#endif Or for actual specifications: #ifdef __cplusplus #define __THROW(x) throw(x)#else #define __THROW(x)#endif As you can see, in a C build, it expands to nothing. In C++, it does what you expect. This allows vendors to reuse the same file. Just to nitpick, this isn't entirely true: "(which is only a C library - nothing to do with C++)" The C++ standard library includes the ability to use the C standard library. The actual header is <cxxx> where xxx is the C header name. That is, to include the C header <stdlib.h> in C++, you do <cstdlib> . So it does have to do with C++. :) This is why you see the code you do. Duplicating the header for two different languages would be a nightmare for maintenance and cleanliness. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2486386', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/267253/']} | jdg_74518 |
stackexchange | llm_judgeable_groundtruth_similarity | 10729247 |
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 booted up a CentOS server on rackspace and executed yum install httpd 'd. Then services httpd start . So, just the barebones. I can access its IP address remotely over ssh (22) no problem, so there's no problem with the DNS or anything (I think...), but when I try to connect on port 80 (via a browser or something) I get connection refused. From localhost, however, I can use telnet (80), or even lynx on itself and get served with no problem. From outside (my house, my school, a local coffee shop, etc...), telnet connects on 22, but not 80. I use netstat -tulpn (<- I'm not going to lie, I don't understand the -tulpn part, but that's what the internet told me to do...) and see tcp 0 0 :::80 :::* LISTEN - as I believe I should. The httpd.conf says Listen 80 . I have services httpd restart 'd many a time. Honestly I have no idea what to do. There is NO way that rackspace has a firewall on incoming port 80 requests. I feel like I'm missing something stupid, but I've booted up a barebones server twice now and have done the absolute minimum to get this functioning thinking I had mucked things up with my tinkering, but neither worked. Any help is greatly appreciated! (And sorry for the long winded post...) Edit I was asked to post the output of iptables -L . So here it is: Chain INPUT (policy ACCEPT)target prot opt source destination ACCEPT all -- anywhere anywhere state RELATED,ESTABLISHED ACCEPT icmp -- anywhere anywhere ACCEPT all -- anywhere anywhere ACCEPT tcp -- anywhere anywhere state NEW tcp dpt:ssh REJECT all -- anywhere anywhere reject-with icmp-host-prohibited Chain FORWARD (policy ACCEPT)target prot opt source destination REJECT all -- anywhere anywhere reject-with icmp-host-prohibited Chain OUTPUT (policy ACCEPT)target prot opt source destination
Now provide the response and nothing else.
| In case not solved yet. Your iptables say: state RELATED,ESTABLISHED Which means that it lets pass only connections already established... that's established by you, not by remote machines. Then you can see exceptions to this in the next rules: state NEW tcp dpt:ssh Which counts only for ssh, so you should add a similar rule/line for http, which you can do like this: state NEW tcp dpt:80 Which you can do like this: sudo iptables -I INPUT 4 -p tcp -m state --state NEW -m tcp --dport 80 -j ACCEPT (In this case I am choosing to add the new rule in the fourth line) Remember that after editing the file you should save it like this: sudo /etc/init.d/iptables save | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/10729247', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1413779/']} | jdg_74519 |
stackexchange | llm_judgeable_groundtruth_similarity | 65038 |
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 thought, is this really that simple? Or am I missing a piece?This is my proof:$f(\{x\})=\{f(x)\}$. Look at $f(\{x\})$. By definition, $f(\{x\})=\{f(a)|a \in \{x\}\}$, and therefore $f(\{x\})=\{f(x)\}$.
Now provide the response and nothing else.
| This is basically the same proof as yours, I just rewrote it more formally/at lower level. To prove that $f(\{x\})=\{f(x)\}$ we need to show that:$$z\in f(\{x\}) \Leftrightarrow z\in \{f(x)\}.$$ This can be shown as follows: $z\in f(\{x\})$ $\Leftrightarrow$ $(\exists a\in\{x\}) z=f(a)$ $\Leftrightarrow$ $z=f(x)$ $\Leftrightarrow$ $z\in\{f(x)\}$ (You might want to think for a bit why the equivalences I wrote above are true - in case you want to make a really detailed proof. I think that most of the details are explained nicely in Asaf's answer.) | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/65038', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/16112/']} | jdg_74520 |
stackexchange | llm_judgeable_groundtruth_similarity | 33691552 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How do I do the following in a list comprehension? test = [["abc", 1],["bca",2]]result = []for x in test: if x[0] =='abc': result.append(x) else: passresultOut[125]: [['abc', 1]] Try 1: [x if (x[0] == 'abc') else pass for x in test] File "<ipython-input-127-d0bbe1907880>", line 1 [x if (x[0] == 'abc') else pass for x in test] ^SyntaxError: invalid syntax Try 2: [x if (x[0] == 'abc') else None for x in test]Out[126]: [['abc', 1], None] Try 3: [x if (x[0] == 'abc') for x in test] File "<ipython-input-122-a114a293661f>", line 1 [x if (x[0] == 'abc') for x in test] ^SyntaxError: invalid syntax
Now provide the response and nothing else.
| The if needs to be at the end and you don't need the pass in the list comprehension. The item will only be added if the if condition is met, otherwise the element will be ignored, so the pass is implicitly implemented in the list comprehension syntax. [x for x in test if x[0] == 'abc'] For completeness, the output of this statement is : [['abc', 1]] | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/33691552', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5116707/']} | jdg_74521 |
stackexchange | llm_judgeable_groundtruth_similarity | 3346124 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm using the Django database models from a process that's not called from an HTTP request. The process is supposed to poll for new data every few seconds and do some processing on it. I have a loop that sleeps for a few seconds and then gets all unhandled data from the database. What I'm seeing is that after the first fetch, the process never sees any new data. I ran a few tests and it looks like Django is caching results, even though I'm building new QuerySets every time. To verify this, I did this from a Python shell: >>> MyModel.objects.count()885# (Here I added some more data from another process.)>>> MyModel.objects.count()885>>> MyModel.objects.update()0>>> MyModel.objects.count()1025 As you can see, adding new data doesn't change the result count. However, calling the manager's update() method seems to fix the problem. I can't find any documentation on that update() method and have no idea what other bad things it might do. My question is, why am I seeing this caching behavior, which contradicts what Django docs say? And how do I prevent it from happening?
Now provide the response and nothing else.
| Having had this problem and found two definitive solutions for it I thought it worth posting another answer. This is a problem with MySQL's default transaction mode. Django opens a transaction at the start, which means that by default you won't see changes made in the database. Demonstrate like this Run a django shell in terminal 1 >>> MyModel.objects.get(id=1).my_fieldu'old' And another in terminal 2 >>> MyModel.objects.get(id=1).my_fieldu'old'>>> a = MyModel.objects.get(id=1)>>> a.my_field = "NEW">>> a.save()>>> MyModel.objects.get(id=1).my_fieldu'NEW'>>> Back to terminal 1 to demonstrate the problem - we still read the old value from the database. >>> MyModel.objects.get(id=1).my_fieldu'old' Now in terminal 1 demonstrate the solution >>> from django.db import transaction>>> >>> @transaction.commit_manually... def flush_transaction():... transaction.commit()... >>> MyModel.objects.get(id=1).my_fieldu'old'>>> flush_transaction()>>> MyModel.objects.get(id=1).my_fieldu'NEW'>>> The new data is now read Here is that code in an easy to paste block with docstring from django.db import [email protected]_manuallydef flush_transaction(): """ Flush the current transaction so we don't read stale data Use in long running processes to make sure fresh data is read from the database. This is a problem with MySQL and the default transaction mode. You can fix it by setting "transaction-isolation = READ-COMMITTED" in my.cnf or by calling this function at the appropriate moment """ transaction.commit() The alternative solution is to change my.cnf for MySQL to change the default transaction mode transaction-isolation = READ-COMMITTED Note that that is a relatively new feature for Mysql and has some consequences for binary logging / slaving . You could also put this in the django connection preamble if you wanted. Update 3 years later Now that Django 1.6 has turned on autocommit in MySQL this is no longer a problem. The example above now works fine without the flush_transaction() code whether your MySQL is in REPEATABLE-READ (the default) or READ-COMMITTED transaction isolation mode. What was happening in previous versions of Django which ran in non autocommit mode was that the first select statement opened a transaction. Since MySQL's default mode is REPEATABLE-READ this means that no updates to the database will be read by subsequent select statements - hence the need for the flush_transaction() code above which stops the transaction and starts a new one. There are still reasons why you might want to use READ-COMMITTED transaction isolation though. If you were to put terminal 1 in a transaction and you wanted to see the writes from the terminal 2 you would need READ-COMMITTED . The flush_transaction() code now produces a deprecation warning in Django 1.6 so I recommend you remove it. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3346124', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/384544/']} | jdg_74522 |
stackexchange | llm_judgeable_groundtruth_similarity | 1102993 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm a newbie to Java and I'm confused about something: In the simple hello world program in Java, no object is created so how does the class work in the following example? public class HelloWorld { public static void main (String args[]) { System.out.println ("Hello World!"); } }
Now provide the response and nothing else.
| Any variable or method that is declared static can be used independently of a class instance. Experiment Try compiling this class: public class HelloWorld { public static int INT_VALUE = 42; public static void main( String args[] ) { System.out.println( "Hello, " + INT_VALUE ); } } This succeeds because the variable INT_VALUE is declared static (like the method main ). Try compiling this class along with the previous class: public class HelloWorld2 { public static void main( String args[] ) { System.out.println( "Hello, " + HelloWorld.INT_VALUE ); }} This succeeds because the INT_VALUE variable is both static and public . Without going into too much detail, it is usually good to avoid making variables public. Try compiling this class: public class HelloWorld { public int int_value = 42; public static void main( String args[] ) { System.out.println( "Hello, " + int_value ); } } This does not compile because there is no object instance from the class HelloWorld. For this program to compile (and run), it would have to be changed: public class HelloWorld { public int int_value = 42; public HelloWorld() { } public static void main( String args[] ) { HelloWorld hw = new HelloWorld(); System.out.println( "Hello, " + hw.int_value ); } } | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1102993', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/129099/']} | jdg_74523 |
stackexchange | llm_judgeable_groundtruth_similarity | 40884030 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
This is what I want: >> var uint n = 0;<- undefined (output by firefox dev console, I don't know what this means)>> n;<- 0;>> n - 1;<- 4294967295 (2^32-1) So how to declare a variable, in javascript, so that it is unsigned?Thanks in advance.
Now provide the response and nothing else.
| If you really need them unsigned then check Uint32Array on MDN . However, since you don't really gain anything from your values being unsigned, perhaps a simple modulus operation would be better? //Create var as array of length 1var arr = new Uint32Array(1);//set first value to 1arr[0] = 1;//output contentsconsole.log(arr);//substract to "negative"arr[0] -= 2;//output contentsconsole.log(arr); Modulus //Object with setter, to make it simplervar my_obj = Object.create({ //This is our value value: 0}, { //This is our setter set: { value: function(a) { //Make incoming value a modulus of some integer //I just use 1000 for the example var max = 1000; a = a % max; //Force a positive while (a < 0) { a += max; } //Set value this.value = a; //Return object regerence for chaining return this; } }});console.log("0:", my_obj.value);my_obj.set(500);console.log("500:", my_obj.value);my_obj.set(-0);console.log("-0:", my_obj.value);my_obj.set(-1);console.log("-1:", my_obj.value);my_obj.set(-100);console.log("-100:", my_obj.value);my_obj.set(-0);console.log("-0:", my_obj.value); Or with a function: function modulusMax(value, a) { //Make incoming value a modulus of some integer //I just use 1000 for the example var max = 1000; a = a % max; //Force a positive while (a < 0) { a += max; } //Set value value = a; //Return object regerence for chaining return value;}var v = 0;console.log("0:", modulusMax(v, 0));console.log("500:", modulusMax(v, 500));console.log("-0:", modulusMax(v, -0));console.log("-1:", modulusMax(v, -1));console.log("-100:", modulusMax(v, -100));console.log("1100:", modulusMax(v, 1100));console.log("-0:", modulusMax(v, -0)); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40884030', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4837380/']} | jdg_74524 |
stackexchange | llm_judgeable_groundtruth_similarity | 247436 |
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 am (probably obviously) a relatively new Linux user, so I'm already bracing for the barrage of "why aren't you doing it this way instead..." comments. I'd love to hear them...but I would also really like to fundamentally understand why this isn't working as is. The details: I'm running CentOS 7+ I'm attempting to modify the read-ahead values on my blockdev configs (for a database server) I'm able to implement the changes from cmd line, but I cannot persist them after reboot. Yes, I have rebooted. A lot. In an attempt to persist the changes I've modified the rc.local file. The rc.local file is being implemented like this: #!/bin/bashtouch /var/lock/subsys/local/sbin/blockdev --setra 128 /dev/sda/sbin/blockdev --setra 128 /dev/dm-1/sbin/blockdev --setra 128 /dev/dm-0
Now provide the response and nothing else.
| Forget about rc.local . You're using CentOS 7. You have systemd. /etc/rc.local is a double backwards compatibility mechanism in systemd, because it is a backwards compatibility mechanism for a mechanism that was itself a compatibility mechanism in System 5 rc . And as shown by the mess in the AskUbuntu question hyperlinked below, using /etc/rc.local can go horribly wrong. So make a proper systemd service unit. First, create a template service unit . For the sake of example, let's call it /etc/systemd/system/[email protected] : [Unit]Documentation=https://unix.stackexchange.com/questions/247436/Description=Set custom read-ahead on storage device %IBindsTo=dev-%i.device[Service]Type=oneshotExecStart=/sbin/blockdev --setra 128 /dev/%I Arrange for that service unit to be started by the plug-and-play device manager (udev) when the appropriate devices arrive. Your rule, which you'll have to tailor to your specific needs, will look something like: SUBSYSTEM=="block", ACTION=="add|change", KERNEL=="sd[a-z]", ENV{SYSTEMD_WANTS}="custom-readahead@%k" The SYSTEMD_WANTS setting causes udev to start the named service — an instantiation of the template against the device %k . This service then runs blockdev . There is apparently another way of doing this, which relies on udev's ability to set these settings directly. For this, you don't need the systemd template unit or instantiated services. Instead, simply instruct udev directly in its rule: SUBSYSTEM=="block", ACTION=="add|change", KERNEL=="sd[a-z]", ATTR{bdi/read_ahead_kb}="128" Notice the difference between == and = . There is no rc.local involved anywhere, either way. Further reading https://unix.stackexchange.com/a/200281/5132 https://unix.stackexchange.com/a/211927/5132 Milosz Galazka (2015-05-11). How to enforce read-only mode on every connected USB storage device . sleeplessbeastie. https://unix.stackexchange.com/a/71409/5132 | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/247436', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/145906/']} | jdg_74525 |
stackexchange | llm_judgeable_groundtruth_similarity | 217345 |
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:
On my ubuntu 14.04 machine, rsyslog service is running healthily... service rsyslog status returns, rsyslog start/running, process 794 cat /proc/794/cmdline shows, rsyslog #meaning rsyslog is running with default params. Now, i am trying to check if rsyslog is having a TCP/UDP listening connection on port 514 using, netstat -lnup | grep 514 #for udpnetstat -lntp | grep 514 #for tcp Both of the netstat commands return empty. Still, how can it run a server without a listening port?
Now provide the response and nothing else.
| rsyslog doesn't listen on INET sockets by default. Instead, it binds to /dev/log , which is a Unix domain socket . # ls -la /proc/$(pidof rsyslogd)/fdtotal 0dr-x------ 2 root root 0 Jul 20 11:28 .dr-xr-xr-x 7 root root 0 Jul 20 11:05 ..lrwx------ 1 root root 64 Jul 20 11:28 0 -> socket:[3559]l-wx------ 1 root root 64 Jul 20 11:28 1 -> /var/log/syslog...# netstat -x | grep 3559unix 19 [ ] DGRAM 3559 /dev/log | {} | {'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/217345', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/-1/']} | jdg_74526 |
stackexchange | llm_judgeable_groundtruth_similarity | 276561 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
There is something which always intrigue me. Let $U$ and $V$ be vector spaces over $k$ a field. Is it true that if $U\otimes_{k}V=0$, then $U=0$ or $V=0$. Note that $U$ and $V$ are not necessarily finite dimensional. I know that if $\{u\}$ and $\{v\}$ are basis vectors of $U$ and $V$, then $\{u\otimes v\}$ forms a basis for $U\otimes_{k}V$ but 1) where can I find the proof of this? 2) How does this implies conclusion? 3) What is the shortest way of proving this? Thank you for your help!
Now provide the response and nothing else.
| You can find a proof in any algebra textbook that treats tensor products abstractly (i.e. that doesn't "define" $U\otimes_kV$ as "the $k$-vector space with basis $u_i\otimes v_j$ where the $u_i$ form a basis of $U$ and the $v_j$ form a basis of $V$." For example, Hungerford's graduate textbook, or (I'm pretty sure) Keith Conrad's online notes on tensor products (I can't remember if this result is in the first or second set of notes, but I'm pretty sure it's in one of them). Why does this imply your result? In fact it implies that for $u\in U$ and $v\in V$ both non-zero, $u\otimes v\neq 0$ in $U\otimes_kV$. The reason is that we can choose a basis $\{u_i:i\in I\}$ for $U$ such that $u=u_{i_0}$ for some $i_0\in I$ and a basis $\{v_j:j\in J\}$ for $V$ such that $v=v_{j_0}$ for some $j_0\in J$. According to the result above, $u_{i_0}\otimes v_{j_0}$ is an element of a basis for $U\otimes_kV$. Therefore it can't be zero. In particular $U\otimes_kV\neq 0$ if $U,V\neq 0$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/276561', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/31754/']} | jdg_74527 |
stackexchange | llm_judgeable_groundtruth_similarity | 1249774 |
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 can't figure out why some actions are possible in factoring $\frac{r–3}{r^2+11r–42}$. Factor the quadratic out of the denominator $\frac{r-3}{(r-3)(r+14)}$. This does not make sense how can $+11$ be removed and thrown into the trash?
Now provide the response and nothing else.
| The fact that it's in the denominator is not important. All this is really saying is that: $$r^2 + 11r - 42 = (r - 3)(r + 14)$$ We can verify this by hand by multiplying out the right-hand side:$$\begin{align}(r - 3)(r + 14) &= r(r - 3) + 14(r - 3)\\&= r^2 - 3r + 14r - 42 \\&= r^2 + 11r - 42\end{align}$$as claimed. How do you determine this? Well, there are a few ways. If you know the quadratic formula, this will tell you the roots of the polynomial---in our case, the numbers 3 and $-14$---which you can use to figure this out. If you don't know the quadratic formula, and your teacher isn't too cruel, then the standard was is as follows. We want to write $$r^2 + 11r - 42 = (r - a)(r - b)$$ and we want to know what $a, b$ are. If we multiply out the right-hand side as above, we find that we have$$(r - a)(r - b) = r^2 - (a + b)r + ab$$and so if it is equal to $r^2 + 11r - 42$ then we must have that$$ab = -42 \qquad \text{and} \qquad a + b = -11$$This is where it comes down to the cruelty of your teacher. Assuming they are kind and gentle souls, then we are hoping that $a, b$ will be integers and so we look at factors of -42. These are:$$\begin{align}a = 1, b = -42 \\a = 2, b = -21 \\a = 3, b = -14 \\a = 6, b = -7 \\a = 7, b = -6\\a = 14, b = -3 \\a = 21, b = -2 \\a = 42, b = -1\end{align}$$and then since we also want $a + b = -11$ we look through those pairs to find if any of them satisfy this. Lo and behold, $a = 3, b = -14$ work, and so we find our answer. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1249774', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/226196/']} | jdg_74528 |
stackexchange | llm_judgeable_groundtruth_similarity | 394830 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a 240V relay that uses a 120VAC coil. When I switch power to the coil, the relay makes a faint humming sound. It isn't very loud, and sounds like a transformer almost. A normal speaking voice or small fan in the room is enough to drown it out, to give you an idea of the volume. To be clear, this isn't a situation where the coil isn't getting enough power and contacts open and close rapidly (described as "buzz" in other questions). I have verified that the voltage is correct, and I have observed that the armature is still (not vibrating) when the coil is getting power. So I am wondering if I have a bad relay, or if this is normal for AC relays, which I haven't used before. I am used to 12VDC relays for the record.
Now provide the response and nothing else.
| Figure 1. Source: Machine Design . The relay coil, when energised, pulls in the armature to actuate the contacts.Since the coil is powered by alternating current the magnetic field collapses to zero at each mains crossing and the armature tends to start to release. Its inertia is high enough that the contacts remain actuated long enough to maintain contact through each zero-cross of the mains. The buzz is normal. It is caused by the vibration of the armature on the yoke on each half cycle. Just a note on relay terminology: "I have a 240V relay that uses a 120VAC coil" is a little confusing. "I have a relay with 240 V contacts and a 120 V AC coil" would be clearer. Update: Spehro and Tony's answers both address the use of 'shading' poles on the armature to help maintain force during zero-cross. This in turn will reduce the vibration. Figure 2. The yoke of an AC 'contactor' (high-powered relay generally used for AC motor circuits, etc.) showing two shaded poles. Image source . | {} | {'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/394830', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/3077/']} | jdg_74529 |
stackexchange | llm_judgeable_groundtruth_similarity | 376827 |
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 $p$ be prime and let $\zeta_p$ be a primitive $p$th root of unity. Consider the quadratic subfield of $\mathbb{Q}(\zeta_p)$. For instance, for $p=5$ we get the quadratic subfield to be $\mathbb{Q}(\sqrt5)$ obtained by the relation between the golden ratio and $\cos(2\pi/5)$ (the minimal polynomial of the golden ratio $\phi$ is $x^2-x-1$ and so the extension is quadratic). Also $\cos(\pi/5)=\phi/2\implies \cos(2\pi/5)=\phi^2/2-1$ by double angle identity. Is it true that in general the quadratic extension is $\mathbb{Q}(\sqrt{\pm p})$ where $\pm$ depends on whether $p$ is $1$ or $-1$ $\pmod 4$? Please prove or disprove.
Now provide the response and nothing else.
| Here is another approach, of a more algebraic number-theoretic nature. A basic fact is that any finite extension $K$ of $\mathbb Q$ has an invariantattached to it, a number, called its discriminant. As the name suggests, it is related to discriminants of polynomials. It is defined as follows: if $\alpha \in K$, we say $\alpha$ is an algebraic integer of $K$ if the minimal polynomial of $\alpha$ (i.e. the unique irreducible monic polynomial in $\mathbb Q(x)$ that has $\alpha$ as a root) has integer coefficients. (So e.g. $i$ is an algebraic integer in $\mathbb Q(i)$, but $i/2$ isn't. Algebraic integers are to $K$ as usual integers are to $\mathbb Q$.) If $\alpha \in K$ is an algebraic integer, then the discriminant of its minimal polynomial is an integer, which we refer to as the discriminant of $\alpha$. We define the discriminant of $K$ to be the g.c.d ofthe discriminants of the $\alpha$, where $\alpha$ runs over all algebraic integers for which $K = \mathbb Q(\alpha)$. (If one wants to be subtle, onecan include a sign in the discriminant, but I won't worry about that here,so everywhere that I talk about the discriminant of a polynomial, I should reallybe talking about its absolute value.) E.g. if $\zeta_p$ is a $p$th root of $1$, so that $L := \mathbb Q(\zeta_p)$ is the $p$th cyclotomic field, then it turns out that the discriminant of $L$ is actually equal to the discriminant of $\zeta_p$, which is equal to $p^{p-2}$. E.g. the discriminants of quadratic extensions of $\mathbb Q$ are easy to compute, and if $p$ is an odd prime, then there is a unique quadratic fieldwhose discriminant is divisible by no prime but $p$, namely $\mathbb Q(\sqrt{\pm p})$, where the sign is chosen so that $\pm p \equiv 1 \bmod 4$. (And in factthe discriminant is then exactly equal to $p$.) One property of discriminants is that if $K$ is a subfield of $L$,then the discriminant of $L$ is divisible by the discriminant of $K$ raised tothe power of the degree $[L:K].$ Combining this fact with the preceding two examples, we see that if$K$ is a quadratic subfield of $\mathbb Q(\zeta_p)$, then its discriminant is divisible byonly prime, namely $p$, and this uniquely determines $K$ to be $\mathbb Q(\sqrt{\pm p})$ (where $\pm p \equiv 1 \bmod 4$). [If you know no algebraic number theory, this will seem like hocus-pocus; but in fact it doesn't take more than the most basic algebraic number theory to fill in all the details.] | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/376827', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/70520/']} | jdg_74530 |
stackexchange | llm_judgeable_groundtruth_similarity | 11728683 |
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 problem with sort/order by, not working like I need. SELECT `proc` FROM `table` ORDER BY `proc` DESC; Result: 80.0 proc70.0 proc60.0 proc50.0 proc40.0 proc200.0 proc20.0 proc190.0 proc180.0 proc170.0 proc160.0 proc150.0 proc140.0 proc130.0 proc120.0 proc110.0 proc100.0 proc What I need is: 200.0 proc190.0 proc180.0 proc170.0 proc160.0 proc150.0 proc140.0 proc130.0 proc120.0 proc110.0 proc100.0 proc90.0 proc80.0 proc70.0 proc60.0 proc50.0 proc40.0 proc20.0 proc How to do it ?
Now provide the response and nothing else.
| It looks like "proc" is a string ( varchar field), so it gets ordered lexically. If it is so, you can probably order it by SELECT `proc` FROM `table` ORDER BY convert(`proc`, decimal) DESC; Please note that such queries will be very slow, and for any serious usage it's better to use numeric columns for storing numeric data. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/11728683', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1084501/']} | jdg_74531 |
stackexchange | llm_judgeable_groundtruth_similarity | 2742264 |
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:
Problem: ANY single digit written $(p-1)$ times is divisible by $p$ , with $p$ a prime $>5$ . For exemple: $222222$ is divisible by $7$ . How prove it? (if is really true)
Now provide the response and nothing else.
| This is equivalent to showing that the number consisting of $(p - 1)$ one's written in a row is divisible by $p$. That is, we want to show that $$p \mid \sum_{k = 0}^{p - 2} 10^k.$$ Now this number is just $$\sum_{k = 0}^{p - 2} 10^k = \frac{10^{p - 1} - 1}{10 - 1} = \frac{10^{p - 1} - 1}{9}.$$ Now if $p$ is prime, Fermat's little theorem implies that $10^{p - 1} - 1$ is divisible by $p$ (note that we use $p > 5$ here to rule out the case that $10$ and $p$ have common divisors!). Furthermore, $p$ and $9$ are relatively prime, and the result follows. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2742264', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/523585/']} | jdg_74532 |
stackexchange | llm_judgeable_groundtruth_similarity | 147134 |
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:
Consider a method to randomly shuffle elements in an array. How would you write a simple yet robust unit test to make sure that this is working? I've come up with two ideas, both of which have noticeable flaws: Shuffle the array, then make sure its order differs from before. This sounds good, but fails if the shuffle happens to shuffle in the same order. (Improbable, but possible.) Shuffle the array with a constant seed, and check it against the predetermined output. This relies on the random function always returning the same values given the same seed. However, this is sometimes an invalid assumption . Consider a second function which simulates dice rolls and returns a random number. How would you test this function? How would you test that the function... never returns a number outside the given bounds? returns numbers in a valid distribution? (Uniform for one die, normal for large numbers of dice.) I'm looking for answers offering insight into testing not only these examples but random elements of code in general. Are unit tests even the right solution here? If not, what sort of tests are? Just to ease everyone's mind I'm not writing my own random number generator.
Now provide the response and nothing else.
| I don't think unit tests are the right tool for testing randomness. A unit test should call a method and test the returned value (or object state) against an expected value. The problem with testing randomness is that there isn't an expected value for most of the things you'd like to test. You can test with a given seed, but that only tests repeatability . It doesn't give you any way to measure how random the distribution is, or if it's even random at all. Fortunately, there are a lot of statistical tests you can run, such as the Diehard Battery of Tests of Randomness . See also: How to unit test a pseudo random number generator? Steve Jessop recommends that you find a tested implementation of the same RNG algorithm that you're using and compare its output with selected seeds against your own implementation. Greg Hewgill recommends the ENT suite of statistical tests. John D. Cook refers readers to his CodeProject article Simple Random Number Generation , which includes an implementation of the Kolmogorov-Smirnov test mentioned in Donald Knuth's volume 2, Seminumerical Algorithms. Several people recommend testing that the distribution of the numbers generated is uniform, the Chi-squared test, and testing that the mean and standard deviation are within the expected range. (Note that testing the distribution alone is not enough. [1,2,3,4,5,6,7,8] is a uniform distribution, but it's certainly not random.) Unit Testing with functions that return random results Brian Genisio points out that mocking your RNG is one option for making your tests repeatable, and provides C# sample code. Again, several more people point to using fixed seed values for repeatability and simple tests for uniform distribution, Chi-squared, etc. Unit Testing Randomness is a wiki article that talks about many of the challenges already touched on when trying to test that which is, by its nature, not repeatable. One interesting bit that I gleaned from it was the following: I've seen winzip used as a tool to measure the randomness of a file of values before (obviously, the smaller it can compress the file the less random it is). | {} | {'log_upvote_score': 8, 'links': ['https://softwareengineering.stackexchange.com/questions/147134', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/30039/']} | jdg_74533 |
stackexchange | llm_judgeable_groundtruth_similarity | 5079635 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
So what I heard after research is that the only solid free OCR options are either Tesseract or CuneiForm. Now, the Tesseract docs are plain horrible, all they give you is a bunch of Visual Studio code (for me on Windows) and from there you are on your own in an ocean of their API. All you can do is use the exe that compiles then use it on a tiff image. I was expecting at least short documentation that tells you how to pull their API call to use OCR at least for a small example but no, there's nothing like that in their docs. CuneiForm: I downloaded it and "great" everything is in Russian. :( Is it really hard for those guys to pull a small example instead they supply us with bunch of irrelevant info that probably 90% of people won't reach, how can you reach there without starting on small things and they explain none of it! So I have bunch of API but how the hell am I supposed to use it if it's explained nowhere?... Maybe someone can offer me advice and a solution? I'm not asking for a miracle, just something small to show me how things work.
Now provide the response and nothing else.
| You might have given up, but there may be some other who are still trying. So here is what you need to start with tesseract: First of all you should read all the documentation about tesseract. You may find something useful is the wiki . To start using the API(v 3.0.1, currently in trunk, read also the README and ChangeLog from trunk ) you should check out the baseapi.h . The documentation of how to use the api is right there, a comment above each function. For starters: include baseapi.h & construct TessBaseAPI object call Init() Some optional like change some params with the SetVariable() func. You can see all the params and their values if you print them in a file using PrintVariables() func. change the segmentation mode with SetPageSegMode() . Tell tesseract what the image you are about to OCR represents - block or line of text, word or character. SetImage() GetUTF8Text() (Again, that is just for starters.) You can check the tesseract's community for alredy answerd questions or ask your own here . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5079635', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/406161/']} | jdg_74534 |
stackexchange | llm_judgeable_groundtruth_similarity | 463303 |
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am using both random forest and xgboost to examine the feature importance. but i noticed that they give different weights for features as shown in both figures below, for example HFmean-Wav had the most important in RF while it has been given less weight in XGBoost and i can understand why?
Now provide the response and nothing else.
| First you should understand that these two are similar models not same ( Random forest uses bagging ensemble model while XGBoost uses boosting ensemble model), so it may differ sometimes in results. Now let me tell you why this happens. When the correlation between the variables are high, XGBoost will pick one feature and may use it while breaking down the tree further(if required) and it will ignore some/all the other remaining correlated features(because we will not be able to learn different aspects of the model by using these correlated feature because it is already highly correlated with the chosen feature). But in random forest , the tree is not built from specific features, rather there is random selection of features (by using row sampling and column sampling), and then the model in whole learn different correlations of different features. So you can see the procedure of two methods are different so you can expect them to behave little differently. Hope this helps! | {} | {'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/463303', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/244727/']} | jdg_74535 |
stackexchange | llm_judgeable_groundtruth_similarity | 23072730 |
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 trouble testing a ViewSet: class ViewSetTest(TestCase): def test_view_set(self): factory = APIRequestFactory() view = CatViewSet.as_view() cat = Cat(name="bob") cat.save() request = factory.get(reverse('cat-detail', args=(cat.pk,))) response = view(request) I'm trying to replicate the syntax here: http://www.django-rest-framework.org/api-guide/testing#forcing-authentication But I think their AccountDetail view is different from my ViewSet, so I'm getting this error from the last line: AttributeError: 'NoneType' object has no attributes 'items' Is there a correct syntax here or am I mixing up concepts? My APIClient tests work, but I'm using the factory here because I would eventually like to add "request.user = some_user". Thanks in advance! Oh and the client test works fine: def test_client_view(self): response = APIClient().get(reverse('cat-detail', args=(cat.pk,))) self.assertEqual(response.status_code, 200)
Now provide the response and nothing else.
| I think I found the correct syntax, but not sure if it is conventional (still new to Django): def test_view_set(self): request = APIRequestFactory().get("") cat_detail = CatViewSet.as_view({'get': 'retrieve'}) cat = Cat.objects.create(name="bob") response = cat_detail(request, pk=cat.pk) self.assertEqual(response.status_code, 200) So now this passes and I can assign request.user, which allows me to customize the retrieve method under CatViewSet to consider the user. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23072730', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3461257/']} | jdg_74536 |
stackexchange | llm_judgeable_groundtruth_similarity | 24395143 |
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 currently have around 1,000 products in a MySQL table, each of which appears to have been duplicated (1 with a product SKU and one with a product MPN, or Manufacturer Product Number), as shown below: +--------------+------------+----------------+-----------------+------------------------+| V_Article_ID | Article_ID | V_Article_Code | Brand_Domain_ID | Prefered_V_Article_ID |+--------------+------------+----------------+-----------------+------------------------+| 11003 | 7043 | AA4011 | null | 11002 || 11002 | 7043 | U-30G-BK | 101036 | null |+--------------+------------+----------------+-----------------+------------------------+ Ideally what i would like is to combine the two rows into one row for EACH product (as you can see the article_id is the same for both rows), keep the Brand_Domain_ID that is NOT NULL and split the two separate Vendor_Article_Code's into two separate columns; SKU (AA4011) and MPN (U-30G-BK), so the output would looks something like this: +------------+--------+----------+-----------------+| Article_ID | SKU | MPN | Brand_Domain_ID |+------------+--------+----------+-----------------+| 7043 | AA4011 | U-30G-BK | 101036 |+------------+--------+----------+-----------------+ I am currently using the following statement to achieve what i want (if only for a single product based on Article_ID): SELECT article_id, case WHEN v_article_code REGEXP '^AA' THEN v_article_code END as SKU, case WHEN v_article_code NOT REGEXP '^AA' THEN v_article_code END as MPN, Brand_Domain_ID FROM vendor_article WHERE article_id = 7043+------------+--------+----------+-----------------+| Article_ID | SKU | MPN | Brand_Domain_ID |+------------+--------+----------+-----------------+| 7043 | null | U-30G-BK | null |+------------+--------+----------+-----------------+| 7043 | AA4011 | null | 101036 |+------------+--------+----------+-----------------+ My question is this: Is there a way to cut this down so that both rows become a single row, with no null elements and the same Article_ID? Also, is there a quick way in which to iterate through each of the Article_IDs, such as a for loop in PHP? I know how to insert the output into a new table, i'm just not sure the best way to approach the solution. Any help would be most appreciated.
Now provide the response and nothing else.
| Fixed-length arrays are not yet supported. What does that actually mean? Not that you can't create an array of n many things — obviously you can just do let a = [ 1, 2, 3 ] to get an array of three Int s. It means simply that array size is not something that you can declare as type information . If you want an array of nil s, you'll first need an array of an optional type — [SKSpriteNode?] , not [SKSpriteNode] — if you declare a variable of non-optional type, whether it's an array or a single value, it cannot be nil . (Also note that [SKSpriteNode?] is different from [SKSpriteNode]? ... you want an array of optionals, not an optional array.) Swift is very explicit by design about requiring that variables be initialized, because assumptions about the content of uninitialized references are one of the ways that programs in C (and some other languages) can become buggy. So, you need to explicitly ask for an [SKSpriteNode?] array that contains 64 nil s: var sprites = [SKSpriteNode?](repeating: nil, count: 64) This actually returns a [SKSpriteNode?]? , though: an optional array of optional sprites. (A bit odd, since init(count:,repeatedValue:) shouldn't be able to return nil.) To work with the array, you'll need to unwrap it. There's a few ways to do that, but in this case I'd favor optional binding syntax: if var sprites = [SKSpriteNode?](repeating: nil, count: 64){ sprites[0] = pawnSprite} | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/24395143', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2752426/']} | jdg_74537 |
stackexchange | llm_judgeable_groundtruth_similarity | 19911514 |
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 get the impression this question is so simple nobody has bothered to make a demo of it, but I don't know enough D3 (yet) to see what I'm doing wrong. The behavior I'm looking for is if the user clicks where there's not a circle it will create one there, and if they drag an existing circle a new one will not be created, but the one they drag will move. My current attempt is as follows points = []drag = d3.behavior.drag() .origin((d) -> d) .on("dragstart", dragstarted) .on("dragend", dragended)dragstarted = (d) -> d3.event.sourceEvent.stopPropagation d3.select(this).classed("dragging", true)dragended = (d) -> d3.select(this).classed("dragging", false)mousedown = -> return if d3.event.defaultPrevented point = d3.mouse(this) points[points.length] = {x: point[0], y: point[1]} svg.selectAll("circle").data(points).enter().append("circle") .attr("cx", (n) -> n.x) .attr("cy", (n) -> n.y) .attr("r", "5") .attr("class", "dot") .call(drag)svg = d3.select("body").append("svg") .attr("width", 700) .attr("height", 400) .on("mousedown", mousedown)
Now provide the response and nothing else.
| First off, you definitely have the right idea for how to add points on mousedown . The two things I'd change are: Use click instead of mousedown , so if you click existing points you don't add a new point on top of the existing one. Add one point at a time, instead of re-adding all the points on each click . Here's a working click function: function click(){ // Ignore the click event if it was suppressed if (d3.event.defaultPrevented) return; // Extract the click location\ var point = d3.mouse(this) , p = {x: point[0], y: point[1] }; // Append a new point svg.append("circle") .attr("transform", "translate(" + p.x + "," + p.y + ")") .attr("r", "5") .attr("class", "dot") .style("cursor", "pointer") .call(drag);} Then, when dragging, it is simplest to move a circle using translate (which is also why I use translate when creating points above). The only real step is to extract the drag's x and y locations. Here's a working example of drag behavior. var drag = d3.behavior.drag() .on("drag", dragmove);function dragmove(d) { var x = d3.event.x; var y = d3.event.y; d3.select(this).attr("transform", "translate(" + x + "," + y + ")");} I put all this together in this jsfiddle . Finally, here's a relevant SO question I read when constructing the drag example: How to drag an svg group using d3.js drag behavior? . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19911514', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1396588/']} | jdg_74538 |
stackexchange | llm_judgeable_groundtruth_similarity | 2201391 |
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:
$p$ is the probability of heads. Note if $p \le 0.5$, the answer is infinity, so assume $p > 0.5$. What is the expected number of flips of the coin where we have 2 more heads than tails? Note you would stop flipping the coin when you first encounter the situation where you have 2 more heads than tails.
Now provide the response and nothing else.
| We only ever need to keep track of the difference between the number of heads, and the number of tails. Moreover, the time it takes to increase this difference by $2$ is twice the time it takes to increase this difference by $1$. So let's call $x$ the time it takes to go from a difference of $k$ to a difference of $k+1$: for example, the time it takes from the start until you have flipped heads once more than tails. After the very first coinflip, we're either done (with probability $p$), or we have made progress in the wrong direction and have a difference of $2$ to make up for (with probablity $1-p$). So we have $$x = 1 + (1-p) \cdot 2x$$ or $x = \frac1{2p-1}$. The answer you want is $2x = \frac2{2p-1}$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2201391', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/211794/']} | jdg_74539 |
stackexchange | llm_judgeable_groundtruth_similarity | 49676 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The question is in the title; I'm looking for the exact decay rate. Naturally, assume the starting point $y_0$ belongs to $(0,1)$. This is motivated by one of the answers to a previous question of mine .
Now provide the response and nothing else.
| Consider the recurrence $\displaystyle x_{n+1} = x_n(1-x_n)$ (sorry changed the notation). If $\displaystyle y_n = \frac{1}{x_n}$ then we see that $$y_{n+1} - y_n = \frac{1}{1-x_n}$$ and thus $$ y_n = y_0 + \sum_{k=0}^{n-1} \frac{1}{1-x_k} $$ Since $\displaystyle 1 - x_n \to 1$ we have that $\displaystyle \frac{1}{1-x_n} \to 1$ and thus $\displaystyle \frac{1}{n} \sum_{k=0}^{n-1} \frac{1}{1-x_k} \to 1$ And thus $\displaystyle \frac{y_n}{n} \to 1$ i.e. $\displaystyle n x_n \to 1$. Similar technique was used in the excellent answer by David Speyer here: Convergence of $\sqrt{n}x_{n}$ where $x_{n+1} = \sin(x_{n})$ Note that we get your sequence by considering the sequence $\displaystyle x_{n+1} = f(x_n)$ where $\displaystyle f(x) = x - x^2$ and applying the technique in that answer here. See also: Limit of the sequence $nx_{n}$ where $x_{n+1} = \log (1 +x_{n})$ PS: One can get more accurate estimates by using the above ($\displaystyle x_n \sim \frac{1}{n}$) and passing it again through $\displaystyle y_n = C + \sum_{k=1}^{n-1} \frac{1}{1-x_k} = C + n + \sum_{k=0}^{n-1} x_k + + \sum_{k=0}^{n-1} \mathcal{O}(x_k^2)$ I believe by doing this we get the estimate $$y_n = n + \log n + \mathcal{O}(1)$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/49676', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/9182/']} | jdg_74540 |
Subsets and Splits