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
|
30608219
|
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 php page with input fields.I gonna put values in these input fields.What I need is to keep the values in the inputs fields when I go to other php page, where I need get this values.How can I do?
Now provide the response and nothing else.
|
Got the real solution now (not workaround), therefore opened new answer. The cause of the warning in Chrome debugger is due to the wrong timing of loading the link imports in the right sequence. Solution: 1.) Remove link imports in the iron-icons (and other icon-sets if needed, like maps, social, etc ...): public bower_components iron-icons iron-icons.html maps-icons.html (optional, if you are using them) social-icons.html (optional, if you are using them) iron-icons.html: before: <!--@group Iron Elements@element iron-icons@demo demo/index.html--><link rel='import' href='../iron-icon/iron-icon.html'><link rel='import' href='../iron-iconset-svg/iron-iconset-svg.html'><iron-iconset-svg name="icons" size="24"> <svg><defs> <g id="3d-rotation"><path d="M7.52 21.48C ..... etc ..... /></g> </defs></svg></iron-iconset-svg> after: <!--@group Iron Elements@element iron-icons@demo demo/index.html--><!--<link rel='import' href='../iron-icon/iron-icon.html'><link rel='import' href='../iron-iconset-svg/iron-iconset-svg.html'>--><iron-iconset-svg name="icons" size="24"> <svg><defs> <g id="3d-rotation"><path d="M7.52 21.48C ..... etc ..... /></g> </defs></svg></iron-iconset-svg> The initial link-imports (dependencies) are blocking (not loading async but sync, which is good because that's the way it should be).However, within the code of <link rel='import' href='../iron-icon/iron-icon.html'> iron-icon is making reference to the icon set that could not load yet ( <iron-iconset-svg name="icons" size="24"> etc ...) because it comes after that initial link-import (due to blocking nature of link import). Hence, at line 164 it cannot find the Default iconset icons , and therefore throwing the famous warning at line 167: could not find iconset icons, did you import the iconset? 2.) Load required dependencies in your project file in the correct sequence: <head> <meta charset="utf-8" /> <title></title> <script src="/bower_components/webcomponentsjs/webcomponents-lite.min.js"></script> <link rel="import" href="/bower_components/polymer/polymer.html"> <link rel="import" href="/bower_components/iron-meta/iron-meta.html"> <link rel="import" href="/bower_components/iron-flex-layout/iron-flex-layout.html"> <link rel="import" href="/bower_components/iron-iconset-svg/iron-iconset-svg.html"> <link rel="import" href="/bower_components/iron-iconset/iron-iconset.html"> <link rel="import" href="/bower_components/iron-icons/iron-icons.html"> <link rel="import" href="/bower_components/iron-icons/maps-icons.html"> <link rel="import" href="/bower_components/iron-icons/social-icons.html"> <link rel="import" href="/bower_components/iron-icon/iron-icon.html"></head> The <link rel="import" href="/bower_components/iron-icon/iron-icon.html"> is loaded in last position now, hence all dependencies are available at this point. Works like a charm for me now. @LuckyRay's :Please let us know whether this works for you, too.I will post this on your github comment for the Polymer Team as well.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30608219', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3353147/']}
|
jdg_373541
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
40605972
|
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 you select an object (in my example a polygon), it gets automatically moved to the Front. I'm searching for a way to prevent the movement on the z-axis or send it backwards after the selection, maybe someone can help? Here is a link to a simple example: http://jsfiddle.net/98cuf9b7/1/ When you select one of the Polygons, it gets moved to the Front. I tried to send it backwards after the selection, but even if the "canvas.sendToBack(object)" function is called, it's still remains in the Front. The code in my Example is: var canvas = new fabric.Canvas('c');var pol = new fabric.Polygon([ {x: 200, y: 0}, {x: 250, y: 50}, {x: 250, y: 100}, {x: 150, y: 100}, {x: 150, y: 50} ], { left: 250, top: 150, angle: 0, fill: 'green' });var pol2 = new fabric.Polygon([ {x: 200, y: 50}, {x: 200, y: 100}, {x: 100, y: 100}, {x: 100, y: 50} ], { left: 300, top: 200, angle: 0, fill: 'blue' });canvas.add(pol, pol2);canvas.on('object:selected', function(event) { var object = event.target; canvas.sendToBack(object); //object.sendToBack(); console.log("OK"); });
Now provide the response and nothing else.
|
Ok so this is happening because of the Fabric version you are using. In fiddle as i can see you have use version 0.9 . So it seems to be the default behaviour that whenever an object is selected its z-index is changed such that its on the top/front. Try using a later version. In other versions this issue is not there if an object is at the back it remains at the back even if you select it.Here is a the demo with a later version(1.4.0) . Here whenever you select the object it will be moved backwards. And if you comment out the sending backwards code it will remain in front if in front and at the back if at the back. var canvas = new fabric.Canvas('c');var pol = new fabric.Polygon([ {x: 200, y: 0}, {x: 250, y: 50}, {x: 250, y: 100}, {x: 150, y: 100}, {x: 150, y: 50} ], { left: 250, top: 150, angle: 0, fill: 'green' });var pol2 = new fabric.Polygon([ {x: 200, y: 50}, {x: 200, y: 100}, {x: 100, y: 100}, {x: 100, y: 50} ], { left: 300, top: 200, angle: 0, fill: 'blue' });canvas.add(pol, pol2);canvas.on('object:selected', function(event) { var object = event.target; canvas.sendToBack(object); //object.sendToBack(); console.log("Selected"); }); <script src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.4.0/fabric.min.js"></script><canvas id="c" width="500" height="500"></canvas>
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40605972', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6144965/']}
|
jdg_373542
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
51179516
|
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 just installed mysql on mac from Homebrew brew install mysqlmysql -Vmysql Ver 8.0.11 for osx10.13 on x86_64 (Homebrew) from terminal it works and I can login to mysql but from Sequel Pro it says Unable to connect to host 127.0.0.1, or the request timed out. Be sure that the address is correct and that you have the necessary privileges, or try increasing the connection timeout (currently 10 seconds). MySQL said: Authentication plugin 'caching_sha2_password' cannot be loaded: dlopen(/usr/local/lib/plugin/caching_sha2_password.so, 2): image not found can't figure out what I am missing
Now provide the response and nothing else.
|
This is because Sequel Pro is not ready yet for a new kind of user login, as the error states: there is no driver. mysql + homebrew Basically you will have to perform some actions manually, however- your database data won't be deleted like in solution below Go to my.cnf file and in section [mysqld] add line: default-authentication-plugin=mysql_native_password Login to mysql server from terminal: run mysql -u root -p , then inside shell execute this command (replacing [password] with your actual password): ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '[password]'; exit from mysql shell with exit and run brew services restart mysql . Should work. Quick fix (destructive method) Quick fix for non-homebrew installs: Apple Logo > System Preferences > MySQL > Initialize Database , then type your new password and select 'Use legacy password' After restart you should be able to connect. Do it only on fresh installs, because you may lost your db tables otherwise. my.cnf The my.cnf file is located in /etc/my.cnf on Unix/Linux Alternatives For those who is still struggling with Sequel Pro problems: Sequel Pro was a great product, but with tons of unresolved issues and last release being dated to 2016 perhaps it's a good idea to look for some alternatives. There is a fork of SequelPro called SequelAce that seems to be pretty stable and up-to-date, it keeps similar functionality, similar look and feel, yet at the same time it is devoid of old Sequel Pro problems
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/51179516', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6017905/']}
|
jdg_373543
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13412
|
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
We are currently converting student test scores in this manner : ( ScaledScore - ScaledScore Mean ) / StdDeviation ) * 15 + 100 I was referring to this calculation as a z-score, I found some information that convinced me that I should really be referring to it as a t-score as opposed to a z-score. My boss wants me to call it a "Standard Score" on our reports. Are z-scores and t-scores both considered standard scores? Is there a well known abbreviation for "Standard Score"? Can someone point me to a reference that will definitively solve this issue.
Now provide the response and nothing else.
|
What you are reporting is a standardized score. It just isn't the standardized score most statisticians are familiar with. Likewise, the t-score you are talking about, isn't what most of the people answering the question think it is. I only ran into these issues before because I volunteered in a psychometric testing lab while in undergrad. Thanks go to my supervisor at the time for drilling these things into my head. Transformations like this are usually an attempt to solve a "what normal person wants to look at all of those decimal points anyway" sort of problem. Z-scores are what most people in statistics call "Standard Scores". When a score is at the mean, they have a value of 0, and for each standard deviation difference from the mean adjusts the score by 1. The "standard score" you are using has a mean of 100 and a difference of a standard deviation adjusts the score by 15. This sort of transformation is most familiar for its use on some intelligence tests. You probably ran into a t-score in your reading. That is yet another specialized term that has no relation (that I am aware of) to a t-test. t-scores represent the mean as 50 and each standard deviation difference as a 10 point change. Google found an example conversion sheet here: http://faculty.pepperdine.edu/shimels/Courses/Files/ConvTable.pdf A couple mentions of t-scores here supports my assertion regarding them: http://www.healthpsych.com/bhi/doublenorm.html http://www.psychometric-success.com/aptitude-tests/percentiles-and-norming.htm Chapter 5, pp 89, Murphy, K. R., & Davidshofer, C. O. (2001). Psychological testing: principles and applications . Upper Saddle River, NJ: Prentice Hall. A mention of standardized scores along my interpretation is here: http://www.gifted.uconn.edu/siegle/research/Normal/Interpret%20Raw%20Scores.html http://www.nfer.ac.uk/nfer/research/assessment/eleven-plus/standardised-scores.cfm This is an intro psych book, so it probably isn't particular official either. Chapter 8, pp 307 in Wade, C., & Tarvis, C. (1996). Psychology . New York: Harper Collins state in regards to IQ testing "the average is set arbitrarily at 100, and tests are constructed so that the standard deviation ... is always 15 or 16, depending on the test". So, now to directly address your questions: Yes, zscores and tscores are both types of "Standard scores". However, please note that your boss is right in calling the transformation you are doing a "standard score". I don't know of any standard abbreviation for standardized scores. As you can see above, I looked for a canonical source, but I was unable to find one. I think the best place to look for a citation people would believe is in the manual of the standardized test you are using. Good luck.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/13412', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/5519/']}
|
jdg_373544
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2284511
|
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:
We know the closed form for $(1)$ $$\int_{0}^{\infty}{\ln(e^x-1)\over e^x+1}x\mathrm dx=\left({\pi\over 2}\right)^2\ln(2)-{\zeta(3)\over 2^3}\tag1$$ Proposed: How can we determine the closed form for $(2)?$ $$\int_{0}^{\infty}{\ln(e^x-1)\over e^x+1}\mathrm dx=I\tag2$$ My try: $y=e^x$ $$\int_{1}^{\infty}{\ln(y-1)\over y+1}\cdot{\mathrm dy\over y}\tag3$$
Now provide the response and nothing else.
|
On the path of Mark Viola, $\displaystyle I=\int_0^\infty \frac{\log(e^x-1)}{e^x+1}\,dx \tag 1$ Perform the change of variable $y=\text{e}^{-x}$, $\displaystyle I=\int_0^1 \frac{\log(1-x)-\log(x)}{1+x}\,dx\tag 2$ In $(1)$ perform the change of variable $y=\dfrac{1-\text{e}^{-x}}{1+\text{e}^{-x}}$, $\begin{align} I&=\int_0^1 \dfrac{\ln\left(\tfrac{2x}{1-x}\right)}{1+x}dx\\&=\int_0^1 \dfrac{\ln 2}{1+x}dx+\int_0^1 \dfrac{\ln x}{1+x}dx-\int_0^1 \dfrac{\ln(1-x)}{1+x}dx\\&=(\ln 2)^2+\int_0^1 \dfrac{\ln x}{1+x}dx-\int_0^1 \dfrac{\ln(1-x)}{1+x}dx\end{align}$ Using $(2)$, $I=(\ln 2)^2-I$ Therefore, $\boxed{I=\dfrac{(\ln 2)^2}{2}}$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2284511', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/343408/']}
|
jdg_373545
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
32966978
|
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 wanna read csv files in Zeppelin and would like to use databricks'spark-csv package: https://github.com/databricks/spark-csv In the spark-shell, I can use spark-csv with spark-shell --packages com.databricks:spark-csv_2.11:1.2.0 But how do I tell Zeppelin to use that package? Thanks in advance!
Now provide the response and nothing else.
|
You need to add the Spark Packages repository to Zeppelin before you can use %dep on spark packages. %depz.reset()z.addRepo("Spark Packages Repo").url("http://dl.bintray.com/spark-packages/maven")z.load("com.databricks:spark-csv_2.10:1.2.0") Alternatively, if this is something you want available in all your notebooks, you can add the --packages option to the spark-submit command setting in the interpreters config in Zeppelin, and then restart the interpreter. This should start a context with the package already loaded as per the spark-shell method.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32966978', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1684129/']}
|
jdg_373546
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
25386839
|
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 make a program in Java for a class I am in, but I need to be able to make 6 methods execute at once. I have no idea how to go about this, but here is a small bit of what I have: public static void main(String[] args) { method1(); method2(); method3(); method4(); method5(); method6();} This just plays the methods one at a time, and I need them all at once.
Now provide the response and nothing else.
|
Make use of multiple threads, although you should read up on concurrency if you're going to edit the same objects from multiple threads. public static void main(String[] args) { new Thread() { public void run() { method1(); } }.start(); new Thread() { public void run() { method2(); } }.start(); //etc //or, as kingdamian42 pointed out, if you use java8, use this new Thread(() -> method1()).start(); new Thread(() -> method2()).start();}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25386839', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3926009/']}
|
jdg_373547
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7877193
|
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 watin to test a web page. The vast majority of which works fine. But I have a function that is run using JQuery. When the option of a SelectList is changed. When I run the browser and I have a break point in the js code the following jquery selector is fired. $("#OwningRegion").change(function () { But I cannot cause this to happen with watin. I have tried the FireEvent("change"). I have tried FireEvent("onClick"). I have tried .Option[1].Click(). etc.
Now provide the response and nothing else.
|
Looks like it might be a problem with uglifier and Windows Script Host: https://github.com/rails/rails/issues/2847 Make sure you're using the last version of uglifier (1.0.4). If you're still having problems, I'd suggest trying a different compiler (e.g. Closure compiler) In Gemfile : gem 'closure-compiler' In config/environments/production.rb config.assets.js_compressor = :closure alternatively disable JS compression altogether: config.assets.compress = false
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7877193', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4692/']}
|
jdg_373548
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7835304
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
A few projects in my client's solution have a post-build event: xcopy the build output to a specific folder. This works fine when building locally. However, in TeamCity, I occasionally get xcopy [...] exited with code 2 If I use regular copy , it exits with code 1. I expect this has something to do with file locks, although the specific files being copied are not the same, so perhaps just locking on the shared destination directory. I use /y to not prompt on overwriting files. Why this fails in TeamCity but not locally?
Now provide the response and nothing else.
|
Even if you provide the /Y switch with xcopy, you'll still get an error when xcopy doesn't know if the thing you are copying is a file or a directory. This error will appear as "exited with code 2". When you run the same xcopy at a command prompt, you'll see that xcopy is asking for a response of file or directory. To resolve this issue with an automated build, you can echo in a pre-defined response with a pipe. To say the thing you are copying is a file, echo in F : echo F|xcopy /y ... To say the thing you are copying is a directory, echo in D : echo D|xcopy /y ... Sometimes the above can be resolved by simply using a copy command instead of xcopy: copy /y ... However, if there are non-existent directories leading up to the final file destination, then an "exited with code 1" will occur. Remember: use the /C switch and xcopy with caution.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/7835304', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/487544/']}
|
jdg_373549
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5389261
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Sometimes I get this kind of exception on not very busy SQL server: Transaction (Process ID 57) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.Line number: 1Error Number: 1205Procedure: Server name: P01Error Source: .Net SqlClient Data ProviderError State: 47 I'm not able to reproduce it. I tried to run several queries from different clients at the same time, but it didn't show up.What is the best way to handle this kind of issue when it happens inside procedure or inside trigger? I mean, how to rerun the transaction? How to do it when exception occurs inside procedure called from the trigger, which was called by the insert made by some procedure (that is: procedure01 -> insert -> trigger -> procedure02 !)
Now provide the response and nothing else.
|
I would suggest that you come at the problem from two perspectives. Trap or Catch Deadlock Errors so that you can re-run the transaction that is chosen as the Deadlock Victim by the SQL Server database engine. Find out what is causing your Deadlock Events. You can do this in one of two ways, either run a SQL Server Profiler Trace to catch and record the Deadlock Event or you can enable some SQL Server Trace Flags that will record the details of the Deadlock Event to the SQL Server Error Log. In the vast majority of cases, you can identify the cause of your Deadlock Events and remedy the situation through either a structural change in the database schema or a logical change to the code involved/responsible for the Deadlock Event. For further reading take a look at: How to track down Deadlocks Using SQL Server Profiler Minimizing Deadlocks Detecting and Ending Deadlocks I hope I've answered your question but do let me know if I can help you further in any way.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5389261', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/653763/']}
|
jdg_373550
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
41318003
|
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 is verified that [\u4e00-\u9fff] can match chinese characters in vim. :%g/[\u4e00-\u9fff]/d The command above can delete all the lines containing chinese characters. ls /tmp/testktop 1_001.png.bakfonts.dir.bakNewScreenshot from 2016-09-12 16:50:29.png.bak你好 Now i want to extract files whose name is chinese characters. ls /tmp/test |grep -P '[\x4e\x00-\x9f\xff]' The command can't get files whose name is chinese characters. How to fix it? ls /tmp/test | grep -v '[a-z]' can get it ,but it is what i want.
Now provide the response and nothing else.
|
To match just lines (filenames) that have Han (Chinese) characters, you can use [\p{Han}] : ls /tmp/test | grep -P '[\p{Han}]' \p{Han} is one Unicode-script category property usable in any PCRE-supporting engine : \p{Common} \p{Arabic} \p{Armenian} \p{Bengali} \p{Bopomofo}\p{Braille} \p{Buhid} \p{Canadian_Aboriginal} \p{Cherokee}\p{Cyrillic} \p{Devanagari} \p{Ethiopic} \p{Georgian} \p{Greek}\p{Gujarati} \p{Gurmukhi} \p{Han} \p{Hangul} \p{Hanunoo} \p{Hebrew}\p{Hiragana} \p{Inherited} \p{Kannada} \p{Katakana} \p{Khmer} \p{Lao}\p{Latin} \p{Limbu} \p{Malayalam} \p{Mongolian} \p{Myanmar} \p{Ogham}\p{Oriya} \p{Runic} \p{Sinhala} \p{Syriac} \p{Tagalog} \p{Tagbanwa}\p{TaiLe} \p{Tamil} \p{Telugu} \p{Thaana} \p{Thai} \p{Tibetan}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41318003', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1982032/']}
|
jdg_373551
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2863179
|
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'll state the Cantor's theorem proof as is it is in my study texts: Theorem (Cantor): Let $X$ be any set. Then $|X|<|\mathcal{P}(X)|$ Proof: Define map $\varphi:X\rightarrow\mathcal{P}(X)$ by $\varphi:x\mapsto\{x\}$. $\varphi$ is injective, thus $|X|\leq|\mathcal{P}(X)|$. Now suppose there is a bijection (surjection) $\psi:X\rightarrow\mathcal{P}(X)$. Denote the set $A=\{x\in X, x\notin \psi(x)\}$. By assumption, $\psi$ is surjection so we find some $a\in X$ such that $\psi(a)=A$. Then we have two cases, either $a\in A$, but the, by definition of $A$: $a\notin \psi(a)$ which is a contradiction. So $a\notin A$ but then $a\in \psi(a)=A$ which is a contradiction aswell thus such surjection cannot exist. So now, for my question. The definition of $A$ seems really weird to me. Because, in the first place. Assume $X=\{1,2\}$ then $\mathcal{P}(X)=\{\{1,2\},\{1\},\{2\},\emptyset\}$. In the proof $A$ is supposed to be the set of all members of $X$ (thus numbers) that are not in the range of $\psi$ but, the range of $\psi$ are sets, aren't they? Thus $A=\{1,2\}$ and the case is $\forall a\in X:a\in{A}$ thus the second case of the proof applies. Basically this leads me to the following idea: instead of constructing this set $A$, we can say that: Estabilish injection and thus $|X|\leq|\mathcal{P}(X)|$ by $\varphi:x\mapsto\{x\}$ thus $\forall{S}\in\varphi(x):|S|=1$, but for any set $X:$ $\emptyset\subset\mathcal{P}(X)$ but $|\emptyset|=0$ so $\emptyset\notin ran(\varphi)$ thus $\varphi$ is not surjective.
Now provide the response and nothing else.
|
In the proof $A$ is supposed to be the set of all members of $X$ (thus numbers) that are not in the range of $\psi$ No, this is not quite true. The construction is more subtle than that. For any $x \in X$, the value $\psi(x) \in \mathcal P(X)$ is some set -- a subset of $X$ to be precise. Note that this is not the range of $\psi$, it is the value of $\psi(x)$ for a single $x$. Then we have either $x \in \psi(x)$ or $x \notin \psi(x)$, and we add $x$ to the set $A$ if and only if $x \notin \psi(x)$.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2863179', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/504245/']}
|
jdg_373552
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1908515
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm new to threads. How can I get t.join to work, whereby the thread calling it waits until t is done executing? This code would just freeze the program, because the thread is waiting for itself to die, right? public static void main(String[] args) throws InterruptedException { Thread t0 = new Thready(); t0.start();}@Overridepublic void run() { for (String s : info) { try { join(); Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.printf("%s %s%n", getName(), s); } } What would I do if I wanted to have two threads, one of which prints out half the info array, then waits for the other to finish before doing the rest?
Now provide the response and nothing else.
|
Use something like this: public void executeMultiThread(int numThreads) throws Exception{ List threads = new ArrayList(); for (int i = 0; i < numThreads; i++) { Thread t = new Thread(new Runnable() { public void run() { // do your work } }); // System.out.println("STARTING: " + t); t.start(); threads.add(t); } for (int i = 0; i < threads.size(); i++) { // Big number to wait so this can be debugged // System.out.println("JOINING: " + threads.get(i)); ((Thread)threads.get(i)).join(1000000); }
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1908515', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/147601/']}
|
jdg_373553
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
957575
|
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 I am trying to do is to create User Defined Functions (UDFs) for Excel using VSTO’s C# “Excel 2007 Add-in”-project type (since I just want to generate some general UDFs). As I am only trying to learn the basics (at this stage anyhow) this is what my code looks like: using System;using System.Collections.Generic;using System.Text;using System.Xml.Linq;using Excel = Microsoft.Office.Interop.Excel;using Office = Microsoft.Office.Core;using Microsoft.Office.Tools.Excel;using Microsoft.Office.Tools.Excel.Extensions;using System.Runtime.InteropServices;namespace ExcelAddIn1{ public partial class ThisAddIn { private void ThisAddIn_Startup(object sender, System.EventArgs e) {} private void ThisAddIn_Shutdown(object sender, System.EventArgs e) {} //My UDF public static double HeronicCal(int a, int b, int c) { //first compute S = (a+b+c)/2 double S = (a + b + c) / 2; double area = Math.Sqrt(S * (S - a) * (S - b) * (S - c)); return area; } #region VSTO generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InternalStartup() { this.Startup += new System.EventHandler(ThisAddIn_Startup); this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown); } #endregion }} It compiles fine, and when I run it, Excel pops up with a fresh spreadsheet, and when I look at the “Add-Ins”-list (in Excel options) I can see my add-in on the list (which is set to “Load at Startup). But here comes my problem, when I try to call my UDF from with-in Excel, Excel can’t find the method! What I would imagine is wrong, is that I have to tag my method as an Excel UDF (using the square brackets – as for instance done when coding webservices -> “[WebService]”). But I haven’t been able to track down this tag (and since I am not sure at all if my hunch is correct), which is why I’ve decided to go to you fine people here at SO. So my question basically is – from where I am with my code is there any easy way to make my UDF accessible to Excel? If yes, how? I really would like to stay within the VSTO project-types (Add-In, Workbook, Template), since my overall goal for my current project is to establish whether or not C# UDF execution with VS2010/Excel2007 works at an acceptable speed. To test this I am working on Windows7RC and with the VS2010 beta1.
Now provide the response and nothing else.
|
VSTO has no support for creating Excel UDFs. Automation Add-Ins can be created in .Net, and seem to be the Microsoft approved way of doing it. You should have a look at ExcelDna - http://www.codeplex.com/exceldna . ExcelDna allows managed assemblies to expose user-defined functions (UDFs) and macros to Excel through the native .xll interface. The project is open-source and freely allows commercial use. And you'll find that the performance of your .Net-based UDF is similar to native .xll add-ins for Excel. Excel 2007 features like the large sheet, long Unicode strings and multi-threaded recalculation are supported. With ExcelDna your function as posted above will be exposed to Excel with no VSTO - you can put to code into an xml-based .dna file or compile it to a .dll. The .dna file exposing your UDF would look like this: <DnaLibrary Language="C#"> using System; using ExcelDna.Integration; public class MyFunctions { [ExcelFunction(Description="Calculate Stuff", Category="Cool Functions")] public static double HeronicCal(int a, int b, int c) { //first compute S = (a+b+c)/2 double S = (a + b + c) / 2; double area = Math.Sqrt(S * (S - a) * (S - b) * (S - c)); return area; } }</DnaLibrary> Update: These days, the easiest way to get started with Excel-DNA is to make a new Class Library project in Visual Studio, then add the 'ExcelDna.AddIn' package from NuGet. That makes a starter add-in - just paste your code and press F5 to run. Update2: Might want to check a full working example VSTO + ExcelDna .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/957575', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
|
jdg_373554
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
28362472
|
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 built-in, simple, input box in Cocoa which is designed for retrieving a string (like there is in good ol' Visual Basic that I remember)? I suppose I could design a tiny window to do that but would prefer to use a native equivalent (if such a thing exists; I can't find it if it does). Thanks.
Now provide the response and nothing else.
|
Thank you DarkDust for pointing me in the right direction. I would never have searched for "accessory views" in NSAlerts (I was lacking the right terms to trick Google or SO into giving me the goods!). I also forgot to mention that I'm using Swift, so I've knocked up a quick translation: func getString(title: String, question: String, defaultValue: String) -> String { let msg = NSAlert() msg.addButtonWithTitle("OK") // 1st button msg.addButtonWithTitle("Cancel") // 2nd button msg.messageText = title msg.informativeText = question let txt = NSTextField(frame: NSRect(x: 0, y: 0, width: 200, height: 24)) txt.stringValue = defaultValue msg.accessoryView = txt let response: NSModalResponse = msg.runModal() if (response == NSAlertFirstButtonReturn) { return txt.stringValue } else { return "" }}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28362472', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4036688/']}
|
jdg_373555
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4890915
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm new to .Net 4.0's Tasks and I wasn't able to find what I thought would be a Task based replacement or implementation of a Timer, e.g. a periodic Task. Is there such a thing? Update I came up with what I think is a solution to my needs which is to wrap the "Timer" functionality inside a Task with child Tasks all taking advantage of the CancellationToken and returns the Task to be able to participate in further Task steps. public static Task StartPeriodicTask(Action action, int intervalInMilliseconds, int delayInMilliseconds, CancellationToken cancelToken){ Action wrapperAction = () => { if (cancelToken.IsCancellationRequested) { return; } action(); }; Action mainAction = () => { TaskCreationOptions attachedToParent = TaskCreationOptions.AttachedToParent; if (cancelToken.IsCancellationRequested) { return; } if (delayInMilliseconds > 0) Thread.Sleep(delayInMilliseconds); while (true) { if (cancelToken.IsCancellationRequested) { break; } Task.Factory.StartNew(wrapperAction, cancelToken, attachedToParent, TaskScheduler.Current); if (cancelToken.IsCancellationRequested || intervalInMilliseconds == Timeout.Infinite) { break; } Thread.Sleep(intervalInMilliseconds); } }; return Task.Factory.StartNew(mainAction, cancelToken);}
Now provide the response and nothing else.
|
It depends on 4.5, but this works. public class PeriodicTask{ public static async Task Run(Action action, TimeSpan period, CancellationToken cancellationToken) { while(!cancellationToken.IsCancellationRequested) { await Task.Delay(period, cancellationToken); if (!cancellationToken.IsCancellationRequested) action(); } } public static Task Run(Action action, TimeSpan period) { return Run(action, period, CancellationToken.None); }} Obviously you could add a generic version that takes arguments as well. This is actually similar to other suggested approaches since under the hood Task.Delay is using a timer expiration as a task completion source.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/4890915', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/222434/']}
|
jdg_373556
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
41390753
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am working on the project which need to broadcast latitude and longitude on realtime I have something like below namespace App\Events;use App\Events\Event;use Illuminate\Queue\SerializesModels;use Illuminate\Contracts\Broadcasting\ShouldBroadcast;use Illuminate\Support\Facades\Redis;class TrackersBroadcast extends Event implements ShouldBroadcast{ public $lat, $lng,$imei,$date_time use SerializesModels; /** * Create a new event instance. * * @return void */ public function __construct( $lat, $lng, $imei, $date_time ) { $this->lat = $lat; $this->lng = $lng; $this->imei = $imei; $this->date_time = $date_time; } /** * Get the channels the event should be broadcast on. * * @return array */ public function broadcastOn() { return ['tracker-channel']; }} In some case I need to trigger real time email , so I decided to implement laravel message queue like below namespace App\Jobs;use App\Jobs\Job;use Illuminate\Queue\SerializesModels;use Illuminate\Queue\InteractsWithQueue;use Illuminate\Contracts\Queue\ShouldQueue;use Mail;class SendAlertEmail extends Job implements ShouldQueue{ use InteractsWithQueue, SerializesModels; public $data; /** * Create a new job instance. * * @return void */ public function __construct($data) { $this->data=$data; } /** * Execute the job. * * @return void */ public function handle() { // Mail::send('emails.test', ['testVar' => $this->data], function($message) { $message->from('no-reply@sample.com', 'Website Name'); $message->to('developer@gmail.com')->subject('A simple test'); }); }} whenever I run php artisan queue:listen database it will queue my broadcasting event too . I dont want to queue the broadcast event . How to do that?
Now provide the response and nothing else.
|
Because Laravel Event Broadcasting queued by default if you extend ShouldBroadcast interface. If you don't want Event Broadcasting queued, you should extend ShouldBroadcastNow interface. use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;class TrackersBroadcast implements ShouldBroadcastNow{......} So It means your Event Broadcasting will using sync queue driver.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/41390753', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1355249/']}
|
jdg_373557
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3208927
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I need to run various machine learning techniques on a big dataset (10-100 billions records)The problems are mostly around text mining/information extraction and include various kernel techniques but are not restricted to them (we use some bayesian methods, bootstrapping, gradient boosting, regression trees -- many different problems and ways to solve them) What would be the best implementation? I'm experienced in ML but do not have much experience how to do it for huge datasetsIs there any extendable and customizable Machine Learning libraries utilizing MapReduce infrastructure Strong preference to c++, but Java and python are okAmazon Azure or own datacenter (we can afford it)?
Now provide the response and nothing else.
|
Unless the classification state space you are attempting to learn is extremely large, I would expect that there is significant redundancy in a text-mining-focused dataset with 10-100 billion records or training samples. As a rough guess, I would doubt that one would need much more than a 1-2% random sample subset to learn reliable classifiers that would hold up well under cross-validation testing. A quick literature search came up with the following relevant papers. The Tsang paper claims O(n) time complexity for n training samples, and there is software related to it available as the LibCVM toolkit . The Wolfe paper describes a distributed EM approach based on MapReduce. Lastly, there was a Large-Scale Machine Learning workshop at the NIPS 2009 conference that looks to have had lots of interesting and relevant presentations. References Ivor W. Tsang, James T. Kwok, Pak-Ming Cheung (2005). " Core Vector Machines: Fast SVM Training on Very Large Data Sets ", Journal of Machine Learning Research, vol 6, pp 363–392. J Wolfe, A Haghighi, D Klein (2008). " Fully Distributed EM for Very Large Datasets ", Proceedings of the 25th International Conference on Machine Learning, pp 1184-1191. Olivier Camp, Joaquim B. L. Filipe, Slimane Hammoudi and Mario Piattini (2005). " Mining Very Large Datasets with Support Vector Machine Algorithms ", Enterprise Information Systems V, Springer Netherlands, pp 177-184.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3208927', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/387263/']}
|
jdg_373558
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6597904
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
We have a scrollable div that has CSS hieght:40px; . Inside it are multiple LI height:20px <div id="#scroller"><li title="I1">item1</li><li title="I2">item2</li><li title="I3">item3</li><li title="I4">item4</li><li title="I5">item5</li><li title="I6">item6</li><li title="I7">item7</li><li title="I8">item8</li><li title="I9">item9</li> </div> When the user scrolls I want to trigger a script that determines the first of the two elements which is visible. The div scroll is designed to snap to elements. So if you scroll down and item3 and item 4 are visible how do I fund out that item 3 is the top visible element. I tried $('#scroller li:visible') but this does not work as far as the div is concerned they are all visible just hidden behind their container. Any ideas, Marvellous
Now provide the response and nothing else.
|
Update Updated with a working example http://jsfiddle.net/U4qyp/32/ I think .position() should do the job. It gives you the position of the element relative to its parent element. After you called .position() you can access the element coordinates using the properties top and left . http://api.jquery.com/position/ The element whose top position plus its height is major than zero, is visible. Here is an example of what I mean. http://jsfiddle.net/U4qyp/10/
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6597904', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/478520/']}
|
jdg_373559
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8683848
|
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 display an UIPopoverController from the rect of a selected text in an UITextView , How can I get the selected text CGRect ? Thanks!
Now provide the response and nothing else.
|
I think [UITextInput selectedTextRange] and [UITextInput caretRectForPosition:] is what you are looking for. [UITextInput selectedTextRange] returns the selected range in character [UITextInput caretRectForPosition:] returns the CGRect of the character range in this input. UITextView conforms to UITextInput (since iOS 5), so you can use these methods for your UITextView instance. It is going to be something like this. UITextRange * selectionRange = [textView selectedTextRange];CGRect selectionStartRect = [textView caretRectForPosition:selectionRange.start];CGRect selectionEndRect = [textView caretRectForPosition:selectionRange.end];CGPoint selectionCenterPoint = (CGPoint){(selectionStartRect.origin.x + selectionEndRect.origin.x)/2,(selectionStartRect.origin.y + selectionStartRect.size.height / 2)}; EDIT : Since the sample code became a little hard to get, I added an image for complementing.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8683848', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
|
jdg_373560
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
21911
|
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a client who wants a web app that will let him do the following (as he told me word for word): User registration Recurring payments for users Online conference room reservation I am supposed to give him a cost estimate very fast and I don't have any time to do any deeper requirements analysis! How would you deal with that kind of situation? Should I just give a very broad estimate and work out the exact requirements once he has accepted the estimate? At which point do you usually gather requirements, after or before getting a contract?
Now provide the response and nothing else.
|
Here is what I usually do to limit problems: Define the information yourself , by describing what you are going to do in details. Bid on that, and only that. Refer to that document in your official purchase order form you will ask your customer to sign . As an altenative, I suggest you to sell your customer with iterations instead of fixed features, with the flexibility to stop or continue development at the end of each iteration. If you don't know how to estimate your own document, try to do some collective estimation using planning poker . You can also split each functionnality into tasks and estimate each. Sum and multiplicate the result by two if you are pretty confident, or three if you are not sure. If you not confortable with your estimations, it's a pretty good indication that you are not experienced enough to accept the job in a fixed price scheme.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/21911', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/2100/']}
|
jdg_373561
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8645430
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How do I get all types that implementing a specific open generic type? For instance: public interface IUserRepository : IRepository<User> Find all types that implement IRepository<> . public static IEnumerable<Type> GetAllTypesImplementingOpenGenericType(Type openGenericType, Assembly assembly){ ...}
Now provide the response and nothing else.
|
This will return all types that inherit a generic base class. Not all types that inherit a generic interface. var AllTypesOfIRepository = from x in Assembly.GetAssembly(typeof(AnyTypeInTargetAssembly)).GetTypes() let y = x.BaseType where !x.IsAbstract && !x.IsInterface && y != null && y.IsGenericType && y.GetGenericTypeDefinition() == typeof(IRepository<>) select x; This will return all types, including interfaces, abstracts, and concrete types that have the open generic type in its inheritance chain. public static IEnumerable<Type> GetAllTypesImplementingOpenGenericType(Type openGenericType, Assembly assembly){ return from x in assembly.GetTypes() from z in x.GetInterfaces() let y = x.BaseType where (y != null && y.IsGenericType && openGenericType.IsAssignableFrom(y.GetGenericTypeDefinition())) || (z.IsGenericType && openGenericType.IsAssignableFrom(z.GetGenericTypeDefinition())) select x;} This second method will find ConcreteUserRepo and IUserRepository in this example: public class ConcreteUserRepo : IUserRepository{}public interface IUserRepository : IRepository<User>{}public interface IRepository<User>{}public class User{}
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/8645430', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/175399/']}
|
jdg_373562
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9807952
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a table with data from an SQL database and the table exists of a few rows and columns. The user has to provide credentials first before the table with the data is shown so i create the table (and its contents) dynamically. On each row in the table i add a cell with a "remove"-button in it: // more code to create the table above Button remove = new Button(); remove.Text = "Remove"; remove.Click += new EventHandler(remove_Click); TableCell last = new TableCell(); last.Controls.Add(remove); row.Cells.Add(last); //... When the user clicks the button i want the corresponding record in the database to be removed and the table updated after the postback. The code for this is written in remove_Click but the event is never fired, just because the remove button doesn't exist anymore after the postback and thus the event of the button can't be fired.As explained here: Dynamically Added Event Handler Not Firing The code works fine if i don't remove the button, but how would i go about firing the event and still wanting to remove the button ?
Now provide the response and nothing else.
|
Here is a solution. I am following all the excellent comments so far, and hopefully adding value by showing you how to handle any number of files. I am assuming you have all your csv files in the same directory ( my.csv.dir below). # locate the filesfiles <- list.files(my.csv.dir)# read the files into a list of data.framesdata.list <- lapply(files, read.csv)# concatenate into one big data.framedata.cat <- do.call(rbind, data.list)# aggregatedata.agg <- aggregate(value ~ index, data.cat, mean) Edit: to handle your updated question in your comment below: files <- list.files(my.csv.dir)algo.name <- sub("-.*", "", files)data.list <- lapply(files, read.csv)data.list <- Map(transform, data.list, algorithm = algo.name)data.cat <- do.call(rbind, data.list)data.agg <- aggregate(value ~ algorithm + index, data.cat, mean)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9807952', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/538047/']}
|
jdg_373563
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4167077
|
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 common pattern in Java to avoid mongoDB injection attacks? Thanks
Now provide the response and nothing else.
|
Use one of the supported drivers. Don't deserialize strings as JSON and pass them as queries, e.g. dont' do this (in Ruby): collection.send(query_type, JSON.parse(parameters)) where query_type and parameters are strings coming from a form. You would have to be criminally stupid to do this though. Since there's no query language as such there's not the same room for injection. Part of the reason that SQL injection attacks are possible is that the action to take ( SELECT , UPDATE , DELETE , etc.) is part of the query string. MongoDB, and many other newer databases, don't work like that, instead the action is a part of the API. Where SQL drivers only have query and in some cases exec , MongoDB has find , update , insert and remove .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4167077', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/298406/']}
|
jdg_373564
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
10897090
|
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 test my small application, that I keep in a separate package. Right now I created a "test_project" directory, created a test project there and I am using the project's manage.py to run tests. But I keep wondering - is there a better method? Is it possible to launch a single app's tests, perhaps with some default configuration (like, sqlite database)?
Now provide the response and nothing else.
|
It is possible to run a single app's tests standalone, without creating a Django test project for that purpose. One way of doing so is by creating a runtests.py in your app's root dir which setups Django settings and runs ./manage.py test your_app programmatically. One example of runtests.py is Django's own: runtests.py ( documentation ). Django's own runtests.py is a good reference but I find it convoluted for most cases. Below are a couple of alternative examples: Django-Modeltranslation My own minimalistic one
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10897090', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/401516/']}
|
jdg_373565
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1979583
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm having fun with Google Chrome extension, and I just want to know how can I store the URL of the current tab in a variable?
Now provide the response and nothing else.
|
Use chrome.tabs.query() like this: chrome.tabs.query({active: true, lastFocusedWindow: true}, tabs => { let url = tabs[0].url; // use `url` here inside the callback because it's asynchronous!}); This requires that you request access to the chrome.tabs API in your extension manifest : "permissions": [ ... "tabs"] It's important to note that the definition of your "current tab" may differ depending on your extension's needs. Setting lastFocusedWindow: true in the query is appropriate when you want to access the current tab in the user's focused window (typically the topmost window). Setting currentWindow: true allows you to get the current tab in the window where your extension's code is currently executing. For example, this might be useful if your extension creates a new window / popup (changing focus), but still wants to access tab information from the window where the extension was run. I chose to use lastFocusedWindow: true in this example, because Google calls out cases in which currentWindow may not always be present . You are free to further refine your tab query using any of the properties defined here: chrome.tabs.query
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/1979583', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/195999/']}
|
jdg_373566
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8184040
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Why is the following bit of code returns Height: -1 which means that the height is yet not known. How to get height of the image? try { // Create a URL for the image's location URL url = new URL("http://bmw-2006.auto-one.co.uk/wp-content/uploads/bmw-m3-2006-3.jpg"); // Get the image java.awt.Image image = Toolkit.getDefaultToolkit().createImage(url); System.out.println("Height: " + image.getHeight(null)); } catch (MalformedURLException e) { } catch (IOException e) { }
Now provide the response and nothing else.
|
Use ImageIO.read(URL) or ImageIO.read(File) instead. It will block while loading, and the image width & height will be known after it returns. E.G. import java.awt.image.BufferedImage;import javax.swing.*;import javax.imageio.ImageIO;import java.net.URL;class SizeOfImage { public static void main(String[] args) throws Exception { URL url = new URL("https://i.stack.imgur.com/7bI1Y.jpg"); final BufferedImage bi = ImageIO.read(url); final String size = bi.getWidth() + "x" + bi.getHeight(); SwingUtilities.invokeLater(new Runnable() { public void run() { JLabel l = new JLabel( size, new ImageIcon(bi), SwingConstants.RIGHT ); JOptionPane.showMessageDialog(null, l); } }); }} Alternately, add a MediaTracker to the image being loaded asynchronously by the Toolkit and wait until it is completely loaded.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8184040', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/647177/']}
|
jdg_373567
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
21749950
|
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 UIScrollView subclass. Its content is reusable - about 4 or 5 views are used to display hundreds of elements (while scrolling hidden objects reused and jumps to another position when its needed to see them) What i need: ability to automatically scroll my scroll view to any position. For example my scroll view displays 4th, 5th and 6th element and when I tap some button it needs to scroll to 30th element. In other words I need standard behaviour of UIScrollView. This works fine: [self setContentOffset:CGPointMake(index*elementWidth, 0) animated:YES]; but I need some customisation. For example, change animation duration, add some code to perform on end of animation. Obvious decision: [UIView animateWithDuration:3 delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{ [self setContentOffset:CGPointMake(index*elementWidth, 0)];} completion:^(BOOL finished) { //some code}]; but I have some actions connected to scroll event, and so now all of them are in animation block and it causes all subview's frames to animate too (thanks to few reusable elements all of them animates not how i want) The question is: How can I make custom animation (in fact I need custom duration, actions on end and BeginFromCurrentState option) for content offset WITHOUT animating all the code, connected to scrollViewDidScroll event? UPD: Thanks to Andrew's answer (first part) I solved issue with animation inside scrollViewDidScroll : - (void)scrollViewDidScroll:(UIScrollView *)scrollView{ [UIView performWithoutAnimation:^{ [self refreshTiles]; }];} But scrollViewDidScroll must (for my purposes) executes every frame of animation like it was in case of [self setContentOffset:CGPointMake(index*elementWidth, 0) animated:YES]; However, now it executes only once at start of animation. How can I solve this?
Now provide the response and nothing else.
|
Did you try the same approach, but with disabled animation in scrollViewDidScroll ? On iOS 7, you could try wrapping your code in scrollViewDidScroll in [UIView performWithoutAnimation:^{ //Your code here }]; on previous iOS versions, you could try: [CATransaction begin]; [CATransaction setDisableActions:YES]; //Your code here [CATransaction commit]; Update: Unfortunately that's where you hit the tough part of the whole thing. setContentOffset: calls the delegate just once, it's equivalent to setContentOffset:animated:NO , which again calls it just once. setContentOffset:animated:YES calls the delegate as the animation changes the bounds of the scrollview and you want that, but you don't want the provided animation, so the only way around this that I can come up with is to gradually change the contentOffset of the scrollview, so that the animation system doesn't just jump to the final value, as is the case at the moment. To do that you can look at keyframe animations, like so for iOS 7: [UIView animateKeyframesWithDuration:duration delay:delay options:options animations:^{ [UIView addKeyframeWithRelativeStartTime:0.0 relativeDuration:0.5 animations:^{ [self setContentOffset:CGPointMake(floorf(index/2) * elementWidth, 0)]; }]; [UIView addKeyframeWithRelativeStartTime:0.5 relativeDuration:0.5 animations:^{ [self setContentOffset:CGPointMake(index*elementWidth, 0)]; }];} completion:^(BOOL finished) { //Completion Block}]; This will get you two updates and of course you could use some math and a loop to add up a lot more of these with the appropriate timings. On previous iOS versions, you'll have to drop to CoreAnimation for keyframe animations, but it's basically the same thing with a bit different syntax. Method 2:You can try polling the presentationLayer of the scrollview for any changes with a timer that you start at the beginning of the animation, since unfortunately the presentationLayer's properties aren't KVO observable. Or you can use needsDisplayForKey in a subclass of the layer to get notified when the bounds change, but that'll require some work to set up and it does cause redrawing, which might affect performance. Method 3:Would be to dissect exactly what happens to the scrollView when animated is YES try and intercept the animation that gets set on the scrollview and change its parameters, but since this would be the most hacky, breakable due to Apple's changes and trickiest method, I won't go into it.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21749950', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/998667/']}
|
jdg_373568
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
519771
|
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 to read data from Bar Code Scanner in .net windows application? Can some one give the sequence of steps to be followed? I am very new to that.
Now provide the response and nothing else.
|
Look at the scanner jack. If it looks like this: , then it's a keyboard wedge scanner. It acts like a keyboard: just types your barcode into an edit field. If it looks like this: , it's a serial port scanner. You need to create an instance of System.IO.Ports.SerialPort and use it to communicate with the scanner. If it looks like this: (source: datapro.net ) , it's a USB scanner. From programmer's point of view, it can be either a keyboard wedge or a serial port scanner. You need to look at the manual, find out which is it and use one of the approaches above. P.S. It will be easier if you post your scanner's model here, really.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/519771', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/53262/']}
|
jdg_373569
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
311062
|
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:
Looking on Digikey there are ~1300 results for 5.1V Zener diodes compared to 6 for 5V ones. Is there any physics-related reason for this or is it something else?
Now provide the response and nothing else.
|
Zener diode voltages largely follow the E24 resistor value intervals, a range of a intervals specified with +/-5 % accuracy. Zener diodes have not particularly developed as a technology, with accurate voltage references using bandgap techniques instead. The intervals have stayed the same for many years. As an aside, Zener diodes are less commonplace in circuits than may be expected to electronics newcomers, who can sometimes regard them as appealing 'magic voltage drops'. Their combination of basic inaccuracy, notable variance with temperature and current and a fairly large working current for stability lessens their usefulness compared to other design approaches and components.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/311062', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/152147/']}
|
jdg_373570
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1303528
|
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 in the very beginnings of teaching myself php.I am giving myself micro projects to push myself. Thus far I have a MYSQL database, created through a php form. One Column is for karma.I have the values of the database table display in an html table, and at the end of each row, I would like a click on a hyperlink, lets say a plus sign, to increase that row's karma level by 1. Then the plus sign would go away. I should that each row has an auto increment integer as a primary key.
Now provide the response and nothing else.
|
For this example, let's assume you're voting on so-answers. This will require at least three tables: Users , Answers , Votes The votes table will hold all the history: voteid | userid | answerid | value---------------------------------- 1 | 12 | 383 | 1 2 | 28 | 383 | -1 (negative number would require signed values) In this example, we see that two votes have been recorded. Users 12 and 28 both voted on Answer 383. User 12 loved it, and added 1 to its support. User 28 didn't like it, and subtracted 1 from its support. Anytime a user votes, you should first check to see if that user has already voted on that particular question. If they have, you can reject any further attempts to vote, or overwrite their old vote with a new one. SELECT * FROM votes WHERE (userid = 12) AND (answerid = 383) That's a very simple example query that will tell you if the user has already voted or not. If it returns records, you know they've voted. You can respond with a very nice "Sorry, you've already voted." message, or you can overwrite it: UPDATE votes SET value = $votevalue WHERE (userid = 12) AND (answerid = 383) Having said that, let's look at how SO accomplishes this: When you click the up-vote arrow, SO fires a request off to a url like the following: http://stackoverflow.com/posts/1303528/vote/2 In this URL, we can see the vote is being cast on post #1303528. And the vote-type is represented by 2. This 2 likely represents "add one." You could use a more basic url, and go with something like: vote.php?answerid=383&vote=1 The vote.php page would have code similar to the following: (warning: do not use this code as-is. It is meant to be an example, not a solution) if ($_GET) { $userid = $_SESSION["userid"]; // assumes the user is logged in via SESSIONS $answerid = $_GET["answerid"]; $votetype = $_GET["vote"]; $query = "SELECT * FROM votes WHERE (userid = {$userid}) AND (answerid = {$answerid})"; $result = mysql_query($query) or die(mysql_error()); if (mysql_num_rows($result) > 0) { # User has voted print "Sorry, you are only allowed one vote."; } else { # User has not voted, cast the vote $query = "INSERT INTO votes (userid, answerid, votevalue) VALUES({$userid},{$answerid},{$vote})"; $result = mysql_query($query) or die(mysql_error()); if (mysql_affected_rows($result) > 0) { print "Your vote has been recorded."; } }}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1303528', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/136929/']}
|
jdg_373571
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
52625979
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm working on a web project using Babel 7 with Webpack 4. I've never used Babel before and can't really understand some parts of it. Based on the documentation I'm using @babel/preset-env because it seems the recommended way (especially for beginners). Also using Browserslist integration via my .browserslistrc file. Webpack does the compilation well ( babel-loader version 8.0.2 ), I have no errors but I'm confused about this useBuiltIns: "entry" option mentioned here and how polyfill system is working in Babel. .babelrc.js module.exports = { presets: [ ['@babel/preset-env', { "useBuiltIns": "entry" // do I need this? }] ], plugins: [ '@babel/plugin-syntax-dynamic-import' ]}; .browserslistrc Copied from here (thought reasonable because my project is using Bootstrap). >= 1%last 1 major versionnot deadChrome >= 45Firefox >= 38Edge >= 12Explorer >= 10iOS >= 9Safari >= 9Android >= 4.4Opera >= 30 So my questions are: 1) Do I need to use that useBuiltIns: "entry" option? 2) Do I need to install @babel/polyfill package and start my vendors.js with require("@babel/polyfill"); ? 3) What if I omit both? If I do 1 and 2, my vendors.js grows up to 411 KB If I ommit both it's just 341 KB after a production build. I thought @babel/preset-env handles all the rewrites and polyfills by default without any extra import/require needed on my side... Thanks! -- EDIT -- Babel's team has just updated the docs of @babel/polyfill based on some GitHub issues (including mine) complaining about unclear/misleading documentation. Now it's obvious how to use it. (...and after that my original question seems stupid :)
Now provide the response and nothing else.
|
1) Do I need to use that useBuiltIns: "entry" option? Yes, if you want to include polyfills based on your target environment. TL;DR There're basically 3 options for useBuiltIns : "entry" : when using this option, @babel/preset-env replaces direct imports of core-js to imports of only the specific modules required for a target environment. That means you need to add import "core-js/stable";import "regenerator-runtime/runtime"; to your entry point and these lines will be replaced by only required polyfills. When targeting chrome 72, it will be transformed by @babel/preset-env to import "core-js/modules/es.array.unscopables.flat";import "core-js/modules/es.array.unscopables.flat-map";import "core-js/modules/es.object.from-entries";import "core-js/modules/web.immediate"; "usage" : in this case polyfills will be added automatically when the usage of some feature is unsupported in target environment. So: const set = new Set([1, 2, 3]);[1, 2, 3].includes(2); in browsers like ie11 will be replaced with import "core-js/modules/es.array.includes";import "core-js/modules/es.array.iterator";import "core-js/modules/es.object.to-string";import "core-js/modules/es.set";const set = new Set([1, 2, 3]);[1, 2, 3].includes(2); In case target browser is latest chrome, no transformations will apply. That's personally my chosen weapon as there's no need to include anything (core-js or regenerator) in source code as only required polyfills will be added automatically based on target environment set in browserlist. false : that's the default value when no polyfills are added automatically. 2) Do I need to install @babel/polyfill package and start my vendors.js with require("@babel/polyfill"); ? Yes for environment prior to babel v7.4 and core-js v3 . TL;DR No. Starting from babel v7.4 and core-js v3 (which is used for polyfilling under the hood) @babel/preset-env will add the polyfills only when it know which of them required and in the recommended order. Moreover @babel/polyfill is considered as deprecated in favor of separate core-js and regenerator-runtime inclusions. So using of useBuiltIns with options other than false should solve the issue. Don't forget to add core-js as a dependency to your project and set its version in @babel/preset-env under corejs property. 3) What if I omit both? As @PlayMa256 already answered, there will be no polyfills. More detailed and whole info con be found at core-js creator's page Also please feel free to play with babel sandbox
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/52625979', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5263363/']}
|
jdg_373572
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
299515
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In C# is there a technique using reflection to determine if a method has been added to a class as an extension method? Given an extension method such as the one shown below is it possible to determine that Reverse() has been added to the string class? public static class StringExtensions{ public static string Reverse(this string value) { char[] cArray = value.ToCharArray(); Array.Reverse(cArray); return new string(cArray); }} We're looking for a mechanism to determine in unit testing that the extension method was appropriately added by the developer. One reason to attempt this is that it is possible that a similar method would be added to the actual class by the developer and, if it was, the compiler will pick that method up.
Now provide the response and nothing else.
|
You have to look in all the assemblies where the extension method may be defined. Look for classes decorated with ExtensionAttribute , and then methods within that class which are also decorated with ExtensionAttribute . Then check the type of the first parameter to see if it matches the type you're interested in. Here's some complete code. It could be more rigorous (it's not checking that the type isn't nested, or that there is at least one parameter) but it should give you a helping hand. using System;using System.Runtime.CompilerServices;using System.Reflection;using System.Linq;using System.Collections.Generic;public static class FirstExtensions{ public static void Foo(this string x) {} public static void Bar(string x) {} // Not an ext. method public static void Baz(this int x) {} // Not on string}public static class SecondExtensions{ public static void Quux(this string x) {}}public class Test{ static void Main() { Assembly thisAssembly = typeof(Test).Assembly; foreach (MethodInfo method in GetExtensionMethods(thisAssembly, typeof(string))) { Console.WriteLine(method); } } static IEnumerable<MethodInfo> GetExtensionMethods(Assembly assembly, Type extendedType) { var query = from type in assembly.GetTypes() where type.IsSealed && !type.IsGenericType && !type.IsNested from method in type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) where method.IsDefined(typeof(ExtensionAttribute), false) where method.GetParameters()[0].ParameterType == extendedType select method; return query; }}
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/299515', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/27887/']}
|
jdg_373573
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
41194545
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I know web browsers have a limit on the amount of simultanous http requests etc. But is there also a limit on the amount of open RTCPeerConnection's a web page can have? And somewhat related: RTCPeerConnection allows to send multiple streams over 1 connection. What would be the trade-offs between combining multiple streams in 1 connection or setting up multiple connections (e.g. 1 for each stream)?
Now provide the response and nothing else.
|
Not sure about the limit, but I think it is around 256 (last time I heard). I saw someone do 200 connections on a single web page recently (via http://testrtc.com ). Multiple RTCPeerConnection objects are great: They are easy to add and remove, so offer a higher degree of flexibility when joining or leaving a group call They can be connected to different destinations That said, they have their own challenges and overheads: Each RTCPeerConnection carries its own NAT configuration - so STUN and TURN bindings and traffic takes place in parallel across RTCPeerConnection objects even if they get connected to the same entity (an SFU for example). This overhead is one of local resources like memory and CPU as well as network traffic (not huge overhead, but it is there to deal with) They clutter your webrtc-internals view on Chrome with multiple tabs (a matter of taste), and SSRC might have the same values between them, making them a bit harder to trace and debug (again, a matter of taste) A single RTCPeerConnection object suffers from having to renegotiate it all whenever someone needs to be added to the list (or removed).
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41194545', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1048733/']}
|
jdg_373574
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8805316
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've seen the 600 calls / 600 seconds rate limit mentioned by some (e.g. on quora ). What I want to know is whether I am allowed to do 600 batch requests in 600 secs (a batch request consists of up to 50 requests).
Now provide the response and nothing else.
|
You should handle the rate limiting programmatically by checking for the following error message. You should then put in a time-wait loop before your next call if you encounter the error. One of my high traffic applications accounts watches for this error and will slow down. From: https://developers.facebook.com/docs/bestpractices/ Rate limited (API_EC_TOO_MANY_CALLS) If your application is making too many calls, the API server might rate limit you automatically, returning an "API_EC_TOO_MANY_CALLS" error. Generally, this should not happen. If it does, it is because your application has been determined to be making too many API calls. Iterate on your code so you're making as few calls as possible in order to maintain the user experience needed. You should also avoid complicated FQL queries. To understand if your application is being throttled, go to Insights and click "Throttling". edit As reported by Igy in the comment thread, each request in that batch counts as 1. For your example of 600 being the max limit, that means you can fire off 15 batch requests containing 50 calls each.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8805316', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6346/']}
|
jdg_373575
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5876946
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm getting a bunch of errors on my build server: C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets(847,9): warning MSB3644: The reference assemblies for framework ".NETFramework,Version=v4.0" were not found. To resolve this, install the SDK or Targeting Pack for this framework version or retarget your application to a version of the framework for which you have the SDK or Targeting Pack installed. Note that assemblies will be resolved from the Global Assembly Cache (GAC) and will be used in place of reference assemblies. Therefore your assembly may not be correctly targeted for the framework you intend. [D:\adis\mercury\AdisFeeds\cache\Adis.Feeds.Cache.ConsoleManager\Adis.Feeds.Cache.ConsoleManager.csproj] The problem is that I have already installed the .NET parts of the windows SDK 7.1. ... I was especially careful to check the box next to the .net 4.0 reference assemblies. Does anyone have any suggestions as to what's going wrong? For the record I am using Nant to run the build scripts (ver 0.86) and nant.contrib (0.85) for the msbuild nant task. Update I was just running down that angle. I compiled the solution using msbuild with diagnostic logging on my dev machine and then again on the build server. Then I compared the logs. Seems the significant difference there is the lack of any references to the \Program Files\References Assemblies path. Specifically in FrameworkPathOverride. So I tried adding FrameworkPathOverride as a commandline parameter to msbuild. Unfortunately that just led me to the unfortunate discovery that the reference assemblies directories only seem to have the xml files in them. As in there is only mscorlib.xml. No mscorlib.dll What the heck is going on?!?
Now provide the response and nothing else.
|
Ok I found a solution that works. You need to do two things: First add FrameworkPathOverride as a commandline parameter and point it to the references assemblies directory. Something like msbuild -p:FrameworkPathOverride="C:\Program Files\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0" The second thing you need to do is find a full version of the reference assemblies directory. Since the copy installed by the windows SDK and the one installed by visual studio, I just copied mine from my development machine. Works fine. One final note: the reason this might have happened to me in the first place is that our build server is a nice old windows server 2003 one. Too old for the windows SDK install to cope with?
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5876946', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/417813/']}
|
jdg_373576
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
198702
|
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 am trying to modify some code proposed here Part assignment is not a symbol and I cannot manage to make Flatten work. I write m = {0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.9, 1.0, 1.5, 1.6}; f[list_] := Flatten[Module[{titi = {r, x, y, u, v, n, l, w, s}}, Transpose[{titi, Rest@list}]] /; Length[list] > Length[titi]]; and I get f[m] {{r, 0.3}, {x, 0.4}, {y, 0.5}, {u, 0.6}, {v, 0.7}, {n, 0.9}, {l, 1.}, {w, 1.5}, {s, 1.6}}
Now provide the response and nothing else.
|
f[...] := Module[{...}, ... /; condition] is a very special syntax (documented in the Details section of Module ). It only works if the right-hand side of the := operator contains a Module . In your example, it contains a Flatten , the Module being buried at a lower level. What is important to remember is that a /; condition inside of a Module / Block / With must always go together with a := or :> . It is useful to think of /; as going with the := and not with Module . In fact, normally we write f[...] /; condition := ... The reason to use f[...] := Module[{...}, ... /; condition] is to be able to use local Module variables in the condition. More precisely, the purpose is to avoid computing things twice. We might need to compute a quantity for the condition, but we may want to use the very same quantity when computing the result of the function. This would not be possible with f[...] /; condition := ... . As @kglr showed, putting the Flatten inside of the Module will fix this.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/198702', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/60972/']}
|
jdg_373577
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
355016
|
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 of matrices in the form of $\left[\begin{array}{cc}\cos \alpha & -\sin \alpha \\ \sin \alpha &\cos \alpha \end{array}\right]$ (while $\alpha \in R$) with the operation of matrix multiplication is an abelian group. Could someone please point me some direction? I know how to multiply matrices or what's the definition of an abelian group but... How can I apply it here? And show such thing, for such a large group of possible alphas? EDIT: OK, so thanks to your advices, I tried to move a little but I think I don't get the idea behind it... On Wikipedia, one can find that "For all a, b in A, the result of the operation a • b is also in A." - does that mean I have to try multiply every term from the matrix by every other? I mean: $cos \alpha \cdot sin \alpha$ and so on? Or did I get it all wrong?
Now provide the response and nothing else.
|
The addition formulas for $\sin$ and $\cos$ yield$$\begin{align}&\begin{bmatrix}\cos(\alpha)&-\sin(\alpha)\\\sin(\alpha)&\cos(\alpha)\end{bmatrix}\begin{bmatrix}\cos(\beta)&-\sin(\beta)\\\sin(\beta)&\cos(\beta)\end{bmatrix}\\&=\begin{bmatrix}\cos(\alpha)\cos(\beta)-\sin(\alpha)\sin(\beta)&-\sin(\alpha)\cos(\beta)-\cos(\alpha)\sin(\beta)\\\sin(\alpha)\cos(\beta)+\cos(\alpha)\sin(\beta)&\cos(\alpha)\cos(\beta)-\sin(\alpha)\sin(\beta)\end{bmatrix}\\&=\begin{bmatrix}\cos(\alpha+\beta)&-\sin(\alpha+\beta)\\\sin(\alpha+\beta)&\cos(\alpha+\beta)\end{bmatrix}\end{align}$$The rest of the group requirements are pretty immediate after this.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/355016', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/29706/']}
|
jdg_373578
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
28410
|
Below is a question asked on the forum mechanics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it possible to use a car's onboard diagnostic port to toggle the headlights, interior lights, or parking lights? If not through the OBD-II port, how would I go about remotely toggling the lights on a car?
Now provide the response and nothing else.
|
The short answer is: no - not without the manufacturer's diagnostic tools. The long answer is: maybe. Modern cars have most (if not all) exterior and interior lights controlled by the body control module (BCM). Most (if not all) switches are connected to the BCM as well. This provides a lot of flexibility. A prime example is if you leave your headlights or interior lights on, the BCM can override and turn them off after a timeout to prevent a dead battery. Another interesting example is the way turn signals operate. In older cars, switching the turn signal on would close a circuit from the battery to a component with a spring in the path. This spring would expand from the heat as current passed through it. Once it expanded enough, it would open the circuit, and as it cooled down, it would shrink and close the circuit again. This in operation generated a clicking sound that we're all too familiar with. Software in the BCM of modern vehicle's control the turn signals, and the "clicking" sound is simulated (usually by a transducer in the instrument cluster). It is possible to control (or actuate) the lights via the OBDII port by issuing an "input/output control" diagnostic command (as defined in ISO-14229 Unified Diagnostic Services) with the ID of the light you want to control. The problem is finding this ID, as they are vehicle manufacturer specific. Only the official diagnostic software/hardware from the manufacturer contains this information. It would be possible to brute force the IDs by sending the IO control command for every possible ID in the system supplier specific range (which is around 500 IDs). This would take a lot of knowledge, time, and effort - but is not impossible.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mechanics.stackexchange.com/questions/28410', 'https://mechanics.stackexchange.com', 'https://mechanics.stackexchange.com/users/16479/']}
|
jdg_373579
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
29985
|
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In the book introduction to automata theory and languages, $L^*$ is defined as $$L^* = \bigcup_{i=0}^\infty L^i $$ The book also says that $\emptyset^* = \{ \epsilon \}$. But since $\emptyset$ is the empty set $$L^* = L^0 \cup L^1 \cup L^2 ... $$ $$= L^0 \cup \emptyset$$ -- since $ \emptyset\emptyset = \emptyset $ and there are 0 elements of $L$ Now since L is $ \emptyset $, then it does not contain $\epsilon$ either. So thus $$L^* = \emptyset $$ But that does not seem to be the case. According to the book, $L^0$ is $\{ \epsilon \}$ and thus $L^* = \{ \epsilon \}$, for L = $\emptyset$. Where am I going wrong?
Now provide the response and nothing else.
|
$O$ is not only used in simple statements like $f(n)=O(g(n))$. It is also used to give error terms as in $f(n) = 14\, n\log n + O(n)$. The interpretation is still the same as @usul has described in his answer: There is a function $h \in O(n)$ so that $f(n) = 14\, n\log n + h(n)$. Here, writing $f(n) \in 14\, n\log n + O(n)$ would emphasize the fact that there is a set involved in the equation, while the important point is that the leading term(s) are exactly as stated, while the $O$-term simply bounds the error. So in this context using $=$ is a sensible choice and I'd assume that it has been carried over to the case with zero leading terms in order to keep notation consistent.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/29985', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/21758/']}
|
jdg_373580
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13787431
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Im trying to implement an Ajax call with the will_paginate gem, I found this guide http://ramblinglabs.com/blog/2011/11/rails-3-1-will_paginate-and-ajax which seemed like a simple solution, though it includes coffeescript which i am not familiar with, so if anyone has a different solution then please advise.. My code is as follows My View <div class="container"> <div class="row"> <div id="userRecipes"> <%= render partial: 'userrecipes' %> </div></div><!--/row--> My partial (userrecipes) <% @recipes.each do |r| %> <div class="span3"> <div class="thumbnail"> <%= image_tag r.avatar.url(:myrecipes) %> </div> <h4><%= link_to r.dish_name, r %></h4> <hr> <p><%= truncate r.description, :length => 90 %></p> <p><%= link_to "Edit Recipe", edit_recipe_path(r.id) %></p> <p><%= link_to "Delete Recipe", recipe_path(r.id), :confirm => "Are you sure?", :method => :delete %></p> <p><%= link_to "Add to favorites", {:controller => 'favourites', :action => 'create', :recipe_id => r.id}, {:method => :post } %></p> </div><!--/span3--> <% end %> <%= will_paginate @recipes %> updated userrecipes.js.erb file $('#userRecipes').html('<%= escape_javascript(render partial: 'userrecipes') %>');$.setAjaxPagination(); Coffeescript $ ->$.setAjaxPagination = ->$('.pagination a').click (event) -> event.preventDefault() loading = $ '<div id="loading" style="display: none;"><span><img src="/assets/loading.gif" alt="cargando..."/></span></div>' $('.other_images').prepend loading loading.fadeIn() $.ajax type: 'GET', url: $(@).attr('href'), dataType: 'script', success: (-> loading.fadeOut -> loading.remove()) false $.setAjaxPagination() When i click on the next anchor tag to show the next set of results the page stays as it is and no new content appears When using the console to see if there are any errors i can see any, the output is GET http://localhost:3000/my_recipes?page=2&_=1355055997639 Am i missing something here? or is there an issue with my userrecipes.js.erb file because in other Ajax examples i have seen thy are using escape_javascript when rendering the partial? Edit Whilst inspecting the response in the console it is also showing that the new recipes to be loaded are being loaded but nothing is happening in the view Any pointers appreciated Thanks
Now provide the response and nothing else.
|
Why not try a simpler approach, create a new helper (ex. app/helpers/will_paginate_helper.rb) with the following content: module WillPaginateHelper class WillPaginateJSLinkRenderer < WillPaginate::ActionView::LinkRenderer def prepare(collection, options, template) options[:params] ||= {} options[:params]['_'] = nil super(collection, options, template) end protected def link(text, target, attributes = {}) if target.is_a? Fixnum attributes[:rel] = rel_value(target) target = url(target) end @template.link_to(target, attributes.merge(remote: true)) do text.to_s.html_safe end end end def js_will_paginate(collection, options = {}) will_paginate(collection, options.merge(:renderer => WillPaginateHelper::WillPaginateJSLinkRenderer)) endend Then in your view use this tag for ajax pagination: <%= js_will_paginate @recipes %> Remember that the pagination links will include existing params of the url, you can exclude these as shown below. This is standard will paginate functionality: <%= js_will_paginate @recipes, :params => { :my_excluded_param => nil } %> Hope that solves your problem. Explanation: Will_paginate allows you to create your own custom renderer . The WillPaginateJSLinkRenderer is such a custom renderer and this class could be defined anywhere, it doesn't have to be defined inside the helper module. The custom renderer extends the standard renderer (LinkRenderer) and redefines only two methods. The prepare method is overriden to explicitly remove the cache buster parameter since will_paginate creates the page urls with all parameters that were present when rendering the page and we do not want to reuse the cache buster parameter. The link method is a copy paste from the original LinkRenderer source code but creates a link with remote: true to make it a JS resquest. Finally the js_will_paginate method is a standard view helper method to call the normal will_paginate view helper method but adds our custom renderer to the options so that it will be used instead of the normal renderer.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13787431', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1150534/']}
|
jdg_373581
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6183276
|
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 on EC2 instance. So there is no GUI. $pip install selenium$sudo apt-get install firefox xvfb Then I do this: $Xvfb :1 -screen 0 1024x768x24 2>&1 >/dev/null &$DISPLAY=:1 java -jar selenium-server-standalone-2.0b3.jar05:08:31.227 INFO - Java: Sun Microsystems Inc. 19.0-b0905:08:31.229 INFO - OS: Linux 2.6.32-305-ec2 i38605:08:31.233 INFO - v2.0 [b3], with Core v2.0 [b3]05:08:32.121 INFO - RemoteWebDriver instances should connect to: http://127.0.0.1:4444/wd/hub05:08:32.122 INFO - Version Jetty/5.1.x05:08:32.123 INFO - Started HttpContext[/selenium-server/driver,/selenium-server/driver]05:08:32.124 INFO - Started HttpContext[/selenium-server,/selenium-server]05:08:32.124 INFO - Started HttpContext[/,/]05:08:32.291 INFO - Started org.openqa.jetty.jetty.servlet.ServletHandler@1186fab05:08:32.292 INFO - Started HttpContext[/wd,/wd]05:08:32.295 INFO - Started SocketListener on 0.0.0.0:444405:08:32.295 INFO - Started org.openqa.jetty.jetty.Server@1ffb8dc Great, everything should work now, right? When I run my code: from selenium import webdriverfrom selenium.common.exceptions import NoSuchElementExceptionfrom selenium.webdriver.common.keys import Keysbrowser = webdriver.Firefox() browser.get("http://www.yahoo.com") I get this: Error: cannot open display: :0
Now provide the response and nothing else.
|
You can use PyVirtualDisplay (a Python wrapper for Xvfb) to run headless WebDriver tests. #!/usr/bin/env pythonfrom pyvirtualdisplay import Displayfrom selenium import webdriverdisplay = Display(visible=0, size=(800, 600))display.start()# now Firefox will run in a virtual display. # you will not see the browser.browser = webdriver.Firefox()browser.get('http://www.google.com')print browser.titlebrowser.quit()display.stop() more info You can also use xvfbwrapper , which is a similar module (but has no external dependencies): from xvfbwrapper import Xvfbvdisplay = Xvfb()vdisplay.start()# launch stuff inside virtual display herevdisplay.stop() or better yet, use it as a context manager: from xvfbwrapper import Xvfbwith Xvfb() as xvfb: # launch stuff inside virtual display here. # It starts/stops in this code block.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6183276', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/179736/']}
|
jdg_373582
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
373648
|
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:
Suppose $X_1, X_2, . . . , X_n$ are i.i.d Poisson ( $\theta$ ) random variables, where $\theta\in(0,\infty)$ . Give the UMVUE of $\theta e^{-\theta}$ I found a similar problem here . I have that the Poisson distribution is an exponential family where $$f(x\mid\theta)=\frac{\theta^x e^{-\theta}}{x!}=\left(\frac{I_{(0,1,...,)}(x)}{x!}\right)e^{-\theta}\text{exp}\left(x\cdot\text{log}(\theta)\right)$$ where $w(\theta)=\text{log}(\theta)$ and $t(x)=x$ . Since $$\{{w(\theta):\theta\in\Theta\}}=\{{\text{log}(\theta):\theta\in(0,\infty)\}}=(-\infty,\infty)$$ contains an open set in $\mathbb{R}$ $$T(\vec{X})=\sum_{i=1}^n t(X_i)=\sum_{i=1}^n X_i$$ is a complete statistic (Complete Statistics in the Exponential Family Theorem) and is also sufficient (Factorization Theorem). Hence $\bar{X}=\frac{T}{n}$ is sufficient for $\theta$ , and hence, for $\theta e^{-\theta}$ . I tried to Rao-Blackwellize the unbiased estimator $\bar{X}$ . For all possible values of $T$ we have that since $\theta e^{-\theta}=\mathsf P(X_i=1)$ then $$\begin{align*}\mathsf P(X_1=1\mid\bar{X}=t)&=\frac{\mathsf P(X_1=1,\sum_{i=2}^n {X_i} =nt-1)}{\mathsf P(\bar{X} = t)}\\\\&=\frac{\frac{e^{-\theta}\theta}{1}\cdot\frac{e^{-(n-1)\theta}((n-1)\theta)^{nt-1}}{nt-1!}}{\frac{e^{-n\theta}(n\theta)^{nt}}{nt!}}\\\\&=t\cdot\left(1-\frac{1}{n}\right)^{nt-1} \end{align*}$$ Since $\mathsf E(X_1)=\theta$ , then $X_1$ is an unbiased estimator of $\theta$ , and so it follows from the Lehmann–Scheffé theorem that $t\cdot\left(1-\frac{1}{n}\right)^{nt-1}$ is the UMVUE. Is this a valid solution? Were my justifications correct and sufficient?
Now provide the response and nothing else.
|
The Poisson distribution is a one-parameter exponential family distribution, with natural sufficient statistic given by the sample total $T(\mathbf{x}) = \sum_{i=1}^n x_i$ . The canonical form is: $$p(\mathbf{x}|\theta) = \exp \Big( \ln (\theta) T(\mathbf{x}) - n\theta \Big) \cdot h(\mathbf{x}) \quad \quad \quad h(\mathbf{x}) = \coprod_{i=1}^n x_i! $$ From this form it is easy to establish that $T$ is a complete sufficient statistic for the parameter $\theta$ . So the Lehmann–Scheffé theorem means that for any $g(\theta)$ there is only one unbiased estimator of this quantity that is a function of $T$ , and this is the is UMVUE of $g(\theta)$ . One way to find this estimator (the method you are using) is via the Rao-Blackwell theorem --- start with an arbitrary unbiased estimator of $g(\theta)$ and then condition on the complete sufficient statistic to get the unique unbiased estimator that is a function of $T$ . Using Rao-Blackwell to find the UMVUE: In your case you want to find the UMVUE of: $$g(\theta) \equiv \theta \exp (-\theta).$$ Using the initial estimator $\hat{g}_*(\mathbf{X}) \equiv \mathbb{I}(X_1=1)$ you can confirm that, $$\mathbb{E}(\hat{g}_*(\mathbf{X})) = \mathbb{E}(\mathbb{I}(X_1=1)) = \mathbb{P}(X_1=1) = \theta \exp(-\theta) = g(\theta),$$ so this is indeed an unbiased estimator. Hence, the unique UMVUE obtained from the Rao-Blackwell technique is: $$\begin{equation} \begin{aligned}\hat{g}(\mathbf{X}) &\equiv \mathbb{E}(\mathbb{I}(X_1=1) | T(\mathbf{X}) = t) \\[6pt]&= \mathbb{P}(X_1=1 | T(\mathbf{X}) = t) \\[6pt]&= \mathbb{P} \Big( X_1=1 \Big| \sum_{i=1}^n X_i = t \Big) \\[6pt]&= \frac{\mathbb{P} \Big( X_1=1 \Big) \mathbb{P} \Big( \sum_{i=2}^n X_i = t-1 \Big)}{\mathbb{P} \Big( \sum_{i=1}^n X_i = t \Big)} \\[6pt]&= \frac{\text{Pois}(1| \theta) \cdot \text{Pois}(t-1| (n-1)\theta)}{\text{Pois}(t| n\theta)} \\[6pt]&= \frac{t!}{(t-1)!} \cdot \frac{ \theta \exp(-\theta) \cdot ((n-1) \theta)^{t-1} \exp(-(n-1)\theta)}{(n \theta)^t \exp(-n\theta)} \\[6pt]&= t \cdot \frac{ (n-1)^{t-1}}{n^t} \\[6pt]&= \frac{t}{n} \Big( 1- \frac{1}{n} \Big)^{t-1} \\[6pt]\end{aligned} \end{equation}$$ Your answer has a slight error where you have conflated the sample mean and the sample total, but most of your working is correct. As $n \rightarrow \infty$ we have $(1-\tfrac{1}{n})^n \rightarrow \exp(-1)$ and $t/n \rightarrow \theta$ , so taking these asymptotic results together we can also confirm consistency of the estimator: $$\hat{g}(\mathbf{X}) = \frac{t}{n} \Big[ \Big( 1- \frac{1}{n} \Big)^n \Big] ^{\frac{t}{n} - \frac{1}{n}} \rightarrow \theta [ \exp (-1) ]^\theta = \theta \exp (-\theta) = g(\theta).$$ This latter demonstration is heuristic, but it gives a nice check on the working. It is interesting here that you get an estimator that is a finite approximation to the exponential function of interest.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/373648', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/177990/']}
|
jdg_373583
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5018545
|
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 couldn't find a satisfying answer to this, so here we go: what's the deal with Activity/Service.getApplication() and Context.getApplicationContext() ? In our application, both return the same object. In an ActivityTestCase however, mocking the application will make getApplication() come back with the mock, but getApplicationContext will still return a different context instance (one injected by Android). Is that a bug? Is it on purpose? I don't even understand the difference in the first place. Are there cases outside a test suite where both calls may come back with different objects? When and why? Moreover, why is getApplication defined on Activity and Service , but not on Context ? Shouldn't there always be a valid application instance available from anywhere ?
Now provide the response and nothing else.
|
Very interesting question. I think it's mainly a semantic meaning, and may also be due to historical reasons. Although in current Android Activity and Service implementations, getApplication() and getApplicationContext() return the same object, there is no guarantee that this will always be the case (for example, in a specific vendor implementation). So if you want the Application class you registered in the Manifest, you should never call getApplicationContext() and cast it to your application, because it may not be the application instance (which you obviously experienced with the test framework). Why does getApplicationContext() exist in the first place ? getApplication() is only available in the Activity class and the Service class, whereas getApplicationContext() is declared in the Context class. That actually means one thing : when writing code in a broadcast receiver, which is not a context but is given a context in its onReceive method, you can only call getApplicationContext() . Which also means that you are not guaranteed to have access to your application in a BroadcastReceiver. When looking at the Android code, you see that when attached, an activity receives a base context and an application, and those are different parameters. getApplicationContext() delegates it's call to baseContext.getApplicationContext() . One more thing : the documentation says that it most cases, you shouldn't need to subclass Application: There is normally no need to subclass Application . In most situation, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), the function to retrieve it can be given a Context which internally uses Context.getApplicationContext() when first constructing the singleton. I know this is not an exact and precise answer, but still, does that answer your question?
|
{}
|
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/5018545', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/127013/']}
|
jdg_373584
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5327
|
Below is a question asked on the forum meta.mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Prompted by Gro-Tsen's recent meta question , it appears that now may be a good time to rethink our site-specific close reasons here on MathOverflow. Background: If you have sufficient rep, you can click the "close" button on a question (or the equivalent "flag" → "needs improvement", which is available for almost all users), and you get a popup which looks like this: These are some general close reasons common to the entire Stack Exchange network as I understand, and which, if we wanted to change them, would at the very least require some discussion with Stack Exchange (and they might tell us no ). What we do have control over is the options you get if you choose the second option on this list -- the community-specific reasons. If you do that, you get the following options: We currently have two options here, and we can have up to three. As a technical point, it appears to be possible for moderators to delete a close reason or to create a new one, but not to edit the description in an existing close reason. We can also tinker with the order they appear in. History: It's hard to trace these sorts of things all the way back to the beginning of MO, but in addition to the current two site-specific close reasons, the software currently remembers two deactivated ones, which read: MathOverflow is for mathematicians to ask questions to each other about their research. Questions about homework are generally off-topic . Questions about homework are generally off-topic . MathOverflow is for mathematicians to ask each other questions about their research. I suspect that one of these reasons at some point replaced the other, as a minor rewording. Judging by this old meta discussion , it appears that this close reason (containing the word "homework") was retired in 2013 in favor of the current close reason which mentions Math Stack Exchange. At the time, no specific rationale was recorded for dropping the word "homework", but I think I agree that explicitly labeling a question as "looking like homework" is not something we want to be doing in our question-closing process. Why do we close questions, anyway? We have recently revamped the help page which describes what's on-topic and what's off-topic on MathOverflow, as suggested by Matt F. in this meta discussion . Currently, that help page lists the following possible reasons that a question may be off-topic: The question looks like homework. The question is a discussion question. The question asks for a broad exposition or encyclopedia article on a topic. The question asks for OP's or somebody else's work to be checked. The question is really just an announcement of results. The question asks a well-known open problem. The question has been inappropriately cross-posted on another site. The question is a meta MathOverflow question. In addition, the user is advised to avoid the following types of questions until they gain a bit of familiarity with the site: Questions asking for a list of something. Questions about the workings of the mathematical community rather than about mathematics per se . Question 1: Are we missing any important close reasons here? Analysis of Close Reasons Needed: It appears to me that, with a few exceptions, most of the above close reasons are well-covered by the close reasons one is allowed to select when voting to close a question: Homework -- not about research math. Discussion -- needs focus / opinion based. Encyclopedia -- needs focus. Checking work -- ?? As suggested by Gro-Tsen, we could perhaps use a specific close reason for this. Result announcement -- ?? If the question is not really a question, in principle we shouldn't need a site-specific close reason. Probably "opinion-based" should cover cases like this. But perhaps there's something to be said for having a close reason which allows this to be lumped with "work-checking". Open problem -- ?? I think that "needs focus" should cover a case like this -- the point is that if you're asking about an open problem, you should be asking some more specific question than just "what is the solution?". However, because "needs focus" is not a site-specific close reason, we can't edit it to point out that specifically, questions about open problems need a very particular kind of focus. So perhaps it would make sense to have an additional close reason covering this case. Cross-post -- duplicate ?? I realize now I'm not sure how we usually handle inappropriate cross-posts. Meta -- not about research math. (Lists) -- needs focus. (Mathematical community) -- not about research math. So by my count, there are up to 3 4 close reasons which could be formalized in addition to the ones we have, but only 1 slot to put them in. So some sort of prioritizing or lumping-together needs to be done. Question 2: Which of the 3 4 close reasons with question marks above is the most important to give a close reason to? More broadly, what would be the ideal way to use our 3 allotted slots of site-specific close reasons? For example, one possibility would be to keep the two existing close reasons we have, and to additionally add something along the lines suggested by Gro-Tsen . In that case, we'd just need to nail down the details a bit more. (Note that there's also the option to provide a custom close reason which you write on the spot. If a close reason is rare enough, it can be covered by that.) Analysis of the close reasons we have: Note also that the two site-specific close reasons we currently have are similar -- one is "not about research math", while the other is "not about research math, and here's a link to Math.SE". It seems to me these should be modified to give a little more clarity about when one should be chosen over the other. This leads into the final point. Technical Point: Since 2019 we have the flexibility to have the close reasons we use display differently to different users. For instance, the message shown to a prospective close voter can be different from the message shown to a prospective close votee. I bring this up because it may be relevant to us when it comes to the two existing close reasons -- we could consider adding some guidance for close-voters over when to choose the one which links to Math Stack Exchange and when not to (I think the main point is: don't choose the Math Stack Exchange one unless you're sure the question meets the standards of Math Stack Exchange questions.) Question 3: What specifically should our site-specific close reasons say? This question is mean to include the specifics of any potential new close reasons, as well as any potential changes to the wording of existing close reasons (technically to change the wording, the process is to delete the old close reason and replace it with a new one, but I think we should be open to doing something like that at this time with our existing close reasons.)
Now provide the response and nothing else.
|
We've now implemented exactly the sort of changes discussed here. (Thanks in particular to Stefan Kohl!). Here's are the new community-specific close reasons: You'll see we've deleted both the old community-specific close reasons, and replaced them with two new ones. The first one is meant to fill the role previously filled by both old community-specific close reasons (one of which said "This question does not appear to be about research level mathematics within the scope defined in the help center.", and the other of which said "MathOverflow is for mathematicians to ask each other questions about their research. See Math.StackExchange to ask general questions in mathematics.") When those old close reasons were written, the system was a bit different. With the current system, it seems feasible to combine them into one reason. The text below does mention Math Stack Exchange, but with enough context to try to dissuade folks from blindly sending people there without regard for the standards of that site. The new close reason looks like this: Text displayed to potential close voter: This question is not about research level mathematics. This close reason should be used if a question is either not about mathematics or if it is not of interest to mathematicians. The latter is often the case because the level of the question is not advanced enough, which in general holds for example for student exercises. If besides being too elementary for MathOverflow the question is good and written down in a reasonable way, please consider leaving a comment suggesting to post the question on Mathematics instead. Text displayed to user whose question has been closed: This question does not appear to be about research level mathematics within the scope defined in the help center . MathOverflow is aimed towards professional mathematics, and questions that are on-topic should reflect this in both subject and level. More elementary questions about mathematics are on-topic on Mathematics , provided they are well-written according to the standards of that site . Text displayed to other users viewing closed post: This question does not appear to be about research level mathematics within the scope defined in the help center. If this question has a research angle which was not noticed before it got closed, then please leave a comment with relevant information and vote to reopen. The same holds if for some other reason you do think that this question is interesting for mathematicians. However, please do not change the question into a significantly different one which is of interest to mathematicians. It is better to ask a new question instead. The second new close reason is essentially as suggested by Gro-Tsen , and is fundamentally new. It looks as follows. Text displayed to potential close voter: This question is either a request to check work for correctness or an announcement of results. This close reason should be used if a question either is announcing new results or asks to verify a proof or a preprint. It should also be used in situations where the work to be checked is included in the text of the post itself. Text displayed to user whose question has been closed. Requests to check work for correctness and announcements of results are off-topic on MathOverflow. If you like to have your work checked before submitting it to a journal, you may kindly ask a colleague for help – but please understand that people may not have time for this in particular if they do not know you well. If you wish to broadly announce your results, then please use other channels available to you for this purpose. Text displayed to other users viewing closed question: Requests to check work for correctness and announcements of results are off-topic on MathOverflow. If this is not the first question of the OP which has been closed for the same reason, then consider flagging for moderator attention.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://meta.mathoverflow.net/questions/5327', 'https://meta.mathoverflow.net', 'https://meta.mathoverflow.net/users/2362/']}
|
jdg_373585
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
26979391
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Like the title says, i am trying to store the results of a query in a variable so that i can use it in another query that would join them. I have been trying to do this using the INTO santex as it describes it on google. This is what i am entering: mysql> select Name, Type, Region from table1 union select Name, Type, Region from Table2 into @temp1; However, with this, i am getting this error: ERROR 1222 (21000): The used SELECT statements have a different number of columns Which does not make sense as the Select statement has the same number of columns. So i figure maybe its my variable, so i remove the @ and tried it again, but i got this error: ERROR 1327 (42000): Undeclared variable: temp So now im at a lost, what am i doing wrong? I am following the syntax that is describe on several wikis on google but with no luck.
Now provide the response and nothing else.
|
Read more about absolute, relative, and fixed position and how they differ here , but I'll try to answer your question about relationships specifically. position: absolute will position that element to its nearest parent with a position other than static . Static is the default for everything. position: relative is a little weird because it really affects that element's children, not its own position. It's just saying to its child elements, "position yourself relative to me if you have position: absolute ." A position of fixed or absolute does the same thing (meaning its positioned children will position themselves relative to its boundaries), but these styles also affect their own position on the page. An element with position: relative won't look any different, but its children might. So consider a situation like this: <div class="parent"> <div class="child"> <div class="grandchild"></div> </div></div> If grandchild has position: absolute , it will position itself relative to the browser window because there is no parent with a position other than the default of static . If parent also has position of relative , absolute , or fixed , grandchild will position itself relative to the boundaries of parent . However, if child also has a position of relative , absolute , or fixed , the grandchild will position itself relative to child 's boundaries, because it is the nearest parent with a position other than static . In summary, relative affects an element's children, while absolute and fixed affect the element itself as well as its children. And remember that position: fixed bypasses all relative and absolute parents and always positions itself relative to the browser window.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/26979391', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4250385/']}
|
jdg_373586
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
11558654
|
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 something simple, just to get the text value inside a p:inputText thought Javascript, but I`m not getting it.Perhaps it's a different procedure with Primefaces, since if I don't use that, I don't encounter the problem. My code: <p:inputText value="any text" widgetVar="youtlink" ></p:inputText> <p:commandButton value="Search" onclick="loadPlayer();" icon="ui-icon-search" /> <script type="text/javascript"> function loadPlayer() { alert(youtlink.text); }</script> I have tried also with JQuery but also no success. Rendered view: <form id="editlFrm" enctype="application/x-www-form-urlencoded" method="post"name="editlFrm"> <input id="editlFrm:j_id_7" class="ui-inputfield ui-inputtext ui-widget ui-state-default ui-corner-all" type="text" value="assd" name="editlFrm:j_id_7" role="textbox" aria-disabled="false" aria-readonly="false" aria-multiline="false"> <button id="editlFrm:j_id_8" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-icon-left" type="submit" onclick="loadPlayer();;PrimeFaces.ab({source:'editlFrm:j_id_8'});return false;" name="editlFrm:j_id_8" role="button" aria-disabled="false">
Now provide the response and nothing else.
|
Add id to your <p:inputText like this <p:inputText id="someID" value="any text" widgetVar="youtlink" ></p:inputText> make sure your form got prependId="false" than access the value like this alert(jQuery('#someID').val()); if you don't want to add prependId="false" to your form you will have to change the jquery selector from jQuery('#someID').val() to jQuery("[id$='someID']").val() EDIT since your form called editlFrm try this (make sure to assign someID id to your p:inputText ) alert(jQuery('#editlFrm\\:someID').val());
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11558654', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1453711/']}
|
jdg_373587
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9425414
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I need to write a program which will write many characters in a output file.My program will also need to write newline for better formatting.I understand ofstream is a buffered stream and if we use a buffered stream for file io, we gain performance. However, if we use std::endl the output will be flushed and we will loose any potential performance gain due to the buffered output. I suppose if I use '\n' for new line the output will be only flushed when we will std::endl . Is this correct? And are there any tricks that can be used to get performance gain during file output? Note: I want to flush the buffered output at the completion of the file write operations. I think in this way I can minimize file I/O and thus can gain performance.
Now provide the response and nothing else.
|
Generally, the user of stream classes shouldn't mess with the stream's flushing if maximum performance is wanted: the streams internally flush their buffer when it is full. This is actually more efficient than waiting until all output is ready, especially with large files: the buffered data is written while it is still likely to be in memory. If you create a huge buffer and only write it once the virtual memory system will have put parts of the data onto disc but not the file. It would need to be read from disc and written again. The main point with respect to std::endl is that people abuse it a line ending which causes the buffer to flush and they are unaware of the performance implications. The intention of std::endl is that people are given control to flush files at reasonable points. For this to be effective they need to know what they are doing. Sadly, there were too many people ignorant of what std::endl does who advertised its use as a line ending such that it is used in many places where it is plain wrong. That said, below are a number of things you might want to try to improve performance. I assume you need formatted output (which the use of std::ofstream::write() won't give you). Obviously, don't use std::endl unless you have to. If the writing code already exists and uses std::endl in many places, some of which possibly outside your control, you can use a filtering stream buffer which uses its internal buffer of reasonable size and which doesn't forward calls to its sync() function to the underlying stream buffer. Although this involves an extra copy, this is better than some spurious flushes as these are orders of magnitude more expensive. Although it shouldn't have an effect on std::ofstream s, calling std::ios_base::sync_with_stdio(false) used to affect the performance on some implementations. You'd want to look at using a different IOstream implementation if this has an effect because there are probably more things wrong with respect to performance. Make sure you are using a std::locale whose std::codecvt<...> returns true when calling its always_noconv() . This can easily be checked by using std::use_facet<std::codecvt<char, char, stdd::mbstate_t> >(out.get_loc()).always_noconv() . You can use std::locale("C") to get hold of an std::locale for which this should be true. Some locale implementations use very inefficient implementations of their numeric facets and even even if they are reasonably good, the default implementation of the std::num_put<char> facet may still do things you don't really need. Especially if your numeric formatting is reasonably simple, i.e. you don't keep changing formatting flags, you haven't replace mapping of characters (i.e. you don't use a funny std::ctype<char> facet), etc. it may be reasonable to use a custom std::num_put<char> facet: It is fairly easy to create a fast but simple formatting function for integer types and a good formatting function for floating points which doesn't use snprintf() internally. Some people have suggested the use of memory mapped files but this only works reasonable when the size of the target file is known in advance. If this is the case this is a great way to also improve performance otherwise it isn't worth the bother. Note that you can use the stream formatting with memory mapped files (or, more generally, with any kind of output interface) by creating a custom std::streambuf which uses the memory mapping interface. I found memory mapping sometimes effective when using them with std::istream s. In many cases the differences don't really matter much. A long time ago I wrote my own IOStreams and locales implementation which doesn't suffer from some of the performance problems mentioned above (it is available from my site but it is a bit stale and I haven't touched it for nearly 10 years now). There are lots of things which can be improved over this implementation still but I haven't an up to date implementation which I'd be ready to post somewhere. Soon, hopefully - something I keep thinking since nearly 10 years, though...
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9425414', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1025408/']}
|
jdg_373588
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
25636897
|
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 get a map with RgoogleMaps from R, with a specific coordinates boundary. What I can call is GetMap, and specify a center, I must add a zoom level. Everything works fine, except that I am not getting an image map bounded with the coordinates I choose. Here's an example: lat <- c(44.49,44.5) lon <- c(11.33,11.36) center = c(mean(lat), mean(lon)) zoom <- 14 mmap <- GetMap(center = center, zoom=zoom, maptype= "satellite", destfile = "m.png") The problem is that only the center is passed as a parameter, and thus the whole image I see is dependant on the zoom level. So, I cannot really understand what are the boundaries of the image I get. What I want to do is to get an image bounded exactly with the coordinates I am defining. Is this possible (also with other map packages)?
Now provide the response and nothing else.
|
Here is one way. First, you get a map with a certain zoom. Then, you add the lon and lat limit when you draw a figure, which you can do with scale_x_continuous and scale_y_continuous . library(ggmap)library(ggplot2)### Set a rangelat <- c(44.49, 44.5) lon <- c(11.33, 11.36) ### Get a mapmap <- get_map(location = c(lon = mean(lon), lat = mean(lat)), zoom = 14, maptype = "satellite", source = "google")### When you draw a figure, you limit lon and lat. foo <- ggmap(map)+ scale_x_continuous(limits = c(11.33, 11.36), expand = c(0, 0)) + scale_y_continuous(limits = c(44.49, 44.5), expand = c(0, 0))foo
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/25636897', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/295525/']}
|
jdg_373589
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
23901168
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How do I insert a JPEG image into a Python 2.7 Tkinter window? What is wrong with the following code? The image is called Aaron.jpg . #!/usr/bin/pythonimport Imageimport Tkinterwindow = Tkinter.Tk()window.title("Join")window.geometry("300x300")window.configure(background='grey')imageFile = "Aaron.jpg"window.im1 = Image.open(imageFile)raw_input()window.mainloop()
Now provide the response and nothing else.
|
Try this: import tkinter as tkfrom PIL import ImageTk, Image#This creates the main window of an applicationwindow = tk.Tk()window.title("Join")window.geometry("300x300")window.configure(background='grey')path = "Aaron.jpg"#Creates a Tkinter-compatible photo image, which can be used everywhere Tkinter expects an image object.img = ImageTk.PhotoImage(Image.open(path))#The Label widget is a standard Tkinter widget used to display a text or image on the screen.panel = tk.Label(window, image = img)#The Pack geometry manager packs widgets in rows or columns.panel.pack(side = "bottom", fill = "both", expand = "yes")#Start the GUIwindow.mainloop() Related docs: ImageTk Module , Tkinter Label Widget , Tkinter Pack Geometry Manager
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/23901168', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3678023/']}
|
jdg_373590
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4436394
|
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 found this question in an old Mathematical Olympiad: Let $0<a<1$ be a real number, and let $f(z)$ be a complex polynomial such that $$|f(z)|\leq \frac{1}{|z-a|}$$ on the unit disk $|z|\leq 1$ . Prove that $$|f(a)| \leq \frac{1}{1-a^2}.$$ My attempt: Since $f$ is analytic in $\{z\in\mathbb{C}:|z|\leq 1\}$ , we have that $$|f(a)| \leq \max_{|z|=1}|f(z)|.$$ Because of the triangle inequality, for all $z\in \mathbb{C}$ with $|z|=1$ we have $$|z-a|\geq |z|-a = 1-a.$$ By applying the hypothesis, we get $$|f(a)| \leq \max_{|z|=1}|f(z)| \leq \max_{|z|=1}\frac{1}{|z-a|}\leq \frac{1}{1-a}.$$ Nevertheless, we know that $1-a^2>1-a$ since $a\in (0,1)$ . Therefore, we cannot get the desired result from the above inequality. What can I apply to complete the proof?
Now provide the response and nothing else.
|
Let $F(z)=(z-a)f(z)$ and $G(z)=F(\frac {z+a} {1+az})$ . [Recall that $ z \to \frac {z+a} {1+az}$ is an analytic bijection of the unit disk into itself whose inverse is $ z \to \frac {z-a} {1-az}$ ]. Now $|G(z)| \leq 1$ and $G(0)=F(a)=0$ . By Schwarz Lemma we get $|G(z)| \leq |z|$ . This can be written as $|F(z)|\leq |\frac {z-a}{1-az}|$ . Hence, $|f(z)|\leq |\frac 1{1-az}|$ and putting $z=a$ finishes the proof.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4436394', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/870421/']}
|
jdg_373591
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
564125
|
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 extended from org.eclipse.ui.editors and defined the editor-id in plugin.xml as "MyEditorId". I wrote corresponding editor class. Then I tried to open the editor from a view with this code. page.openEditor(input, "MyEditorId"); But I am getting "PartInitException". i.e apllication is not recognising the editor by it's id. I have checked that there is no spelling mistake in the referenced editor-id. Why is editor not getting recognised?
Now provide the response and nothing else.
|
The specific datastructure you want is probably the implicit heap . The raw datastructure is just an array; for convenience, say that it is N=2^n elements in size, and that you want to maintain the largest N-1 elements. The idea is to treat the array (call it A) as a complete binary tree of depth n: ignore A[0]; treat A[1] as the root node for each node A[k], the children are A[2*k] and A[2*k+1] nodes A[N/2..N-1] are the leaves To maintain the tree as a "heap", you need to ensure that each node is smaller than (or equal to) its children. This is called the "heap condition": A[k] <= A[2*k] A[k] <= A[2*k+1] To use the heap to maintain the largest N elements: note that the root A[1] is the smallest element in the heap. compare each new element (x) to the root: if it is smaller (x<A[1]), reject it. otherwise, insert the new element into the heap, as follows: remove the root (A[1], the smallest element) from the heap, and reject it replace it with the new element (A[1]:= x) now, restore the heap condition: if x is less than or equal to both of its children, you're done otherwise, swap x with the smallest child repeat the test&swap at each new position until the heap condition is met Basically, this will cause any replacement element to "filter up" the tree until it achieves its natural place. This will take at most n=log2(N) steps, which is as good as you can get. Also, the implicit form of the tree allows a very fast implementation; existing bounded-priority-queue libraries will most likely use an implicit heap.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/564125', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/65412/']}
|
jdg_373592
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
43142580
|
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 C#. I want the Json array in the below structure "bed_configurations": [ [{ "type": "standard", "code": 3, "count": 1 }, { "type": "custom", "name": "Loft", "count": 1 }] ] Please any one can help me..
Now provide the response and nothing else.
|
You can't use a temp table - you have to use a table variable : declare @t [MyNameSpace].[MyTypeTable]insert into @t (/*columns*/) values(/* first row */),(/* second row */)EXECUTE MyNameSpace.MyStoredProc @MyTypeTableVar = @t; (You can populate it with either INSERT ... VALUES as shown above or INSERT ... SELECT if you have an existing table containing the data you care about)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43142580', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7780389/']}
|
jdg_373593
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
42127446
|
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 a bit manipulation method which multiplies a number toward five eighths and if there is a remainder rounds toward 0. The method works, and I understand almost all of it. When I was reviewing it, however, I realized I'm not certain how anding 7 (00000111) accounts for rounding error, in which it would round toward a more negative number instead of 0, and I need to understand why that line works. As far as I can see, shifting multiplyByFive 31 bits to the right will just check the sign of the variable and yield all ones if negative, so anding it with 7 will either yield all zeroes if positive, or y in binary if negative. If my understanding is correct, why does adding that to multiplyFiveEighths and dividing the sum by 8 round a negative number down, without error. int multFiveEights(int x) { break it down into multiplying by 5 and then dividing by 8shifting it two to the left multiplies it by four, plus x makes it by 5 int multiplyByFive = (x << 2) + x; if the result is negative, and 2^3 - 1 = 7 before right shift int addNumber = 7 & (multiplyByFive >> 31); 11111111 (if you right shift by 31 when negative you get all 1s) will return all 0s if positive and 1 in the LSB if negative adding 7 to multiplyByFive accounts for error if its negative it will try to round down which goes toward the more negative number, so anding it with 7 accounts for this error/ tests for a remainder int fiveEigths = (multiplyByFive + addNumber) >> 3;return fiveEigths;
Now provide the response and nothing else.
|
Here is how I set up my AppDelegate file to do this: To handle push notifications, import the following framework: import UserNotifications To make the phone vibrate on any device import the following framework: import AudioToolbox Make your AppDelegate a UNUserNotificationCenterDelegate: @UIApplicationMainclass AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate { In your "didFinishLaunchingWithOptions" add this: UNUserNotificationCenter.current().delegate = self UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .sound, .alert], completionHandler: {(granted, error) in if (granted) { UIApplication.shared.registerForRemoteNotifications() } else{ print("Notification permissions not granted") } }) This will determine if the user has previously said that your app can send notifications. If not, handle it how you please. To get access to the device token once it is registered: //Completed registering for notifications. Store the device token to be saved laterfunc application( _ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data ) { self.deviceTokenString = deviceToken.hexString} hexString is an extension I added to my project: extension Data { var hexString: String { return map { String(format: "%02.2hhx", arguments: [$0]) }.joined() }} To handle what happens when your app receives a notification in the foreground: //Called when a notification is delivered to a foreground app.func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { //Handle the notification //This will get the text sent in your notification let body = notification.request.content.body //This works for iphone 7 and above using haptic feedback let feedbackGenerator = UINotificationFeedbackGenerator() feedbackGenerator.notificationOccurred(.success) //This works for all devices. Choose one or the other. AudioServicesPlayAlertSoundWithCompletion(SystemSoundID(kSystemSoundID_Vibrate), nil)} To handle what happens when a users presses on a notification they receive (from your application) while your app is in the background, call the following function: //Called when a notification is interacted with for a background app.func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { //Handle the notification print("did receive") let body = response.notification.request.content.body completionHandler()}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42127446', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5544627/']}
|
jdg_373594
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
906111
|
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've been asked to deploy an IPSEC server for a project and after doing some research, StrongSwan looks like a good candidate. Since this project requires top security, I decided to install the latest version of StrongSwan (5.6.2) as it seems to fix a few security issues and what-not. So I've spent the past few days working out how to configure it, which I have been able to do using /etc/ipsec.conf , however, on reading StrongSwan's website, is now a legacy way of setting it up. The recommended way of configuring strongSwan is via the powerful vici interface and the swanctl command line tool. The swanctl.conf configuration file used by swanctl is stored together with certificates and corresponding private keys in the swanctl directory. Global strongSwan settings as well as plugin-specific configurations are defined in strongswan.conf. Alternatively the legacy ipsec stroke interface and its ipsec.conf and ipsec.secrets configuration files may be used. So now I am in the process of trying to change the configuration to use a file stored in /etc/swanctl/conf.d instead... So my question is this: Does anyone know how to build StrongSwan from source and have it start with the Server (Ubuntu 16.04) and use the new configuration method? My configure line looks like this ./configure --prefix=/usr --sysconfdir=/etc \ --enable-systemd --enable-swanctl \ --disable-charon --disable-stroke --disable-scepclient \ --enable-gcm --enable-eap-tls but this still doesnt start with the Server, nor can I find any strongswan or strongswan-swanctl for startup. My current ipsec.conf looks like this conn %default auto=add forceencaps=yes keyexchange=ikev2 keyingtries=1 ike=aes256-sha256-modp2048! esp=aes256-sha256,aes128-sha256! dpdaction=clear inactivity=120s leftsendcert=always leftcert=vpn-server-cert.pem leftsubnet=10.0.0.0/20 leftid=@vpnserver rightsourceip=172.16.0.0/12 eap_identity=%identityconn ikev2-cert rightauth=eap-tls which 'I think' translates to this connections { rw { version = 2 send_certreq = yes proposals = aes256-sha256-modp2048! encap = yes dpd_delay = 30s local { auth = eap-tls certs = vpn-server-cert.pem id = vpnserver } remote { auth = eap-tls } children { net { local_ts = 172.16.0.0/12 esp_proposals = aes256-sha256,aes128-sha256! inactivity = 120s } } }}
Now provide the response and nothing else.
|
If you configure with --enable-systemd the charon-systemd daemon will be built and a systemd service unit named strongswan will be installed. You can manage that (like any other systemd unit) with systemctl . So to start it at system boot enable the unit with: sudo systemctl enable strongswan.service ( Note: The systemd service unit was called strongswan-swanctl before 5.8.0 .) Also, a more accurate translation of the config is the following: connections { rw { version = 2 send_cert = always proposals = aes256-sha256-modp2048 encap = yes pools = rw # dpd_delay = 30s you didn't specify this in your ipsec.conf and it seems rather short for roadwarriors local { certs = vpn-server-cert.pem id = vpnserver } remote { auth = eap-tls eap_id = %any } children { net { local_ts = 10.0.0.0/20 esp_proposals = aes256-sha256,aes128-sha256 inactivity = 120s } } }}pools { rw { addrs = 172.16.0.0/12 }}
|
{}
|
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/906111', 'https://serverfault.com', 'https://serverfault.com/users/96611/']}
|
jdg_373595
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
19495
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
I was told that one of the most efficient tools (e.g. in terms of computations relevant to physics, but also in terms of guessing heuristically mathematical facts) that physicists use is the so called "Feynman path integral", which, as far as I understand, means "integrating" a functional (action) on some infinite-dimentional space of configurations (fields) of a system. Unfortunately, it seems that, except for some few instances like Gaussian-type integrals, the quotation marks cannot be eliminated in the term "integration", cause a mathematically sound integration theory on infinite-dimensional spaces — I was told — has not been invented yet. I would like to know the state of the art of the attempts to make this "path integral" into a well-defined mathematical entity. Difficulties of analytical nature are certainly present, but I read somewhere that perhaps the true nature of path integral would be hidden in some combinatorial or higher-categorical structures which are not yet understood... Edit: I should be more precise about the kind of answer that I expected to this question. I was not asking about reference for books/articles in which the path integral is treated at length and in detail. I'd have just liked to have some "fresh", (relatively) concise and not too-specialistic account of the situation; something like: "Essentially the problems are due to this and this, and there have been approaches X, Y, Z that focus on A, B, C; some progress have been made in ... but problems remain in ...".
Now provide the response and nothing else.
|
It's not accurate to say that no theory of integration on infinite-dimensional spaces exists. The Euclidean-signature Feynman measure has been constructed -- as a measure on a space of distributions -- in a number of non-trivial cases, mainly by the Constructive QFT school in the 70s. The mathematical constructions reflect the physical ideas of effective quantum field theory: One obtains the measure on the space of field histories as the limit of a sequence/net of "regularized" integrals, which encode how the effective "long distance" degrees of freedom interact with each other after one averages out the short distance degrees of freedom in various ways. (You can imagine here that long/short distance refers to some wavelet basis, and that we get the sequence of regularized integrals by varying the way we divide the wavelet basis into short distance and long distance components.) I don't think the main problem in the subject is that we need some new notion of integration. The Feynman measures we mathematicians can construct exhibit all the richness of the "higher categories" axioms, and moreover, the numerical computations in lattice gauge theory and in statistical physics indicates that the existing framework is at the least a very good approximation. The problem, rather, is that we need a better way of constructing examples. At the moment, you have to guess which family of regularized integrals you ought to study when you try to construct any particular example. (In Glimm & Jaffe's book, for example, they simply replace the interaction Lagrangian with the corresponding "normally ordered" Lagrangian. In lattice gauge theory, they use short-distance continuum perturbation theory to figure out what the lattice action should be.) Then -- and this is the really hard and physically interesting part -- you have to have enough analytic control on the family to say which observables (functions on the space of distributions) are integrable with respect to the limiting continuum measure. This is where you earn the million dollars, so to speak.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/19495', 'https://mathoverflow.net', 'https://mathoverflow.net/users/4721/']}
|
jdg_373596
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6200910
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
SciPy appears to provide most (but not all [1]) of NumPy's functions in its own namespace. In other words, if there's a function named numpy.foo , there's almost certainly a scipy.foo . Most of the time, the two appear to be exactly the same, oftentimes even pointing to the same function object. Sometimes, they're different. To give an example that came up recently: numpy.log10 is a ufunc that returns NaNs for negative arguments; scipy.log10 returns complex values for negative arguments and doesn't appear to be a ufunc. The same can be said about log , log2 and logn , but not about log1p [2]. On the other hand, numpy.exp and scipy.exp appear to be different names for the same ufunc. This is also true of scipy.log1p and numpy.log1p . Another example is numpy.linalg.solve vs scipy.linalg.solve . They're similar, but the latter offers some additional features over the former. Why the apparent duplication? If this is meant to be a wholesale import of numpy into the scipy namespace, why the subtle differences in behaviour and the missing functions? Is there some overarching logic that would help clear up the confusion? [1] numpy.min , numpy.max , numpy.abs and a few others have no counterparts in the scipy namespace. [2] Tested using NumPy 1.5.1 and SciPy 0.9.0rc2.
Now provide the response and nothing else.
|
Last time I checked it, the scipy __init__ method executes a from numpy import * so that the whole numpy namespace is included into scipy when the scipy module is imported. The log10 behavior you are describing is interesting, because both versions are coming from numpy. One is a ufunc , the other is a numpy.lib function. Why scipy is preferring the library function over the ufunc , I don't know off the top of my head. EDIT: In fact, I can answer the log10 question. Looking in the scipy __init__ method I see this: # Import numpy symbols to scipy name spaceimport numpy as _numfrom numpy import oldnumericfrom numpy import *from numpy.random import rand, randnfrom numpy.fft import fft, ifftfrom numpy.lib.scimath import * The log10 function you get in scipy comes from numpy.lib.scimath . Looking at that code, it says: """Wrapper functions to more user-friendly calling of certain math functionswhose output data-type is different than the input data-type in certaindomains of the input.For example, for functions like log() with branch cuts, the versions in thismodule provide the mathematically valid answers in the complex plane:>>> import math>>> from numpy.lib import scimath>>> scimath.log(-math.exp(1)) == (1+1j*math.pi)TrueSimilarly, sqrt(), other base logarithms, power() and trig functions arecorrectly handled. See their respective docstrings for specific examples.""" It seems that module overlays the base numpy ufuncs for sqrt , log , log2 , logn , log10 , power , arccos , arcsin , and arctanh . That explains the behavior you are seeing. The underlying design reason why it is done like that is probably buried in a mailing list post somewhere.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/6200910', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/367273/']}
|
jdg_373597
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
15990084
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've been reading the blogs about rust and this closure for example made me wonder: fn each<E>(t: &Tree<E>, f: &fn(&E) -> bool) {if !f(&t.elem) { return;}for t.children.each |child| { each(child, f); }} why couldn't it be: each<E>(t: &Tree<E>, f: &(&E) -> bool) {if !f(&t.elem) { return;}for t.children.each |child| { each(child, f); }} Maybe i'm missing something on the class system that would prevent this.
Now provide the response and nothing else.
|
It makes parsing more complicated for compilers, syntax-highlighters, shell scripts and humans (i.e. everyone). For example, with fn , foo takes a function that has two int arguments and returns nothing, and bar takes a pointer to a tuple of 2 int s fn foo(f: &fn(int, int)) {}fn bar(t: &(int, int)) {} Without fn , the arguments for both become &(int, int) and the compiler couldn't distinguish them. Sure one could come up with other rules so they are written differently, but these almost certainly have no advantages over just using fn .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15990084', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/214260/']}
|
jdg_373598
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
48642450
|
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 iterate through all nodes of a json object, and write out a plain key-value map, as follows: { "name": [ { "first": "John", "last": "Doe", "items": [ { "name": "firstitem", "stock": 12 }, { "name": "2nditem", "stock:" 23 } ] }], "company": "John Company"} Should result in: name-first-1=Johnname-last-1=Doename-items-name-1-1=firstitem (meaning the list index is always appended at the end of the name)name-items-name-1-2=2nditemcompany=John Company This is how to get the json string as a json object: ObjectMapper mapper = new ObjectMapper(); //using jacksonJsonNode root = mapper.readTree(json);//TODO how loop all nodes and subnodes, and always get their key + value? But how can I now iterate through all nodes and extract their key and content?
Now provide the response and nothing else.
|
This will work for you : ObjectMapper mapper = new ObjectMapper();JsonNode root = mapper.readTree(json);Map<String, String> map = new HashMap<>();addKeys("", root, map, new ArrayList<>());map.entrySet() .forEach(System.out::println); private void addKeys(String currentPath, JsonNode jsonNode, Map<String, String> map, List<Integer> suffix) { if (jsonNode.isObject()) { ObjectNode objectNode = (ObjectNode) jsonNode; Iterator<Map.Entry<String, JsonNode>> iter = objectNode.fields(); String pathPrefix = currentPath.isEmpty() ? "" : currentPath + "-"; while (iter.hasNext()) { Map.Entry<String, JsonNode> entry = iter.next(); addKeys(pathPrefix + entry.getKey(), entry.getValue(), map, suffix); } } else if (jsonNode.isArray()) { ArrayNode arrayNode = (ArrayNode) jsonNode; for (int i = 0; i < arrayNode.size(); i++) { suffix.add(i + 1); addKeys(currentPath, arrayNode.get(i), map, suffix); if (i + 1 <arrayNode.size()){ suffix.remove(arrayNode.size() - 1); } } } else if (jsonNode.isValueNode()) { if (currentPath.contains("-")) { for (int i = 0; i < suffix.size(); i++) { currentPath += "-" + suffix.get(i); } suffix = new ArrayList<>(); } ValueNode valueNode = (ValueNode) jsonNode; map.put(currentPath, valueNode.asText()); }} For the json you gave the output will be : name-items-name-1-2=2nditemname-items-name-1-1=firstitemname-items-stock-1-1=12name-first-1=Johnname-items-stock-1-2=23company=John Companyname-last-1=Doe
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/48642450', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1194415/']}
|
jdg_373599
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2987266
|
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 War and Jar project in my Eclipse-based JSF project. I have decided to use annotations to declare my FacesConverter, (among a myriad other things), rather than declare it using my faces-config.xml. @FacesConverter(value="passwordFieldStringConverter")public class PasswordFieldStringConverter implements Converter { public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2) throws ConverterException { try { return arg2.getBytes("UTF-16BE"); } catch(UnsupportedEncodingException uee) { Assert.impossibleException(uee); } return(null); } public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2) throws ConverterException { try { return new String((byte[]) arg2, "UTF-16BE"); } catch(UnsupportedEncodingException uee) { Assert.impossibleException(uee); } return(null); }} And then I use passwordFieldStringConverter directly in my .xhtml: <?xml version="1.0" encoding="UTF-8" ?><html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:sec="http://www.springframework.org/security/facelets/tags"> <ui:composition> <f:view> <f:loadBundle basename="landingPage.bundle" var="bundle" /> <ui:decorate template="/WEB-INF/jsf_helpers/htmlShell.xhtml"> <ui:param name="PageTitleParam" value="#{bundle.pageTitle}" /> <h:form> <h:dataTable var="rowVar" value="#{userListContainer.users}"> <f:facet name="header"><h:outputText value="Users you are currently managing:" /></f:facet> <h:column> <f:facet name="header"> <h:outputText value="Screen Name" /> </f:facet> <h:outputText value="#{rowVar.screenName}" /> </h:column> <h:column> <f:facet name="header"> <h:outputText value="Password" /> </f:facet> <h:outputText value="#{rowVar.password}"> <f:converter converterId="passwordFieldStringConverter" /> </h:outputText> </h:column> </h:dataTable> </h:form> </ui:decorate> </f:view> </ui:composition></html> JSF is supposed to scan the jars in my War at deployment-time and detect which classes have annotations on them (and auto-configure the application accordingly). My problem is that JSF is apparently not detecting the classes I have which sport annotations. The War project has all of my .xhtml files as well as the project's faces-config.xml, my Jar project has all of my faces related Java code (action beans, managed beans, custom converters, etc.)
Now provide the response and nothing else.
|
Yes, I'm immediately answering my own question because I already spent a week banging my head on the table and I only figured out my problem after debugging through the JSF 2.0 RI (Mojarra) to see what it was doing. Basically, the annotation scanner only consults the WAR's /WEB-INF/classes .class files for annotations (assuming you have a faces-config.xml in /WEB-INF). If you keep your code in separate Jar files and want your .class files you have in /WEB-INF/lib .jar files to be scanned for annotations, you must have a faces-config.xml in that Jar's META-INF folder . The faces-config.xml you plop into your jar can be empty, it just needs to be there or else the annotation scanner will passover your jar like it was leftover meatloaf. Empty faces-config.xml: <?xml version="1.0" encoding="UTF-8"?><faces-config xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee /WEB-INF/schema/web-facesconfig_2_0.xsd" version="2.0" metadata-complete="false"> <!-- This file must be present with our jar, even if it is empty. Otherwise, our Java annotations won't get scanned! --></faces-config> I know a threw out a lot of -INF's there. So, just to recap. Your faces-config.xml in your War goes in WEB-INF. Your potentially empty, annotation scanner enabling, faces-config.xml in each of your Jar files goes in that Jar's META -INF. If you're wondering why the behavior has to be so nutty, it's because the JSF configs can be decentralized and scattered across 1st and 3rd party libraries this way. And if you're wondering about the whole presence of the faces-config.xml in a jar being a factor, well, my opinion is that that is what marks a Jar as interesting to the engine - and the absence of a faces-config.xml means the annotation scanner can avoid that jar and save on processing at deployment time. It just would have been nice if those scanner semantics were a little more clearly explained somewhere, <expletives deleted>! The following blog post was very useful in my understanding of what the code was doing: http://one-size-doesnt-fit-all.blogspot.com/2007/01/using-multiple-faces-configxml-files-in.html I really hope this saves someone from a week of pain like I had.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2987266', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/360064/']}
|
jdg_373600
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
20282054
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
When I use ngx.var.request_uri I'm getting back a string that contains %20 in place of spaces. Is there a urldecode() function or similar to decode my string?
Now provide the response and nothing else.
|
The decoded URI can be found in ngx.var.uri . It does not contain the query string, if you need it see ngx.var.query_string . EDIT: if you cannot use this, here is a simple way to unescape a URL in Lua. local hex_to_char = function(x) return string.char(tonumber(x, 16))endlocal unescape = function(url) return url:gsub("%%(%x%x)", hex_to_char)end Example usage: local url = "/test/some%20string?foo=bar"print(unescape(url)) -- /test/some string?foo=bar But you should probably split the query string before using it.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20282054', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/479947/']}
|
jdg_373601
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
216267
|
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:
Is there any difference between a directory name such as mydirectory and mydirectory/ I noticed this happens when I execute ls in some directories - some of the directory names have a slash and some don't. This is problematic because if I want to access a file contained in a directory, I may need to add a slash at the end: vi $mydirectory"/"$myfile or simply do vi $mydirectory$myfile
Now provide the response and nothing else.
|
Without / it might also be a file. In some situations it can be deadly. For example when using mv : mv file1 mydirectorymv file2 mydirectorymv file3 mydirectory All right? But if mydirectory did not exist or wasn't a directory, the final result is that file1 and file2 are gone and file3 is now named mydirectory . mv file1 mydirectory/mv file2 mydirectory/mv file3 mydirectory/ If mydirectory did not exist, all you get is three error messages and file1 , file2 and file3 are still there. So the / removes some ambiguity. Apart from that there aren't really any rules. Some programs may behave differently depending whether you supplied the / at the end or not. It's up to them what to make of it. In some cases you also get problems if you use too many / . For example find keeps surplus / in its output, which might trip you up if you try to find file/pathnames using simple string comparisons instead of, say, realpath or something.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/216267', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/117308/']}
|
jdg_373602
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
154919
|
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:
The other day I tried installing opencv-git from the AUR with makepkg on Arch Linux. Of course it pulls from the git repository as the name indicates. This pulls 1Gb. I am reading about making a shallow clone with git . When I look at the PKGBUILD file, using grep git PKGBUILD , I see: pkgname="opencv-git"makedepends=('git' 'cmake' 'python2-numpy' 'mesa' 'eigen2')provides=("${pkgname%-git}")conflicts=("${pkgname%-git}")source=("${pkgname%-git}::git+http://github.com/Itseez/opencv.git" cd "${srcdir}/${pkgname%-git}" git describe --long | sed -r 's/([^-]*-g)/r\1/;s/-/./g' cd "${srcdir}/${pkgname%-git}" cd "${srcdir}/${pkgname%-git}" cd "${srcdir}/${pkgname%-git}" install -Dm644 "LICENSE" "${pkgdir}/usr/share/licenses/${pkgname%-git}/LICENSE" Is there a way to modify the recipe or the makepkg command to pull only a shallow clone (the latest version of the source is what I want) and not the full repository to save space and bandwidth? Reading man 5 PKGBUILD doesn't provide the insight I'm looking for. Also looked quickly through the makepkg and pacman manpages - can't seem to find how to do that.
Now provide the response and nothing else.
|
This can be done by using a custom dlagent . I do not really understand Arch packaging or how the dlagents work, so I only have a hack answer, but it gets the job done. The idea is to modify the PKGBUILD to use a custom download agent. I modified the source "${pkgname%-git}::git+http://github.com/Itseez/opencv.git" into "${pkgname%-git}::mygit://opencv.git" and then defined a new dlagent called mygit which does a shallow clone by makepkg DLAGENTS='mygit::/usr/bin/git clone --depth 1 http://github.com/Itseez/opencv.git' Also notice that the repository that is being cloned is hard-coded into the command. Again, this can probably be avoided. Finally, the download location is not what the PKGBUILD expects. To work around this, I simply move the repository after downloading it. I do this by adding mv "${srcdir}/../mygit:/opencv.git" "${srcdir}/../${pkgname%-git}" at the beginning of the pkgver function. I think the cleaner solution would be to figure out what the git+http dlagent is doing and redfine that temporarily. This should avoid all the hack aspects of the solution.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/154919', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/-1/']}
|
jdg_373603
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
672602
|
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:
Imagine two persons ( A and B ) in a vacuum in outer space that are in front of each other and are not in motion. Say that suddenly A starts moving away with a constant velocity from B . In this case, would A or B be able to determine themselves in any way that A is the one who is actually moving and B is stationary? I think they can reach only one of the following conclusions but never know who was actually moving: A is moving and B is stationary. B is moving and A is stationary. A and B are both moving with some velocity from each other that could be equal or not.
Now provide the response and nothing else.
|
If A changes their velocity then you can say absolutely that A has accelerated, since acceleration is not a relative effect. That said, you still cannot say in any absolute sense who is moving, since all movement is relative. A is moving relative to B and B is moving relative to A - both statements hold true at the same time. Likewise, the concept of 'being stationary' only makes sense if you specify a reference frame relative to which something is motionless.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/672602', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/315871/']}
|
jdg_373604
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
317279
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm currently having a problem with a ShoppingCart for my customer. He wants to be able to add Text between the CartItems so I was wondering if there is some way to still only have one List. My solution would be to have two lists, one of type IList that gets iterated over when calculating Weight and overall Price of the Cart while having another IList that only exposes the necessary fields for displaying it in the ListView and that is a SuperType of CartItem. (But how do I then access additional fields for the listView, defaulting weight and price to 0 in the Description-Text-Class would break LSP). But having two lists somehow feels a bit odd (and still gives me problems), so I was wondering if I could do some sort of a TypedList where I specify the Type of each item. Any suggestions are welcome, I'm not really happy with both options.
Now provide the response and nothing else.
|
Use an interface: ICartListItem And make your list be: List<ICartListItem> Now, create several types, have all of them implement this interface, and you can store them all safely in your list. Alternatively, if you want there to be some default logic in a CartItem, use a base class instead of an interface.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/317279', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/21699/']}
|
jdg_373605
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
16470151
|
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 differences among PloneTestCase, plone.testing and plone.app.testing packages? By the way, is PloneTestCase not recommended for testing new Plone 4 products?
Now provide the response and nothing else.
|
PloneTestCase is an older product. It's still used by many packages, but it is more cumbersome, more error prone, and less well documented than plone.testing and plone.app.testing. plone.testing and plone.app.testing are complementary. The former implements low-level primitives that are not dependent on Plone-the-CMS for managing test layers and testing Zope applications. The latter provides the glue to set up a Plone site in an integration test. If you read the plone.app.testing docs, you should get everything you need.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16470151', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1750580/']}
|
jdg_373606
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4598702
|
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 approaches for changing the log4j log level dynamically, so that I will not have to redeploy the application. Will the changes be permanent in those cases?
Now provide the response and nothing else.
|
Changing the log level is simple; modifying other portions of the configuration will pose a more in depth approach. LogManager.getRootLogger().setLevel(Level.DEBUG); The changes are permanent through the life cyle of the Logger . On reinitialization the configuration will be read and used as setting the level at runtime does not persist the level change. UPDATE: If you are using Log4j 2 you should remove the calls to setLevel per the documentation as this can be achieved via implementation classes. Calls to logger.setLevel() or similar methods are not supported in the API. Applications should remove these. Equivalent functionality is provided in the Log4j 2 implementation classes but may leave the application susceptible to changes in Log4j 2 internals.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/4598702', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/177971/']}
|
jdg_373607
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
327414
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
It seems that outside of researchers in Mathematical Logic, mathematicians use almost exclusively bounded quantifiers instead of unbounded quantifiers. In fact, I haven't observed any other practice from the very first day on when I was a student. For example, a logician would write $\forall a : ( a \in \mathbb R ) \rightarrow ( a^2 \geq 0 )$ whereas most working analysists and algebraists write $\forall a \in \mathbb R : a^2 \geq 0$ On the other hand, most mathematicians I know accept the idea that all of mathematics can be built up from set-theoretical foundations alone (starting the natural numbers). So there seems to be a set of assumptions, almost universally agreed upon, which most working mathematicians assume implicitly for their practice. These assumptions start with set theory but apparently exclude unbounded quantifiers. In fact, unless you attend a class in formal logic you might never encounter unbounded quantifiers. It seems that most mathematicians use a subset of human language enhanced with a subset of mathematical language (avoiding universal quantifiers) as their working language. Question: Have there been attempts at precisely identifying this mathematical sublanguage and the rules that it governs?
Now provide the response and nothing else.
|
The most ambitious (and well-argued) attempt at formulating a set-theoretical foundation of the type you are proposing using bounded quantification has been suggested by non other than Saunders Mac Lane in the last chapter of his book Mathematics, Form and Function . Mac Lane dubbed his system ZBQC, which can be described as a weakening of Zermelo set theory in which the scheme of separation is limited to formulae with bounded quantification. Curiously, at the level of consistency strength, ZBQC is the only known lower bound to the consistency strength of Quine's system NF ; moreover, it is known that that the urelement-version, NFU, of NF (in which the axiom of infinity is included) is equiconsistent with ZBQC. On the other hand, Adrian Mathias has critically-and-forcefully responded to Mac Lane's thesis to found mathematics on ZBQC; see here for an article of his addressed to philosophers and general mathematicians, together with a response from Mac Lane; and here for an article addressed to logicians.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/327414', 'https://mathoverflow.net', 'https://mathoverflow.net/users/2082/']}
|
jdg_373608
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
53896184
|
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 having issues when trying to insert records from a database table into another database table, I wonder how to execute the query with one connection string while I have two different connection strings related to the two database, my code is shown below. SqlCommand insert = new SqlCommand();insert.Connection = conn2; // conn2 is the connection of the second databaseinsert.Parameters.Add("@Réf", SqlDbType.Int).Value = row["N° Caisse"];// row is a row of a datagridinsert.CommandText = "INSERT INTO Caisse([N° Caisse], [Date d'Ouverture], [Date de Clôture], [Fond de Caisse], [Vendeur]) SELECT * FROM Database1.Caisse WHERE Databse1.Caisse.[N° Caisse] = @Réf";// notice that both database have a table named "Caisse" so I'm inserting into 'Caisse of the second database the records selected from "Caisse" of the first tableconn2.Open();insert.ExecuteNonQuery();conn2.Close(); I get this error message : Invalid object name 'Database1.Caisse'. I am using Visual Studio WPF as IDE
Now provide the response and nothing else.
|
Short Answer You're assuming after this point: Stream<String> jFilter = strStream.filter(str -> str.startsWith("J")); That a new stream of the elements starting with "J" are returned i.e. only Java . However this is not the case; streams are lazy i.e. they don't perform any logic unless told otherwise by a terminal operation. The actual execution of the stream pipeline starts on the toArray() call and since the list was modified before the terminal toArray() operation commenced the result will be [Java, JavaScript, JQuery] . Longer Answer here's part of the documentation which mentions this: For well-behaved stream sources, the source can be modified before the terminal operation commences and those modifications will be reflected in the covered elements. For example, consider the following code: List<String> l = new ArrayList(Arrays.asList("one", "two")); Stream<String> sl = l.stream(); l.add("three"); String s = sl.collect(joining(" ")); First a list is created consisting of two strings: "one"; and "two". Then a stream is created from that list. Next the list is modified by adding a third string: "three". Finally the elements of the stream are collected and joined together. Since the list was modified before the terminal collect operation commenced the result will be a string of "one two three". All the streams returned from JDK collections, and most other JDK classes, are well-behaved in this manner;
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/53896184', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10435168/']}
|
jdg_373609
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
154157
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
I am aware that the following question is a very basic one and therefore I would not be at all offended if it were to be closed. Moreover, I am not familiar at all with category theory. Let $\mathcal{C}$ be a concrete category and $X$ be a free object of $\mathcal{C}$. If $Y_1$ and $Y_2$ are both free subobjects of $X$, then is the intersection, $Y_1 \cap Y_2,$ free?
Now provide the response and nothing else.
|
It's not in general true for the category of modules for a ring. For example, let $R=\mathbb{C}[x]/(x^2)$, let $X=R\oplus R$ be the free module on two generators, and let $Y_1$ and $Y_2$ be the submodules of $X$ generated by $(1,0)$ and $(1,x)$ respectively. Then $Y_1$ and $Y_2$ are both free modules on one generator, but $Y_1\cap Y_2$ is one-dimensional, spanned by $(x,0)$, and is not free.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/154157', 'https://mathoverflow.net', 'https://mathoverflow.net/users/15551/']}
|
jdg_373610
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
45351800
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to understand how multithreading works in Java. I understand the difference between Volatile and Synchronization . Volatile is about visibility and doesn't guarantee synchronization. When we are working with multithreading environments, each thread creates its own copy on a local cache of the variable they are dealing with. When this value is being updated, the update happens first in the local cache copy, and not in the real variable. Therefore, other threads are agnostic about the values that other threads are changing. And this is where volatile comes into picture. Volatile fields are immediately written through to main memory, and reads occur from main memory. Snippet from Thinking In Java - Synchronization also causes flushing to main memory, so if a field is completely guarded by synchronized methods or blocks, it is not necessary to make it volatile. It’s typically only safe to use volatile instead of synchronized if the class has only one mutable field. Again, your first choice should be to use the synchronized keyword—that’s the safest approach, and trying to do anything else is risky. But my question is, if in a synchronized block, a non volatile shared variable is being modified, will the other threads see the updated data ? (Since the variable in question is non volatile, other threads should read stale data from cache instead of main main memory) If the answer to the above question is NO , then can I conclude that everytime I use synchronization, I should ensure that shared variables must be marked volatile ? And if the answer is YES , then does that mean that I can always use synchronization instead of marking shared variables are volatile ? p.s: Before asking this question, I have read through lot of answers on StackOverflow and on other sites, but I couldn't find the answer to my question.
Now provide the response and nothing else.
|
To simplify a little: volatile only provides visibility: when you read a volatile variable you get two guarantees: (1) you see the latest write to the variable, even if it was performed in another thread and (2) all the writes before that volatile write are also visible. synchronized gives you visibility AND atomicity - thread observing the actions performed in a synchronized block from a synchronized block using the same monitor will either see all of them or none of them. So to answer your question, no, if a variable is written to within a synchronized block, you don't need to mark it volatile , provided that you always read that variable from a synchronized block using the same monitor. Here are a few examples with volatile: static class TestVolatile { private int i = 0; private volatile int v = 0; void write() { i = 5; v = 7; } void read() { //assuming write was called beforehand print(i); //could be 0 or 5 print(v); //must be 7 print(i); //must be 5 } void increment() { i = i + 1; //if two threads call the method concurrently //i could be incremented by 1 only, not 2: no atomicity }} And a few examples with synchronized : static class TestSynchronized { private int i = 0; private int j = 0; void write() { synchronized(this) { i = 5; j = 7; } } void read_OK() { synchronized(this) { //assuming write was called beforehand print(i); //must be 5 print(j); //must be 7 print(i); //must be 5 } } void read_NOT_OK() { synchronized(new Object()) { //not the same monitor //assuming write was called beforehand print(i); //can be 0 or 5 print(j); //can be 0 or 7 } } void increment() { synchronized(this) { i = i + 1; //atomicity guarantees that if two threads call the method //concurrently, i will be incremented twice } }}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45351800', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2556478/']}
|
jdg_373611
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
66607
|
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:
Well, this is a toughie -- though fairly simple. Does anyone have experience with board twist affecting your circuit? We have a board design that is supposed to measure a loadcell. We have finally tracked a system accuracy fault down to the amp IC. When we twist the board, the amp IC changes its output. _ Added RM: Circuit: Datasheet here Gain is 100,000 / R7 =~ 454.5 according to datasheet p15. I get +80mV when I twist the board from its 4 corners. I'm using the amount of twist that I use to unlock my car with my car key. I get -80mV when I twist the other way. The amount of twist is proportional to the variance in output voltage. Alternatively, if I put, say, typical pencil pressure on the top of the IC, I get +20mV. This is the most sensitive corner of the IC near pin 1. To isolate the amp circuit, I have shorted its input and disconnected other circuits from it so that what you see in the diagram is what we're testing with. I'm stuck. What physics principle would cause this? How can I prevent it? Notes: This is a system fault, not a single-board fault. It happens on all our boards. I have tried re-soldering the pins. That's not the problem. It isn't the gain resistor R7. I've put that on long leads to test its twist separately. Twisting it doesn't make any difference. The resistor R7 is 220 ohms which equals an amp gain of 456 The power supply rail, AVdd, measures steady at 3.29V The IC is the industry-standard AD623ARM (uSOIC package) For those who really must see it, here is the board -- though I'm afraid that it will raise more red herrings than answers:
Now provide the response and nothing else.
|
There are known effects like this that need to be taken into account for high precision circuits. Thermal gradients can also have adverse effects, component orientation across or along stress and thermal gradients etc. Of course we have to do some guessing because we can't magically know what is in the package. But an educated guess is that the die is either eutectic bonded or glued very rigidly to the bottom of the package cavity. A small SOIC package is very non compliant (i.e. rigid) so the stresses translate directly into the package die cavity floor and then through the die attach into the Si substrate. Stress can adversely affect Si performance by affecting the electron/hole mobility and Si has known piezo resistance (through similar effects of lattice changes). In fact Intel uses localized stress to increase the performance of PMOS transistors at some process nodes. In laying out precision circuits in silico it is recommended that sensitive amplifiers in Si not have metal layers over them so that the transistors are not adversely affected. (but here it is a matching issue). to test the hypothesis: I recommend desoldering the amplifier, and then attaching short stubs of PTH (resistor would work) leads to lift the package up off the PCB so the stress doesn't translate into the package. Once you've fiddled with this and re-fired it up. You should see a change and therefore a verification. USe the new "legs" as compliant members. Or use solder braid if you want to get really carried away. Solutions? a DIP version of the same part will have less of an issue because the leads are compliant. In that case using a compliant thermal compound under the package to get heat out might be used. You should also consider your board design as a contributing factor. Perhaps running stiffeners (in the existing design) as a test will help eliminate/study the issue. I'd epoxy stiffer pieces of FR4 (on edge) just to see.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/66607', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/22954/']}
|
jdg_373612
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3051407
|
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 found a statement that says $$\forall x[P(x) \rightarrow Q] \equiv \exists x[P(x)] \rightarrow Q$$ Where $Q$ is a formula that does not contain $x$ . I need to know when exactly would the equivalence hold. Can we just convert $\forall$ quantifiers to $\exists$ . Is there a way to prove the right hand side statement from the left hand side?
Now provide the response and nothing else.
|
I found a statement that says $$\forall x[P(x) \rightarrow Q] \equiv \exists x[P(x)] \rightarrow Q$$ Where $Q$ is a formula that does not contain $x$ . Correct. This is a true equivalence. Is there a way to prove the right hand side statement from the left hand side? Yes. And the other way around as well. See the other Answer. All equivalences in first-order logic can be proven, both mathematically, as well as using a first-order logic formal proof, if that's what you are asking. I need to know when exactly would the equivalence hold. Hmm, that's a bit of a weird question. The equivalence holds ... and as with mathematical results, it will therefore always hold. OK, but given your: Can we just convert $\forall$ quantifiers to $\exists$ . I assume you real question is: Are there other cases that are like this where we can change universal and existential quantifiers? Now, the first thing to note is that we are not just swapping quantifiers. Indeed, it does not hold that: $$\forall x[P(x) \rightarrow Q] \equiv \exists x[P(x) \rightarrow Q] \text{ WRONG!}$$ nor does it hold that: $$\forall x[P(x)] \rightarrow Q \equiv \exists x[P(x)] \rightarrow Q \text{ WRONG!}$$ Rather, it is the fact that we changed the scope of the quantifiers (that is, note how the square brackets get moved!) that makes the equivalence hold: $$\forall x[P(x) \rightarrow Q] \equiv \exists x[P(x)] \rightarrow Q \text{ Correct}$$ Indeed, simply converting existentials to universals will almost never hold true, since in general we do not have that $\forall x \ P(x) \equiv \exists x \ P(x)$ \forall. The only time where you can just swap existentials is where they don't do any work, i.e. where they are null quntifiers. An example of this is that: $$\forall x \ Q \equiv \exists x \ Q$$ where again $Q$ is a formula that does not contain $x$ (and even this equivalence only hold in logics that make the Assumption of Existential Import: that there is at least element in the domain) OK, so at this point your question really seems to become: are there other equivalences like: $$\forall x[P(x) \rightarrow Q] \equiv \exists x[P(x)] \rightarrow Q$$ where you swap quantifiers and change their scope? What are the conditions under which we can make, or cannot make, such a swap? Well, the relevant set of equivalences that I think you are really looking for are what are called the Prenex Laws. Here they are: Prenex Laws Where $x$ is not a free variable in $Q$ : $$ \forall x \ [P(x)] \land Q \Leftrightarrow \forall x [P(x) \land Q]$$ $$ \exists x \ [P(x)] \land Q \Leftrightarrow \exists x [P(x) \land Q]$$ $$ \forall x \ [P(x)] \lor Q \Leftrightarrow \forall x [P(x) \lor Q]$$ $$\exists x \ [P(x)] \lor Q \Leftrightarrow \exists x [P(x) \lor Q]$$ $$\forall x \ [Q] \rightarrow P(x) \Leftrightarrow \forall x [Q\rightarrow P(x)]$$ $$\exists x \ [Q] \rightarrow P(x) \Leftrightarrow \exists x [Q\rightarrow P(x)]$$ $$\exists x \ [P(x)] \rightarrow Q \Leftrightarrow \forall x [P(x) \rightarrow Q]$$ $$\forall x \ [P(x)] \rightarrow Q \Leftrightarrow \exists x [P(x) \rightarrow Q]$$ We recognize your equivalence as the seventh one down, though with the LHS and RHS swapped. It is a little more practical to represent the Laws like this, though, since in practice we often use the Prenex Laws to 'pull out' quantifiers and 'move them over' other logical operators. The Prenex Laws show that it is ok to change the scope of the quantifiers to include the formula $Q$ (where again, the important criterion is that $Q$ does not contain any free variables $x$ !), but that the quantifier swaps or stays the same depending on what operator we move the scope of the quantifier 'over'. Indeed, it turns out that your equivalence is a bit of an exception: the only time the quantifier gets swapped is if we move it over the consequent of a conditional (or put differently, if the quantifier in the LHS is the antecedent of a conditional). Finally, I would like to point out that there is not a corresponding Prenex law for biconditionals: there is no easy way to pull a quantifier 'over' a biconditional, and we can understand, given that the quantifier swaps when it is the antecedent of a conditional, but stays the same when it is the consequent. Indeed, if you want to pull out a quantifier when you have a biconditionals, you first have to rewrite the biconditionals as two conditionals, and then apply the two relevant Prenex laws for each of the conditionals (and, of course, pull them over the conjunction between them as well) Also, the last two Prenex Laws can be derived from the others (actually, from the first two you can derive all others, and same for the third and fourth; this might be a good exercise). Just doing yours: $$\exists x \ [P(x)] \rightarrow Q \Leftrightarrow$$ $$\neg \exists x \ [P(x)] \lor Q \Leftrightarrow$$ $$\forall x \ [\neg P(x)] \lor Q \Leftrightarrow$$ $$\forall x \ [\neg P(x) \lor Q] \Leftrightarrow$$ $$\forall x [P(x) \rightarrow Q]$$ You can make some intuitive sense of the Prenex Laws by observing that a universal can be seen as kind of conjunction, and an existential as a kind of existential. That is, if $a,b,c,...$ denote the objects in your domain, then you can think of universals and existentials like this: $$\forall x \: P(x) \approx P(a) \land P(b) \land P(c) \land ...$$ $$\exists x \: P(x) \approx P(a) \lor P(b) \lor P(c) \lor ...$$ I have to use $\approx$ here, because with different domains you would get different expressions, and so this is certainly not an equivalence! ... but again, intuitively you can make sense of them this way. And ... you can now give an informal proof of your equivalence as well: $$\exists x \ [P(x)] \rightarrow Q \Leftrightarrow \text{ (Implication)}$$ $$\neg \exists x \ [P(x)] \lor Q \Leftrightarrow \text{ (Quantifier Negation)}$$ $$\forall x \ [\neg P(x)] \lor Q \approx$$ $$(\neg P(a) \land \neg P(b) \land \neg P(c) \land ...) \lor Q \Leftrightarrow \text{ (Distribution)}$$ $$(\neg P(a) \lor Q) \land (\neg P(b) \lor Q) \land (\neg P(c) \lor Q) \land ... \Leftrightarrow \text{ (Implication)}$$ $$(P(a) \rightarrow Q) \land (P(b) \rightarrow Q) \land (P(c) \rightarrow Q) \land ... \approx$$ $$\forall x [P(x) \rightarrow Q] $$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3051407', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/111634/']}
|
jdg_373613
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17328742
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm using the chrome mobile browser on galaxy s4, android 4.2.2 and for some reason every time I scroll the page down, it fires a resize event verified by the scaling of images from a jquery.cycle2 slideshow. Any idea why this might be happening?
Now provide the response and nothing else.
|
Just for curiosity, I was trying to reproduce it and if I'm correct this is caused by the navigation chrome bar. When you scroll down and chrome hides the browser navigation bar it produces a window resize, but this is correct, because after that we have a bigger window size due to the free space that the browser nav bar has left. Related article: https://developers.google.com/web/updates/2016/12/url-bar-resizing Consider CWitty answer to avoid this behavior.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/17328742', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1543395/']}
|
jdg_373614
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
371961
|
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 are you supposed to unit test a web service in C# with Visual Studio 2008? When I generate a unit test it adds an actual reference to the web service class instead of a web reference. It sets the attributes specified in: http://msdn.microsoft.com/en-us/library/ms243399(VS.80).aspx#TestingWebServiceLocally Yet, it will complete without executing the test. I attempted to add the call to WebServiceHelper.TryUrlRedirection(...) but the call does not like the target since it inherits from WebService , not WebClientProtocol .
Now provide the response and nothing else.
|
What I usually do is not test directly against the web-service, but to try and put as little code as possible in the service, and call a different class which does all the real work. Then I write unit tests for that other class. It turns out that class can sometimes be useful outside of the web-service context, so this way - you gain twice.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/371961', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/42588/']}
|
jdg_373615
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
122107
|
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 is not possible to check out a single file. The finest level of checkouts you can do is at the directory level." How do I get around this issue when using Subversion? We have this folder in Subversion where we keep all our images. I just want to check out one file (image) from that. This folder is really big and has ton of other stuff which I don't need now.
Now provide the response and nothing else.
|
The simple answer is that you svn export the file instead of checking it out. But that might not be what you want. You might want to work on the file and check it back in, without having to download GB of junk you don't need. If you have Subversion 1.5+, then do a sparse checkout: svn checkout <url_of_big_dir> <target> --depth emptycd <target>svn up <file_you_want> For an older version of SVN, you might benefit from the following: Checkout the directory using a revision back in the distant past, when it was less full of junk you don't need. Update the file you want, to create a mixed revision. This works even if the file didn't exist in the revision you checked out. Profit! An alternative (for instance if the directory has too much junk right from the revision in which it was created) is to do a URL->URL copy of the file you want into a new place in the repository (effectively this is a working branch of the file). Check out that directory and do your modifications. I'm not sure whether you can then merge your modified copy back entirely in the repository without a working copy of the target - I've never needed to. If so then do that. If not then unfortunately you may have to find someone else who does have the whole directory checked out and get them to do it. Or maybe by the time you've made your modifications, the rest of it will have finished downloading...
|
{}
|
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/122107', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1175964/']}
|
jdg_373616
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
314512
|
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have: sleep 210m && for i in $(seq 1 5); do echo -e '\a'; sleep 0.5; done running as a simple, no-frills timer to remind me when something should be done. That sleep 210m is PID 25347. I'm trying to figure out how much time is left in the sleep. The best I've come up with, with me putting in the original sleep amount (210 minutes) is: $ echo "210 60 * $(ps -o etimes= 25347) - 60 ~ r n [:] P p" | dc78:11 (Explanation: First bit computes the number of seconds in the original sleep; the $(ps…) bit gets the time since sleep started in seconds, then the rest subtracts them and displays in minutes and seconds.) It occurs to me this would be useful in general; is there a better way to do this? Or at least a clever way to parse the sleep time from ps -o args ?
Now provide the response and nothing else.
|
Supporting GNU or Solaris 11 sleep arguments (one or more <double>[smhd] durations, so would also work with traditional implementations that support only one decimal integer number (like on FreeBSD), but not with those accepting more complex arguments like ISO-8601 durations ). Using etime instead of etimes as that's more portable (standard Unix). remaining_sleep_time() { # arg: pid ps -o etime= -o args= -p "$1" | perl -MPOSIX -lane ' %map = qw(d 86400 h 3600 m 60 s 1); $F[0] =~ /(\d+-)?(\d+:)?(\d+):(\d+)/; $t = -($4+60*($3+60*($2+24*$1))); for (@F[2..$#F]) { s/\?//g; ($n, $p) = strtod($_); $n *= $map{substr($_, -$p)} if $p; $t += $n } print $t'} (the s/\?//g is to get rid of the ? characters that procps ' ps uses as replacement for control characters. Without it, it would fail to parse sleep $'\r1d' or sleep $'\t1d' ... Unfortunately, in some locales, including the C locale, it uses . instead of ? . Not much we can do in that case as there's no way to tell a \t5d from a .5d (half day)). Pass the pid as argument. That also assumes the argv[0] passed to sleep doesn't contain blanks and that the number of arguments is small enough that it's not truncated by ps . Examples: $ sleep infinity & remaining_sleep_time "$!"Inf$ sleep 0xffp-6d &$ remaining_sleep_time "$!"344249$ sleep 1m 1m 1m 1m 1m & remaining_sleep_time "$!"300 For a [[[ddd-]HH:]MM:]SS output instead of just the number of seconds, replace the print $t with: $output = "";for ([60,"%02d\n"],[60,"%02d:"],[24,"%02d:"],[inf,"%d-"]) { last unless $t; $output = sprintf($_->[1], $t % $_->[0]) . $output; $t = int($t / $_->[0])}printf "%s", $output;
|
{}
|
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/314512', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/977/']}
|
jdg_373617
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6518
|
Below is a question asked on the forum skeptics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
According to a Reuters article California state senator Ted Lieu said: "If everyone knew the true dangers of tanning beds, they'd be shocked. Skin cancer is a rising epidemic and the leading cause of cancer death for women between 25 and 29." Edit: I read it wrong... It is just Cancer deaths. I still have difficulty believing that skin cancer is greater danger than leukemia, breast, or colon cancer.
Now provide the response and nothing else.
|
The CDC provides data files containing cancer statistics for the US that you can break down a number of ways. I downloaded the 1999-2007 file, took the BYAGE.txt file within it, replaced the tildes with zeroes (which is what they represent), and imported it into Excel (note, if you import into Excel 2003 or lower, you will hit the limit for maximum number of rows, so you'll need to remove some of the rows which are irrelevant for our purposes here). Putting it into a data table, I applied the following filters: AGE = 25-29 EVENT_TYPE = Mortality RACE = All Races SEX = Female And sorted by rate. You can download my spreadsheet . Having done so, I find that "Melanomas of the Skin" is well down the list. It varies year-by-year, but 9th is most common and the highest it gets it 7th in 2005 and 2007. Now, the results could be different if you're just looking at California, but xiaohouzi79's data suggest otherwise. Another factor is that there are a couple of other types of skin cancer - such as basal cell carcinomas and squamous cell cancer - but those are much less fatal than melanomas. Basically, it looks as though Lieu's statement was incorrect.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://skeptics.stackexchange.com/questions/6518', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/3126/']}
|
jdg_373618
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
49733027
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I know how to read the command line arguments, but I am having difficulties reading the command output from a pipe. Connect a program (A) that outputs data to my Rust program using a pipe: A | R The program should consume the data line by line as they come. $ pwd | cargo run should print the pwd output. OR $ find . | cargo run should output the find command output which is more than 1 line.
Now provide the response and nothing else.
|
Use BufRead::lines on a locked handle to standard input : use std::io::{self, BufRead};fn main() { let stdin = io::stdin(); for line in stdin.lock().lines() { let line = line.expect("Could not read line from standard in"); println!("{}", line); }} If you wanted to reuse the allocation of the String , you could use the loop form: use std::io::{self, Read};fn main() { let stdin = io::stdin(); let mut stdin = stdin.lock(); // locking is optional let mut line = String::new(); // Could also `match` on the `Result` if you wanted to handle `Err` while let Ok(n_bytes) = stdin.read_to_string(&mut line) { if n_bytes == 0 { break } println!("{}", line); line.clear(); }}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49733027', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3014263/']}
|
jdg_373619
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8149569
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to create a function in c which scans all my path C: \ temp (Windows) to search for a file that I pass (eg test.txt) and each time it finds one return the path to steps another function to write something in the bottom of this file.I managed to do the function that writes to the file but can not figure out how to do that scans the folder and pass the address of the file found.
Now provide the response and nothing else.
|
#include <unistd.h>#include <stdio.h>#include <dirent.h>#include <string.h>#include <sys/stat.h>#include <stdlib.h>void printdir(char *dir, int depth){ DIR *dp; struct dirent *entry; struct stat statbuf; if((dp = opendir(dir)) == NULL) { fprintf(stderr,"cannot open directory: %s\n", dir); return; } chdir(dir); while((entry = readdir(dp)) != NULL) { lstat(entry->d_name,&statbuf); if(S_ISDIR(statbuf.st_mode)) { /* Found a directory, but ignore . and .. */ if(strcmp(".",entry->d_name) == 0 || strcmp("..",entry->d_name) == 0) continue; printf("%*s%s/\n",depth,"",entry->d_name); /* Recurse at a new indent level */ printdir(entry->d_name,depth+4); } else printf("%*s%s\n",depth,"",entry->d_name); } chdir(".."); closedir(dp);}int main(){ printf("Directory scan of /home:\n"); printdir("/home",0); printf("done.\n"); exit(0);}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8149569', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1035523/']}
|
jdg_373620
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
26570132
|
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 practicing pointers by creating a Big Number struct, which has numDigits (number of digits) and digits (contents of the big number). I create a function called removeZero(). After passing the integer array and the size n into it, because of passing by reference, I am supposed to cut down the leading zeros for my input. It works, when the integer array is in main function. However, when I pass an array that is in readDigits, it does not return with a non-leading-zero version. Why? How to fix it? struct BigNum{ int numDigits; int *digits; //the content of the big num};int main(){ int A[] = {0,0,0,0,0,0,1,2,3}; int n=9; int *B=A; //removeZero(A,n); If I use this, it cannot compile //error: invalid initialization of non-const reference of type ‘int*&’ from an rvalue of type ‘int*’ removeZero(B,n); for (int i=0; i<n; i++){ std::cout << *(B+i) << std::endl; } BigNum *num = readDigits(); return 0;}BigNum* readDigits(){ std::string digits; std::cout << "Input a big number:" << std::endl; std::cin >> digits; //resultPt in heap or in stack? int *resultPt = new int[digits.length()]; //in heap int n = digits.length(); toInt(digits,resultPt); removeZero(resultPt,n); //Output the leading zeros, why? for (int i=0; i<n; i++){ std::cout << *(resultPt +i) << std::endl; } BigNum *numPtr = new BigNum(); numPtr->numDigits = n; numPtr->digits = resultPt; return numPtr;}void toInt(std::string& str, int *result){ for (int i=0;i<str.length() ;i++ ){ result[str.length()-i-1] = (int)(str[i]-'0'); }}void removeZero(int* &A,int& n){ int i=0; while (A[i]==0){ i++; } A=A+i; //memory leak? n=n-i;}bool areDigits(std::string num){ for(int i=0;i<num.length();i++){ if(num[i]<'0' || num[i] >'9'){ return false; } } return true;}
Now provide the response and nothing else.
|
It turned out that launch agent was configured to listen only 127.0.0.1 (or localhost).To fixed that edit jenkins agent's plist: nano /Users/admin/Library/LaunchAgents/homebrew.mxcl.jenkins.plist and modify httpListenAddress to 0.0.0.0 instead of 127.0.0.1 <?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs$<plist version="1.0"> <dict> <key>Label</key> <string>homebrew.mxcl.jenkins</string> <key>ProgramArguments</key> <array> <string>/usr/bin/java</string> <string>-Dmail.smtp.starttls.enable=true</string> <string>-jar</string> <string>/usr/local/opt/jenkins/libexec/jenkins.war</string> <string>--httpListenAddress=0.0.0.0</string> <string>--httpPort=8080</string> </array> <key>RunAtLoad</key> <true/> </dict></plist>
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/26570132', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3171335/']}
|
jdg_373621
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
29985158
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am new to NHibernate and C#, so please be gentle! I have the following two NHibernate entities: Employee{ private long _id; private String _name; private String _empNumber; private IList<Address> _addresses; //Properties...} and Address{ private long _id; private String _addrLine1; private String _addrLine2; private String _city; private String _country; private String _postalCode; //Properties} and they have a one-to-many relationship from Employee to Address (eachemployee can have multiple addresses in their record) . Conveniently ignoringthe fact that more than one employee may reside at the same address. I understand this from the perspective of objects in memory (the NHibernateentities). What I am struggling with are the mapping files (and I am taking aneasy example here). This is what I have come up with so far: // Intentionally left out XML and <hibernate-mapping> // Mappings for class 'Employee'. --><class name="Employee" table="Employees"> <id name="ID"> <generator class="native"> </id> <property name="Name" /> <property name="EmpNumber" /> <bag name="Addresses"> <key column="AddressId" /> <one-to-many class="Address" /> </bag></class> and // Intentionally left out XML and <hibernate-mapping> .// Mappings for class 'Address'<class name="Address" table="Addresses"> <id name="ID"> <generator class="native"> </id> // Intentionally left out name="Employee" // as I don't have corresponding field in Address entity. <many-to-one class="Employee" column="EmployeeID" cascade="all" /> <property name="AddrLine1" /> <property name="AddrLine2" /> <property name="City" /> <property name="Country" /> <property name="PostalCode" /></class> Is this correct? If not, it seems like what I am missing here is a field in the Address entity that is a reference to the corresponding Employee entity. But ifso, then I can't understand why this is required: I don't need to fetch an Address from an Employee , only the other way round...
Now provide the response and nothing else.
|
Just few hints, summarizing the most suitable standards I found out when working with NHibernate. 1) If there is a bi-directional reference in persitence (DB column) , express it in C# code bi-directional as well. Other words, if a child has reference to parent , parent should have reference to child . public class Employee{ ... public virtual IList<Address> { get; set; }}public class Address{ ... public virtual Employee Employee { get; set; }} This represents Business Domain as is. Address belongs to Employee and Employee belongs to Address. If we for some reasons really want to restrict that, we should rather protected modifier, but still keep the reference in C# 2) Use inverse="true" . This could be used only if we mapped both sides (as above), and will lead to more "expected and optimized" INSERT and UPDATE scritps Read more here: inverse = “true” example and explanation by mkyong 3) Use batch fetching mapping almost everwhere. That will avoid 1 + N issues during querying. Read more: few details about batch fetching 4) In case, that one object (in our case Employee) is root (the other does not make so much sense without it) - use cascading. Read more: nhibernate - Create child by updating parent, or create explicitly? Rules 2,3,4 in a mapping snippets: <class name="Employee" ... batch-size="25"> ... <bag name="Addresses" lazy="true" inverse="true" batch-size="25" cascade="all-delete-orphan" > // wrong! This columns is the same as for many-to-one //<key column="AddressId" /> // it is the one column expressing the relation <key column="EmployeeId" /> <one-to-many class="Address" /> </bag><class name="Address" ... batch-size="25"> ... <many-to-one not-null="true" name="Employee" column="EmployeeID" /> 3) if we use inverse="true do not forget to assign both sides of relation (mostly critical during creation) The reason is: we instruct NHibernate - the other side ( Address ) is responsible for persisting relation. But to do that properly, that Address needs to have reference to Employee - to be able to persist its ID into its column in Address table. So this should be the standard code to create new Address Employee employee = ... // load or create newAddress address = new Address { ... Employee = employee, // this is important};Employee.Addresses.Add(address);session.SaveOrUpdate(employee); // cascade will trigger the rest We can also introduce some method like AddAddress() which will hide this complexity, but setting both sides is a good prectice.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29985158', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/91933/']}
|
jdg_373622
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
32427
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
I am sorry for spamming MO with questions I have not thought about for more than 3 hours, but currently I am quite busy with preparing a talk on representations of $S_n$, and I don't want these to get lost. I hope this one is not quite as vague as the last one. This here is an attempt to generalize Exercise I.21 in Kraft-Procesi, Classical Invariant Theory . Let $K$ be a field - say, infinite, since we are going to do classical invariant theory. Let $K\left[\mathrm{SL}_n K\right]$ denote the $K$-algebra of polynomial functions on $\mathrm{SL}_n K$, which I define either as $\left\lbrace f\mid_{\mathrm{SL}_n K} \ \mid \ f\in K\left[\mathrm{M}_n K\right]\right\rbrace$ or as $K\left[\mathrm{M}_n K\right]\diagup \left(\det-1\right)$ (proving the equivalence of these two definitions is not the matter, it's rather easy - even easier than Kraft and Procesi try to make one believe). Now, the group $\mathrm{U}_n K$ of unipotent upper triangular matrices acts on $\mathrm{SL}_n K$ from the left. What is the invariant ring? It is easily seen that $\det\left(\text{the submatrix formed by the intersection of the rows }i,i+1,...,n\text{ with the columns }j,i+1,i+2,...,n\right)$ is an invariant for any $i\geq j$. These generate the fraction field of the invariants, but do they also generate the ring of the invariants itself? (The above-mentioned exercise is the above for $n=2$.) Arguments using Victorian age methods (as opposed to Zariski-topological or other algebro-geometrical) would be particularly preferred. EDIT: As Allen Knutson has pointed out, my question has a negative answer. However, the (larger) collection of determinants of the form $\det\left(\text{the submatrix formed by the intersection of the rows }i,i+1,...,n\text{ with the columns }j_1, j_2, ..., j_{n-i+1}\right)$ for $1 < i \leq n$ and $1 \leq j_1 < j_2 < ... < j_{n-i+1} \leq n$ does generate the ring of invariants. When $K$ has characteristic $0$, this can be proven using the standard theory of highest-weight modules and multiplicity-free algebras explained in Kraft-Procesi (see my errata, "Page 9, Exercise 21" for a proof). I am still wondering whether it holds for arbitrary $K$ and has a more elementary or combinatorial proof.
Now provide the response and nothing else.
|
No, they don't. $U_n(K)$ is performing upward row operations, so any $m\times m$ minor that uses the last $m$ rows will be $U_n(K)$-invariant, e.g. any single bottom entry. You won't be able to generate those linear functions using your higher-degree functions. (Victor's disproof is nice too!) What is true is that the invariant ring is generated by those $2^n-1$ many minors (corresponding to nonempty subsets of columns). One nice place to read about them is [Miller-Sturmfels], chapter 14, where they show e.g. that you can degenerate this invariant ring by replacing each minor by the product of its diagonal entries, obtaining the semigroup algebra of the cone of Gel'fand-Cetlin patterns.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/32427', 'https://mathoverflow.net', 'https://mathoverflow.net/users/2530/']}
|
jdg_373623
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
32839866
|
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 log every request that come to the my site with all the parameters and the time it need to generate the response. The site is build in Laravel 5. I did try different approaches but no luck. My main problem is in how to get the total execution time. Thanks
Now provide the response and nothing else.
|
You can use a Terminable Middleware to log the HTTP response after it has already been sent to the browser. To get the total time you can compare the result of microtime(true) with the laravel constant LARAVEL_START . That constant is defined at bootstrap/autoload.php , the entry point of the framework For instance, here is a middleware that will log in both HTTP headers and system log the response time. Since you have access to the current request in the $request variable you could leverage that to also log any parameters you want <?php // File: app/Http/Middleware/MeasureResponseTime.phpnamespace App\Http\Middleware;use Symfony\Component\HttpFoundation\Request;use Symfony\Component\HttpFoundation\Response;class MeasureResponseTime{ /** * Handle an incoming HTTP request. * * @param \Symfony\Component\HttpFoundation\Request $request * @param \Closure $next * @return \Symfony\Component\HttpFoundation\Response */ public function handle($request, \Closure $next) { $response = $next($request); // Add response time as an HTTP header. For better accuracy ensure this middleware // is added at the end of the list of global middlewares in the Kernel.php file if (defined('LARAVEL_START') and $response instanceof Response) { $response->headers->add(['X-RESPONSE-TIME' => microtime(true) - LARAVEL_START]); } return $response; } /** * Perform any final actions for the request lifecycle. * * @param \Symfony\Component\HttpFoundation\Request $request * @param \Symfony\Component\HttpFoundation\Response $response * @return void */ public function terminate($request, $response) { // At this point the response has already been sent to the browser so any // modification to the response (such adding HTTP headers) will have no effect if (defined('LARAVEL_START') and $request instanceof Request) { app('log')->debug('Response time', [ 'method' => $request->getMethod(), 'uri' => $request->getRequestUri(), 'seconds' => microtime(true) - LARAVEL_START, ]); } }}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32839866', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/661253/']}
|
jdg_373624
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12056068
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Possible Duplicate: How can I find the common ancestor of two nodes in a binary tree? first common ancestor of a binary tree I have a binary tree as below. I need to find the least common ancestor (LCA). e.g LCA of 6 and 4 is 1, LCA of 4 and 5 is 2. 1 / \ 2 3 / \ / \4 5 6 7 Can anyone please suggest how should I approach and solve this problem?
Now provide the response and nothing else.
|
Start with an ordinary depth-first search algorithm: public Node find(Node node, int target) { if(node == null || node.value == target) { return node; } if(node.value > target) { return find(node.left, target); } else { return find(node.right, target); }} Now, adapt this to take two "target" parameters, target1 and target2. When the search for target1 takes you left, and the search for target2 takes you right, you've found the LCA. This assumes that both targets actually do exist. If you need to assert that they do, you'll need to continue the search after finding the potential LCA. public Node findLca(Node node, int t1, int t2) { if(node == null) { return null; } if(node.value > t2 && node.value > t1) { // both targets are left return findLca(node.left, t1, t2); } else if (node.value < t2 && node.value < t1) { // both targets are right return findLca(node.right, t1, t2); } else { // either we are diverging or both targets are equal // in both cases so we've found the LCA // check for actual existence of targets here, if you like return node; }}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12056068', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1548650/']}
|
jdg_373625
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
924947
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $A$ be a bounded linear operator on the Banach space $X$. Assuming that $AK = KA$ for every compact operator $K$, how do I show that $A$ must be a scalar multiple of the identity, i.e., we have $A = \lambda I$ for some number $\lambda$. So far I attempt to solve this using Schur's lemma but I can't reason that $A$ will have an eigenvalue in the first place for the lemma to applies (the book where I got the problem from doesn't even specify if the field is real or complex). Any hint or help is highly appreciated.
Now provide the response and nothing else.
|
I think we can just play around with some special compact operators, unless I'm missing some subtlety. If $x$ and $y$ are linearly independent, then their span is complemented in $X$, so that $X \cong span\{x, y\} \oplus V$ for some closed subspace $V$ of $X$. The projection $P$ along $V$ onto $span\{x, y\}$ is then bounded. Define a map $B: P(X) \rightarrow X$ that swaps $x$ with $y$ and extend by linearity. Then $K_{x,y} = BP$ is continuous and of finite rank (since its image lives in $P(X)$). So it's compact. [I've suppressed in the notation the fact that $K_{x,y}$ depends on a choice of complementary subspace $V$.] Claim: If there's an $x$ such that $Ax = \lambda x$, then $A=\lambda I$. Proof: If $x$ and $y$ are linearly independent with $x$ as above, then we have $$Ay=A(K_{x,y}x)=K_{x,y}(Ax)=K_{x,y}(\lambda x)=\lambda y.$$ Now suppose, by contradiction, that we can find an $x$ such that $x$ and $Ax$ are linearly independent (i.e. $x$ is not an eigenvector for $A$). Then we must have $$x = K_{x, Ax}(Ax) = A(K_{x, Ax}x) = A(Ax)=A^2x,$$ so $x+Ax$ is an eigenvector for $A$. But by our claim, if $A$ has an eigenvector, then $A=\lambda I$, contradicting linear independence of $x$ and $Ax$. So all vectors are eigenvectors, and, by our claim, $A=\lambda I$ for some $\lambda$.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/924947', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/113988/']}
|
jdg_373626
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12899548
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Possible Duplicate: Does unicode or HTML have a vertical double guillemet (chevron)? Is there a downwards facing alternative to « and » ( « and » respectively)? I have tried to find an answer elsewhere but to no avail. I assume css rotating the text is the only real answer.
Now provide the response and nothing else.
|
The short answer to your question is "No, there aren't." « and » are not actually intended as direction arrows, despite their frequent usage as such. What they are actually intended for is hinted at by their entity names -- they're supposed to be "angled quotes". Certain European countries (notably France) tend to use these characters for speech marks instead of the inverted-comma style quote marks that are more commonly used by the English speaking world, and that is what these characters are actually meant for -- see http://en.wikipedia.org/wiki/Guillemet for more info. Given this, it's hardly surprising that there aren't any up and down arrow variants of them. Feel free to use them as directional arrows (everyone else does, even if the semantics are questionable), but don't expect them to have every variant you might want, because they're not graphics; they're typographical characters. I guess if you really want to, you could use CSS to rotate the existing left and right arrows by 90 degrees. I wouldn't suggest it as a good idea though.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12899548', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/504299/']}
|
jdg_373627
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12476302
|
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 query data from sqlite db through CursorLoader. When i go through the documentation in android developer website, i can't find the limit query. CursorLoader(Context context, Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) How can i implement limit in CursorLoader? Thanks in Advance
Now provide the response and nothing else.
|
The hackish way: String sortOrder = "ROWID LIMIT 5" which will result in ORDER BY ROWID LIMIT 5 . ROWID would sort by the implicit row ids that SQLite keeps - very close to what happens when you don't specify a sort oder at all.Not that this is abusing the fact that the order parameter does not check if the supplied value is just a valid order type. Kind of a buffer overflow attack. A better way would be to define Uri parameters. // query codeUri queryUri = Uri.parse("content://what/ever/items");queryUri = queryUri.buildUpon().appendQueryParameter("limit", "5").build();// in ContentProviderString limit = queryUri.getQueryParameter("limit"); Both approaches will only work if the ContentProvider is compatible with above attempts to limit. There is actually no well-defined way to limit or select certain data from a ContentProvider . Each ContentProvider comes with it's own contract so above will not work with every provider.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12476302', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/873999/']}
|
jdg_373628
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3469116
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The question was "If a 52 card deck is split into 13 piles of 4 cards each. What is the expected value of piles with 4 cards of the same suit?" I thought perhaps this was a problem with the tower rule (Law of Total Expectation)E(X) = E(E(X|Y)) But there seems to be no "given" scenario in the problem. I answered with $(13+12+11+10+9+8+7+6+5+4+3+2+1)*P($ 4 cards of the same suit $)$ or $(13+12+11+10+9+8+7+6+5+4+3+2+1)*(1*\frac{12}{51}*\frac{11}{50}*\frac{10}{49}$ But it seemed far too simple. I am not quite sure how to account for the following probabilities, i.e. assuming the first deck is all hearts, what about the next being all hearts or all spades/clubs/diamonds. How would one take these variables into account?
Now provide the response and nothing else.
|
I guess by the "Cartesian product" you mean the product as sets. There is the canonical map (of schemes) from $X\times_{\operatorname{Spec}{\mathbb Z}}Y$ to $X$ , which can be viewed as a map of the underlying sets. Same for the map from $X\times_{\operatorname{Spec}{\mathbb Z}}Y$ to $Y$ . These two maps then gives a map of sets $f:X\times_{\operatorname{Spec}{\mathbb Z}}Y\rightarrow X\times Y$ . However, the map $f$ is in general neither injective nor surjective. This is easily seen from the following examples: $X = \operatorname{Spec}\mathbb Z[x]$ , $Y = \operatorname{Spec}\mathbb Z[y]$ , $X\times_{\operatorname{Spec}{\mathbb Z}}Y = \operatorname{Spec}\mathbb Z[x, y]$ . The map $f$ is then not injective: the image of the prime ideal $(x + y)$ is the same as the image of the prime ideal $(0)$ . $X = \operatorname{Spec}\mathbb Z/2\mathbb Z$ , $Y = \operatorname{Spec}\mathbb Z/3\mathbb Z$ , $X\times_{\operatorname{Spec}{\mathbb Z}}Y = \operatorname{Spec}0$ . The map $f$ is then obviously not surjective, since $X\times_{\operatorname{Spec}{\mathbb Z}}Y$ is empty as a set.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3469116', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/733167/']}
|
jdg_373629
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
38738785
|
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 with the VizFrame control of the SAPUI5 Framework. I want to display some data in an complex chart with two Y-axes. My data model looks like this: { "d" : { "results" : [ { "DataA" : "2", "DataB" : "4", "Id" : "1", }, { "DataA" : "3", "DataB" : "2", "Id" : "2", } ] }} I tried to display DataA on the left Y-Axis and DataB on the right one, while using the Id for the X-Axis. This works without problems with the VizFrame types: dual_line and dual_column . I havent found a way to display the data as a bar (DataA on Y1) and line (DataB on Y2). My current coding looks like this: var oModel = new sap.ui.model.json.JSONModel(); oModel.loadData("data.json"); var oDataset = new sap.viz.ui5.data.FlattenedDataset({ dimensions: [{ axis : 2, name : oLocText.getText('Id'), value : "{Id}" }], measures : [{ group : 1, name : DataA, value : '{DataA}' },{ group : 2, name: DataB, value: '{DataB}' }], data : { path : "/d/results" } }); oVizFrame.setDataset(oDataset); oVizFrame.setModel(oModel); oVizFrame.setVizType('combination'); oVizFrame.setVizProperties({ title: { visible: true, text: "Combined" }, plotArea: { colorPalette : d3.scale.category20().range(), }}); var feedValueAxis = new sap.viz.ui5.controls.common.feeds.FeedItem({ 'uid': "primaryValues", 'type': "Measure", 'values': [ DataA , DataB] }), feedCategoryAxis = new sap.viz.ui5.controls.common.feeds.FeedItem({ 'uid': "axisLabels", 'type': "Dimension", 'values': [ Id] }); oVizFrame.addFeed(feedValueAxis); oVizFrame.addFeed(feedCategoryAxis); Thank you very much for your help!
Now provide the response and nothing else.
|
Nothing is magic in the life : if you update a value, your Observable won't be notified. You have to do it by yourself. For example using a PublishSubject . public class Test extends MyChildActivity { private int VARIABLE_TO_OBSERVE = 0; Subject<Integer> mObservable = PublishSubject.create(); protected void onCreate() {/*onCreate method*/ super(); setContentView(); method(); changeVariable(); } public void changeVariable() { VARIABLE_TO_OBSERVE = 1; // notify the Observable that the value just change mObservable.onNext(VARIABLE_TO_OBSERVE); } public void method() { mObservable.map(value -> { if (value == 1) doMethod2(); return String.valueOf(value); }).subScribe(string -> System.out.println(string)); } public void doMethod2() {/*Do additional operations*/} }
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/38738785', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4532833/']}
|
jdg_373630
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4440594
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Just curious, they sound similar. What are the differences between ExecuteCore() vs OnActionExecuting(ActionExecutingContext filterContext)? In what situations would one be more useful over the other?
Now provide the response and nothing else.
|
Actually, they're just different points in MVC execution pipeline. ExecuteCore is called byMvcHandler after controller itselfis instantiated. By this moment MVCdoesn't even know about howcontroller will invoke its action.You can override standardController's ExecuteCore to tweakits overall execution process alittle bit. OnActionExecuting is a completelydifferent story. It is called duringaction filters invocation byControllerActionInvoker. By thatpoint MVC already knows that actionexists, invokes it, obtains allfilters (usually defined asattributes) and executes it in agiven moment of overall executionpipeline (OnActionExecuting,OnActionExecuted, OnResultExecutingand so on). It depends on what exactly you want to achieve when deciding what extension point to use. Override ExecuteCore in derivedController to tweak its commonbehavior (not really often the casein normal app). Use filters toperform some additional tasks thatseem orthogonal to what acion itselfis supposed to do (often this is someAOP-like logic or relates to database session/transaction management).
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4440594', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61320/']}
|
jdg_373631
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
43224410
|
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 facebook-android-sdk:4.20.+ and com.android.support libraries which are conflicting with error message: All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes). Found versions 25.2.0, 25.0.0. Examples include com.android.support:animated-vector-drawable:25.2.0 and com.android.support:customtabs:25.0.0 less... (⌘F1) There are some combinations of libraries, or tools and libraries, that are incompatible, or can lead to bugs. One such incompatibility is compiling with a version of the Android support libraries that is not the latest version (or in particular, a version lower than your targetSdkVersion.) Following are my dependencies. dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) compile files('libs/YouTubeAndroidPlayerApi.jar') compile 'com.android.support:appcompat-v7:25.2.0' compile 'com.android.support:customtabs:25.0.0' compile 'com.android.support:design:25.+' compile 'com.android.support:cardview-v7:25.+' compile 'com.android.support:recyclerview-v7:25.+' compile 'com.fasterxml.jackson.core:jackson-core:2.7.4' compile 'com.fasterxml.jackson.core:jackson-annotations:2.7.4' compile 'com.fasterxml.jackson.core:jackson-databind:2.7.4' compile 'org.jsoup:jsoup:1.8.3' compile 'com.github.bumptech.glide:glide:3.7.0' compile 'com.squareup.picasso:picasso:2.5.2' compile 'com.android.support.constraint:constraint-layout:1.0.2' compile 'commons-io:commons-io:2.4' compile 'com.google.android.gms:play-services-analytics:10.0.1' compile 'com.facebook.android:facebook-android-sdk:4.+' testCompile 'junit:junit:4.12'} On running a gradle dependency report using: ./gradlew -q dependencies app:dependencies --configuration compile , following are the results for facebook-android-sdk . +--- com.facebook.android:facebook-android-sdk:4.+ -> 4.20.0| +--- com.android.support:support-v4:25.0.0 -> 25.2.0 (*)| +--- com.android.support:appcompat-v7:25.0.0 -> 25.2.0 (*)| +--- com.android.support:cardview-v7:25.0.0 -> 25.2.0 (*)| +--- com.android.support:customtabs:25.0.0| | +--- com.android.support:support-compat:25.0.0 -> 25.2.0 (*)| | \--- com.android.support:support-annotations:25.0.0 -> 25.2.0| \--- com.parse.bolts:bolts-android:1.4.0| +--- com.parse.bolts:bolts-tasks:1.4.0| \--- com.parse.bolts:bolts-applinks:1.4.0| \--- com.parse.bolts:bolts-tasks:1.4.0 What is the right combination of dependencies that I must use?
Now provide the response and nothing else.
|
In your specific case the problem is because the facebook sdk has a dependency with com.android.support:customtabs:25.0.0 and that version is old and your current version of the support library is 25.2.0 . As you can see on the dependency graph the newer versions of cardview-v7, appcompat-v7 and support-v4 are already being used, so you can try adding: compile 'com.android.support:customtabs:25.2.0' to the dependencies so that the newer version of customtabs is used also by the facebook sdk. This answer could be useful also: Gradle error after including facebook sdk
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43224410', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6193126/']}
|
jdg_373632
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
24471109
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Has anyone using RecyclerView found a way to set an onClickListener to items in the RecyclerView ?I thought of setting a listener to each of the layouts for each item but that seems a little too much hassleI'm sure there is a way for the RecyclerView to listen for the onClick event but I can't quite figure it out.
Now provide the response and nothing else.
|
As the API's have radically changed, It wouldn't surprise me if you were to create an OnClickListener for each item. It isn't that much of a hassle though. In your implementation of RecyclerView.Adapter<MyViewHolder> , you should have: private final OnClickListener mOnClickListener = new MyOnClickListener();@Overridepublic MyViewHolder onCreateViewHolder(final ViewGroup parent, final int viewType) { View view = LayoutInflater.from(mContext).inflate(R.layout.myview, parent, false); view.setOnClickListener(mOnClickListener); return new MyViewHolder(view);} The onClick method: @Overridepublic void onClick(final View view) { int itemPosition = mRecyclerView.getChildLayoutPosition(view); String item = mList.get(itemPosition); Toast.makeText(mContext, item, Toast.LENGTH_LONG).show();}
|
{}
|
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/24471109', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1354811/']}
|
jdg_373633
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
202773
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
I have a rather soft question. Let's assume that we consider the heat equation posed in $S^1$:$$\partial_t u=\partial_x^2u.$$It is well known that if we define the functionals$$H(t)=\int_{-\pi}^\pi u\log(u)-u+1dx,$$$$E(t)=\int_{-\pi}^\pi u^2dx,$$they decay. As far as I know, in the literature, a functional similar to $H$ is called entropy while a functional like $E$ is called energy . I understand the physical reasons behind that. The question is: are there some subtle mathematical differences between these two Lyapunov functionals that we emphasize by using different names entropy/energy? Or, on the other hand, it's just a reminder from the physical origin of both terms?
Now provide the response and nothing else.
|
First, note that entropy is well-defined only if $u$ is positive. Using integration by parts, it is in fact true on the flat torus or $\mathbb{R}^n$ (if $u$ is nonnegative and decays in space fast enough) that$$\frac{\partial}{\partial t}\frac{1}{p(p-1)}\log \int u^p = -\frac{\int u^{p-2}|\nabla u|^2}{\int u^p}\le 0$$for all $p > 1$. The case $p = 2$ is the usual $L^2$ energy inequality. If you normalize $u$ so that$$\int u = 1$$and take the limit $p \rightarrow 1$, you get the entropy inequality. So there are $L^p$ analogues of energy or entropy, depending on your point of view. In information theory, if $u$ is a probability density, then$$-\int u\log u$$is called Shannon entropy and$$\frac{1}{1-p}\log\int u^p$$is called Rényi entropy.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/202773', 'https://mathoverflow.net', 'https://mathoverflow.net/users/33135/']}
|
jdg_373634
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1235534
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
On our mailing application we are sending emails with the following header: FROM: marketing@customer.comTO: subscriber1@domain1.exampleReturn-PATH: bouncemgmt@ourcompany.example The problem that we are facing is that some email servers will bounce back a message immediately and use the from or reverse path ( marketing@customer.example ) instead to our bounce mgmt server. We want to know if we modify in the header the reply-to to be the same as the return-path if we will be able to catch all bounces. Any other ideas are welcome? We are using the following documents as references: VERP RFC Bounce Messages SMTP Log Parsing to get Bounces EDIT 1: A few more bits of information to see if we can get this resolve. We want to know at what point the email server relaying the message will choose to use the reply-to versus the return-path. We have notice that when the first SMTP server relaying the message gets rejected it sends it to the reply-to, but when it happens after one hop it sends it to the return-path.
Now provide the response and nothing else.
|
Let's start with a simple example. Let's say you have an email list, that is going to send out the following RFC2822 content. From: <coolstuff@mymailinglist.example>To: <you@example.com>Subject: Super simple emailReply-To: <coolstuff-threadId=123@mymailinglist.example>This is a very simple body. Now, let's say you are going to send it from a mailing list, that implements VERP (or some other bounce tracking mechanism that uses a different return-path). Lets say it will have a return-path of coolstuff-you=yourcompany.com@mymailinglist.example . The SMTP session might look like: {S}220 workstation1 Microsoft ESMTP MAIL Service{C}HELO workstation1{S}250 workstation1 Hello [127.0.0.1]{C}MAIL FROM:<coolstuff-you=yourcompany.com@mymailinglist.example>{S}250 2.1.0 me@mycompany.com....Sender OK{C}RCPT TO:<you@example.com>{S}250 2.1.5 you@example.com{C}DATA{S}354 Start mail input; end with <CRLF>.<CRLF>{C}From: <coolstuff@mymailinglist.example>To: <you@example.com>Subject: Super simple emailReply-To: <coolstuff-threadId=123@mymailinglist.example>This is a very simple body..{S}250 Queued mail for delivery{C}QUIT{S}221 Service closing transmission channel Where {C} and {S} represent Client and Server commands, respectively. The recipient's mail would look like: Return-Path: coolstuff-you=yourcompany.com@mymailinglist.exampleFrom: <coolstuff@mymailinglist.example>To: <you@example.com>Subject: Super simple emailReply-To: <coolstuff-threadId=123@mymailinglist.example>This is a very simple body. Now, let's describe the different "FROM"s. The return path (sometimes called the reverse path, envelope sender, or envelope from — all of these terms can be used interchangeably) is the value used in the SMTP session in the MAIL FROM command. As you can see, this does not need to be the same value that is found in the message headers. Only the recipient's mail server is supposed to add a Return-Path header to the top of the email. This records the actual Return-Path sender during the SMTP session. If a Return-Path header already exists in the message, then that header is removed and replaced by the recipient's mail server. All bounces that occur during the SMTP session should go back to the Return-Path address. Some servers may accept all email, and then queue it locally, until it has a free thread to deliver it to the recipient's mailbox. If the recipient doesn't exist, it should bounce it back to the recorded Return-Path value. Note, not all mail servers obey this rule; Some mail servers will bounce it back to the FROM address. The FROM address is the value found in the FROM header. This is supposed to be who the message is FROM. This is what you see as the "FROM" in most mail clients. If an email does not have a Reply-To header, then all human (mail client) replies should go back to the FROM address. The Reply-To header is added by the sender (or the sender's software). It is where all human replies should be addressed too. Basically, when the user clicks "reply", the Reply-To value should be the value used as the recipient of the newly composed email. The Reply-To value should not be used by any server. It is meant for client-side (MUA) use only. However, as you can tell, not all mail servers obey the RFC standards or recommendations. Hopefully this should help clear things up. However, if I missed anything, let me know, and I'll try to answer.
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/1235534', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/47222/']}
|
jdg_373635
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1214629
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have this code. byte dup = 0;Encoding.ASCII.GetString(new byte[] { (0x80 | dup) }); When I try to compile I get: Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?) Why does this happen? Shouldn't | two bytes give a byte? Both of the following work, assuring that each item is a byte. Encoding.ASCII.GetString(new byte[] { (dup) });Encoding.ASCII.GetString(new byte[] { (0x80) });
Now provide the response and nothing else.
|
It's that way by design in C#, and, in fact, dates back all the way to C/C++ - the latter also promotes operands to int , you just usually don't notice because int -> char conversion there is implicit, while it's not in C#. This doesn't just apply to | either, but to all arithmetic and bitwise operands - e.g. adding two byte s will give you an int as well. I'll quote the relevant part of the spec here: Binary numeric promotion occurs for the operands of the predefined +, –, *, /, %, &, |, ^, ==, !=, >, <, >=, and <= binary operators. Binary numeric promotion implicitly converts both operands to a common type which, in case of the non-relational operators, also becomes the result type of the operation. Binary numeric promotion consists of applying the following rules, in the order they appear here: If either operand is of type decimal, the other operand is converted to type decimal, or a compile-time error occurs if the other operand is of type float or double. Otherwise, if either operand is of type double, the other operand is converted to type double. Otherwise, if either operand is of type float, the other operand is converted to type float. Otherwise, if either operand is of type ulong, the other operand is converted to type ulong, or a compile-time error occurs if the other operand is of type sbyte, short, int, or long. Otherwise, if either operand is of type long, the other operand is converted to type long. Otherwise, if either operand is of type uint and the other operand is of type sbyte, short, or int, both operands are converted to type long. Otherwise, if either operand is of type uint, the other operand is converted to type uint. Otherwise, both operands are converted to type int. I don't know the exact rationale for this, but I can think about one. For arithmetic operators especially, it might be a bit surprising for people to get (byte)200 + (byte)100 suddenly equal to 44 , even if it makes some sense when one carefully considers the types involved. On the other hand, int is generally considered a type that's "good enough" for arithmetic on most typical numbers, so by promoting both arguments to int , you get a kind of "just works" behavior for most common cases. As to why this logic was also applied to bitwise operators - I imagine this is so mostly for consistency. It results in a single simple rule that is common for all non-boolean binary types. But this is all mostly guessing. Eric Lippert would probably be the one to ask about the real motives behind this decision for C# at least (though it would be a bit boring if the answer is simply "it's how it's done in C/C++ and Java, and it's a good enough rule as it is, so we saw no reason to change it").
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1214629', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/52622/']}
|
jdg_373636
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
10499435
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Why does this work: $('.button_30').click(function(){ $(this).closest('.portlet').find('.portlet_content').text("foo");}); any why does this not work: $('.button_30').click(function(){ $(this).parent('.portlet').find('.portlet_content').text("foo");}); where the html looks something like this: <div class="portlet portlet_30"> <div class="portlet_header portlet_header_30"> header content here </div> <div class="portlet_sub_header portlet_sub_header_30"> <input type="text" class="textbox_30" /> </div> <div class="portlet_content portlet_content_30"> results go here </div> <div class="portlet_footer portlet_footer_30"> <input type="button" class="button_30" /> </div></div><div class="portlet portlet_30"> <div class="portlet_header portlet_header_30"> header content here </div> <div class="portlet_sub_header portlet_sub_header_30"> <input type="text" class="textbox_30 /> </div> <div class="portlet_content portlet_content_30"> results go here </div> <div class="portlet_footer portlet_footer_30"> <input type="button" class="button_30" /> </div></div>
Now provide the response and nothing else.
|
Because parent() will return the parent (immediate ancestor) only if it matches the selector specified. However, closest() will search all ancestors and return the first one that matches the selector. As the parent of button_30 is a div , whose parent is the div with the class of portlet , the parent() function is not matching it and returning an empty set, where-as closest() is matching it. To complete the set of similar methods here you have parents() , which is like closest() but doesnt stop at the first matched element; it returns all ancestors which match the selector.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10499435', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/364312/']}
|
jdg_373637
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2810020
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Me and my colleagues got into this discussion early this morning, and our opinions started to clash a bit, so I decided to get some impartial advice here. One of my colleagues reckons that the DAO should return an object (populated bean). I think it's completely fine when you're returning a recordset with only one line, but think it's overkill if you have to return 10 lines, and create 10 separate objects. I on the other see that the difference between DAO and Gateway pattern is that the gateway pattern will allow you to return a recordset to your business class, which will therefore deal with the recordset data and do whatever it needs to do. My questions here are: Which assumptions are correct? What should the return type be for aDAO (i.e. getContact() - for one record) Should getContacts() (for multiple records) even be on theDAO, if so, what's it's returntype? We seem to be having some sort of confusion about DAO and Gateway Patterns. Should they be used together? Thanks in advance
Now provide the response and nothing else.
|
The gateway pattern is concerned with providing a single point of access for a system or subsystem. The DAO pattern is a specific type of gateway - it provides the sole means of getting a particular type of data from the data store. I'll answer the questions directly, here and expand upon the answers below. 1. Which assumptions are correct. The DAO patten is concerned with hiding the details of fetching entities and queries over entities. Returning a recordset that is directly tied to the persistence mechanism is generally not a good idea since it breaks the abstraction. By keeping the DAO storage-agnostic, testing is much simpler - it is then possible to mock the DAO interface using for example a simple in-memory implementation based on test data stored in collections. 2. What should the return type be for a DAO (i.e. getContact() - for one record) The return type should be Contact bean. As you add attributes to the contact, only the Contact class needs to change - the DAO interface stays the same. 3. Should getContacts() (for multiple records) even be on the DAO, if so, what's it's returntype? I put query methods alongside other DAO methods - I don't really see a distinction. Multiple contacts can be returned as a List or appropriate Collection of Contact beans. The debate about returning objects or just the needed values is one of extensible design and performance. The default choice should be to return Beans. Most ORM mappers and even JDBC access layers make creating objects relatively lightweight (modern JVMs can create a new object in under 10 CPU instructions), and it is by far the best design choice, and will evolve easily. Returning non-object results, such as a list of CustomerIDs is a possibility, but should be taken when there is clear evidence that it is necessary. Performance is usually the motivating factor, and so the design should be backed up with profiling evidence. Otherwise this is likely to be sacrificing good design in favor of premature optimization. Extending a design that returns non-object data can be difficult - say you want now to return the customer ID and the last order date. If you are returning data as rows and primitive types, then the shape of the return type is going to change, typically requiring the methods on the DAO interface and implementation to change, and all clients that use them. With a bean, related data can be fetched without changing the shape of the data - assuming the related data is available starting from the bean already being returned. The beans do not need to be fully populated. ORM mappers tend to lazily fetch related objects and collections, so you take the performance hit for what just what you retrieve. To sum up, while it is possible to have a mix of methods returning bean and non-bean results, I would steer away from the non-bean results unless there is a compelling reason to do so. And do so with awareness of the maintainance issues this may cause.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2810020', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/279395/']}
|
jdg_373638
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17678881
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
My application has a dark background, but in iOS 7 the status bar became transparent. So I can't see anything there, only the green battery indicator in the corner. How can I change the status bar text color to white like it is on the home screen?
Now provide the response and nothing else.
|
Set the UIViewControllerBasedStatusBarAppearance to YES in the .plist file. In the viewDidLoad do a [self setNeedsStatusBarAppearanceUpdate]; Add the following method: - (UIStatusBarStyle)preferredStatusBarStyle{ return UIStatusBarStyleLightContent; } Note : This does not work for controllers inside UINavigationController , please see Tyson's comment below :) Swift 3 - This will work controllers inside UINavigationController . Add this code inside your controller. // Preferred status bar style lightContent to use on dark background.// Swift 3override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent} Swift 5 and SwiftUI For SwiftUI create a new swift file called HostingController.swift import Foundationimport UIKitimport SwiftUIclass HostingController: UIHostingController<ContentView> { override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent }} Then change the following lines of code in the SceneDelegate.swift window.rootViewController = UIHostingController(rootView: ContentView()) to window.rootViewController = HostingController(rootView: ContentView())
|
{}
|
{'log_upvote_score': 12, 'links': ['https://Stackoverflow.com/questions/17678881', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1142999/']}
|
jdg_373639
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
323188
|
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a mouse with an internal IC: SPCP168A , having read about it, I discovered that it is specifically designed and programmed for the mouse functionality. I am interested in reprogramming the device to be able to use its "camera" (160frame/s).My questions are:Can I reprogram it, or is it an OTP?Has anyone done something similar ?
Now provide the response and nothing else.
|
Specifications for this particular chip (SPCP168A) don't show any explicit serial/SPI port. Also, there is no indication in blogosphere that this particular chip has any field firmware update options. So it is very likely that it runs from a mask ROM. However, there are other optical mice on the market, they are based on the original patented Avago technology. The main chip ADNS-2051 does have an interface to a MCU, both some serial, and "quadrature outputs". There are some hack examples that use this chip as 16x16 video matrix using Arduino.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/323188', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/142452/']}
|
jdg_373640
|
Subsets and Splits
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves samples with 'mathoverflow.net' in the prompt, providing a basic subset for inspection but with limited analytical value.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves 10 samples where the prompt mentions Mathematica Stack Exchange, offering basic filtering to locate specific content.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves a limited number of rows where the prompt contains a specific URL, providing basic filtering that offers minimal insight into the broader dataset patterns.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves 10 samples from the dataset where the prompt contains 'dsp.stackexchange.com', offering a basic filtering of data points related to that specific domain.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves a sample of rows where the prompt contains 'cs.stackexchange.com', providing a basic filter without extensive insight.
Electronics Q&A Subset
Retrieves a limited number of samples that contain a specific URL, providing only raw data filtered by that URL.
StackExchange Stats Questions
Retrieves 100 entries containing 'stats.stackexchange.com' in the prompt, which is useful for finding specific content but lacks broader analytical value.
Math StackExchange Questions
Retrieves 100 records from the train dataset where the prompt contains 'math.stackexchange.com', providing a basic filtered overview of specific entries.
Physics SE Questions
Retrieves 100 samples containing the word 'physics.stackexchange.com' in the prompt, offering basic filtering without deep analysis.