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
19733447
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 Bootstrap , what is the most platform-friendly way to create a navigation bar that has Logo A on the left, menu items in the center, and Logo B on the right? Here is what I've tried so far, and it ends up being aligned so that Logo A is on the left, menu items next to the logo on the left and Logo B on the right. <div class="navbar navbar-fixed-top navbar-custom "> <div class="container" > <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#"><span class="navbar-logo">Logo_A</span></a> </div> <div class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li class="active"><a href="#">Home</a></li> <li><a href="#about">Menu Item 1</a></li> <li><a href="#contact">Menu Item 2</a></li> <li><a href="#about">Menu Item 3</a></li> </ul> <ul class="nav navbar-nav navbar-right"> <li><a href="#"><img src="images/Logo_B.png" class="img-responsive"></a></li> </ul> </div> </div></div> Now provide the response and nothing else.
2021 Update Bootstrap 5 (beta) Bootstrap 5 also has a flexbox Navbar, and introduces new RTL support. For this reason the concept of "left" and "right" has been replaced with "start" and "end". Therefore the margin utilities changed for Bootstrap 5 beta: ml-auto => ms-auto mr-auto => me-auto Also note that data-toggle and data-target have changed too: data-toggle => data-bs-toggle data-target => data-bs-target Navbar Demo for Bootstrap 5 Bootstrap 4 Now that Bootstrap 4 has flexbox, Navbar alignment is much easier. Here are updated examples for left , right and center in the Bootstrap 4 Navbar , and many other alignment scenarios demonstrated here . The flexbox , auto-margins , and ordering utility classes can be used to align Navbar content as needed. There are many things to consider including the order and alignment of Navbar items (brand, links, toggler) on both large screens and the mobile/collapsed views. Don't use the grid classes (row,col) for the Navbar . Here are various examples... Left, center(brand) and right links: <nav class="navbar navbar-expand-md navbar-dark bg-dark"> <div class="navbar-collapse collapse w-100 order-1 order-md-0 dual-collapse2"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Left</a> </li> <li class="nav-item"> <a class="nav-link" href="//codeply.com">Codeply</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> </ul> </div> <div class="mx-auto order-0"> <a class="navbar-brand mx-auto" href="#">Navbar 2</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".dual-collapse2"> <span class="navbar-toggler-icon"></span> </button> </div> <div class="navbar-collapse collapse w-100 order-3 dual-collapse2"> <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link" href="#">Right</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> </ul> </div></nav> http://codeply.com/go/qhaBrcWp3v Another BS4 Navbar option with center links and overlay logo image : <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <div class="navbar-collapse collapse w-100 dual-collapse2 order-1 order-md-0"> <ul class="navbar-nav ml-auto text-center"> <li class="nav-item active"> <a class="nav-link" href="#">Link</a> </li> </ul> </div> <div class="mx-auto my-2 order-0 order-md-1 position-relative"> <a class="mx-auto" href="#"> <img src="//placehold.it/120/ccff00" class="rounded-circle"> </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".dual-collapse2"> <span class="navbar-toggler-icon"></span> </button> </div> <div class="navbar-collapse collapse w-100 dual-collapse2 order-2 order-md-2"> <ul class="navbar-nav mr-auto text-center"> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> </ul> </div></nav> Or , these other Bootstrap 4 alignment scenarios: brand left, dead center links, (empty right) brand and links center, icons left and right More Bootstrap 4 examples : toggler left on mobile, brand right center brand and links on mobile right align links on desktop, center links on mobile left links & toggler, center brand, search right Also see: Bootstrap 4 align navbar items to the right Bootstrap 4 navbar right align with button that doesn't collapse on mobile Center an element in Bootstrap 4 Navbar Bootstrap 3 Option 1 - Brand center, with left/right nav links: <nav class="navbar navbar-default" role="navigation"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <a class="navbar-brand" href="#">Brand</a> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav navbar-left"> <li><a href="#">Left</a></li> <li><a href="#about">Left</a></li> </ul> <ul class="nav navbar-nav navbar-right"> <li><a href="#about">Right</a></li> <li><a href="#contact">Right</a></li> </ul> </div></nav>.navbar-brand{ position: absolute; width: 100%; left: 0; text-align: center; margin:0 auto;}.navbar-toggle { z-index:3;} http://bootply.com/98314 (3.x) Option 2 - Left, center and right nav links: <nav class="navbar navbar-default" role="navigation"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a href="#">Left</a></li> </ul> <ul class="nav navbar-nav navbar-center"> <li><a href="#">Center</a></li> <li><a href="#">Center</a></li> <li><a href="#">Center</a></li> </ul> <ul class="nav navbar-nav navbar-right"> <li><a href="#">Right</a></li> </ul> </div></nav>@media (min-width: 768px) { .navbar-nav.navbar-center { position: absolute; left: 50%; transform: translatex(-50%); }} http://bootply.com/SGYC6BWeBK Option 3 - Center both brand and links .navbar .navbar-header,.navbar-collapse { float:none; display:inline-block; vertical-align: top;}@media (max-width: 768px) { .navbar-collapse { display: block; }} http://codeply.com/go/1lrdvNH9GI More examples: Left brand, center links Left toggler, center brand For 3.x also see nav-justified: Bootstrap center navbar Center Navbar in Bootstrap Bootstrap 4 align navbar items to the right
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/19733447', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2934431/']}
jdg_380141
stackexchange
llm_judgeable_groundtruth_similarity
84641
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: $$4^{\sin^2x}+4^{\cos^2x}=8$$ I solved like this: \begin{align*}4^{\sin^2x}+4^{\cos^2x}=8&\Rightarrow4^{\sin^2x}+4^{1-\sin^2x}=8\\&\Rightarrow4^{\sin^2x}+\frac{4}{4^{\sin^2x}}=8 |\cdot4^{\sin^2x}\\&\Rightarrow4^{2\sin^2x}-8\cdot4^{\sin^2x}+4=0\\y=4^{\sin^2x}&\Rightarrow y^2-8y+4=0\\&\Rightarrow\Delta=64-16=48\\&\Rightarrow y_{1,2}=\frac{8\pm 4\sqrt{3}}{2}\\&\Rightarrow y_{1,2}=4\pm 2\sqrt{3}\\&\Rightarrow 4^{\sin^2x}=4 \pm 2\sqrt{3}\end{align*} But now I'm stuck. Now provide the response and nothing else.
This equality cannot happen. Since $\sin^2 x , \cos^2 x \in [0,1]$ it follows that $$4^{\sin^2 x}+4^{\cos^2 x}\leq 4+4=8$$ with equality when $\sin^2x=\cos^2x=1$. The last equality is impossible.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/84641', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/15346/']}
jdg_380142
stackexchange
llm_judgeable_groundtruth_similarity
47167786
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 check boxes in the table created dynamically using JSF and i get the HTML output like the following, <input name="testForm:j_idt78:0:negative" id="testForm:j_idt78:0:negative" onchange='PrimeFaces.ab({s:this,e:"change",p:"testForm:j_idt78:0:negative"});' type="checkbox"><input name="testForm:j_idt78:0:positive" id="testForm:j_idt78:0:positive" onchange='PrimeFaces.ab({s:this,e:"change",p:"testForm:j_idt78:0:positive"});' type="checkbox"><input name="testForm:j_idt78:0:na" id="testForm:j_idt78:0:na" onchange='PrimeFaces.ab({s:this,e:"change",p:"testForm:j_idt78:0:na"});' type="checkbox"> if i select one check box then other two should be un selected and it is same for all the checkbox, at any time only one check box should be selected in a row. the above is the sample of only one row and how to do do this dynamically for N number rows[the table may contain any number of rows.] the following is the actual code which generates the check boxes dynamically <ui:repeat var="item" value="#{testController.itemsList}" varStatus="loop"> <p:row> <p:column> <h:outputText value="#{item.desc}" /> </p:column> <p:column> <h:outputText value="#{item.code}" /> </p:column> <p:column> <h:selectBooleanCheckbox value="#{testController.negative}" id="negative"> </h:selectBooleanCheckbox> </p:column> <p:column> <h:selectBooleanCheckbox value="#{testController.positive}" id="positive"> </h:selectBooleanCheckbox> </p:column> <p:column> <h:selectBooleanCheckbox value="#{testController.na}" id="na"> </h:selectBooleanCheckbox> </p:column> </p:row> </ui:repeat> I tried something like the following but still it is not un selecting the check boxes in the row and gives me the following exception in the console SCRIPT5022: Syntax error, unrecognized expression: unsupported pseudo: j_idt78function selectUnSelect(elementName) { var fields = elementName.split(':'); var formName = fields[0]; var jsfId = fields[1]; var fieldIndex = fields[2]; var propertyName = fields[3]; console.log(formName+":"+jsfId+":"+fieldIndex+":positive"); if(propertyName == 'positive'){ $("#"+formName+":"+jsfId+":"+fieldIndex+":positive").attr('checked', true); $("#"+formName+":"+jsfId+":"+fieldIndex+":negative").attr('checked', false); $("#"+formName+":"+jsfId+":"+fieldIndex+":na").attr('checked', false); } if(propertyName == 'negative'){ $("#"+formName+":"+jsfId+":"+fieldIndex+":positive").attr('checked', false); $("#"+formName+":"+jsfId+":"+fieldIndex+":negative").attr('checked', true); $("#"+formName+":"+jsfId+":"+fieldIndex+":na").attr('checked', false); } if(propertyName == 'na'){ $("#"+formName+":"+jsfId+":"+fieldIndex+":positive").attr('checked', false); $("#"+formName+":"+jsfId+":"+fieldIndex+":negative").attr('checked', false); $("#"+formName+":"+jsfId+":"+fieldIndex+":na").attr('checked', true); } } Please help me to fix the issue. Now provide the response and nothing else.
Yes you can easily do it ALL from the command line (NO IDE involved, I promise). This uses the old faithful Apache Ant . It does not use Gradle , that takes more work. To Summarize What you type is ( just 2 lines to produce an apk): android create project --target "android-16" --path basj --activity TestActivity --package com.android.basj (This produces an Apache Ant build file called build.xml file which is like the build.gradle file. Now write some code but TestActivity.java is there already and will compile) ant debug Setup ( Note : The " android.bat " command is deprecated since Build Tools v26 , so use an old one (see link below), deprecated in this case means TOTALLY removed !{ naughty Google }). Install Java JDK if not installed already (you can use jdk-8u151-windows-x64.exe for example), and make sure JAVA_HOME environment variable is defined e.g.: JAVA_HOME=C:\Program Files\Java\jdk1.8.0_112 JAVA_PATH=C:\Program Files\Java\jre1.8.0_112\bin JDK is the Java Development Kit. JRE is the Java Run-time Environment. Install Android SDK Tools (e.g. installer_r24.4.1-windows.exe , see this answer ) if not already done, and then in the SDK Manager GUI, deselect everything and choose "Android SDK Build-Tools" (e.g. Android SDK Build-Tools 19.1 ) + one (or many) platforms (e.g. Android 4.1.2 (API 16) JELLY_BEAN ). To prove you don't need Android Studio , were not going to download it ! (only the SDK). Download Apache Ant (for example apache-ant-1.9.9-bin.zip ) Detail To create a project from the command line using Android SDK : Decide on a place to put your project: cd c:\androidmkdir antTestcd antTest Run the command: C:\Android\sdk1\tools\android create project --target "android-16" --path basj --activity TestActivity --package com.android.basj ^ |--------------+ (here's where I keep an old version of tools (version 25 in my case) Here is the directory structure created (and all the files you need to build): C:.+---basj +---bin +---libs +---res ¦ +---drawable-hdpi ¦ +---drawable-ldpi ¦ +---drawable-mdpi ¦ +---drawable-xhdpi ¦ +---layout ¦ +---values +---src +---com +---android +---basj detailed output of create project: Created project directory: C:\Android\antTest\basjCreated directory C:\Android\antTest\basj\src\com\android\basjAdded file C:\Android\antTest\basj\src\com\android\basj\TestActivity.javaCreated directory C:\Android\antTest\basj\resCreated directory C:\Android\antTest\basj\binCreated directory C:\Android\antTest\basj\libsCreated directory C:\Android\antTest\basj\res\valuesAdded file C:\Android\antTest\basj\res\values\strings.xmlCreated directory C:\Android\antTest\basj\res\layoutAdded file C:\Android\antTest\basj\res\layout\main.xmlCreated directory C:\Android\antTest\basj\res\drawable-xhdpiCreated directory C:\Android\antTest\basj\res\drawable-hdpiCreated directory C:\Android\antTest\basj\res\drawable-mdpiCreated directory C:\Android\antTest\basj\res\drawable-ldpiAdded file C:\Android\antTest\basj\AndroidManifest.xmlAdded file C:\Android\antTest\basj\build.xmlAdded file C:\Android\antTest\basj\proguard-project.txt Download Apache Ant from http://ant.apache.org/ . See this tutorial for setup: http://www.vogella.com/tutorials/ApacheAnt/article.html Also see this tutorial: http://blog.vogella.com/2011/03/16/creating-android-applications-via-the-command-line-ant/ Write your code (Hello world). Run this command and you get an Android Apk out the other side (called TestActivity-debug.apk): ant debug Hey presto, you got an android apk ! With new structure added: C:.├───bin│ ├───classes│ │ └───com│ │ └───android│ │ └───basj│ ├───dexedLibs│ └───res│ ├───drawable-hdpi│ ├───drawable-ldpi│ ├───drawable-mdpi│ └───drawable-xhdpi├───gen│ └───com│ └───android│ └───basj For a final build : ant release If your interested in a more extensive example of Ant build.xml , or DEX files, and the deeper workings of Android look here How to sign an already compiled apk See how to sign an already compiled apk and also this From an answer by @for3st here's a relevant piece of that post: Manual Process: Step 1: Generate Keystore (only once) You need to generate a keystore once and use it to sign your unsigned apk.Use the keytool provided by the JDK found in %JAVA_HOME%/bin/ keytool -genkey -v -keystore my.keystore -keyalg RSA -keysize 2048 -validity 10000 -alias app Step 2 or 4: Zipalign zipalign which is a tool provided by the Android SDK found in e.g. %ANDROID_HOME%/sdk/build-tools/24.0.2/ is a mandatory optimization step if you want to upload the apk to the Play Store. zipalign -p 4 my.apk my-aligned.apk Note: when using the old jarsigner you need to zipalign AFTER signing. When using the new apksigner method you do it BEFORE signing (confusing, I know). Invoking zipalign before apksigner works fine because apksigner preserves APK alignment and compression (unlike jarsigner ). You can verify the alignment with: zipalign -c 4 my-aligned.apk Step 3: Sign & Verify Using build-tools 24.0.2 and older Use jarsigner which, like the keytool, comes with the JDK distribution found in %JAVA_HOME%/bin/ and use it like so: jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my.keystore my-app.apk my_alias_name and can be verified with jarsigner -verify -verbose my_application.apk Using build-tools 24.0.3 and newer Android 7.0 introduces APK Signature Scheme v2 , a new app-signing scheme that offers faster app install times and more protection against unauthorized alterations to APK files (See here and here for more details). Therefore, Google implemented their own apk signer called: apksigner (duh!)The script file can be found in %ANDROID_HOME%/sdk/build-tools/24.0.3/ (the .jar is in the /lib subfolder). Use it like this: apksigner sign --ks my.keystore my-app.apk --ks-key-alias alias_name and can be verified with: apksigner verify my-app.apk
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/47167786', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1277859/']}
jdg_380143
stackexchange
llm_judgeable_groundtruth_similarity
18156505
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 when I want to insert multiple fields into one table. Here's my form: <h1>Add user</h1> <form method="post" action="index.php"> <table> <thead> <th>Name</th> <th>Age</th> </thead> <tr> <td><input name="name[]" type="text" /></td> <td><input name="age[]" type="text" /></td> </tr> <tr> <td><input name="name[]" type="text" /></td> <td><input name="age[]" type="text" /></td> </tr> <tr> <td><input name="name[]" type="text" /></td> <td><input name="age[]" type="text" /></td> </tr></table> <input type="submit" name="submit" value="Submit" /> </form> And here's the submit code: if (isset($_POST['submit'])) { foreach ($_POST as $val) { $name = $val['name']; $age = $val['age']; mysql_query("INSERT INTO users (name, age) VALUES ('$name', '$age')"); } } The query inserts into the database, but not the values that I've entered. Can someone please help me? Now provide the response and nothing else.
You are doing a foreach on $_POST rather than on the name/age arrays. You should be doing foreach on name or age array like this: if ( !empty($_POST['name']) && !empty($_POST['age']) && is_array($_POST['name']) && is_array($_POST['age']) && count($_POST['name']) === count($_POST['age'])) { $name_array = $_POST['name']; $age_array = $_POST['age']; for ($i = 0; $i < count($name_array); $i++) { $name = mysql_real_escape_string($name_array[$i]); $age = mysql_real_escape_string($age_array[$i]); mysql_query("INSERT INTO users (name, age) VALUES ('$name', '$age')"); } } I would also note that you are currently susceptible to SQL injection so I added the step of escaping your strings for name/age. I would also highly suggest simply making a single bulk insert into the DB instead of an insert of each record individually (I will leave that up to you to implement). This approach is almost always preferable from a performance standpoint. Finally, you REALLY should not be using mysql_* functions as they are deprecated. Consider changing to mysqli or PDO.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18156505', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1813293/']}
jdg_380144
stackexchange
llm_judgeable_groundtruth_similarity
14148786
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 sample PHP app out there that allows user to set up custom fields? Such as an address book, etc. Such as setting a field as Home, Home Away, etc without database columns in mySQL. Being able to have as many fields as they want and naming it however they want. So result might be: | # | Name | DOB | Address 1 | Health | 1 | Scott | 7/1/12 | 2222 Jackson | GOOD Another set of data might be | # | Name | Expertise Level | Contact Info | 1 | Scott | High | 408-555-5555 I'm curious as how that would be done. Would everything be stored as JSON in single mysql table? And how would data for each field be stored? Any PHP script out there that already does this so I can just take it apart to understand? Now provide the response and nothing else.
Since you have this tagged with MySQL there are ways that you can have a flexible database table. You can create a table that contains Name-Value-Pairs similar to this: create table YourTable( id int, name varchar(50), attribute varchar(50), value varchar(50));insert into yourtablevalues(1, 'Scott', 'DOB', '07/01/2012'), (1, 'Scott', 'Address 1', '2222 Jackson'), (1, 'Scott', 'Health', 'Good'), (1, 'Scott', 'Expertise Level', 'High'), (1, 'Scott', 'Contact Info', '408-555-5555'); This is also known an Entity-Attribute-Value . There are positives and negatives to using this type of structure. In order to query this data, you have to either perform multiple joins or you can pivot the data to get it into columns. Here is an question on DBA.SE that outlines this type of structure (EAV). You can query the data using an aggregate function with a CASE statement: select id, name, max(case when attribute = 'DOB' then value end) DOB, max(case when attribute = 'Address 1' then value end) Address1, max(case when attribute = 'Health' then value end) Healthfrom yourtablegroup by id, name; If you wanted to perform multiple joins, then the query would be similar to this: select t1.id, t1.name, t1.value DOB, t2.value Address1, t3.value Healthfrom yourtable t1left join yourtable t2 on t1.id = t2.id and t1.name = t2.name and t2.attribute='Address 1'left join yourtable t3 on t1.id = t3.id and t1.name = t3.name and t3.attribute='Health'where t1.attribute = 'DOB'; See SQL Fiddle with Demo of data retrieval.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14148786', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/157173/']}
jdg_380145
stackexchange
llm_judgeable_groundtruth_similarity
2463813
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: Definition: $C(A): A\cup A'$ Definition: $A'$: the set of limit points of $A$. Exercise: Prove $C(A)$ is closed My work: We need to show $C(A)^c$ is open. Let $x \in C(A)^c$, Then $x\notin A$ and $x \notin A'$, That implies $x$ is not a limit point of $A$. Here my question: Why this happen? Then exists a neighborhood $V$ of $x$ such that $V\cap A=\emptyset$ Hence, $C(A)^c$ is open. My other question: Why $V\cap A=\emptyset$ implies this:$C(A)^c$ is open Thanks for all. I will be very grateful. Now provide the response and nothing else.
Recall that $$\sin^2\alpha = 1 - \cos^2\alpha$$ and express everything in terms of $\cos^2\alpha$:$$\begin{align}R &= \left(\;\sin^2\alpha\;\right)^3 + \left(\;\cos^2\alpha\;\right)^3+K\left(\;\left(\;\sin^2\alpha\;\right)^2+\left(\;\cos^2\alpha\;\right)^2\;\right) \\&= \left(\;1-\cos^2\alpha\;\right)^3 + \left(\;\cos^2\alpha\;\right)^3+K\left(\;\left(\;1-\cos^2\alpha\;\right)^2+\left(\;\cos^2\alpha\;\right)^2\;\right) \\&= \left(\;1-x\;\right)^3 + \left(\;x\;\right)^3+K\left(\;\left(\;1-x\;\right)^2+\left(\;x\;\right)^2\;\right) \qquad\text{(writing $x$ for $\cos^2\alpha$)}\\&= 1 - 3 x + 3 x^2 + K \left(\; 1 - 2 x + 2 x^2 \;\right) \\&= 1 +K -(3+2K) x + (3+2K) x^2\end{align}$$ Independence from $\alpha$ translates to independence from $x$. We need a value of $K$ that causes the non-constant terms of the polynomial to vanish. Clearly, $K = -3/2$. $\square$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2463813', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/334143/']}
jdg_380146
stackexchange
llm_judgeable_groundtruth_similarity
3361239
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 annotation in JUnit to exclude a non param test in parameterized test class? Now provide the response and nothing else.
JUnit 5 As of Junit 5.0.0 you can now annotate your test methods with @ParameterizedTest . So no need for inner classes. There are many ways to supply the arguments to the parameterized test apart from ValueSource as shown below. See the official junit user guide for details: import org.junit.jupiter.api.Test;import org.junit.jupiter.api.ParameterizedTest;import org.junit.jupiter.params.provider.ValueSource;public class ComponentTest { @ParameterizedTest @ValueSource(strings = { "racecar", "radar", "able was I ere I saw elba" }) public void testCaseUsingParams(String candidate) throws Exception { } @Test public void testCaseWithoutParams() throws Exception { }} JUnit 4 If you are still using Junit 4 (I tested with v4.8.2) you can use the Enclosed runner in conjunction with inner classes and the Parameterized runner: import org.junit.Test;import org.junit.experimental.runners.Enclosed;import org.junit.runner.RunWith;import org.junit.runners.Parameterized;@RunWith(Enclosed.class)public class ComponentTest { @RunWith(Parameterized.class) public static class ComponentParamTests { @Parameters ... @Test public void testCaseUsingParams() throws Exception { } } public static class ComponentSingleTests { @Test public void testCaseWithoutParams() throws Exception { } }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3361239', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/405516/']}
jdg_380147
stackexchange
llm_judgeable_groundtruth_similarity
14190068
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: i have this text in file "0000000441244""0000000127769" I want to replace all zeros with 'L' I am trying this and nothing gets chnaged sed -e 's/0+/L/g' regex.txt sed -e 's/(0+)/L/g' regex.txt I want to know where i am wrong Now provide the response and nothing else.
Posix compliant version should use 00* instead of 0+ : sed -e 's/00*/L/g' regex.txt As a side note, you only need the g flag if you want to convert "000000012700009" or even "000000012709" into "L127L9" . Otherwise, the * in 's/00*/L/' will include all zeros at the beginning anyway.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14190068', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1953864/']}
jdg_380148
stackexchange
llm_judgeable_groundtruth_similarity
14149
Below is a question asked on the forum economics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Suppose we have a production function $f(z)=2$. I am asked to determine whether the function exhibits increasing, decreasing, constant or no returns to scale. For $t>0$, $f(tz)=2$. I'm not sure about the answer: should I say the function exhibits no returns to scale whatsoever or take different values for $t$ ($0<t<1 \implies$decreasing returns to scale, $t=1 \implies$ constant returns to scale, $t>1 \implies$ increasing returns to scale)? Now provide the response and nothing else.
You want to find a relation between $tF(z)$ and $F(tz)$ for all $t>1$ (or $0$ for CRS). So since $2t=tF(z)>F(tz)=2$ for all $t>1$, we see decreasing returns to scale.
{}
{'log_upvote_score': 4, 'links': ['https://economics.stackexchange.com/questions/14149', 'https://economics.stackexchange.com', 'https://economics.stackexchange.com/users/5936/']}
jdg_380149
stackexchange
llm_judgeable_groundtruth_similarity
7570
Below is a question asked on the forum physics.meta.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Recently I asked a question on physics stack exchange. It was closed with a reference to faq guidelines . Here is the question that was closed: Maximum period of a vertically spinning ball . Please note that while this was not a "homework" question, I can understand that it is classified as a homework question according to the faq referenced above. The wisdom of applying "homework" tag to my question is still mysterious to me since the definition of that tag is so general that it can be applied to almost any question that asks for application of general concepts to a particular problem. But that's not the issue that I want addressed. Let's assume that it is indeed a "homework" question. The issue that I want to address is (1) how this question is inconsistent with the faq guidelines ? Although I do not find any inconsistencies with the guidelines myself, I have to assume that such inconsistency does exist since it was closed. If that inconsistency can be pointed, I'd also appreciate a pointer or two on (2) how to ask an "acceptable" question that qualifies as "homework" under the guidelines. By "acceptable" I mean a question that won't be closed. Now provide the response and nothing else.
For the record, we ourselves consider those guidelines a bit of a mess. But I'll bypass that issue and just answer based on the existing homework policy as it stands. ...how this question is inconsistent with the faq guidelines ? The guidance in that FAQ can be summarized in two points: Ask a specific conceptual question Show some work toward answering that conceptual question Your post certainly meets condition #1; there is a specific conceptual question, namely whether the stated assumption is correct. But in its current form, it fails condition #2: it doesn't show any attempt to understand whether the assumption is correct. Even in the revision at which it was closed , I think the same is true. In that revision you show work toward solving the underlying problem - in fact you have a complete solution - but none of that work addresses the issue you're asking about, namely whether the assumption is correct. If you ask me, to make this clearly not close-worthy/hold-worthy, it would need to expand on the issue of whether the assumption you've made is correct. A good place to start would be identifying some reason you think it might not be correct. For example, is there some alternative assumption you could make that also seems reasonable? Or do you get nonsensical results by making the assumption? Are you unable to find a justification for the assumption in any references you have access to, despite expecting that it should be justified somewhere? Do you find it necessary to make the assumption even though you think it shouldn't be necessary? Or so on.
{}
{'log_upvote_score': 4, 'links': ['https://physics.meta.stackexchange.com/questions/7570', 'https://physics.meta.stackexchange.com', 'https://physics.meta.stackexchange.com/users/83488/']}
jdg_380150
stackexchange
llm_judgeable_groundtruth_similarity
35853490
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 classes and the compiler (Microsoft Visual Studio 2012) gives me strange result since there is no problem compiling a*v but compiling b*v I get the following error: "error C2678: binary '*': no operator found which takes a right-hand operator of type const double (or there is no acceptable conversion). The compiler does not use the A::operator*() for a*v , but for b*v the function operator*(U t, Vector<T> v) is used. So does anyone know what is going on? template <class T>class Vector{public: Vector() { v[0] = 1; v[1] = 2; v[2] = 3; } Vector(T a, T b, T c) { v[0] = a; v[1] = b; v[2] = c; } T v[3];};template <class T, class U>Vector<U> operator*(const T& t, const Vector<U>& v){ return Vector<U>(t*v.v[0], t* v.v[1], t*v.v[2])}class A{public: Vector<double> operator *(const Vector<double>& v) { return Vector<double>(99.0,99.0,99.0); }};class B : public A { };void MyFct(){ Vector<double> v; A a; B b; Vector<double> test1 = a * v; Vector<double> test2 = b * v; printf("%f %f", test1.v[0], test2.v[0]);} Now provide the response and nothing else.
A tf.constant() has fixed size and value at graph construction time, so it probably isn't the right op for your application. If you are trying to create a tensor with a dynamic size and the same (constant) value for every element, you can use tf.fill() and tf.shape() to create an appropriately-shaped tensor. For example, to create a tensor t that has the same shape as input and the value 0.5 everywhere: input = tf.placeholder(tf.float32, shape=(None, ...))# `tf.shape(input)` takes the dynamic shape of `input`.t = tf.fill(tf.shape(input), 0.5) As Yaroslav mentions in his comment , you may also be able to use (NumPy-style) broadcasting to avoid materializing a tensor with dynamic shape. For example, if input has shape (None, 32) and t has shape (1, 32) then computing tf.mul(input, t) will broadcast t on the first dimension to match the shape of input .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/35853490', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6031074/']}
jdg_380151
stackexchange
llm_judgeable_groundtruth_similarity
714226
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I saw the definition of 'lens' in an online portal as Lens is a type of mirror which refracts the light instead of reflection Is that true to say 'type of mirror'? Mirrors have an opaque surface in general but lenses have both surfaces transparent. Definition of Lens found in the web . Now provide the response and nothing else.
The question is about the meaning of terms such as 'microscopic' and 'macroscopic' in thermal physics generally. To define these terms it is best to put to one side for a moment the idea that large things are often made of atoms and molecules and things like that. Rather, pretend you really don't know what sort of stuff the physical things under consideration are made of. Pretend you don't even know if they are made of continuous wobbly things like waves or itty bitty things like particles. So with this kind of ignorance, what can you still define, measure and reason about? The answer is: quantities such as volume and energy and mass and pressure (and electric field and viscosity and density etc. etc.). This is what thermodynamics is all about. Now the question was, is temperature a macroscopic concept? The answer is yes it is macroscopic, because we can define it using macroscopic concepts. Temperature can be defined as that property which two system in thermal equilibrium with one another must have in common . This seems like a rather abstract definition at first, but stay with me for a moment. The next thing we need is a scale of temperature. There are two ways to quantify temperature in thermodynamics. They are each equally profound, but not independent of each other, because either can be derived from the other. But note: neither of them mention kinetic energy! The first way is to consider a pair of thermal reservoirs (also called 'heat bath') and imagine operating a reversible heat engine between them. In this case, suppose that when heat energy $Q_1$ is extracted from the first reservoir, heat energy $Q_2$ is delivered to the second reservoir. It is found that the ratio $Q_1/Q_2$ does not depend on what kind of process was involved, as long as it can be operated equally well forward (an engine) or back (a heat pump). (There is some very elegant reasoning that leads to this conclusion, starting from the laws of thermodynamics,but I am skipping that part). This leads to a way to define a temperature scale. The temperature scale is defined such that $$\frac{T_1}{T_2} = \frac{Q_1}{Q_2}. \tag{1}$$ This is sufficient to define all temperatures because once you have a way to comparetwo temperatures, they can all be compared to some agreed case called unit temperature. Notice that nowhere in this argument is any mention needed of the microscopic composition of the systems involved. Nor did I need to introduce a microscopic description and then take a limit of large numbers. The second way to define temperature in thermodynamics (as I said, equally fundamental as the one I just gave) is to use the expression: $$T = \left. \frac{\partial U}{\partial S} \right|_{V, m,\, \rm etc.}\tag{2}$$ where $U$ is the entire internal energy of the system in question, $S$ is its entropy, and in the partial derivative properties of the system such as volume,mass and other things related to work are kept constant.(For readers unfamiliar with partial differentiation, I offer some simpler thoughts at the end. Here I am being completely precise and thorough).In order to use this second definition, we need to know what entropy is. One way to figure out what entropy is is to use the first temperature definition, plus some more clever reasoning named after Clausius, and eventually define entropy such that the second result holds. But you can if you like just assert that physical systems have a property called entropy, and assert some very general facts about it (e.g. it can only ever stay constant or increase in an isolated system), and then arrive at equation (2)as a definition of what we even mean by temperature (not just an assertionabout temperature). In this approach it is normally felt to be more insightful to write it the other way up: $$\frac{1}{T} \equiv \left. \frac{\partial S}{\partial U} \right|_{V, m,\, \rm etc.}\tag{3}$$ Equations (2) and (3) are saying precisely the same thing; I have just taken an inverse on both sides. I have now shown that temperature is a macroscopic concept because I have only needed macroscopic physical ideas and quantities (energy, entropy, mass, volume) to define and describe it precisely. It remains to say how temperature relates to microscopic behaviours and quantities. To find out the temperature of a collection of small things such as atoms or molecules or vibrations or whatever, the mathematical method amounts, in the end, to finding out the entropy and using equation (2) or (3). In many cases it turns out that the temperature is closely related to the mean kinetic energy of the parts of the system, but in order to say this in a quantitative way one has to be quite careful in deciding how the parts are being counted. But temperature is not a property of a single atom or a single vibration or a single rotation. It is a collective property, like an average. If atoms in a gas are moving around and colliding with one another, then at any given time some atoms will be moving fast, with lots of energy, and some will be slow, with little energy. But we should not say that in this case some atoms are hot and some cold. Rather, the temperature is a property of the distribution of energy. It is a measure of how quickly the number of atoms at a given energy falls off as a function of energy, when the atoms are continuously exchanging energy with one another through collisions. (This measure is somewhat related to the average energy per particle but they are not quite the same.) Relating temperature to energy Here is a further comment on the relationship between temperature and energy, suitable for school-level study. For many simple systems it happens that the entropy goes up in proportion to the logarithm of the energy, as long as the temperature is high enough: $$S \propto \log U$$ with a proportionality constant of order $R$ (the gas constant): $$S \simeq R \log U .$$ This implies that the energy is proportional to the exponential of the entropy: $$U = A e^{S/R}$$ where $A$ is a constant. In this case $$\frac{dU}{dS} = \frac{1}{R} A e^S = \frac{U}{R}$$ so using equation (2) we find $$T = \frac{U}{R}.$$ This results works for many gases and solids at room temperature, as long as you understand I have omitted a factor of order 1 which depends on the individual case. The purpose of this added note is to show that temperature does often indicate energy, but it does not have to be like that. It happens when the relationship between entropy and energy is logarithmic, and this in turns happens when the dominant energy is kinetic (or potential in a harmonic well), andthe system is excited well above its ground state.
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/714226', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/338370/']}
jdg_380152
stackexchange
llm_judgeable_groundtruth_similarity
63211082
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using VSCode 1.47.3 on Windows 10. I cannot edit default settings in json: Open Default Settings ("File -> Preferences -> Settings") Type in Default Settings json file to edit. Window appears "Cannot edit in read-only editor" I've tried opening VSCode as admin, uninstalling and reinstalling, restarting my computer, and downgrading to 1.46, but still cannot edit. Does someone know how to fix this? Now provide the response and nothing else.
The default settings in vscode is a non-editable document. It acts as a way for you to view the default settings for native settings as well as extension default settings. These defaults are also used to identify when a setting has changed with a 'blue' line indicator, when using the settings editor : Changes to settings are reloaded by VS Code as you change them. Modified settings are now indicated with a blue line similar to modified lines in the editor. The gear icon opens a context menu with options to reset the setting to its default value as well as copy setting as JSON. Currently, vscode only offers 2 editable settings: VS Code provides two different scopes for settings: User Settings - Settings that apply globally to any instance of VS Code you open. Workspace Settings - Settings stored inside your workspace and only apply when the workspace is opened. Workspace settings override user settings. Workspace settings are specific to a project and can be shared across developers on a project. Note: A VS Code "workspace" is usually just your project root folder. Workspace settings as well as debugging and task configurations are stored at the root in a .vscode folder. You can also have more than one root folder in a VS Code workspace through a feature called Multi-root workspaces. You can configure these settings with the settings editor, as pictured above, or you can navigate to their JSON counterparts for manual entry (example pictured on the right below). For workspace settings JSON, the JSON file is located in a folder of the root directory called .vscode , you can create it yourself if it is not there. By default, VS Code shows the Settings editor, but you can still edit the underlying settings.json file by using the Open Settings (JSON) command from your command palette or by changing your default settings editor with the workbench.settings.editor setting. Settings You can define which view is shown using the following settings: workbench.settings.openDefaultSettings Opens the default settings any time you open regular settings (this only works with the JSON settings editor option) workbench.settings.editor Determine which editor to use, you can elect UI or JSON workbench.settings.useSplitJSON This will open a JSON settings editor, with the default settings to the left, but the default editor to the left will behave like a UI editor in that you can collapse regions based on category and there is a search input box and it will share the same tab as the json editor on the right , whereas the workbench.settings.openDefaultSettings option mentioned above puts each setting view in its own respective tab (editor)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/63211082', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8748308/']}
jdg_380153
stackexchange
llm_judgeable_groundtruth_similarity
480632
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Prove $2^n >2n$ for all integral values of n greater than 2. Let $p_n$ be the statement:$$2^n>2n\ \forall\ n\gt2$$ If the inequality is valid for $n=k$ where $k>2$:$$p_k: 2^k>2k$$ Then for $n=k+1$:$$p_{k+1} = 2^{k+1}>2(k+1)$$ I don't know how to do the inductive step itself, I have only done series/recurrence relations inductions. Have I used the correct layout/notation? Is there more cool notation I could add to improve the mathematical-ness of the proof? Thanks Now provide the response and nothing else.
Don't forget the "base case": $p(3)$. It may seem obviously true, but formally , an inductive proof requires it. With respect to the inductive step, note that $$2^{k+1} = \underbrace{2 \cdot 2^k \gt 2\cdot 2k}_{\text{inductive step}} = 4k = \underbrace{\color{blue}{\bf 2k+2k\geq 2k+2}}_{\text{for all }\; k \geq 1}=2(k+1)$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/480632', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/90771/']}
jdg_380154
stackexchange
llm_judgeable_groundtruth_similarity
26694108
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 looked at the documentation for building with Gradle, but I'm still not sure what the difference between compileSdkVersion and targetSdkVersion is. All it says is: The `compileSdkVersion` property specifies the compilation target. Well, what is the "compilation target"? I see two possible ways to interpret this: compileSdkVersion is the version of the compiler used in building the app, while targetSdkVersion is the "API level that the application targets" . (If this were the case, I'd assume compileSdkVersion must be greater than or equal to the targetSdkVersion ? They mean the same thing. "compilation target" == "the API level that the application targets" Something else? I see that this question has been asked before, but the one answer just quotes the doc, which is what is unclear to me. Now provide the response and nothing else.
compileSdkVersion The compileSdkVersion is the version of the API the app is compiled against. This means you can use Android API features included in that version of the API (as well as all previous versions, obviously). If you try and use API 16 features but set compileSdkVersion to 15, you will get a compilation error. If you set compileSdkVersion to 16 you can still run the app on a API 15 device as long as your app's execution paths do not attempt to invoke any APIs specific to API 16. targetSdkVersion The targetSdkVersion has nothing to do with how your app is compiled or what APIs you can utilize. The targetSdkVersion is supposed to indicate that you have tested your app on (presumably up to and including) the version you specify. This is more like a certification or sign off you are giving the Android OS as a hint to how it should handle your app in terms of OS features. For example, as the documentation states: For example, setting this value to "11" or higher allows the system to apply a new default theme (Holo) to your app when running on Android 3.0 or higher... The Android OS, at runtime , may change how your app is stylized or otherwise executed in the context of the OS based on this value. There are a few other known examples that are influenced by this value and that list is likely to only increase over time. For all practical purposes, most apps are going to want to set targetSdkVersion to the latest released version of the API. This will ensure your app looks as good as possible on the most recent Android devices. If you do not specify the targetSdkVersion , it defaults to the minSdkVersion .
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/26694108', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3761530/']}
jdg_380155
stackexchange
llm_judgeable_groundtruth_similarity
223873
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I would like to know if $\mathbb Q \left[\sqrt {2+\sqrt 2}\right ]: \mathbb Q$ is normal . The roots of the minimal polynomial is $\pm\sqrt {2\pm\sqrt 2}$ . Now the thing that i have really tried and have no idea to get is to write $\sqrt {2-\sqrt 2}$ as the combination of the powers of $\sqrt {2+\sqrt 2}$ If at all it is possible? What are the possible ways of finding the coefficients? Thanks for you help. Now provide the response and nothing else.
$\mathbb Q(\sqrt{2+\sqrt{2}})$ contains $\sqrt{2}$ and $\sqrt{2+\sqrt{2}}\sqrt{2-\sqrt{2}}=\sqrt{2}$ so $\sqrt{2-\sqrt{2}}\in \mathbb Q(\sqrt{2+\sqrt{2}})$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/223873', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/24598/']}
jdg_380156
stackexchange
llm_judgeable_groundtruth_similarity
36747293
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Let's say I have a controller that uses attribute based routing to handle a requested url of /admin/product like so: [Route("admin/[controller]")] public class ProductController: Controller { // GET: /admin/product [Route("")] public IActionResult Index() { return View(); }} Now let's say that I'd like to keep my views organized in a folder structure that roughly reflects the url paths they are related to. So I'd like the view for this controller to be located here: /Views/Admin/Product.cshtml To go further, if I had a controller like this: [Route("admin/marketing/[controller]")] public class PromoCodeListController: Controller { // GET: /admin/marketing/promocodelist [Route("")] public IActionResult Index() { return View(); }} I would like the framework to automatically look for it's view here: Views/Admin/Marketing/PromoCodeList.cshtml Ideally the approach for informing the framework of the view location would work in a general fashion based on the attribute based route information regardless of how many url segments are involved (ie. how deeply nested it is). How can I instruct the the Core MVC framework (I'm currently using RC1) to look for the controller's view in such a location? Now provide the response and nothing else.
You can expand the locations where the view engine looks for views by implementing a view location expander. Here is some sample code to demonstrate the approach: public class ViewLocationExpander: IViewLocationExpander { /// <summary> /// Used to specify the locations that the view engine should search to /// locate views. /// </summary> /// <param name="context"></param> /// <param name="viewLocations"></param> /// <returns></returns> public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations) { //{2} is area, {1} is controller,{0} is the action string[] locations = new string[] { "/Views/{2}/{1}/{0}.cshtml"}; return locations.Union(viewLocations); //Add mvc default locations after ours } public void PopulateValues(ViewLocationExpanderContext context) { context.Values["customviewlocation"] = nameof(ViewLocationExpander); }} Then in the ConfigureServices(IServiceCollection services) method in the startup.cs file add the following code to register it with the IoC container. Do this right after services.AddMvc(); services.Configure<RazorViewEngineOptions>(options => { options.ViewLocationExpanders.Add(new ViewLocationExpander()); }); Now you have a way to add any custom directory structure you want to the list of places the view engine looks for views, and partial views. Just add it to the locations string[] . Also, you can place a _ViewImports.cshtml file in the same directory or any parent directory and it will be found and merged with your views located in this new directory structure. Update: One nice thing about this approach is that it provides more flexibility then the approach later introduced in ASP.NET Core 2 (Thanks @BrianMacKay for documenting the new approach). So for example this ViewLocationExpander approach allows for not only specifying a hierarchy of paths to search for views and areas but also for layouts and view components. Also you have access to the full ActionContext to determine what an appropriate route might be. This provides alot of flexibility and power. So for example if you wanted to determine the appropriate view location by evaluating the path of the current request, you can get access to the path of the current request via context.ActionContext.HttpContext.Request.Path .
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/36747293', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1415614/']}
jdg_380157
stackexchange
llm_judgeable_groundtruth_similarity
34646055
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 use json.dumps() to pretty print JSON inside my app.Currently, my template is set up like this: <table>{% for test in list_of_decoded_json %} <tr> <td><pre>{{ test|safe }}</pre></td> </tr>{% endfor %}</table> Where test is the decoded JSON string. However, this implementation only prints the JSON strings in one line. Knowing that jinja2 doesn't support the json.dumps() function in-template, how can I get the pretty printed layout that I want? Now provide the response and nothing else.
You can create your own to_pretty_json filter. First of all, you have to wrap json.dumps() into a new function and then register it as jinja filter : import jsondef to_pretty_json(value): return json.dumps(value, sort_keys=True, indent=4, separators=(',', ': '))app.jinja_env.filters['tojson_pretty'] = to_pretty_json And then use it in the template: <table>{% for test in list_of_decoded_json %} <tr> <td><pre>{{ test|tojson_pretty|safe }}</pre></td> </tr>{% endfor %}</table>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34646055', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5739015/']}
jdg_380158
stackexchange
llm_judgeable_groundtruth_similarity
62102476
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm getting issue during install pod in react-native project Nanaimo::Reader::ParseError - [!] Array missing ',' in between objects please help me if anyone have idea about that. Now provide the response and nothing else.
I don't think (but I might be wrong) that there's a correct way of doing it per se, but what you could do it have a central module ( maindash.py ) around your startup code app = dash.Dash(__name__) , and have different callbacks simply import app from my_dash_app.maindash . This would set up the callbacks in their own separate modules but re-use that one central module for the app instance. It's easiest to show an overview of it like this: app.py being the main script called to start everything up. maindash.py is in charge of creating the main app instance. first_view.py is where the decorators are defined to set up all the callbacks. Here's the result: .├── my_dash_app│ ├── app.py│ ├── maindash.py│ └── views│ ├── first_view.py│ └── __init__.py└── setup.py Since imports are re-used in Python, there's no real harm in doing from my_dash_app.maindash import app several times from different other modules, such as event handlers and the main script. They'll share the same import instance - thus re-using the dash.Dash() instance as well. Just make sure you import the central module before setting up the handlers, and you should be good to go. Here's the code snippets separated for testing: app.py from my_dash_app.maindash import appfrom my_dash_app.views.first_view import make_layoutif __name__ == '__main__': app.layout = make_layout() app.run_server(debug=True) maindash.py import dashapp = dash.Dash(__name__) first_view.py from my_dash_app.maindash import appfrom dash.dependencies import Input, Outputimport dash_core_components as dccimport dash_html_components as htmldef make_layout(): return html.Div([ dcc.Input(id='my-id', value='initial value', type='text'), html.Div(id='my-div') ])@app.callback(Output(component_id='my-div', component_property='children'), [Input(component_id='my-id', component_property='value')])def update_output_div(input_value): return 'You\'ve entered "{}"'.format(input_value)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/62102476', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5506557/']}
jdg_380159
stackexchange
llm_judgeable_groundtruth_similarity
55468
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In other words, how to prove: For all real constants $a$ and $b$ such that $a > 1$ , $$\lim_{n\to\infty}\frac{n^b}{a^n} = 0$$ I know the definition of limit but I feel that it's not enough to prove this theorem. Now provide the response and nothing else.
We could prove this by induction on integers $k$: $$\lim_{n \to \infty} \frac{n^k}{a^n} = 0.$$ The case $k = 0$ is straightforward. I will leave the induction step to you. To see how this implies the statement for all real $b$, just note that every real number is less than some integer. In particular, $b \leq \lceil b \rceil$. Thus, $$0 \leq \lim_{n \to \infty} \frac{n^b}{a^n} \leq \lim_{n \to \infty} \frac{n^{\lceil b \rceil}}{a^n} = 0.$$ The first inequality follows since all the terms are positive. The last equality follows from the induction we established previously.
{}
{'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/55468', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/1618/']}
jdg_380160
stackexchange
llm_judgeable_groundtruth_similarity
19922077
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 run Genymotion, I get the following error: Unable to start the Genymotion virtual device. Unable to configure the network adapter for the virtual device. Please, check the following points: From VirtualBox, in the main parameters of software, check a network adapter "Host-only" is present.From VirtualBox, in the Genymotion virtual device parameters, check the first network interface has the type "Host-only". If no, then set this parameter manually. How can I fix that? Now provide the response and nothing else.
Update: Before you read further, I want to notice that I didn't have any problems since I upgraded VirtualBox to 4.3.4. I use VirtualBox 4.3.2 under Ubuntu 13.10. I had same issue after upgrading from Genymotion 2.0.0 to 2.0.1. These are the steps I followed to fix this, although I'm not sure which one works for you. Step 1. Start VirtualBox, go to menu File/Preferences menu, go to Network section, select Host-only Networks tab. If you don't have any adapter defined, then you can create one (as indicated below) or you can ignore step 1 and Genymotion will create it when you try to start the VM. If you do have an adapter there (vboxnet0) click the edit button. In the edit window, you must have DHCP server enabled AND the IP address and allocation pool of the server must be inside same network as the IP of the network controller. For example, I use: IPv4 address/netmask: 192.168.56.1/255.255.255.0 (on Adapter tab) DHCP server enabled checked (on DHCP server tab) Server address/netmask: 192.168.56.100/255.255.255.0 Server lower/upper address: 192.168.56.100/192.168.56.254 Still in VirtualBox, select the Android VM you have, click Settings button, select Network section. In the Adapter 1 tab, you should have: Enable network adapter checked Attached to: Host-only adapter Name: vboxnet0 Normally, if you have all these settings, it should work ok, but it didn't for me. So I moved to step 2. Step 2. As indicated by Genymotion, start VirtualBox, go to menu File/Preferences menu, go to Network section, select Host-only Networks tab and delete the defined adapters. Start your VM in Genymotion. Genymotion will recreate the adapter with proper settings (as described in step 1) Normally, if step 1 didn't work for you, step 2 should work ok, but it didn't for me. So I moved to step 3. Step 3. Delete and recreate the Android VM in Genymotion (VirtualBox host-only network settings I left as described in step 1). This solved my issue and Android VM works ok now. Good luck. Andrei. Update: A day after posting answer, when I was first starting a VM in genymotion, it gave again same error again and vboxnetdhcp process crashed (and restarted). On second and later start attempts it worked ok. So it might still be some minor issue there with VirtualBox DHCP process. Update: The issue seems to reside in virtual Box DHCP server which crashes: /usr/lib/virtualbox/VBoxNetDHCP --network HostInterfaceNetworking-vboxnet0 --trunk-type netflt --trunk-name vboxnet0 --mac-address 08:00:27:72:4C:7B --ip-address 192.168.56.100 --netmask 255.255.255.0 --verboseFloating point exception (core dumped) Deleting and recreating the VM fixed again the issue. Maybe Genymotion sends some invalid data to VBox DHCP that makes it crash (still a VBox bug though).
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19922077', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2089418/']}
jdg_380161
stackexchange
llm_judgeable_groundtruth_similarity
311165
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How can you convert a byte array to a hexadecimal string and vice versa? Now provide the response and nothing else.
You can use Convert.ToHexString starting with .NET 5. There's also a method for the reverse operation: Convert.FromHexString . For older versions of .NET you can either use: public static string ByteArrayToString(byte[] ba){ StringBuilder hex = new StringBuilder(ba.Length * 2); foreach (byte b in ba) hex.AppendFormat("{0:x2}", b); return hex.ToString();} or: public static string ByteArrayToString(byte[] ba){ return BitConverter.ToString(ba).Replace("-","");} There are even more variants of doing it, for example here . The reverse conversion would go like this: public static byte[] StringToByteArray(String hex){ int NumberChars = hex.Length; byte[] bytes = new byte[NumberChars / 2]; for (int i = 0; i < NumberChars; i += 2) bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16); return bytes;} Using Substring is the best option in combination with Convert.ToByte . See this answer for more information. If you need better performance, you must avoid Convert.ToByte before you can drop SubString .
{}
{'log_upvote_score': 12, 'links': ['https://Stackoverflow.com/questions/311165', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/19582/']}
jdg_380162
stackexchange
llm_judgeable_groundtruth_similarity
13109252
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I would like to invoke a javascript function (without JQuery) when the onclick even fires from a link_to tag in haml. How can I do this? Now provide the response and nothing else.
I think this could work: link_to "your link", href, :onclick => "jsFunction" Or, doing everything JS side: document.body.addEventListener('click',function(e){ var target = e.target || e.srcElement; if (target.tagName.toLowerCase() !== 'a') { return e;//not clicked on link } //a link was clicked, maybe check class or id or other stuff to narrow it down //if a link you were interested in was clicked: return theClickFunction.apply(target,[e]);},false);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13109252', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1165493/']}
jdg_380163
stackexchange
llm_judgeable_groundtruth_similarity
22424059
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 mongo collection with following structure { "userId" : ObjectId("XXX"), "itemId" : ObjectId("YYY"), "resourceId" : 1, "_id" : ObjectId("528455229486ca3606004ec9"), "parameter" : [ { "name" : "name1", "value" : 150, "_id" : ObjectId("528455359486ca3606004eed") }, { "name" : "name2", "value" : 0, "_id" : ObjectId("528455359486ca3606004eec") }, { "name" : "name3", "value" : 2, "_id" : ObjectId("528455359486ca3606004eeb") } ]} There can be multiple documents with the same 'useId' with different 'itemId' but the parameter will have same key/value pairs in all of them. What I am trying to accomplish is return aggregated parameters "name1", "name2" and "name3" for each unique "userId" disregard the 'itemId'. so final results would look like for each user : { "userId" : ObjectId("use1ID"), "name1" : (aggregatedValue), "name2" : (aggregatedValue), "name3" : (aggregatedVAlue) },{ "userId" : ObjectId("use2ID"), "name1" : (aggregatedValue), "name2" : (aggregatedValue), "name3" : (aggregatedVAlue) } Is it possible to accomplish this using the aggregated methods of mongoDB ? Could you please help me to build the proper query to accomplish that ? Now provide the response and nothing else.
The simplest form of this is to keep things keyed by the "parameter" "name": db.collection.aggregate( // Unwind the array { "$unwind": "$parameter"}, // Group on the "_id" and "name" and $sum "value" { "$group": { "_id": { "userId": "$userId", "name": "$parameter.name" }, "value": { "$sum": "$parameter.value" } }}, // Put things into an array for "nice" processing { "$group": { "_id": "$_id.userId", "values": { "$push": { "name": "$_id.name", "value": "$value" }} }}) If you really need to have the "values" of names as the field values, you can do the the following. But since you are "projecting" the fields/properties then you must specify them all in your code . You cannot be "dynamic" anymore and you are coding/generating each one: db.collection.aggregate([ // Unwind the array { "$unwind": "$parameter"}, // Group on the "_id" and "name" and $sum "value" { "$group": { "_id": { "userId": "$userId", "name": "$parameter.name" }, "value": { "$sum": "$parameter.value"} }}, // Project out discrete "field" names with $cond { "$project": { "name1": { "$cond": [ { "$eq": [ "$_id.name", "name1" ] }, "$value", 0 ]}, "name2": { "$cond": [ { "$eq": [ "$_id.name", "name2" ] }, "$value", 0 ]}, "name3": { "$cond": [ { "$eq": [ "$_id.name", "name3" ] }, "$value", 0 ]}, }}, // The $cond put "0" values in there. So clean up with $group and $sum { "$group": { _id: "$_id.userId", "name1": { "$sum": "$name1" }, "name2": { "$sum": "$name2" }, "name3": { "$sum": "$name3" } }} ]) So while the extra steps give you the result that you want ( well with a final project to change the _id to userId ), for my mind the short version is workable enough, unless you really do need it. Consider the output from there as well: { "_id" : ObjectId("53245016ea402b31d77b0372"), "values" : [ { "name" : "name3", "value" : 2 }, { "name" : "name2", "value" : 0 }, { "name" : "name1", "value" : 150 } ]} So that would be what I would use, personally. But your choice.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22424059', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/753669/']}
jdg_380164
stackexchange
llm_judgeable_groundtruth_similarity
30840782
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I would have thought that executing the following code for an empty collection that implements IEnumerable<T> would throw an exception: var enumerator = collection.GetEnumerator();enumerator.MoveNext();var type = enumerator.Current.GetType(); // Surely should throw? Because the collection is empty, then accessing IEnumerator.Current is invalid, and I would have expected an exception. However, no exception is thrown for List<T> . This is allowed by the documentation for IEnumerator<T>.Current , which states that Current is undefined under any of the following conditions: The enumerator is positioned before the first element in the collection, immediately after the enumerator is created. MoveNext must be called to advance the enumerator to the first element of the collection before reading the value of Current. The last call to MoveNext returned false, which indicates the end ofthe collection. The enumerator is invalidated due to changes made in the collection, such as adding, modifying, or deleting elements. (I'm assuming that "fails to throw an exception" can be categorised as "undefined behaviour"...) However, if you do the same thing but use an IEnumerable instead, you DO get an exception. This behaviour is specified by the documentation for IEnumerator.Current , which states: Current should throw an InvalidOperationException if the last call to MoveNext returned false, which indicates the end of the collection. My question is: Why this difference? Is there a good technical reason that I'm unaware of? It means identical-seeming code can behave very differently depending on whether it's using IEnumerable<T> or IEnumerable , as the following program demonstrates (note how the code inside showElementType1() and showElementType1() is identical): using System;using System.Collections;using System.Collections.Generic;namespace ConsoleApplication2{ class Program { public static void Main() { var list = new List<int>(); showElementType1(list); // Does not throw an exception. showElementType2(list); // Throws an exception. } private static void showElementType1(IEnumerable<int> collection) { var enumerator = collection.GetEnumerator(); enumerator.MoveNext(); var type = enumerator.Current.GetType(); // No exception thrown here. Console.WriteLine(type); } private static void showElementType2(IEnumerable collection) { var enumerator = collection.GetEnumerator(); enumerator.MoveNext(); var type = enumerator.Current.GetType(); // InvalidOperationException thrown here. Console.WriteLine(type); } }} Now provide the response and nothing else.
The problem with IEnumerable<T> is that Current is of type T . Instead of throwing an exception, default(T) is returned (it is set from MoveNextRare ). When using IEnumerable you don't have the type, and you can't return a default value. The actual problem is you don't check the return value of MoveNext . If it returns false , you shouldn't call Current . The exception is okay. I think they found it more convenient to return default(T) in the IEnumerable<T> case. Exception handling brings overhead, returning default(T) doesn't (that much). Maybe they just thought there was nothing useful to return from the Current property in the case of IEnumerable (they don't know the type). That problem is 'solved' in IEnumerable<T> when using default(T) . According to this bug report (thanks Jesse for commenting): For performance reasons the Current property of generated Enumerators is kept extremely simple - it simply returns the value of the generated 'current' backing field. This could point in the direction of the overhead of exception handling. Or the required extra step to validate the value of current . They effectively just wave the responsibility to foreach , since that is the main user of the enumerator: The vast majority of interactions with enumerators are in the form of foreach loops which already guard against accessing current in either of these states so it would be wasteful to burn extra CPU cycles for every iteration to check for these states that almost no one will ever encounter.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/30840782', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/106159/']}
jdg_380165
stackexchange
llm_judgeable_groundtruth_similarity
48466028
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: As I got from 'Cloud Firestore Data Model' guide "each document is identified by a name." Is it possible to query a collection by that document identifier (which is the name or ID)? For example, documents in the collection "Things" have IDs: 0, 1, 2 etc.: Is it possible to query documents which IDs are less than 100? Now provide the response and nothing else.
You can query by documentId using the special sentinel FieldPath.documentId() , e.g.: const querySnap = collection.where(firebase.firestore.FieldPath.documentId(), '<', '100').get(); But be aware that document IDs are strings and therefore this will include documents with ID '0' or '1', but not '2' since '2' > '100' lexicographically. So if you want a numeric query, you'll need to write the document ID as a numeric field in the document and then do a normal query on it.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/48466028', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2825964/']}
jdg_380166
stackexchange
llm_judgeable_groundtruth_similarity
410626
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I am reading up on TCP/IP and other related protocols and technologies. MAC addresses are described as being (reasonably :) unique, and as having a large possibility space (several hundred trillions), while also being assigned to all network interfaces. What are the historical and technical reasons why IPv4 or IPv6 addresses are used instead of MAC addresses for internetwork communication? Am I missing something fundamental or is it just a silly reason (e.g. building on top of legacy tech)? Now provide the response and nothing else.
The MAC address might be unique, but there's nothing special about the number that would indicate where it is. MAC 00-00-00-00-00-00 might be on the other side of the planet from 00-00-00-00-00-01 . IP is an arbitrary numbering scheme imposed in a hierarchical fashion on a group of computers to logically distinguish them as a group (that's what a subnet is). Sending messages between those groups is done by routing tables, themselves divided into multiple levels so that we don't have to keep track of every single subnet. For instance, 17.x.x.x is within the Apple network. From there, Apple will know where each of its thousands of subnets are located and how to get to them (nobody else needs to know this information, they just need to know that 17.anything goes to Apple). It's also pretty easy to relate this to another pair of systems. You have a State Issued ID Number, why would you need a mailing address if that ID number is already unique to just you? You need the mailing address because it's an arbitrary system that describes where the unique destination for communications to you should go.
{}
{'log_upvote_score': 9, 'links': ['https://serverfault.com/questions/410626', 'https://serverfault.com', 'https://serverfault.com/users/53391/']}
jdg_380167
stackexchange
llm_judgeable_groundtruth_similarity
26255344
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 change video poster and source VideoJS when selectedVideo changed var VideoPlayer = React.createClass({ render: function() { var selectedVideo = this.props.selectedVideo; function filterVideo(video) { return video.id == selectedVideo; } var data = this.props.videos.filter(filterVideo); return ( <div className="col-md-6 videoplayer"> <h2>{data[0].title}</h2> <video id="videoplayer" className="video-js vjs-default-skin vjs-big-play-centered" controls preload="none" width="100%" height="300" poster={data[0].poster} data-setup="{}"> <source src={data[0].video} type='video/mp4' /> </video> <div className="video-description"> {data[0].description} </div> </div> ); }}); but i got error: Uncaught Error: Invariant Violation: ReactMount: Two valid but unequal nodes with the same `data-reactid`: .0.0.1.1 title and description changed but video poster doesn't change Now provide the response and nothing else.
This is a problem with destructive libraries. Basically what happens is you render the <video> element, and then VideoJS injects a bunch of sibling elements next to your <video> (child elements are fine). React tries to update the element, and it can't figure out what's going on, so it panics and gives that error. So you have two options: Option 1: render a <div ref="target" /> , construct the video node in componentDidMount and this.refs.target.appendChild(that) , and then invoke VideoJS manually. In componentWillRecieveProps you need to update the poster img's src directly. Option 2: fork video.js and make it only emit events instead of directly modifying the DOM. Your component would react to those events, modifying state, and rendering the poster, buttons, etc. Option 1 is easier, option 2 is potentially more efficient and cleaner. I'd go with option 1. Neither of these are good solutions, but libraries that escape their container don't play nicely with react.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26255344', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3859283/']}
jdg_380168
stackexchange
llm_judgeable_groundtruth_similarity
2717614
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 display a random string each time a button is pressed from a set of strings defined in strings.xml . this is an example of the strings ID's <string name="q0"> <string name="q1"> <string name="q2"> <string name="q3"> <string name="q4"> java code for getting a random string. private static final Random rgenerator = null; int RandomQ = R.string.q0 (rgenerator.nextInt(5) + 1); String q = getString(RandomQ); if i try to use this java code i get an error at "q0" in R.string.q0 which is The method q0(int) is undefined for the type R.string if i try to use the quick fix and create a method, it works. but it wont let me save or run the app because it replaces my create method and shows this message R.java was modified manually! Reverting to generated version! thanks for reading. Now provide the response and nothing else.
You can define your strings in an array which will help simplify this task (res/values/array.xml): <string-array name="myArray"> <item>string 1</item> <item>string 2</item> <item>string 3</item> <item>string 4</item> <item>string 5</item></string-array> You can then create an array to hold the strings and select a random string from the array to use: private String[] myString; myString = res.getStringArray(R.array.myArray); String q = myString[rgenerator.nextInt(myString.length)]; Example code : package com.test.test200;import java.util.Random;import android.app.Activity;import android.content.res.Resources;import android.os.Bundle;import android.widget.TextView;public class Test extends Activity {/** Called when the activity is first created. */ private String[] myString; private static final Random rgenerator = new Random();@Overridepublic void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Resources res = getResources(); myString = res.getStringArray(R.array.myArray); String q = myString[rgenerator.nextInt(myString.length)]; TextView tv = (TextView) findViewById(R.id.text1); tv.setText(q);}}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2717614', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/326423/']}
jdg_380169
stackexchange
llm_judgeable_groundtruth_similarity
40891868
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 facing a problem about angular async call inside angular.forEach. How to wait for nested async call finished, then go to next foreach object. For below concept example. Suppose i insert record to database with temp code is 1200, 1201, 1202. Now i found the problem point is first finish forEach loop by 1200, then createMember through factory, so the 3 record temp code was 1200, 1200, 1200.how should i fix in correct loop order. I want the sequence is //1200forEach 1 of $scope.xyzList -> getTempCode -> createMember -> updateTempCode, //1201forEach 2 of $scope.xyzList -> getTempCode -> createMember -> updateTempCode, //1202forEach 3 of $scope.xyzList -> getTempCode -> createMember -> updateTempCode, Sample Concept Code as below Suppose $scope.xyzList object list have 3 objects. var data = {"code": "null"};angular.forEach($scope.xyzList, function(v, k){ $http({ method: 'POST', url: 'http://xxxx.com/getTempCode', // for example temp code: 1200 data: JSON.stringify(data), headers: {'Content-Type': 'application/json'} }).then(function(obj) { $scope.createMember(obj, v); }})$scope.createMember = function(obj, listVal) { var currentCode = obj; var cdata = {"code": currentCode}; var memberView = New MemberView(); memberView.code = obj; memberView.name = listVal.name; $http({ method: 'POST', url: 'http://xxxx.com/checkCodeExist', data: JSON.stringify(data), headers: {'Content-Type': 'application/json'} }).then(function(rs) { if (rs.code == null) { xxxxFactory.createMember($rootScope.global.systemObj, memberView) .then(function(result){ $http({ method: 'POST', url: 'http://xxxx.com/updateTempCode', // Temp code + 1 data: JSON.stringify(cdata), headers: {'Content-Type': 'application/json'} }) }) } }} Now provide the response and nothing else.
Based on https://github.com/gradle/gradle/issues/6172#issuecomment-409883128 Amended in 2020 to take lazy task configuration and Gradle 5 into account. See answer's history for older versions. plugins { id "java"}def test = tasks.named("test") { useJUnitPlatform { excludeTags "integration" }}def integrationTest = tasks.register("integrationTest2", Test) { useJUnitPlatform { includeTags "integration" } shouldRunAfter test}tasks.named("check") { dependsOn integrationTest} Running gradlew test will run tests without integration gradlew integrationTest will run only integration test gradlew check will run test followed by integrationTest gradlew integrationTest test will run test followed by integrationTest note: order is swapped because of shouldRunAfter History Gradle 4.6+ supports JUnit 5 natively JUnit 5 deprecated their plugin: https://github.com/junit-team/junit5/issues/1317 JUnit 5 deleted plugin: 'org.junit.platform.gradle.plugin' JUnit 5 closed junit5#579 (same as OP's question) as won't-fix (due to decommissioning their plugin) Gradle supports the above feature: https://github.com/gradle/gradle/issues/6172 Tip Note: while the above works, IntelliJ IDEA has a hard time inferring stuff, so I suggest to use this more explicit version where everything is typed and code completion is fully supported : ... { Test task -> task.useJUnitPlatform { org.gradle.api.tasks.testing.junitplatform.JUnitPlatformOptions options -> options.includeTags 'integration' }} build.gradle.kts Root project Kotlin DSL drop-in for configuring integration tests in all modules in Gradle 5.6.4 allprojects { plugins.withId("java") { @Suppress("UnstableApiUsage") [email protected] { val test = "test"(Test::class) { useJUnitPlatform { excludeTags("integration") } } val integrationTest = register<Test>("integrationTest") { useJUnitPlatform { includeTags("integration") } shouldRunAfter(test) } "check" { dependsOn(integrationTest) } } }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/40891868', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1249002/']}
jdg_380170
stackexchange
llm_judgeable_groundtruth_similarity
17845932
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there a way to render a Meteor template as the HTML body of an email? For example if I want to show collection data or generate dynamic links inside that email. Now provide the response and nothing else.
Yes this is possible, here I provide a client-side solution to this common problem. First you should define a simple template that will serve as your email html body : <template name="shareEmailContent"> <p>{{message}}</p> <a href="{{url}}">{{title}}</a></template> Then you can use Email.send (see Email.send at docs.meteor.com , you'll need some proper configuration such as adding the email Smart Package and setting MAIL_URL ) to email the result of the template rendering.Email.send only works on the server, so you must define a server method callable from the client. Server side : Meteor.methods({ sendShareEmail:function(options){ // you should probably validate options using check before actually // sending email check(options,{ from:String, // etc... }); Email.send(options); }}); Client side : var dataContext={ message:"You must see this, it's amazing !", url:"http://myapp.com/content/amazingstuff", title:"Amazing stuff, click me !"};var html=Blaze.toHTMLWithData(Template.shareEmailContent,dataContext);var options={ from:"[email protected]", to:"[email protected]", subject:"I want to share this with you !", html:html })};Meteor.call("sendShareEmail",options); As mentioned in the comments, you can also decide to render email templates on the server. Server-side rendering is not yet supported but you can still accomplish it using a third party templating package. EDIT 06/09/2014 : updated to use the latest Blaze API as of Meteor 0.9.1
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17845932', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1307721/']}
jdg_380171
stackexchange
llm_judgeable_groundtruth_similarity
425439
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 partially nfilled array of objects, and when I iterate through them I tried to check to see whether the selected object is null before I do other stuff with it. However, even the act of checking if it is null seem to through a NullPointerException . array.length will include all null elements as well. How do you go about checking for null elements in an array? For example in the following code will throw an NPE for me. Object[][] someArray = new Object[5][];for (int i=0; i<=someArray.length-1; i++) { if (someArray[i]!=null) { //do something } } Now provide the response and nothing else.
You have more going on than you said. I ran the following expanded test from your example: public class test { public static void main(String[] args) { Object[][] someArray = new Object[5][]; someArray[0] = new Object[10]; someArray[1] = null; someArray[2] = new Object[1]; someArray[3] = null; someArray[4] = new Object[5]; for (int i=0; i<=someArray.length-1; i++) { if (someArray[i] != null) { System.out.println("not null"); } else { System.out.println("null"); } } }} and got the expected output: $ /cygdrive/c/Program\ Files/Java/jdk1.6.0_03/bin/java -cp . testnot nullnullnot nullnullnot null Are you possibly trying to check the lengths of someArray[index]?
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/425439', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/37857/']}
jdg_380172
stackexchange
llm_judgeable_groundtruth_similarity
542677
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I know there a 3 different class of ip address reserved for privete network. they are 192.168.0.0/16 , 172.16.0.0/12 and 10.0.0.0/8. in our company we use 192.168.0.0/16 for many things, servers,printers,vpn,computers etc. but I have noticed many other company use 172.16.0.0/12 or 10.0.0.0/8 instead. I know the technical differences, they are offer different numbers of contiguous segment and the quantity of ips. but can you tell me why they use 172.xx or 10.xxx ? what's the advantage in a network infrastructure? Now provide the response and nothing else.
There is no technical difference. The main reason I choose to avoid 192.168 like the plague is that every piece of SOHO equipment comes out of the box using it; often, using 192.168.0/24, which means that many company networks that have grown from small installations using this equipment are still using that address range. Sooner or later, every RFC1918-addressed network I've ever run ends up needing to peer (via VPN) with some other RFC1918-addressed network. If there's no overlap, it make the whole job much easier; 172.16 networks have the least chance of overlapping, simply because so few people choose to use that space. 10. is next best, though don't run with a /8 netmask unless you know for a fact that it's a good idea (hint: it never is). Edit : Kossel, I don't entirely understand your comment. If you mean "can I use 192.168 for the desktops but NAT it all to 172.16 for VPN purposes", that's exactly the sort of headaches us old-timers are grumbling about in the comments. It's much better if your office network doesn't overlap with the network you're trying to VPN to. Usually you don't control the addressing on the remote network, it belongs to some business partner or outsourced provider, who will have often picked 192.168 for their network. So I find the chances of avoiding overlap are maximised when I'm using 172.16 on my desktops.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/542677', 'https://serverfault.com', 'https://serverfault.com/users/115924/']}
jdg_380173
stackexchange
llm_judgeable_groundtruth_similarity
12454408
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: From Objective C Programming Guide (Under the "Object Messaging" section), Methods that take a variable number of parameters are also possible,though they’re somewhat rare. Extra parameters are separated by commasafter the end of the method name. (Unlike colons, the commas are notconsidered part of the name.) In the following example, the imaginarymakeGroup: method is passed one required parameter (group) and threeparameters that are optional: [receiver makeGroup:group, memberOne, memberTwo, memberThree]; I tried to create such a method and it shows an error "Expected ';' after method prototype" when I try to declare the below function in my interface file(.h file). - (void) printMyClass: (int) x, (int) y, (int) z; Can anyone give sample example to create such a method like makeGroup Thank you Now provide the response and nothing else.
You can see this link . In your header file define the methods with three dots at the end -(void)yourMethods:(id)string1,...; And in you implementation file write the methods body -(void)yourMethods:(id)string1, ...{ NSMutableArray *arguments=[[NSMutableArray alloc]initWithArray:nil]; id eachObject; va_list argumentList; if (string1) { [arguments addObject: string1]; va_start(argumentList, string1); while ((eachObject = va_arg(argumentList, id))) { [arguments addObject: eachObject]; } va_end(argumentList); } NSLog(@"%@",arguments);} Now call your method [self yourMethods:@"ab",@"cd",@"ef",@"gf",nil]; NOTE: remember to put nil at the end
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12454408', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1389515/']}
jdg_380174
stackexchange
llm_judgeable_groundtruth_similarity
45462987
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Trying to migrate my project to java8 + Junit5 using IntelliJ 2017.2 I have added junit-jupiter-api version 5.0.0-M6 and junit-platform-launcher version 1.0.0-M6 Project structure is a default maven convention src/test/java Found a couple articles about this but none of them did solve my issue. It runs nicely in a console, I presume this is something to do with the IntelliJ default JUnit Runner, or I am missing some dependencies? When I Run a single test class all works fine but when I select the directory and Run all 'Tests' in Java like I used to do then I encounter few errors. WARNING: TestEngine with ID 'junit-jupiter' failed to discover testsjava.lang.NoSuchMethodError: org.junit.platform.engine.TestDescriptor.pruneTree()VAug 02, 2017 2:44:56 PM org.junit.platform.launcher.core.DefaultLauncher handleThrowableWARNING: TestEngine with ID 'junit-vintage' failed to discover testsjava.lang.NoSuchMethodError: org.junit.platform.engine.EngineDiscoveryRequest.getDiscoveryFiltersByType(Ljava/lang/Class;)Ljava/util/List;Aug 02, 2017 2:44:56 PM org.junit.platform.launcher.core.DefaultLauncher handleThrowableWARNING: TestEngine with ID 'junit-jupiter' failed to discover testsjava.lang.NoSuchMethodError: org.junit.platform.engine.TestDescriptor.pruneTree()VAug 02, 2017 2:44:56 PM org.junit.platform.launcher.core.DefaultLauncher handleThrowableWARNING: TestEngine with ID 'junit-vintage' failed to discover testsjava.lang.NoSuchMethodError: org.junit.platform.engine.EngineDiscoveryRequest.getDiscoveryFiltersByType(Ljava/lang/Class;)Ljava/util/List; Note : I have not migrated any tests yet, all are Junit 4 syntax. Now provide the response and nothing else.
Adding specific dependencies solve the problem. NOTE: UPDATE INTELLIJ ABOVE 2017.2.0 AS THERE WAS A BUG WITH THE JUNIT LAUNCHER OXYGEN if you using eclipse. Below dependency enables Junit5 parametrized tests which can be used instead of a DataProvider . "org.junit.jupiter:junit-jupiter-params:5.0.0"//for JUnit5 parametrized tests. Junit5 API . "org.junit.jupiter:junit-jupiter-api:5.0.0"//JUnit5 API Needed if you want to run legacy JUnit4 tests without changing the syntax and imports. "org.junit.vintage:junit-vintage-engine:4:12.0"//for legacy JUnit4 tests EDIT: 07/2018 Match the version of the vintage runner to the jupiter version Needed if you want to run JUnit5 tests with new syntax and imports. "org.junit.jupiter:junit-jupiter-engine:5.0.0"//for JUnit5 tests java.lang.NoSuchMethodError: org.junit.platform.engine.EngineDiscoveryRequest.getDiscoveryFiltersByType(Ljava/lang/Class;)Ljava/util/List; Launcher . "org.junit.platform:junit-platform-launcher:1.0.0//to handle default launcher Exception in thread "main" java.lang.NoSuchMethodError: org.junit.platform.commons.util.ReflectionUtils.getDefaultClassLoader()Ljava/lang/ClassLoader; Additional info how to install JUnit5 Since version 4.6 for Gradle, there is no need for plugins anymoreGradle supports Junit5 natively just do: And the version of the vintage runner is now same as the JUnit 5 version. dependencies { testImplementation "org.junit.jupiter:junit-jupiter-params:$junitVersion" testImplementation "org.junit.jupiter:junit-jupiter-api:$junitVersion" testRuntimeOnly "org.junit.vintage:junit-vintage-engine:$junitVersion" testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:$junitVersion"}test { useJUnitPlatform { includeEngines 'junit-jupiter', 'junit-vintage' }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/45462987', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4664558/']}
jdg_380175
stackexchange
llm_judgeable_groundtruth_similarity
97024
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 have 10 models analysing pupal developmental rates ( DR ) and developmental times ( DT ) depending on a number of factors: m1 <- lm(DR ~ population+sex+temperature+weight+population*temperature)m2 <- lm(DR ~ population+sex+population*sex)m3 <- lm(DR ~ population+sex+temperature+population*temperature)m4 <- gls(DR ~ population+sex, ...)m5 <- lm(DR ~ population+sex+temperature+weight+population*temperature)m6 <- glm(DT ~ sex+temperature+weight, gamma) ... and so on The models refer to datasets of two different species, two different years and different phases of pupal development. One of the reviewers asked for control of the experiment-wide false discovery rate, which is not so common in the field of ecology. In many of the examples from genetics and medical studies one testing results in only one p-value, which is then adjusted using the FDR procedures. How does it work in my case? Extracting p-values of only, say, the population variable and use them? And then the same separately for sex and so on? Or use all the p-values from each of the models as one vector? If so, what shall I do in cases when the factor has already been excluded from the final model – skip them and use only the ones left? Add them back to the model? Now provide the response and nothing else.
@Dian breathe easy, it's pretty much not too difficult. So let's work from familiar territory to false discovery rate (FDR). First, I see that you have a bunch of outcomes, with a varying number of predictors. Someone who is more familiar with multivariate regression (i.e. multiple dependent variables, assuming possible correlations between errors of different models) will have to speak to whether your modeling approach is the best one. Let's take it as given. Each of your models will produce some number of $p$-values (incidentally I am an epidemiologist, and have absolutely no idea what you mean about "only one $p$-value." If that were true, it would change the nature of my work and that of my colleagues considerably. :). You could go ahead and test your hypotheses about individual effects separately using these $p$-values. Unfortunately, hypothesis testing is like the lottery (the more you play, the more your chance to "win"), so if you want to go into each hypothesis test assuming that the null hypothesis is true , then you are in trouble, because $\alpha$ (your willingness to make/probability of making a false rejection of a true null hypothesis) only applies to a single test. You may have heard of "the Bonferroni correction/adjustment", where you try to solve this conundrum by multiplying your $p$-values by the total number of null hypotheses you are testing (let's call that number of tests $m$). You are effectively trying to redefine $\alpha$ as a family-wise error rate (FWER), or the probability of making at least one false rejection out of a family of tests, assuming all null hypotheses are true. Alternatively, and equivalently, you can think about the Bonferroni adjustment as dividing $\alpha$ by $m$ (or $\alpha/2$ by $m$ if you are performing two-tailed tests, which in all likelihood you are in a regression context). We get these two alternatives because basing a rejection decision on $p \le \frac{\alpha/2}{m}$ is equivalent to $mp \le \frac{\alpha}{2}$. Of course, the Bonferroni technique is a blunt hammer. It positively hemorrhages statistical power. $\overset{_{\vee}}{\mathrm{S}}\mathrm{idák}$ got a smidge more statistical power, by altering the adjustment of the $p$-value to $1-(1-p)^{m}$. Holm improved upon both Bonferroni and $\overset{_{\vee}}{\mathrm{S}}\mathrm{idák}$ adjustments by creating a stepwise adjustment. The step-up procedure for the Bonferroni adjustemnt: Compute the exact $p$-value for each test. Order the $p$-values from smallest to largest. For the first test, adjust the $p$-value to be $pm$; and generally: For the i$^{\text{th}}$ test, adjust the $p$-value to be $p(m–(i–1))$. Using Holm’s method, for all tests following the first test for which we fail to reject H$_{0}$ we will also fail to reject the null hypothesis. The Holm-$\overset{_{\vee}}{\mathrm{S}}\mathrm{idák}$ adjustment is similar, but you would adjust each $p$-value using $1-(1-p)^{m-(i-1)}$. Some folks, most notably Benjamini and Hochberg (1995), were not comfortable with the world view implied by the assumption that all null hypotheses are true within a stepwise procedure. Surely, they reasoned, if you make an adjustment and reject a single hypothesis, that must imply that a better assumption would be that the remaining $m-1$ hypotheses have a lower probability of all null hypotheses being true? Also, science in general does not assume that there are no relationships in the world: quite the opposite, in fact. Enter the FDR which progressively assumes that rejection probabilities must increase if previous hypotheses were rejected after adjustment. Here's the step - down procedure they proposed: Compute the exact $p$-value for each test. Order the $p$-values from largest to smallest (step- down !). For the first test ($i=1$), adjust the $p$-value to be $\frac{pm}{m-(1-1)} = p$. For the i$^{\text{th}}$ test, adjust the $p$-value to be $\frac{pm}{m-(i–1)}$. Using Benjamini & Hochberg’s method, we reject all tests including and following the first test for which we reject the null hypothesis. We often term $p$-values that have been adjusted this way $q$-values. The advantages of this FDR adjustment include (1) more statistical power, especially for large $m$, and (2) easy integration of additional tests/$p$-values (say, adding $p$-values from an additional regression model) in a manner which leaves the inferences from the first FDR adjustment unchanged. Update: All these FWER procedures, and the FDR procedure I just described can produce adjusted $p$-values that are greater than one. When reporting adjusted $p$-values, these are typically reported as $p=1$, $p>.999$, $p=$ not reject or something along those lines. References Benjamini, Y. and Hochberg, Y. (1995). Controlling the False Discovery Rate: A Practical and Powerful Approach to Multiple Testing. Journal of the Royal Statistical Society. Series B (Methodological) , 57(1):289–300.
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/97024', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/45258/']}
jdg_380176
stackexchange
llm_judgeable_groundtruth_similarity
14550802
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 the context: git revert HEAD~2 myFilefatal: bad revision '/Users/rose/gitTest/myFile' I'm sure HEAD~2 exists. EDIT Amber is correct. I meant to use reset instead of revert . Now provide the response and nothing else.
If you only want to revert a single file to its state in a given commit, you actually want to use the checkout command: git checkout HEAD~2 myFile The revert command is used for reverting entire commits (and it doesn't revert you to that commit; it actually just reverts the changes made by that commit - if you have another commit after the one you specify, the later commit won't be reverted).
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14550802', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/365298/']}
jdg_380177
stackexchange
llm_judgeable_groundtruth_similarity
23670079
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 checkout form that uses php to load some javascript & html into #Div-A when the page loads. The javascript binds a click event to #Button-A in the same div. Something like this: <div id="#Div-A"><input type="button" id="Button-A"/><script type="text/javascript"> $('#Button-A').bind('click', function() { $.ajax({ type: 'get', url: 'some/url/gets/called', success: function() { this happens on success } });});</script></div> Afterward, #Global-Button is created and a javascript function binds a different click event to this second button which then triggers #Button-A to be clicked like this: $('#Global-Button').live('click', function(event) { $("#Button-A").trigger("click");}) The reason being that the contents of #Div-A can change (via ajax), so the second button acts as a global trigger regardless of which button or function happens to reside in #Div-A . The problem I'm encountering is that for some reason if #Global-Button is clicked after page load #Button-A gets triggered twice . If an Ajax event reloads the contents of #Div-A then all is well and the the trigger happens only once as it should. I've examined the html within #Div-A before and after reloading via Ajax and everything appears to be identical. There are definitely no duplicate buttons or functions anywhere as far as I can see that would cause two events to be triggered. I know only a very little about the DOM and can only guess this has something to do with the order in which things are loaded and events are bound. Now provide the response and nothing else.
This is always recommended to use 'unbind' before bind to make sure the event is not bound multiple times. In your case, there may be two possibilities - '#Global-Button' click function is bound twice. '#Button-A' click function is bound twice and '#Global-Button' is actually triggering the click once. Change your code like - $('#Global-Button').unbind('click').bind('click', function(event) { $("#Button-A").trigger("click");}) and also - $('#Button-A').unbind('click').bind('click', function() { $.ajax({ type: 'get', url: 'some/url/gets/called', success: function() { this happens on success } });});
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23670079', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1767412/']}
jdg_380178
stackexchange
llm_judgeable_groundtruth_similarity
20210787
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a matrix like so: Only in reality it is hundreds or thousands of values. What I need to do is return the minimum value for each row, along with the row/col name. So for row 1 in the example, "BAC", the minimum is 0.92 for BAC/CSCO, so I need to return something like: BAC/CSCO 0.92 And then repeat this for each row in the matrix. Assistance is greatly appreciated. I think apply is the trick, but I can't quite get the right combination. Now provide the response and nothing else.
X <- matrix(runif(20), nrow=4)rownames(X) <- paste0("foo", seq(nrow(X)))colnames(X) <- paste0("bar", seq(ncol(X)))result <- t(sapply(seq(nrow(X)), function(i) { j <- which.min(X[i,]) c(paste(rownames(X)[i], colnames(X)[j], sep='/'), X[i,j])}))print(X)print(result) will give you: bar1 bar2 bar3 bar4 bar5foo1 0.2085419 0.6290522 0.12730378 0.17775105 0.3239684foo2 0.8061464 0.7948392 0.09330563 0.06698921 0.5557932foo3 0.1790950 0.7788139 0.35787944 0.39117325 0.2578457foo4 0.9099254 0.4048508 0.54791272 0.38674301 0.3272156 and [,1] [,2] [1,] "foo1/bar3" "0.127303782384843" [2,] "foo2/bar4" "0.0669892099685967"[3,] "foo3/bar1" "0.179094966035336" [4,] "foo4/bar5" "0.327215566998348"
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20210787', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1530260/']}
jdg_380179
stackexchange
llm_judgeable_groundtruth_similarity
466946
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: .NET offers a generic list container whose performance is almost identical (see Performance of Arrays vs. Lists question). However they are quite different in initialization. Arrays are very easy to initialize with a default value, and by definition they already have certain size: string[] Ar = new string[10]; Which allows one to safely assign random items, say: Ar[5]="hello"; with list things are more tricky. I can see two ways of doing the same initialization, neither of which is what you would call elegant: List<string> L = new List<string>(10);for (int i=0;i<10;i++) L.Add(null); or string[] Ar = new string[10];List<string> L = new List<string>(Ar); What would be a cleaner way? EDIT: The answers so far refer to capacity, which is something else than pre-populating a list. For example, on a list just created with a capacity of 10, one cannot do L[2]="somevalue" EDIT 2: People wonder why I want to use lists this way, as it is not the way they are intended to be used. I can see two reasons: One could quite convincingly argue that lists are the "next generation" arrays, adding flexibility with almost no penalty. Therefore one should use them by default. I'm pointing out they might not be as easy to initialize. What I'm currently writing is a base class offering default functionality as part of a bigger framework. In the default functionality I offer, the size of the List is known in advanced and therefore I could have used an array. However, I want to offer any base class the chance to dynamically extend it and therefore I opt for a list. Now provide the response and nothing else.
I can't say I need this very often - could you give more details as to why you want this? I'd probably put it as a static method in a helper class: public static class Lists{ public static List<T> RepeatedDefault<T>(int count) { return Repeated(default(T), count); } public static List<T> Repeated<T>(T value, int count) { List<T> ret = new List<T>(count); ret.AddRange(Enumerable.Repeat(value, count)); return ret; }} You could use Enumerable.Repeat(default(T), count).ToList() but that would be inefficient due to buffer resizing. Note that if T is a reference type, it will store count copies of the reference passed for the value parameter - so they will all refer to the same object. That may or may not be what you want, depending on your use case. EDIT: As noted in comments, you could make Repeated use a loop to populate the list if you wanted to. That would be slightly faster too. Personally I find the code using Repeat more descriptive, and suspect that in the real world the performance difference would be irrelevant, but your mileage may vary.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/466946', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2892/']}
jdg_380180
stackexchange
llm_judgeable_groundtruth_similarity
39032325
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 implemented an high pass filter in python using this code: from scipy.signal import butter, filtfiltimport numpy as npdef butter_highpass(cutoff, fs, order=5): nyq = 0.5 * fs normal_cutoff = cutoff / nyq b, a = butter(order, normal_cutoff, btype='high', analog=False) return b, adef butter_highpass_filter(data, cutoff, fs, order=5): b, a = butter_highpass(cutoff, fs, order=order) y = filtfilt(b, a, data) return yrawdata = np.loadtxt('sampleSignal.txt', skiprows=0)signal = rawdatafs = 100000.0cutoff = 100order = 6conditioned_signal = butter_highpass_filter(signal, cutoff, fs, order) I am applying this filter on a 100 kHz voltage signal and it works fine for cutoff frequencies >= 60 Hz. But it doesn't work below. I would like to cut off all the frequencies below 10 Hz. Any hints where my mistake is? What I observed is the lower the order of the filter the lower the cutoff frequency could be. The sample Signal can be found here. Now provide the response and nothing else.
I hope this can help you: import numpy as npimport pandas as pdfrom scipy import signalimport matplotlib.pyplot as pltdef sine_generator(fs, sinefreq, duration): T = duration nsamples = fs * T w = 2. * np.pi * sinefreq t_sine = np.linspace(0, T, nsamples, endpoint=False) y_sine = np.sin(w * t_sine) result = pd.DataFrame({ 'data' : y_sine} ,index=t_sine) return resultdef butter_highpass(cutoff, fs, order=5): nyq = 0.5 * fs normal_cutoff = cutoff / nyq b, a = signal.butter(order, normal_cutoff, btype='high', analog=False) return b, adef butter_highpass_filter(data, cutoff, fs, order=5): b, a = butter_highpass(cutoff, fs, order=order) y = signal.filtfilt(b, a, data) return yfps = 30sine_fq = 10 #Hzduration = 10 #secondssine_5Hz = sine_generator(fps,sine_fq,duration)sine_fq = 1 #Hzduration = 10 #secondssine_1Hz = sine_generator(fps,sine_fq,duration)sine = sine_5Hz + sine_1Hzfiltered_sine = butter_highpass_filter(sine.data,10,fps)plt.figure(figsize=(20,10))plt.subplot(211)plt.plot(range(len(sine)),sine)plt.title('generated signal')plt.subplot(212)plt.plot(range(len(filtered_sine)),filtered_sine)plt.title('filtered signal')plt.show()
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39032325', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3573247/']}
jdg_380181
stackexchange
llm_judgeable_groundtruth_similarity
2405802
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Prove that the set $\Big\{ 1/(n+1): n \in \mathbb{N} \Big\} \cup \big\{ 0 \big\} $ is closed By definition of closed, I know that you have to show that the complement of the set is open. But I don't know how to take its complement. How should I do it? Or are there other ways to show that a set is open? Now provide the response and nothing else.
Let $A = \{ \frac{1}{n+1}: n\in\mathbb{N} \} \cup \{0\}$. Then $$A^{c} = \left(\bigcup_{n=1}^{\infty}\left(\frac{1}{n+1},\frac{1}{n}\right)\right) \cup (-\infty,0) \cup (1,\infty)$$ is a countable union of open intervals (which are open sets), hence it is open. Therefore $A$ is closed. $\textbf{Edit}$: my answer assumed that $\mathbb{N}$ includes $0$. If your convention for $\mathbb{N}$ does not include $0$, then we would have $$A^{c} = \left(\bigcup_{n=2}^{\infty}\left(\frac{1}{n+1},\frac{1}{n}\right)\right) \cup (-\infty,0) \cup \left(\frac{1}{2},\infty\right)$$ and the conclusion is the same.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2405802', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/474492/']}
jdg_380182
stackexchange
llm_judgeable_groundtruth_similarity
33832488
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 object-oriented R programming (especially Winston Chang's R6 package), what is an active binding ? Now provide the response and nothing else.
First it is probably best to understand what a "binding" is. If we run code like: x <- 5 then what has happened inside the computer is that we have put the value of 5 into a slot of memory and we have also 'bound' the name "x" to that location and value so that later we can use x and it will go to that memory location and look up the value (which is 5 until we change it to something else). This is called a static binding because the value does not change unless the program specifically makes a change. An active binding is similar in that we bind a variable name (like "x") to something, but that something is not just a constant value, but rather a function that will be run every time we try to access x . So you could bind the name "x" to a function that calls rnorm and then each time you access x you would see a different random normal value. Another example, consider if we do something with static bindings like: mydf <- data.frame( x=1:10, y=10:1 )df.size <- nrow(mydf)mydf <- data.frame(z=1:100) Now the variable df.size has the number of rows of mydf when it was created, not how many rows it has now (since nrow was run once, then the result was put into the df.size variable as a static binding, it does not update with changes to the data frame). If on the other hand we created an active binding between df.size and a function that ran nrow(mydf) then any time we looked at the "value" of df.size then it would show the current number of rows in mydf no matter how many times we change it.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33832488', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1308031/']}
jdg_380183
stackexchange
llm_judgeable_groundtruth_similarity
76667
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am reading the book about abstract algebra, which author of Joseph Gallian. In the book, at page 35, about the Group.Having a example, but I dont understand it. The set S of positive irrational numbers together with 1 under multiplication satisfies the three properties given in the definition of a group but is not a group. Indeed, $\sqrt{2}.\sqrt{2} = 2$, so S is not closed under multiplication Why is S not closed under multiplication and S not group ??? Thanks ! Now provide the response and nothing else.
You can easily verify that there is only one solution: if $x\leq0$ then $x\cdot\mathrm e^x\leq0<1$; if $x>0$ then $x\cdot\mathrm e^x=1$ iff $\mathrm e^x = \frac1x$ (see the graph below); indeed, $\mathrm e^x$ increases and $\frac1x$ decreases on the set $\{x>0\}$ so there is no more than one solution. The solution exists since $\mathrm e^{0.1}<10$ but on the other hand $\mathrm e^1>1$ and hence by Intermediate Value Theorem there is a point $x\in (0.1,1)$ such that $\mathrm e^x = \frac1x$. This point you can easily find numerically: $x\approx 0.567143$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/76667', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/16873/']}
jdg_380184
stackexchange
llm_judgeable_groundtruth_similarity
2434156
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 capture the content of the WebBrowser control. DrawToBitmap() would work perfectly, but it is not supported in documentation for the WebBrowser control. I have been trying to find another way to capture the contents of the WebBrowser control and save them to a local image file. Does anyone have any workarounds or other methods to save the contents of the WebBrowser control to a local image file? Now provide the response and nothing else.
The Control.DrawToBitmap doesn't always work so I resorted to the following native API calls that provide more consistent results: The Utilities class. Call Utilities.CaptureWindow(Control.Handle) to capture a specific control: public static class Utilities{ public static Image CaptureScreen() { return CaptureWindow(User32.GetDesktopWindow()); } public static Image CaptureWindow(IntPtr handle) { IntPtr hdcSrc = User32.GetWindowDC(handle); RECT windowRect = new RECT(); User32.GetWindowRect(handle, ref windowRect); int width = windowRect.right - windowRect.left; int height = windowRect.bottom - windowRect.top; IntPtr hdcDest = Gdi32.CreateCompatibleDC(hdcSrc); IntPtr hBitmap = Gdi32.CreateCompatibleBitmap(hdcSrc, width, height); IntPtr hOld = Gdi32.SelectObject(hdcDest, hBitmap); Gdi32.BitBlt(hdcDest, 0, 0, width, height, hdcSrc, 0, 0, ApiConstants.SRCCOPY); Gdi32.SelectObject(hdcDest, hOld); Gdi32.DeleteDC(hdcDest); User32.ReleaseDC(handle, hdcSrc); Image image = Image.FromHbitmap(hBitmap); Gdi32.DeleteObject(hBitmap); return image; }} The Gdi32 class: public class Gdi32{ [DllImport("gdi32.dll")] public static extern bool BitBlt(IntPtr hObject, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hObjectSource, int nXSrc, int nYSrc, int dwRop); [DllImport("gdi32.dll")] public static extern IntPtr CreateCompatibleBitmap(IntPtr hDC, int nWidth, int nHeight); [DllImport("gdi32.dll")] public static extern IntPtr CreateCompatibleDC(IntPtr hDC); [DllImport("gdi32.dll")] public static extern bool DeleteDC(IntPtr hDC); [DllImport("gdi32.dll")] public static extern bool DeleteObject(IntPtr hObject); [DllImport("gdi32.dll")] public static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject);} The User32 class: public static class User32{ [DllImport("user32.dll")] public static extern IntPtr GetDesktopWindow(); [DllImport("user32.dll")] public static extern IntPtr GetWindowDC(IntPtr hWnd); [DllImport("user32.dll")] public static extern IntPtr GetWindowRect(IntPtr hWnd, ref RECT rect); [DllImport("user32.dll")] public static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hDC);} The constants used: public const int SRCCOPY = 13369376; The structs used: [StructLayout(LayoutKind.Sequential)]public struct RECT{ public int left; public int top; public int right; public int bottom;} A friendly Control extension method: public static class ControlExtensions{ public static Image DrawToImage(this Control control) { return Utilities.CaptureWindow(control.Handle); }} This is a code snippet from my CC.Utilities project and I specifically wrote it to take screenshots from the WebBrowser control.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2434156', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/155085/']}
jdg_380185
stackexchange
llm_judgeable_groundtruth_similarity
51393988
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What are the different ways to convert the lodash _.mapValues to ES6. Code: var fruits= { 'apple': { 'name': 'apple', 'number': 5}, 'orange': { 'name': 'orange', 'number': 10 }};_.mapValues(fruits, 'number'); Output: { 'apple': 5, 'orange': 10 } Now provide the response and nothing else.
reduce the entries of the object into another object, extracting only the number from the value: var fruits= { 'apple': { 'name': 'apple', 'number': 5}, 'orange': { 'name': 'orange', 'number': 10 }};console.log(Object.entries(fruits) .reduce((a, [key, { number }]) => { a[key] = number; return a; }, {})); In newer environments, you can make it even more elegant by using Object.fromEntries instead, to map to an array of key-value pair arrays: var fruits= { 'apple': { 'name': 'apple', 'number': 5}, 'orange': { 'name': 'orange', 'number': 10 }};console.log(Object.fromEntries( Object.entries(fruits).map(([key, { number }]) => [key, number])));
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/51393988', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9162980/']}
jdg_380186
stackexchange
llm_judgeable_groundtruth_similarity
520288
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: Intuitively the interval $(0,1)$ can be an uncountable union of disjoint uncountable sets, but I'm wondering if there is a nice function to show this easily. Namely, what is a simple example of $f:(0,1) \to (0,1)$ such that $f^{-1}(y)$ is uncountable for every $y$? Now provide the response and nothing else.
$f(0.x_1x_2x_3x_4x_5\ldots)=0.x_1x_3x_5\ldots$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/520288', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/87313/']}
jdg_380187
stackexchange
llm_judgeable_groundtruth_similarity
16044020
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 following link in the official documentation for GCC: https://gcc.gnu.org/onlinedocs/gcc/gcc-command-options/environment-variables-affecting-gcc.html Explains the following environment variables: LANGLC_CTYPELC_MESSAGESLC_ALLTMPDIRGCC_COMPARE_DEBUGGCC_EXEC_PREFIXCOMPILER_PATHLIBRARY_PATHCPATHC_INCLUDE_PATHCPLUS_INCLUDE_PATHOBJC_INCLUDE_PATHDEPENDENCIES_OUTPUTSUNPRO_DEPENDENCIES But I have also heard/read before about these other compiling flags: For compiling C code: CC , CFLAGS For compiling C++ code: CXX , CPPFLAGS And linking flags: For the linking stage: LDFLAGS After the code is compiled: LD_LIBRARY_PATH What is the meaning of CC , CFLAGS , CXX , and CPPFLAGS ? Why aren't they included in the official list of environment variables for gcc ? Now provide the response and nothing else.
To begin with, all the variables you mentioned: CC , CFLAGS , CXX , CXXFLAGS , LDFLAGS , LD_LIBRARY_PATH , are originated from Unix OS family. These variables have nothing to do with GCC in the first place, that's why you see no trace of them in the manuals. The only meaningful variable (which has no direct connection with GCC too) among these is LD_LIBRARY_PATH . You'll probably find this variable to be defined out-of-the-box on any modern Unix-like OS. Here is the the LD.SO(8) man-page from Linux Programmer's Manual which mentions LD_LIBRARY_PATH and its purpose. Here is one more extract: The LD_LIBRARY_PATH environment variable contains a colon-separated list of directories that are searched by the dynamic linker when looking for a shared library to load. The directories are searched in the order they are mentioned in. If not specified, the linker uses the default, which is /lib:/usr/lib:/usr/local/lib . As you can see LD_LIBRARY_PATH is nothing but an OS-specific environment variable for proper loading of shared libraries. Windows has similar environment variable in this regard: PATH . Windows will scan directories listed in it when searching for dynamic-link library (DLL, a counterpart of SO on Linux) too. Concerning the rest of the variables ( CC , CFLAGS , CXX , CXXFLAGS , LDFLAGS ), you see them so often due to the historical reasons. Since the rise of Unix era, software projects were built using Make (scroll down and look at the examples of typical makefile s) — one of the pioneering build tools. These variables were so extensively used in makefile s that eventually they became sort of a convention (see Implicit Rules , for instance). That's why you can even see them defined out-of-the-box on, for example, Linux, and most likely pointing to GCC (as it is considered to be the native toolchain for Linux). To conclude, the point is: don't scratch your head over CC , CFLAGS , CXX , CXXFLAGS , LDFLAGS , and friends, as they are just a blast from the past . ;) BONUS Using plain old Make directly to build complex software today quickly becomes tedious and error-prone. As a result, numerous sophisticated build system generators like GNU Automake or CMake have been developed. In brief, their goal is to provide (arguably) more readable, easy-to-maintain, and high-level syntax to define an arbitrarily complex build system for an arbitrary software project to be built. Typically, before actually building the project, one has to generate a native build system (which could also be represented by plain old makefile s, for example, for portability reasons, but not necessarily) out of this high-level definition using the corresponding set of tools. Finally, one has to build the project with the tool(s) corresponding to the generated (native) build system (for example, Make in case of plain old makefile s, but not necessarily). Since you are asking these questions, I suspect that you are about to dive into native software development with C or C++. If so, I would strongly recommend you to pick a modern build system (CMake would be my personal recommendation) in the first place, play with it, and learn it well.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16044020', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/283296/']}
jdg_380188
stackexchange
llm_judgeable_groundtruth_similarity
14416651
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 box width and height to include all of the content, padding, border width, and margin by default. Is there a way to do this? Especially, I want to be able to specify something like width: 100% including everything up to the margin. Now provide the response and nothing else.
This is a vague question, but I'll answer the best I can. Margin, by definition, is the area around the outside of your box; meaning there's no way to include margins inside of your div. If you would like more padding on the inside of your box, but you don't want the box to resize, then use: box-sizing:content-box; Or if you would like to include padding and the border, use: box-sizing:border-box; A workable solution that preserves the size of your divs and removes overflow would look something like this: #parent{ box-sizing:border-box; width:100%; height:200px; padding:2em;}#child{ box-sizing:border-box; width:100%; height:100%; padding:1em;} <div id="parent"> <div id="child"></div></div> Just place the div you want to give margins to inside of another div that has padding. Thus creating faux margins.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14416651', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/314166/']}
jdg_380189
stackexchange
llm_judgeable_groundtruth_similarity
15820780
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 following console message: [16:04:01.292] Error: Syntax error, unrecognized expression: unsupported pseudo: invalid @ http://localhost:8080/assets/js/jquery-1.9.1.min.js:4 When I try something like: if( $(e.target).is(':invalid') ){ ... } How do I fix this? Here's an example: http://jsfiddle.net/L4g99/ - try changing the jQuery version (stops working after 1.9) Now provide the response and nothing else.
Using querySelectorAll as suggested by @JanDvorak (and his answer should be accepted for thinking of that), you can write your own expression, making .is(':invalid') valid ? jQuery.extend(jQuery.expr[':'], { invalid : function(elem, index, match){ var invalids = document.querySelectorAll(':invalid'), result = false, len = invalids.length; if (len) { for (var i=0; i<len; i++) { if (elem === invalids[i]) { result = true; break; } } } return result; }}); now you can do : if( $(e.target).is(':invalid') ){ ... } FIDDLE
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15820780', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/171461/']}
jdg_380190
stackexchange
llm_judgeable_groundtruth_similarity
860796
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How to show that $\sum\limits_{n = 0}^{\infty} \frac {1}{n!} = e$ where $e = \lim\limits_{n\to\infty} \left({1 + \frac 1 n}\right)^n$ ? I'm guessing this can be done using the Squeeze Theorem by applying the AM-GM inequality. But I can only get the lower bound. If $S_n$ is the $n$ th partial sum of our series then, $$ \left({1 + \frac 1 n}\right)^n = 1 + n\cdot\frac{1}{n} + \frac{n(n - 1)}{2}\cdot \frac{1}{n^2} + \cdots + \frac{n(n - 1)\ldots(n - (n -1))}{n!} \cdot \frac{1}{n^n} $$ $$ \le 1 + \frac{1}{2!} + \cdots + \frac{1}{n!} =S_n $$ How can I show that $S_n \le $ a subsequence of $\left({1 + \frac 1 n}\right)^n$ or any sequence that converges to $e$ ? Now provide the response and nothing else.
Try bounding $$E_n = \left ( 1 + \frac{1}{n} \right )^n - \sum_{k=0}^n \frac{1}{k!}$$ using the binomial expansion you wrote, and pairing off terms. That is, write $$E_n = (1-1) + (1-1) + (1/2 - 1/2n - 1/2) + \dots$$ Using the factorial definition of the binomial coefficient will prove useful.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/860796', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/109161/']}
jdg_380191
stackexchange
llm_judgeable_groundtruth_similarity
56150932
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 3 Projects in a solution. [Solution] 'BuySellApi' (3 Projects) | +-- [BuySellApi] | | | +--- BuySellApi.csproj (This project holds the Docker file) | +-- [BuySellApi.Core] | | | +--- BuySellApi.Core.csproj | +-- [BuySellApi.Data] | +--- BuySellApi.Data.csproj 1. BuySellApi.csproj -> API 2. BuySellApi.Data/BuySellApi.Data.csproj -> Model 3. BuySellApi.Core/BuySellApi.Core.csproj -> Data Access I'm trying to build this using Docker by specifying following commands in Dockerfile FROM microsoft/dotnet:2.2-aspnetcore-runtime AS baseWORKDIR /appEXPOSE 5000ENV ASPNETCORE_URLS=http://+:5000FROM microsoft/dotnet:2.2-sdk AS buildWORKDIR /srcCOPY ["BuySellApi.csproj", "./"]COPY ["BuySellApi.Data/BuySellApi.Data.csproj", "./"]COPY ["BuySellApi.Core/BuySellApi.Core.csproj", "./"]RUN dotnet restore "./BuySellApi.csproj"COPY . .WORKDIR "/src/."RUN dotnet build "BuySellApi.csproj" -c Release -o /appFROM build AS publishRUN dotnet publish "BuySellApi.csproj" -c Release -o /appFROM base AS finalWORKDIR /appCOPY --from=publish /app .ENTRYPOINT ["dotnet", "BuySellApi.dll", "--server.urls", "http://0.0.0.0:5000"] After running the following command docker build -t cog/buysellapi . I'm getting the error as below: e:\Apps\trunk\BuySell\BuySellApi>docker build -t cog/buysellapi .Sending build context to Docker daemon 19.15MBStep 1/19 : FROM microsoft/dotnet:2.2-aspnetcore-runtime AS base ---> ce06b36fcba4Step 2/19 : WORKDIR /app ---> Using cache ---> 184385dc16fbStep 3/19 : EXPOSE 5000 ---> Using cache ---> 0e0cdd17e04dStep 4/19 : ENV ASPNETCORE_URLS=http://+:5000 ---> Using cache ---> 54cee58d679fStep 5/19 : FROM microsoft/dotnet:2.2-sdk AS build ---> a4974ac66bfcStep 6/19 : WORKDIR /src ---> Using cache ---> 7f9a2990f973Step 7/19 : COPY ["BuySellApi.csproj", "./"] ---> Using cache ---> d526083ece6dStep 8/19 : COPY ["BuySellApi.Data/BuySellApi.Data.csproj", "./"]COPY failed: stat /mnt/sda1/var/lib/docker/tmp/docker-builder475321395/BuySellApi.Data/BuySellApi.Data.csproj: no such file or directory It is not copying Data and Core Layers. When I try the same thing for a Solution with Single Project, It is working fine. Now provide the response and nothing else.
Based on your input I propose below folder structure and Dockerfile. [Solution] 'BuySellApi' (3 Projects) | +-- Dockerfile | +-- [BuySellApi] | | | +--- BuySellApi.csproj | +-- [BuySellApi.Core] | | | +--- BuySellApi.Core.csproj | +-- [BuySellApi.Data] | +--- BuySellApi.Data.csproj Dockerfile FROM microsoft/dotnet:2.2-aspnetcore-runtime AS base WORKDIR /app EXPOSE 5000 ENV ASPNETCORE_URLS=http://+:5000 FROM microsoft/dotnet:2.2-sdk AS build WORKDIR /src COPY . . RUN dotnet restore ". BuySellApi/BuySellApi.csproj" WORKDIR "/src/BuySellApi" RUN dotnet build "BuySellApi.csproj" -c Release -o /app FROM build AS publish WORKDIR "/src/BuySellApi" RUN dotnet publish "BuySellApi.csproj" -c Release -o /app FROM base AS final WORKDIR /app COPY --from=publish /app . ENTRYPOINT ["dotnet", "BuySellApi.dll", "--server.urls", "http://0.0.0.0:5000"]
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/56150932', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8253888/']}
jdg_380192
stackexchange
llm_judgeable_groundtruth_similarity
6474768
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: From this great explanation about the differences between WebViewClient and WebChromeClient it seems that if you use one, you shouldn't be using the other (for the same WebView object). Is my understanding correct? If not, when would one use both WebViewClient and WebChromeClient for the same WebView object? Is there an example of a situation where only use both WebViewClient and WebChromeClient for the same WebView object would accomplish a certain goal? Now provide the response and nothing else.
You certainly can use both, they just have different functions. Setting your own custom WebViewClient lets you handle onPageFinished, shouldOverrideUrlLoading, etc., WebChromeClient lets you handle Javascript's alert() and other functions. Just make your own class, for example: public class MyWebChromeClient extends WebChromeClient { //Handle javascript alerts: @Overridepublic boolean onJsAlert(WebView view, String url, String message, final android.webkit.JsResult result) { Log.d("alert", message); Toast.makeText(context, message, 3000).show(); result.confirm(); return true;};... and / or public class MyWebViewClient extends WebViewClient {@Override //Run script on every page, similar to Greasemonkey:public void onPageFinished(WebView view, String url) { view.loadUrl("javascript:alert('hi')"); }... Just override the functions described in the documentation, then set your client in onCreate with: webview.setWebViewClient(new MyWebViewClient());webview.setWebChromeClient(new MyWebChromeClient());
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/6474768', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/722603/']}
jdg_380193
stackexchange
llm_judgeable_groundtruth_similarity
5797539
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How can I make it so when you click inside a textarea, its entire content gets selected? And eventually when you click again, to deselect it. Now provide the response and nothing else.
To stop the user from getting annoyed when the whole text gets selected every time they try to move the caret using their mouse, you should do this using the focus event, not the click event. The following will do the job and works around a problem in Chrome that prevents the simplest version (i.e. just calling the textarea's select() method in a focus event handler) from working. jsFiddle: http://jsfiddle.net/NM62A/ Code: <textarea id="foo">Some text</textarea><script type="text/javascript"> var textBox = document.getElementById("foo"); textBox.onfocus = function() { textBox.select(); // Work around Chrome's little problem textBox.onmouseup = function() { // Prevent further mouseup intervention textBox.onmouseup = null; return false; }; };</script> jQuery version: $("#foo").focus(function() { var $this = $(this); $this.select(); // Work around Chrome's little problem $this.mouseup(function() { // Prevent further mouseup intervention $this.unbind("mouseup"); return false; });});
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/5797539', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/376947/']}
jdg_380194
stackexchange
llm_judgeable_groundtruth_similarity
9152224
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to use Javascript in order to add a canvas to one page which originally does not have one.I am trying to do the following: var canv=document.createElement("canvas");canv.setAttribute("id", "canvasID");alert(canv.id);var c=document.getElementById("canvasID");alert(c.id); The problem is the the first alert(canv.id) results in canvasID, while the second alert is undefined because c is null. Can anybody tell me what am I doing wrong? PS: the code is designed to run under Greasemonkey so adding the canvas and its ID in the HTML itself is not a viable option. Now provide the response and nothing else.
Use something like Node.appendChild( child ) for adding it to the DOM: var canv = document.createElement('canvas');canv.id = 'someId';document.body.appendChild(canv); // adds the canvas to the body elementdocument.getElementById('someBox').appendChild(canv); // adds the canvas to #someBox Or you can use element.innerHTML : document.body.innerHTML += '<canvas id="someId"></canvas>'; // the += means we add this to the inner HTML of bodydocument.getElementById('someBox').innerHTML = '<canvas id="someId"></canvas>'; // replaces the inner HTML of #someBox to a canvas
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9152224', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/144333/']}
jdg_380195
stackexchange
llm_judgeable_groundtruth_similarity
9259
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am reading an old paper of M.C. Golumbic about EPT (edge intersection of paths in a tree) graphs. In the paper it is shown that the number of maximal cliques of an EPT graph instance is polynomial. It concludes that if an oracle reports that a graph $G$ is an EPT graph, then it is possible to find the maximum clique with a standard clique enumeration algorithm. First of all, what are these standard clique enumeration algorithms? If there are more than one, can we say that if the number of maximal cliques of a graph is polynomial then can we use any of these enumeration algorithms? Or should we derive a special algorithm from a generic algorithm which uses some special structures of the graph class? Thanks in advance. Now provide the response and nothing else.
There are several output-sensitive algorithms to enumerate all maximal cliques in polynomial time per output. One of the earliest algorithms was developed by Tsukiyama, Ide, Ariyoshi, and Shirakawa (1977). Shuji Tsukiyama, Mikio Ide, Hiromu Ariyoshi, Isao Shirakawa: A New Algorithm for Generating All the Maximal Independent Sets. SIAM J. Comput. 6(3): 505-517 (1977) This means that if you know your graph has at most polynomially many maximal cliques, then the total running time of their algorithm will be polynomial in the input size.
{}
{'log_upvote_score': 5, 'links': ['https://cstheory.stackexchange.com/questions/9259', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/2296/']}
jdg_380196
stackexchange
llm_judgeable_groundtruth_similarity
139969
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: Is there a way to speed up $Z(Z'Z)^{-1}Z'$ type matrices? I am implementing the expression below directly using a matrix language and my program frequently crashes while if I run OLS on them using a pre-fabricated command, it is not an issue. Is there a tip you guys might have to compute these matrices efficiently? The goal here (but that is just an aside) is to implement the following estimator\begin{eqnarray}(X' P X - \sum_{i=1}^{n} P_{ii} X_{i}X_{i}' - \alpha X'X)^{-1} (X' P_Z y - \sum_{i=1}^{n} P_{ii} X_{i} y_{i} - \alpha X' y)\end{eqnarray}Now, $\alpha$ is the smallest eigenvalue of $(\overline{X}'\overline{X})^{-1} (\overline{X}' P_Z \overline{X} - \sum_{i=1}^{n} P_{ii} \overline{X}_{i} \overline{X}'_{i})$ where $\overline{X} = [y,X]$. I am pretty confident that once I have found an efficient way to compute the projections, I can easily implement the rest easily. Thanks so much! Now provide the response and nothing else.
Using QR decomposition (which ought to be available if you already have calculated the regression): Let $X$ have $n$ rows and $p$ columns and be of full column rank. $H=X(X'X)^{-1}X'$ $=QR(R'Q'QR)^{-1}R'Q'$ $=QR(R'R)^{-1}R'Q'$ But if $R_1$ is the first $p$ rows of $R$ then $R'R=R_1'R_1$ $=QR(R_1'R_1)^{-1}R'Q'$ Now let $Q=(Q_1,Q_2)$ where $Q_1$ is the first $p$ columns of $Q$. Then $QR=Q_1R_1$. $=Q_1R_1R_1^{-1}(R_1')^{-1}R_1'Q_1'$ $=Q_1Q_1'$ Where $Q_1$ is $n\times p$. So if you have the QR decomposition of $X$, then the hat matrix is fairly simple. Note that some regression programs will give $Q_1$ automatically. [It's also possibly that a regression program will have performed pivoting. That shouldn't impact the calculation of the hat matrix though.]
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/139969', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/64735/']}
jdg_380197
stackexchange
llm_judgeable_groundtruth_similarity
2885171
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 trying to evaluate $$\int_0^1\frac {\{2x^{-1}\}}{1+x}\,\mathrm d x$$ where $\{x\}$ is the fractional part of $x$. I have tried splitting up the integral but it gets quite complicated and confusing. Is there an easy method for such integrals? Now provide the response and nothing else.
$$\begin{eqnarray*} \int_{0}^{1}\frac{\{2x^{-1}\}}{1+x}=\int_{1}^{+\infty}\frac{\{2x\}}{x(x+1)}\,dx &=&2\int_{2}^{+\infty}\frac{\{x\}}{x(2+x)}\,dx\\&=&\int_{2}^{+\infty}\left(\frac{\{x\}}{x}-\frac{\{x+2\}}{x+2}\right)\,dx\end{eqnarray*}$$clearly equals$$ \int_{2}^{4}\frac{\{x\}}{x}\,dx = \int_{2}^{3}\frac{x-2}{x}\,dx+\int_{3}^{4}\frac{x-3}{x}\,dx = \color{red}{2-4\log 2+\log 3}.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2885171', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/584849/']}
jdg_380198
stackexchange
llm_judgeable_groundtruth_similarity
278443
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: Just hit this problem, and learned a lot from the chosen answer: Create random data with dd and get "partial read warning". Is the data after the warning now really random? Unfortunately the suggested solution head -c is not portable. For folks who insist that dd is the answer, please carefully read the linked answer which explains in great detail why dd can not be the answer. Also, please observe this: $ dd bs=1000000 count=10 if=/dev/random of=randomdd: warning: partial read (89 bytes); suggest iflag=fullblock0+10 records in0+10 records out143 bytes (143 B) copied, 99.3918 s, 0.0 kB/s$ ls -l random ; du -kP random-rw-rw-r-- 1 me me 143 Apr 22 19:19 random4 random$ pwd/tmp Now provide the response and nothing else.
Unfortunately, to manipulate the content of a binary file, dd is pretty much the only tool in POSIX. Although most modern implementations of text processing tools ( cat , sed , awk , …) can manipulate binary files, this is not required by POSIX: some older implementations do choke on null bytes, input not terminated by a newline, or invalid byte sequences in the ambient character encoding. It is possible, but difficult, to use dd safely. The reason I spend a lot of energy steering people away from it is that there's a lot of advice out there that promotes dd in situations where it is neither useful nor safe. The problem with dd is its notion of blocks: it assumes that a call to read returns one block; if read returns less data, you get a partial block, which throws things like skip and count off. Here's an example that illustrates the problem, where dd is reading from a pipe that delivers data relatively slowly: yes hello | while read line; do echo $line; done | dd ibs=4 count=1000 | wc -c On a bog-standard Linux (Debian jessie, Linux kernel 3.16, dd from GNU coreutils 8.23), I get a highly variable number of bytes, ranging from about 3000 to almost 4000. Change the input block size to a divisor of 6, and the output is consistently 4000 bytes as one would naively expect — the input to dd arrives in bursts of 6 bytes, and as long as a block doesn't span multiple bursts, dd gets to read a complete block. This suggests a solution: use an input block size of 1 . No matter how the input is produced, there's no way for dd to read a partial block if the input block size is 1. (This is not completely obvious: dd could read a block of size 0 if it's interrupted by a signal — but if it's interrupted by a signal, the read system call returns -1. A read returning 0 is only possible if the file is opened in non-blocking mode, and in that case a read had better not be considered to have been performed at all. In blocking mode, read only returns 0 at the end of the file.) dd ibs=1 count="$number_of_bytes" The problem with this approach is that it can be slow (but not shockingly slow: only about 4 times slower than head -c in my quick benchmark). POSIX defines other tools that read binary data and convert it to a text format: uuencode (outputs in historical uuencode format or in Base64), od (outputs an octal or hexadecimal dump). Neither is well-suited to the task at hand. uuencode can be undone by uudecode , but counting bytes in the output is awkward because the number of bytes per line of output is not standardized. It's possible to get well-defined output from od , but unfortunately there's no POSIX tool to go the other way round (it can be done but only through slow loops in sh or awk, which defeats the purpose here).
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/278443', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/94174/']}
jdg_380199
stackexchange
llm_judgeable_groundtruth_similarity
37679552
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 cannot stop or delete versions of a project created as it was created as a flexible environment within the EU. I understand the restriction by region but cannot work out why it cannot be removed. jamie@dartmoor-1320:~$ gcloud preview app versions delete 20160607t131220Deleting the following versions: - dartmoor-1320/default/20160607t131220Do you want to continue (Y/n)? Deleting [default/20160607t131220]...failed.ERROR: (gcloud.preview.app.versions.delete) Issue deleting version: [default/20160607t131220][default/20160607t131220]: Error Response: [13] Managed VMs can not be hosted in the application's region. (e~)) The GUI fails too but with a non descript error message. Now provide the response and nothing else.
You have to have at least one version for the default module. That's the reason why it doesn't allow you to delete it. You need to deploy a new version, it can be a Flexible VM (deployed to another region in your situation), or Standard VM. As a workaround, when you don't have any app to replace it right now, you can deploy an empty app instead. You have to create an app.yaml : ---runtime: python38handlers: - url: / script: auto and deploy it using: gcloud app deploy app.yaml As your app.yaml doesn't have any script to execute, you'll not be charged for any instance.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/37679552', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3346163/']}
jdg_380200
stackexchange
llm_judgeable_groundtruth_similarity
27763340
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 changed /etc/default/docker with DOCKER_OPTS="-H tcp://127.0.0.1:2375 -H unix:///var/run/docker.sock" (docker version 1.4.1 in ubuntu 14.04), but it do not take any effect for me (not listening at port 2375 ). It seems that docker do not read this initial config file because I found export http_proxy enviroment do not work too. Only sudo docker -H tcp://127.0.0.1:2375 -H unix:///var/run/docker.sock -d works. It really confused me! Now provide the response and nothing else.
According to docker documentation , The recommended way to configure the daemon flags and environment variables for your Docker daemon is to use a systemd drop-in file . So, for this specific case, do the following: Use the command sudo systemctl edit docker.service to open an override file for docker.service in a text editor. Add or modify the following lines, substituting your own values. [Service]ExecStart=ExecStart=/usr/bin/dockerd -H tcp://127.0.0.1:2375 -H unix:///var/run/docker.sock Save the file. Reload the systemctl configuration. $ sudo systemctl daemon-reload Restart Docker: $ sudo systemctl restart docker.service Check to see whether the change was honored by reviewing the output of netstat to confirm dockerd is listening on the configured port. $ sudo netstat -lntp | grep dockerdtcp 0 0 127.0.0.1:2375 0.0.0.0:* LISTEN 3758/dockerd
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27763340', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4162734/']}
jdg_380201
stackexchange
llm_judgeable_groundtruth_similarity
11123867
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an app that uses MagicalRecord, and I'm pre-populating the database with a large amount of data that is used for reference. Within that same data model, I have user-definable information pertaining to things the user may do in the app. The app was rejected because the pre-populated data is supposed to be marked as "do not backup". So, I'd like to have that data in a separate datastore so that I can keep the user data as backupable. Is there a way to have two separate datastores using MagicalRecord? Now provide the response and nothing else.
I think it's possible, but not too easy though.As you know, to work with more than one database, you should bring some changes to your PersistentStoreCoordinator , so it will have two PersistentStores . After this, you Core Data stack would look like this: The other way is two make two separate PersistentStoreCoordinators, each carrying one store. In Magical Record, there are several class methods for adding stores in NSPersistentStoreCoordinator+MagicalRecord.h . (NSPersistentStore *) MR_addInMemoryStore; (NSPersistentStore *) MR_addAutoMigratingSqliteStoreNamed:(NSString *) storeFileName; (NSPersistentStore *) MR_addSqliteStoreNamed:(id)storeFileName withOptions:(__autoreleasing NSDictionary *)options; I think, that this is the place where you could do the thing you want. Also i should mention, that the whole proccess of setting up the stack goes in MagicalRecord+Setup.h + (void) setupCoreDataStackWithStoreNamed:(NSString *)storeName So you can add your Stores and Coordinators there.I've never managed it by myself, that was just a brief investigation of a possible solution.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11123867', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/722/']}
jdg_380202
stackexchange
llm_judgeable_groundtruth_similarity
36927956
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Doing a forced push is done by: git push origin +branch Doing a push to a differently-named remote branch is done by: git push origin local:remote How does one do a forced push to a differently-named remote branch? I tried: git push origin local:+remote But it creates a new branch named +remote Now provide the response and nothing else.
The + needs to come at the beginning of the argument representing the couple. git push origin +localBranchName:remoteBranchName That's hard to remember sometimes, so there's also the --force flag. git push origin --force localBranchName:remoteBranchName But be aware if you push multiple branches with that flag, then they will all be force pushed. git push origin --force localBranchName:remoteBranchName anotherLocalBranch In that case, you may not have wanted to force push anotherLocalBranch , so you should instead use the + to specify which ones you want forced. git push origin +localBranchNameForced:remoteBranchName localBranchNotForced:remoteBranchNotForced +anotherLocalBranchForcePushedToUpstreamTracking Do read Torek's answer for a better explanation, and check out some of his other answers for world-class knowledge on git.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/36927956', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2319794/']}
jdg_380203
stackexchange
llm_judgeable_groundtruth_similarity
69759
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: In SVM, the Gaussian kernel is defined as:$$K(x,y)=\exp\left({-\frac{\|x-y\|_2^2}{2\sigma^2}}\right)=\phi(x)^T\phi(y)$$ where $x, y\in \mathbb{R^n}$.I do not know the explicit equation of $\phi$. I want to know it. I also want to know whether$$\sum_ic_i\phi(x_i)=\phi \left(\sum_ic_ix_i \right)$$ where $c_i\in \mathbb R$. Now, I think it is not equal, because using a kernel handles the situation where the linear classier does not work. I know $\phi$ projects x to a infinite space. So if it still remains linear, no matter how many dimensions it is, svm still can not make a good classification. Now provide the response and nothing else.
You can obtain the explicit equation of $\phi$ for the Gaussian kernel via the Tailor series expansion of $e^x$. For notational simplicity, assume $x\in \mathbb{R}^1$: $$\phi(x) = e^{-x^2/2\sigma^2} \Big[ 1, \sqrt{\frac{1}{1!\sigma^2}}x,\sqrt{\frac{1}{2!\sigma^4}}x^2,\sqrt{\frac{1}{3!\sigma^6}}x^3,\ldots\Big]^T$$ This is also discussed in more detail in these slides by Chih-Jen Lin of NTU (slide 11 specifically). Note that in the slides $\gamma=\frac{1}{2\sigma^2}$ is used as kernel parameter. The equation in the OP only holds for the linear kernel.
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/69759', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/30172/']}
jdg_380204
stackexchange
llm_judgeable_groundtruth_similarity
1454363
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 don't understand the answer to the exercise that I'm doing, can anyone explain it in a more clear manner? Let $ v_1 = \begin{bmatrix} 1 \\ 0 \\ 1 \end{bmatrix}, v_2 = \begin{bmatrix} 0 \\ 1 \\ 1 \end{bmatrix}, v_3 = \begin{bmatrix} 0 \\ 1 \\ 0 \end{bmatrix} $, and let $H$ be the set of vectors in $\Bbb R^3$ whose second and third entries are equal. Then every vector in $H$ has a unique expansion as a linear combination of $v_1, v_2, v_3$, because $ \begin{bmatrix} s \\ t \\ t \end{bmatrix} = s \begin{bmatrix} 1 \\ 0 \\ 1 \end{bmatrix} + (t-s) \begin{bmatrix} 0 \\ 1 \\ 1 \end{bmatrix} + s \begin{bmatrix} 0 \\ 1 \\ 0 \end{bmatrix} $ for any $s$ and $t$. Is $\{v_1,v_2,v_3\}$ a basis for $H$? Why or why not? The answer given was: In order for the set to be a basis for $H$, $\{v_1,v_2,v_3\}$ must be a spanning set for $H$; that is, $H=\operatorname{Span}\{v_1,v_2,v_3\}$. The exercise shows that $H$ is a subset of $\operatorname{Span}\{v_1,v_2,v_3\}$, but there are vectors in $\operatorname{Span}\{v_1,v_2,v_3\}$ which are not in $H$ ($v_1$ and $v_3$, for example). So $H \neq \operatorname{Span}\{v_1,v_2,v_3\}$, and $\{v_1,v_2,v_3\}$ is not a basis for $H$. I see $v_1$ and $v_3$ making $H$, why does it say they are not in $H$? Now provide the response and nothing else.
You'll notice that $H$ is indeed a subset of $\Bbb R^3$, but to be more precise, it's a subspace of it resembling $\Bbb R^2$ (it's a plane). To see this, notice that the first variable is free, and the third dependent upon the third. Now, you can use the vectors $v_1, v_2, v_3$ to express points in that plane, but you'll notice that you can also use those vectors to express points that are not in the plane, $v_1$ for example, so $Span(v_1,v_2,v_3)$ does not span $H$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1454363', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/68385/']}
jdg_380205
stackexchange
llm_judgeable_groundtruth_similarity
19113682
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 showing a web app in an UIWebView , and sometimes the content of pages will change. After content have been changed the app clears the cache. But when I go to a page I've previously visited the UIWebView doesn't send a HTTP GET request, but loads from cache even though I've disabled cache like so: [[NSURLCache sharedURLCache] removeAllCachedResponses];[[NSURLCache sharedURLCache] setDiskCapacity:0];[[NSURLCache sharedURLCache] setMemoryCapacity:0]; Initally I'm loading a request with cachePolicy cachePolicy:NSURLRequestReturnCacheDataElseLoad . [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:myURLString] cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:10.0]]; UIWebView have some kind of internal cache. Already visited pages will be loaded from this internal cache instead of going through NSURLCache and also there's no request sent. Is there any way to clear the internal cache of UIWebView ? I'm even recreating the UIWebView but the cache is still there. Now provide the response and nothing else.
It appears that what's happening here is that it reloads the actual HTML file, but does not necessarily reload the resources within that page. A possible solution I've seen is to append a query parameter on to the end of the URL. For example: NSString *testURL = [NSString stringWithFormat:@"%@?t=%@", url, randQuery];[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:testURL] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10.0]]; where you generate a random alphanumeric string as your randQuery query parameter, or keep a persistent count and just count up. This should force the UIWebView to load from the remote resource.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19113682', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/257577/']}
jdg_380206
stackexchange
llm_judgeable_groundtruth_similarity
40692
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: This is related to this old MO question which wasn't answered properly, though I don't feel I phrased the question in the best way (or posted it on the right site) Define the abelianization of a group $G$ to be the quotient group $G_{ab} := G/[G,G]$, where $[G,G]$ is the commutator subgroup . I want to know how this definition implies the following property of abelianization. Let $\phi: G \to G_{ab}$ be the canonical surjection. For any abelian group $H$ and homomorphism $f:G\to H$, there exists a unique homomorphism $F: G_{ab} \to H$ such that $f = F\circ \phi$. This is the ability to 'descend to a homomorphism' that I explained so badly in my initial post, though at the time it was the only terminology I heard being used. I am aware that these two definitions are equivalent but I have not yet seen a proof, nor managed to prove it myself. Please do point me to an online proof if you know of one. Now provide the response and nothing else.
If $f : G \to H$ is a homomorphism to an abelian group, then $f(ab) = f(a) f(b) = f(b) f(a) = f(ba)$, hence $[a, b] \in \ker f$, hence $[G, G] \subseteq \ker f$. Is the rest clear from here?
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/40692', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/10477/']}
jdg_380207
stackexchange
llm_judgeable_groundtruth_similarity
37318670
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 tried to use system() in a c++ appit works very well if i do it like: system("notepad"); But it gives error when i try to do like: cin >> cmdlol; system(cmdlol); Error: cannot convert 'std::string {aka std::basic_string}' to 'const char*' for argument '1' to 'int system(const char*)'| Now provide the response and nothing else.
cmdlol seemes to be std::string , which can't be converted to const char* implicitly. And std::system only accepts const char* as its argument, that's why compiler complains. You could use std::basic_string::c_str() explicitly. system(cmdlol.c_str()); And about why system("notepad"); works well, "notepad" is a string literal with type const char[8] (including null character), note it's not std::string and might decay to const char* when passed to std::system .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37318670', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5615834/']}
jdg_380208
stackexchange
llm_judgeable_groundtruth_similarity
40974
Below is a question asked on the forum raspberrypi.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I've been using my PC to access the files on RPi, using Samba Server on RPi. But, Is there any way I could open Samba Connections on Pi? Like browsing Windows PC Samba Files on RPi? Now provide the response and nothing else.
First install some packages: apt-get install samba-common smbclient samba-common-bin smbclient cifs-utils Then, create a local directory and mount the remote share: mkdir /mnt/abcmount -t cifs //server/share /mnt/abc where server is your windows computer name (dns or netbios) and share is your windows shared directory. Depending on the access you give to your windows share are the credentials required: if you give your share 'Everyone' read (and write) access nothing else is required, otherwise you must add credentials at mount time: mount -t cifs //server/share /mnt/abc -o user=user,pass=password,dom=domain replace with your own credentials. When finished just dismount the share: umount /mnt/abc
{}
{'log_upvote_score': 6, 'links': ['https://raspberrypi.stackexchange.com/questions/40974', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/27757/']}
jdg_380209
stackexchange
llm_judgeable_groundtruth_similarity
11599957
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 upload multiple files to a server using the curl command line utility. for a single file I have no problem using: curl -F "[email protected]" http://localhost:8888/web/Upload.php how would I do this with more than one file so that the php variable $_FILES["image"]["error"] would return an array? I've tried curl -F "[email protected]" -F "[email protected]" http://localhost:8888/web/Upload.phpcurl -F "[email protected],[email protected]" http://localhost:8888/web/Upload.php but these are a stab in the dark. Now provide the response and nothing else.
The trick is to name the file uploading parameters unique. curl -F "[email protected]" -F "[email protected]" http://localhost:8888/web/Upload.php This will show up in the $_FILES superglobal as $_FILES['image'] and $_FILES['image2'] . To make the files grouped under one $_FILES index you need to name the parameters as arrays: curl -F "image[][email protected]" -F "image[][email protected]" http://localhost:8888/web/Upload.php
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/11599957', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/239841/']}
jdg_380210
stackexchange
llm_judgeable_groundtruth_similarity
32173557
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 list vector with length of multiple four: mylist <- c("1", "darkorange", "16876", "16890", "2", "pink", "6833", "7189", "2", "pink", "9181", "9279", "2", "darkgreen", "1846", "2170") What I want do do is to turn that list into a data framewith dimension (M * 4): V1 V2 V3 V4"1" "darkorange" "16876" "16890" "2" "pink" "6833" "7189" "2" "pink" "9181" "9279" "2" "darkgreen" "1846" "2170" How can I achieve that? Now provide the response and nothing else.
Just convert to a matrix , specify the ncol m1 <- matrix(mylist, ncol=4, byrow=TRUE)d1 <- as.data.frame(m1, stringsAsFactors=FALSE)d1# V1 V2 V3 V4#1 1 darkorange 16876 16890#2 2 pink 6833 7189#3 2 pink 9181 9279#4 2 darkgreen 1846 2170 The 'data.frame' columns are all character class as the input vector is character . We could convert the class based on the numeric/non-numeric values with type.convert d1[] <- lapply(d1, type.convert)str(d1) #'data.frame': 4 obs. of 4 variables:#$ V1: int 1 2 2 2#$ V2: Factor w/ 3 levels "darkgreen","darkorange",..: 2 3 3 1#$ V3: int 16876 6833 9181 1846#$ V4: int 16890 7189 9279 2170
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32173557', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/67405/']}
jdg_380211
stackexchange
llm_judgeable_groundtruth_similarity
237769
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I received an "Undelivered Mail Returned to Sender" email, which is quite suspicious. The message is displayed in Thunderbird like this: From: someRandomStuff [email protected] Date: 24.08.20, 21:05 To: a list of very random looking email addresses, probably machine generated Is this simply a case of using some email address in the reply-to field, or is there something worse going on? Now provide the response and nothing else.
In addition to @SteffenUllrich, you might also want to double check the headers of the attached mail. In particular, pay a lot of attention to the Received: from header (well.. the header is just Received ...). Two circumstances (asssume mx.example.org is the server who sends the return): You don't find your own MX on the stack. ✔ Case closed, someone is (failing at) spoofing your email You do find your own MX somewhere on the stack. Now check: If your server is the first entry after mx.example.org … You must investigate further. Your account might really have been pwned (because of a leaked password) to be used for spam. You may want to check your password for leakage at haveibeenpwned.com and the server logs for suspicious activity. Another interpretation is that the header, which is just a plaintext header, was forged. This would mean that there is no attempt to deliver mail at [email protected] but instead someone else is trying to deceive you into thinking you sent an undeliverable mail. It is unlikely, but without checking the contents of the attached email for malware , it's just hypotetical. Also, don't forget that the foreign mail server could be poorly configured, worse than not just checking for SPF/DKIM. If your server is not the first entry after mx.example.org … ⚠ This means that the email claims to have bounced back and forth. It is unlikely, especially for how SPF works. Unless some strict corporate routing configuration for firewalled stations, emails travel non-stop from the origin ISP to the destination ISP 99 .9 % of cases. In that case, the header was very likely forged to give more credibility to the email, deceiving old antispam filter ("hi Mr. mail server, I have to deliver a mail to you that was given to me by the intended sender"). I'd still trash it, but maybe you would take a look, low priority, at the logs for message id. Just as a triple-check. You can somewhat reduce the problem of such misuse by having strict SPF policies (and better also DKIM and DMARC) but this does not help much if the initial mail server will not check such policies or not block the mail based on the policies. This was my case, and apparently the server never enforced those policies on their side to discard that mail allegedly coming from myself. Case closed.
{}
{'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/237769', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/177170/']}
jdg_380212
stackexchange
llm_judgeable_groundtruth_similarity
25538
Below is a question asked on the forum politics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In How to Become a Country in 3 Easy Steps they mention: Step 1 Declare independence Step 2 Gain recognition Step 3 Join the United Nations Foreign Policy has a similar article How to Start Your Own Country in Four Easy Steps which lists: Step 1: Make sure you are eligible Step 2: Declare independence Step 3: Get recognized Step 4: Join the club Assuming a territory has already gone through the step of declaring the independence, what would be the next bureaucratic steps in order to reach the status of a sovereign, independent country? In the second article they mention: Since its founding in 1945, membership in the United Nations has become the gold standard of international legitimacy. When you are admitted to the U.N, that's a form of approval. And reading the article they show some cases like Nagorno Karabakh , Palestine (or Ossetia , I would add) that are somehow frozen in between the "declare independence" and "get recognized" steps. For this, what would be the formal steps to take in case the international community agree on a territory becoming independent? Now provide the response and nothing else.
First of all there is no etched-in-stone way to become a sovereign state. Some follow military ways e.g. Bangladesh seceding from Pakistan and becoming an independent country. Some follow political ways e.g. Pakistan and India carved out of united British India. There is no way to get the entire international community on board as interests of all states vary. They rarely agree on anything anyways. You could say that a state is considered independent if it is considered a person in international law . There are however two theories which can be considered as "How to be Independent" guides. They are: Constitutive Theory Declarative Theory Constitutive Theory This theory concludes that a regional entity is considered an independent state or a person in international law if and only if it is recognized as such by other sovereign entities. In 1815, Congress of Vienna Final Act acknowledged existence of only 39 sovereign states in Europe. It further outlined the process by which other states who claimed to be sovereign could be acknowledged as such. The process was nominally acknowledgement of their independence by the 39-club which in practice meant that a new state would be recognized as independent if and only if the Great Powers France, Russia, Great Britain, Prussia and Austria recognized them as such. Lassa Openheim in 1921 however provided a realistic view . He said that even though there is no requirement by the international law for a state to be recognized by others for it to exist or its independence to exist, the Law simply refuses to note their independence. They may be de-facto independent however de-jure, they shall not be treated as such unless other nations recognize them. Of course recognizing a nation is also a subjective thing, subjective to a number of factors. Chief among those are the interests of pre-existing states. If the new state serves interests of existing states, they might recognize it, if they don't, they might choose not to. Hypothetically consider Kurdistan. If an independent Kurdistan is established today, Israel would be inclined towards recognizing them as an independent Kurdistan is beneficial for Israel. It provides them a friendly partner in the region and it also weakens their regional rivals such as Iran whose own Kurdish region could be stirred to follow the same suite. Iran on the other hand, will oppose formation of Kurdistan for the exact same reasons. Declarative Theory Declarative theory is more clearer than the constitutive one. It lays out the following criteria for a state to be considered independent: It has a defined territory. It has a permanent population. It has a government. It has a capacity to enter into relations with other states. The most important point is, if these four points are met, a territory is considered an independent state even if it is not recognized by any existing independent states. See the Article 3 of Convention on Rights and duties of states or Montevideo Convention which not only explicitly states that the independence is not bound to recognition by others, it also grants new states the right to defend themselves. So if, let's say Catalonia starts a war against Spain, they would be well within their rights to do so as per Convention on Rights and Duties of States. This convention was adopted in 1933 and applies to all parties of International law and not just the signatories. This was also the set of Laws used by Badinter Arbitration Committee to resolve the crisis of dissolution of Yugoslavia in 1991. So One could say that declarative theory is the one which is currently in practice. In Practice In Practice however, one could assert that the only sure way to be seen as an independent state is to join the United Nations. The following is how you join the UN as a member state : The procedure is briefly as follows: The State submits an application to the Secretary-General and a letter formally stating that it accepts the obligations under theCharter. The Security Council considers the application. Any recommendation for admission must receive the affirmative votes of 9 of the 15members of the Council, provided that none of its five permanentmembers — China, France, the Russian Federation, the United Kingdom ofGreat Britain and Northern Ireland and the United States of America —have voted against the application. If the Council recommends admission, the recommendation is presented to the General Assembly for consideration. A two-thirdsmajority vote is necessary in the Assembly for admission of a newState. Membership becomes effective the date the resolution for admission is adopted. So you need at least 9 friends in 15 members of the UNSC to pass the first step and make sure that none of the Permanent members veto the application, (Sorry Palestine, Chechnya, Taiwan, Brittany, Northern Ireland). If that's done (And this is the most difficult step as the General Assembly will mostly follow the suite), you need 2/3 majority in UNGA to gain admission. But even by joining UN, you are in no way obligating the UN states to recognize you as independent. UN's recognition in itself provides you just a platform to communicate with the rest of the world. It doesn't guarantee the integrity and independence of your country for eternity. But that in itself means little because Montevideo Convention already accords you the right to defend your territory even if no state or UN recognizes you as independent. Not to mention, quite the contrary, UN may in fact take steps to hinder your independence. For example, UNSC resolution 541 which declared that Northern Cypriot declaration of Independence was legally invalid. Furthermore, UN could ask for advise from International Court of Justice as it did in Case of Kosovo . If you take a look at List of States with limited recognition , you will notice there are UN members not recognized by other UN members, there are Non-UN members not recognized by a number UN members, there are non-UN members who are not recognized by any UN members etc. So there is no certain pattern. Independent countries may choose their own ways to deal with your independence, e.g. the split among nations regarding Israel. Similarly independent countries may choose their own reactions to violation of your sovereignty i.e. support or opposition on the scale of verbal to in-field. Standard IANAL disclaimer. I was hoping someone with good knowledge of International law could weigh in. But since the OP insisted, oh well.
{}
{'log_upvote_score': 5, 'links': ['https://politics.stackexchange.com/questions/25538', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/1874/']}
jdg_380213
stackexchange
llm_judgeable_groundtruth_similarity
36914221
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: For the program : #include<stdio.h>int main(void){ int (*a)[2]; int b[5]; printf("sizeof(int) : %zu\n", sizeof(int)); printf("sizeof(int*) : %zu\n", sizeof(int*)); printf("sizeof(b) : %zu\n",sizeof(b)); printf("sizeof((int*)b) : %zu\n",sizeof((int*)b)); printf("sizeof(&b[0]) : %zu\n",sizeof(&b[0])); printf("sizeof(a) : %zu\n",sizeof(a)); printf("sizeof(a[0]) : %zu\n",sizeof(a[0])); printf("sizeof(a[1]) : %zu\n",sizeof(a[1])); return 0;} Output is : sizeof(int) : 4 -> Fact 1sizeof(int*) : 8 -> Fact 2sizeof(b) : 20 -> Case 1sizeof((int*)b) : 8 -> Case 2sizeof(&b[0]) : 8 -> Case 3sizeof(a) : 8 -> Case 4sizeof(a[0]) : 8 -> Case 5sizeof(a[1]) : 8 -> Case 6 Questions/Observations (in Case Order ) : Is Case 1 output 20 because b was declared as an array of integers ie int[] ? The total block in bytes is returned as confirmed by Fact1. Isn't it? I guess casting b to int* made the difference here. Here b is considered a pointer. I confirmed this using Fact2. Right or wrong? &b[0] decays to a pointer b . The output coincides with Fact2 . I expected 16 here but I got 8 as the output. I concluded that this is because a is afterall a pointer and the output coincides with Fact2 . I got the output similar to Question 2. a[0] is pointer. The output coincides with Fact2 a[1] is pointer. The output coincides with Fact2 Please answer the questions and correct me if any of the observations are wrong. Now provide the response and nothing else.
Please answer the questions and correct me if any of the observations are wrong. Is Case 1 output 20 because b was declared as an array of int egers ie int[] ? The total block in bytes is returned as confirmed by Fact1. Isn't it? Yes, the result shows the sizeof(int [5]) . So from Fact1, the size is 5*4 I guess casting b to int* made the difference here. Here b is considered a pointer. I confirmed this using Fact2. Right or wrong? Right. But adding more info: sizeof needs only the type of expression and it does not evaluate expression (for value) unless it is VLA type.(From section 6.5.3.4 The sizeof operator of C99 specs ) Because you are applying cast on final result, anything after that does not matter. &b[0] decays to a pointer b . The output coincides with Fact2 . No and yes. Type of b[0] is int and thus type of &b[0] is already int * (Recall that [...] binds tighter than & ). There is no decaying. And yes the output coincides with Fact2. I expected 16 here but I got 8 as the output. I concluded that this is because a is afterall a pointer and the output coincides with Fact2 . I got the output similar to Question 2. a as pointer to array 2 of int . So the printed size is of pointer (to an int array). int (*a)[2]; declares a as pointer to array 2 of int . So you get the size of pointer to array . To get the desired result (size of array 2 of pointers to int ) use: int *a[2]; int (*a)[2];a anonymous+----+ +----+----+| a |----->|int |int |+----+ +----+----+int *b[2];b +----+----+|int*|int*|+----+----+b[0] b[1] a[0] is pointer. The output coincides with Fact2 a[2] is pointer. The output coincides with Fact2 As stated earlier, a is a pointer to array 2 of int . So a[index] is an array 2 if int . So, type of a[0] and a[1] are array 2 of int . So the output is 2*4 from Fact 1. Possibly irrelevant to this answer but a is uninitialized and using it in expression would cause undefined behaviour . Though it is fine to use in sizeof To understand the output, let's analyse the type of argument of sizeof printf("sizeof(b) : %zu\n",sizeof(b)); // int [5]printf("sizeof((int*)b) : %zu\n",sizeof((int*)b)); // int *printf("sizeof(&b[0]) : %zu\n",sizeof(&b[0])); // int *printf("sizeof(a) : %zu\n",sizeof(a)); // int (*) [2]printf("sizeof(a[0]) : %zu\n",sizeof(a[0])); // int [2]printf("sizeof(a[1]) : %zu\n",sizeof(a[1])); // int [2] A portable program (not foolproof) to confirm the types looks like: assert(sizeof(b) == sizeof(int [5]));assert(sizeof((int*)b) == sizeof(int *));assert(sizeof(&b[0]) == sizeof(int *));assert(sizeof(a) == sizeof(int(*)[2]));assert(sizeof(a[0]) == sizeof(int[2]));assert(sizeof(a[1]) == sizeof(int[2]));
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36914221', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1620779/']}
jdg_380214
stackexchange
llm_judgeable_groundtruth_similarity
29179848
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: It works fine when have one or two tasks however throws an error "A task was cancelled" when we have more than one task listed. List<Task> allTasks = new List<Task>();allTasks.Add(....);allTasks.Add(....);Task.WaitAll(allTasks.ToArray(), configuration.CancellationToken);private static Task<T> HttpClientSendAsync<T>(string url, object data, HttpMethod method, string contentType, CancellationToken token){ HttpRequestMessage httpRequestMessage = new HttpRequestMessage(method, url); HttpClient httpClient = new HttpClient(); httpClient.Timeout = new TimeSpan(Constants.TimeOut); if (data != null) { byte[] byteArray = Encoding.ASCII.GetBytes(Helper.ToJSON(data)); MemoryStream memoryStream = new MemoryStream(byteArray); httpRequestMessage.Content = new StringContent(new StreamReader(memoryStream).ReadToEnd(), Encoding.UTF8, contentType); } return httpClient.SendAsync(httpRequestMessage).ContinueWith(task => { var response = task.Result; return response.Content.ReadAsStringAsync().ContinueWith(stringTask => { var json = stringTask.Result; return Helper.FromJSON<T>(json); }); }).Unwrap();} Now provide the response and nothing else.
There's 2 likely reasons that a TaskCanceledException would be thrown: Something called Cancel() on the CancellationTokenSource associated with the cancellation token before the task completed. The request timed out, i.e. didn't complete within the timespan you specified on HttpClient.Timeout . My guess is it was a timeout. (If it was an explicit cancellation, you probably would have figured that out.) You can be more certain by inspecting the exception: try{ var response = task.Result;}catch (TaskCanceledException ex){ // Check ex.CancellationToken.IsCancellationRequested here. // If false, it's pretty safe to assume it was a timeout.}
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/29179848', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/261708/']}
jdg_380215
stackexchange
llm_judgeable_groundtruth_similarity
26607
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Here is something I've wondered about since I was an undergraduate. Let $R$ be a ring (commutative, let's say, although the generalization to noncommutative rings is obvious). Ideals of $R$ can be multiplied and can be added (the ideal $I+J$ is the ideal generated by $I$ and $J$), and multiplication distributes over addition. Therefore we can consider the semiring $S$ of ideals of $R$. The question is, does the structure of $S$ tell us anything interesting about the structure of $R$? Or vice versa? I asked this question on sci.math.research last year and got a few replies but nothing very substantive. http://mathforum.org/kb/thread.jspa?messageID=6599151 For a more concrete question: Give an interesting sufficient condition for $S$ to be finitely generated. Conversely, if $S$ is finitely generated, does that imply anything interesting about $R$? Now provide the response and nothing else.
Here are a few observations. None of them require our ring to be commutative. First, notice that one can recover the natural partial ordering of the ideals via addition, because for any two ideals $I$ and $J$ of $R$, $I\subseteq J$ if and only if $I+J=J$. (More generally, $I+J$ is the smallest ideal containing both $I$ and $J$.) Second, this allows us to recover the prime ideals of $R$. This is because an ideal $P$ of $R$ is prime if and only if, for any ideals $I$ and $J$ of $R$, $IJ\subseteq P$ implies $I\subseteq P$ or $J\subseteq P$. (The same can be said for the semiprime ideals of $R$, which are the radical ideals of $R$ in case $R$ is commutative.) Third, we can recover the Zariski topology on the prime spectrum of $R$ because it is defined using the natural partial ordering on the ideals of $R$.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/26607', 'https://mathoverflow.net', 'https://mathoverflow.net/users/3106/']}
jdg_380216
stackexchange
llm_judgeable_groundtruth_similarity
27610
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: Study Design: I showed participants some information about sea-level rise, focusing the information in different ways, both in terms of the time-scale and the magnitude of potential rise. Thus I had a 2 (Time: 2050 or 2100) by 2 (Magnitude: Medium or High) design. There were also two control groups who received no information, only answering the questions for my DVs. Questions: I've always checked for normality within cells -- for the 2x2 portion of this design, it would mean looking for normality within 4 groups. However, reading some discussions here has made me second guess my methods. First, I've read that I should be looking at the normality of the residuals. How can I check for normality of residuals (in SPSS or elsewhere)? Do I have to do this for each of the 4 groups (6 including the controls)? I also read that normality within groups implies normality of the residuals. Is this true? (Literature references?) Again, does this mean looking at each of the 4 cells separately? In short, what steps would you take to determine whether your (2x2) data are not violating assumptions of normality? References are always appreciated, even if just to point me in the right direction. Now provide the response and nothing else.
Most statistics packages have ways of saving residuals from your model. Using GLM - UNIVARIATE in SPSS you can save residuals. This will add a variable to your data file representing the residual for each observation. Once you have your residuals you can then examine them to see whether they are normally distributed, homoscedastic, and so on. For example, you could use a formal normality test on your residual variable or perhaps more appropriately, you could plot the residuals to check for any major departures from normality. If you want to examine homoscedasticity, you could get a plot that looked at the residuals by group. For a basic between subjects factorial ANOVA, where homogeneity of variance holds, normality within cells means normality of residuals because your model in ANOVA is to predict group means. Thus, the residual is just the difference between group means and observed data. Response to comments below: Residuals are defined relative to your model predictions. In this case your model predictions are your cell means. It is a more generalisable way of thinking about assumption testing if you focus on plotting the residuals rather than plotting individual cell means, even if in this particular case, they are basically the same. For example, if you add a covariate (ANCOVA), residuals would be more appropriate to examine than distributions within cells. For purposes of examining normality, standardised and unstandardised residuals will provide the same answer. Standardised residuals can be useful when you are trying to identify data that is poorly modelled by the data (i.e., an outlier). Homogeneity of variance and homoscedasticity mean the same thing as far as I'm aware. Once again, it is common to examine this assumption by comparing the variances across groups/cells. In your case, whether you calculate variance in residuals for each cell or based on the raw data in each cell, you will get the same values. However, you can also plot residuals on the y-axis and predicted values on the x-axis. This is a more generalisable approach as it is also applicable to other situations such as where you add covariates or you are doing multiple regression. A point was raised below that when you have heteroscedasticity (i.e., within cell variance varies between cells in the population) and normally distributed residuals within cells, the resulting distribution of all residuals would be non-normal. The result would be a mixture distribution of variables with mean of zero and different variances with proportions relative to cell sizes. The resulting distribution will have no zero skew, but would presumably have some amount of kurtosis. If you divide residuals by their corresponding within-cell standard deviation, then you could remove the effect heteroscedasticity; plotting the residuals that result would provide an overall test of whether residuals are normally distributed independent of any heteroscedasticity.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/27610', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/10227/']}
jdg_380217
stackexchange
llm_judgeable_groundtruth_similarity
18479771
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 confused in join() method used in Threads in Java. In the following code: // Using join() to wait for threads to finish.class NewThread implements Runnable { String name; // name of thread Thread t; NewThread(String threadname) { name = threadname; t = new Thread(this, name); System.out.println("New thread: " + t); t.start(); // Start the thread }// This is the entry point for thread. public void run() { try { for (int i = 5; i > 0; i--) { System.out.println(name + ": " + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println(name + " interrupted."); } System.out.println(name + " exiting."); }}class DemoJoin { public static void main(String args[]) { NewThread ob1 = new NewThread("One"); NewThread ob2 = new NewThread("Two"); NewThread ob3 = new NewThread("Three"); System.out.println("Thread One is alive: " + ob1.t.isAlive()); System.out.println("Thread Two is alive: " + ob2.t.isAlive()); System.out.println("Thread Three is alive: " + ob3.t.isAlive());// wait for threads to finish try { System.out.println("Waiting for threads to finish."); ob1.t.join(); ob2.t.join(); ob3.t.join(); } catch (InterruptedException e) { System.out.println("Main thread Interrupted"); } System.out.println("Thread One is alive: " + ob1.t.isAlive()); System.out.println("Thread Two is alive: " + ob2.t.isAlive()); System.out.println("Thread Three is alive: " + ob3.t.isAlive()); System.out.println("Main thread exiting."); }} Sample output from this program is shown here: New thread: Thread[One,5,main]New thread: Thread[Two,5,main]New thread: Thread[Three,5,main]Thread One is alive: trueThread Two is alive: trueThread Three is alive: trueWaiting for threads to finish.One: 5Two: 5Three: 5One: 4Two: 4Three: 4One: 3Two: 3Three: 3One: 2Two: 2Three: 2One: 1Two: 1Three: 1Two exiting.Three exiting.One exiting.Thread One is alive: falseThread Two is alive: falseThread Three is alive: falseMain thread Exiting In the above code : I'm not able to understand the flow of execution of the program, And when ob1 is created then the constructor is called where t.start() is written but still run() method is not executed rather main() method continues execution. So why is this happening? join() method is used to wait until the thread on which it is called does not terminates, but here in output we see alternate outputs of the thread why?? And if the use of join is this then what is the use of synchronized ?? I know I'm missing a basic concept here, but I'm not able to figure it out so please help. Now provide the response and nothing else.
You must understand , threads scheduling is controlled by thread scheduler.So, you cannot guarantee the order of execution of threads under normal circumstances. However, you can use join() to wait for a thread to complete its work. For example, in your case ob1.t.join(); This statement will not return until thread t has finished running. Try this, class Demo { Thread t = new Thread( new Runnable() { public void run () { //do something } } ); Thread t1 = new Thread( new Runnable() { public void run () { //do something } } ); t.start(); // Line 15 t.join(); // Line 16 t1.start();} In the above example, your main thread is executing. When it encounters line 15, thread t is available at thread scheduler. As soon as main thread comes to line 16, it will wait for thread t to finish. NOTE that t.join did not do anything to thread t or to thread t1 . It only affected the thread that called it (i.e., the main() thread). Edited: t.join(); needs to be inside the try block because it throws the InterruptedException exception, otherwise you will get an error at compile time. So, it should be: try{ t.join();}catch(InterruptedException e){ // ...}
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/18479771', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2696258/']}
jdg_380218
stackexchange
llm_judgeable_groundtruth_similarity
58351239
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 does the new ViewBinding compare with the Kotlin Android Extensions with synthetic views bindings? Apart from the NullSafety and TypeSafety provided by new ViewBindings, why should we consider ditching the Kotlin way of using synthetic bindings on Views? Is the new ViewBinding more performant since it generates the Binding class beforehand? Now provide the response and nothing else.
Let's review the two. Configuration Kotlin Android Extensions Import appropriate layout synthetic extensions: import kotlinx.android.synthetic.main.<layout>.* Reference views in code via their ids: textView.text = "Hello, world!" . These extensions work on: Activities , Fragments and Views . View Binding Create binding reference inside your class: private lateinit var bindingYourClassBinding Inflate your binding binding = YourClassBinding.inflate(layoutInflater) inside Activity 's onCreate and call setContentView(binding.root) , or inflate it in Fragment 's onCreateView then return it: return binding.root Reference views in code via binding using their ids binding.textView.text = "Hello, world!" Type safety Kotlin Android Extensions and ViewBinding are type safe by definition, because referenced views are already casted to appropriate types. Null safety Kotlin Android Extensions and ViewBinding are both null safe. ViewBinding doesn't have any advantage here . In case of KAE , if view is present only in some layout configurations, IDE will point that out for you: So you just treat it as any other nullable type in Kotlin, and the error will disappear: Applying layout changes In case of Kotlin Android Extensions , layout changes instantly translate to generation of synthetic extensions, so you can use them right away. In case of ViewBinding , you have to build your project Incorrect layout usage In case of Kotlin Android Extensions , it is possible to import incorrect layout synthetic extensions, thus causing NullPointerException . The same applies to ViewBinding , since we can import wrong Binding class. Although, it is more probable to overlook incorrect import than incorrect class name, especially if layout file is well named after Activity / Fragment / View , so ViewBinding has upper hand here. Summary of KAE vs ViewBinding Type safety - Draw. Null safety - Draw. Boilerplate code - KAE wins. From Kotlin Android Extensions documentation : The Kotlin Android Extensions plugin allows us to obtain the same experience we have with some of these libraries, without having to add any extra code. Applying layout changes - KAE wins. Changes are instant in contrast to ViewBinding . Incorrect layout usage - ViewBinding wins I think there is big misconception about ViewBinding being replacement for KAE . People hear big keywords and repeat them without verifying it beforehand. Sure, ViewBinding is best option for Java development right now (replacement for ButterKnife ), but there is no or little advantage over KAE in Kotlin (see Incorrect layout usage section). Side note: I'm sure DataBinding people will like ViewBinding :)
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/58351239', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1336154/']}
jdg_380219
stackexchange
llm_judgeable_groundtruth_similarity
4379724
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 rule for identity type elimination still mystifies me, and I have not been able to find anything that satisfies me in any book. Consider, for example, the form of the rule on p. 112 of Thompson: \begin{array}{c} c: I(A,a,b) \hskip 0.6 cm d:C(a,a,r(a)) \\ \hline J(c,d): C(a,b,c)\end{array} If the rule were just: \begin{array}{c} c: I(A,a,b) \hskip 0.6 cm d:C(a,a) \\ \hline J(c,d): C(a,b)\end{array} then I would understand it completely - from a verification $c$ of $a=b$ and a verification $d$ of $C(a,a)$ , one can construct a verification of $C(a,b)$ , and that's what $J(c,d)$ encodes. But how can I move from a verification $c$ of $a=b$ and a verification $d$ of $C(a,a,r(a))$ , to a verification of $C(a,b,c)$ ? I don't even see the intuition behind it. Now provide the response and nothing else.
The idea is that we want to allow our theorems to depend not only on $a$ and $b$ , but also on the particular proof of equality! Here I'm assuming $r(a) : I(a,a)$ is reflexivity. It's tricky to reason about what this means, since it's consistent that the only proofs of type $I(A,a,b)$ are reflexivity (this is called axiom k ). That is, it's possible that $c$ is always $r(a)$ ! In fact, many "natural" modelshave exactly this property! Models where this property fails are called " proof relevant ", and the idea is that types $C(a,b,c)$ might depend on which particular proof $c : I(A,a,b)$ we're given! It's extremely surprising that we can understand terms of type $C(a,b,c)$ just by understanding terms of type $C(a,a,r(a))$ . More than most induction principles, this feels like we're getting something for free. So when it comes to being confused by this principle, you're in very good company! Lots of people (myself very much included) have struggled with this, and there's a lot of resources for trying to understand it (see here , for instance). The most natural way to understand the dependence on $c$ , at least in my mind, is through the homotopy theoretic interpretation. So let's take a moment to talk about that. Here types are geometric spaces, and terms $a : A$ are points in $A$ . Now, in homotopy theory, when do we consider two points to be "the same"? Precisely when there's a path from $a$ to $b$ in $A$ . But now it should be very clear that there are multiple possible paths from $a$ to $b$ , and thus multiple possible proofs of $I(A,a,b)$ . So now say we have a proposition $C$ which depends on $a,b$ as well as the path $p : I(A,a,b)$ . For instance, we might have $$C(a,b,p) = \prod_{p : I(A,a,b)} \sum_{q : I(A,b,a)} p \cdot q = r(a)$$ where homotopy theoretically we interpet $p \cdot q$ as the concatenation of the paths $p$ and $q$ (I'll not formally define it, though). The magical thing (called " path induction " in this context) is that to prove the above claim for every $a,b,p$ , it suffices to prove it for $a,a,r(a)$ ! Again, I agree that it's far from obvious that this should work. But here's a homotopy theoretic justification: One can show that the space of paths one one endpoint fixed and one endpoint free is contractible , in the sense that, for any two such paths (which are now points in the space of all paths) there is a path between them (in the space of all paths). In the type theoretic interpretation, this is saying that for any two proofs $p,q : \sum_{b : A} I(A,a,b)$ there is a proof of $I \left ( \sum_{b : A} I(A,a,b), p, q \right )$ . But this is good, because it means that every such proof is equal to $(a,r(a)) : \sum_{b : A} I(A,a,b)$ . And we know that we can substitute equal things, so once we've proven $C(a, (a,r(a))$ we can substitute to get a proof of $C(a, (b,c))$ (where I've silently uncurried $C$ . Obviously this isn't an issue). Edit: In the comments you bring up a reasonable point, that bringing in homotopy theory seems like some heavy duty machinery for something comparatively simple. Here's a (possibly anachronistic) view of how this might have been developed and understood in a pre-HoTT world. First, remember that we use elimination rules in order to define functions. For instance, the elimination rule for $\mathbb{N}$ exactly says that we can define functions on $\mathbb{N}$ by recursion. So, if we want to be able to define functions out of an identity type $I(A,a,b)$ , then we need the elimination rule to give us something of the form $J : C(a,b,p)$ , where of course $p : I(A,a,b)$ . That way we know where to send a given proof of equality $p$ . Now, you might say "if $r(a)$ is the only proof, can't we leave it as an implicit argument?" and while we probably could , it's fairly standard to not. For instance, we define the type $\mathbf{1}$ , which we want to think of as having exactly one inhabitant, $\star : \mathbf{1}$ . But the way we encode that is with an elimination rule called singleton induction : $$\frac{{}}{\star : \mathbf{1}}\ \ (\mathbf{1} \text{ intro}) \quad \quad \frac{c : C(\star) \quad x : \mathbf{1}}{\mathtt{ind}_\mathbf{1}(C,c,x) : C(x)}\ \ (\mathbf{1} \text{ elim})$$ It's then a theorem in the type theory that $\prod_{x : \mathbf{1}} x=\star$ , so we don't need to specify uniqueness in the metalanguage. This is because our elimination rule says that the value of a function on $\mathbf{1}$ is completely determined by its action on $\star$ . Of course, our approach to the identity type is entirely analogous. Even if we're thinking of $I(A,a,b)$ as being either empty or uniquely inhabited, it's "more hygenic" in a sense to leave that as a theorem in the type theory, rather than try to force it in the metalanguage. This leads us to do exactly what we did with singleton induction. Since we want the entire type to be generated by $r(a)$ , we define introduction and elimination rules: $$\frac{a : A}{r(a) : I(A,a,a)}\ \ (I\text{ intro})\quad \quad\frac{c : C(a,a,r(a)) \quad p : I(A,a,b)}{\mathtt{ind}_{I}(C,c,p) : C(a,b,p)}\ \ (I\text{ elim})$$ these are entirely analogous to the rules for singletons, and indeed we can prove inside the theory that $$\prod_{(b,p) : \sum_{b : A} I(A,a,b)} (b,p) = (a,r(a))$$ I wasn't there, but I suspect it came as a surprise when people first realized that there are models of this type theory where the identity type can have more than one element. I hope this helps ^_^
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4379724', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/683716/']}
jdg_380220
stackexchange
llm_judgeable_groundtruth_similarity
765
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: How do i measure the level of a water tank with a microcontroller? Now provide the response and nothing else.
Well, assuming you are operating here on earth (as opposed to in orbit), you can use a float sensor that you measure using the micro. The question is: Do you need to know the exact level, or do you just need some sort of trip when it gets to high/low? On the 'trip at specific level' theme, you can get switches like this - generally the float contains some kind of attitude sensing switch. When the water level is lower, the float ends up on it's side, and the switch is 'off', while raising the level forces the float upright, and therefore 'on'. These are often used for sump pumps. They are pretty reliable and very easy to deal with, though you have to be careful to anchor them correctly, and you have to be sure that nothing gets in the way of the float. If you need to know the actual level, then you've got lots of choices, but it's less simple. You can go with something like an ultrasonic sensor (ultrasound beam firing down from the top of the tank to reflect off the water level). These guys seem to make level indicators for BIG tanks which consist of a float and an external weight cabled together. As the float rides up and down on the fluid, the external indicator moves appropriately. You could build something similar, with nothing more complicated than photo-cells to read the level (if it's a large tank, or you want lots of granularity, you'd need a lot of photo-cells). Alternately, taking the cabled float idea, you could put an idler wheel that moves whenever the cable moves, and then attach an encoder to that. This would allow you to track the level with pretty high accuracy.
{}
{'log_upvote_score': 6, 'links': ['https://electronics.stackexchange.com/questions/765', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/21/']}
jdg_380221
stackexchange
llm_judgeable_groundtruth_similarity
2057701
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: Determine the functions $ f:\mathbb{R}^{*}\rightarrow \mathbb{R} $ for which $ G=\left \{ \begin{pmatrix}x & f(x)\\ 0& 1\end{pmatrix}|x\in \mathbb{R}^{*} \right \} $ is closed under multiplication of matrices from $ M_{2}(\mathbb{R}) $. In this case, prove that groups $ (G,\cdot ) $ and $ (\mathbb{R}_{+}^{*},\cdot ) $ are isomorphic. I think that $ f(x)\cdot f(y)=x\cdot f(y)+f(x) $, but I don't know what to do next. Now provide the response and nothing else.
$f$ has to satisfy $f(xy)=xf(y)+f(x).$ For $y=-1$ we have $$f(-x)=xf(-1)+f(x).$$ For $x=-1$ we have $$f(-y)=-f(y)+f(-1).$$ That is $$f(-x)=-f(x)+f(-1).$$ Thus we have $$\begin{cases}f(-x)-f(x)&=xf(-1)\\f(-x)+f(x)&=f(-1)\end{cases}$$ Solving the system we get $f(x)=\frac{f(-1)}{2}(1-x).$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2057701', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/326591/']}
jdg_380222
stackexchange
llm_judgeable_groundtruth_similarity
1958667
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 know my binary string is composed of exactly $n$ $1$s and $m$ $0$s. How many such strings are possible, if we add the constraint that they must not contain a specific given substring $S$ (whose length is $\leq n+m$)? I am specifically interested in the answer in the case that $S=010$. Note: I know how to determine the answer programatically / via dynamic programming. I'm looking for a more closed form / combinatoric solution. For example, if $n=3$, $m=2$, and $S=010$, then the following would be all $7$ relevant ways:$$00111$$$$01101$$$$01110$$$$10011$$$$10110$$$$11001$$$$11100$$ Now provide the response and nothing else.
This answer is based upon the Goulden-Jackson Cluster Method . We consider the set words of length $n\geq 0$ built from an alphabet $$\mathcal{V}=\{0,1\}$$ and the set $B=\{010\}$ of bad words , which are not allowed to be part of the words we are looking for. We derive a generating function $f(s)$ with the coefficient of $s^n$ being the number of searched words of length $n$. According to the paper (p.7) the generating function $f(s)$ is\begin{align*}f(s)=\frac{1}{1-ds-\text{weight}(\mathcal{C})}\tag{1}\end{align*}with $d=|\mathcal{V}|=2$, the size of the alphabet and $\mathcal{C}$ the weight-numerator of bad words with\begin{align*}\text{weight}(\mathcal{C})=\text{weight}(\mathcal{C}[010])\end{align*} We calculate according to the paper \begin{align*}\text{weight}(\mathcal{C}[010])&=-s^3-s^2\text{weight}(\mathcal{C}[010])\tag{1}\\\end{align*} and get \begin{align*}\text{weight}(\mathcal{C})=-\frac{s^3}{1+s^2}\end{align*} It follows \begin{align*}f(s)&=\frac{1}{1-ds-\text{weight}(\mathcal{C})}\\&=\frac{1}{1-2s+\frac{s^3}{1+s^2}}\tag{2}\\&=\frac{1+s^2}{1-2s+s^2-s^3}\\&=1+2s+4s^2+7s^3+12s^4+\color{blue}{21}s^5\\&\qquad+37s^6+65s^7+114s^8+200s^9+351s^{10}+\cdots\end{align*} The last line was calculated with the help of Wolfram Alpha. The coefficient of $s^5$ shows there are $\color{blue}{21}$ valid words of length $5$ from the alphabet $\{0,1\}$ which do not contain the word $010$. But we want to also keep track of the number of $0$'s and $1$'s. We get a refinement of $f(s)$ by marking the $0$ with $x$ and the $1$'s with $y$. We obtain from (1)\begin{align*}\text{weight}(\mathcal{C}[010])&=-x^2ys^3-xys^2\text{weight}(\mathcal{C}[010])\end{align*}and get\begin{align*}\text{weight}(\mathcal{C})=-\frac{x^2ys^3}{1+xys^2}\end{align*} Using this generalized weight we obtain from (2) a generating function $g(s;x,y)$ \begin{align*}g(s;x,y)&=\frac{1}{1-(x+y)s+\frac{x^2ys^3}{1+xys^2}}\\&=\frac{1+xys^2}{1-(x+y)s+xys^2-xy^2s^3}\\&=1+(x+y)s+(x^2+2xy+y^2)s^2+(x^3+2x^2y+3xy^2+y^3)\\&\qquad+(x^4+2x^3y+4x^2y^2+4xy^3+y^4)s^4\\&\qquad+(x^5+2x^4y+5x^3y^2+\color{red}{7}x^2y^3+5xy^4+y^5)s^5+\cdots\end{align*} So, e.g. out of $2^5=32$ binary words of length $5$ there are $\color{blue}{21}$ valid words which do not contain $010$ and $\color{red}{7}$ of them contain $n=2$ zeros and $m=3$ ones: \begin{array}{cccc}\qquad\color{blue}{00000}\qquad&\qquad01000\qquad&\qquad\color{blue}{10000}\qquad&\qquad\color{blue}{11000}\qquad\\\color{blue}{00001}&01001&\color{blue}{10001}&\color{red}{11001}\\00010&01010&10010&11010\\\color{blue}{00011}&01011&\color{red}{10011}&\color{blue}{11011}\\00100&\color{blue}{01100}&10100&\color{red}{11100}\\00101&\color{red}{01101}&10101&\color{blue}{11101}\\\color{blue}{00110}&\color{red}{01110}&\color{red}{10110}&\color{blue}{11110}\\\color{red}{00111}&\color{blue}{01111}&\color{blue}{10111}&\color{blue}{11111}\\\end{array}
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1958667', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/93666/']}
jdg_380223
stackexchange
llm_judgeable_groundtruth_similarity
39451134
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 install the phantomjs executable in /usr/local/bin in a docker container, alongside node. I think I'm almost there, but I'm pretty new to docker and not well versed in installing binaries or working with Linux so struggling to work out where I'm going wrong. This is my docker file: FROM node:6.4-onbuild# Install phantomjsWORKDIR ~RUN apt-get install libfreetype6 libfreetype6-dev \ && apt-get install libfontconfig1 libfontconfig1-devRUN export PHANTOM_JS="phantomjs-2.1.1-linux-i686" \ && wget https://bitbucket.org/ariya/phantomjs/downloads/$PHANTOM_JS.tar.bz2 \ && tar xvjf $PHANTOM_JS.tar.bz2 \ && mv $PHANTOM_JS /usr/local/share \ && ln -sf /usr/local/share/$PHANTOM_JS/bin/phantomjs /usr/local/binWORKDIR /usr/src/appRUN npm run buildEXPOSE 8080CMD ["node", "./bin/start.js"] I've run bash on the container and there is definitely something called phantomjs in /usr/local/bin but I'm assuming that I've linked the wrong thing or it's an invalid executable. I'm thrown an error from my application telling me that there is no phantomjs executable in /usr/local/bin . Can anyone give me a few pointers? Happy to provide more details if you post a comment. Now provide the response and nothing else.
There's an existing image for this already on Docker hub using the following Dockerfile: FROM debian:jessie MAINTAINER Werner Beroux <[email protected]> # 1. Install runtime dependencies # 2. Install official PhantomJS release # 3. Clean up RUN apt-get update \ && apt-get install -y --no-install-recommends \ ca-certificates \ bzip2 \ libfontconfig \ && apt-get clean \ && rm -rf /var/lib/apt/lists/* RUN apt-get update \ && apt-get install -y --no-install-recommends \ curl \ && mkdir /tmp/phantomjs \ && curl -L https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-linux-x86_64.tar.bz2 \ | tar -xj --strip-components=1 -C /tmp/phantomjs \ && cd /tmp/phantomjs \ && mv bin/phantomjs /usr/local/bin \ && cd \ && apt-get purge --auto-remove -y \ curl \ && apt-get clean \ && rm -rf /tmp/* /var/lib/apt/lists/* # Run as non-root user RUN useradd --system --uid 72379 -m --shell /usr/sbin/nologin phantomjs USER phantomjs EXPOSE 8910 CMD ["/usr/local/bin/phantomjs"]
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39451134', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2929228/']}
jdg_380224
stackexchange
llm_judgeable_groundtruth_similarity
3785577
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: Usually the topological object which goes under the name of the torus is defined as the product $$T=S^1 \times S^1 $$ of two circles. I call this Definition (1) Another definition I have seen is the following, Definition (2A) We draw a rectangle, label each pair of parallel sides with letters e.g. $a,$ $b,$ and make sure each couple of parallel sides is oriented in the same direction. Then we quotient the rectangle so that the parallel sides are identified. What we get is again the torus. Another version of this last one is the following Definition (2B) We consider in $\mathbb{R}^2$ the unit square $[0,1]\times[0,1]$ and we quotient it by the relation that identifies $$(x,y)\sim (x',y') \iff (x=0,x'=1,y=y') \lor (y=0,y'=1,x=x')\lor (x=x',y=y') $$ Yet another one, Definition (3A) is We consider $\mathbb{R}^2$ , its group of homeomorphisms $H=\text{homeo}(\mathbb{R^2})$ and the subgroup $G\subset H$ generated by the traslations $a:(x,y)\mapsto (x+1,y)$ $ \ $ $b:(x,y) \mapsto (x,y+1).$ Then we define the Torus as the group $$T=\mathbb{R}^2/G$$ with the quotient topology. Related to this is Definition (3B) We define the Torus as the quotient $$T= \mathbb{R}^2/\mathbb{Z}^2.$$ The main question is the following I want to understand, in a detailed and rigorous way, how to go back and forth from each one of these definitions to the others. A few more specific questions related to the main one: In the second definition we just consider a "rectangle" as a topological object, but how is it defined? Do we have to see it as some $[a,b] \times [c,d]$ embedded in $\mathbb{R}^2$ ? Can I define it without embedding it in $\mathbb{R}^2?$ Still thinking about the second definition, I understand, at an intuitive level, that we have to consider the parallel sides of the rectangle "oriented in the same direction", because otherwise, with different orientations, we would get a completely different object such as a sphere or the Klein bottle or a Mobius strip. How is this choice of orientation, that gives us the torus, encoded in the other definitions? In particular why we do not need to talk about the orientation of the sides in definition 2B? Looking at definition 3A, I see that the translations $a,b$ morally correspond to the two couples of parallel sides in the previous definitions, and the important thing is that they commmute i.e. $ab=ba$ , which morally says that the parallel sides have the same orientation. The commutativity of $a,b$ implies immediately that $G$ is isomorphic as a group to $\mathbb{Z}^2,$ but I'm not sure this implies immediately that $\mathbb{R}^2/G \simeq \mathbb{R}^2/\mathbb{Z}^2$ without having to say anything else. Now provide the response and nothing else.
Let $I$ be a closed interval. It is convenient to associate it with $[0,1] \subset \Bbb{R}$ , especially as we will wish to treat it as a metric space as well as a topological space. It should be no surprise that $I$ is homeomorphic to any other closed interval of $\Bbb{R}$ , so the choice of the endpoints $0$ and $1$ is not essential. In the following, I will distinguish between $\Bbb{R}$ , a topological space without a metric, and $\Bbb{E}$ , the Euclidean line, which is $\Bbb{R}$ endowed with the usual metric, $d(x,y) = |x-y|$ . (This distinction is frequently viewed as superfluous, since remembering "the $\Bbb{R}$ I've been studying for years has always been a metric space and sometimes we just choose to forget about the metric when we are doing topology and then suddenly remember it when it is convenient to do so" seems to be easy for most of us.) $2 \leftrightarrow 1$ In plane geometry, rectangle is a quadrilateral with right angles in each of its four corners and each pair of opposite sides parallel. "Right angles" and "parallel" are meaningless in a topological space. Also, on some 2-manifolds (a reasonable large set of spaces on which one might try to talk about a conformal (= angle preserving) embedding of a rectangle) a geometric figure made of (geodesic) line segments turning through three right angles can close (uniform spherical geometry -- two vertices on the equator and one vertex at the north pole). On others (uniform hyperbolic geometry) a geometric figure made of (geodesic) line segments and three right angles does not close at a right angle (the first and fourth segments may not meet or may meet at some smaller angle). So to get a rectangle, the space has to be flat where we try to put the rectangle, so we can require uniformly flat. This gives one option -- a rectangle always lies in (some connected subset) of the Euclidean plane, $\Bbb{E}^2$ . In a metric space, we can distinguish different rectangles by their orientation and edge lengths, so three numbers. In a topological space, a rectangle and a circle are indistinguishable and edge length is meaningless, so all three of our numbers are useless in distinguishing rectangles in $\Bbb{R}^2$ . (This is a two step process : first embed the rectangle in $\Bbb{E}^2$ , then forget about the metric and observe that you have a bunch of points in the topological space $\Bbb{R}^2$ , labelled "rectangle".) There are then several alternative notions of equivalence that one might apply -- the strictest is usually ambient isotopy and any rectangle in the plane is ambient isotopic to any other rectangle. So in a topological space, we lose nothing by deciding that "rectangle" means $I \times I$ . $I \times I = [0,1] \times [0,1] \subset \Bbb{E}^2$ , its product topology is equivalent to its subspace topology inherited from $\Bbb{R}^2$ , and its product metric is equivalent to its subspace metric inherited from $\Bbb{E}^2$ . The specified quotient is a disjunction of three terms. The first term makes the identification $(0,y) \sim (1,y)$ for $y \in I$ . The second term makes the identification $(x,0) \sim (x,1)$ for $x \in I$ . (The third term leaves all the interior points alone.) These choices set the orientation of the identification. One could alternatively make the identification $(x,0) \sim (1-x,1)$ , which would reverse the orientation of that piece of the quotient. The following pair of diagrams show by arrows how the identification in the quotient preserves the orientation and how the proposed alternative reverses the orientation using arrows from points on the lower edge to the equivalent point on the upper edge. Note that $I \times I$ is "for each point in one copy of $I$ a copy of $I$ " (with the product topology). We are free to decide which factor is which copy in that phrase -- in fact, we can reverse our point of view and get the same result. This means that we can treat $I \times I$ as a bundle of horizontal copies of $I$ or as a bundle of vertical copies of $I$ . When we apply the $(x,0) \sim (x,1)$ equivalence, each line in the vertical bundle has its lower endpoint identified with its upper endpoint, producing a circle. So temporarily pausing after performing that part of the quotient, we have "for each point in the horizontal $I$ , we have a vertical $S^1$ ". If we start at $I \times I$ and instead apply the $(0,y) \sim (1,y)$ part of the equivalence, we obtain "for each point in the vertical $I$ , we have a horizontal $S^1$ ". In both cases, we have a cylinder (just the curved part, not including the two flat disks that are normally used to cap off the ends), closed since it includes the two circles on its boundary. When we finish the quotient, all of the vertical line segments quotient into a circle and all of the horizontal line segments quotient into a circle and for each point in one family of circles, we have a circle in the other family. That is, we have an $S^1 \times S^1$ . Now suppose we have an $S^1 \times S^1$ . This naturally lives embedded in $\Bbb{R}^4$ (or $\Bbb{C}^2$ ) as the unit circle in the first two coordinates cross the unit circle in the second two coordinates, $$ T^2 \simeq \{(a,b,c,d) \mid a^2 + b^2 = 1, c^2 + d^2 = 1\} \text{.} $$ When you embed a torus in $\Bbb{R}^3$ , you have to make a decision about which $S^1$ factor corresponds to the longitude of the torus and which factor corresponds to the meridian. The two are not interchangeable -- the longitude bounds a disk exterior to the torus and the meridian bounds a disk interior to the torus. In the $\Bbb{R}^4$ version, we need make no such distinction -- there is a rigid rotation of $\Bbb{R}^4$ that implements $\{a \leftrightarrow c, b \leftrightarrow d\}$ , making the distinction between the factors superficial. As I said, we can also express this in $\Bbb{C}^2$ : $$ T^2 \simeq \{(w,z) \mid ||w|| = 1, ||z|| = 1 \} \text{.} $$ But for our purpose, it is better to use the polar representation of complex numbers, $$ T^2 \simeq \{(\mathrm{e}^{2\pi \mathrm{i} \theta}, \mathrm{e}^{2\pi \mathrm{i} \phi}) \mid \theta \in [0,1), \phi \in [0,1) \} \text{.} $$ Notice that we are almost there -- we are close to having our two parameters only vary over $[0,1]$ , we just need to undo the quotient. Start by deleting the circle $\theta = 0$ . This gives us a cylinder excluding its boundary circles. Now make two copies of the circle we just deleted, glue one along the $\theta = 0$ boundary, and glue the other along the $\theta = 1$ boundary. This gives $I \times S^1$ . Now repeat with $\phi$ replacing $\theta$ , cutting out a line and gluing in two lines, producing $I \times I$ . (Instead of deleting, we can cut to obtain $[0,1)$ for one factor, then duplicate the circle or line at $0$ to glue to the boundary at $1$ , yielding an $I$ factor. Recall that when we do any cutting the two new boundary components are in no sense "close" to each other -- we have cleaved apart all the open sets that crossed the cut.) (From here, going back to the torus, we start with $I \times I$ , identify two lines, producing one line (obtaining $S^1 \times I$ ), then identify two circles, producing one circle (obtaining $S^1 \times S^1$ ), just as we described when talking about horizontal and vertical line bundles.) $3 \leftrightarrow \{1,2\}$ In this case, you will be much better served seeing these as maps onto $[0,1) \times [0,1)$ . Then looking at a small open disk neighborhood of a point in the middle of this "half-open square" (small enough to not meet an edge or corner), such a disk centered on an edge (small enough to not touch another edge or corner), and such a disk centered on a corner. You will discover that you have rediscovered the $\theta-\phi$ parametrization of the torus from above. That is, the open sets will reveal the quotients of the ends of the horizontal and vertical half-open line segment bundles. $\Bbb{R}^2 /G \simeq \Bbb{R}^2 / \Bbb{Z}^2$ Happily, $\Bbb{R}^2$ is a vector space, so if you pick any two nonzero linearly independent elements of $\Bbb{R}^2$ , say $\{\alpha, \beta\}$ , then $$ \Bbb{R}^2 /G \simeq \Bbb{R}^2 / \langle \alpha, \beta \rangle \simeq \Bbb{R}^2 / \Bbb{Z}^2 \text{,} $$ where $\Bbb{R}^2$ is treated as an abelian group of displacement vectors, and $\langle \alpha, \beta \rangle$ is the free abelian subgroup of $\Bbb{R}^2$ (equivalently, a module over the PID $\Bbb{Z}$ ) generated by $\alpha$ and $\beta$ . $G$ is given as the free abelian subgroup spanned by the two displacement vectors $(1,0)$ and $(0,1)$ (or their transposes, depending on how you are thinking of this object), which are linearly independent. It may help to notice that the block square matrix $\left( \alpha \ \beta \right)$ is an invertible ("two linearly independent elements") linear map taking the generators of $G$ to $\alpha$ and $\beta$ , respectively. A linear map is a homeomorphism. The various parallelograms with opposite sides identified (preserving orientation) are all equivalent (to the special parallelogram, $I \times I$ ). One should check that the three types of neighborhoods meet the quotient requirements, as discussed in the previous section.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3785577', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/801596/']}
jdg_380225
stackexchange
llm_judgeable_groundtruth_similarity
20549016
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 really like the "explode" option on matplotlib pie charts. I was hoping to be able to "explode in groups". I'm plotting lots of little slices that fall into 3 or 4 categories. I'd like to explode all the little slices together, as groups. I figure that's not entirely clear, so I have called upon my sorely lacking ability to draw basic shapes and made this picture showing what I'm trying to do: Please note the little unshaded gaps between the groups. Is this possible? Thanks a lot, Alex Now provide the response and nothing else.
I'm not aware of any direct way to specify grouped exploded pies, but it is quite simple to use patches to redraw a pie with groups like # original part (left)import numpy as npimport matplotlib.pyplot as pltf,ax = plt.subplots(1,2) ax[0].set_aspect('equal')data=np.abs(np.random.randn(7))wedges, texts = ax[0].pie(data)# redraw plot using patches (right)import matplotlib.patches as mpatchesfrom matplotlib.collections import PatchCollectionax[1].set_aspect('equal')ax[1].axis('off')groups=[[0,1,2],[3,4],[5,6]]radfraction = 0.1patches = []for i in groups: ang = np.deg2rad((wedges[i[-1]].theta2 + wedges[i[0]].theta1)/2,) for j in i: we = wedges[j] center = (radfraction*we.r*np.cos(ang), radfraction*we.r*np.sin(ang)) patches.append(mpatches.Wedge(center, we.r, we.theta1, we.theta2))colors = np.linspace(0, 1, len(patches))collection = PatchCollection(patches, cmap=plt.cm.hsv)collection.set_array(np.array(colors))ax[1].add_collection(collection)ax[1].autoscale(True) This may result in a plot like Of course, you could simply compute the required theta-angles based on your data instead of using the precomputed ones.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20549016', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/728286/']}
jdg_380226
stackexchange
llm_judgeable_groundtruth_similarity
9982433
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm developing an application for my final thesis on computer science, and I need to collect and log accelerometer data. I need to acquire it for a whole day long, so there are serious battery constraints (for instance, I cannot leave the screen on). Also, this isn't a market targeted application, so it is pretty acceptable to do some serious hacking, even low level C/C++ coding, if required. It is well known that on many devices the listeners for accelerometer events stop generating events when screen goes off (some links regarding this problem: http://code.google.com/p/android/issues/detail?id=3708 , Accelerometer stops delivering samples when the screen is off on Droid/Nexus One even with a WakeLock ). I have thoroughly searched for some alternatives, some of them include workarounds that do not work for my device (LG P990, stock ROM). So what happens is this: When you register an event listener for android accelerometer sensor in a Service, it works fine until the screen is turned off. I have already tried to register the eventListener on a Service, on an IntentService, tried to acquire WakeLocks. Regarding wakelocks, I can verify that the service is still running watching the LOGcat output, but it seems the accelerometer is put into sleep mode. One of the workarounds presented in some of the links is to unregister and re-register the event listener periodically using the thread of an IntentService like in this code snippet bellow synchronized private static PowerManager.WakeLock getLock(Context context) { if (lockStatic==null) { PowerManager mgr=(PowerManager)context.getSystemService(Context.POWER_SERVICE); lockStatic = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,NAME); lockStatic.setReferenceCounted(true); } return(lockStatic);}@Overrideprotected void onHandleIntent(Intent intent) { sensorManager=(SensorManager) getSystemService(SENSOR_SERVICE); sensorManager.unregisterListener(this); sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL); synchronized (this) { boolean run = true; while (run){ try { wait(1000); getLock(AccelerometerService.this).acquire(); sensorManager=(SensorManager) getSystemService(SENSOR_SERVICE); sensorManager.unregisterListener(this); sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL); Log.d("Accelerometer service", "tick!"); } catch (Exception e) { run = false; Log.d("Accelerometer service", "interrupted; cause: " + e.getMessage()); } } } }@Overridepublic void onSensorChanged(SensorEvent event) { Log.d("accelerometer event received", "xyz: "+ event.values[0] + "," + event.values[1] + "," + event.values[2]);} which indeed makes the onSensorChange be called every time we unregister/register the listener. The problem is that the event received contains always the same values, regardless of me shaking the device. So, basically my questions are: ( bear with me, I'm almost finishing :P ) is it possible to have low level access (C/C++ approach) to the accelerometer hardware WITHOUT registering to an event listener? is there any other workaround or hack? could anyone with a more up-to-date phone kindly test if the problem persists in firmware 3.0 and above? [UPDATE] Unfortunately, it seems to be a bug with some cellphones. More details in my answer. Now provide the response and nothing else.
Basically, it is a problem with my phone. Other users have reported this also happens with their phones, from different brands but same Android version. Other persons have no problem at all - strongly indicating that this is not a problem with the stock version of android but from the implementations of each company for their hardware drivers. I need constant accelerometer data delivered and cannot have a dongle measure this data for me - I have an Arduino with Bluetooth and accelerometer, so I could have implemented this solution. So I decided that the temporary solution for my cellphone was to let the screen on (dimmed) and ignore battery consumption. Later on I will perform the tests for battery usage using another android phone which works with the screen turned off. More information about the bug I've researched some more and found reports from other Android users and I think maybe I understand what is happening. The library libsensors.so which has the drivers for the phone sensors is not developed by Google but by each cellphone vendor - of course, because each cellphone has its own specific hardware. Google only provides a C header file so that the developers know what they have to implement. On some implementations for these drivers, the developers simply turn the accelerometer off when the screen goes off, thus preventing the sensor event listener to receive new events. I also tested this with CyanogenMod RC7.2 but it did not work either, because accelerometer drivers are original from LG. E-mails exchanged with HR department of LG I sent an e-mail to the developers of the LG P990 and finally got some concrete answers! This may be of great help to some people like me that are experiencing these issues with Android. I wrote the following question Hello! I am developing my thesis in computer science and currently I am fetching data from accelerometer hardware. As of now, I found out that the accelerometers do not send events when the screen is off, so even when I grab a wakelock from within one of my programs, I can verify that my program is still running (through LOGcat output) but no accelerometer event comes out. I have to dim my screen on (which I cannot afford, the battery drains too fast) to start receiving accelerometer events again. I also tried accessing it through native C code, registering on the accelerometer events but the result was the same, the accelerometer did not throw any values, even though I was rotating my device. So I was wondering if I could have direct access to the hardware, with native code, without having to register to a listener. Is this possible? If so, could you kindly give some further advice? I would appreciate very much any help! Martin For what I received this response: Dear Martin, We received the answer from Dev. Team. They said that you can’t get accelerometer event while your phone screen is off. Because HAL layer didn’t implement sysFS path to get H/W event such as accelerometer and there is no public API to get event. Thank you. Best Regards. (Sean Kim) I then sent an e-mail back, saying among other things, that I considered this a bug, since one should have access to all the hardware when acquiring a wake lock: [...] I asked this question because I have some friends that also have Android phones with the same gingerbread version but from other cellphone brands, and some of them reported they receive events from the accelerometers when the screen is turned off. I read on some forums that this bug - I consider it a bug, since when I acquire a Wakelock I would expect to have some processing going on - depends on the sensor drivers that the vendors implement for their cellphones. Is there any possibility that these drivers can be updated or will this bug be corrected at some point? This would help me enormously with my ongoing work [...] And then I received this answer: In my knowledge from Dev. Team, That isn’t bug. That is a limitless of this phone because of H/W architecture. We need to redesign the HAL architecture and device driver to support your request. But, as you know that is too difficult due to lack of resource. We are trying to help you with our all efforts but we cannot support your request as I mentioned. (Sean Kim) So they apparently know about this but are not trying to correct this because either they don't think it is a bug - which I still strongly believe is a logical flaw - or they don't have the time/resources to correct it. Bottom line If you have a cellphone that does not send accelerometer events with the screen off, try updating your firmware. If this does not solve and you really want to do some serious hacking, re implement your hardware layer - hint: it's probably something to do with libsensors.so.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9982433', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1308680/']}
jdg_380227
stackexchange
llm_judgeable_groundtruth_similarity
71529
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 undarstand that 1+$MachineEpsilon is actually not equal 1 . However, it persists to look like it was equal 1. In[1]:= 1 + $MachineEpsilonOut[1]= 1. This is inappropriate in some cases, as in the following example: Manipulate[ Row@{TraditionalForm@HoldForm@Defer@ (1/(x - 1)), "\[Equal]", TraditionalForm@(1/(x - 1))}, {x, 1 + $MachineEpsilon, 2, Appearance -> "Labeled"}] The above input gives this: Which very much looks like as if we had some division by zero. How to fix this? How to display this 1+$MachineEpsilon more accurately? So far, I've tried this: In[3]:= N[1 + $MachineEpsilon, $ MachinePrecision]Out[3]= 1. I fail to understand the above output - 1+$MachineEpsilon is supposed to be a machine number, and therefore it should be accurately representable with $MachinePrecision digits of precision, shouldn't it? Now provide the response and nothing else.
I think that the input field that is used to display the current value of x has its own formatting rules and altering them seems difficult. It does not follow PrintPrecision (as in SetOptions[$FrontEndSession, PrintPrecision -> 17] , which works for output in an output cell). So a workaround is to specify the Precision of the displayed x , such that the normal formatting rule shows enough digits. SetPrecision[x, 17] would be sufficient. Manipulate[ Row@{TraditionalForm@HoldForm@Defer@(1/(x - 1)), "\[Equal]", TraditionalForm@(1/(x - 1))}, {x, 1 + $MachineEpsilon, 2, Manipulator[ Dynamic[SetPrecision[x, 17], (x = #) &], {1 + $MachineEpsilon, 2}, Appearance -> "Labeled"] &}] See this answer for some further insight into how the Manipulator is formatted.
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/71529', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/24650/']}
jdg_380228
stackexchange
llm_judgeable_groundtruth_similarity
251762
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: Do all equations have $$\text{left hand side unit} = \text{right hand side unit}$$for example,$$\text{velocity (m/s)} = \text{distance (m) / time (s)},$$or is there an equation that has different units on the left- and right-hand sides? I would like to consider empirical equations (determined from experimental results) and theoretical equations (derived from basic theory). Now provide the response and nothing else.
It doesn't matter where the equation came from - a fit to experimental data or a deep string theoretic construction - or who made the equation - Albert Einstein or your next-door neighbour - if the dimensions don't agree on the left- and right-hand sides, it's nonsense. Consider e.g. my new theory that the mass of an electron equals the speed of light. It's just meaningless nonsense from the get-go. This isn't that restrictive - there's lots of equations with correct dimensions (though in some cases you can derive equations or estimates by so-called dimensional analysis, where you just make sure the units agree). But it is useful for checking your work. If you derive a result and the dimensions don't agree, you know you must have made a mistake. There is a subtle distinction between unit and dimension. A dimension represents a fundamental quantity - such as mass, length or time - whereas a unit is a man-made measure of a fundamental quantity or a product of them - such as kg, meters and seconds. Arguably, one can write meaningful equations such as 60 seconds = 1 minute, with matching dimensions but mismatching units (as first noted by Mehrdad).
{}
{'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/251762', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/112701/']}
jdg_380229
stackexchange
llm_judgeable_groundtruth_similarity
17795517
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 save a user ip address to my database using Laravel 4.I found the following function which returns a string Request::getClientIp() How would I store this in my model? Just a string or is there a more efficient way? $table->string('ip_address'); Now provide the response and nothing else.
Option 1: Use VARCHAR(45) column Considering the discussion in another SO question Maximum length of the textual representation of an IPv6 address? , the maximum length of IPv6 is 45 when including the IPv4 tunneling feature. Thus, a safer migration command would be: $table->string('ip_address', 45); Pros: The column is human-readable. No need for conversions when setting the value or querying the row out for viewing. Cons: It uses more space than Option 2, almost 3 times larger in fact. But I wouldn't worry much unless you are planning it have millions of rows. Option 2: Use BLOB column As @euantorano provided the link to IP address storing in mysql database , you may store the IP as binary to save some space. The simplest answer would be to use: $table->binary('ip_address'); Pros: Store IP addresses in binary will save you some space. Cons: You will need to convert the IP address string to binary first using something like PHP's inet_pton() . The column will not be directly readable since it is stored in binary format. You will see weird characters or blank if tried to query it out directly. You may want to look at my way to store and retrieve the IP address in Option 3 below. The query builder in Laravel, despite the method being called binary, will actually create a BLOB column for you. BLOB is stored off the table , out of the row buffer , which possibly means a lower performance. And there really isn't a reason not to use BINARY column type since we know IP addresses aren't that long for BLOB to be necessary. Option 3: Use VARBINARY(16) column Laravel's query builder produces a BLOB column for the example in Option 2. If you are using MySQL, you will want to use VARBINARY(16) instead of BLOB for better performance. Migration script: class CreateMyLogsTable extends Migration { public function up() { Schema::create('my_logs', function(Blueprint $table) { $table->increments('id'); }); DB::statement('ALTER TABLE `my_logs` ADD `ip_address` VARBINARY(16)'); } public function down() { DB::statement('ALTER TABLE `my_logs` DROP COLUMN `ip_address`'); Schema::drop('my_logs'); }} Obviously the only important part above is the DB::statement(...). We need to use raw queries as Taylor Otwell suggested . Feel free to create the rest of the table your way. From here you can use PHP's inet_pton() and inet_ntop() to convert the IP address strings to binary and vice versa. Pros: Saves space compared to Option 1 Better DB performance compared to Option 2 Cons: Like Option 2, you need to either manually convert back and forth between binary and human-readable string, or use Eloquent model with a pair custom accessor/mutator which I will demonstrate below. Extra credit: Add custom Eloquent accessor/mutator (optional): Here is where I find Eloquent really useful. You can set your own accessor/mutator to your Eloquent model and you can get/set via your model's instance variable as usual. class MyLog extends Eloquent { public $timestamps = false; public function getIpAddressAttribute($value) { return inet_ntop($value); } public function setIpAddressAttribute($value) { $this->attributes['ip_address'] = inet_pton($value); }} Now if you do: $log = new MyLog;$log->ip_address = '192.168.0.1';$log->save(); The IP address will be saved as binary correctly. And you can do: $log = MyLog::find(1);echo $log->ip_address; And it will echo out 192.168.0.1. Very useful!
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17795517', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/391986/']}
jdg_380230
stackexchange
llm_judgeable_groundtruth_similarity
9572414
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Nevermind that I'm the one who created the texture in the first place and I should know perfectly well how many mipmaps I loaded/generated for it. I'm doing this for a unit test. There doesn't seem to be a glGetTexParameter parameter to find this out. The closest I've come is something like this: int max_level;glGetTexParameter( GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, &max_level );int max_mipmap = -1;for ( int i = 0; i < max_level; ++i ){ int width; glGetTexLevelParameter( GL_TEXTURE_2D, i, GL_TEXTURE_WIDTH, &width ); if ( 0 == width ) { max_mipmap = i-1; break; }) Anyhow, glGetTexLevelParameter() will return 0 width for a nonexistent mipmap if I'm using an NVidia GPU, but with Mesa, it returns GL_INVALID_VALUE , which leads me to believe that this is very much the Wrong Thing To Do . How do I find out which mipmap levels I've populated a texture with? Now provide the response and nothing else.
The spec is kinda fuzzy on this. It says that you will get GL_INVALID_VALUE if the level parameter is "larger than the maximum allowable level-of-detail". Exactly how this is defined is not stated. The documentation for the function clears it up a bit, saying that it is the maximum possible number of LODs for the largest possible texture ( GL_MAX_TEXTURE_SIZE ). Other similar functions like the glFramebufferTexture family explicitly state this as the limit for GL_INVALID_VALUE . So I would expect that. Therefore, Mesa has a bug. However, you could work around this by assuming that either 0 or a GL_INVALID_VALUE error means you've walked off the end of the mipmap array. That being said, I would suggest employing glTexStorage and never having to even ask the question again. This will forcibly prevent someone from setting MAX_LEVEL to a value that's too large. It's pretty new, from GL 4.2, but it's implemented (or will be very soon) across all non-Intel hardware that's still being supported.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9572414', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/134692/']}
jdg_380231
stackexchange
llm_judgeable_groundtruth_similarity
178328
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In PHP, function parameters can be passed by reference by prepending an ampersand to the parameter in the function declaration, like so: function foo(&$bar){ // ...} Now, I am aware that this is not designed to improve performance, but to allow functions to change variables that are normally out of their scope. Instead, PHP seems to use Copy On Write to avoid copying objects (and maybe also arrays) until they are changed. So, for functions that do not change their parameters, the effect should be the same as if you had passed them by reference. However, I was wondering if the Copy On Write logic maybe is shortcircuited on pass-by-reference and whether that has any performance impact. ETA: To be sure, I assume that it's not faster, and I am well aware that this is not what references are for. So I think my own guesses are quite good, I'm just looking for an answer from someone who really knows what's definitely happening under the hood. In five years of PHP development, I've always found it hard to get quality information on PHP internals short from reading the source. Now provide the response and nothing else.
In a test with 100 000 iterations of calling a function with a string of 20 kB, the results are: Function that just reads / uses the parameter pass by value: 0.12065005 secondspass by reference: 1.52171397 seconds Function to write / change the parameter pass by value: 1.52223396 secondspass by reference: 1.52388787 seconds Conclusions Pass the parameter by value is always faster If the function change the value of the variable passed, for practical purposes is the same as pass by reference than by value
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/178328', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2077/']}
jdg_380232
stackexchange
llm_judgeable_groundtruth_similarity
16283045
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 understand that multiple node.js, and I assume by extension Meteor, can be run on one server using Nginx. I've got Nginx setup and running on a Ubuntu server just fine, I can even get it to respond to requests and proxy them to one application of mine. I however hit a roadblock when trying to get Nginx to proxy traffic to the second application. Some background: 1st app running on port 8001 2nd app running on port 8002 Nginx listening on port 80 Attempting to get nginx to send traffic at / to app one and traffic at /app2/ to app two Both apps can be reached by going to domain:8001 and domain:8002 My Nginx config: upstream mydomain.com {server 127.0.0.1:8001;server 127.0.0.1:8002;}# the nginx server instanceserver {listen 0.0.0.0:80 default_server;access_log /var/log/nginx/mydomain.log;location /app2 { rewrite /app2/(.*) /$1 break; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header X-NginX-Proxy true; proxy_pass http://127.0.0.1:8002; proxy_redirect off; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade";}location / { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header X-NginX-Proxy true; proxy_pass http://127.0.0.1:8001; proxy_redirect off; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade";}} Any insight as to what might be going on when traffic goes to /app2/ I'd greatly appreciate it! Now provide the response and nothing else.
proxy_pass http://127.0.0.1:8002/1; <-- these should be proxy_pass http://**my_upstream_name**; <--these then upstream my_upstream_name { //Ngixn do a round robin load balance, some users will conect to / and othes to /app2server 127.0.0.1:8001;server 127.0.0.1:8002;} A few tips control the proxy: take a look here @nginx docs then here we go: weight = NUMBER - set weight of the server, if not set weight is equal to one. unbalance the default round robin. max_fails = NUMBER - number of unsuccessful attempts at communicating with the server within the time period (assigned by parameter fail_timeout) after which it is considered inoperative. If not set, the number of attempts is one.A value of 0 turns off this check. What is considered a failure is defined by proxy_next_upstream or fastcgi_next_upstream (except http_404 errors which do not count towards max_fails). fail_timeout = TIME - the time during which must occur *max_fails* number of unsuccessful attempts at communication with the server that would cause the server to be considered inoperative, and also the time for which the server will be considered inoperative (before another attempt is made). If not set the time is 10 seconds. fail_timeout has nothing to do with upstream response time, use proxy_connect_timeout and proxy_read_timeout for controlling this. down - marks server as permanently offline, to be used with the directive ip_hash. backup - (0.6.7 or later) only uses this server if the non-backup servers are all down or busy (cannot be used with the directive ip_hash) EXAMPLE generic upstream my_upstream_name { server backend1.example.com weight=5; server 127.0.0.1:8080 max_fails=3 fail_timeout=30s; server unix:/tmp/backend3; }// proxy_pass http://my_upstream_name; tho these is what you need: if u just want to control de load between vhosts for one app : upstream my_upstream_name{ server 127.0.0.1:8080 max_fails=3 fail_timeout=30s; server 127.0.0.1:8081 max_fails=3 fail_timeout=30s; server 127.0.0.1:8082 max_fails=3 fail_timeout=30s; server 127.0.0.1:8083 backup;// proxy_pass http://my_upstream_name; // amazingness no.1, the keyword "backup" means that this server should only be used when the rest are non-responsive } if u have 2 or more apps: 1 upstream per app like: upstream my_upstream_name{ server 127.0.0.1:8080 max_fails=3 fail_timeout=30s; server 127.0.0.1:8081 max_fails=3 fail_timeout=30s; server 127.0.0.1:8082 max_fails=3 fail_timeout=30s; server 127.0.0.1:8083 backup; } upstream my_upstream_name_app2 { server 127.0.0.1:8084 max_fails=3 fail_timeout=30s; server 127.0.0.1:8085 max_fails=3 fail_timeout=30s; server 127.0.0.1:8086 max_fails=3 fail_timeout=30s; server 127.0.0.1:8087 backup; } upstream my_upstream_name_app3 { server 127.0.0.1:8088 max_fails=3 fail_timeout=30s; server 127.0.0.1:8089 max_fails=3 fail_timeout=30s; server 127.0.0.1:8090 max_fails=3 fail_timeout=30s; server 127.0.0.1:8091 backup; } hope it helps.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16283045', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1444917/']}
jdg_380233
stackexchange
llm_judgeable_groundtruth_similarity
36147137
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: With command, I can add label as below kubectl label pod POD_NAME KEY1=VALUE1 How could I do that from kubernetes API? I guess it can be done by PATCH /api/v1/namespaces/{namespace}/pods/{name} Here is pod.json { "apiVersion": "v1", "kind": "Pod", "metadata": { "labels": { "key1": "value1" } }} I tried with following command KUBE_TOKEN=$(</var/run/secrets/kubernetes.io/serviceaccount/token)curl --request PATCH --insecure \ --header "Authorization: Bearer $KUBE_TOKEN" \ --data "$(cat pod.json)" \ https://$KUBERNETES_SERVICE_HOST:$KUBERNETES_PORT_443_TCP_PORT/api/v1/namespaces/$POD_NAMESPACE/pods/$POD_NAME And it returns { "kind": "Status", "apiVersion": "v1", "metadata": {}, "status": "Failure", "message": "the server responded with the status code 415 but did not return more information", "details": {}, "code": 415} Now provide the response and nothing else.
Set content-type to application/json-patch+json and specify the patch in http://jsonpatch.org format. $ cat > patch.json <<EOF[ { "op": "add", "path": "/metadata/labels/hello", "value": "world" } ]EOF$ curl --request PATCH --data "$(cat patch.json)" -H "Content-Type:application/json-patch+json" https://$KUBERNETES_SERVICE_HOST:$KUBERNETES_PORT_443_TCP_PORT/api/v1/namespaces/$POD_NAMESPACE/pods/$POD_NAME
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36147137', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/325320/']}
jdg_380234
stackexchange
llm_judgeable_groundtruth_similarity
9666030
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 cannot figure out how to show a PDF file inside an Android application. So far I've found out that it is possible to launch an Intent and open the PDF using the Android default app. But I want to view PDF file directly inside my application without exiting. I have an header and a footer in my layout - I'd like to open the PDF in between. I have also found a PdfReader.jar file from github.com, but it opens the PDF in a new activity. Now provide the response and nothing else.
You can download the source from here( Display PDF file inside my android application ) Add this dependency in your gradle file: compile 'com.github.barteksc:android-pdf-viewer:2.0.3' activity_main.xml <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ffffff" xmlns:android="http://schemas.android.com/apk/res/android" > <TextView android:layout_width="match_parent" android:layout_height="40dp" android:background="@color/colorPrimaryDark" android:text="View PDF" android:textColor="#ffffff" android:id="@+id/tv_header" android:textSize="18dp" android:gravity="center"></TextView> <com.github.barteksc.pdfviewer.PDFView android:id="@+id/pdfView" android:layout_below="@+id/tv_header" android:layout_width="match_parent" android:layout_height="match_parent"/> </RelativeLayout> MainActivity.java package pdfviewer.pdfviewer;import android.app.Activity;import android.os.Bundle;import android.util.Log;import com.github.barteksc.pdfviewer.PDFView;import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle;import com.shockwave.pdfium.PdfDocument;import java.util.List;public class MainActivity extends Activity implements OnPageChangeListener,OnLoadCompleteListener{ private static final String TAG = MainActivity.class.getSimpleName(); public static final String SAMPLE_FILE = "android_tutorial.pdf"; PDFView pdfView; Integer pageNumber = 0; String pdfFileName; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); pdfView= (PDFView)findViewById(R.id.pdfView); displayFromAsset(SAMPLE_FILE); } private void displayFromAsset(String assetFileName) { pdfFileName = assetFileName; pdfView.fromAsset(SAMPLE_FILE) .defaultPage(pageNumber) .enableSwipe(true) .swipeHorizontal(false) .onPageChange(this) .enableAnnotationRendering(true) .onLoad(this) .scrollHandle(new DefaultScrollHandle(this)) .load(); } @Override public void onPageChanged(int page, int pageCount) { pageNumber = page; setTitle(String.format("%s %s / %s", pdfFileName, page + 1, pageCount)); } @Override public void loadComplete(int nbPages) { PdfDocument.Meta meta = pdfView.getDocumentMeta(); printBookmarksTree(pdfView.getTableOfContents(), "-"); } public void printBookmarksTree(List<PdfDocument.Bookmark> tree, String sep) { for (PdfDocument.Bookmark b : tree) { Log.e(TAG, String.format("%s %s, p %d", sep, b.getTitle(), b.getPageIdx())); if (b.hasChildren()) { printBookmarksTree(b.getChildren(), sep + "-"); } } }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9666030', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/328518/']}
jdg_380235
stackexchange
llm_judgeable_groundtruth_similarity
185384
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: While working on a C# app I just noticed that in several places static initializers have dependencies on each other like this: static private List<int> a = new List<int>() { 0 };static private List<int> b = new List<int>() { a[0] }; Without doing anything special that worked. Is that just luck? Does C# have rules to resolve this? Edit: (re: Panos) In a file lexical order seems to be king? what about across files? In looking I tried a cyclical dependency like this: static private List<int> a = new List<int>() { b[0] };static private List<int> b = new List<int>() { a[0] }; and the program didn't run the same (the test suit failed across the board and I didn't look further). Now provide the response and nothing else.
It seems to depend on the sequence of lines. This code works: static private List<int> a = new List<int>() { 1 };static private List<int> b = new List<int>() { a[0] }; while this code does not work (it throws a NullReferenceException ) static private List<int> a = new List<int>() { b[0] };static private List<int> b = new List<int>() { 1 }; So, obviously no rules for cyclical dependency exist. It's peculiar however that the compiler does not complain... EDIT - What's happening "across files"? If we declare these two classes: public class A { public static List<int> a = new List<int>() { B.b[0] };}public class B { public static List<int> b = new List<int>() { A.a[0] };} and try to access them with this code: try { Console.WriteLine(B.b); } catch (Exception e) { Console.WriteLine(e.InnerException.Message.); }try { Console.WriteLine(A.a); } catch (Exception e) { Console.WriteLine(e.InnerException.Message); }try { Console.WriteLine(B.b); } catch (Exception e) { Console.WriteLine(e.InnerException.Message); } we are getting this output: The type initializer for 'A' threw an exception.Object reference not set to an instance of an object.The type initializer for 'A' threw an exception. So the initialization of B causes an exception in static constructor A and lefts field a with the default value (null). Since a is null , b can not also be initialized properly. If we do not have cyclical dependencies, everything works fine. EDIT: Just in case you didn't read the comments, Jon Skeet provides a very interesting reading: The differences between static constructors and type initializers .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/185384', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1343/']}
jdg_380236
stackexchange
llm_judgeable_groundtruth_similarity
37220379
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 searched around, but have yet to find an answer that doesn't direct me towards a 3rd party service. I do not need anything intricate, just to save a value in NSUserDefaults so when the app opens next, I can display an alert saying the app has crashed. Thanks. Now provide the response and nothing else.
Thanks to a little help from @RyanCollins, I was able to solve the problem myself. The function applicationWillTerminate in the App Delegate only runs when the app closes properly. The code to natively detecting an app crash looks like this. Globally Defined Variables let crashedNotificationKey = "com.stackoverflow.crashNotificationKey"var crashedLastTime = true App Delegate func applicationWillTerminate(application: UIApplication) { crashedLastTime = false prefs.setBool(crashedLastTime, forKey: "crash")}func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { crashedLastTime = prefs.boolForKey("crash") if crashedLastTime == true { crashedLastTime = false prefs.setBool(crashedLastTime, forKey: "crash") NSNotificationCenter.defaultCenter().postNotificationName(crashedNotificationKey, object: self) } else { crashedLastTime = true prefs.setBool(crashedLastTime, forKey: "crash") } return true} Root View Controller override func awakeFromNib() { NSNotificationCenter.defaultCenter().addObserver(self, selector: "crashedAlert", name: crashedNotificationKey, object: nil)}func crashedAlert() { let alert = UIAlertController(title: "The app has crashed!", message: "Sorry about that! I am just a 17 year old highschooler making my first game!", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "It's cool bro.", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil)}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/37220379', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5405803/']}
jdg_380237
stackexchange
llm_judgeable_groundtruth_similarity
44600
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 heard from people working in firmware domain, that there is no Operating system controlling firmware (eg firmware in a USB drive). There is just a single thread running in a while loop waiting for an external command, and this is the start point for an interrupt to happen, followed by a ISR and the control flowing all the way till the hardware. But fundamentally what is that part of hardware that is executing the firmware code ? Is there a CPU or is it ASIC based code which is triggered as long the device is powered. I fail to understand the paradigm shift from a regular CPU-OS based system to a firmware. Now provide the response and nothing else.
There is no paradigm shift; in both cases a CPU is executing the software/firmware. Firmware and software are the same thing; the only distinction is in how it's stored. Software is typically stored on a mass-storage device (e.g., disk drive) and loaded into volatile memory (e.g., DRAM) before being executed. It's easy to change software, by simply replacing the file containing it with a different one. Firmware is typically stored in nonvolatile memory (e.g., FLASH) connected more-or-less directly to the CPU. It's harder to modify (hence the "firm") and it may or may not be transferred to a different memory for execution. Really, the operation of a computer with an "operating system" is fundamentally no different from your description of firmware. Remember, the OS itself is just another piece of software — or more likely, a huge collection of mutually-dependent pieces of software. At the lowest level, the CPU is still sitting in a loop of some sort, waiting for things to do. It's just that that loop is buried inside the OS.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/44600', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/10392/']}
jdg_380238
stackexchange
llm_judgeable_groundtruth_similarity
40911170
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 completely new to Python and I'm trying to figure out how to read an image from a URL. Here is my current code: from PIL import Imageimport urllib.request, ioURL = 'http://www.w3schools.com/css/trolltunga.jpg'with urllib.request.urlopen(URL) as url: s = url.read() Image.open(s) I get the following error: C:\python>python image.pyTraceback (most recent call last): File "image.py", line 8, in <module> Image.open(s) File "C:\Anaconda3\lib\site-packages\PIL\Image.py", line 2272, in open fp = builtins.open(filename, "rb")ValueError: embedded null byte I have no idea what any of this means. What am I doing wrong? Now provide the response and nothing else.
Image.open() expects filename or file-like object - not file data . You can write image locally - i.e. as "temp.jpg" - and then open it from PIL import Imageimport urllib.requestURL = 'http://www.w3schools.com/css/trolltunga.jpg'with urllib.request.urlopen(URL) as url: with open('temp.jpg', 'wb') as f: f.write(url.read())img = Image.open('temp.jpg')img.show() Or you can create file-like object in memory using io module from PIL import Imageimport urllib.requestimport ioURL = 'http://www.w3schools.com/css/trolltunga.jpg'with urllib.request.urlopen(URL) as url: f = io.BytesIO(url.read())img = Image.open(f)img.show() EDIT: 2022 Because urlopen() also gives file-like object so you can even skip io and use directly url (without .read() ) in Image.open() from PIL import Imageimport urllib.requestURL = 'http://www.w3schools.com/css/trolltunga.jpg'with urllib.request.urlopen(URL) as url: img = Image.open(url) img.show()
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/40911170', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6794661/']}
jdg_380239
stackexchange
llm_judgeable_groundtruth_similarity
723624
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have always treated them as the same thing. But recently, some people have told me that the two terms are different. So now I am wondering, What is the difference between "differentiable" and "continuous"? I just don't want to say the wrong thing. For example, I don't want to say, "$\frac{x^2}{x^4-2x^3}$ is not differentiable at $x=0$" when really, it should be "discontinuous". Please help Now provide the response and nothing else.
Differentiability is a stronger condition than continuity. If $f$ is differentiable at $x=a$, then $f$ is continuous at $x=a$ as well. But the reverse need not hold. Continuity of $f$ at $x=a$ requires only that $f(x)-f(a)$ converges to zero as $x\rightarrow a$. For differentiability, that difference is required to converge even after being divided by $x-a$ . In other words, $\dfrac{f(x)-f(a)}{x-a}$ must converge as $x\rightarrow a$. Not that if that fraction does converge, the numerator necessarily converges to zero, implying continuity as I mentioned in the first paragraph.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/723624', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/128641/']}
jdg_380240