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
5534928
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I got problem with line breaks in a textarea. I get the text with .val() function: var messageBody = $('#composeInput').val(); This is my ajax request $.ajax({ url: 'serverScripts/messages/addMessage.php', data: 'messageBody='+messageBody+'&invitedJSONText='+invitedJSONText, success: function(){ //Do something }}); And PHP: $messageBody = nl2br(mysql_real_escape_string($_GET['messageBody'])); The text: Hi! How are you? Becomes: Hi! How are you? If I insert the variable messageBody to an another div-element I can't see any \n is this normal. How do I fix this? Now provide the response and nothing else.
When you pass a string as the data parameter, you must URL encode it like this: 'messageBody=' + encodeURIComponent(messageBody) + '&invitedJSONText=' + encodeURIComponent(invitedJSONText) If you pass the parameters as an object, jQuery takes care of encoding the data: $.ajax({ url: 'serverScripts/messages/addMessage.php', data: { messageBody: messageBody, invitedJSONText: invitedJSONText }, success: function (data, textStatus, jqXHR) { $("#foo").html(data); // <-- did something }});
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5534928', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/449132/']}
jdg_81941
stackexchange
llm_judgeable_groundtruth_similarity
4807808
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Strings are reference types, but they are immutable. This allows for them to be interned by the compiler; everywhere the same string literal appears, the same object may be referenced. Delegates are also immutable reference types. (Adding a method to a multicast delegate using the += operator constitutes assignment ; that's not mutability.) And, like, strings, there is a "literal" way to represent a delegate in code, using a lambda expression, e.g.: Func<int> func = () => 5; The right-hand side of that statement is an expression whose type is Func<int> ; but nowhere am I explicitly invoking the Func<int> constructor (nor is an implicit conversion happening). So I view this as essentially a literal . Am I mistaken about my definition of "literal" here? Regardless, here's my question. If I have two variables for, say, the Func<int> type, and I assign identical lambda expressions to both: Func<int> x = () => 5;Func<int> y = () => 5; ...what's preventing the compiler from treating these as the same Func<int> object? I ask because section 6.5.1 of the C# 4.0 language specification clearly states: Conversions of semantically identical anonymous functions with the same (possibly empty) set of captured outer variable instances to the same delegate types are permitted (but not required) to return the same delegate instance. The term semantically identical is used here to mean that execution of the anonymous functions will, in all cases, produce the same effects given the same arguments. This surprised me when I read it; if this behavior is explicitly allowed , I would have expected for it to be implemented. But it appears not to be. This has in fact gotten a lot of developers into trouble, esp. when lambda expressions have been used to attach event handlers successfully without being able to remove them. For example: class EventSender{ public event EventHandler Event; public void Send() { EventHandler handler = this.Event; if (handler != null) { handler(this, EventArgs.Empty); } }}class Program{ static string _message = "Hello, world!"; static void Main() { var sender = new EventSender(); sender.Event += (obj, args) => Console.WriteLine(_message); sender.Send(); // Unless I'm mistaken, this lambda expression is semantically identical // to the one above. However, the handler is not removed, indicating // that a different delegate instance is constructed. sender.Event -= (obj, args) => Console.WriteLine(_message); // This prints "Hello, world!" again. sender.Send(); }} Is there any reason why this behavior—one delegate instance for semantically identical anonymous methods—is not implemented? Now provide the response and nothing else.
You're mistaken to call it a literal, IMO. It's just an expression which is convertible to a delegate type. Now as for the "interning" part - some lambda expressions are cached , in that for one single lambda expression, sometimes a single instance can be created and reused however often that line of code is encountered. Some are not treated that way: it usually depends on whether the lambda expression captures any non-static variables (whether that's via "this" or local to the method). Here's an example of this caching: using System;class Program{ static void Main() { Action first = GetFirstAction(); first -= GetFirstAction(); Console.WriteLine(first == null); // Prints True Action second = GetSecondAction(); second -= GetSecondAction(); Console.WriteLine(second == null); // Prints False } static Action GetFirstAction() { return () => Console.WriteLine("First"); } static Action GetSecondAction() { int i = 0; return () => Console.WriteLine("Second " + i); }} In this case we can see that the first action was cached (or at least, two equal delegates were produced, and in fact Reflector shows that it really is cached in a static field). The second action created two unequal instances of Action for the two calls to GetSecondAction , which is why "second" is non-null at the end. Interning lambdas which appear in different places in the code but with the same source code is a different matter. I suspect it would be quite complex to do this properly (after all, the same source code can mean different things in different places) and I would certainly not want to rely on it taking place. If it's not going to be worth relying on, and it's a lot of work to get right for the compiler team, I don't think it's the best way they could be spending their time.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4807808', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/105570/']}
jdg_81942
stackexchange
llm_judgeable_groundtruth_similarity
21524487
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 abstraction: int i = 1;auto go = [] () { return i;}; Is it possible to make something like that in modern C++ syntax? Now provide the response and nothing else.
Formally speaking, the ability to access the surrounding context is the key difference between a function (which cannot) and a closure (which can). Depending on the languages this capture of the environment may occur via copy or reference. In C++11 (and beyond), lambdas are closures and as usual with C++ we have a fine-grained way of specifying how the capture is done: by copy: implicitly [=]() { return i; } or explicitly [i]() { return i; } by reference: implicitly [&]() { return i; } or explicitly [&i]() { return i; } and C++14 even introduces generalized lambda captures , so you can capture: by move: existing variable [i = std::move(i)]() { return i; } or create a new variable [i = 1]() { return i; } The square brackets delimit the capture list.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21524487', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/238232/']}
jdg_81943
stackexchange
llm_judgeable_groundtruth_similarity
23369296
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The Google Spreadsheet looks like can only select one value in the dropdown list. Is there any way to select multiple values from a dropdown list in google spreadsheet? Now provide the response and nothing else.
To Add to AlexG's answer, a better and enhanced version of multi-select is found in this following link (which I tried and worked as expected): https://gist.github.com/coinsandsteeldev/4c67dfa5411e8add913273fc5a30f5e7 For general guidance on setting up a script in Google Sheets, see this quickstart guide. To use this script: In your Google Sheet, set up data validation for a cell (or cells),using data from a range. In cell validation, do not select 'Rejectinput'. Go to Tools > Script editor... In the script editor, go to File > New > Script file Name the file multi-select.gs and paste in the contents ofmulti-select.gs. File > Save. In the script editor, go to File > New > Html file Name the filedialog.html and paste in the contents of dialog.html. File > Save. Back in your spreadsheet, you should now have a new menu called'Scripts'. Refresh the page if necessary. Select the cell you want to fill with multiple items from yourvalidation range. Go to Scripts > Multi-select for this cell... and the sidebar shouldopen, showing a checklist of valid items. Tick the items you want and click the 'Set' button to fill yourcell with those selected items, comma separated. You can leave the script sidebar open. When you select any cell that has validation, click 'Refresh validation' in the script sidebar to bring up that cell's checklist. The above mentioned steps are taken from this link
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23369296', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3084196/']}
jdg_81944
stackexchange
llm_judgeable_groundtruth_similarity
7451517
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there any way to use a Rails helper method, more specifically, a path helper method within a javascript asset file. This file foo.js.coffee.erb $('#bar').val("<%= create_post_path %>") I would love it if I could get from erubis $('#bar').val("path/to/create") Now provide the response and nothing else.
You can include any helper/module/class in an erb template with: <% environment.context_class.instance_eval { include MyHelper } %> See: https://github.com/rails/sprockets/blob/master/lib/sprockets/environment.rb and https://github.com/rails/sprockets/blob/master/lib/sprockets/context.rb To use the url helpers you have to include your specific applications' helpers. They are available at Rails.application.routes.url_helpers so: <% environment.context_class.instance_eval { include Rails.application.routes.url_helpers } %> EDIT: Fixed links to moved sprockets repo but not really sure this still makes sense so many years later.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7451517', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/178110/']}
jdg_81945
stackexchange
llm_judgeable_groundtruth_similarity
4571389
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: So I have a statement that goes like this: $$( \lnot A \lor B) \land(\lnot A \lor \lnot B)$$ I think it is equivalent to $$\lnot A$$ Am I right or not? Now provide the response and nothing else.
Although it's a bit overkill for this problem, since there are only two variables, you can easily solve this with a truth table: A B $\lnot A$ $( \lnot A \lor B) \land(\lnot A \lor \lnot B)$ True True False False True False False False False True True True False False True True As you fill in the last column, you can quickly realize that the truth value of B has no impact on the truth value of the expression $( \lnot A \lor B) \land(\lnot A \lor \lnot B)$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4571389', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/1111533/']}
jdg_81946
stackexchange
llm_judgeable_groundtruth_similarity
133178
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Let $f:X \rightarrow (Y, \mathcal{Y})$ be an abstract function, with $\mathcal{Y}$ a $\sigma$-algebra on $Y$. Endow $X$ with $f^{-1}(\mathcal{Y})$. Is then $f(X)$ a measurable set in $Y$? If not, are there simple conditions on $f$ making $f(X)$ measurable? If $\mathcal{Y}$ were a $\sigma$-ring, would this modify anything? More concisely (and generally): when is the image of a measurable set under a measurable function a measurable set? Now provide the response and nothing else.
There are actually positive results if you change the context a little bit.Suppose that $X$ is a separable complete metric space, i.e., a Polish space, and assume that $Y$ is something like $\mathbb R^n$, a Polish space that carriesa measure that interacts nicely with the topology like the Lebesgue measure. Now, if $f:X\to Y$ is Borel measurable, then for every Borel set $B\subseteq X$the image $f[B]$ is not necessarily Borel in $Y$, but it is Lebesgue measurable in $Y$.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/133178', 'https://mathoverflow.net', 'https://mathoverflow.net/users/54780/']}
jdg_81947
stackexchange
llm_judgeable_groundtruth_similarity
3483690
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 tried the current Google sample for ExpandableListiew : This sample seem very simple and easy to use, but what I would like to do is to say that one of the category has no child. I removed all the children but the problem is that the arrow still appears on this current line. For instance, imagine that I remove all "Cat Names" , the arrow is still there and when I click on it, the arrow just change. How to remove this arrow and launch an activity instead? Now provide the response and nothing else.
If you're talking about the arrow that is used to collapse/expand the list then you can remove it by using setGroupIndicator() in the activity you can call getExpandableListView().setGroupIndicator(null); that will remove the arrow permanently though. If you want to only hide it if the list is empty you can do it through xml attributes like this To launch an activity when the list is expanded/collapsed you can override onGroupExpanded (or collapsed) in your ListAdapter implementation and used that to fire up your activity
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3483690', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/327402/']}
jdg_81948
stackexchange
llm_judgeable_groundtruth_similarity
15036121
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 using the following with Play2/Scala using the FileUploader Javascript utility to upload a file to my server: def fileUploader = Action(parse.multipartFormData) { request => request.body.file("qqfile").map { picture => import java.io.File val filename = picture.filename val contentType = picture.contentType picture.ref.moveTo(new File("/tmp",filename)) Ok(Json.toJson(Map( "success" -> "true" ))) }.getOrElse { Ok(Json.toJson(Map( "error" -> "error occured"))) }} I'm only dealing with small files (<10MB) and I want to use casbah to write those files directly into a Mongo Document or GridFS using the Mongo drivers. I realize I could just read the saved file from disk, but is there a way to handle this all from memory without buffering the file on disk first? The play documentation here recommends writing a custom BodyParser ( http://www.playframework.com/documentation/2.1.0/ScalaFileUpload ) but there doesn't seem to be any documentation on how to go about writing one. It wasn't clear how the API/implementation worked from the Scaladocs. I tried looking for the MultiPartFormData source code to see how it worked, but I can't seem to find it in their Git repo: https://github.com/playframework/Play20/tree/master/framework/src/play/src/main/scala/play/api/mvc I've searched quite a bit, but can't seem to find a good example. Now provide the response and nothing else.
Untested The Multipart object of the BodyParsers does a lot of work for us. The first thing we need to do write a handler for the FilePart . I assume here that you want the file parts an Array[Byte] . def handleFilePartAsByteArray: PartHandler[FilePart[Array[Byte]]] = handleFilePart { case FileInfo(partName, filename, contentType) => // simply write the data to the a ByteArrayOutputStream Iteratee.fold[Array[Byte], ByteArrayOutputStream]( new ByteArrayOutputStream()) { (os, data) => os.write(data) os }.mapDone { os => os.close() os.toByteArray } } The next step is to define your body parser: def multipartFormDataAsBytes:BodyParser[MultipartFormData[Array[Byte]]] = multipartFormData(handleFilePartAsByteArray) Then, in order to use it, specify it at you Action : def fileUploader = Action(multipartFormDataAsBytes) { request => request.body.files foreach { case FilePart(key, filename, contentType, bytes) => // do something } Ok("done")} Some types and methods in the above pieces of code are a bit hard to find. Here is a complete list of imports in case you need it: import play.api.mvc.BodyParsers.parse.Multipart.PartHandlerimport play.api.mvc.BodyParsers.parse.Multipart.handleFilePartimport play.api.mvc.BodyParsers.parse.Multipart.FileInfoimport play.api.mvc.BodyParsers.parse.multipartFormDataimport play.api.mvc.MultipartFormData.FilePartimport play.api.libs.iteratee.Iterateeimport java.io.ByteArrayOutputStreamimport play.api.mvc.BodyParserimport play.api.mvc.MultipartFormData
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15036121', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/696836/']}
jdg_81949
stackexchange
llm_judgeable_groundtruth_similarity
10251391
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: For the following command: subprocess.call(shlex.split( """/usr/local/itms/bin/iTMSTransporter -m lookupMetadata -apple_id %s -destination %s"""%(self.apple_id, self.destination)) It prints the entire output into the Terminal window. How would I suppress ALL output here? I tried doing subprocess.call(shlex.split(<command> > /dev/null 2&1 )), but it didn't produce the required results. How would I do this here? Now provide the response and nothing else.
You can use the stdout= and stderr= parameters to subprocess.call() to direct stdout or stderr to a file descriptor of your choice. So maybe something like this: import osdevnull = open(os.devnull, 'w')subprocess.call(shlex.split( '/usr/local/itms/bin/iTMSTransporter -m lookupMetadata ' '-apple_id %s -destination %s' % (self,apple_id, self.destination)), stdout=devnull, stderr=devnull) Using subprocess.PIPE , if you're not reading from the pipe, could cause your program to block if it generates a lot of output. Update As @yanlend mentions in a comment, newer (3.x) versions of Python include subprocess.DEVNULL to solve this problem in a more convenient and portable fashion. In that case, the code would look like: subprocess.call(shlex.split( '/usr/local/itms/bin/iTMSTransporter -m lookupMetadata ' '-apple_id %s -destination %s' % (self,apple_id, self.destination)), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/10251391', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/651174/']}
jdg_81950
stackexchange
llm_judgeable_groundtruth_similarity
14095778
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an If-else statement which checks a string to see whether there is an ISBN-10 or ISBN-13 (book ID). The problem I am facing is with the ISBN-10 check which occurs before the ISBN-13 check, the ISBN-10 check will match anything with 10 characters or more and so may mistake an ISBN-13 for an ISBN-10. here is the code... $str = "ISBN:9780113411436";if(preg_match("/\d{9}(?:\d|X)/", $str, $matches)){ echo "ISBN-10 FOUND\n"; //isbn returned will be 9780113411 return 0;}else if(preg_match("/\d{12}(?:\d|X)/", $str, $matches)){ echo "ISBN-13 FOUND\n"; //isbn returned will be 9780113411436 return 1;} How do I make sure I avoid this problem? Now provide the response and nothing else.
You really only need one regex for this. Then do a more efficient strlen() check to see which one was matched. The following will match ISBN-10 and ISBN-13 values within a string with or without hyphens, and optionally preceded by the string ISBN: , ISBN:(space) or ISBN(space) . Finding ISBNs : function findIsbn($str){ $regex = '/\b(?:ISBN(?:: ?| ))?((?:97[89])?\d{9}[\dx])\b/i'; if (preg_match($regex, str_replace('-', '', $str), $matches)) { return (10 === strlen($matches[1])) ? 1 // ISBN-10 : 2; // ISBN-13 } return false; // No valid ISBN found}var_dump(findIsbn('ISBN:0-306-40615-2')); // return 1var_dump(findIsbn('0-306-40615-2')); // return 1var_dump(findIsbn('ISBN:0306406152')); // return 1var_dump(findIsbn('0306406152')); // return 1var_dump(findIsbn('ISBN:979-1-090-63607-1')); // return 2var_dump(findIsbn('979-1-090-63607-1')); // return 2var_dump(findIsbn('ISBN:9791090636071')); // return 2var_dump(findIsbn('9791090636071')); // return 2var_dump(findIsbn('ISBN:97811')); // return false This will search a provided string to see if it contains a possible ISBN-10 value (returns 1 ) or an ISBN-13 value (returns 2 ). If it does not it will return false . See DEMO of above. Validating ISBNs : For strict validation the Wikipedia article for ISBN has some PHP validation functions for ISBN-10 and ISBN-13 . Below are those examples copied, tidied up and modified to be used against a slightly modified version of the above function. Change the return block to this: return (10 === strlen($matches[1])) ? isValidIsbn10($matches[1]) // ISBN-10 : isValidIsbn13($matches[1]); // ISBN-13 Validate ISBN-10: function isValidIsbn10($isbn){ $check = 0; for ($i = 0; $i < 10; $i++) { if ('x' === strtolower($isbn[$i])) { $check += 10 * (10 - $i); } elseif (is_numeric($isbn[$i])) { $check += (int)$isbn[$i] * (10 - $i); } else { return false; } } return (0 === ($check % 11)) ? 1 : false;} Validate ISBN-13: function isValidIsbn13($isbn){ $check = 0; for ($i = 0; $i < 13; $i += 2) { $check += (int)$isbn[$i]; } for ($i = 1; $i < 12; $i += 2) { $check += 3 * $isbn[$i]; } return (0 === ($check % 10)) ? 2 : false;} See DEMO of above.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14095778', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1131217/']}
jdg_81951
stackexchange
llm_judgeable_groundtruth_similarity
23635070
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is it possible to download and save files in parallel using goroutines? Below is my code which downloads files from my dropbox: package mainimport ( "encoding/json" "fmt" "io" "io/ioutil" "net/http" "net/url" "os" "path/filepath")const app_key string = "<app_key>"const app_secret string = "<app_secret>"var code stringtype TokenResponse struct { AccessToken string `json:"access_token"`}type File struct { Path string}type FileListResponse struct { FileList []File `json:"contents"`}func download_file(file File, token TokenResponse) { download_file := fmt.Sprintf("https://api-content.dropbox.com/1/files/dropbox/%s?access_token=%s", file.Path, token.AccessToken) resp, _ := http.Get(download_file) defer resp.Body.Close() filename := filepath.Base(file.Path) out, err := os.Create(filename) if err != nil { panic(err) } defer out.Close() io.Copy(out, resp.Body)}func main() { authorize_url := fmt.Sprintf("https://www.dropbox.com/1/oauth2/authorize?response_type=code&client_id=%s", app_key) // Get code fmt.Printf("1. Go to: %s\n", authorize_url) fmt.Println("2. Click 'Allow' (you might have to log in first)") fmt.Println("3. Copy the authorization code.") fmt.Printf("Enter the authorization code here: ") fmt.Scanf("%s", &code) // End get code // Get access token data := url.Values{} data.Add("code", code) data.Add("grant_type", "authorization_code") data.Add("client_id", app_key) data.Add("client_secret", app_secret) resp, _ := http.PostForm("https://api.dropbox.com/1/oauth2/token", data) defer resp.Body.Close() contents, _ := ioutil.ReadAll(resp.Body) var tr TokenResponse json.Unmarshal(contents, &tr) // End get access token // Get file list file_list_url := fmt.Sprintf("https://api.dropbox.com/1/metadata/dropbox/Camera Uploads?access_token=%s", tr.AccessToken) resp2, _ := http.Get(file_list_url) defer resp2.Body.Close() contents2, _ := ioutil.ReadAll(resp2.Body) var flr FileListResponse json.Unmarshal(contents2, &flr) // End get file list for i, file := range flr.FileList { download_file(file, tr) if i >= 2 { break } }} It doesn't work when I prefix the download_file function with the go command. go download_file(file, tr) Now provide the response and nothing else.
That's because your main goroutine is exiting. You need to add a WaitGroup to wait until all the goroutines exit. For example, var wg sync.WaitGroupfor i, file := range flr.FileList { wg.Add(1) go download_file(file, tr, wg) if i >= 2 { break }}wg.Wait()...func download_file(file File, token TokenResponse, wg sync.WaitGroup) { ... wg.Done()}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23635070', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/288424/']}
jdg_81952
stackexchange
llm_judgeable_groundtruth_similarity
16995
Below is a question asked on the forum emacs.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am very used to typing in a shell something like: emacsclient **/Threshold.java Where Threshold.java is a file deeply nested in a directory and I just want toopen it by name. When I try the same thing in eshell, I get (ec is an alias for find-file ): ec **/Threshold.javaWrong type argument: stringp, ("src/main/java/org/elasticsearch/shield/admin/Threshold.java") How can I get this working in eshell? Now provide the response and nothing else.
(defun eshell/my-find-file (pattern) (mapc #'find-file (mapcar #'expand-file-name pattern))) then use my-find-file **/Threshold.java from Eshell, if you also want my-find-file to support non-glob pattern (for example, my-find-file Threshold.java ), try following: (defun eshell/my-find-file (pattern) (if (stringp pattern) (find-file pattern) (mapc #'find-file (mapcar #'expand-file-name pattern))))
{}
{'log_upvote_score': 4, 'links': ['https://emacs.stackexchange.com/questions/16995', 'https://emacs.stackexchange.com', 'https://emacs.stackexchange.com/users/379/']}
jdg_81953
stackexchange
llm_judgeable_groundtruth_similarity
9515505
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 the content after the last comma in a string using a regular expression? Example: abcd,fg;ijkl, cas The output should be cas Note: There is a space between last comma and 'c' character which also needs to be removed. Also the pattern contains only one space after last comma. Now provide the response and nothing else.
Using regular expressions: Pattern p = Pattern.compile(".*,\\s*(.*)");Matcher m = p.matcher("abcd,fg;ijkl, cas");if (m.find()) System.out.println(m.group(1)); Outputs: cas Or you can use simple String methods: System.out.println(s.substring(s.lastIndexOf(",") + 1).trim()); System.out.println(s.substring(s.lastIndexOf(", ") + 2));
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9515505', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/575250/']}
jdg_81954
stackexchange
llm_judgeable_groundtruth_similarity
22022261
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 make jQuery Chosen and KnockoutJS work at the same time. The problem is "jQuery Chosen" refuses to update options list even though I've created custom binding for it. Here is the example - http://jsfiddle.net/5fGAf/ I have two changeable selects - "Country" and "Method". "Method" options list depends on country selected. When I select the country for the first time - everything works perfect. But when I want to change the country - "Method" options list remains the same, even though corresponding knockout computed value is updated. If I manually run $(".chosen-select").trigger('chosen:updated') in the browser console - options list updates. Custom binding code: ko.bindingHandlers.chosen = { init: function(element) { $(element).chosen({disable_search_threshold: 10}); }, update: function(element) { $(".chosen-select").trigger('chosen:updated'); }}; Now provide the response and nothing else.
You have two problems: in your fiddle there is no .chosen-select so your update function does not find the select but anyway you should use $(element) to access the currently bound element in KO 3.0 bindings are fired independently . Because your chosen binding is not connected to the your observable array your update won't fire when you change that array. You can solve this "update" problem with explicitly declaring a dependency on the options binding in your custom binding but a better solution would be to delegate to it: ko.bindingHandlers.chosen = { init: function(element) { ko.bindingHandlers.options.init(element); $(element).chosen({disable_search_threshold: 10}); }, update: function(element, valueAccessor, allBindings) { ko.bindingHandlers.options.update(element, valueAccessor, allBindings); $(element).trigger('chosen:updated'); }}; And use it where you would normally use the options binding: <select id="option1" class="form-control" data-bind="chosen: payoutOptions, optionsText: 'optionText', optionsValue: 'optionValue', value: activePayoutOption"></select> Demo JSFiddle .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22022261', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1110044/']}
jdg_81955
stackexchange
llm_judgeable_groundtruth_similarity
30599478
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 considering using the factory_boy library for API testing. An example from the documentation is: class UserFactory(factory.Factory): class Meta: model = base.User first_name = "John" last_name = "Doe" For this to work, we need first_name , last_name , etc to be passed as parameters to the __init__() method of the base.User() class . However, if you have many parameters this leads to something like: class User(object): GENDER_MALE = 'mr' GENDER_FEMALE = 'ms' def __init__(self, title=None, first_name=None, last_name=None, is_guest=None, company_name=None, mobile=None, landline=None, email=None, password=None, fax=None, wants_sms_notification=None, wants_email_notification=None, wants_newsletter=None, street_address=None): self. title = title self.first_name = first_name self.last_name = last_name self.company_name = company_name self.mobile = mobile self.landline = landline self.email = email self.password = password self.fax = fax self.is_guest = is_guest self.wants_sms_notification = wants_sms_notification self.wants_email_notification = wants_email_notification self.wants_newsletter = wants_newsletter self.company_name = company_name self.street_address = street_address Now the question is, is this construction considered anti-pattern, and if yes, what alternatives do I have? Thanks Now provide the response and nothing else.
You could pack the __init__ method's keyword arguments into one dict, and set them dynamically with setattr : class User(object): GENDER_MALE = 'mr' GENDER_FEMALE = 'ms' def __init__(self, **kwargs): valid_keys = ["title", "first_name", "last_name", "is_guest", "company_name", "mobile", "landline", "email", "password", "fax", "wants_sms_notification", "wants_email_notification", "wants_newsletter","street_address"] for key in valid_keys: setattr(self, key, kwargs.get(key))x = User(first_name="Kevin", password="hunter2")print(x.first_name, x.password, x.mobile) However, this has the drawback of disallowing you from supplying arguments without naming them - x = User("Mr", "Kevin") works with your original code, but not with this code.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30599478', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2535477/']}
jdg_81956
stackexchange
llm_judgeable_groundtruth_similarity
38459625
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 port an ASP.NET application to ASP.NET Core. I have property injection (using Ninject) on my UnitOfWork implementation like this: [Inject]public IOrderRepository OrderRepository { get; set; }[Inject]public ICustomerRepository CustomerRepository { get; set; } Is there a way to achieve the same functionality using built-in DI on .NET Core? Also, is it possible to use convention-based binding? Now provide the response and nothing else.
No, the built-in DI/IoC container is intentionally kept simple in both usage and features to offer a base for other DI containers to plug-in. So there is no built-in support for: Auto-Discovery, Auto-Registrations, Decorators or Injectors, or convention based registrations. There are also no plans to add this to the built-in container yet as far as I know. You'll have to use a third party container with property injection support. Please note that property injection is considered bad in 98% of all scenarios, because it hides dependencies and there is no guarantee that the object will be injected when the class is created. With constructor injection you can enforce this via constructor and check for null and the not create the instance of the class. With property injection this is impossible and during unit tests its not obvious which services/dependencies the class requires when they are not defined in the constructor, so easy to miss and get NullReferenceExceptions . The only valid reason for Property Injection I ever found was to inject services into proxy classes generated by a third party library, i.e. WCF proxies created from an interface where you have no control about the object creation. And even there, its only for third party libraries. If you generate WCF Proxies yourself, you can easily extend the proxy class via partial class and add a new DI friendly constructor, methods or properties. Avoid it everywhere else.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/38459625', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/659695/']}
jdg_81957
stackexchange
llm_judgeable_groundtruth_similarity
3434065
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 does the address in a pointer refer to, real address location in main memory or virtual address. Can it be configured. And if it refers to virtual address , does Memory manager needs to convert this address to real address everytime it is accessed Now provide the response and nothing else.
This depends on your system and OS. For a typical windows/linux user space application, the address is a virtual memory address. User space applications have no way of accessing the memory using physical addresses - that's one of the abstractions the OS gives each process. The MMU(Memory management unit) does this translation for every memory access, and it's up to the OS to set up the corect mapping for your process.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3434065', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7965/']}
jdg_81958
stackexchange
llm_judgeable_groundtruth_similarity
16778425
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 pass a couple of variables from one PHP page to another. I am not using a form. The variables are some messages that the target page will display if something goes wrong. How can I pass these variables to the other PHP page while keeping them invisible ? e.g. let's say that I have these two variables: //Original page$message1 = "A message";$message2 = "Another message"; and I want to pass them from page1.php to page2.php. I don't want to pass them through the URL. //I don't want'page2.php?message='.$message1.'&message2='.$message2 Is there a way (maybe through $_POST?) to send the variables? If anyone is wondering why I want them to be invisible, I just don't want a big URL address with parameters like "&message=Problem while uploading your file. This is not a valid .zip file" and I don't have much time to change the redirections of my page to avoid this problem. Now provide the response and nothing else.
Sessions would be good choice for you. Take a look at these two examples from PHP Manual : Code of page1.php <?php// page1.phpsession_start();echo 'Welcome to page #1';$_SESSION['favcolor'] = 'green';$_SESSION['animal'] = 'cat';$_SESSION['time'] = time();// Works if session cookie was acceptedecho '<br /><a href="page2.php">page 2</a>';// Or pass along the session id, if neededecho '<br /><a href="page2.php?' . SID . '">page 2</a>';?> Code of page2.php <?php// page2.phpsession_start();echo 'Welcome to page #2<br />';echo $_SESSION['favcolor']; // greenecho $_SESSION['animal']; // catecho date('Y m d H:i:s', $_SESSION['time']);// You may want to use SID here, like we did in page1.phpecho '<br /><a href="page1.php">page 1</a>';?> To clear up things - SID is PHP's predefined constant which contains session name and its id. Example SID value: PHPSESSID=d78d0851898450eb6aa1e6b1d2a484f1
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16778425', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1860791/']}
jdg_81959
stackexchange
llm_judgeable_groundtruth_similarity
16058571
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 very simple view as follows def simple_view(request): documents = request.user.document_set.all() return render(request, 'simple.html', {'documents': documents}) To test the above view in my test case i have the following method which errors out. Class SomeTestCase(TestCase): # ... def test_simple_view(self): # ... some other checks docset = self.resonse.context['documents'] self.assertTrue(self.user.document_set.all() == docset) # This line raises an error # ... The error i get is AssertionError: False is not true .I have tried printing both the querysets and both are absolutely identical. Why would it return False when both the objects are identical ? Any Ideas ? Currently to overcome this, I am using a nasty hack of checking lengths as follows: ds1, ds2 = self.response.context['documents'], self.user.document_set.all()self.assertTrue(len([x for x in ds1 if x in ds2]) == len(ds1) == len(ds2)) # Makes sure each entry in ds1 exists in ds2 Now provide the response and nothing else.
The queryset objects will not be identical if they are the result of different queries even if they have the same values in their result (compare ds1.query and ds2.query ). If you convert the query set to a list first, you should be able to do a normal comparison (assuming they have the same sort order of course): self.assertEqual(list(ds1), list(ds2))
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16058571', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1373822/']}
jdg_81960
stackexchange
llm_judgeable_groundtruth_similarity
5266272
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 load UIImages in a background thread and then display them on the iPad. However, there's a stutter when I set the imageViews' view property to the image.I soon figured out that image loading is lazy on iOS, and found a partial solution in this question: CGImage/UIImage lazily loading on UI thread causes stutter This actually forces the image to be loaded in the thread, but there's still a stutter when displaying the image. You can find my sample project here: http://www.jasamer.com/files/SwapTest.zip (edit: fixed version ), check the SwapTestViewController. Try dragging the picture to see the stutter. The test-code I created that stutters is this (the forceLoad method is the one taken from the stack overflow question I posted above): NSArray* imagePaths = [NSArray arrayWithObjects: [[NSBundle mainBundle] pathForResource: @"a.png" ofType: nil], [[NSBundle mainBundle] pathForResource: @"b.png" ofType: nil], nil];NSOperationQueue* queue = [[NSOperationQueue alloc] init];[queue addOperationWithBlock: ^(void) { int imageIndex = 0; while (true) { UIImage* image = [[UIImage alloc] initWithContentsOfFile: [imagePaths objectAtIndex: imageIndex]]; imageIndex = (imageIndex+1)%2; [image forceLoad]; //What's missing here? [self performSelectorOnMainThread: @selector(setImage:) withObject: image waitUntilDone: YES]; [image release]; }}]; There are two reasons why I know the stuttering can be avoided: (1) Apple is able to load images without stuttering in the Photos app (2) This code does not cause stutter after placeholder1 and placeholder2 have been displayed once in this modified version of the above code: UIImage* placeholder1 = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource: @"a.png" ofType: nil]];[placeholder1 forceLoad];UIImage* placeholder2 = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource: @"b.png" ofType: nil]];[placeholder2 forceLoad];NSArray* imagePaths = [NSArray arrayWithObjects: [[NSBundle mainBundle] pathForResource: @"a.png" ofType: nil], [[NSBundle mainBundle] pathForResource: @"b.png" ofType: nil], nil];NSOperationQueue* queue = [[NSOperationQueue alloc] init];[queue addOperationWithBlock: ^(void) { int imageIndex = 0; while (true) { //The image is not actually used here - just to prove that the background thread isn't causing the stutter UIImage* image = [[UIImage alloc] initWithContentsOfFile: [imagePaths objectAtIndex: imageIndex]]; imageIndex = (imageIndex+1)%2; [image forceLoad]; if (self.imageView.image==placeholder1) { [self performSelectorOnMainThread: @selector(setImage:) withObject: placeholder2 waitUntilDone: YES]; } else { [self performSelectorOnMainThread: @selector(setImage:) withObject: placeholder1 waitUntilDone: YES]; } [image release]; }}]; However, I can't keep all my images in memory. This implies that forceLoad doesn't do the complete job - there's something else going on before the images are actually displayed. Does anyone know what that is, and how I can put that into the background thread? Thanks, Julian Update Used a few of Tommys tips. What I figured out is that it's CGSConvertBGRA8888toRGBA8888 that's taking so much time, so it seems it's a color conversion that's causing the lag.Here's the (inverted) call stack of that method. Running Symbol Name6609.0ms CGSConvertBGRA8888toRGBA88886609.0ms ripl_Mark6609.0ms ripl_BltImage6609.0ms RIPLayerBltImage6609.0ms ripc_RenderImage6609.0ms ripc_DrawImage6609.0ms CGContextDelegateDrawImage6609.0ms CGContextDrawImage6609.0ms CA::Render::create_image_by_rendering(CGImage*, CGColorSpace*, bool)6609.0ms CA::Render::create_image(CGImage*, CGColorSpace*, bool)6609.0ms CA::Render::copy_image(CGImage*, CGColorSpace*, bool)6609.0ms CA::Render::prepare_image(CGImage*, CGColorSpace*, bool)6609.0ms CALayerPrepareCommit_(CALayer*, CA::Transaction*)6609.0ms CALayerPrepareCommit_(CALayer*, CA::Transaction*)6609.0ms CALayerPrepareCommit_(CALayer*, CA::Transaction*)6609.0ms CALayerPrepareCommit_(CALayer*, CA::Transaction*)6609.0ms CALayerPrepareCommit6609.0ms CA::Context::commit_transaction(CA::Transaction*)6609.0ms CA::Transaction::commit()6609.0ms CA::Transaction::observer_callback(__CFRunLoopObserver*, unsigned long, void*)6609.0ms __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__6609.0ms __CFRunLoopDoObservers6609.0ms __CFRunLoopRun6609.0ms CFRunLoopRunSpecific6609.0ms CFRunLoopRunInMode6609.0ms GSEventRunModal6609.0ms GSEventRun6609.0ms -[UIApplication _run]6609.0ms UIApplicationMain6609.0ms main The last bit-mask changes he proposed didn't change anything, sadly. Now provide the response and nothing else.
UIKit may be used on the main thread only. Your code is therefore technically invalid, since you use UIImage from a thread other than the main thread. You should use CoreGraphics alone to load (and non-lazily decode) graphics on a background thread, post the CGImageRef to the main thread and turn it into a UIImage there. It may appear to work (albeit with the stutter you don't want) in your current implementation, but it isn't guaranteed to. There seems to be a lot of superstition and bad practice advocated around this area, so it's not surprising you've managed to find some bad advice... Recommended to run on a background thread: // get a data provider referencing the relevant fileCGDataProviderRef dataProvider = CGDataProviderCreateWithFilename(filename);// use the data provider to get a CGImage; release the data providerCGImageRef image = CGImageCreateWithPNGDataProvider(dataProvider, NULL, NO, kCGRenderingIntentDefault);CGDataProviderRelease(dataProvider);// make a bitmap context of a suitable size to draw to, forcing decodesize_t width = CGImageGetWidth(image);size_t height = CGImageGetHeight(image);unsigned char *imageBuffer = (unsigned char *)malloc(width*height*4);CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();CGContextRef imageContext = CGBitmapContextCreate(imageBuffer, width, height, 8, width*4, colourSpace, kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little);CGColorSpaceRelease(colourSpace);// draw the image to the context, release itCGContextDrawImage(imageContext, CGRectMake(0, 0, width, height), image);CGImageRelease(image);// now get an image ref from the contextCGImageRef outputImage = CGBitmapContextCreateImage(imageContext);// post that off to the main thread, where you might do something like// [UIImage imageWithCGImage:outputImage][self performSelectorOnMainThread:@selector(haveThisImage:) withObject:[NSValue valueWithPointer:outputImage] waitUntilDone:YES];// clean upCGImageRelease(outputImage);CGContextRelease(imageContext);free(imageBuffer); There's no need to do the malloc/free if you're on iOS 4 or later, you can just pass NULL as the relevant parameter of CGBitmapContextCreate, and let CoreGraphics sort out its own storage. This differs from the solution you post to because it: creates a CGImage from a PNG data source — lazy loading applies, so this isn't necessarily a fully loaded and decompressed image creates a bitmap context of the same size as the PNG draws the CGImage from the PNG data source onto the bitmap context — this should force full loading and decompression since the actual colour values have to be put somewhere we could access them from a C array. This step is as far as the forceLoad you link to goes. converts the bitmap context into an image posts that image off to the main thread, presumably to become a UIImage So there's no continuity of object between the thing loaded and the thing displayed; pixel data goes through a C array (so, no opportunity for hidden shenanigans) and only if it was put into the array correctly is it possible to make the final image.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5266272', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/654352/']}
jdg_81961
stackexchange
llm_judgeable_groundtruth_similarity
35129697
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: As we can validate the values using the conventional model field then why Django REST Framework contains its own serializer fields. I know that serializer fields are used to handle the converting between primitive values and internal datatypes. Except this, is there anything different between them. Now provide the response and nothing else.
Well there is a ModelSerializer that can automatically provide the serializer fields based on your model fields (given the duality you described). A ModelSerializer allows you to select which models fields are going to appear as fields in the serializer, thus allowing you to show/hide some fields. A field in a model, is conventionally tied to a data store (say a column in a database). A DRF Serializer can exist without a Django model too, as it serves to communicate between the API and the client, and its fields can be in many forms that are independent from the model and the backing database, e.g. ReadOnlyField , SerializerMethodField etc
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35129697', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5176343/']}
jdg_81962
stackexchange
llm_judgeable_groundtruth_similarity
262385
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: If I'm moving with a considerable fraction of speed of light, the time and any process in my system will be going slower. If B is an outstanding person that is watching me passing by, he will see everything in my system in slow motion. This means he observes less ticks per seconds; thus the ticks are slower or the interval between the ticks is bigger. From my perspective everything is normal and time is not running slower. Is it okay to talk about the speed of time in this context? Is it okay to say: "The shorter the interval between two ticks the faster the speed of time."? Now provide the response and nothing else.
Temperature is related to kinetic energy in the rest frame of the fluid/gas. In non-relatvistic kinetic theory the distribution function is $$ f(p) \sim \exp\left(-\frac{(\vec{p}-m\vec{u})^2}{2mT}\right)$$ where $\vec{u}$ is the local fluid velocity. The velocity can be found by demanding that the mean momentum in the local rest frame is zero. Then $\vec{u}$ transform as a vector under Galilean transformations, and $T$ is a scalar. In relativistic kinetic theory $$ f(p) \sim \exp\left(-\frac{p\cdot u}{T}\right)$$ where $p$ is the four-momentum, $u$ is the four-velocity, and $T$ is the temperature scalar. The rest frame is defined by $\vec{u}=0$ , and in the rest frame $f\sim \exp(-E_p/T)$ , as expected. The relativistic result is known as the Jüttner distribution (Juttner, 1911), and is discussed in standard texts on relativistic kinetic theory, for example Cercignani and Kremer , equ. (2.124), and de Groot et al , equ (ch4)(25). See also (2.120) in Rezzolla and Zanotti . For an intro available online see equ. (55-58) of Romatschke's review .Neumaier notes that some (like Beccatini ) advocate defining a four-vector field $\beta_\mu=u_\mu/T$ , and then define a frame dependent temperature $T'\equiv 1/\beta_0$ . I fail to see the advantage of this procedure, and it is not what is done in relativistic kinetic theory, hydrodynamics, numerical GR, or AdS/CFT. Ultimately, the most general definition of $T$ comes from local thermodynamics (fluid dynamics), not kinetic theory, because strongly correlated fluids (classical or quantum) are not described in kinetic theory. The standard form of relativistic fluid dynamics (developed by Landau, and explained in his book on fluid dynamics) also introduces a relarivistic 4-velocity $u_\mu$ (with $u^2=1$ ), and a scalar temperature $T$ , defined by thermodynamic identities, $dP=sdT+nd\mu$ . The ideal fluid stress tensor is $$T_{\mu\nu}=({\cal E}+P) u_\mu u_\nu -Pg_{\mu\nu}$$ where ${\cal E}$ is the energy density and $P$ is the pressure. Note that for a kinetic system the parameter $u_\mu$ in the Juttner distribution is the fluid velocity, as one would expect. More generally, the fluid velocity can be defined by $u^\mu T_{\mu\nu}={\cal E}u_\nu$ , which is valid even if dissipative corrections are taken into account. Regarding the ``paradox'': Temperature is not relative, it is a scalar. The relation in B is only correct in the rest frame. The Doppler effect is of course a real physical effect. The spectrum seen by an observer moving vith relative velocity $v$ is $f\sim\exp(-p\cdot v/T)$ , which exhibits a red/blue shift. The spectrum only depends on the relative velocity, as it should. Measuring the spectrum can be used to determine both the relative velocity and the temperature. However, if you look at a distant star you only measure light coming off in one direction. Then, in order to disentangle $u$ and $T$ , you need either a spectral line, or information on the absolute luminosity.
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/262385', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/120973/']}
jdg_81963
stackexchange
llm_judgeable_groundtruth_similarity
2188469
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 creating a folder to cache images inside Documents with my iPhone App. I want to be able to keep the size of this folder down to 1MB, so I need to to check the size in bytes of my folder. I have code to calculate the size of file , but I need the size of the folder. What would be the best way to do this? Now provide the response and nothing else.
tl;dr All the other answers are off :) Problem I'd like to add my two cents to this old question as there seem to be many answers that are all very similar but yield results that are in some cases very unprecise. To understand why we first have to define what the size of a folder is. In my understanding (and probably the one of the OP) it is the amount of bytes that the directory including all of its contents uses on the volume. Or, put in another way: It is the space becoming available if the directory would be completely removed. I'm aware that this definition is not the only valid way to interpret the question but I do think it's what most use cases boil down to. Error The existing answers all take a very simple approach: Traverse the directory contents, adding up the sizes of (regular) files. This does not take a couple of subtleties into account. The space used on the volume increments in blocks , not in bytes. Even a one byte file uses at least one block. Files carry around meta data (like any number of extended attributes). This data must go somewhere. HFS deploys file system compression to actually store the file using less bytes then its real length. Solution All of these reasons make the existing answers produce unprecise results. So I'm proposing this extension on NSFileManager (code on github due to length: Swift 4 , Objective C ) to remedy the problem. It's also quite a bit faster, especially with directories containing a lot of files. The core of the solution is to use NSURL 's NSURLTotalFileAllocatedSizeKey or NSURLFileAllocatedSizeKey properies to retrieve file sizes. Test I've also set up a simple iOS test project , demonstrating the differences between the solutions. It shows how utterly wrong the results can be in some scenarios. In the test I create a directory containing 100 small files (ranging from 0 to 800 bytes). The folderSize: method copied from some other answer calculates a total of 21 kB while my allocatedSize method yields 401 kB. Proof I made sure that the results of allocatedSize are closer to the correct value by calculating the difference of the available bytes on the volume before and after deleting the test directory. In my tests the difference was always exactly equal to the result of allocatedSize . Please see Rob Napier's comment to understand that there's still room for improvement. Performance But there's another advantage: When calculating the size of a directory with 1000 files, on my iPhone 6 the folderSize: method takes about 250 ms while allocatedSize traverses the same hierarchy in 35 ms. This is probably due to using NSFileManager 's new(ish) enumeratorAtURL:includingPropertiesForKeys:options:errorHandler: API to traverse the hierachy. This method let's you specify prefetched properties for the items to be iterated, resulting in less io. Results Test `folderSize` (100 test files) size: 21 KB (21.368 bytes) time: 0.055 s actual bytes: 401 KB (401.408 bytes)Test `allocatedSize` (100 test files) size: 401 KB (401.408 bytes) time: 0.048 s actual bytes: 401 KB (401.408 bytes)Test `folderSize` (1000 test files) size: 2 MB (2.013.068 bytes) time: 0.263 s actual bytes: 4,1 MB (4.087.808 bytes)Test `allocatedSize` (1000 test files) size: 4,1 MB (4.087.808 bytes) time: 0.034 s actual bytes: 4,1 MB (4.087.808 bytes)
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2188469', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/166126/']}
jdg_81964
stackexchange
llm_judgeable_groundtruth_similarity
8596109
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 do some machine learning stuff that involves a lot of factor-type variables (words, descriptions, times, basically non-numeric stuff). I usually rely on randomForest but it doesn't work w/factors that have >32 levels. Can anyone suggest some good alternatives? Now provide the response and nothing else.
Tree methods won't work, because the number of possible splits increases exponentially with the number of levels. However, with words this is typically addressed by creating indicator variables for each word (of the description etc.) - that way splits can use a word at a time (yes/no) instead of picking all possible combinations. In general you can always expand levels into indicators (and some models do that implicitly, such as glm). The same is true in ML for handling text with other methods such as SVM etc. So the answer may be that you need to think about your input data structure, not as much the methods. Alternatively, if you have some kind of order on the levels, you can linearize it (so there are only c-1 splits).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8596109', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/914308/']}
jdg_81965
stackexchange
llm_judgeable_groundtruth_similarity
3276821
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 experimenting with lidgren in XNA and I'm having some issues with the 'lag'. I've downloaded their XNA sample and noticed that even their sample lags. The thing is, the movement is not smooth on the other side, and I'm trying this on a LAN (on the same computer actually) not over the internet. Has any had the same issues as regards unsmooth movement due to a lagging connection with lidgren and XNA ? Now provide the response and nothing else.
The sample you linked directly sets the position to whatever it receives from the network, this is a bad idea for a multiplayer game! What you should do in a real game is interpolate between the local position and the remote position. So, your receive method would look a little like this: void Receive(packet){ unit.RemoteX = packet.Read_X_Position(); unit.RemoteY = packet.Read_Y_Position();} This has no affect on the local position on the unit, instead in your update method (every frame), you move the local position towards the remote position: void Interpolate(deltaTime){ difference = unit.RemoteX - unit.LocalX if (Math.Abs(difference) < threshold) unit.LocalX = unit.RemoteX else unit.LocalX += difference * deltaTime * interpolation_constant} You then display the "local" position of the unit, this achieves lagless movement like so: If the unit position is almost at the remote position, it will jump to the remote position (however, it will jump such a tiny distance that it won't look laggy). If the difference is too big to jump, then move slowly towards the position you should be in. Since the unit moves smoothly towards where it should be, it looks like there is no lag at all! The interpolation constant controls how fast the local and remote positions will converge: 0: Ignore network updates Small: Snap into place very quickly (possibly look laggy) Large: Slide slowly into place, looks smooth but may feel unresponsive You need to choose a compromise somewhere in between these options. There are some other things to consider when implementing this kind of system, for example you often want an upper limit on how far apart units can be from their remote position otherwise the local and remote state can become "unstuck" in some situations. If they are too far apart (which should never happen except in cases of extreme lag) you can either halt the game and tell the user it's too laggy, or jump the unit straight into position, which will look laggy but at least the game will continue. Addendum: Rereading this answer, it occurs to me that an enhancement would be to track time differences. If you know (roughly) what the lag is in the system, then you know that when you receive a packet with a remote position in you know roughly how far into the past that packet is from. If you send remote velocity too, you can predict where the object is now (assuming constant velocity). This may make the difference between estimated local state and true remote state smaller in some games, in other games (where you have lots of changing velocities) it might make things worse.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3276821', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/44084/']}
jdg_81966
stackexchange
llm_judgeable_groundtruth_similarity
357032
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have to prove that: $$\frac{(k!)!}{k!^{(k-1)!}} \in \Bbb Z$$ for any $k \geq 1, k \in \Bbb N$ Tried doing $t = k!$ which would give $$\frac{t!}{t^{t/k}}$$ But I think I just made it harder, and I have no other clue! Now provide the response and nothing else.
A hint: Assume that there are $(k-1)!$ colors, and that you have $k$ balls of each color. In how many ways can you arrange them in a long line?
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/357032', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/67836/']}
jdg_81967
stackexchange
llm_judgeable_groundtruth_similarity
40481700
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I got device-specific problem with Meizu PRO 6 / android 6.0 I try to set statusBar color by defining colorPrimaryDark in my theme file When i set it to #FF0000 (red) it works fine But when i set it to #000000 (black) it doesn't apply (as you see, color is the same as colorPrimary ) The same code run on LG Nexus 5x: What could go wrong here? And how it can be fixed? Suppose current device has some kind of color filtering for statusBar, maybe it allows only colors, that are lighter than colorPrimary or something like this... Now provide the response and nothing else.
It is not $arguments[0] , but just arguments[0] (without the $). I am surprised that it actually works in the inline handler. So the following code is valid and will work: <component @some-event="someObject.field = arguments[0]"></component> The docs for Methods in Inline Handlers specifies $event as a special variable that gets the first parameter passed via event. I have always used it till now. After reading your question, a bit more research led me to this reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments It seems every javascript function has a local variable called arguments , which is used when a function is expected to get variable number of arguments. Using arguments[] as inline statements is definitely possible, but not documented anywhere in the context of vue.js framework. On the other hand, if you use $event in inline handler for events, it feels safer as it is documented clearly and will not break in a future version of Vue.js Sample usage for $event : <component @some-event="someObject.field = $event"></component>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/40481700', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6619441/']}
jdg_81968
stackexchange
llm_judgeable_groundtruth_similarity
1642732
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to prove the limit I came up with: $$\lim_{x\to\infty}\left(\csc\dfrac{m}{n+x}-\csc\dfrac{m}{x}\right)=\dfrac{n}{m}$$ This fact came from the double generalization of the special case $\,m=\pi,\;n=1\,$ which has exceptional connections to the longest length of a $2n$-gon of radius $1$, $\csc\left(\frac{\pi}{x}\right)$ which allows you to prove that $$\lim_{x\to\infty}\left(\csc\left(\frac{\pi}{x+1}\right)-\csc\left(\frac{\pi}{x}\right)\right)=\frac{1}{\pi}$$ When I was bored, I began graphing and came up with the above result after a bit. Thanks. Now provide the response and nothing else.
The minimum for the length functional is badly non-unique: it is given by any parametrization of the geodesic, not necessarily the natural one. On the other hand, the energy functional is locally uniformly convex; therefore the minimizer is unique and the variational calculus is nice. It is instructive to do the computation for the Euclidean plane. Suppose we are looking for the condition that a curve $(x(t),y(t))$ is a geodesic. Then, for the energy functional $\int \left(x'(t)^2+y'(t)^2\right)dt,$the Euler-Lagrange equations read $x''(t)=0$ and $y''(x)=0$, which is the straight line traced at constant speed. On the other hand, for the length functional $\int \sqrt{x'(t)^2+y'(t)^2}dt,$ one gets, after some algebra,$$\frac{x''}{x'}=\frac{x'x''+y'y''}{x'^2+y'^2}\;\mathrm{and}\;\frac{y''}{y'}=\frac{x'x''+y'y''}{x'^2+y'^2},$$and from the equality between the left-hand sides we get $x'(t)\equiv Cy'(t)$, which also gives a straight line, but with arbitrary parametrization. Added: It is worth to mention that the "energy functional" is a Lagrangian action for a free particle confined to the surface. Therefore, the law of conservation of energy implies that any solution $\gamma(t)$ will move at constant speed (which is of course also possible to see directly). And if one restricts the the class of curves to such solutions, the EL equations indeed take the same form for both functionals.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1642732', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_81969
stackexchange
llm_judgeable_groundtruth_similarity
1917647
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Given a random variable $X\sim\mathcal N(0,\sigma^2)$, how can we prove that $E[X^4]=3\sigma^4$? I am having trouble even starting with the proof. Now provide the response and nothing else.
First with $\sigma=1$ , omitting the range $(-\infty,\infty)$ for convenience and integrating twice by parts $$E[X^4]=\frac{\displaystyle\int x^4e^{-x^2/2}dx}{\displaystyle\int e^{-x^2/2}dx}=\frac{-x^3e^{-x^2/2}+3\displaystyle\int x^2e^{-x^2/2}dx}{\displaystyle\int e^{-x^2/2}dx}=\frac{0-3xe^{-x^2/2}+3\displaystyle\int e^{-x^2/2}dx}{\displaystyle\int e^{-x^2/2}dx}=3.$$ Then by rescaling the variable, $$3\sigma^4.$$ By observing the pattern, you easily generalize to $$E[X^{2n}]=(2n-1)!!\sigma^{2n}.$$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1917647', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/366908/']}
jdg_81970
stackexchange
llm_judgeable_groundtruth_similarity
15201064
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 migrating a makefile project to CMake. The person who wrote the makefile the first time had done a module for writing certain values in an include file. There's a main config.h file that includes a config_in.h. The config.h file contains something like this: #ifndef USE_FEATURE_A#define USE_FEATURE_A 0#endif#ifndef USE_FEATURE_B#define USE_FEATURE_B 0#endif In the makefile there's a fake target like with_feature_a that writes in config_in.h #define USE_FEATURE_A 1 In this way someone can type make with_feature_amake to get the right build. I want to replicate something like this using this codebase but using CMake. I tried a couple of approaches suggested on the net, but I didn't get it to work. set_target_properties(with_feature_a PROPERTIES COMPILE_DEFINITIONS "WITH_FEATURE_A=1") This isn't working because if I run make with_feature_a I don't see with_feature_a in the preprocessor command line. The second attempt I made is to write a file directly with the content set to whatever I want, but I didn't understand how to connect the file() command to my target. I placed this in my CMakeLists.txt file(WRITE local/config_in.h "#define WITH_FEATURE_A 1") but this isn't executed everytime and I don't know how to set it to a single target. Any help is appreciated. Thank you for reading all this stuff. Sorry for the long story :) UPDATE The solution provided here is a big enhacement on the road to solution. The problem is that is don't allow recursive definitions. I show an example: in CMakeLists.txt I placed: if (WITH_FEATURE_A)MESSAGE(STATUS "WITH_FEATURE_A")add_definitions(-DUSE_FEATURE_A=1) add_definitions(-DWITH_FEABURE_B=1)endif()if (WITH_FEABURE_B)MESSAGE(STATUS "WITH_FEATURE_B")add_definitions(-DUSE_FEATURE_D=1)endif()if (WITH_FEABURE_C)MESSAGE(STATUS "WITH_FEATURE_C")add_definitions(-DUSE_FEATURE_D=1)endif()if (WITH_FEABURE_D)MESSAGE(STATUS "WITH_FEATURE_D")endif() in this case if I execute cmake with -DWITH_FEATURE_A=1 I'd love to see in the output: WITH_FEATURE_AWITH_FEATURE_BWITH_FEATURE_D actually this code print just WITH_FEATURE_A Now provide the response and nothing else.
You can simplify things by avoiding creating the dummy targets and removing the config file. Instead, if you pass the requirements via the command line when you invoke CMake (or via the CMake GUI), you can run make only once. For example, you could add the following to your CMakeLists.txt: option(WITH_FEATURE_A "Option description" ON)option(WITH_FEATURE_B "Option description" OFF)if(WITH_FEATURE_A) add_definitions(-DUSE_FEATURE_A)endif()if(WITH_FEATURE_B) add_definitions(-DUSE_FEATURE_B)endif() By default, if you just run CMake, it will set the CMake variable WITH_FEATURE_A to ON which consequently adds USE_FEATURE_A as a preprocessor definition to the build. USE_FEATURE_B is undefined in the code. This would be equivalent to doing #define USE_FEATURE_A in your code. If you really need the equivalent of #define USE_FEATURE_A 1#define USE_FEATURE_B 0 then in your CMakeLists.txt you can do: option(WITH_FEATURE_A "Option description" ON)option(WITH_FEATURE_B "Option description" OFF)if(WITH_FEATURE_A) add_definitions(-DUSE_FEATURE_A=1)else() add_definitions(-DUSE_FEATURE_A=0)endif()if(WITH_FEATURE_B) add_definitions(-DUSE_FEATURE_B=1)else() add_definitions(-DUSE_FEATURE_B=0)endif() To change these defaults from the command line, simply do (e.g.): cmake . -DWITH_FEATURE_A=OFF -DWITH_FEATURE_B=ONmake Once a variable has been set via the command line this way, it is cached and will remain unchanged until either it is overwritten with a different value on the command line, or you delete the CMakeCache.txt file in your build root. Response to update: As @Peter noted, you appear to be mixing up CMake variables (the WITH_FEATURE... ones) and the preprocessor definitions (the USE_FEATURE... ones). You can as suggested resolve all the dependencies between options first, then set the resulting preprocessor definitions, or in this case where the flow is quite straightforward, just do it all in one go: if(WITH_FEATURE_A) message(STATUS "WITH_FEATURE_A") add_definitions(-DUSE_FEATURE_A=1) set(WITH_FEATURE_B ON)endif()if(WITH_FEATURE_B) message(STATUS "WITH_FEATURE_B") add_definitions(-DUSE_FEATURE_B=1) set(WITH_FEATURE_D ON)endif()if(WITH_FEATURE_C) message(STATUS "WITH_FEATURE_C") add_definitions(-DUSE_FEATURE_C=1) set(WITH_FEATURE_D ON)endif()if(WITH_FEATURE_D) message(STATUS "WITH_FEATURE_D") add_definitions(-DUSE_FEATURE_D=1)endif()
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/15201064', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1350961/']}
jdg_81971
stackexchange
llm_judgeable_groundtruth_similarity
7270
Below is a question asked on the forum linguistics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Verbal roots of PIE are generally reconstructed as (C 5 ) (C 3 ) C 1 e C 2 (C 4 ) (C 6 ) ; with certain phonetical restrictions, especially on the outmost consonants. I wonder why only "e" should be allowed as a root vowel and why it is generally attempted to "explain away" cases of other root vowels (like "a"), as stated in Tichy's "Indogermanistisches Grundwissen" (p. 35; my approximate translation): Next to verbal roots with the ie. base vowel e , some roots with a are also documented, e.g. * Hiaǵ 'to worship'. In spite of all efforts, there has been no success in plausibly explaining away these cases. So: Why should all roots have only the root vowel e and what evidence would a theory postulating that in all PIE roots the only vowel is e be based on? Now provide the response and nothing else.
It's not that PIE roots always contain the vowel e , it's that PIE roots don't contain vowels. This is a common misconception, unfortunately aided by the traditions of IE lexicography. Take a root like lei̯k w - 'leave'. This root is found in: e-grade, e.g. Gk. pres. leip-ō o-grade, e.g. Gk. pf. le-loip-a zero-grade, e.g. Gk. aor. e-lip-on What this shows is that the vowel (or lack thereof) depends on the grammatical category, not the root. The e in leip-ō is due to the fact that this class of present stems are formed with e , not to anything about the root's lexical entry. The tradition in IE studies is to cite all roots in the e-grade, but it could just as well have been the o-grade (in which case you might now be asking why all PIE roots contain the vowel o ). It would be less misleading to cite roots as e.g. l-i̯k w , with no vowels at all, but for historical reasons this isn't how it's done. The explanation for the existence of some roots with a , at least those which can't plausibly be ascribed to the combination of e with h2 , is probably that in late PIE this system was beginning to break down, as it does in all the daughter languages, with consonantal roots starting to give way to vowel-containing stems. But there are very few of these a -roots, i.e. on the whole the consonantal system is still intact. (The system I'm describing looks rather like the Semitic root system, but there's an important difference, namely that PIE roots contain consonant clusters which can't be broken up: for example you never see a form like li̯ek w - .)
{}
{'log_upvote_score': 4, 'links': ['https://linguistics.stackexchange.com/questions/7270', 'https://linguistics.stackexchange.com', 'https://linguistics.stackexchange.com/users/3432/']}
jdg_81972
stackexchange
llm_judgeable_groundtruth_similarity
1918841
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I need a function that, given a character, returns the CGKeyCode associated with the position of that character on the current keyboard layout. E.g., given "b", it should return kVK_ANSI_B if using U.S. QWERTY, or kVK_ANSI_N if using Dvorak. The Win32 API has the function VkKeyScan() for this purpose; X11 has the function XStringToKeySym() . Is there such a function in the CG API? I need this in order to pass a parameter to CGEventCreateKeyboardEvent() . I've tried using CGEventKeyboardSetUnicodeString() instead, but that apparently does not support modifier flags (which I need). I have searched extensively for this but cannot find a decent answer. Currently I am using the following code ( found online ), which works, but is not exactly elegant (and rather difficult to decipher how to simplify) and I would prefer not to use it in production code: #include <stdint.h>#include <stdio.h>#include <ApplicationServices/ApplicationServices.h>CGKeyCode keyCodeForCharWithLayout(const char c, const UCKeyboardLayout *uchrHeader);CGKeyCode keyCodeForChar(const char c){ CFDataRef currentLayoutData; TISInputSourceRef currentKeyboard = TISCopyCurrentKeyboardInputSource(); if (currentKeyboard == NULL) { fputs("Could not find keyboard layout\n", stderr); return UINT16_MAX; } currentLayoutData = TISGetInputSourceProperty(currentKeyboard, kTISPropertyUnicodeKeyLayoutData); CFRelease(currentKeyboard); if (currentLayoutData == NULL) { fputs("Could not find layout data\n", stderr); return UINT16_MAX; } return keyCodeForCharWithLayout(c, (const UCKeyboardLayout *)CFDataGetBytePtr(currentLayoutData));}/* Beware! Messy, incomprehensible code ahead! * TODO: XXX: FIXME! Please! */CGKeyCode keyCodeForCharWithLayout(const char c, const UCKeyboardLayout *uchrHeader){ uint8_t *uchrData = (uint8_t *)uchrHeader; UCKeyboardTypeHeader *uchrKeyboardList = uchrHeader->keyboardTypeList; /* Loop through the keyboard type list. */ ItemCount i, j; for (i = 0; i < uchrHeader->keyboardTypeCount; ++i) { /* Get a pointer to the keyToCharTable structure. */ UCKeyToCharTableIndex *uchrKeyIX = (UCKeyToCharTableIndex *) (uchrData + (uchrKeyboardList[i].keyToCharTableIndexOffset)); /* Not sure what this is for but it appears to be a safeguard... */ UCKeyStateRecordsIndex *stateRecordsIndex; if (uchrKeyboardList[i].keyStateRecordsIndexOffset != 0) { stateRecordsIndex = (UCKeyStateRecordsIndex *) (uchrData + (uchrKeyboardList[i].keyStateRecordsIndexOffset)); if ((stateRecordsIndex->keyStateRecordsIndexFormat) != kUCKeyStateRecordsIndexFormat) { stateRecordsIndex = NULL; } } else { stateRecordsIndex = NULL; } /* Make sure structure is a table that can be searched. */ if ((uchrKeyIX->keyToCharTableIndexFormat) != kUCKeyToCharTableIndexFormat) { continue; } /* Check the table of each keyboard for character */ for (j = 0; j < uchrKeyIX->keyToCharTableCount; ++j) { UCKeyOutput *keyToCharData = (UCKeyOutput *)(uchrData + (uchrKeyIX->keyToCharTableOffsets[j])); /* Check THIS table of the keyboard for the character. */ UInt16 k; for (k = 0; k < uchrKeyIX->keyToCharTableSize; ++k) { /* Here's the strange safeguard again... */ if ((keyToCharData[k] & kUCKeyOutputTestForIndexMask) == kUCKeyOutputStateIndexMask) { long keyIndex = (keyToCharData[k] & kUCKeyOutputGetIndexMask); if (stateRecordsIndex != NULL && keyIndex <= (stateRecordsIndex->keyStateRecordCount)) { UCKeyStateRecord *stateRecord = (UCKeyStateRecord *) (uchrData + (stateRecordsIndex->keyStateRecordOffsets[keyIndex])); if ((stateRecord->stateZeroCharData) == c) { return (CGKeyCode)k; } } else if (keyToCharData[k] == c) { return (CGKeyCode)k; } } else if (((keyToCharData[k] & kUCKeyOutputTestForIndexMask) != kUCKeyOutputSequenceIndexMask) && keyToCharData[k] != 0xFFFE && keyToCharData[k] != 0xFFFF && keyToCharData[k] == c) { return (CGKeyCode)k; } } } } return UINT16_MAX;} Is there a.) (preferably) a standard function I am overlooking, or b.) (almost certainly) a more elegant way write my own? Now provide the response and nothing else.
This is what I ended up using. Much cleaner. #include <CoreFoundation/CoreFoundation.h>#include <Carbon/Carbon.h> /* For kVK_ constants, and TIS functions. *//* Returns string representation of key, if it is printable. * Ownership follows the Create Rule; that is, it is the caller's * responsibility to release the returned object. */CFStringRef createStringForKey(CGKeyCode keyCode){ TISInputSourceRef currentKeyboard = TISCopyCurrentKeyboardInputSource(); CFDataRef layoutData = TISGetInputSourceProperty(currentKeyboard, kTISPropertyUnicodeKeyLayoutData); const UCKeyboardLayout *keyboardLayout = (const UCKeyboardLayout *)CFDataGetBytePtr(layoutData); UInt32 keysDown = 0; UniChar chars[4]; UniCharCount realLength; UCKeyTranslate(keyboardLayout, keyCode, kUCKeyActionDisplay, 0, LMGetKbdType(), kUCKeyTranslateNoDeadKeysBit, &keysDown, sizeof(chars) / sizeof(chars[0]), &realLength, chars); CFRelease(currentKeyboard); return CFStringCreateWithCharacters(kCFAllocatorDefault, chars, 1);}/* Returns key code for given character via the above function, or UINT16_MAX * on error. */CGKeyCode keyCodeForChar(const char c){ static CFMutableDictionaryRef charToCodeDict = NULL; CGKeyCode code; UniChar character = c; CFStringRef charStr = NULL; /* Generate table of keycodes and characters. */ if (charToCodeDict == NULL) { size_t i; charToCodeDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 128, &kCFCopyStringDictionaryKeyCallBacks, NULL); if (charToCodeDict == NULL) return UINT16_MAX; /* Loop through every keycode (0 - 127) to find its current mapping. */ for (i = 0; i < 128; ++i) { CFStringRef string = createStringForKey((CGKeyCode)i); if (string != NULL) { CFDictionaryAddValue(charToCodeDict, string, (const void *)i); CFRelease(string); } } } charStr = CFStringCreateWithCharacters(kCFAllocatorDefault, &character, 1); /* Our values may be NULL (0), so we need to use this function. */ if (!CFDictionaryGetValueIfPresent(charToCodeDict, charStr, (const void **)&code)) { code = UINT16_MAX; } CFRelease(charStr); return code;}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1918841', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/217476/']}
jdg_81973
stackexchange
llm_judgeable_groundtruth_similarity
8059526
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: Difference between using var and not using var in JavaScript var foo = 1;foo = 1; What is the difference between above two lines ? Now provide the response and nothing else.
Basically, var declares a variable and you can also assign to it at the same time. Without var , it's assigning to the variable. Assigning will either assign to an existing variable or create a global variable of that name then assign to it. Outside of functions, that means there's no real difference (in principal) if the variable does not already exist. Both create the global variable foo in that case. Within a function, there's a huge difference. The first creates a variable local to the function regardless of whether or not it exists elsewhere. The second will create a global variable if it doesn't exist, or simply change the value if it does exist. In order to keep code as modular as possible, you should always use var unless you are specifically wanting to change existing global variables. That means declaring all globals outside of functions with var and declaring all locals with var .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8059526', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/574122/']}
jdg_81974
stackexchange
llm_judgeable_groundtruth_similarity
8358
Below is a question asked on the forum engineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Not sure how to ask a question usefully, as I'm not an engineer, but here goes. I have a harpsichord, essentially a sort of triangular slab (I'm assuming a general answer, though I could provide specifics) for which I've turned 3 tapered legs, each set in some distance from the edges, and attached securely with 4 screws. But the instrument wobbles extremely easily: if you push it on a side with one finger it's easy to move it half an inch or more. So I'd like it to be "stable" instead of wobbly. Each leg is 2.75" square at the top and at the bottom is a circle with diameter .675". Here's an early version of the leg (its final dimensions are slightly different), but very close to the present version: Here are the legs in context: My question: By what factor do I need to scale the thickness of the present legs (height is constant) to make the instrument "stable?" I'm not sure how to define stable, but the point is, it should only wobble with "significant" effort, not minimal, one-fingered effort. I'm pretty sure that if the thickness was increased by a factor of 10 it wouldn't wobble easily, as it would be resting on tree trunks, practically. But what's a reasonable number? 1.5, 1.7, 2.3? I have no idea, but I'd be grateful for your suggestions. Edit in response to the answer: I'd like to avoid redesigning with bracing. And I've already made a large plate, which is the bottom of the instrument. Assuming a rigid connection with the legs, wouldn't increasing the thickness improve stability? Now provide the response and nothing else.
Since you actually asked for the moment about the $x$ axis. Calculating the moment of inertia about the $x$ axis is a fair deal more complicated than calculating it about the $z$ axis as in my other answer. To start with, we will recognize that the symmetry about the $x$ axis lets us only work on the top half and then multiply by a factor of 2 in the end. Now, only looking at the top half we can break the piece up into two sections: $I_1$ is on the left and is a triangle and $I_2$ is on the right and is a right triangle with a circular hypotenuse. Since this is clearly a homework problem, I'm going to skip the algebra steps and just show you the core parts of the problem (i.e. I'm going to use Mathematica to do the brute force algebra and integration). $I_1$ Calculation The moment of inertia is given by $$I_1=\rho\iint y^2\ dydx,$$where $\rho$ is the mass density per unit area, which looks simple enough. The difficulty is just in getting the correct limits of the double integral. For a a given position along the $x$ axis, the limits of $y$ range from $0$ to $x\tan(\alpha/2)$. And we will integrate $x$ from 0 to $r_0\cos(\alpha/2)$. This gives$$\begin{align}I_1&=\rho\int_0^{r_0\cos(\alpha/2)}dx\int_0^{x\tan(\alpha/2)}dy\ y^2\\&=\rho\int_0^{r_0\cos(\alpha/2)}dx\ x^3\tan^3(\alpha/2)\\&=\rho\frac{r_0^4}{12}\sin^3(\alpha/2)\cos(\alpha/2)\end{align}$$This simplifies to $\frac{\rho}{12} bh^3$ which is the well known value for the moment of inertia of a triangle . $I_2$ Calculation This one goes the same way as the last one, but the limits and the integration are more difficult. This time $x$ will vary from $r_0\cos(\alpha/2)$ to $r_0$. Over that range $y$ will vary from 0 to $\sqrt{r_0^2-x^2}$. Putting this into the integral gives$$\begin{align}I_2&=\rho\int_{r_0\cos(\alpha/2)}^{r_0}dx\int_0^{\sqrt{r_0^2-x^2}}dy\ y^2\\&=\frac{\rho}{3}\int_{r_0\cos(\alpha/2)}^{r_0}dx\ (r_0^2-x^2)^{3/2}\\&=\frac{\rho}{96}r_0^4\left(6\alpha-8\sin(\alpha)+\sin(2\alpha)\right)\end{align}$$That last integral was quite tricky, and I ended up just plugging it into Mathematica. I'm sure it is possible to find it in the standard integral tables though. All together now Finally, putting everything together and working through some trig identities simplifies the whole thing to$$2(I_1+I_2)=\frac{\rho}{8}r_0^4(\alpha-\sin\alpha)$$Which is again what we expect from the standard table for a circular segment .
{}
{'log_upvote_score': 4, 'links': ['https://engineering.stackexchange.com/questions/8358', 'https://engineering.stackexchange.com', 'https://engineering.stackexchange.com/users/5925/']}
jdg_81975
stackexchange
llm_judgeable_groundtruth_similarity
45026
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: Can you give some real-life examples of time series for which a moving average process of order $q$, i.e.$$y_t = \sum_{i=1}^q \theta_i \varepsilon_{t-i} + \varepsilon_t, \text{ where } \varepsilon_t \sim \mathcal{N}(0, \sigma^2) $$has some a priori reason for being a good model? At least for me, autoregressive processes seem to be quite easy to understand intuitively, while MA processes do not seem as natural at first glance. Note that I am not interested in theoretical results here (such as Wold's Theorem or invertibility). As an example of what I am looking for, suppose that you have daily stock returns $r_t \sim \text{IID}(0, \sigma^2)$. Then, average weekly stock returns will have an MA(4) structure as a purely statistical artifact. Now provide the response and nothing else.
One very common cause is mis-specification. For example, let $y$ be grocery sales and $\varepsilon$ be an unobserved (to the analyst) coupon campaign that varies in intensity over time. At any point in time, there may be several "vintages" of coupons circulating as people use them, throw them away, and receive new ones. Shocks can also have persistent (but gradually weakening) effects. Take natural disasters or simply bad weather. Battery sales go up before the storm, then fall during, and then jump again as people people realize that disaster kits may be a good idea for the future. Similarly, data manipulation (like smoothing or interpolation) can induce this effect. I also have "inherently smooth behavior of time series data (inertia) can cause $MA(1)$" in my notes, but that one no longer makes sense to me.
{}
{'log_upvote_score': 6, 'links': ['https://stats.stackexchange.com/questions/45026', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/4783/']}
jdg_81976
stackexchange
llm_judgeable_groundtruth_similarity
1127789
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: If $f(ab)f(ac)f(bc)f(a+b)f(a+c)f(b+c)=2015$ for every positive (non-zero) $a$, $b$ and $c$, find $f(2016)$. Can someone help me? Now provide the response and nothing else.
$$a=b=c=1\to f(1)f(2)=\sqrt[3]{2015}\\a=c=1\to f(1)f(2)f(b)^2f(b+1)^2=2015\to f(b)f(b+1)=\sqrt[3]{2015}\\a=b=c=2\to f(4)=\sqrt[6]{2015}\\f(n)=\sqrt[6]{2015}\text{ by induction}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1127789', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/209130/']}
jdg_81977
stackexchange
llm_judgeable_groundtruth_similarity
12051357
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Creating an object called car: function car(temp){ this.brand=temp[0]; this.color=temp[1]; this.year=temp[2];}var temp = ['Skoda', 'Red', '2012'];car = new car(temp); Setting object and stringify after reading from localStorage: localStorage.setItem('car',car);car = localStorage.getItem('car');car = JSON.stringify(car); car after stringify-----------------> [object Object] at file:///android_asset/www/... Stringify object and Setting object to localStorage after it: localStorage.setItem('car',JSON.stringify(car));car = localStorage.getItem('car'); car after stringify-----------------> "{\"brand\":\"Skoda\",\"color\":\"Red\",\"year\":\"2012\"}" at file:///android_asset/www/... Question 1: Why does it make difference what is the order when you stringify the object? Question 2: Why can't I use stringified object like that: 08-21 11:49:14.860: I/Web Console(9642): car after stringify-----------------> {"brand":"Skoda","color":"Red","year":"2012"} console.log("car.brand----->" +car.brand);car.name----->undefined Now provide the response and nothing else.
From my understanding you can't use your stringified object once it's been stringified because it's no longer an object. It's a String. So when you try to do car.brand on the string there is no property brand . Personally, good practice in my opinion would be to do. function car(temp){ this.brand=temp[0]; this.color=temp[1]; this.year=temp[2]; } var temp = ['Skoda', 'Red', '2012']; car = new car(temp); localStorage.setItem('car',JSON.stringify(car)); car = localStorage.getItem('car'); car = JSON.parse(car); This means the car object is now not a string but an object. When doing this also write to local storage using stringify and read using parse.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12051357', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1165009/']}
jdg_81978
stackexchange
llm_judgeable_groundtruth_similarity
1188925
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: If $f:X\to Y$ is an affine morphism of schemes, say with $Y$ irreducible, that is quasi-finite - all of the fibers, including the generic fiber, are finite - is it true that $f$ is finite? If not, what is a good counterexample. EDIT: I also am requiring that $f$ be closed. Now provide the response and nothing else.
Let $U = \mathbb{P}^1 - \{1\}$ and let $f : U \to \mathbb{P}^1$ be the squaring map $z\mapsto z^2$. Then $f$ is a counterexample. (Note that it is still surjective.) The point is that "closed" is not sufficient. The property you want is "universally closed", that is, remains closed after any base change. It is true that quasi-finite + affine + universally closed $\Rightarrow$ finite. (The precise statement is that finite = quasi-finite + proper.)
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1188925', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/37200/']}
jdg_81979
stackexchange
llm_judgeable_groundtruth_similarity
16914
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: Hi I have some problem how to get count of elements in $\Bbb{Z}_7[x]/(3x^2+2x)$. I think there belong to only polynomials which are indivisible with $3x^2+2x$ ($\gcd=1$). I think it is so as far I know that for example in every $\Bbb{Z}_m$, $m$ prime, is the count of belonging elements eqauls to $\phi(m)$. But I really dont know how to get these polynomials in some efficient way. Now provide the response and nothing else.
Since this seems to be homework, here is just an outline of the proof. Show that the map $X\rightarrow \nabla_X \nabla f$ is self adjoint, that is, that $g(\nabla_X \nabla f, Y) = g(\nabla_Y \nabla f, X)$ for any vector fields $X$ and $Y$. You'll need to use the fact that $\nabla f$ is a gradient field, but you won't need the fact that it has norm 1. Show that $g(\nabla_{\nabla f} \nabla f, X) = 0$ for all $X$ by using 1. to write it as $g(\nabla_X \nabla f, \nabla f)$ and expanding. Here, you'll need to use the fact that $\nabla f$ has norm 1. Once you show this, conclude that $\nabla_{\nabla f} \nabla f = 0$, i.e., that the integral curves are geodesics. Assuming I remember, or that you send a comment, I can update this in a few days with full solutions to either 1 or 2.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/16914', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/5342/']}
jdg_81980
stackexchange
llm_judgeable_groundtruth_similarity
7809397
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 standard way to require a Node module located at some URL (not on the local filesystem)? Something like: require('http://example.com/nodejsmodules/myModule.js'); Currently, I am simply fetching the file into a temporary file, and requiring that. Now provide the response and nothing else.
You can fetch module using http.get method and execute it in the sandbox using vm module methods runInThisContext and runInNewContext . Example var http = require('http') , vm = require('vm') , concat = require('concat-stream'); // this is just a helper to receive the // http payload in a single callback // see https://www.npmjs.com/package/concat-streamhttp.get({ host: 'example.com', port: 80, path: '/hello.js' }, function(res) { res.setEncoding('utf8'); res.pipe(concat({ encoding: 'string' }, function(remoteSrc) { vm.runInThisContext(remoteSrc, 'remote_modules/hello.js'); }));}); IMO, execution of the remote code inside server application runtime may be reasonable in the case without alternatives. And only if you trust to the remote service and the network between.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7809397', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_81981
stackexchange
llm_judgeable_groundtruth_similarity
17350072
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 set soft delete on an intermediate table which is connecting two different types of entities? I've added deleted_at column, but the docs say that I need to put this into the model: protected $softDelete = true; Of course, I don't have a model for an intermediate table. Any idea? Now provide the response and nothing else.
You can put a constraint on the Eager Load: public function groups() { return $this ->belongsToMany('Group') ->whereNull('group_user.deleted_at') // Table `group_user` has column `deleted_at` ->withTimestamps(); // Table `group_user` has columns: `created_at`, `updated_at` } Instead of HARD deleting the relationship using: User::find(1)->groups()->detach(); You should use something like this to SOFT delete instead: DB::table('group_user') ->where('user_id', $user_id) ->where('group_id', $group_id) ->update(array('deleted_at' => DB::raw('NOW()')));
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/17350072', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/256179/']}
jdg_81982
stackexchange
llm_judgeable_groundtruth_similarity
1393946
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 a C# function has an output parameter, you make that clear as follows: private void f(out OutputParameterClass outputParameter); This states that the parameter does not have to be initialized when the function is called. However, when calling this function, you have to repeat the out keyword : f(out outputParameter); I am wondering what this is good for. Why is it necessary to repeat part of the function specification? Does anyone know? Now provide the response and nothing else.
It means you know what you're doing - that you're acknowledging it's an out parameter. Do you really want the utterly different behaviour to happen silently? The same is true for ref , by the way. (You can also overload based on by-value vs out/ref, but I wouldn't recommend it.) Basically, if you've got an (uncaptured) local variable and you use it as a non-out/ref argument, you know that the value of that variable won't be changed within the method. (If it's a reference type variable then the data within the object it refers to may be changed, but that's very different.) This avoids the kind of situation you get in C++ where you unknowingly pass something by reference, but assume that the value hasn't changed...
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1393946', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/74612/']}
jdg_81983
stackexchange
llm_judgeable_groundtruth_similarity
9351423
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In my MySQL database I see these statistics: Type Usage Data 16,384 Bytes Index 32,768 Bytes Overhead 405,0 MB Effective -424,624,128 Bytes Total 49,152 Bytes When I try the commands check table , ALTER TABLE 'mytable' ENGINE = INNODB , OPTIMIZE TABLE , nothing happens to the overhead. Why does nothing happen, should I worry, and when should I worry? I've seen other questions that state 'to worry when the overhead gets too large'. What is too large? Now provide the response and nothing else.
Overhead in PHPMyAdmin is calculated by 'Data_free' column returned by SHOW TABLE STATUS.It is actually explained in MySQL documentation: http://dev.mysql.com/doc/refman/5.1/en/show-table-status.html Data_free: The number of allocated but unused bytes. Beginning with MySQL 5.1.24, this information is also shown for InnoDB tables (previously, it was in the Comment value). InnoDB tables report the free space of the tablespace to which the table belongs. For a table located in the shared tablespace, this is the free space of the shared tablespace. If you are using multiple tablespaces and the table has its own tablespace, the free space is for only that table. Free space means the number of completely free 1MB extents minus a safety margin. Even if free space displays as 0, it may be possible to insert rows as long as new extents need not be allocated. However for InnoDB this is important "InnoDB tables report the free space of the tablespace to which the table belongs. For a table located in the shared tablespace, this is the free space of the shared tablespace.". So with a typical InnoDB setup ('innondb_file_per_table' is not set) you will get the free space for all tables and not for a single table. That is probably why phpMyAdmin ignores/discards the information or on Optimize table nothing happens. You should read this post which clearly explains how to optimize a table in innodb.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9351423', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/675383/']}
jdg_81984
stackexchange
llm_judgeable_groundtruth_similarity
40255096
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 was reading about generator and iterators and the role of __next__() . '__next__' in dir(mygen) . is true '__next__' in dir(mylist) , is false As I looked deeper into it, '__next__' in dir (mylist.__iter__()) is true why is __next__ only available to list but only to __iter__() and mygen but not mylist . How does __iter__() call __next__ when we are stepping thru the list using list-comprehension Trying to manually step (+1) up the generator, I called mygen.__next__() . It doesn't exist. It only exist as mygen.__next__ which is called method-wrapper. what is a method-wrapper and what does it do? How is it applied here: in mygen() and __iter__() ? if __next__ is what both generator and iterator provide (and their sole properties) then what is the difference between generator and iterator?* Answer to 3: Solved, as noted by mod/editor: Difference between Python's Generators and Iterators UPDATE: both generator and iterator have __next__() . My mistake. Looking at the logs, somehow mygen.__next__() test was giving me stopiteration exception error. But I wasn't able to duplicate that error again. Thanks everyone for answering! Now provide the response and nothing else.
The special methods __iter__ and __next__ are part of the iterator protocol to create iterator types . For this purpose, you have to differentiate between two separate things: Iterables and iterators . Iterables are things that can be iterated, usually, these are some kind of container elements that contain items. Common examples are lists, tuples, or dictionaries. In order to iterate an iterable, you use an iterator . An iterator is the object that helps you iterate through the container. For example, when iterating a list, the iterator essentially keeps track of which index you are currently at. To get an iterator, the __iter__ method is called on the iterable. This is like a factory method that returns a new iterator for this specific iterable. A type having a __iter__ method defined, turns it into an iterable. The iterator generally needs a single method, __next__ , which returns the next item for the iteration. In addition, to make the protocol easier to use, every iterator should also be an iterable, returning itself in the __iter__ method. As a quick example, this would be a possible iterator implementation for a list: class ListIterator: def __init__ (self, lst): self.lst = lst self.idx = 0 def __iter__ (self): return self def __next__ (self): try: item = self.lst[self.idx] except IndexError: raise StopIteration() self.idx += 1 return item The list implementation could then simply return ListIterator(self) from the __iter__ method. Of course, the actual implementation for lists is done in C, so this looks a bit different. But the idea is the same. Iterators are used invisibly in various places in Python. For example a for loop: for item in lst: print(item) This is kind of the same to the following: lst_iterator = iter(lst) # this just calls `lst.__iter__()`while True: try: item = next(lst_iterator) # lst_iterator.__next__() except StopIteration: break else: print(item) So the for loop requests an iterator from the iterable object, and then calls __next__ on that iterable until it hits the StopIteration exception. That this happens under the surface is also the reason why you would want iterators to implement the __iter__ as well: Otherwise you could never loop over an iterator. As for generators, what people usually refer to is actually a generator function , i.e. some function definition that has yield statements. Once you call that generator function, you get back a generator . A generator is esentially just an iterator, albeit a fancy one (since it does more than move through a container). As an iterator, it has a __next__ method to “generate” the next element, and a __iter__ method to return itself. An example generator function would be the following: def exampleGenerator(): yield 1 print('After 1') yield 2 print('After 2') The function body containing a yield statement turns this into a generator function. That means that when you call exampleGenerator() you get back a generator object. Generator objects implement the iterator protocol, so we can call __next__ on it (or use the the next() function as above): >>> x = exampleGenerator()>>> next(x)1>>> next(x)After 12>>> next(x)After 2Traceback (most recent call last): File "<pyshell#10>", line 1, in <module> next(x)StopIteration Note that the first next() call did not print anything yet. This is the special thing about generators: They are lazy and only evaluate as much as necessary to get the next item from the iterable. Only with the second next() call, we get the first printed line from the function body. And we need another next() call to exhaust the iterable (since there’s not another value yielded). But apart from that laziness, generators just act like iterables. You even get a StopIteration exception at the end, which allows generators (and generator functions) to be used as for loop sources and wherever “normal” iterables can be used. The big benefit of generators and their laziness is the ability to generate stuff on demand . A nice analogy for this is endless scrolling on websites: You can scroll down item after after (calling next() on the generator), and every once in a while, the website will have to query a backend to retrieve more items for you to scroll through. Ideally, this happens without you noticing. And that’s exactly what a generator does. It even allows for things like this: def counter(): x = 0 while True: x += 1 yield x Non-lazy, this would be impossible to compute since this is an infinite loop. But lazily, as a generator, it’s possible to consume this iterative one item after an item. I originally wanted to spare you from implementing this generator as a fully custom iterator type, but in this case, this actually isn’t too difficult, so here it goes: class CounterGenerator: def __init__ (self): self.x = 0 def __iter__ (self): return self def __next__ (self): self.x += 1 return self.x
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/40255096', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5337263/']}
jdg_81985
stackexchange
llm_judgeable_groundtruth_similarity
89025
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I was going through my professor's notes about Canonical transformations . He states that a canonical transformation from $(q, p)$ to $(Q, P)$ is one that if which the original coordinates obey Hamilton's canonical equations then so do the transformed coordinates, albeit for a different Hamiltonian. He then considers, as an example the Hamiltonian $$H=\frac{1}{2}p^2,$$ with a transformation: $$Q = q,$$$$P = \sqrt{p} - \sqrt{q}.$$ The notes state that this transformation is locally canonical with respect to $H$, and that in the transformed coordinates the new Hamiltonian is: $$K = \frac{1}{3} \left( P + \sqrt{Q} \right)^3.$$ I don't understand how we know that this is locally canonical, or what it really even means to be locally canonical. Also, where do we get K from? Considering that the inverse transformation would be: $$q=Q,$$$$p=\left( P + \sqrt{Q} \right)^2,$$ Why isn't the new Hamiltonian this: $$K= \frac{1}{2} \left(P + \sqrt{Q} \right)^4,$$ where all I've done is plug the inverted transformation into the original Hamiltonian? I'm a bit confused by all this. Would appreciate any help. Now provide the response and nothing else.
Cool question! Thanks to user lionelbrits for his answer that prompted me to pull out my mechanics books and check the definitions of "canonical transformation" given by different authors. If you look in Goldstein's classical mechanics texts in the section on canonical transformations, then you'll find that canonical transformations are essentially defined as follows (I paraphrase) Goldstein Definition: A transformation $f:\mathcal P\to\mathcal P$ on phase space $\mathcal P$ is canonical provided there exists a phase space function $K$ such that if $(q(t), p(t))$ is a solution to Hamilton's equations generated by $H$, then $(Q(t), P(t)) = f(q(t), p(t))$ is a solution to Hamilton's equations generated by $K$. This is essentially the definition given by lionelbrits in his answer. On the other hand, if you look, for example, in Spivak's mechanics text, then you'll find the following definition: Spivak's Definition: A transformation $f:\mathcal P \to \mathcal P$ on phase space is canonical provided it preserves the symplectic form. In more concrete terms (namely in canonical coordinates), Spivak's definition can be stated as follows: The transformation $f(q,p) = (f^q(q,p), f^p(q,p))$ is canonical if and only if its Jacobian (derivative) matrix preserves the symplectic matrix $J$, namely\begin{align} f'(p,q)\,J\,f'(p,q)^t = J \end{align}where\begin{align} J=\begin{pmatrix} 0 & I_n \\ -I_n & 0 \\ \end{pmatrix},\qquad f' = \begin{pmatrix} \frac{\partial f^q}{\partial q} & \frac{\partial f^q}{\partial p} \\ \frac{\partial f^p}{\partial q} & \frac{\partial f^p}{\partial p} \\ \end{pmatrix}\end{align}where $2n$ is the dimension of phase space and $I_n$ is the $n\times n$ identity matrix. It also turns out that If a transformation is canonical in the sense defined by Spivak, then it is canonical is the sense of Goldstein with $K = H\circ f^{-1}$ but the converse is not true. In fact, this example you brink up is a counterexample to the converse! What lionelbrit showed in his answer is that the example you have written is a canonical transformation in the sense of Goldstein, but, as you should try to convince yourself (I did), the function $K = H\circ f^{-1}$ that you wrote down by inverting the transformation and plugging back into $H$ leads to Hamilton's equations that are not satisfied by $(Q(t), P(t)) = f(q(t), p(t))$. You can show this directly by writing down the equations of motion. You can also show this by computing the Jacobian of the transformation and showing that it does not preserve the symplectic matrix. In fact, you should find that the Jacobian is given by\begin{align} f'(q,p)=\begin{pmatrix} 1 & 0 \\ -\frac{1}{2\sqrt{q}} & \frac{1}{2\sqrt{p}} \\ \end{pmatrix}\end{align}and that\begin{align} f'(q,p) J f'(q,p)^t = \frac{1}{2\sqrt{p}} J\end{align}In other words, the Jacobian of the transformation preserves the symplectic matrix up to a multiplicative factor. Speculation. I'm going to go out on a limb and guess that your professor calls Goldstein's definition a "local canonical transformation" and Spivak's definition a "canonical transformation." If we adopt this terminology, then it's clear from our remarks that the $K$ he gives shows that your example is a local canonical transformation, but that the transformation is not canonical.
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/89025', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/35268/']}
jdg_81986
stackexchange
llm_judgeable_groundtruth_similarity
30154560
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 help in clicking each and every link that has been listed under a main menu. I was able to list them using list method. Now I want to click the link as they are being listed and if they open a new window get the URL title and navigate back to current URL. Again list the next link and click. I tried the below code, but it isn't working for me: WebDriver driver = new FirefoxDriver();driver.navigate().to(myurl);WebElement element = driver.findElement(By.linkText(mylinkText));element.click();System.out.println(element.getText());WebElement elements = driver.findElement(By.linkText(mylinkText2));String text123 =elements.getText();List<WebElement> linkElements = driver.findElements(By.tagName(mytagname)); String[] linkTexts = new String[linkElements.size()];int i =0; for (WebElement e : linkElements) { linkTexts[i] = e.getText(); System.out.println("sub menus listed under mylinkText" + linkTexts[i]); WebElement tag = driver.findElement(By.tagName(mytagname2)); Thread.sleep(1000); tag.click(); // driver.navigate().to(linkTexts[i]); Thread.sleep(1000); System.out.println(driver.getCurrentUrl()); driver.navigate().back(); Thread.sleep(1000); if(linkTexts[i].equals(text123)){ break; }i++; Now provide the response and nothing else.
When you concatenate strings, you need to allocate memory to store the result. The easiest to start with is String and &str : fn main() { let mut owned_string: String = "hello ".to_owned(); let borrowed_string: &str = "world"; owned_string.push_str(borrowed_string); println!("{}", owned_string);} Here, we have an owned string that we can mutate. This is efficient as it potentially allows us to reuse the memory allocation. There's a similar case for String and String , as &String can be dereferenced as &str . fn main() { let mut owned_string: String = "hello ".to_owned(); let another_owned_string: String = "world".to_owned(); owned_string.push_str(&another_owned_string); println!("{}", owned_string);} After this, another_owned_string is untouched (note no mut qualifier). There's another variant that consumes the String but doesn't require it to be mutable. This is an implementation of the Add trait that takes a String as the left-hand side and a &str as the right-hand side: fn main() { let owned_string: String = "hello ".to_owned(); let borrowed_string: &str = "world"; let new_owned_string = owned_string + borrowed_string; println!("{}", new_owned_string);} Note that owned_string is no longer accessible after the call to + . What if we wanted to produce a new string, leaving both untouched? The simplest way is to use format! : fn main() { let borrowed_string: &str = "hello "; let another_borrowed_string: &str = "world"; let together = format!("{}{}", borrowed_string, another_borrowed_string); // After https://rust-lang.github.io/rfcs/2795-format-args-implicit-identifiers.html // let together = format!("{borrowed_string}{another_borrowed_string}"); println!("{}", together);} Note that both input variables are immutable, so we know that they aren't touched. If we wanted to do the same thing for any combination of String , we can use the fact that String also can be formatted: fn main() { let owned_string: String = "hello ".to_owned(); let another_owned_string: String = "world".to_owned(); let together = format!("{}{}", owned_string, another_owned_string); // After https://rust-lang.github.io/rfcs/2795-format-args-implicit-identifiers.html // let together = format!("{owned_string}{another_owned_string}"); println!("{}", together);} You don't have to use format! though. You can clone one string and append the other string to the new string: fn main() { let owned_string: String = "hello ".to_owned(); let borrowed_string: &str = "world"; let together = owned_string.clone() + borrowed_string; println!("{}", together);} Note - all of the type specification I did is redundant - the compiler can infer all the types in play here. I added them simply to be clear to people new to Rust, as I expect this question to be popular with that group!
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/30154560', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4884895/']}
jdg_81987
stackexchange
llm_judgeable_groundtruth_similarity
30424355
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 newbie and doing Al Sweigar's book at the moment. In chapter 4's exercise, he asks the following, Say you have a list of lists where each value in the inner lists is a one-character string, like this: grid = [['.', '.', '.', '.', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['O', 'O', 'O', 'O', 'O', '.'], ['.', 'O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['.', '.', '.', '.', '.', '.']] You can think of grid[x][y] as being the character at the x- and y-coordinates of a “picture” drawn with text characters. The (0, 0) origin will be in the upper-left corner, the x-coordinates increase going right, and w the y-coordinates increase going down. Copy the previous grid value, and write code that uses it to print the image. ..OO.OO.. .OOOOOOO. .OOOOOOO. ..OOOOO.. ...OOO... ....O.... So I have written the code and it does what he asks for but I think its very poorly written and I wanted to ask you how can I improve it. My code, grid = [['.', '.', '.', '.', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['O', 'O', 'O', 'O', 'O', '.'], ['.', 'O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['.', '.', '.', '.', '.', '.']]newString = ''for i in range(len(grid)): newString += str(grid[i][0])newString1 = '\n'for i in range(len(grid)): newString1 += str(grid[i][1])newString2 = '\n'for i in range(len(grid)): newString2 += str(grid[i][2])newString3 = '\n'for i in range(len(grid)): newString3 += str(grid[i][3])newString4 = '\n'for i in range(len(grid)): newString4 += str(grid[i][4])newString5 = '\n'for i in range(len(grid)): newString5 += str(grid[i][5])print(newString+newString1+newString2+newString3+newString4+newString5) Output of program: ..OO.OO...OOOOOOO..OOOOOOO...OOOOO.....OOO.......O.... Now provide the response and nothing else.
>>> print('\n'.join(map(''.join, zip(*grid))))..OO.OO...OOOOOOO..OOOOOOO...OOOOO.....OOO.......O.... The zip(*grid) effectively transposes the matrix (flip it on the main diagonal), then each row is joined into one string, then the rows are joined with newlines so the whole thing can be printed at once.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30424355', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4459635/']}
jdg_81988
stackexchange
llm_judgeable_groundtruth_similarity
43415759
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 was wondering if its possible to use a firebase cloud function to send a post request to a non-google server (from what I can find I need to be on the blaze plan in order to interact with non google servers) Basically I want to POST to an external server running on an arduino whenever a value is added to my database. I have looked through the docs and found examples of having a cloud function respond to an HTTP post request (HTTP cloud functions) but can't seem to find any examples of posting to an external server. Is this possible? Now provide the response and nothing else.
Note : request package has been deprecated as stated in the npm page request-npm . Consider using other alternatives like axios This can be done using the request module: // import the modulevar request = require('request');// make the requestrequest('put your external url here', function (error, response, body) { if (!error && response.statusCode == 200) { //here put what you want to do with the request }}) NOTE: This will only work on paid plans. It is not possible to call non-google APIs using the free Spark plan as explained on the Firebase pricing page : The Spark plan allows outbound network requests only to Google-owned services. Inbound invocation requests are allowed within the quota. On the Blaze plan, Cloud Functions provides a perpetual free tier. The first 2,000,000 invocations, 400,000 GB-sec, 200,000 CPU-sec, and 5 GB of Internet egress traffic is provided for free each month. You are only charged on usage past this free allotment. Pricing is based on total number of invocations, and compute time. Compute time is variable based on the amount of memory and CPU provisioned for a function. Usage limits are also enforced through daily and 100s quotas. For more information, see Cloud Functions Pricing .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/43415759', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2217579/']}
jdg_81989
stackexchange
llm_judgeable_groundtruth_similarity
364375
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I'm wearing the devops hat for my company. All our infrastructure is manually configured in AWS and I would like to start using Chef for configuration. First step: Make it easy to bootstrap an environment and reach out to the chef server! Here is my thoughts on how to approach it. Start a fresh Ubuntu AMI Add a script that runs at startup the bootstraps an enviro (ruby, ruby gems, etc.) and registers with Chef. Squirrel away this as a custom AMI so I can start many of these. So, my question is: What is the best way to go about running a script just once on the next startup? Now provide the response and nothing else.
Changing the Content-Type of .txt files may work, but it's a somewhat risky way to solve this problem, because you can't guarantee 100% that the user's browser will respond how you expect. And furthermore, it's misleading to label a .txt file as a binary file. Instead, I suggest using the standard way to force a browser to download rather than display the file, which is to use the Content-Disposition header with a value of attachment ( RFC 2183 , see also RFC 2616 ). For example, this nginx location block will send down such a header with .txt files under the /downloads/ URI and thus they will be forced to download: location ~ ^/downloads/.*\.txt$ { add_header Content-Disposition "attachment";} So you could add other appropriate matching, etc, appropriate to your configuration.
{}
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/364375', 'https://serverfault.com', 'https://serverfault.com/users/112196/']}
jdg_81990
stackexchange
llm_judgeable_groundtruth_similarity
583064
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: #!/usr/bin/env bashset -euo pipefailif [ -z "$BUILD_DATE" ]; then export BUILD_DATE="$(date +%s%N)" echo "???"else echo "!!!!!!!"fi The above does not output anything as it runs into an error: env/local-testing.sh:22: BUILD_DATE: parameter not set . Is there an alternative to running set +u and set -u again surrounding this conditional? Now provide the response and nothing else.
If you're running under set -u and have a variable that might be unset, and you would need to test whether it's empty with the -z test, then you can use if [ -z "${BUILD_DATE:-}" ]; then The "${BUILD_DATE:-}" would expand to an empty string if the BUILD_DATE variable is empty or unset.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/583064', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/124109/']}
jdg_81991
stackexchange
llm_judgeable_groundtruth_similarity
3126169
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: $ABCD$ is a square, $E$ is a midpoint of side $BC$ , points $F$ and $G$ are on the diagonal $AC$ so that $|AF|=3\ \text{cm}$ , $|GC|=4\ \text{cm}$ and $\angle{FEG}=45 ^{\circ}$ . Determine the length of the segment $FG$ . How can I approach this problem, preferably without trigonometry? Now provide the response and nothing else.
Let $H$ be the midpoint of $AC$ and $\angle EIC= 90^{\circ}$ . We can observe that $$FH+3=HG+4,\quad FH+HG=x.$$ So we obtain $HG=\frac{x-1}2$ . Since two corresponding angles are congruent; $\angle FEG =\angle EHG=45^{\circ}$ and $\angle EGF=\angle HGE$ , we have that $\triangle FEG$ and $\triangle EHG$ are similar to each other. This gives $$FG:EG=EG:HG\implies EG^2 = FG\cdot HG=\frac{x(x-1)}2.$$ Now, note that $EI=\frac14 AC=\frac{x+7}4$ and $IG=IH-GH=\frac{x+7}{4}-\frac{x-1}2=\frac{9-x}{4}$ . Since $\triangle EIG$ is a right triangle, by Pythagorean theorem, we find that $$EG^2=\frac{x(x-1)}{2}=EI^2+IG^2=\frac{(x+7)^2}{16}+\frac{(9-x)^2}{16},$$ which implies $x=5 $ or $x=-\frac{13}3$ . Since $x>0$ , we get $x=5$ .
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/3126169', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/19583/']}
jdg_81992
stackexchange
llm_judgeable_groundtruth_similarity
6434865
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 pass an object to HTML attributes?For example I have the following code: var attrs = new { id = "myid", style = "color: Red;" }; How to convert attrs to string like this to embed them into an HTML markup: id="myid" style="color: Red;" Thanks in advance :) Now provide the response and nothing else.
This functionality is, surprisingly enough, provided by the RouteValueDictionary class: IDictionary<string, object> htmlAttributes = new RouteValueDictionary(attrs); You can then use this dictionary in conjunction with a TagBuilder , which you will probably be using anyway: var tagBuilder = new TagBuilder("input");tagBuilder.MergeAttributes(htmlAttributes);tagBuilder.ToString(TagRenderMode.Normal); You can see this done in the ASP.NET MVC source code itself; one of the simpler examples is in TextAreaExtensions.cs . EDIT: In order to properly convert "data_attr" to "data-attr", use the AnonymousObjectToHtmlAttributes static method. IDictionary<string, object> htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(attrs);
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6434865', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/463650/']}
jdg_81993
stackexchange
llm_judgeable_groundtruth_similarity
48066337
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 project on ReadTheDocs. As part of the documentation generation, I have Sphinx compile a large number of images using matplotlib's plot directive showing what various commands do. It seems this takes more memory than RTD allocates for a build process. I'm trying to figure out what to do about this. Thoughts I have: I could pay RTD to increase my memory limit. But I am a small developer working on an as-yet boutique analysis tool, and their plan is pricey. I could switch to a smaller dataset for my figure generation and hope this uses less memory. This kind of guess-and-check strategy is frustrating and may not be sustainable anyway, if the number of images increases or the computational complexity increases. I could commit statically generated images to the existing repo and hack together an extension that generates new images only if the static image is not already present. But I do not like this because now my code repo will grow every time the images need to be changed for some reason, and I prefer to keep the repo light-weight. I could commit the compiled documentation to a separate repo of some sort and upload that to RTD. This prevents the code repo from growing every time an image changes. However, I'm not sure how to tell RTD about this documentation. What is a good way to include computationally-expensive auto-generated images in a ReadTheDocs project? Now provide the response and nothing else.
It is definitely possible. One approach would be to adjust the flake8 output using the --format command-line option to specify http(s) links to the Flake8Rules catalog: --format='%(path)s:%(row)d,%(col)d:%(code)s:%(text)s:https://lintlyci.github.io/Flake8Rules/rules/%(code)s.html' The problem then is for the console or PyCharm output window to render the links properly. Fortunately, we can do that using the plugins - "Awesome Console" for the terminal and "Console Link" for the output window. Step-by-step Instructions make sure to have flake8 installed in the current Python environment install "Awesome Console" plugin: go to PyCharm Preferences -> Plugins -> Browser Repositories... find "Awesome Console" and install (PyCharm restart required): configure "flake8" as an External Tool : go to PyCharm Preferences -> Tools -> External Tools -> "+" configure the path to flake8 as well as $FilePath$ placeholder for the desired directory/path to be processed: Demo Now, let's say we have created this test.py file with a few violations: def f(a = 10): return a*10 If we right-click on a test.py file, select External Tools -> flake8 , this is the output we are going to get (note the clickable links for every warning): Now, whenever in doubt, we can follow the link for additional details about a warning. This is just one way to do it, would be happy to hear if there is an easier or better way to combine these tools and projects.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/48066337', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/752843/']}
jdg_81994
stackexchange
llm_judgeable_groundtruth_similarity
104324
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Is there a way to use strucchange package in R on ARIMA models?I haven't been able to find any.Thanks a lot. Now provide the response and nothing else.
The package strucchange requires as input the formula of a linear model to be passed to lm . I don't think there is a straightforward way to use the package with function arima . I don't know either any other R packages implementing this but I can give some basic guidelines that may be helpful for your purposes. You can carry out some diagnostics based on the cumulative sum of squared residuals (CUMSUM) and based on F-tests for the parameters of the model in different subsamples. Let's take for illustration the following simulated AR process, x . The first 50 observations are generated from an AR(1) model and the next 100 observations from an AR(2) model: set.seed(135)x1 <- arima.sim(model = list(order = c(1,0,0), ar = -0.2), n = 50)x2 <- arima.sim(model = list(order = c(2,0,0), ar = c(0.3, 0.5)), n = 100)x <- ts(c(x1, x2)) CUMSUM approach: Once an AR model is fitted to the entire series the CUMSUM process can be obtained as follows: fit <- arima(x, order = c(2,0,0), include.mean = FALSE)e <- residuals(fit)sigma <- sqrt(fit$sigma2)n <- length(x)cs <- cumsum(e) / sigma As a reference, confidence limits can be obtained as done in package strucchange for the OLS-based CUSUM test. For that, we can create an object of class efp and plot it: require(strucchange)retval <- list()retval$coefficients <- coef(fit)retval$sigma <- sigmaretval$process <- csretval$type.name <- "OLS-based CUSUM test"retval$lim.process <- "Brownian bridge"retval$datatsp <- tsp(x)class(retval) <- c("efp")plot(retval) The confidence limits are just for reference, I'm not sure they are the right values to carry out a formal test in this context. Regardless of this, a sudden change or shift in the sequence cs can be interpreted as a sign that something is going on around that time point, possibly a structural change. In the plot we observe that at around observation 50, where we introduced a change in the data generating process. F-tests: Another approach is based on F-test statistics computed as:$$Fstat = \frac{RSS - USS}{RSS/n}$$where RSS is the residual sum of squares in the restricted model (the model fitted for the entire data) and USS is the residual sum of squares of models fitted to two subsamples. The statistics can be computed iteratively for the following sequence of subsamples: from observations 1 to 20 and 21 to $n$; then from 1 to 21 and a next subsample from 22 to $n$, and so on as done below: rss <- sum(residuals(fit)^2)sigma2 <- fit$sigma2stats <- rep(NA, n)for (i in seq.int(20, n-20)){ fit1 <- arima(x[seq(1,i)], order = c(2,0,0), include.mean = FALSE) fit2 <- arima(x[seq(i+1,n)], order = c(2,0,0), include.mean = FALSE) ess <- sum(c(residuals(fit1), residuals(fit2))^2) stats[i] <- (rss - ess)/sigma2} Similarly to the CUMSUM plot, a plot of the F-statistics may reveal the presence of a structural change. A 95% confidence limit can be obtained based on the chi-square distribution. plot(stats)abline(h = qchisq(0.05, df = length(coef(fit)), lower.tail = FALSE), lty = 2, col = "red") If the minimum p-value related to each statistic is below a significance level, e.g. 0.05, then we can suspect that there is a structural change at that point. In this simulated series that happens at observation 50, when the AR coefficients changed in the data generating process: which.min(1 - pchisq(stats, df = 2))#[1] 50 You may find further details in the vignette of the strucchange package that you probably already know and in the references therein.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/104324', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/43790/']}
jdg_81995
stackexchange
llm_judgeable_groundtruth_similarity
16203394
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Trying to make a text adventure with a game engine somewhat in Python. Anyway I keep getting this error message. TypeError: module.__init__() takes at most 2 arguments (3 given) Here is my code: from engine import gamefrom engine import eventfrom engine import placeclass TextAdventureGame(game): def __init__(self): super(TextAdventureGame, self).__init__() self.introduction = ('''Welcome to Can You Escape text adventure game.You wake up in a dark room and you have no idea where you are.''') Why does this error occur? class TextAdventureGame(game):TypeError: module.__init__() takes at most 2 arguments (3 given) Now provide the response and nothing else.
This usually means your connection string isn't any good. If you look at the stack trace, you'll notice that this is failing when trying to interpret your connection string. Check your connection string to make sure it is correct - or post it here for help (but without any sensitive information such as passwords ;) ) UPDATE According to the SqlDatabase documentation the SqlDatabase class takes a connection string, not a key to the connection string configuration. So new SqlDatabase("SiteSqlServer"); Should be var connection = ConfigurationManager.ConnectionStrings["SiteSqlServer"];Database objDB = new SqlDatabase(connection.ConnectionString); (I have omitted any defensive code here for brevity)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16203394', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2117754/']}
jdg_81996
stackexchange
llm_judgeable_groundtruth_similarity
15259632
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 never done something like this before and I am asking how to do this. I can find how to do this with plain html multiform part etc. But now how to do this with ajax? Pseudo code: html: <input type="text" class="imgform" name="imagename" value="name" /><input type="file" class="imgform_image" name="image" value="C:\Users\william\Pictures\image.png" /><input type="button" id="btn" form="imgform" /> JQUERY: $('body').on('click', '#btn', function(){ var form = $(this).attr("form"); var string = $('.' + form).serialize(); var image = $('.imgform_image').value("form"); image = converttobase64(image); $.post('action.php?action=uploadimg', string + {'image':image}, function (data){ datalader(data); });}); No clue on how to do this. Also is there a way to do this for multiple img files and chek if the the file actually is a image and of course use the filename as the image name instead of using a input textfield. Any tip, link or code example would be useful thank you in advance! Now provide the response and nothing else.
Note: I totally reviewed my answer and made it better! HTML First we make a traditional form without a confirm button. Instead we make a button. <form enctype="multipart/form-data" id="myform"> <input type="text" name="some_usual_form_data" /> <br> <input type="file" accept="image/*" multiple name="img[]" id="image" /> <sub>note that you have to use [] behind the name or php wil only see one image</sub> <br> <input type="button" value="Upload images" class="upload" /></form><progress value="0" max="100"></progress><hr><div id="content_here_please"></div> Javascript/jquery upload side than here is the Javascript.. o yes and Jquery to upload the images and the other form data: $(document).ready(function () { $('body').on('click', '.upload', function(){ // Get the form data. This serializes the entire form. pritty easy huh! var form = new FormData($('#myform')[0]); // Make the ajax call $.ajax({ url: 'action.php', type: 'POST', xhr: function() { var myXhr = $.ajaxSettings.xhr(); if(myXhr.upload){ myXhr.upload.addEventListener('progress',progress, false); } return myXhr; }, //add beforesend handler to validate or something //beforeSend: functionname, success: function (res) { $('#content_here_please').html(res); }, //add error handler for when a error occurs if you want! //error: errorfunction, data: form, // this is the important stuf you need to overide the usual post behavior cache: false, contentType: false, processData: false }); }); }); // Yes outside of the .ready space becouse this is a function not an event listner! function progress(e){ if(e.lengthComputable){ //this makes a nice fancy progress bar $('progress').attr({value:e.loaded,max:e.total}); } } PHP processing side And for those who need the php side to do something with those images here is the php code to loop trough: <?php $succeed = 0; $error = 0; $thegoodstuf = ''; foreach($_FILES["img"]["error"] as $key => $value) { if ($value == UPLOAD_ERR_OK){ $succeed++; // get the image original name $name = $_FILES["img"]["name"][$key]; // get some specs of the images $arr_image_details = getimagesize($_FILES["img"]["tmp_name"][$key]); $width = $arr_image_details[0]; $height = $arr_image_details[1]; $mime = $arr_image_details['mime']; // Replace the images to a new nice location. Note the use of copy() instead of move_uploaded_file(). I did this becouse the copy function will replace with the good file rights and move_uploaded_file will not shame on you move_uploaded_file. copy($_FILES['img']['tmp_name'][$key], './upload/'.$name); // make some nice html to send back $thegoodstuf .= " <br> <hr> <br> <h2>Image $succeed - $name</h2> <br> specs, <br> width: $width <br> height: $height <br> mime type: $mime <br> <br> <br> <img src='./upload/$name' title='$name' /> "; } else{ $error++; } } echo 'Good lord vader '.$succeed.' images where uploaded with success!<br>'; if($error){ echo 'shameful display! '.$error.' images where not properly uploaded!<br>'; } echo 'O jeah there was a field containing some usual form data: '. $_REQUEST['some_usual_form_data']; echo $thegoodstuf;?> live demo at my dev web server which is not always online! If you want to compress and resize You need this class: class SimpleImage{ var $image; var $image_type; function load($filename){ $image_info = getimagesize($filename); $this->image_type = $image_info[2]; if($this->image_type == IMAGETYPE_JPEG) { $this->image = imagecreatefromjpeg($filename); } elseif($this->image_type == IMAGETYPE_GIF) { $this->image = imagecreatefromgif($filename); } elseif($this->image_type == IMAGETYPE_PNG) { $this->image = imagecreatefrompng($filename); } } function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=0777){ if($image_type == IMAGETYPE_JPEG) { $gelukt = imagejpeg($this->image,$filename,$compression); } elseif($image_type == IMAGETYPE_GIF) { $gelukt = imagegif($this->image,$filename); } elseif($image_type == IMAGETYPE_PNG) { $gelukt = imagepng($this->image,$filename); } if($permissions != false) { chmod($filename,$permissions); } return $gelukt; } function output($image_type=IMAGETYPE_JPEG) { if($image_type == IMAGETYPE_JPEG) { imagejpeg($this->image); } elseif($image_type == IMAGETYPE_GIF) { imagegif($this->image); } elseif($image_type == IMAGETYPE_PNG) { imagepng($this->image); } } function getWidth(){ return imagesx($this->image); } function getHeight(){ return imagesy($this->image); } function maxSize($width = 1920, $height = 1080){ if(($this->getHeight() > $height) && ($this->getWidth() > $width)){ $ratio = $height / $this->getHeight(); $newwidth = $this->getWidth() * $ratio; if($newwidth > $width){ $ratio = $width / $newwidth; $height = $height * $ratio; $newwidth = $width; } $this->resize($newwidth,$height); return true; } elseif($this->getHeight() > $height){ $ratio = $height / $this->getHeight(); $width = $this->getWidth() * $ratio; $this->resize($width,$height); return true; } elseif($this->getWidth() > $width){ $ratio = $width / $this->getWidth(); $height = $this->getheight() * $ratio; $this->resize($width,$height); return true; } return false; } function resizeToHeight($height){ $ratio = $height / $this->getHeight(); $width = $this->getWidth() * $ratio; $this->resize($width,$height); } function resizeToWidth($width){ $ratio = $width / $this->getWidth(); $height = $this->getheight() * $ratio; $this->resize($width,$height); } function scale($scale){ $width = $this->getWidth() * $scale/100; $height = $this->getheight() * $scale/100; $this->resize($width,$height); } function resize($width,$height) { $new_image = imagecreatetruecolor($width, $height); if( $this->image_type == IMAGETYPE_GIF || $this->image_type == IMAGETYPE_PNG ) { $current_transparent = imagecolortransparent($this->image); if($current_transparent != -1) { $transparent_color = imagecolorsforindex($this->image, $current_transparent); $current_transparent = imagecolorallocate($new_image, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']); imagefill($new_image, 0, 0, $current_transparent); imagecolortransparent($new_image, $current_transparent); } elseif($this->image_type == IMAGETYPE_PNG) { imagealphablending($new_image, false); $color = imagecolorallocatealpha($new_image, 0, 0, 0, 127); imagefill($new_image, 0, 0, $color); imagesavealpha($new_image, true); } } imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight()); $this->image = $new_image; }} you can use it like this: $succeed = 0;$error = 0;$thegoodstuf = '';foreach($_FILES["img"]["error"] as $key => $value) { if ($value == UPLOAD_ERR_OK){ $succeed++; $name = $_FILES["img"]["name"][$key]; $image = new SimpleImage(); $image->load($_FILES['img']['tmp_name'][$key]); $chek = $image->maxSize(); if($chek){ $move = $image->save('./upload/'.$name); $message= 'Afbeelding verkleind naar beter formaat!<br>'; } else{ $move = copy($_FILES['img']['tmp_name'][$key], './upload/'.$name); #$move = move_uploaded_file($_FILES['img']['tmp_name'][$key], './upload/'.$name); $message= ''; } if($move){ $arr_image_details = getimagesize('./upload/'.$name); $width = $arr_image_details[0]; $height = $arr_image_details[1]; $mime = $arr_image_details['mime']; $thegoodstuf .= " <br> <hr> <br> <h2>Image $succeed - $name</h2> <br> specs, <br> $message width: $width <br> height: $height <br> mime type: $mime <br> <br> <br> <img src='./upload/$name' title='$name' /> "; } else{ $error++; } } else{ $error++; }}echo 'Good lord vader '.$succeed.' images where uploaded with success!<br>';if($error){ echo 'shameful display! '.$error.' images where not properly uploaded!<br>';}echo 'O jeah there was a field containing some usual form data: '. $_REQUEST['some_usual_form_data'];echo $thegoodstuf;
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15259632', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1714329/']}
jdg_81997
stackexchange
llm_judgeable_groundtruth_similarity
22766017
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 zxing to generate barcodes with different types (EAN, 2of5 and DataMatrix). Generating in general works fine. The only problem I currently have is that zxing only generates a 14x14 pixel bitmap which is way too small. But only when using DataMatrix! EAN13, 2of5/ITF and QR-Codes work perfect with the same code. My code: BitMatrix bitMatrix = new DataMatrixWriter().encode(message, BarcodeFormat.DATA_MATRIX, 1080, 1080, null);int height = bitMatrix.getHeight(); //height is always 14, it doesn't matter what value I pass to the encoder As you can imagine this looks pretty shitty on a 1080p screen like the nexus 5. Am I getting something wrong? Do I have to do some special settings for DataMatrix? Google and Stackoverflow couldn't help me so far as I can't find any examples for the usage of DataMatrix Update This is how I convert the bitmatrix to a bitmap int width = bitMatrix.getWidth(); int height = bitMatrix.getHeight(); int[] pixels = new int[width * height]; // All are 0, or black, by default for (int y = 0; y < height; y++) { int offset = y * width; for (int x = 0; x < width; x++) { pixels[offset + x] = bitMatrix.get(x, y) ? BLACK : WHITE; } } Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); bitmap.setPixels(pixels, 0, width, 0, 0, width, height); If I use any other values for the height I get an OutOfBoundsException which is pretty obvious (I didn't expect anything else)... When I try to scale the imageview and set a fixed width and height, the barcode is scannable but looks like shit. This is obvious too, as the bitmatrix is only 14x14 instead of the size I specified. Is there a simple way to somehow scale a bitmatrix? Because it only consists of dots so it should be possible but I don't want to calculate it myself. I couldn't find any documentation for bitmatrix besides stackoverflow and this didn't help me at all. If I pass a MinWidth or MaxWidth to the encoder via HintMap the app always crashes with an Exception.HintMap (mWidth is the display width of the device but I tried several values): Hashtable hintMap = new Hashtable(); hintMap.put(EncodeHintType.MIN_SIZE, new Dimension(mWidth, mWidth));hintMap.put(EncodeHintType.MAX_SIZE, new Dimension(mWidth, mWidth));hintMap.put(EncodeHintType.DATA_MATRIX_SHAPE, SymbolShapeHint.FORCE_SQUARE); Exception: java.lang.IllegalArgumentException: Can't find a symbol arrangement that matches the message. Data codewords: 7 This last issue seems to me like a bug in zxing. I don't get it why the generating doesn't work if I change the size. Now provide the response and nothing else.
Here is a small example how you can change your method for the conversion from BitMatrix to Bitmap. The method does the scaling of the BitMatrix. int BLACK = 0xFF000000;int WHITE = 0xFFFFFFFF;// change the values to your needsint requestedWidth = 300;int requestedHeight = 300;int width = bitMatrix.getWidth();int height = bitMatrix.getHeight();// calculating the scaling factorint pixelsize = requestedWidth/width;if (pixelsize > requestedHeight/height){ pixelsize = requestedHeight/height;}int[] pixels = new int[requestedWidth * requestedHeight];// All are 0, or black, by defaultfor (int y = 0; y < height; y++) { int offset = y * requestedWidth * pixelsize; // scaling pixel height for (int pixelsizeHeight = 0; pixelsizeHeight < pixelsize; pixelsizeHeight++, offset+=requestedWidth) { for (int x = 0; x < width; x++) { int color = bitMatrix.get(x, y) ? BLACK : WHITE; // scaling pixel width for (int pixelsizeWidth = 0; pixelsizeWidth < pixelsize; pixelsizeWidth++) { pixels[offset + x * pixelsize + pixelsizeWidth] = color; } } }}Bitmap bitmap = Bitmap.createBitmap(requestedWidth, requestedHeight, Bitmap.Config.ARGB_8888);bitmap.setPixels(pixels, 0, requestedWidth, 0, 0, requestedWidth, requestedHeight);// I could only test it with BufferedImage and a modified version of the zxing J2SE client// BufferedImage bitmap = new BufferedImage(requestedWidth, requestedHeight, BufferedImage.TYPE_INT_ARGB);// bitmap.getRaster().setDataElements(0, 0, requestedWidth, requestedHeight, pixels);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22766017', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1384756/']}
jdg_81998
stackexchange
llm_judgeable_groundtruth_similarity
39532594
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: in my MainActivity, which extends from AppCompatActivity, I want to override the onBackPressed method like so: @Overridepublic void onBackPressed() { Log.d("MainActivity","onBackPressed"); Toast.makeText(getApplicationContext(),"onBackPressed",Toast.LENGTH_SHORT).show();} but onBackPressed does not get called. How ever if I do not override onBackPressed, the application closes, when I press the backbutton and if I do override it it doesn't. The rest of my activity looks like this: public class MainActivity extends AppCompatActivity {private Toolbar toolbar;private Drawer drawer;private FloatingActionButton fab_test;@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); fab_test = (FloatingActionButton) findViewById(R.id.fab_test); fab_test.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(getApplicationContext(),"FAB Test pressed",Toast.LENGTH_SHORT).show(); } }); buildDrawer(); getSupportFragmentManager().beginTransaction().add(R.id.fragmentContainer,page).commit();}@Overridepublic void onBackPressed() { Log.d("MainActivity","onBackPressed"); Toast.makeText(getApplicationContext(),"onBackPressed",Toast.LENGTH_SHORT).show();}@Overridepublic boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main_menu, menu); return true;}} EDIT: I'm talking about the hardware-backbutton(not the actionbar one) Now provide the response and nothing else.
This question is already answered, but I feel to clear something here in this topic. Most comments and answeres point out to use super.onBackPressed() and that this is the cause of the not working method onBackPressed() . But that is not correct and important to let other beginners know. The method onBackPressed() does not need to use super.onBackPressed() . onBackPressed() also works if somebody, for example, comment super.onBackPressed() out. As the questionier has written, he won´t use super.onBackPressed() because it will close the activity. So, the cause of this why it isn´t working, could be seperated into three possible causes: The Log doesn´t work because of a wrong filter in the logcat console The Toast dosn´t work because of the wrong passed context The OS is implemented wrong by the supplier. Usually, the toast works by passing the correct context. In the case of questioner, simply passing this . @Overridepublic void onBackPressed() { Log.d("MainActivity","onBackPressed"); Toast.makeText(this,"onBackPressed",Toast.LENGTH_SHORT).show();} For the Log, simply set the correct filter on logcat. I don´t care if somebody give downvotes now, but it must be clear for other beginners, that super.onBackPressed() must not be used. Anyway, the use of onKeyDown() also is a solution.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/39532594', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6792590/']}
jdg_81999
stackexchange
llm_judgeable_groundtruth_similarity
3485009
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have this definite integral $$\int_{-1}^14x^3-x\,dx=0$$ I had that function rendered and found out it should be calculated in four intervals: $[-1,-0.5], [-0.5,0], [0,0.5], [0.5,1].$ Is there any other (shorter and correct) method how to calculate that? thx :) Now provide the response and nothing else.
Yes, you're right — this is a bit of a problem. But the issue is not with the Fundamental Theorem of Calculus (FTC), but with that integral. In order to take the derivative of a function (with or without the FTC), we've got to have that function in the first place. So the real question is: do we have a function defined as $$F(x)=\int_0^x \ln(t)\,dt \quad ?$$ As you correctly noticed, we have a problem here with the lower limit of integration, since $\ln(0)$ is undefined. So this integral does not make sense as a usual integral, but it does as an improper integral — of course, if we also assume that its domain is $x\ge0$ . Let's evaluate this improper integral: $$F(x)=\int_0^x \ln(t)\,dt=\lim_{b\to0^{+}}\int_b^x \ln(t)\,dt=\lim_{b\to0^{+}}\left.\left(t\ln(t)-t\right)\right|_b^x=\lim_{b\to0^{+}}\left[\left(x\ln(x)-x\right)-\left(\color{red}{b\ln(b)}-b\right)\right]=x\ln(x)-x-\color{red}{0}+0=x\ln(x)-x.$$ The only non-trivial part there was the limit highlighted in red, and it can be shown to be zero using L'Hôpital's Rule: $$\lim_{b\to0^{+}}b\ln(b)=\lim_{b\to0^{+}}\frac{\ln(b)}{1/b}=\frac{-\infty}{+\infty}=\lim_{b\to0^{+}}\frac{1/b}{-1/b^2}=\lim_{b\to0^{+}}(-b)=0.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3485009', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/712300/']}
jdg_82000
stackexchange
llm_judgeable_groundtruth_similarity
39491
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Consider a planar point process $X$ and call $N_A = \text{Card}\big( X \cap A\big)$ the number of points inside the subset $A \subset \mathbb{R}^2$. If one knows the law of $(N_{A_1}, \ldots, N_{A_r})$ for any sets $A_1, \ldots, A_r$, then the process is completely characterized. I recently learned that it in fact suffices to know $f(A)=P(N_A=0)$ (called the void-probability function) for any set $A$ in order to completely characterize the law of $X$. Intuitively, I do not understand why such a result is true. Indeed, the knowledge of the function $f$ brings some information in the correlation structure of the process $X$: nevertheless, I still fail to understand how the function $f$ can encode the whole correlation structure of the process. Any thoughts on this ? Now provide the response and nothing else.
This is only true for simple point processes (no duplicate points). By the inclusion-exclusion principle, $f$ determines the joint distribution of several (disjoint) sets being empty or occupied. If the process is simple this allows recovering the law of $(N_{A_1},\dots,N_{A_r})$ as a limit over finer partitions.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/39491', 'https://mathoverflow.net', 'https://mathoverflow.net/users/1590/']}
jdg_82001
stackexchange
llm_judgeable_groundtruth_similarity
462451
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 read in the Essential C# 3.0 and .NET 3.5 book that: GetHashCode()’s returns over the life of a particular object should be constant (the same value), even if the object’s data changes. In many cases, you should cache the method return to enforce this. Is this a valid guideline? I have tried a couple built-in types in .NET and they didn't behave like this. Now provide the response and nothing else.
The answer is mostly, it is a valid guideline, but perhaps not a valid rule. It also doesn't tell the whole story. The point being made is that for mutable types, you cannot base the hash code on the mutable data because two equal objects must return the same hash code and the hash code has to be valid for the lifetime of the object. If the hash code changes, you end up with an object that gets lost in a hashed collection because it no longer lives in the correct hash bin. For example, object A returns hash of 1. So, it goes in bin 1 of the hash table. Then you change object A such that it returns a hash of 2. When a hash table goes looking for it, it looks in bin 2 and can't find it - the object is orphaned in bin 1. This is why the hash code must not change for the lifetime of the object , and just one reason why writing GetHashCode implementations is a pain in the butt. Update Eric Lippert has posted a blog that gives excellent information on GetHashCode . Additional Update I've made a couple of changes above: I made a distinction between guideline and rule. I struck through "for the lifetime of the object". A guideline is just a guide, not a rule. In reality, GetHashCode only has to follow these guidelines when things expect the object to follow the guidelines, such as when it is being stored in a hash table. If you never intend to use your objects in hash tables (or anything else that relies on the rules of GetHashCode ), your implementation doesn't need to follow the guidelines. When you see "for the lifetime of the object", you should read "for the time the object needs to co-operate with hash tables" or similar. Like most things, GetHashCode is about knowing when to break the rules.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/462451', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/51816/']}
jdg_82002
stackexchange
llm_judgeable_groundtruth_similarity
95302
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: As someone who trained as a physicist, I have known for ages that $\operatorname{SU}(2)$ is a double cover of $\operatorname{SO}(3)$, so, during an idle day at the office I decided to look up what this meant. It turned out to be more complicated than I had expected. The definition of a covering space of a topological space seemed to be quite fiddly and left me thinking that these things were born of utility rather than essential beauty. So, what are they for, and why are they more useful, than say a simple open cover? And why are the pre-images of a point in the covered space called a ‘fibre’ (is it linked to fibre bundles in differential geometry?). And, all of the many definitions I have seen seem to imply that the fibres must be discrete (presumably, countably infinite at the most, does this follow from the definitions?), and beyond that they always seem to be finite and of the same number (i.e., always $2$ at every point in the case of $\operatorname{SU}(2)$ and $\operatorname{SO}(3)$) is this always the case? Now provide the response and nothing else.
Covering spaces naturally occur in the study of analytic continuation (in fact I believe this is where they first appeared). For example, the square root function $\sqrt{z}$ cannot be extended to a holomorphic function on all of $\mathbb{C}$. It can be locally defined on various open sets in $\mathbb{C} - \{ 0 \}$, and by analytic continuation it can be defined, for example, starting from a neighborhood of $z = 1$ (so that $\sqrt{z} = 1$ for example) and counterclockwise around the origin. However, this process is inconsistent: when you get back to $z = 1$ you'll find that $\sqrt{z} = -1$. The solution is to define $\sqrt{z}$ on a double cover of $\mathbb{C} - \{ 0 \}$; there are two sheets of the cover for each of the two possible values of the square root. Similarly, $\sqrt[n]{z}$ is defined on an $n$-sheeted cover of $\mathbb{C} - \{ 0 \}$, and $\log z$ is defined on a cover of $\mathbb{C} - \{ 0 \}$ with infinitely many sheets. There is a nice analogy with the theory of field extensions and Galois theory ; the double cover mentioned above corresponds in some sense to the field extension $\mathbb{C}(z, \sqrt{z})$ of the field $\mathbb{C}(z)$, and it has Galois group $\mathbb{Z}/2\mathbb{Z}$. In this analogy the fundamental group of a space is analogous to the absolute Galois group of a field, and this has been a very fruitful analogy in mathematics, leading to the theory of the étale fundamental group . These ideas are thoroughly explored in Szamuely's Galois Groups and Fundamental Groups . In quantum mechanics, covering spaces of topological groups naturally occur for the following reason. Because a wave function $\psi$ and any multiple $e^{i \theta} \psi$ of it represent the same physical state, to say that a group $G$ acts as a group of symmetries of a quantum system whose states lie in a Hilbert space $H$ is not to say that there is a representation $G \to \text{U}(H)$ (the unitary group of $H$) but rather a projective representation $G \to \text{PU}(H)$. For Lie groups $G$ such representations can be analyzed using representations of a covering group $\tilde{G}$ of $G$. This is why quantum systems with $\text{SO}(3)$-symmetry, e.g. an electron orbiting a proton, are naturally analyzed using the representation theory of $\text{SU}(2)$.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/95302', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/22019/']}
jdg_82003
stackexchange
llm_judgeable_groundtruth_similarity
5562322
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 I wonder why the range is given with the my sql data types. I define a table with a field name "id" and the data type is "int(2)". I inserted the value to the field "id" as "123456".This is accepted and stored. So what is the use of giving the range. Thanks in advance. Now provide the response and nothing else.
For INT and other numeric types that attribute only specifies the display width. See Numeric Type Attributes in the MySQL documentation: MySQL supports an extension for optionally specifying the display width of integer data types in parentheses following the base keyword for the type. For example, INT(4) specifies an INT with a display width of four digits. This optional display width may be used by applications to display integer values having a width less than the width specified for the column by left-padding them with spaces. (That is, this width is present in the metadata returned with result sets. Whether it is used or not is up to the application.) The display width does not constrain the range of values that can be stored in the column. Nor does it prevent values wider than the column display width from being displayed correctly. For example, a column specified as SMALLINT(3) has the usual SMALLINT range of -32768 to 32767, and values outside the range permitted by three digits are displayed in full using more than three digits.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5562322', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/535451/']}
jdg_82004
stackexchange
llm_judgeable_groundtruth_similarity
1510569
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 $C(K)$ be the set of all continuous complex valued functions on a compact Hausdorff space $K$ . Is it true that $K$ must be finite if $C(K)$ is reflexive?To me it seems true, but I don't know how to prove it. As $C(K)$ is reflexive then we have canonical isometry onto $C(K)^{**}$ . How does that help? Now provide the response and nothing else.
The dual space of $C(K)$ is the space of Radon measure $\nu$ on $K$. For every bounded Borel function $u$ on $K$, one can define $\bar u \in C(K)^{**}$ by $$\bar u (\nu) = \int_K u d\nu,\ \ \ \ \forall \nu \in C(K)^*. $$ Note that the canonical embedding $\Phi: C(K) \to C(K)^{**}$ is given by $$\Phi f(\nu) = \nu(f) = \int_K fd\nu,$$thus if $\Phi$ is surjective, for all bounded Borel measurable $u$ there is $f\in C(K)$ so that $$\bar u = \Phi f \Rightarrow \int_K u d\nu = \int_K f d\nu$$ for all Radon measure $\nu$. In particular for the Dirac measure $\nu = \delta_x$, $x\in K$, we have $$u(x) = f(x).$$ Thus all bounded Borel measurable functions are indeed continuous. In particular, all one point sets are open and so $K$ is discrete. By compactness, $K$ is finite.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1510569', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/92619/']}
jdg_82005
stackexchange
llm_judgeable_groundtruth_similarity
604974
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In relation to ideal gases, Boyle's Law states that pressure is inversely proportional to volume under constant temperature. In other words, $$P \propto 1/V$$ Below is a graph that plots pressure, $P$ , against inverse volume, $1/V$ . How can $1/V$ ever equal zero? How is this possible? Now provide the response and nothing else.
Formally we have $$\lim_{V\rightarrow \infty} \frac{1}{V}=0$$ I.e. the statement is true in the limit of infinite volume. For an ideal gas, this can be interpreted as saying that as the confining volume for the gas becomes infinite, the gas no longer exerts a normal pressure on the walls of the volume.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/604974', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/64502/']}
jdg_82006
stackexchange
llm_judgeable_groundtruth_similarity
782432
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 $$\nabla_A \mbox{Tr} \left( A A^T \right) = 2A$$ where $A$ is any square matrix. I did a simple derivative with product rule, but I don't know where i messed up. I started with $$ \nabla_A \mbox{Tr} \left( A A^T \right) = \mbox{Tr} \left( \frac {\partial A}{\partial A}A^T+A\frac {\partial A^T}{\partial A} \right) $$ Now provide the response and nothing else.
I'm going to work with square matrices, but it should be easy enough to change the dimensions as you please. Write $A = [\vec x_1 | \cdots | \vec x_n ]$ where each $\vec x_i = [x_{1i}, \ldots, x_{ni}]$. Notice then that the $i^{th}$ diagonal element of $AA^T$ is just $\vec x_i \cdot \vec x_i = x_{1i}^2 + \cdots + x_{ni}^2$. Thus the trace of $AA^T$ is the sum of every element of $A$; namely$$ \operatorname{Tr}(AA^T) = \sum_{i=1}^n \sum_{j=1}^n x_{ij}^2.$$Now taking $\nabla_A$ will give the desired result.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/782432', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/92619/']}
jdg_82007
stackexchange
llm_judgeable_groundtruth_similarity
26387052
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 developing a web application Dashboard and I was wondering how to detect that is midnight in order to reset some arrays that contains datas from the previous day using jquery or momentjs. Now provide the response and nothing else.
Use moment().format("h:mm:ss") that returns time in a h:mm:ss format. var midnight = "0:00:00";var now = null;setInterval(function () { now = moment().format("H:mm:ss"); if (now === midnight) { alert("Hi"); } $("#time").text(now);}, 1000); JSFIDDLE A better way would be to compute the seconds until midnight. This is very simple and human readable using MomentJS: // returns the number of seconds until next midnightmoment("24:00:00", "hh:mm:ss").diff(moment(), 'seconds'); So, just do: setTimeout( midnightTask, moment("24:00:00", "hh:mm:ss").diff(moment(), 'seconds'));function midnightTask() { /* do something */} JSFIDDLE
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26387052', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1764931/']}
jdg_82008
stackexchange
llm_judgeable_groundtruth_similarity
1995439
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 know if there is a way for reading the Phone Model programmatically in Android. I would like to get a string like HTC Dream, Milestone, Sapphire or whatever... Now provide the response and nothing else.
On many popular devices the market name of the device is not available. For example, on the Samsung Galaxy S6 the value of Build.MODEL could be "SM-G920F" , "SM-G920I" , or "SM-G920W8" . I created a small library that gets the market (consumer friendly) name of a device. It gets the correct name for over 10,000 devices and is constantly updated. If you wish to use my library click the link below: AndroidDeviceNames Library on Github If you do not want to use the library above, then this is the best solution for getting a consumer friendly device name: /** Returns the consumer friendly device name */public static String getDeviceName() { String manufacturer = Build.MANUFACTURER; String model = Build.MODEL; if (model.startsWith(manufacturer)) { return capitalize(model); } return capitalize(manufacturer) + " " + model;}private static String capitalize(String str) { if (TextUtils.isEmpty(str)) { return str; } char[] arr = str.toCharArray(); boolean capitalizeNext = true; StringBuilder phrase = new StringBuilder(); for (char c : arr) { if (capitalizeNext && Character.isLetter(c)) { phrase.append(Character.toUpperCase(c)); capitalizeNext = false; continue; } else if (Character.isWhitespace(c)) { capitalizeNext = true; } phrase.append(c); } return phrase.toString();} Example from my Verizon HTC One M8: // using method from aboveSystem.out.println(getDeviceName());// Using https://github.com/jaredrummler/AndroidDeviceNamesSystem.out.println(DeviceName.getDeviceName()); Result: HTC6525LVW HTC One (M8)
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/1995439', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/314407/']}
jdg_82009
stackexchange
llm_judgeable_groundtruth_similarity
638704
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I've recently started studying the concept of space-time diagrams in special relativity, and I came across the concept of representing the time axis using $ct$ , with units being that of length. Now I'm told that this is done, first of all, to keep the speed of light = 1, and give a common unit to both the axis, so that we can show, that space and time are inherently the same thing. However, I'm still not being able to understand, how can I intuitively think of time in meters or any unit of length. Also, doesn't plugging $ct$ and $ct'$ into Lorentz transformations, make it dimensionally inconsistent.For example : $x' = \gamma(x-vt)$ if $x$ and $x'$ are in terms of distance, and so is $t$ , then the term inside the bracket becomes dimensionally inconsistent. So, how can I intuitively measure time in meters, or solve Lorentz transformations this way? What exactly does setting the speed of light $c = 1$ mean? It would be really helpful, if someone can explain to me the motivation, and the intuition behind expressing both axis in the same units. Moreover, what would have happened, if we had kept them in separate units? Now provide the response and nothing else.
The basic problem is that for a sufficiently massive star, the electrons become relativistic. The fine details of this calculation are rather complicated, but you can get a qualitative sense of the argument as follows: For non-relativistic fermions at zero temperature, it is possible to show that the total energy of $N$ particles in a box of volume $V$ is proportional to $N^{5/3}/V^{2/3}$ . This can be done via counting the density of states, and using the fact that the energy of a non-relativistic particle obeys $E \propto |\vec{p}|^{2}$ .For a spherical volume of radius $R$ , we have $R \propto V^{1/3}$ , and the number of fermions present is proportional to the mass. This means that the total energy of the fermions is proportional to $M^{5/3}/R^2$ . This energy is positive. On the other hand, the gravitational energy of a solid sphere is negative and proportional to $M^2/R$ . This means that the total energy is the sum of a negative $R^{-1}$ term and a positive $R^{-2}$ term, and such a function will have a minimum somewhere. This will be the equilibrium point. At smaller radii, the energy of the degeneracy grows faster than the binding energy decreases, pushing the radius back to larger values. At larger radii, the reverse occurs. This means that the star will be stable. This argument doesn't hold up to arbitrarily large energies, though, because eventually the Fermi energy of the electrons exceeds the rest energy of the electron; in other words, the electrons become relativistic. This changes the relationship between energy and momentum of the electrons. For highly relativistic electrons, we have $E \propto |\vec{p}|$ instead; and going through the same calculations (neglecting the electron mass entirely), we find that the total energy of a relativistic fermion gas is proportional to $N^{4/3}/V^{1/3} \propto M^{4/3}/R$ . The gravitational binding energy, on the other hand, remains negative and proportional to $M^2/R$ . This implies that the overall energy is itself proportional to $1/R$ , and there is no extremum of the total energy of the system. Since the fermion energy and the binding energy always increase or decrease at exactly the same rate, there will be no stable equilibrium radius. The star will either blow itself apart or collapse in on itself, depending on whether the kinetic energy of the fermions or the gravitational binding energy wins out.
{}
{'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/638704', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/300178/']}
jdg_82010
stackexchange
llm_judgeable_groundtruth_similarity
513
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In the title I am refering to silver spoons, which, when used to consume milk products (like yogurt), get a weird taste. It could be described as umami/meaty, a little bit like onions. I came to the conclusion that it must be the silver, because this taste is never observed when using steel spoons. My guess was: the silver (or maybe its oxide?) reacts with an ingredient of the milk product. My question is: Is this documented/known process/reaction or is this some kind of misperception on my part? If the former is true, what exactly is happening? (By)-products? Now provide the response and nothing else.
You're right: the silver is reacting with sulfur compounds in the food to form a tarnish of silver sulfide. This is most commonly observed, in my experience, using silver teaspoons with boiled eggs, which are pretty rich in sulfur . There are a number of reactions that can take place depending on the sulfur-containing species - the abstract from this paper from the Journal of Chemical Education (unfortunately pay-walled) has a nice example: Silver and silver-plated objects react with sulfur and sulfur compounds to produce silver sulfide $\ce{Ag2S}$ or tarnish. Contact with materials that contain sulfur compounds, such as hard boiled eggs, mayonnaise, mustard, and rubber bands can cause tarnish. In the air, a silver object can tarnish owing to the reaction of silver with hydrogen sulfide ( $\ce{H2S}$ ). This is a gas found in the air as a result of some industrial processes and the decomposition of dead plants and animals. The reaction of silver with hydrogen sulfide to form tarnish is as follows: $\ce{2 Ag(s) + H2S(g) -> Ag2S(s) + H2(g)}$ In Sterling silver specifically, you'll often also get copper sulfide formed. The paper also mentions that you can remove the tarnish abrasively, or through reacting the tarnish with aluminium ( via solution, electrochemically): $\ce{3 Ag2S(s) + 2 Al(s) -> 6 Ag(s) + Al2S3(s)}$ But a more common approach used by many commercial products is to dissolve off the tarnish, usually in sodium thiosulfate or thiourea. This means you end up with slightly less silver on your item, but is otherwise pretty effective and very mild (it's commonly used for museum pieces ).
{}
{'log_upvote_score': 5, 'links': ['https://chemistry.stackexchange.com/questions/513', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/34/']}
jdg_82011
stackexchange
llm_judgeable_groundtruth_similarity
31920934
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 next classes: Mapper public interface DeviceTokensMapper { DeviceTokensMapper INSTANCE = Mappers.getMapper(DeviceTokensMapper.class); @Mappings({ @Mapping(source = "tokenName", target = "tokenName"), @Mapping(source = "userOsType", target = "osType"), }) DeviceTokensDTO toDeviceTokensDTO(DeviceTokens deviceTokens);} Entity: @Entitypublic class DeviceTokens { @Id @Column(name="token_name", nullable = false) private String tokenName; @Column(name = "os", nullable = false) @Enumerated private UserOSType userOsType; public DeviceTokens() {} public DeviceTokens(String tokenName, UserOSType userOSType) { this.tokenName = tokenName; this.userOsType = userOSType; } public String getTokenName() { return tokenName; } public void setTokenName(String tokenName) { this.tokenName = tokenName; } public UserOSType getUserOsType() { return userOsType; } public void setUserOsType(UserOSType userOsType) { this.userOsType = userOsType; }} DTO: public class DeviceTokensDTO { private String tokenName; private UserOSType osType; public DeviceTokensDTO() {} public DeviceTokensDTO(String tokenName, UserOSType osType) { this.tokenName = tokenName; this.osType = osType; } public UserOSType getOsType() { return osType; } public void setOsType(UserOSType osType) { this.osType = osType; } public String getTokenName() { return tokenName; } public void setTokenName(String tokenName) { this.tokenName = tokenName; }} And method from spring service class where I use this mapping: @Transactionalpublic DeviceTokensDTO storeToken(String tokenId, UserOSType userOsType) { DeviceTokens deviceTokens = new DeviceTokens(tokenId, userOsType); DeviceTokens newDevice = deviceTokensRepository.save(deviceTokens); return DeviceTokensMapper.INSTANCE.toDeviceTokensDTO(newDevice);} When I run above method I see next exception: ERROR [dispatcherServlet]:? - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Handler processing failed; nested exception is java.lang.ExceptionInInitializerError] with root cause java.lang.ClassNotFoundException: dto.DeviceTokensMapperImpl So why mapper require implementation class? Could please someone advise?Thanks. Now provide the response and nothing else.
MapStruct generates code at compile time, and the call to Mappers.getMapper(DeviceTokensMapper.class); will look for the generated implementation of the mapper interface. For some reason it seems to be missing in your deployment unit (WAR etc.). Btw. when working with Spring as your DI container, you can use @Mapper(componentModel="spring") and you will be able to obtain mapper instances via dependency injection instead of using the Mappers factory.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31920934', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2125399/']}
jdg_82012
stackexchange
llm_judgeable_groundtruth_similarity
15048096
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 graphing web-app and I've decided that leaflet would make a decent graph view. I have it displaying (sort of) but I need a way to force it to update when the user enters a new formula to graph. I'm using JQuery as well, but that shouldn't matter. Here is the relevant code: function formulaChange(formula){ //submits a request to the server to add a graph to display map.setView(map.getCenter(),map.getZoom(),true);//doesn't work //and neither does: //map.fire('viewreset'); //tiles.redraw();}function enterHandler(event){ if(event.keyCode==13){ formulaChange(document.getElementById("formula").value); }}var map;var tiles;$(document).ready(function(){ map=L.map('plot',{crs:L.CRS.Simple}).setView([0,0],10); //url is actually a servlet on the server that generates an image on the fly tiles = L.tileLayer('./GraphTile.png?x={x}&y={y}&z={z}&tilesize={tileSize}&{s}', { maxZoom: 20, continuousWorld: true, tileSize: 128, //subdomains used as a random in the URL to prevent caching subdomains: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890' } ).addTo(map);}); This works but won't refresh when the user clicks, the event is definitely running (I've omitted other code that updates a text display). It displays properly, but when the user adds a function to display the view never updates and leaflet continues to display cached images, only a new zoom level or panning to an area never before viewed causes it to update the tiles. The question I have is: How do I force leaflet to completely reload everything and drop and reload all the images? EDIT added another failed attempt Now provide the response and nothing else.
I found the answer. Despite the no-cache headers my browser was caching the images anyway. The subdomains are not "randomly chosen" as the documentation claims, they are generated using a hash of the tile location. So I had to improvise a way to add "&RANDOM##" to the end of the URL instead of the subdomain. The new code looks like this: function enterHandler(event){ if(event.keyCode==13){ formulaChange(document.getElementById("formula").value); }}function formulaChange(formula){ val.item=Math.random(); tiles.redraw();}var map;var tiles;var val={ item: Math.random(), toString: function(){ return this.item; }};$(document).ready(function(){ map=L.map('plot',{crs:L.CRS.Simple}).setView([0,0],10); tiles = L.tileLayer('./GraphTile.png?x={x}&y={y}&z={z}&tilesize={tileSize}&{test}', { maxZoom: 20, continuousWorld: true, tileSize: 128, test: val } ).addTo(map);}); Hope this helps someone else. Please comment if there's a better way to do this.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15048096', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/972242/']}
jdg_82013
stackexchange
llm_judgeable_groundtruth_similarity
24930690
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Consider following scheme. We have 3 files: main.cpp: int main() { clock_t begin = clock(); int a = 0; for (int i = 0; i < 1000000000; ++i) { a += i; } clock_t end = clock(); printf("Number: %d, Elapsed time: %f\n", a, double(end - begin) / CLOCKS_PER_SEC); begin = clock(); C b(0); for (int i = 0; i < 1000000000; ++i) { b += C(i); } end = clock(); printf("Number: %d, Elapsed time: %f\n", a, double(end - begin) / CLOCKS_PER_SEC); return 0;} class.h: #include <iostream>struct C {public: int m_number; C(int number); void operator+=(const C & rhs);}; class.cpp C::C(int number): m_number(number){}void C::operator+=(const C & rhs) { m_number += rhs.m_number;} Files are compiled using clang++ with flags -std=c++11 -O3 . What I expected were very similar performance results, since I thought that compiler will optimize the operators not to be called as functions. The reality though was a bit different, here is the result: Number: -1243309312, Elapsed time: 0.000003Number: -1243309312, Elapsed time: 5.375751 I played around a bit and found out, that if I paste all of the code from class.* into the main.cpp the speed dramatically improves and results are very similar. Number: -1243309312, Elapsed time: 0.000003Number: -1243309312, Elapsed time: 0.000003 Than I realized that this behavior is probably caused by the fact, that compilation of main.cpp and class.cpp is completely separated and therefore compiler is unable to perform adequate optimizations. My question: Is there any way of keeping the 3-file scheme and still achieve the optimization level as if the files were merged into one and than compiled? I have read something about 'unity builds' but that seems like an overkill. Now provide the response and nothing else.
Short answer What you want is link time optimization. Try the answer from this question . I.e., try: clang++ -O4 -emit-llvm main.cpp -c -o main.bc clang++ -O4 -emit-llvm class.cpp -c -o class.bc llvm-link main.bc class.bc -o all.bcopt -std-compile-opts -std-link-opts -O3 all.bc -o optimized.bcclang++ optimized.bc -o yourExecutable You should see that your performance reaches the one that you had when pasting everything into main.cpp . Long answer The problem is that the compiler cannot inline your overloaded operator during linking, because it no longer has its definition in a form which it can use to inline it (it cannot inline bare machine code). Thus, the operator call in main.cpp will stay a real function call to the function declared in class.cpp . A function call is very expensive in comparison to a simple inlined addition which can be optimized further (e.g., vectorized). When you enable link time optimization, the compiler is able to do this. As you see above, you first create llvm intermediate representation byte code (the .bc files, which I will simply call llvm code hereinafter) instead of machine code.You then link these files to a new .bc file which still contains llvm code instead of machine code. In contrast to machine code, the compiler is able to perform inlining on llvm code. opt is the llvm optimizer (be sure to install llvm ), which performs the inlining and further link time optimizations. Then, we call clang++ a final time to generate executable machine code from the optimized llvm code. For People with GCC The answer above is only for clang. GCC (g++) users must use the -flto flag during compilation and during linking to enable link time optimization. It is simpler than with clang, simply add -flto everywhere: g++ -c -O2 -flto main.cpp g++ -c -O2 -flto class.cpp g++ -o myprog -flto -O2 main.o class.o
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24930690', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1474847/']}
jdg_82014
stackexchange
llm_judgeable_groundtruth_similarity
24620599
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an Ubuntu Virtual machine that is configured to have VT-x enabled, 6 Processors, and 25 GB RAM. Inside that virtual machine I am trying to start a vagrant machine with the following configuration: master.vm.box = "precise32"master.vm.provider "virtualbox" do |vb| vb.customize ["modifyvm", :id, "--cpuexecutioncap", "80"] vb.memory = 10000 vb.customize ["modifyvm", :id, "--cpus", "2"] vb.customize ["modifyvm", :id, "--ioapic", "on"]end When I start the Vagrant I get the error VT-x not enabled. I tried both 32 bit and 64 bit versions of Vagrant but still no luck. Any idea how can I run Vagrant machine inside the Virtualbox? Now provide the response and nothing else.
You can only use one virtual CPU without VT-x. Thus, the error message stating that VT-x isn't enabled is caused by the following line: vb.customize ["modifyvm", :id, "--cpus", "2"] Replacing it with the following works (Vagrant has a shorthand for setting the CPU count): vb.cpus = 1 NOTE: You can only run 32-bit VMs inside another VM.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24620599', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2230605/']}
jdg_82015
stackexchange
llm_judgeable_groundtruth_similarity
38922124
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This are my rules, applied to an img dir: match /img { match /{fileId} { allow read, write: if request.resource.contentType.matches('image/jpeg') || request.resource.contentType.matches('image/png') || request.resource.contentType.matches('image/gif') && request.resource.size < 2 * 1024 * 1024 } }} The problem is that those rules are also being applied to delete() as it is a write method too, so it always returns a permission error. I couldn't find anything in the documentation regarding this. How can I defer from POST/PUT rules and DELETE rules? Now provide the response and nothing else.
Found the solution by myself. By letting the rule to apply when there is no resource sent at all (delete), it also gets write permission. The rest of the create/update code is sent to an OR expression. match /img { match /{fileId} { allow read, write: if request.resource == null || (request.resource.contentType.matches('image/jpeg') || request.resource.contentType.matches('image/png') || request.resource.contentType.matches('image/gif') && request.resource.size < 2 * 1024 * 1024) }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/38922124', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4783564/']}
jdg_82016
stackexchange
llm_judgeable_groundtruth_similarity
70770
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: Is it possible for a DFA to have less states than its equivalent NFA? Number of transitions does not matter. If possible also give an example. Now provide the response and nothing else.
Theoretically yes, that NFA could have 9001 unreachable stats that are completely useless. If you expect that NFA to be connected (common sense) then if you allow epsilon-moves you can have a huge useless cykle. If you rephrase your question to: Lets consider any Language and its 'smallest' (min number of states) NFA with $\epsilon$-moves and its 'samllest' DFA then the answer is no and the reason is simple. any DFA is also NFA (names does not suggest that though).therefore if we take a 'smallest' NFA and then manage find equivalent DFA that is 'smaller' that would contradict previous NFA being smallest.
{}
{'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/70770', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/66898/']}
jdg_82017
stackexchange
llm_judgeable_groundtruth_similarity
1105990
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 often run into the case where I want to eval a query right where I declare it. This is usually because I need to iterate over it multiple times and it is expensive to compute. For example: string raw = "...";var lines = (from l in raw.Split('\n') let ll = l.Trim() where !string.IsNullOrEmpty(ll) select ll).ToList(); This works fine. But if I am not going to modify the result, then I might as well call ToArray() instead of ToList() . I wonder however whether ToArray() is implemented by first calling ToList() and is therefore less memory efficient than just calling ToList() . Am I crazy? Should I just call ToArray() - safe and secure in the knowledge that the memory won't be allocated twice? Now provide the response and nothing else.
Unless you simply need an array to meet other constraints you should use ToList . In the majority of scenarios ToArray will allocate more memory than ToList . Both use arrays for storage, but ToList has a more flexible constraint. It needs the array to be at least as large as the number of elements in the collection. If the array is larger, that is not a problem. However ToArray needs the array to be sized exactly to the number of elements. To meet this constraint ToArray often does one more allocation than ToList . Once it has an array that is big enough it allocates an array which is exactly the correct size and copies the elements back into that array. The only time it can avoid this is when the grow algorithm for the array just happens to coincide with the number of elements needing to be stored (definitely in the minority). EDIT A couple of people have asked me about the consequence of having the extra unused memory in the List<T> value. This is a valid concern. If the created collection is long lived, is never modified after being created and has a high chance of landing in the Gen2 heap then you may be better off taking the extra allocation of ToArray up front. In general though I find this to be the rarer case. It's much more common to see a lot of ToArray calls which are immediately passed to other short lived uses of memory in which case ToList is demonstrably better. The key here is to profile, profile and then profile some more.
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/1105990', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/338/']}
jdg_82018
stackexchange
llm_judgeable_groundtruth_similarity
18242374
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to write an ORDER BY clause before my WHERE condition because I need to truncate my results to just 10, but I need to sort them in alphabetical order first. I know that you can't put ORDER BY before WHERE so how can I do it? I need to do something like the following: SELECT *FROM myTableORDER BY TOP10WHERE ROWNUM <=10 Now provide the response and nothing else.
You can use an inline view for this SELECT * FROM ( SELECT * FROM myTable ORDER BY TOP10) TWHERE ROWNUM <=10
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18242374', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1751883/']}
jdg_82019
stackexchange
llm_judgeable_groundtruth_similarity
203049
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Consider the standard embedded $n$-cross polytope $P_n$ with vertices $\pm e_i \in \mathbb R^n$. Let us consider decompositions of this polytope into $2^{n-1}$ simplices, such that these simplices have only vertices that are also vertices of $P_n$. How many different such decompositions exist? (Note that such a decomposition is not necessarily a triangulation.) Secondly, I want to know the same about the $n$-polytope $Q_n$ which is defined to be the convex hull of the set $\{e_i+e_j \in \mathbb R^{n+1} \ | \ 1 \leq i < j \leq n+1\}$. (Think about $Q_n$ as a $n$-simplex which is twice as large as usual and has its corners removed.) Now provide the response and nothing else.
The cross-polytope has $2n$ vertices in $n$ antipodal pairs. A simplex with $n+1$ points from these must contain exactly one antipodal pair of points, since if it contains more than one, it has a square face and $0$ volume. So, the simplex is the union of two adjacent cones over facets, or the intersection of the cross-polytope with two adjacent orthants. This means a division of the cross-polytope into $2^{n-1}$ simplices corresponds to a perfect matching of the dual hypercube. These are counted by A005271 . The first $7$ values are known. The number increases extremely rapidly, doubly exponentially, since one lower bound is $2^{2^{n-2}}$ (matchings contained in $2^{n-2}$ parallel squares) and one upper bound is $n^{2^{n-1}} = 2^{(\log_2 n) 2^{n-1}}$ (choose a direction for each odd vertex of the cube).
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/203049', 'https://mathoverflow.net', 'https://mathoverflow.net/users/14233/']}
jdg_82020
stackexchange
llm_judgeable_groundtruth_similarity
2078232
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am searching for a non-constant function $f:\mathbb{R}\rightarrow \mathbb{R}$ with the following properties: 1) $f(a+b)=f(a)f(b)$ 2) $\lim\limits_{x\rightarrow -\infty} f(x) = 1$. Is it possible to find such a function or is there a reason why such a function can not exist? Now provide the response and nothing else.
By induction, you get $f (-n )=f(-1)^{n} $. The limit condition now forces $f (-1)=1$. But then, for any $x $, $$f (-n+x)=f (-1)^nf (x)=f (x), $$ and now the limit condition gives $f (x)=1$.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2078232', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/401603/']}
jdg_82021
stackexchange
llm_judgeable_groundtruth_similarity
37298393
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Consider following code, I don't understand why empty function of print must be defined. #include <iostream>using namespace std;void print(){ } template <typename T, typename... Types>void print (const T& firstArg, const Types&... args){ cout << firstArg << endl; // print first argument print(args...); // call print() for remaining arguments}int main(){ int i=1; int j=2; char c = 'T'; print(i,"hello",j,i,c,"word");} Now provide the response and nothing else.
CORRECT WAY: Variadic templates is strictly related to induction , a mathematical concept. The compiler resolves the following function call print('a', 3, 4.0f); into std::cout<< 'a' <<std::endl;print(3, 4.0f); which is resolved into std::cout<< 'a' <<std::endl;std::cout<< 3 <<std::endl;print( 4.0f); which is resolved into std::cout<< 'a' <<std::endl;std::cout<< 3 <<std::endl;std::cout<< 4.0f <<std::endl;print(); At this point it searches for a function overload whose match is the empty function. All functions that have 1 or more arguments are matched to the variadic template All functions that have no argument are matched to the empty function The culprit is that you must have, for every possible combination of parameters, only 1 function. ERROR 1: Doing the following would be an error template< typename T>void print( const T& arg) // first version{ cout<< arg<<endl;} template <typename T, typename... Types>void print (const T& firstArg, const Types&... args) // second version{ cout << firstArg << endl; // print first argument print(args...); // call print() for remaining arguments} Because when you call print the compiler doesn't know which function to call. Does print(3) refers to "first" or "second" version? Both would be valid because the first has 1 parameter, and the second can accept one parameter too. print(3); // error, ambiguous, which one you want to call, the 1st or the 2nd? ERROR 2: The following would be an error anyway // No empty functiontemplate <typename T, typename... Types>void print (const T& firstArg, const Types&... args) { cout << firstArg << endl; // print first argument print(args...); // call print() for remaining arguments} In fact, if you use it alone without the compiler would do print('k', 0, 6.5); which is resolved into std::cout<<'k'<<std::endl; print(0, 6.5); which is resolved into std::cout<<'k'<<std::endl; std::cout<< 0 <<std::endl; print( 6.5); which is resolved into std::cout<<'k'<<std::endl; std::cout<< 0 <<std::endl; std::cout<< 6.5 <<std::endl; print(); //Oops error, no function 'print' to call with no arguments As you see in the last attempt, the compiler tries to call print() with no arguments. However if such a function does not exists it is not called, and that's why you should provide that empty function (don't worry, the compiler will optimize code so empty functions don't decrease performance).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37298393', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5905343/']}
jdg_82022
stackexchange
llm_judgeable_groundtruth_similarity
36557308
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: You might think that following issue is very simple, but I don't know what I did wrong here. I feel I added required dependencies. Haven't I? Could anyone please suggest me whats wrong here? Exception in thread "main" java.lang.NoClassDefFoundError: com/sun/xml/bind/v2/model/annotation/AnnotationReader at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:760) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) at java.net.URLClassLoader.defineClass(URLClassLoader.java:467) at java.net.URLClassLoader.access$100(URLClassLoader.java:73) at java.net.URLClassLoader$1.run(URLClassLoader.java:368) at java.net.URLClassLoader$1.run(URLClassLoader.java:362) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:361) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) at java.lang.Class.getDeclaredMethods0(Native Method) at java.lang.Class.privateGetDeclaredMethods(Class.java:2701) at java.lang.Class.privateGetMethodRecursive(Class.java:3048) at java.lang.Class.getMethod0(Class.java:3018) at java.lang.Class.getMethod(Class.java:1784) at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:242) at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:234) at javax.xml.bind.ContextFinder.find(ContextFinder.java:441) at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:641) at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:584) at com.misc.common.ReadXMLFileJaxb.main(ReadXMLFileJaxb.java:14)Caused by: java.lang.ClassNotFoundException: com.sun.xml.bind.v2.model.annotation.AnnotationReader at java.net.URLClassLoader.findClass(URLClassLoader.java:381) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ... 23 more Book.java @XmlRootElement@XmlAccessorType(XmlAccessType.FIELD)public class Book { @XmlAttribute private String firstName; @XmlElement private String lastName; @XmlElement private String age; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } @Override public String toString() { return "Book [firstName=" + firstName + ", lastName=" + lastName+ ", age=" + age + "]"; }} ReadXMLFileJaxb.java public class ReadXMLFileJaxb { public static void main(String[] args) { File file = new File(ReadXMLFileDOM.class.getClassLoader().getResource("book.xml").getFile()); try { JAXBContext context = JAXBContext.newInstance(Book.class); Unmarshaller unmarshaller = context.createUnmarshaller(); Book book = (Book) unmarshaller.unmarshal(file); System.out.println(book.toString()); } catch (JAXBException e) { System.out.println(e.getMessage()); } }} My book.xml <?xml version="1.0"?><book> <person> <first>Kiran</first> <last>Pai</last> <age>22</age> </person> <person> <first>Bill</first> <last>Gates</last> <age>46</age> </person> <person> <first>Steve</first> <last>Jobs</last> <age>40</age> </person></book> pom.xml <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.8</java.version> </properties> <dependencies> <!-- JAXB --> <dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-impl</artifactId> <version>2.2.11</version> </dependency> <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.2.12</version> </dependency> </dependencies> Now provide the response and nothing else.
As per link: Why has AnnotationReader been removed from JAXB reference implementation? , you need to simply use below maven dependencies: <dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-impl</artifactId> <version>2.2.11</version></dependency><dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-core</artifactId> <version>2.2.11</version></dependency> You need to refactor code a bit. Also looks like you've not created same name fields of model class, it should be like below:Person.java @XmlRootElement(name="Person")@XmlAccessorType(XmlAccessType.FIELD)public class Person { @XmlElement private String first; @XmlElement private String last; @XmlElement private String age; public String getFirst() { return first; } public void setFirst(String first) { this.first = first; } public String getLast() { return last; } public void setLast(String last) { this.last = last; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } @Override public String toString() { return "Person [first=" + first + ", last=" + last + ", age=" + age + "]"; }} Book.java @XmlRootElement(name="book")@XmlAccessorType(XmlAccessType.FIELD)public class Book { private List<Person> person = new ArrayList<Person>(); public List<Person> getPerson() { return person; } public void setPerson(List<Person> person) { this.person = person; }} ReadXMLFileJaxb.java public class ReadXMLFileJaxb { public static void main(String[] args) { File file = new File(ReadXMLFileDOM.class.getClassLoader().getResource("book.xml").getFile()); try { JAXBContext context = JAXBContext.newInstance(Book.class); Unmarshaller unmarshaller = context.createUnmarshaller(); Book book = (Book) unmarshaller.unmarshal(file); System.out.println(book.getPerson().size()); for (int i = 0; i < book.getPerson().size(); i++) { System.out.println("------------"); System.out.println(book.getPerson().get(i).getFirst()); System.out.println(book.getPerson().get(i).getLast()); System.out.println(book.getPerson().get(i).getAge()); } } catch (JAXBException e) { System.out.println(e.getMessage()); } }} The below output I see: 3------------KiranPai22------------BillGates46------------SteveJobs40
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/36557308', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_82023
stackexchange
llm_judgeable_groundtruth_similarity
131679
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How do i differentiate the following: $$y = \tan^{-1} \biggl\{ \frac{\sqrt{1+x^{2}} - \sqrt{1-x^{2}}}{\sqrt{1+x^{2}}+ \sqrt{1-x^{2}}}\biggr\}$$ I know that $\text{derivative}$ of $\tan^{-1}{x}$ is $\frac{1}{1+x^{2}}$ but not sure as to how to do this. Now provide the response and nothing else.
First the idea is to observe as to what would you substitute for $x$ in order to remove the square root. After some manipulations you find that the correct substitution is $x^{2} = \sin{2\theta}$. Once you have done this then you have $$y = \tan^{-1}\biggl\{ \frac{(\cos\theta + \sin\theta) - (\cos\theta - \sin\theta)}{(\cos\theta + \sin\theta)+(\cos\theta - \sin\theta)}\biggr\} = \theta = \frac{1}{2}\sin^{-1}{x^2}$$ So if $y = \frac{1}{2}\sin^{-1}{x^2}$ then $$\frac{dy}{dx} = \frac{1}{2} \cdot \frac{1}{\sqrt{1-x^{4}}} \cdot 2x = \frac{x}{\sqrt{1-x^{4}}}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/131679', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/29106/']}
jdg_82024
stackexchange
llm_judgeable_groundtruth_similarity
29161932
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 used this helpful post to learn how to pass a list of Enum values as a parameter. Now I would like to know whether I can make this parameter optional? Example: public enum EnumColors { [Flags] Red = 1, Green = 2, Blue = 4, Black = 8 } I want to call my function that receives the Enum param like this: DoSomethingWithColors(EnumColors.Red | EnumColors.Blue) OR DoSomethingWithColors() My function should then look like what? public void DoSomethingWithColors(EnumColors someColors = ??) { ... } Now provide the response and nothing else.
Yes it can be optional. [Flags]public enum Flags{ F1 = 1, F2 = 2}public void Func(Flags f = (Flags.F1 | Flags.F2)) { // body} You can then call your function with or without parameter. If you call it without any parameter you'll get (Flags.F1 | Flags.F2) as the default value passed to the f parameter If you don't want to have a default value but the parameter to be still optional you can do public void Func(Flags? f = null) { if (f.HasValue) { }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29161932', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1208908/']}
jdg_82025
stackexchange
llm_judgeable_groundtruth_similarity
23894221
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 upload a file from my python script to my dropbox account automatically. I can't find anyway to do this with just a user/pass. Everything I see in the Dropbox SDK is related to an app having user interaction. I just want to do something like this: https://api-content.dropbox.com/1/files_put/ /?user=me&pass=blah Now provide the response and nothing else.
Important Note: this answer is deprecated since dropbox uses v2 API now. See the answer of @SparkAndShine for current API version solution Thanks to @smarx for the answer above! I just wanted to clarify for anyone else trying to do this. Make sure you install the dropbox module first of course, pip install dropbox . Create an app under your own dropbox account in the "App Console". ( https://www.dropbox.com/developers/apps ) Just for the record I created my App with the following: a. App Type as "Dropbox API APP". b. Type of data access as "Files & Datastores" c. Folder access as "My app needs access to files already on Dropbox". (ie: Permission Type as "Full Dropbox".) Then click the "generate access token" button and cut/paste into the python example below in place of <auth_token> : import dropboxclient = dropbox.client.DropboxClient(<auth_token>)print 'linked account: ', client.account_info()f = open('working-draft.txt', 'rb')response = client.put_file('/magnum-opus.txt', f)print 'uploaded: ', responsefolder_metadata = client.metadata('/')print 'metadata: ', folder_metadataf, metadata = client.get_file_and_metadata('/magnum-opus.txt')out = open('magnum-opus.txt', 'wb')out.write(f.read())out.close()print metadata
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/23894221', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1735506/']}
jdg_82026
stackexchange
llm_judgeable_groundtruth_similarity
53023
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 value of pi is determined by the circumference of a circle. Why is it any particular constant number? Would a circle as defined as a perfect circle in any universe lead to a different value of pi? Would all universes where a circle could be constructed by "people" there also lead to the value of pi? If it is true then it leads to the conclusion that pi is some sort of constant value constant to all universe. What is the meaning of that? Science fiction references. In science fiction pi sometimes has a different value in different universes, for example Greg Bear's "The Way" , it says "Gates are capped with cupolas formed from Space-time itself. As distortions in space-time geometry, their nature can be calculated by 21st century instruments laid on their 'surfaces'. The constant pi, in particular, is most strongly affected.". A message is found encoded within pi, in the novel by Carl Sagan, "Contact" "Ellie, acting upon a suggestion by the senders of the message, works on a program which computes the digits of pi to record lengths in different bases. Very far from the decimal point (1020) and in base 11, it finds that a special pattern does exist when the numbers stop varying randomly and start producing 1s and 0s in a very long string.". Now provide the response and nothing else.
Physically, the ratio of a circle's circumference to its diameter $C/d$ is not really $\pi$. General relativity describes gravity in terms of the curvature of spacetime, and roughly speaking, if you take $(C/d-\pi)/A$, where $A$ is the circle's area, what you get is a measure of curvature called the Ricci scalar. But even if you're doing general relativity, you don't just go around redefining $\pi$. The thing is, $\pi$ occurs in all kinds of contexts, not just as $C/d$. For instance, you could define $\pi$ as $4-4/3+4/5-4/7+\ldots$, which has nothing to do with the curvature of space. So if you define $\pi$ as $C/d$, you don't even get a consistent value within our own universe, whereas if you define it as $4-4/3+4/5-4/7+\ldots$, you get an answer that is guaranteed to be the same in any other universe. Another way of looking at it is that $\pi$ is not the $C/d$ ratio of a physical circle, it's the $C/d$ ratio of a mathematically idealized circle that exists in certain axiomatic systems, such as Euclidean geometry. Viewed this way, it doesn't matter that our universe isn't actually Euclidean.
{}
{'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/53023', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/13619/']}
jdg_82027
stackexchange
llm_judgeable_groundtruth_similarity
47440659
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 could print something like below by running for(i in 1:5) print(i,i)) I'm using R here :) [1] 1[1] 2 2[1] 3 3 3 [1] 4 4 4 4 [1] 5 5 5 5 5 but I couldn't really find a way to print something like below. Can anyone open my eyes please? [1] 1 1 1 1 1[1] 2 2 2[1] 3[1] 4[1] 5 5 5[1] 6 6 6 6 6 Now provide the response and nothing else.
Ok I ended up creating a Module, and passing a UI Component reference on it's constructor: Here's my UI component : public class RCTACCalendarManager extends ViewGroupManager <RCTACCalendar> { public static final String REACT_CLASS = "RCTACCalendar"; private RCTACCalendar calendarInstance; public RCTACCalendarManager(ReactApplicationContext reactContext) { super(); } @Override public String getName() { return REACT_CLASS; } @Override public RCTACCalendar createViewInstance(ThemedReactContext context) { calendarInstance = new RCTACCalendar(context); return calendarInstance; } public RCTACCalendar getCalendarInstance() { // <-- returns the View instance return calendarInstance; }} Here's the Module I created for that component: public class RCTACCalendarModule extends ReactContextBaseJavaModule { private RCTACCalendar calendarInstance; public RCTACCalendarModule(ReactApplicationContext reactContext, RCTACCalendarManager calManager) { super(reactContext); if (calManager != null) { calendarInstance = calManager.getCalendarInstance(); } } @Override public String getName() { return "ACCalendarManager"; } @ReactMethod public void mySuperDuperFunction(Promise promise) { if (calendarInstance != null) { calendarInstance.mySuperDuperFunction(promise); // <-- Magic } }} and here's how I combine those two together in my Package declaration: public class RCTACCalendarPackage implements ReactPackage { private RCTACCalendarManager calManager; @Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { if (calManager == null) { calManager = new RCTACCalendarManager(reactContext); } return Arrays.<NativeModule>asList( new RCTACCalendarModule(reactContext, calManager) ); } @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { if (calManager == null) { calManager = new RCTACCalendarManager(reactContext); } return Arrays.<ViewManager>asList( calManager ); }} It works like a charm.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47440659', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8992086/']}
jdg_82028
stackexchange
llm_judgeable_groundtruth_similarity
557209
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: Physics theories are always constrained by symmetry principles (Strong equivalence principle, Galilean invariance principle, Gauge invariance, …). This means that each model of a theory inherits (by construction) the symmetries enforced by the theory. For example, in classical mechanics, every model is (supposedly) Galilean invariant (no absolute frame of reference, invariance by rotations, translations, boosts, …). Now, take the classical expression of the Lorentz force: it depends explicitly on v and and cannot therefore be Galilean invariant. The same is true for the harmonic oscillator $F = -kx$ or the central force $F = -\frac{1}{r^2}$ . In these cases, an absolute frame of reference is defined because an absolute point is discriminated (the origin) from all others. As these models are not Galilean invariant, we should not expect them to preserve energy, momentum, angular momentum or any other quantity related to these broken symmetries (say, by Noether theorem). How to explain that in some case the conservation laws are preserved while they a priori have reason to be, say, for the central force? It seems to me that we cannot even know when it i the case, so why are we even using them to begin with? Isn't this kind of practice extremely bad and confusing for students too? As an example, notice that in the central force case the momentum is not preserved because you don't have invariance by translation in space as a point is discriminated and fixed. EDIT: apparently my question wasn't clear, so here's a new formulation. Given a model $M$ , some physics claims are sometimes preserved by doing a limit process or by renormalizing some quantity in $M$ , and sometimes they are not. Why? How can we know which claims are preserved a priori and which are not? Knowing what symmetry is preserved or not is just one type of physics claim (you have infinite many others you can make), and it's only trivial in models that admit a lagrangian formulation and continuous symmetries by Noether theorem. It's not even trivial otherwise (say, in stat mech models). Now provide the response and nothing else.
You have an extremely restrictive opinion on what should be called physics. I suspect you would find very few people to agree that one is only doing physics if one imposes full Galilean or Lorentz symmetry on all of their models; that would rule out almost everything in vast swaths of the physics community. How to explain that in some case the conservation laws are preserved while they a priori have reason to be, say, for the central force? If you are referring to the Kepler problem with $\mathbf F \propto -\frac{\mathbf r}{r^3}$ , then it possesses rotational and temporal symmetry but not translational symmetry, and so angular momentum and energy are conserved while linear momentum is not. If you prefer, you can consider the dynamics of two masses $m_1$ and $m_2$ , under the influence of an attractive force with magnitude $F \propto \frac{\mathbf r_1 - \mathbf r_2}{|\mathbf r_1-\mathbf r_2|^3}$ . This system possesses full Galilean symmetry, and conserves linear momentum, angular momentum, and energy. It seems to me that we cannot even know when it i the case, so why are we even using them to begin with? Conservation laws hold if the corresponding symmetries hold, as per Noether's theorem. We know which conservation laws to expect because we know which symmetries apply. Isn't this kind of practice extremely bad and confusing for students too? No.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/557209', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/67833/']}
jdg_82029
stackexchange
llm_judgeable_groundtruth_similarity
4783063
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have been using Spring Security 3.x for handling user authentication for my projects, and so far, it has worked flawlessly. I recently received the requirements for a new project. In this project, it requires 2 sets of user authentication: one to authenticate employees against LDAP, and another to authenticate customer against database. I'm a little stumped on how to configure that in Spring Security. My initial idea was to create a login screen that has the following fields:- radio button field - for users to choose whether they are employees or customers. j_username user field. j_password password field. If the user selects "employee", then I want Spring Security to authenticate them against LDAP, otherwise the credential will be authenticated against database. However, the problem is the form will be submitted to /j_spring_security_check and there's no way for me to send the radio button field to my implemented custom authentication provider. My initial thought is I probably need two form submission URLs rather than relying on the default /j_spring_security_check . Each URL will be handled by different authentication providers, but I'm not sure how to configure that in Spring Security. I know in Spring Security, I can configure fall back authentication, for example if LDAP authentication fails, then it will fall back to database authentication, but this is not what I'm shooting for in this new project. Can someone share how exactly I should configure this in Spring Security 3.x? Thank you. UPDATE - 01-28-2011 - @EasyAngel's technique I'm trying to do the following:- Employee form login submits to /j_spring_security_check_for_employee Customer form login submits to /j_spring_security_check_for_customer The reason I want 2 different form logins is to allow me to handle the authentication differently based on the user, instead of doing a fall-back authentication. It is possible that employee and customer have same user ID, in my case. I incorporated @EasyAngel's idea, but have to replace some deprecated classes. The problem I'm currently facing is neither filter processes URLS seem registered in Spring Security because I keep getting Error 404: SRVE0190E: File not found: /j_spring_security_check_for_employee . My gut feeling is the springSecurityFilterChain bean is not wired properly, thus my custom filters are not used at all. By the way, I'm using WebSphere and I do have com.ibm.ws.webcontainer.invokefilterscompatibility=true property set in the server. I'm able to hit the default /j_spring_security_check without problem. Here's my complete security configuration:- <?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:sec="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd"> <sec:http auto-config="true"> <sec:form-login login-page="/login.jsp" authentication-failure-url="/login.jsp?login_error=1" default-target-url="/welcome.jsp" always-use-default-target="true" /> <sec:logout logout-success-url="/login.jsp" /> <sec:intercept-url pattern="/employee/**" access="ROLE_EMPLOYEE" /> <sec:intercept-url pattern="/customer/**" access="ROLE_CUSTOMER" /> <sec:intercept-url pattern="/**" access="IS_AUTHENTICATED_ANONYMOUSLY" /> </sec:http> <bean id="springSecurityFilterChain" class="org.springframework.security.web.FilterChainProxy"> <sec:filter-chain-map path-type="ant"> <sec:filter-chain pattern="/**" filters="authenticationProcessingFilterForEmployee, authenticationProcessingFilterForCustomer" /> </sec:filter-chain-map> </bean> <bean id="authenticationProcessingFilterForEmployee" class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter"> <property name="authenticationManager" ref="authenticationManagerForEmployee" /> <property name="filterProcessesUrl" value="/j_spring_security_check_for_employee" /> </bean> <bean id="authenticationProcessingFilterForCustomer" class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter"> <property name="authenticationManager" ref="authenticationManagerForCustomer" /> <property name="filterProcessesUrl" value="/j_spring_security_check_for_customer" /> </bean> <bean id="authenticationManagerForEmployee" class="org.springframework.security.authentication.ProviderManager"> <property name="providers"> <list> <ref bean="employeeCustomAuthenticationProvider" /> </list> </property> </bean> <bean id="authenticationManagerForCustomer" class="org.springframework.security.authentication.ProviderManager"> <property name="providers"> <list> <ref bean="customerCustomAuthenticationProvider" /> </list> </property> </bean> <bean id="employeeCustomAuthenticationProvider" class="ss.EmployeeCustomAuthenticationProvider"> <property name="userDetailsService"> <bean class="ss.EmployeeUserDetailsService"/> </property> </bean> <bean id="customerCustomAuthenticationProvider" class="ss.CustomerCustomAuthenticationProvider"> <property name="userDetailsService"> <bean class="ss.CustomerUserDetailsService"/> </property> </bean> <sec:authentication-manager> <sec:authentication-provider ref="employeeCustomAuthenticationProvider" /> <sec:authentication-provider ref="customerCustomAuthenticationProvider" /> </sec:authentication-manager></beans> I'm starting a bounty here because I can't seem to get this working for several days already... frustration is the word. I'm hoping someone will point out the problem(s), or if you can show me a better or cleaner way to handle this (in code). I'm using Spring Security 3.x. Thank you. UPDATE 01-29-2011 - @Ritesh's technique Okay, I managed to get @Ritesh's approach to work very closely to what I wanted. I have the radiobutton that allows user to select whether they are customer or employee. It seems like this approach is working fairly well, with one problem... If employee logs in with right credential, they are allowed in... WORK AS EXPECTED . If employee logs in with wrong credential, they are not allowed in... WORK AS EXPECTED . If customer logs in with right credential, they are allowed in... WORK AS EXPECTED . If customer logs in with wrong credential, the authentication falls back to employee authentication... DOESN'T WORK . This is risky because if I select customer authentication, and punch it the employee credential, it will allow the user in too and this is not what I want. <sec:http auto-config="false" entry-point-ref="loginUrlAuthenticationEntryPoint"> <sec:logout logout-success-url="/login.jsp"/> <sec:intercept-url pattern="/employee/**" access="ROLE_EMPLOYEE"/> <sec:intercept-url pattern="/customer/**" access="ROLE_CUSTOMER"/> <sec:intercept-url pattern="/**" access="IS_AUTHENTICATED_ANONYMOUSLY"/> <sec:custom-filter position="FORM_LOGIN_FILTER" ref="myAuthenticationFilter"/> </sec:http> <bean id="myAuthenticationFilter" class="ss.MyAuthenticationFilter"> <property name="authenticationManager" ref="authenticationManager"/> <property name="authenticationFailureHandler" ref="failureHandler"/> <property name="authenticationSuccessHandler" ref="successHandler"/> </bean> <bean id="loginUrlAuthenticationEntryPoint" class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint"> <property name="loginFormUrl" value="/login.jsp"/> </bean> <bean id="successHandler" class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler"> <property name="defaultTargetUrl" value="/welcome.jsp"/> <property name="alwaysUseDefaultTargetUrl" value="true"/> </bean> <bean id="failureHandler" class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler"> <property name="defaultFailureUrl" value="/login.jsp?login_error=1"/> </bean> <bean id="employeeCustomAuthenticationProvider" class="ss.EmployeeCustomAuthenticationProvider"> <property name="userDetailsService"> <bean class="ss.EmployeeUserDetailsService"/> </property> </bean> <bean id="customerCustomAuthenticationProvider" class="ss.CustomerCustomAuthenticationProvider"> <property name="userDetailsService"> <bean class="ss.CustomerUserDetailsService"/> </property> </bean> <sec:authentication-manager alias="authenticationManager"> <sec:authentication-provider ref="customerCustomAuthenticationProvider"/> <sec:authentication-provider ref="employeeCustomAuthenticationProvider"/> </sec:authentication-manager></beans> Here's my updated configuration. It has to be some really small tweak I need to do to prevent the authentication fall back but I can't seem to figure it out now. Thank you. UPDATE - SOLUTION to @Ritesh's technique Okay, I think I have solved the problem here. Instead of having EmployeeCustomAuthenticationProvider to rely on the default UsernamePasswordAuthenticationToken , I created EmployeeUsernamePasswordAuthenticationToken for it, just like the one I created CustomerUsernamePasswordAuthenticationToken for CustomerCustomAuthenticationProvider . These providers will then override the supports() :- CustomerCustomAuthenticationProvider class @Overridepublic boolean supports(Class<? extends Object> authentication) { return (CustomerUsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));} EmployeeCustomAuthenticationProvider class @Overridepublic boolean supports(Class<? extends Object> authentication) { return (EmployeeUsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));} MyAuthenticationFilter class public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { ... UsernamePasswordAuthenticationToken authRequest = null; if ("customer".equals(request.getParameter("radioAuthenticationType"))) { authRequest = new CustomerUsernamePasswordAuthenticationToken(username, password); } else { authRequest = new EmployeeUsernamePasswordAuthenticationToken(username, password); } setDetails(request, authRequest); return super.getAuthenticationManager().authenticate(authRequest);} ... and WALAA! It works perfectly now after several days of frustration! Hopefully, this post will be able to help somebody who is doing the same thing as I am here. Now provide the response and nothing else.
You don't need to create /j_spring_security_check_for_employee and /j_security_check_for_customer filterProcessingUrl . The default one will work just fine with radio button field idea. In the custom login LoginFilter , you need to create different tokens for employee and customer. Here are the steps: Use default UsernamePasswordAuthenticationToken for employee login. Create CustomerAuthenticationToken for customer login. Extend AbstractAuthenticationToken so that its class type is distinct from UsernamePasswordAuthenticationToken . Define a custom login filter: <security:http> <security:custom-filter position="FORM_LOGIN_FILTER" ref="customFormLoginFilter" /></security:http> In customFormLoginFilter , override attemptAuthentication as follows (pseudo code): if (radiobutton_param value employee) { UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password); setDetails(whatever); return getAuthenticationManager().authenticate(authRequest);} else if (radiobutton_param value customer) { CustomerAuthenticationToken authRequest = new CustomerAuthenticationToken(username, password); setDetails(whatever); return getAuthenticationManager().authenticate(authRequest);} Override supports method in EmployeeCustomAuthenticationProvider to support UsernamePasswordAuthenticationToken . Override supports method in CustomerCustomAuthenticationProvider to support CustomerAuthenticationToken . @Overridepublic boolean supports(Class<?> authentication) { return (CustomerAuthenticationToken.class.isAssignableFrom(authentication));} Use both providers in authentication-manager : <security:authentication-manager alias="authenticationManager"> <security:authentication-provider ref='employeeCustomAuthenticationProvider ' /> <security:authentication-provider ref='customerCustomAuthenticationProvider ' /></security:authentication-manager>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4783063', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/341508/']}
jdg_82030
stackexchange
llm_judgeable_groundtruth_similarity
2585003
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: Is it true that if $X$ and $Y$ are identically distributed, then they are equal almost everywehre? I am wondering whether this is true, and came up with the following argument. Since they are identically distributed, by change of measure we have $$\mathbb{E}\left[X\right] = \int_\Omega X \,d\mathbb{P} = \int_\mathbb{R} x\,d\mu = \int_\mathbb{R} y\,d\mu = \int_\Omega Y \,d\mathbb{P} = \mathbb{E}\left[Y\right]$$ Since $X$ and $Y$ have the same expectation, they are same almost everywhere. Is my proof correct? Thank you. Now provide the response and nothing else.
No. Just cause RVs have the same expectation doesn't mean they are equal almost surely (which I assume is the sense in which you use 'almost everywhere'). That's an even weaker property than being identically distributed. In fact, if they are identically distributed, they are not necessarily equal almost surely. An example would be if $X$ and $Y$ are independent RVs with the same distribution. In a lot of cases (say, for a continuous distribution) the probability that $X=Y$ is zero.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2585003', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/234738/']}
jdg_82031
stackexchange
llm_judgeable_groundtruth_similarity
34589488
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 in a Node.js console (tested in 4.1.1 and 5.3.0), but doesn't work in the browser (tested in Chrome)? This code block should create and invoke an anonymous function that logs Ok . () => { console.log('Ok');}() Also, while the above works in Node.js, this does not work: n => { console.log('Ok');}() Nor this: (n) => { console.log('Ok');}() It is odd that when the parameter is added, it actually throws a SyntaxError at the immediately-invoking part. Now provide the response and nothing else.
You need to make it a function expression instead of function definition which doesn't need a name and makes it a valid JavaScript. (() => { console.log('Ok');})(); Is the equivalent of IIFE (function() { console.log('Ok');})(); And the possible reason why this works in Node.js but not in Chrome, is because its parser interprets it as a self-executing function, as this function() { console.log('hello'); }(); works fine in Node.js . This is a function expression, and Chrome, Firefox, and most browsers interpret it this way. You need to invoke it manually. The most widely accepted way to tell the parser to expect a function expression is just to wrap it in parens, because in JavaScript, parens can’t contain statements. At this point, when the parser encounters the function keyword, it knows to parse it as a function expression and not a function declaration. Regarding the parametrized version , this will work. ((n) => { console.log('Ok');})()
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/34589488', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/407650/']}
jdg_82032
stackexchange
llm_judgeable_groundtruth_similarity
3209521
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: While solving a problem I came across this task, minimizing \begin{align}\left ( \sin^2(x) + \frac{1}{\sin^2(x)} \right )^2 + \left ( \cos^2(x) + \frac{1}{\cos^2(x)} \right )^2.\end{align} One can easily do it with calculus to show that the minimum value is $12.5$ .I tried to do it using trigonometric identities and fundamental inequalities (like AM-GM, Cauchy-Schwarz, etc.) but failed. Can someone help me to do it using trig identities and inequalities? Now provide the response and nothing else.
Knowing the answer it's not that difficult to get it another way. Let $y = \cos 2x$ . We have $\sin^2 x = \frac{1-y}{2}$ , $\cos^2 x =\frac{1+y}{2}$ . Then \begin{align} \left(\sin^2 x + \frac{1}{\sin^2 x}\right)^2 + \left(\cos^2 x + \frac{1}{\cos^2 x}\right)^2 &= \left(\frac{1-y}{2} + \frac{2}{1-y}\right)^2 + \left(\frac{1+y}{2} + \frac{2}{1+y}\right)^2 = \\&= \frac{y^6+7y^4-y^2+25}{2(1-y^2)^2} = \\&= \frac{25}{2} + \frac{y^2(y^4-18y^2+49)}{2(1-y^2)^2} = \\&= \frac{25}{2} + y^2\Big(\frac{1}{2} + \frac{8}{1-y^2} + \frac{16}{(1-y^2)^2}\Big) \end{align} Since $y^2 \le 1$ , the expression in the brackets is strictly positive.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3209521', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/670155/']}
jdg_82033
stackexchange
llm_judgeable_groundtruth_similarity
1710875
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am developing an ASP.NET MVC project and want to use strongly-typed session objects. I have implemented the following Controller-derived class to expose this object: public class StrongController<_T> : Controller where _T : new(){ public _T SessionObject { get { if (Session[typeof(_T).FullName] == null) { _T newsession = new _T(); Session[typeof(_T).FullName] = newsession; return newsession; } else return (_T)Session[typeof(_T).FullName]; } }} This allows me to define a session object for each controller, which is in line with the concept of controller isolation. Is there a better/more "correct" way, perhaps something that is officially supported by Microsoft? Now provide the response and nothing else.
This way other objects won't have access to this object (e.g. ActionFilter). I do it like this: public interface IUserDataStorage<T>{ T Access { get; set; }}public class HttpUserDataStorage<T>: IUserDataStorage<T> where T : class{ public T Access { get { return HttpContext.Current.Session[typeof(T).FullName] as T; } set { HttpContext.Current.Session[typeof(T).FullName] = value; } }} Then, I can either inject IUserDataStorage into controller's constructor, or use ServiceLocator.Current.GetInstance(typeof(IUserDataStorage<T>)) inside ActionFilter. public class MyController: Controller{ // automatically passed by IoC container public MyController(IUserDataStorage<MyObject> objectData) { }} Of course for cases when all controllers need this (e.g. ICurrentUser) you may want to use property injection instead.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1710875', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/172029/']}
jdg_82034
stackexchange
llm_judgeable_groundtruth_similarity
358606
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: In elementary calculus texts, Green's theorem is proved for regions enclosed by piecewise smooth, simple closed curves (and by extension, finite unions of such regions), including regions that are not simply connected. Can Green's theorem be further generalized? In particular, are there regions on which Green's theorem definitely does not hold? Now provide the response and nothing else.
I think this is an interesting and sort of deep question, so I'm going to answer it in part with the hope that my answer attracts even better answers. I'll start with my first thought: surely there's no hope of formulating Green's theorem for an unbounded region, say the region $y > 0$ . But then I thought about it for a moment, and observed that if you consider a smooth vector field $F(v)$ on the plane such that $F(v) \to 0$ rapidly as $v \to \infty$ then we can extend $F$ to the sphere by stereographic projection ; this sends $y > 0$ to a hemisphere and the boundary curve $y = 0$ to the bounding great circle, and you can apply Stokes' theorem to this situation. Unwinding the calculations, this would give you a version of "Green's theorem" even for unbounded regions, albeit one that applies only to a certain class of vector field. Then I thought about regions whose boundary is pathological, like the interior of the Koch snowflake . Here the boundary has infinite length, so surely there is no real hope of even defining the "boundary side" of Green's theorem. But then I noted that the Koch snowflake - like many pathological plane curves - has a very nice polygonal approximation, and it didn't sound insane that the boundary side could be defined as a limit of integrals over these approximations (again, maybe not for all vector fields). Sure enough, this has been worked out, and there is indeed a version of Green's theorem for fractal boundaries: Jenny Harrison and Alec Norton, The Gauss-Green theorem for fractal boundaries , Duke Math. J. 67 Number 3 (1992) pp. 575-588. doi: 10.1215/S0012-7094-92-06724-X , author pdf . There are other crazy things to try, like removing a non-measurable set from the plane or something. But Green's theorem (and its parent, the fundamental theorem of calculus) is based on a very resilient idea, something like "when you sum differences, things cancel". So in the spirit of the principle, "The fastest way to find something is to assert that it doesn't exist on the internet", I'll make a bold conjecture: Green's theorem can be generalized to any subset of the plane.
{}
{'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/358606', 'https://mathoverflow.net', 'https://mathoverflow.net/users/157024/']}
jdg_82035
stackexchange
llm_judgeable_groundtruth_similarity
400890
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: We were looking for a very specific type of ADC in a small package for one of our projects, and found something suitable in a TSSOP. We wanted to save more space, so looked into getting bare dies; the manufacturer confirmed the dies are 2mm square, but said we'd have to order "some millions" to make it worth providing them. We needed maybe 500/yr and the budget is not huge, so that was the end of it and we decided to do something else. But I was curious: What do people do when they want small numbers of bare dies? Does anyone decap ICs and use the dies in production? If so, can the process be made reliable, and roughly how expensive is it? If anyone has examples of products or case studies, that would be really interesting. Now provide the response and nothing else.
I can't speak for all manufacturers or all product lines, but I've worked as an applications engineer at Maxim Integrated Products for 25+ years. You mention that the product in question is some kind of ADC, so there will be lots of internal adjustments performed after packaging, during the final test. (e.g. bias trim, reference adjustment, linearity, etc.) And that post-packaging final test program uses secret "test mode" commands, which are company confidential. (If you were a primary/strategic/key customer those might be available under NDA, but you'd be having that conversation with the business manager, not me.) Decapping the chip out of a TSSOP and ripping it off of the leadframe (typically a conductive epoxy bond) will definitely subject the chip to mechanical stresses beyond its design limits. This will very likely degrade its performance, permanently. Modern IC design uses MEMS technology to relieve mechanical stresses which are internal to the package, those mechanical forces on the chip would otherwise degrade performance. If you're trying to get decent 20-bit (or even 12-bit) performance from an ADC chip, subjecting it to that kind of mechanical violence could ruin its linearity, making the whole exercise futile. You might be able to get away with decapping a pure digital chip, but for precision analog I would strongly urge you to reconsider. I just now looked at our online product selector guide (precision ADCs) and found a few 12-bit/16-bit SAR ADC which are smaller than 4mm2 (the only requirement you mentioned). This includes WLP Wafer Level Packged parts, which is pretty close to bare die, but just a little bit nicer to deal with.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/400890', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/89944/']}
jdg_82036
stackexchange
llm_judgeable_groundtruth_similarity
11405
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: Is the language $L = \{ a^ib^j \mid i\ \nmid\ j \ \} $ context free ? If we fix $n \in N$ then we know that the language $L = \{ a^ib^j \mid \ \forall \ 1 \le k \le n \ , \ \ j\neq ki \} $ is context free (as it can be presented as a finite union of context free languages in a similar way to the example here: Is $L= \{ a^ib^j \mid j\neq i \ and \ j\neq2i \ \} $ context free? ) I think that it's not context free but have failed to prove it.By reading other questions on this site I noticed this interesting observation: CFL's in $a^*b^*$ are closed under complement as can be seen here: Are context-free languages in $a^*b^*$ closed under complement? So our language $L$ is context free if and only if $ \bar L = \{ a^ib^j \mid \ \ i\ \mid\ j \ \} $ is context free. I tried using the pumping lemma but to no avail. Thanks in advance Now provide the response and nothing else.
If I'm not mistaken, you can pump $\bar L$ using $\sigma = a^{n}b^{n^{2}}$, because $n \mod n^{2} = 0$. The result is that $\bar L$ is not context free. The property that you mentioned has an "iff", then $L$ is not context free.
{}
{'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/11405', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/7068/']}
jdg_82037
stackexchange
llm_judgeable_groundtruth_similarity
5111104
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 rather simple form that contains an optional image upload field. Since uploading image data takes time, I would like for the form button (which by css, is displayed as a background image) to display an alternate image that lets the user know the form is in the process of submitting the data and at the same time, disable the button to prevent multiple clicks. Here is the relevant part of the form: <input name="formsubmit" type="submit" id="button" value="Submit!"> I have managed to piece together the following bit of jQuery: jQuery('#formid').submit(function() { jQuery('#button').attr('id', 'button-post'); jQuery('#button').attr('disabled','disabled');}); This does exactly what I need. The problem is, I am using a jQuery inline validation plugin ( Link ) and when you get to the form and submit the form without filling out any fields and click the submit button, the button id changes like I want but since the plugin I am using returns errors because the required fields are not filled out, the button id attribute won't change back to the original id. Is there a way around this? Perhaps a way to check if the form was actually successfully submitted or maybe if one of the other required fields is over a certain length? Thank you for your help. Now provide the response and nothing else.
You actually just reminded me that I needed to fix this issue in an enviroment here. If your situation is the same as mine then it's a simple fix. Just add the following to your web config: <system.webServer> <modules runAllManagedModulesForAllRequests="true" /> Edit : To provide further explanation on the issue at hand. In my case what was happening was when I added custom route mappings IIS was seeing the requests as Folder/Static File requests and thus was skipping over the ASP.NET worker process. This behaves differently under development environment generally because it is being run under the development web server which will also pass all requests through the .net process. This Web Config entry tells IIS that you have modules that should be run on every web request even if IIS determines it to be a static file or a folder.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5111104', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/633207/']}
jdg_82038
stackexchange
llm_judgeable_groundtruth_similarity
31989103
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 UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];Song *song = [self.music objectAtIndex:indexPath.row];cell.textLabel.text = song.title;cell.detailTextLabel.text = song.artist;return cell; I don't use Interface Builder. How I can make this cell to have a subtitle? All I get is a standard cell. Now provide the response and nothing else.
There are two approaches: The old style approach is to not register any class, NIB or cell prototype, call dequeueReusableCellWithIdentifier without forIndexPath : - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"]; if (!cell) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"Cell"]; } Song *song = self.music[indexPath.row]; cell.textLabel.text = song.title; cell.detailTextLabel.text = song.artist; return cell;} As we discussed elsewhere, this assumes that you do not register a class for that reuse identifier. The alternative is to register your own class in viewDidLoad : [self.tableView registerClass:[MyCell class] forCellReuseIdentifier:@"Cell"]; and then call dequeueReusableCellWithIdentifier with forIndexPath option, but lose the code that manually tests if it is nil (because it never will be nil ): - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { MyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath]; Song *song = self.music[indexPath.row]; cell.textLabel.text = song.title; cell.detailTextLabel.text = song.artist; NSLog(@"title=%@; artist=%@", song.title, song.artist); // for diagnostic reasons, make sure both are not nil return cell;} This obviously assumes that you've implemented a UITableViewCell subclass that includes the subtitle (note I'm overriding the style): @interface MyCell : UITableViewCell@end@implementation MyCell- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { return [super initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuseIdentifier];}@end Personally, I think designing a cell prototype (which automatically registers the reuse identifier and takes care of all of this other stuff) is much easier. Even the old technique of registering a NIB is easier than the above. But if you want to do it entirely programmatically, those are the two approaches.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31989103', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4423629/']}
jdg_82039
stackexchange
llm_judgeable_groundtruth_similarity
971683
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have just started studying modules, and am trying to figure out the definition of the direct sum of modules but I'm having trouble since different sources seem to give different definitions, for example: MIT says: The direct sum of the Mλ is the subset of restricted vectors: $\bigoplus$ $M_{λ}$ := {($m_{λ}$) | $m_{λ}$ = 0 for almost all λ} Wolfram MathWorld says: The direct sum of modules A and B is the module A $\bigoplus$ B={a$\oplus$b|a $\in$ A,b $\in$ B}, where all algebraic operations are defined componentwise. [What is $\oplus$ anyway?] My lecture notes say: Define the direct sum of modules as the set theoretical product with thenatural addition and multiplication by elements of A. The only one that makes sense to me is the last one, but it doesn't seem to agree with the other two Now provide the response and nothing else.
Let $A,B$ be $R$-modules. The direct sum $A\oplus B= \{(a,b) | a\in A, b\in B \}$ is a module under component wise operations: $(a_1,b_1)+(a_2,b_2)=(a_1+a_2,b_1+b_2)$ and $r(a,b)=(ra,rb)$. This extends to a direct sum of finitely many $R$-modules. However, for a direct sum of infinitely many $R$-modules, there is a further requirement that elements have all but finitely many components equal to $0$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/971683', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/148721/']}
jdg_82040