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
32950
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: While in a mood to purchase a Peltier strip, I visited the amazon page which stated the specs of a Peltier thermoelectric cooler, one stated 12 V and 92 W and other one stated 12 V and some 77 W. As I already know power is the product of voltage and current drawn. And the amount of current drawn is dependent on the resistance the circuit has to the battery, the less the resistance the more the current, the more the resistance the less the current. So why should power be part of the electronic instrument's specification? Will a set of 8 pencil cells (1.5 volts each) are not enough for each one of these two peltier devices? my assumption is that since one will draw 92 watts and another will draw 77 watts so the batteries operating 92 watts device will consume more quickly than the other batteries with 77 watts device. But eventually both can be operated on a 12 V battery with different performances depending on their power requirements, am I right? Now provide the response and nothing else.
Any two of voltage, current, and power can be specified and the third inferred. Which two are listed in the datasheet depends on what is customary to talk about for that class of device, what the datasheet writers think is more relevant, or what matters most to the design engineers that give the specs to the datasheet writer. Sometimes with lesser datasheets you get the parameters marketing wants to push because they think their device is better than the competition in that area. It varies. If a devices is rated to require 92 Watts at 12 Volts, then you can infer it draws 7.7 Amps at that operating point . Again, you can compute any one of these numbers from the other two. Be careful what the power spec really means. There are two different specs that have units of power for Peltier coolers. One is the electrical power the device will use, the other is the thermal cooling power. Both are relevant to different parts of the design. Possibly only one of these is listed and a efficiency spec is provided so that you can determine the other. With Peltier coolers, efficiency is a strong inverse function of input current. There should be either a equation or a graph in the datasheet showing the relationship. As always, it's important to read the datasheet carefully . If you find a spec that doesn't make sense, come back and ask about it specifically. Otherwise there is too much general stuff to get into here. As a separate issue, 92 Watts is way way way too much power to expect from a few "pencil cells". Go read a datasheet for any ordinary AA battery, paying close attention to maximum current and derating at high current levels.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/32950', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/9574/']}
jdg_378541
stackexchange
llm_judgeable_groundtruth_similarity
45581752
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 will try to make this as clear as I possibly can. But right now, I have a table being displayed when it's called into HTML. However, when someone types in a president name, I want the fully listed table to go away and display the results that is filtered after the person clicks on "Search for Presidents". I tried a conditional if else statement but it clears out the table (making it blank), then it makes me have to do another click, which then displays the filtered results. Is there any way of preventing that double click? JSfiddle for viewing https://jsfiddle.net/rtomino/7Lod1szp/1/ The conditional I had but it makes me do the double click. if (document.getElementById('presidentialTable').innerHTML !== "") { document.getElementById("presidentialTable").innerHTML = "";} else { document.getElementById('presidentialTable').appendChild(table);} The HTML <form> <label for="name">Name:</label> <input id='input' placeholder="President Name" type="text"> <button onclick="loadPresidents()" type="button">Search for Presidents</button> <button type="button" onclick="clearTable()">Clear</button> <div id="presidentialTable"></div></form> The JS function loadPresidents() {"use strict";var xhttp = new XMLHttpRequest();xhttp.onreadystatechange = function() { if (this.readyState === 4 && this.status === 200) { var data = this.responseText, jsonResponse = JSON.parse(data), table = document.createElement('table'); table.setAttribute('class', 'history'); var properties = ['number', 'name', 'date', 'took_office', 'left_office']; var capitalize = function(s) { return s.charAt(0).toUpperCase() + s.slice(1); }; function filterPresidents(data) { var input = document.getElementById('input').value; return data.filter(function(historicalData) { return historicalData.name.toLowerCase().indexOf(input.toLowerCase()) != -1; }); } var tr = document.createElement('tr'); for (var i = 0; i < properties.length; i++) { var th = document.createElement('th'); th.appendChild(document.createTextNode(capitalize(properties[i]))); tr.appendChild(th); } table.appendChild(tr); var tr, row; var filtered = filterPresidents(jsonResponse["presidents"].president); for (var r = 0; r < filtered.length; r++) { tr = document.createElement('tr'); row = filtered[r]; for (var i = 0; i < properties.length; i++) { var td = document.createElement('td'); td.appendChild(document.createTextNode(row[properties[i]])); tr.appendChild(td); } table.appendChild(tr); } if (document.getElementById('presidentialTable').innerHTML !== "") { document.getElementById("presidentialTable").innerHTML = ""; } else { document.getElementById('presidentialTable').appendChild(table); } }};xhttp.open("GET", "http://schwartzcomputer.com/ICT4570/Resources/USPresidents.json", true);xhttp.send(); } loadPresidents(); function clearTable() { document.getElementById("presidentialTable").innerHTML = ""; } Now provide the response and nothing else.
When an Amazon DynamoDB table is created, you can specify the desired throughput in Reads per second and Writes per second . The table will then be provisioned across multiple servers (partitions) sufficient to provide the requested throughput. You do not have visibility into the number of partitions created -- it is fully managed by DynamoDB. Additional partitions will be created as the quantity of data increases or when the provisioned throughput is increased. Let's say you have requested 1000 Reads per second and the data has been internally partitioned across 10 servers (10 partitions). Each partition will provide 100 Reads per second . If all Read requests are for the same partition key, the throughput will be limited to 100 Reads per second. If the requests are spread over a range of different values, the throughput can be the full 1000 Reads per second . If many queries are made for the same Partition Key, it can result in a Hot Partition that limits the total available throughput. Think of it like a bank with lines in front of teller windows . If everybody lines up at one teller, less customers can be served. It is more efficient to distribute customers across many different teller windows. A good partition key for distributing customers might be the customer number, since it is different for each customer. A poor partition key might their zip code because they all live in the same area nearby the bank. The simple rule is that you should choose a Partition Key that has a range of different values. See: Partitions and Data Distribution
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/45581752', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5261505/']}
jdg_378542
stackexchange
llm_judgeable_groundtruth_similarity
760904
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 change is made within a directory on a Windows system, I need a program to be notified immediately of the change. Is there some way of executing a program when a change occurs? I'm not a C/C++/.NET programmer, so if I could set up something so that the change could trigger a batch file then that would be ideal. Now provide the response and nothing else.
Use a FileSystemWatcher like below to create a WatcherCreated Event(). I used this to create a Windows Service that watches a Network folder and then emails a specified group on arrival of new files. // Declare a new FILESYSTEMWATCHER protected FileSystemWatcher watcher; string pathToFolder = @"YourDesired Path Here"; // Initialize the New FILESYSTEMWATCHER watcher = new FileSystemWatcher {Path = pathToFolder, IncludeSubdirectories = true, Filter = "*.*"}; watcher.EnableRaisingEvents = true; watcher.Created += new FileSystemEventHandler(WatcherCreated); void WatcherCreated(object source , FileSystemEventArgs e) { //Code goes here for when a new file is detected }
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/760904', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/18333/']}
jdg_378543
stackexchange
llm_judgeable_groundtruth_similarity
2662005
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: Suppose $G$ and $H$ are groups and we have an equivalence of categories between $G\textrm{-}\mathbf{Set}$ and $H\textrm{-}\mathbf{Set}$. (One can think of this as a form of "nonlinear Morita equivalence".) What can be said about $G$ and $H$? I suspect that $G$ and $H$ have to be isomorphic, but I can't prove it. If this is too hard in general, I'm also interested in the case that $G$ and $H$ are assumed to be finite. Here are some things I've tried: Since $G$-modules are the abelian group objects in $G\textrm{-}\mathbf{Set}$, we get a Morita equivalence between $\Bbb{Z}[G]$ and $\Bbb{Z}[H]$. So if we tensor with any field $k$, we get a Morita equivalence between $k[G]$ and $k[H]$. Assume for a moment that $G$ and $H$ are finite. If we take $k = \Bbb{C}$, then this means that $G$ and $H$ have the same number of irreducible representations, so the same number of conjugacy classes. If we take $k=\Bbb{R}, \Bbb{Q}, \overline{\Bbb{F}_p}$, we also get the same number of real, rational and $p$-regular conjugacy classes. While this approach gives some common properties between $G$ and $H$, it's not possible to conclude that $G$ and $H$ are isomorphic, because there are known examples of non-isomorphic finite groups with isomorphic integral group algebras. (See here ) This means that we have to use some of the "nonlinear" information from the category $G\textrm{-}\mathbf{Set}$. Another thing I considered is that the automorphism group of the forgetful functor $G\textrm{-}\mathbf{Set} \to \mathbf{Set}$ is isomorphic to $G$, by a simple Yoneda-argument, so if we could somehow reconstruct the forgetful functor just from the category $G\textrm{-}\mathbf{Set}$, this would show that $G$ and $H$ must be isomorphic. I haven't been able to do this, but I reconstructed some other functors: The terminal object in $G\textrm{-}\mathbf{Set}$ is a one-point set with a trivial action, denote this $G$-set by $\{*\}$, we have a natural bijection $\operatorname{Hom}_{G\textrm{-}\mathbf{Set}}(\{*\},X) \cong X^G$, where $X^G$ denotes the set of fixed points under the action of $G$.So we can reconstruct the fixed point functor $G\textrm{-}\mathbf{Set} \to \mathbf{Set}$. The left adjoint of that functor is the functor $\mathbf{Set} \to G\textrm{-}\mathbf{Set}$ which gives each set a trivial $G$-action. Denote $X$ with a trivial $G$-action by $X_{triv}$. We have $\operatorname{Hom}_{G\textrm{-}\mathbf{Set}}(X,Y_{triv}) \cong \operatorname{Hom}_{\mathbf{Set}}(X/G,Y)$, so the functor which sends each $G$-set to the orbit space $X/G$ is left adjoint to the functor which gives each set a trivial $G$-action, so we can reconstruct the functor $X \mapsto X/G$ from the category $G\textrm{-}\mathbf{Set}$. Not sure if that's helpful. Maybe it's even possible that $G$ and $H$ don't have to be isomorphic? I'm looking either for a counterexample or a proof. Now provide the response and nothing else.
The empty $G$-set is the initial object. The coproduct of $G$-sets is the disjoint union. Call a $G$-set “indecomposable” if it is not the coproduct of two non-empty $G$-sets, so an indecomposable $G$-set is just a transitive one. An epimorphism of $G$-sets is just a surjective map of $G$-sets. Up to isomorphism, there is a unique transitive $G$-set with an epimorphism to every other transitive $G$-set, namely the regular $G$-set, whose automorphism group is $G$. So $G$ can be recovered from the category of $G$-sets.
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/2662005', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/348926/']}
jdg_378544
stackexchange
llm_judgeable_groundtruth_similarity
4024
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Do security questions subvert hard to crack passwords? For example, if a site requires passwords with a certain scheme (length + required character sets) and has a security question, why would someone try cracking the password instead of the security question? I assume most answers to these are shorter and have a smaller variety of characters. For example, "Mother's Maiden Name" (somewhat common question) is typically not as long as a decent password (even after satisfying password requirements) and often contains only letters. When a site requires a security question, is it best to fill it in with a lengthy string containing random characters? Now provide the response and nothing else.
The manner in which security questions are used by a site, determines whether they undermine the supposedly stronger authentication mechanism (of using good passwords). Typically, systems that allow access to users after they've answered a security question, are weaker than systems that would communicate a (temporary) password to the user via a (different and secure) channel. The previous statement conveys a best practice, and certain systems need not implement all of it; some systems would provide a new password (which need not be changed by a user), and there are other systems that would communicate the password via an insecure channel. Filling a security question with random characters is not necessarily a good approach (although it is better than having a smaller answer with low entropy), for it would make it difficult to remember, resulting in a potential lock-out scenario (from where this is often no point of recovery). It should be remembered that security questions are often not changed periodically unlike passwords. The answer therefore depends on how well the answer is protected (both by the user and the system), how public the answer actually is, and how frequently can the question (and answer) be changed. Reading this related StackOverflow question is recommended, for the answers discuss out-of-band communication, amongst other issues like the potential lock-out scenario.
{}
{'log_upvote_score': 6, 'links': ['https://security.stackexchange.com/questions/4024', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/2560/']}
jdg_378545
stackexchange
llm_judgeable_groundtruth_similarity
931114
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 keeping several texts in an App_GlobalResources.resx file. The texts have to be multi-line and I need to have them contain line feeds. However, when I read the contents, all line feeds are gone ( \r\n is printed, not as CRLF 10 13 control character). I know that I could work around this by re-replacing \r\n (or anything else for that matter) back to CRLF when I read the contents, but I wondered why these clearly text-targeted resx files ignore control characters - and CRLF is kind of important - and if anybody knows if there's a setting or something that would enable this to work naturally. Now provide the response and nothing else.
I used VB.NET Express Edition to test this. In the resource editor (where you can specify the name of the resource and string content) put the string content separated by Shift + Enter . Lets say you want to type in hello world Type "hello" followed by Shift + Enter and "world". If you look at the Resources.Resx file (which is an xml file), you can see that it creates a node with the attribute xml:space="preserve" . 2nd option Also, you can edit the Resources.resx manually and modify the content to be under CDATA section. Assume that you have the string named "example". Search for it in Resources.resx and change the content to have CDATA section inside it as against having a simple value. e.g. <data name="example"><![CDATA[helloworld12 34]]> </data>
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/931114', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/114916/']}
jdg_378546
stackexchange
llm_judgeable_groundtruth_similarity
350501
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: void Animation::playAnimation() const{ static const int index = 0; const std::string& animationFileName = m_animationContainer.getAnimationName(index); static const int zOrder = -1; static bool isLooping = false; AnimationBank::play(animationFileName, zOrder, isLooping);} Is there any benefit to to define constant local variables as static ? Or it is unnecessary and even bad practice. Now provide the response and nothing else.
Beyond @Christophe's very good answer, the code generated for the static is most likely worse than the one for the local variable, so if you're interested the under-the-hood benefit, statics are worse on modern processors. The reason is that the statics must be located somewhere in memory that can be found by all the other threads and by all the other invocations. This basically means putting them in global memory. Over the years, processors & compilers together have significantly optimized access to local variables due to the popularity of their usage, as compared with other variables, such as globals, statics, and fields. The compiler may choose to store a local variable in a CPU register, and even if it doesn't (so it uses the invocation stack instead) all of the stack is almost certainly in the cache. Accessing the stack is usually a short displacement addressing mode (off the stack pointer register). However, accessing globals or statics usually requires and extended offset or absolute address, so the resulting instructions doing so are longer than their equivalent for stack memory access. All that being said, due to the combination of static and const the compiler may detect that it can substitute the constant value at the point of usage, so perhaps use of const mitigates the above. Still, your snippet shows at least one non-const statics, so perhaps the discussion is topical.
{}
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/350501', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/200019/']}
jdg_378547
stackexchange
llm_judgeable_groundtruth_similarity
3640604
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 confused by a piece of code found in a function I am studying: char GetCommand( void ){ char command; do { printf( "Enter command (q=quit, n=new, l=list): " ); scanf( "%c", &command ); Flush(); } while ( (command != 'q') && (command != 'n') && (command != 'l') ); printf( "\n----------\n" ); return( command );}void Flush( void ) { while ( getchar() != '\n' ) ;} What I don't quite understand here is the usage of the Flush() function. I mean, the book I am reading explains it by saying that it prevents the user from inputting more than a single character and then having that character read when they are prompted for input the 2nd time. What I don't understand is how Flush() is preventing this from happening. It doesn't DO anything. All it is is a while command. (While this is true......what?????) Doesn't make sense. Now provide the response and nothing else.
getchar() has the side effect of removing the next character from the input buffer. The loop in Flush reads and discards characters until - and including - the newline \n ending the line. Since the scanf is told to read one and only one character ( %c ) this has the effect of ignoring everything else on that input line. It would probably be more clear if the scanf was replace with command = getchar(); but it's actually a generally bad example as it does not handle End Of File well. In general scanf is best forgotten; fgets and sscanf work much better as one is responsible for getting the input and the other for parsing it. scanf (and fscanf ) try to do too many jobs at once.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3640604', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/324788/']}
jdg_378548
stackexchange
llm_judgeable_groundtruth_similarity
4207656
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Since a function in C returns only one value, all the time, how can fork() , which is also a function, return two values? Now provide the response and nothing else.
If you read, build, and run the following program you should get a better idea of what is going on. #include <stdio.h>#include <unistd.h>int main(void) { pid_t fk; printf("\tbefore fork my pid = %lu\n", (unsigned long)getpid() ); fflush(stdout); /* This may keep the above print statement from outputing twice. */ fk = fork(); /* The OS kernel makes a copy of the current process here */ printf("fork returned %lu and now my pid = %lu\n", (unsigned long)fk, (unsigned long)getpid() ); return 0;} The reason that the fflush(stdout) is needed is that since the process is duplicated by fork that means that the buffering done for stdout by stdio is duplicated as well. The "\n" at the end of that first print statement may make it go ahead and flush stdout, but this isn't guaranteed.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4207656', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/507401/']}
jdg_378549
stackexchange
llm_judgeable_groundtruth_similarity
38356283
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 list of thousands of instagram user-ids. How do I get their Instagram usernames/handles? Now provide the response and nothing else.
You can access it without needing API via internal /user/ endpoint instagram uses for AJAX requests: https://i.instagram.com/api/v1/users/{user_id}/info/ where {user_id} is numeric user id like 6817966272 . Returned response example (see user['username'] key for username): GET https://i.instagram.com/api/v1/users/6817966272/info/ { "user": { "pk": 6817966272, "username": "myriaamaa", "full_name": "\u2661", "is_private": false, "profile_pic_url": "https://instagram.fcnx2-1.fna.fbcdn.net/vp/66486d198fc02046d04d7bc11e51e54a/5D913015/t51.2885-19/s150x150/61226760_298998544311382_2345929352031502336_n.jpg?_nc_ht=instagram.fcnx2-1.fna.fbcdn.net", "profile_pic_id": "2056076981860037983_6817966272", "is_verified": false, "has_anonymous_profile_picture": false, "media_count": 216, "follower_count": 4926, "following_count": 83, "following_tag_count": 0, "biography": "YOU. ARE. HOLY \ud83c\udf19", "external_url": "", "total_igtv_videos": 0, "total_ar_effects": 0, "usertags_count": 6, "is_favorite": false, "is_interest_account": true, "hd_profile_pic_versions": [ { "width": 320, "height": 320, "url": "https://instagram.fcnx2-1.fna.fbcdn.net/vp/fafecdc76c82de85580c9c03d14b1aaa/5D9BD2E5/t51.2885-19/s320x320/61226760_298998544311382_2345929352031502336_n.jpg?_nc_ht=instagram.fcnx2-1.fna.fbcdn.net" }, { "width": 640, "height": 640, "url": "https://instagram.fcnx2-1.fna.fbcdn.net/vp/0ec5339e3958c9c41414e5378fa2443c/5D7DD28A/t51.2885-19/s640x640/61226760_298998544311382_2345929352031502336_n.jpg?_nc_ht=instagram.fcnx2-1.fna.fbcdn.net" } ], "hd_profile_pic_url_info": { "url": "https://instagram.fcnx2-1.fna.fbcdn.net/vp/8b3859950f0bb8e1a4a8f65566992b78/5D9132EF/t51.2885-19/61226760_298998544311382_2345929352031502336_n.jpg?_nc_ht=instagram.fcnx2-1.fna.fbcdn.net", "width": 774, "height": 774 }, "mutual_followers_count": 0, "has_highlight_reels": true, "can_be_reported_as_fraud": false, "is_business": false, "account_type": 1, "is_call_to_action_enabled": null, "include_direct_blacklist_status": true, "is_potential_business": true, "is_bestie": false, "has_unseen_besties_media": false, "show_account_transparency_details": false, "auto_expand_chaining": false, "highlight_reshare_disabled": false }, "status": "ok"} EDIT 2019-10: This endpoint only serves user-agents that identify themselves as instagram app. I got it working with iphone's instagram user agent: Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_3 like Mac OS X) AppleWebKit/603.3.8 (KHTML, like Gecko) Mobile/14G60 Instagram 12.0.0.16.90 (iPhone9,4; iOS 10_3_3; en_US; en-US; scale=2.61; gamut=wide; 1080x1920) For more check out this online user agent database: https://developers.whatismybrowser.com/useragents/explore/software_name/instagram/1 # top 5:Mozilla/5.0 (Linux; Android 8.1.0; motorola one Build/OPKS28.63-18-3; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/70.0.3538.80 Mobile Safari/537.36 Instagram 72.0.0.21.98 Android (27/8.1.0; 320dpi; 720x1362; motorola; motorola one; deen_sprout; qcom; pt_BR; 132081645) Mozilla/5.0 (Linux; Android 7.0; Lenovo K33b36 Build/NRD90N; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/65.0.3325.109 Mobile Safari/537.36 Instagram 41.0.0.13.92 Android (24/7.0; 480dpi; 1080x1920; LENOVO/Lenovo; Lenovo K33b36; K33b36; qcom; pt_BR; 103516666) Mozilla/5.0 (Linux; Android 5.0.1; LG-H342 Build/LRX21Y; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/65.0.3325.109 Mobile Safari/537.36 Instagram 40.0.0.14.95 Android (21/5.0.1; 240dpi; 480x786; LGE/lge; LG-H342; c50ds; c50ds; pt_BR; 102221277) Mozilla/5.0 (Linux; Android 6.0.1; SM-G610M Build/MMB29K; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/65.0.3325.109 Mobile Safari/537.36 Instagram 41.0.0.13.92 Android (23/6.0.1; 480dpi; 1080x1920; samsung; SM-G610M; on7xelte; samsungexynos7870; pt_BR; 103516666) Mozilla/5.0 (Linux; Android 8.0.0; SM-A520F Build/R16NW; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/66.0.3359.158 Mobile Safari/537.36 Instagram 46.0.0.15.96 Android (26/8.0.0; 480dpi; 1080x1920; samsung; SM-A520F; a5y17lte; samsungexynos7880; pt_BR; 109556226) Edit 2020-05/2022-05: Currently this endpoint returns less information but username is still present: { "user": { "username": "meram.ba", "pk": 6817966272, "profile_pic_url": "https://instagram.fbkk5-5.fna.fbcdn.net/v/t51.2885-19/s150x150/93795245_228684278392964_3931284463400517632_n.jpg?_nc_ht=instagram.fbkk5-5.fna.fbcdn.net&_nc_ohc=O6-_BTmMHUIAX9Qy8up&oh=8303e6fc8444b920c0c0edc603c917b5&oe=5EE91CF3" }, "status": "ok"}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38356283', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4337181/']}
jdg_378550
stackexchange
llm_judgeable_groundtruth_similarity
14304128
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am new to the spring-data-jpa and am currently trying to implement with hibernate. I've followed the tutorial ! for this and am currently facing issues starting the application itself.I get the following exception during startup: Caused by: org.springframework.data.mapping.PropertyReferenceException: No property customer found for type com.adaptris.dashboard.customer.Customerat org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:74)at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:326)at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:352)at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:306)at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:270)at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:244)at org.springframework.data.repository.query.parser.Part.<init>(Part.java:73)at org.springframework.data.repository.query.parser.PartTree$OrPart.<init>(PartTree.java:180)at org.springframework.data.repository.query.parser.PartTree$Predicate.buildTree(PartTree.java:260)at org.springframework.data.repository.query.parser.PartTree$Predicate.<init>(PartTree.java:240)at org.springframework.data.repository.query.parser.PartTree.<init>(PartTree.java:71)at org.springframework.data.jpa.repository.query.PartTreeJpaQuery.<init>(PartTreeJpaQuery.java:57)at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:90)at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateIfNotFoundQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:162)at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$AbstractQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:68)at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.<init>(RepositoryFactorySupport.java:280)at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:148)at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.getObject(RepositoryFactoryBeanSupport.java:125)at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.getObject(RepositoryFactoryBeanSupport.java:41)at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:142) Customer is my domain class annotated with @Entity(name = "customer") And I suppose it is trying to connect to the DB and fetch the customer table which I've actually configured. Here is my spring-config: <tx:annotation-driven transaction-manager="transactionManager" /><!-- Activate Spring Data JPA repository support --><jpa:repositories base-package="com.adaptris.dashboard.customer" /> <!-- Declare a datasource that has pooling capabilities --><bean id="jpaDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close" p:driverClass="${app.jdbc.driverClassName}" p:jdbcUrl="${app.jdbc.url}" p:user="${app.jdbc.username}" p:password="${app.jdbc.password}" p:acquireIncrement="5" p:idleConnectionTestPeriod="60" p:maxPoolSize="100" p:maxStatements="50" p:minPoolSize="10" /><!-- Declare a JPA entityManagerFactory --><bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" p:persistenceXmlLocation="classpath*:META-INF/persistence.xml" p:persistenceUnitName="hibernatePersistenceUnit" p:dataSource-ref="jpaDataSource" p:jpaVendorAdapter-ref="hibernateVendor" /><!-- Specify our ORM vendor --><bean id="hibernateVendor" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" p:showSql="false" /><!-- Declare a transaction manager --><bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" p:entityManagerFactory-ref="entityManagerFactory" /> And the DB is MYSQL which is running. Following are the properties: # database propertiesapp.jdbc.driverClassName=com.mysql.jdbc.Driverapp.jdbc.url=jdbc\:mysql\://Mallik-PC/adaptrisschemaapp.jdbc.username=dbuserapp.jdbc.password=dbpassword Please help me out in getting out of this issue!! Now provide the response and nothing else.
Sounds like the Repository interface you have specified for your Domain class contains a findXXX method whereas XXX is not a property of your Domain class. Example: public interface UserRepository extends CrudRepository<User, String> { /** * Finds a user by name. * * @param name The name of the User to find. * @return The User with the given name. */ public User findByName(String name);} And your Domain class looks like this and misses the "name" property: @Entitypublic class User { private String firstname; private String lastname; // No "private String name" in here! ... } In your particular example it looks like you added a findByCustomer(Customer customer) method to your Repository interface (probably called something like CustomerRepository ). You don't need that method as a findOne(<PrimaryKeyClass> id) method is automatically generated for you by Spring Data for JPA and you can just call it with the @Id of your Domain class Customer as a parameter.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14304128', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1798932/']}
jdg_378551
stackexchange
llm_judgeable_groundtruth_similarity
55487
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: My question is about two equations regarding uniform spheres that I've run into: $\quad V=\frac{GM}{r},$ and $\quad U = \frac{3}{5}\frac{GM^2}{r}.$ 1) On one hand, $V$ is unknown to me, and is described (in Solved Problems in Geophysics) as "the gravitational potential of a sphere of mass M." I also found it online called "the potential due to a uniform sphere." 2) On the other hand, $U$ is what I've seen before and I know it by the descriptions "sphere gravitational potential energy" or "gravitational binding energy." My understanding is that $U$ is the amount of energy required to build the sphere piece by piece from infinity. I also recognize $GMm/r$ as the gravitational potential between two masses. Can someone explain the difference between these concepts? How can $GM/r$ be the "gravitational potential of a sphere"? Isn't that what $U$ is? Now provide the response and nothing else.
There is a mistake in one of your formulas, $U=\frac{3 G M^2}{5 R}$ with $R$ equal to the sphere radius is the energy required to blow every tiny shred of the sphere apart so that its pieces no longer interact gravitationally, as you said, while $V$ as given above with $r$ equal to distance from the sphere center describes how the sphere interacts with other (celestial) bodies , i.e test particles moving in the sphere's gravitational field feel $V$. To elaborate: the gravitational field around a point mass and around an object that's spherically symmetric is the same outside of the object due to symmetry considerations, which is why $V$ agrees with the formula for the gravitational potential between 2 masses.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/55487', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/21374/']}
jdg_378552
stackexchange
llm_judgeable_groundtruth_similarity
275805
Below is a question asked on the forum meta.stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This is not an attempt to appeal the decisions of the community, I just want to become a better stackoverflower... I posted a question (Now edited, so no need to go looking for it) asking how to convert an NSString to an int. Within moments, it had several downvotes. quick Swift question: So, I have an app that needs to convert from NSString to an integer. Here's what I tried - var variable = (NSString(data:data, encoding:NSUTF8StringEncoding)) exampeStruct.otherVariable = (variable).toInt() I would expect it to set exampleStruct.otherVariable to an int value of the NSString, but it gives the error "NSString does not have a member toInt?" What is the proper way to convert nsstring to int? It was soon closed as off topic. I've looked through the How to Ask Questions thing in help center, and I can't seem to find what I missed... Search, and Research This was done. First, I tried it by guessing, then next I went to google. As you know, google displays result differently for everyone, but in case you need to check, there was no help while researching this way. Write a title that summarizes the specific problem "NSString to Integer" would seem to fit this rule... Introduce the problem before you post any code Yup! "...Convert from nsstring to integer..." Would seem to do that. Help others reproduce the problem I included the smallest amount of code necessary to reproduce the problem. Include all relevant tags ios xcode swift nsstring all seem to be relevant Proof-read before posting! Done! Not saying it was perfect, but it was proofread. Post the question and respond to feedback I interacted with the commentors... Look for help asking for help This is this post :D It was also closed for being a a problem that can no longer be reproduced or a simple typographical error It was a reproducible (I gave code!) debugging question. There was no typos in the code, as far as I am aware... As well as... "Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. It had a desired behavior/specific problem/problem statement "Convert from NSString to an integer". It had code that reproduced it. So, having tried in vain to figure out what I did wrong, any chance you can tell me? Thanks for your time, and apologies for probably a basic question. Again, I have no issues with what the community decided to do, I just want to learn. Now provide the response and nothing else.
Your question wasn't closed because it was basic (at least I hope not). It appears to have been closed incorrectly (at least for the reason given). It doesn't appear from the comments or the question itself that it is just a typographical error. If the question was closed because "No Research was done", that has never been a reason to close a question. It's a reason to downvote, but not close. As far as making your question more better, here are some things you could have done to help your question be better received: Spend time on the formatting of the question. As an example, your question looked like this: With just a few minutes, you could have made it look like this: How do I convert an NSString to an integer using Swift? I need to convert an NSString to an integer in Swift: Here's the current code I'm using; it doesn't work: var variable = (NSString(data:data, encoding:NSUTF8StringEncoding)) exampeStruct.otherVariable = (variable).intValue I expect it to set exampleStruct.otherVariable to an int value of the NSString , but I get the following error: "Cannot convert the expression's type () to type Float" How do I convert an NSString to int in Swift? Appearance matters. Your question had nothing wrong with it other than you didn't take the time to make it look good. That's important on Stack Overflow. It shows that you respect our time and you respect the fact that this question will be around for a while. Another tip is to make your question title what you'd search for if you were on Google. Would you search for "NsString to Integer"? Or would you search for "Converting NSString to Integer in Swift"? Your title isn't just for you, it's for the answerers and most importantly the people who have the problem following you.
{}
{'log_upvote_score': 6, 'links': ['https://meta.stackoverflow.com/questions/275805', 'https://meta.stackoverflow.com', 'https://meta.stackoverflow.com/users/3892545/']}
jdg_378553
stackexchange
llm_judgeable_groundtruth_similarity
32951256
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 file that contains data from a device, and I need to insert this data into a database. The text file looks like this: 10/01/15-20:37:30 = 40.2,25.4,42.3,54.3,70.0,66.610/01/15-20:38:26 = 67.3,18.4,30.6,39.3,70.0,66.610/01/15-20:39:21 = 74.5,16.8,28.2,36.0,70.0,66.610/01/15-20:40:16 = 76.8,16.6,27.6,35.2,70.0,66.610/01/15-20:41:12 = 78.1,16.4,27.3,34.9,70.0,66.6 And my code currently looks like this: <?php $servername = "localhost"; $username = "root"; $password = "pass"; $dbname = "dbase"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } ?><?PHP $file_handle = fopen("datalog.txt", "r"); while (!feof($file_handle) ) { $line_of_text = fgets($file_handle); $parts = explode(' ', $line_of_text); print $parts[0] . $parts[1]. "<BR>";}$datainsert = "INSERT INTO reading (val1, val2, val3, val4, val5, val6, val7, val8, val9, val10) VALUES ($parts[0])"; if (mysqli_query($conn, $datainsert)) { echo "New record created successfully";} else { echo "Error: " . $datainsert . "<br>" . mysqli_error($conn);}?><?php$conn->close();?> The error I get is this: Error: INSERT INTO reading (Box_ID, Time_Stamp, Temperature, Humidity, CO_Level, VOC_Reading_UOM, VOC_Reading_V1, VOC_Reading_V2, VOC_Reading_V3, VOC_Reading_V4) VALUES () Column count doesn't match value count at row 1 My database and site do connect without errors, and this page is the only one with problems. What is going wrong? Now provide the response and nothing else.
if (File.Exists(f)) { DoSomething(f) } (or the negation thereof) is an anti-pattern. The file can be deleted or created in between those two statements, so it makes little sense to check its existence like that. Apart from that, as pointed out in the comments, while File.Exists() may return true, the actual opening of the file can then still fail for a variety of reasons. So you'll have to repeat the error checking and throwing around the opening of the file. As you don't want to repeat yourself but instead keep your code DRY, just attempt to open the file and let new FileStream() throw. Then you can catch the exception, and if you wish, re-throw the original or throw an application-specific exception. Of course calling File.Exists() can be justified, but not in this pattern.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/32951256', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5410284/']}
jdg_378554
stackexchange
llm_judgeable_groundtruth_similarity
36374842
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using the express framework and would like to connect to a mongodb without using mongoose, but with the native nodejs Mongodb driver. How can I do this without creating a new connection every time? To handle get or post requests I currently open a new connection to the db for every request and close it on completion of the request. Is there a better way to do this? Thanks in advance. Now provide the response and nothing else.
Following the example from my comment, modifying it so that the app handles errors rather than failing to start the server. var express = require('express');var mongodb = require('mongodb');var app = express();var MongoClient = require('mongodb').MongoClient;var dbURL = "mongodb://localhost:27017/integration_test";var db;// Initialize connection onceMongoClient.connect(dbURL, function(err, database) { if(err) return console.error(err); db = database; // the Mongo driver recommends starting the server here // because most apps *should* fail to start if they have no DB. // If yours is the exception, move the server startup elsewhere. });// Reuse database object in request handlersapp.get("/", function(req, res, next) { var collection = "replicaset_mongo_client_collection"; db.collection(collection).find({}, function(err, docs) { if(err) return next(err); docs.each(function(err, doc) { if(doc) { console.log(doc); } else { res.end(); } }); });});app.use(function(err, req, res){ // handle error here. For example, logging and // returning a friendly error page});// Starting the app here will work, but some users // will get errors if the db connection process is slow. app.listen(3000);console.log("Listening on port 3000");
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36374842', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3978887/']}
jdg_378555
stackexchange
llm_judgeable_groundtruth_similarity
71354
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm attempting to start a service that our company created. In one particular environment, it's failing to start on three "permission denied" errors. I'm not sure which files it is failing on, so I would like to log all permissions-related errors while I attempt to start the daemon. I've found auditd , but I've been unable to place a watch on the whole disk for specifically permissions-related errors. What is the best way to audit all permissions-related errors? Now provide the response and nothing else.
You could use strace to view all filesystem activity of the processes related to the daemon, and see which ones fail when the permission denied errors appear. If the error comes from a shell script that starts the service, you can run sh -x /path/to/startup/script (or bash -x /path/to/startup/script if the script begins with #!/bin/bash ) and the shell will print each line as it executes it.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/71354', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/17107/']}
jdg_378556
stackexchange
llm_judgeable_groundtruth_similarity
138666
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I recently started learning about buffer overflows and how they work. Someone shared a binary to practice on (in a vm, don't worry). I've been feeding strings to the socket that the binary opens, and I noticed that at a certain length, the string will cause the program to not respond with the message it is supposed to. Also, if I feed another string of certain lengths, parts of the message are sent back through the socket from the server, but the other parts just print to console on the server end. I'm not entirely sure what caused this (this isn't the official question for this post, but I'd love to hear an answer in the comments). And that brings me to my question: Are there any applications that can generate an image of the stack or dump it and generally what's written to it? I think it'd be really helpful for seeing what is happening when I feed the socket strings of different lengths. I'd love it if the size of each 'section' of the stack (don't know what it's called) were represented in the image with a size relative to the other sections (so, I can visualize the size of the stack), or in a readable way. Something like this would be great if your answer is about generating the image, except it would be nice if it showed how much is written to it (that way I can see when it is overflowing)... I'd probably generate an image when I start the program, and after I feed the socket the huge values. Then I'd compare. If there are any other ways / better ways of learning, I'd love to hear them. Edit #1: I'm black-box testing. Edit #2: While there already is anaccepted answer to this question, I would appreciate other answerstoo. The more information, and responses, the more I will be able tolearn. Thus, I will reward new answers (if deserved) with bounties. Appreciate it! Now provide the response and nothing else.
Getting a dump of memory the simple way You can simply send your vulnerable process a SIGSEGV (kill -SEGV pid) and, if coredump is allowed (ulimit -c unlimited), you gonna get a nice core dump file with all your memory in it. Example: On terminal #1: /tmp$ ./test idling...idling...Segmentation fault <---- HERE I SEND THE 1st SIGSEGV/tmp$ ulimit -c unlimited/tmp$ ./test idling...idling...Segmentation fault (core dumped) <---- HERE IS THE 2d SIGSEGV/tmp$ ls testtest test.c /tmp$ ls -lah core -rw------- 1 1000 1000 252K Oct 10 17:42 core On terminal #2 /tmp$ ps aux|grep test1000 6529 0.0 0.0 4080 644 pts/1 S+ 17:42 0:00 ./test1000 6538 0.0 0.0 12732 2108 pts/2 S+ 17:42 0:00 grep test/tmp$ kill -SEGV 6529/tmp$ ps aux|grep test1000 6539 0.0 0.0 4080 648 pts/1 S+ 17:42 0:00 ./test1000 6542 0.0 0.0 12732 2224 pts/2 S+ 17:42 0:00 grep test/tmp$ kill -SEGV 6539 Please note that this will give you a dump of your state at the moment the binary got the SIGSEGV.So, if your binary consists of main() and evil_function() and, while receiving SIGSEV, your program was running evil_function(), you gonna get the stack of evil_function(). But you may also inspect around to get back to main() stack. Good pointer about all that is Aleph One paper: http://insecure.org/stf/smashstack.html Guessing the "mapping" by yourself If we imagine that your binary is implementing a basic buffer overflow, like in this code snippet: #include <stdio.h>#include <stdlib.h>#include <string.h>int evil_function(char *evil_input){ char stack_buffer[10]; strcpy(stack_buffer, evil_input); printf("input is: %s\n", stack_buffer); return 0;}int main (int ac, char **av){ if (ac != 2) { printf("Wrong parameter count.\nUsage: %s: <string>\n",av[0]); return EXIT_FAILURE; } evil_function(av[1]); return (EXIT_SUCCESS);} It's quite simple to guess where you should write your buffer address just by using gdb.Let's have a try with the above example program: /tmp/bo-test$ ./test-buffer-overflow $(perl -e "print 'A'x10")input is: AAAAAAAAAA/tmp/bo-test$ ./test-buffer-overflow $(perl -e "print 'A'x11")input is: AAAAAAAAAAA/tmp/bo-test$ ./test-buffer-overflow $(perl -e "print 'A'x12")input is: AAAAAAAAAAAA/tmp/bo-test$ ./test-buffer-overflow $(perl -e "print 'A'x13")input is: AAAAAAAAAAAAA/tmp/bo-test$ ./test-buffer-overflow $(perl -e "print 'A'x14")input is: AAAAAAAAAAAAAA/tmp/bo-test$ ./test-buffer-overflow $(perl -e "print 'A'x15")input is: AAAAAAAAAAAAAAA/tmp/bo-test$ ./test-buffer-overflow $(perl -e "print 'A'x16")input is: AAAAAAAAAAAAAAAASegmentation fault (core dumped) Ok, so the stack begin being fucked up after giving 6 extra chars...Let's have a look to the stack: /tmp/bo-test$ gdb test-buffer-overflow coreGNU gdb (Debian 7.7.1+dfsg-5) 7.7.1[...]Core was generated by `./test-buffer-overflow AAAAAAAAAAAAAAAA'.Program terminated with signal SIGSEGV, Segmentation fault.#0 0x00007f2cb2c46508 in ?? () from /lib/x86_64-linux-gnu/libc.so.6(gdb) bt#0 0x00007f2cb2c46508 in ?? () from /lib/x86_64-linux-gnu/libc.so.6#1 0x0000000000000000 in ?? ()(gdb) Quit Let's continue with feeding it more extra char: /tmp/bo-test$ ./test-buffer-overflow $(perl -e "print 'A'x26")input is: AAAAAAAAAAAAAAAAAAAAAAAAAASegmentation fault (core dumped)/tmp/bo-test$ gdb test-buffer-overflow coreGNU gdb (Debian 7.7.1+dfsg-5) 7.7.1[...]Core was generated by `./test-buffer-overflow AAAAAAAAAAAAAAAAAAAAAAAAAA'.Program terminated with signal SIGSEGV, Segmentation fault.#0 0x0000000000004141 in ?? ()(gdb) Hey ... look at this adress: 0x0000000000004141 ! 0x41 is hex ascii code for ... 'A' :pWe just rewrote the RET adress :)Now, last attempt, just to see: /tmp/bo-test$ ./test-buffer-overflow AAAAAAAAAAAAAAAAAAAAAAAAABCDEFGHIinput is: AAAAAAAAAAAAAAAAAAAAAAAAABCDEFGHISegmentation fault (core dumped)/tmp/bo-test$ gdb test-buffer-overflow core GNU gdb Core was generated by `./test-buffer-overflow AAAAAAAAAAAAAAAAAAAAAAAAABCDEFGHI'.Program terminated with signal SIGSEGV, Segmentation fault.#0 0x0000000000400581 in evil_function ( evil_input=0x7fff7e2712a6 'A' <repeats 25 times>, "BCDEFGHI") at test-buffer-overflow.c:1212 }(gdb) bt#0 0x0000000000400581 in evil_function ( evil_input=0x7fff7e2712a6 'A' <repeats 25 times>, "BCDEFGHI") at test-buffer-overflow.c:12#1 0x4847464544434241 in ?? ()#2 0x00007fff7e260049 in ?? ()#3 0x0000000200000000 in ?? ()#4 0x0000000000000000 in ?? () This time, look at the address again: 0x4847464544434241 ... Now you know exactly where to write ...
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/138666', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/107521/']}
jdg_378557
stackexchange
llm_judgeable_groundtruth_similarity
44515668
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 detect if the user add new fingerprint to Android settings after he/she authenticate finger inside my application ? i.e. iOS have something called (evaluatedPolicyDomainState) to detect changes in fingerprint catalog what is the alternative in Android ? This require for security reasons to prompt password in this case Now provide the response and nothing else.
From the documentation for setUserAuthenticationRequired : The key will become irreversibly invalidated once the secure lock screen is disabled (reconfigured to None, Swipe or other mode which does not authenticate the user) or when the secure lock screen is forcibly reset (e.g., by a Device Administrator). Additionally, if the key requires that user authentication takes place for every use of the key, it is also irreversibly invalidated once a new fingerprint is enrolled or once no more fingerprints are enrolled, unless setInvalidatedByBiometricEnrollment(boolean) is used to allow validity after enrollment. Attempts to initialize cryptographic operations using such keys will throw KeyPermanentlyInvalidatedException. So to check if any new fingerprints have been enrolled since you created your fingerprint-associated key, just create a cipher with that key and try to init the cipher. If any new fingerprints have been enrolled, the init call should trigger a KeyPermanentlyInvalidatedException .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44515668', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8153212/']}
jdg_378558
stackexchange
llm_judgeable_groundtruth_similarity
24111813
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 have a react component flip over when a user clicks on the DOM element. I see some documentation about their animation mixin but it looks to be set up for "enter" and "leave" events. What is the best way to do this in response to some user input and be notified when the animation starts and completes? Currently I have a list item and I want it to flip over an show a few buttons like delete, edit, save. Perhaps I missed something in the docs. animation mixin http://facebook.github.io/react/docs/animation.html Now provide the response and nothing else.
Upon clicks you can update the state, add a class and record the animationend event. class ClickMe extends React.Component { constructor(props) { super(props) this.state = { fade: false } } render() { const fade = this.state.fade return ( <button ref='button' onClick={() => this.setState({ fade: true })} onAnimationEnd={() => this.setState({ fade: false })} className={fade ? 'fade' : ''}> Click me! </button> ) }} See the plnkr: https://next.plnkr.co/edit/gbt0W4SQhnZILlmQ?open=Hello.js&deferRun=1&preview Edit : Updated to reflect current React, which supports animationend events.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/24111813', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/83080/']}
jdg_378559
stackexchange
llm_judgeable_groundtruth_similarity
10770585
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: assume that class Dog extends class Animal:why this polymorphic statement is not allowed: List<Animal> myList = new ArrayList<Dog>(); However, it's allowed with plain arrays: Animal[] x=new Dog[3]; Now provide the response and nothing else.
The reasons for this are based on how Java implements generics. An Arrays Example With arrays you can do this (arrays are covariant as others have explained) Integer[] myInts = {1,2,3,4};Number[] myNumber = myInts; But, what would happen if you try to do this? Number[0] = 3.14; //attempt of heap pollution This last line would compile just fine, but if you run this code, you could get an ArrayStoreException . Because you’re trying to put a double into an integer array (regardless of being accessed through a number reference). This means that you can fool the compiler, but you cannot fool the runtime type system. And this is so because arrays are what we call reifiable types . This means that at runtime Java knows that this array was actually instantiated as an array of integers which simply happens to be accessed through a reference of type Number[] . So, as you can see, one thing is the actual type of the object, an another thing is the type of the reference that you use to access it, right? The Problem with Java Generics Now, the problem with Java generic types is that the type information is discarded by the compiler and it is not available at run time. This process is called type erasure . There are good reason for implementing generics like this in Java, but that's a long story, and it has to do with binary compatibility with pre-existing code. But the important point here is that since, at runtime there is no type information, there is no way to ensure that we are not committing heap pollution. For instance, List<Integer> myInts = new ArrayList<Integer>();myInts.add(1);myInts.add(2);List<Number> myNums = myInts; //compiler errormyNums.add(3.14); //heap polution If the Java compiler does not stop you from doing this, the runtime type system cannot stop you either, because there is no way, at runtime, to determine that this list was supposed to be a list of integers only. The Java runtime would let you put whatever you want into this list, when it should only contain integers, because when it was created, it was declared as a list of integers. As such, the designers of Java made sure that you cannot fool the compiler. If you cannot fool the compiler (as we can do with arrays) you cannot fool the runtime type system either. As such, we say that generic types are non-reifiable . Evidently, this would hamper polymorphism. Consider the following example: static long sum(Number[] numbers) { long summation = 0; for(Number number : numbers) { summation += number.longValue(); } return summation;} Now you could use it like this: Integer[] myInts = {1,2,3,4,5};Long[] myLongs = {1L, 2L, 3L, 4L, 5L};Double[] myDoubles = {1.0, 2.0, 3.0, 4.0, 5.0};System.out.println(sum(myInts));System.out.println(sum(myLongs));System.out.println(sum(myDoubles)); But if you attempt to implement the same code with generic collections, you will not succeed: static long sum(List<Number> numbers) { long summation = 0; for(Number number : numbers) { summation += number.longValue(); } return summation;} You would get compiler erros if you try to... List<Integer> myInts = asList(1,2,3,4,5);List<Long> myLongs = asList(1L, 2L, 3L, 4L, 5L);List<Double> myDoubles = asList(1.0, 2.0, 3.0, 4.0, 5.0);System.out.println(sum(myInts)); //compiler errorSystem.out.println(sum(myLongs)); //compiler errorSystem.out.println(sum(myDoubles)); //compiler error The solution is to learn to use two powerful features of Java generics known as covariance and contravariance. Covariance With covariance you can read items from a structure, but you cannot write anything into it. All these are valid declarations. List<? extends Number> myNums = new ArrayList<Integer>();List<? extends Number> myNums = new ArrayList<Float>()List<? extends Number> myNums = new ArrayList<Double>() And you can read from myNums : Number n = myNums.get(0); Because you can be sure that whatever the actual list contains, it can be upcasted to a Number (after all anything that extends Number is a Number, right?) However, you are not allowed to put anything into a covariant structure. myNumst.add(45L); //compiler error This would not be allowed, because Java cannot guarantee what is the actual type of the object in the generic structure. It can be anything that extends Number, but the compiler cannot be sure. So you can read, but not write. Contravariance With contravariance you can do the opposite. You can put things into a generic structure, but you cannot read out from it. List<Object> myObjs = new List<Object();myObjs.add("Luke");myObjs.add("Obi-wan");List<? super Number> myNums = myObjs;myNums.add(10);myNums.add(3.14); In this case, the actual nature of the object is a List of Objects, and through contravariance, you can put Numbers into it, basically because all numbers have Object as their common ancestor. As such, all Numbers are objects, and therefore this is valid. However, you cannot safely read anything from this contravariant structure assuming that you will get a number. Number myNum = myNums.get(0); //compiler-error As you can see, if the compiler allowed you to write this line, you would get a ClassCastException at runtime. Get/Put Principle As such, use covariance when you only intend to take generic values out of a structure, use contravariance when you only intend to put generic values into a structure and use the exact generic type when you intend to do both. The best example I have is the following that copies any kind of numbers from one list into another list. It only gets items from the source, and it only puts items in the destiny. public static void copy(List<? extends Number> source, List<? super Number> destiny) { for(Number number : source) { destiny.add(number); }} Thanks to the powers of covariance and contravariance this works for a case like this: List<Integer> myInts = asList(1,2,3,4);List<Double> myDoubles = asList(3.14, 6.28);List<Object> myObjs = new ArrayList<Object>();copy(myInts, myObjs);copy(myDoubles, myObjs);
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10770585', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/813159/']}
jdg_378560
stackexchange
llm_judgeable_groundtruth_similarity
450233
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So I have a generic list, and an oldIndex and a newIndex value. I want to move the item at oldIndex , to newIndex ...as simply as possible. Any suggestions? Note The item should be end up between the items at (newIndex - 1) and newIndex before it was removed. Now provide the response and nothing else.
I know you said "generic list" but you didn't specify that you needed to use the List(T) class so here is a shot at something different. The ObservableCollection(T) class has a Move method that does exactly what you want. public void Move(int oldIndex, int newIndex) Underneath it is basically implemented like this. T item = base[oldIndex];base.RemoveItem(oldIndex);base.InsertItem(newIndex, item); So as you can see the swap method that others have suggested is essentially what the ObservableCollection does in it's own Move method. UPDATE 2015-12-30: You can see the source code for the Move and MoveItem methods in corefx now for yourself without using Reflector/ILSpy since .NET is open source.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/450233', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/39709/']}
jdg_378561
stackexchange
llm_judgeable_groundtruth_similarity
27038051
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 encounter a problem by picking images from gallery with android 5.0. My code for starting intent is: private void takePictureFromGallery() { Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI); startActivityForResult(intent, PICK_FROM_FILE);} and here is function called in onActivityResult() method for request code PICK_FROM_FILE private void handleGalleryResult(Intent data) { Uri selectedImage = data.getData(); String[] filePathColumn = { MediaStore.Images.Media.DATA }; Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); // field declaration private String mTmpGalleryPicturePath; mTmpGalleryPicturePath = cursor.getString(columnIndex); cursor.close(); // at this point mTmpGalleryPicturePath is null ...} For previous versions than 5.0 this code always work, using com.android.gallery application. Google Photos is default gallery application on Android 5.0. Could be this problem depends by application or is an issue of new android OS distribution? EDIT I understand the problem: Google Photos automatically browse content of its backupped images on cloud server. In fact trying pratice suggest by @maveň if i turn off each internet connections and after choose an image, it doesn't get result by decoding Bitmap from InputStream. So at this point question become: is there a way in android 5.0 to handle the Intent.ACTION_PICK action so that system browse choose in local device image gallery? Now provide the response and nothing else.
I found solution to this problem combining following methods.Here to start activity for pick an image from gallery of device: private void takePictureFromGallery() { startActivityForResult( Intent.createChooser( new Intent(Intent.ACTION_GET_CONTENT) .setType("image/*"), "Choose an image"), PICK_FROM_FILE);} Here to handle result of intent, as described in this post , note that getPath() function works differently since android build version: private void handleGalleryResult(Intent data) { Uri selectedImage = data.getData(); mTmpGalleryPicturePath = getPath(selectedImage); if(mTmpGalleryPicturePath!=null) ImageUtils.setPictureOnScreen(mTmpGalleryPicturePath, mImageView); else { try { InputStream is = getContentResolver().openInputStream(selectedImage); mImageView.setImageBitmap(BitmapFactory.decodeStream(is)); mTmpGalleryPicturePath = selectedImage.getPath(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}@SuppressLint("NewApi")private String getPath(Uri uri) { if( uri == null ) { return null; } String[] projection = { MediaStore.Images.Media.DATA }; Cursor cursor; if(Build.VERSION.SDK_INT >19) { // Will return "image:x*" String wholeID = DocumentsContract.getDocumentId(uri); // Split at colon, use second item in the array String id = wholeID.split(":")[1]; // where id is equal to String sel = MediaStore.Images.Media._ID + "=?"; cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, sel, new String[]{ id }, null); } else { cursor = getContentResolver().query(uri, projection, null, null, null); } String path = null; try { int column_index = cursor .getColumnIndex(MediaStore.Images.Media.DATA); cursor.moveToFirst(); path = cursor.getString(column_index).toString(); cursor.close(); } catch(NullPointerException e) { } return path;} takePictureFromGallery() is invoked from onActivityResult Thats all!!
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27038051', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2401522/']}
jdg_378562
stackexchange
llm_judgeable_groundtruth_similarity
18891500
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 do POSIX and other standards say about the situation where multiple threads are doing poll() or select() calls on a single socket or pipe handle at the same time? If any data arrives, does only one of the waiting threads get woken up or do all of the waiting threads get woken up? Now provide the response and nothing else.
Interesting question ... I read through the current POSIX and did not find a specific answer, i.e., no specification about concurrent invocations. So I'll explain why I think the standard means all will wake up. The relevant part of the text for select / pselect is: Upon successful completion, the pselect() or select() function shall modify the objects pointed to by the readfds, writefds, and errorfds arguments to indicate which file descriptors are ready for reading, ready for writing, or have an error condition pending, respectively, [...] and later A descriptor shall be considered ready for reading when a call to an input function with O_NONBLOCK clear would not block, whether or not the function would transfer data successfully. (The function might return data, an end-of-file indication, or an error other than one indicating that it is blocked, and in each of these cases the descriptor shall be considered ready for reading.) In short (the reading case only), we can understand this as: select does not block this means that the next call to an input function with O_NONBLOCK would not return an error with errno==EWOULDBLOCK . [Note that the "next" is my interpretation of the above.] If one admits to this interpretation then two concurrent select calls could both return the same FD as readable. In fact even if they are not concurrent, but a first thread calls select with some FD being readable and later e.g., read , a second thread calling select between the two could return the FD as readable for the second thread. Now the relevant part for the "waking up" part of the question is this: If none of the selected descriptors are ready for the requested operation, the pselect() or select() function shall block until at least one of the requested operations becomes ready, until the timeout occurs, or until interrupted by a signal. Here clearly the above interpretation suggests that concurrently waiting calls will all return.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18891500', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/341065/']}
jdg_378563
stackexchange
llm_judgeable_groundtruth_similarity
64040286
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 Vue 2, you can access this.$root inside the created hook. In Vue 3, everything that would have gone inside the created hook now goes in setup() . In setup() we don't have access to this , so, how can we access anything on the root instance? Say, I set a property on the root instance: const app = createApp(App).mount('#app');app.$appName = 'Vue3'; I can access this from mounted() with this.$root.$appName , how can I do this in setup() ? UPDATE I can access it if I import it: import app from '@/main';...setup() { console.log(app.$appName) // Vue3 But, this is a hassle if I have to do this for every file. UPDATE 2 Another workaround is to use provide() inside App.vue and then inject() in any other components: setup() { provide('$appName', 'Vue3') setup() { inject('$appName') // Vue3 Now provide the response and nothing else.
It seems you need provide / inject . In your App.vue : import { provide } from 'vue';export default { setup() { provide('appName', 'vue3') }} Or provide it with your app : const app = createApp(App);app.mount('#app');app.provide('appName', 'Vue3'); And then in any child component where you want to access this variable, inject it: import { inject } from 'vue'export default { setup() { const appName = inject('appName'); }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/64040286', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12701949/']}
jdg_378564
stackexchange
llm_judgeable_groundtruth_similarity
32262182
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This is my Add query array for the table (tb_empgrocery) and this works case "Add": $itemno = $_POST['itemno']; $qty = $_POST['qty']; $unitprc = $_POST['unitprc']; $amt = $_POST['amt']; $coopmemid = $_SESSION['kiosk']['is_coopmemID_kiosk']; for($x=0; $x<count($itemno); $x++) { $Addquery = "INSERT INTO tb_empgrocery (coopmemID , date_ordered, item_no, qty_ordered, unit_price, amount) VALUES ('$coopmemid',(NOW()),'$itemno[$x]','$qty[$x]','$unitprc[$x]','$amt[$x]')"; mysql_query($Addquery, $con); }break; This is my Save query for the table (tb_empgroc_master) and this doesn't save any data into the table. This table has many columns but I only put data_ordered because it is set to timestamp and the other columns has no value yet. I'm trying to have at least one row data in a table which is the value of the date_ordered to be shown. case "Save": if(isset($_POST['Save'])){ $Savequery = "INSERT INTO tb_empgroc_master (date_ordered) VALUES ((NOW()))"; mysql_query($Savequery, $con); }break; This is the looping array function for the Add query function saveme(){var data = new Array();$('#cLoanOut2 > tbody > tr').each(function() { var nodes = $(this).children(); var itemno = nodes[0].innerHTML, qty = nodes[2].innerHTML, unitprc = nodes[3].innerHTML, amt = nodes[4].innerHTML; data.push({ name: "itemno[]", value: itemno },{ name: "qty[]", value: qty },{ name: "unitprc[]", value: unitprc },{ name: "amt[]", value: amt }); }); return data;} And this is my ajax request calling the 2 queries $('#OKBtn2').click(function(){ $('#myModal2').modal('hide'); var itemid = $('#main-form2 .active').attr('id'), qty = $('#main-form2 #'+itemid+' td:eq(2)').text(), unit_price = $('#main-form2 #'+itemid+' td:eq(3)').text(), amount = $('#main-form2 #'+itemid+' td:eq(4)').text(); bootbox.confirm("Are you sure?","No","Yes",function(r){ if(r) { var data = saveme(); data.push({ name: "todo", value: "Add" }); console.log(data); $.ajax({ url : url, type : "POST", async : false, data : data, --->//This calls the first query which is Add query and it push the data array and it works for the table (tb_empgrocery) todo: "Save", --->//Is this right to call the Save query? Because this doesn't work for the table (tb_empgroc_master) success:function(result){ bootbox.alert('Ordered',function(){ }); updateTable(); } }); } else { } });}); How can I call the 2nd query after that first one? Thanks in advance :)) Now provide the response and nothing else.
The method for finding strong reference cycles is the same in Swift as in Objective-C. You'd run the app from Xcode, exercise the app sufficiently to manifest the cycle, and then tap on the "debug memory graph" button ( ). You can then select an unreleased object in the panel on the left, and it will show you the memory graph, often which can clearly illustrate the strong reference cycles: Sometimes the memory cycles are not as obvious as that, but you can at least see what object is keeping a strong reference to the object in question. If necessary, you can then track backward and identify what's keeping a strong reference to that, and so on. Sometimes knowing what sort of object is keeping the strong reference is insufficient, and you really want to know where in your code that strong reference was established. The "malloc stack" option, as shown in https://stackoverflow.com/a/30993476/1271826 , can be used to identify what the call stack was when this strong reference was established (often letting you identify the precise line of code where these strong references were established). For more information, see WWDC 2016 video Visual Debugging with Xcode . You can also use Instruments to identify leaked object. Just run the app through Instruments with the Allocations tool, repeatedly (not just once or twice) returning the app back to some steady-state condition, and if memory continues to go up, then you likely have a strong reference cycle. You can use the Allocations tool to identify what type of objects are not being released, use "record reference count" feature to determine precisely where these strong references were established, etc. See WWDC 2013 video Fixing Memory Issues and WWDC 2012 video iOS App Performance: Memory for introductions to identifying and resolving memory issues. The basic techniques proposed there are still applicable today (though the UI of Instruments tools has changed a bit ... if you want an introduction to the slightly changed UI, see WWDC 2014 video Improving Your App with Instruments ). As an aside, "garbage collection" refers to a very different memory system and isn't applicable here.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/32262182', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5241619/']}
jdg_378565
stackexchange
llm_judgeable_groundtruth_similarity
589573
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: From this paper https://aclanthology.org/D19-1006.pdf "How Contextual are Contextualized Word Representations? Comparing the Geometry of BERT, ELMo, and GPT-2 Embeddings" When they say word vectors are anisotropic, do they mean all embeddings for words in the vocabulary are distributed in this cone shape in semantic space, and so there is a cosine similarity of 0.99 often between two different words from two different context? So a cosine similarity between the same word of two different contexts of 0.99 is not special? If so, isn't it a problem that if there is a large semantic space, the vectors for the whole vocabulary are clustering to a region of the space? Now provide the response and nothing else.
It seems that the authors are writing about all words in the vocabulary. From the paper: In all layers of all three models, the contextualized word representations of all wordsare not isotropic: they are not uniformly distributed with respect to direction. Instead,they are anisotropic, occupying a narrowcone in the vector space. The anisotropy inGPT-2’s last layer is so extreme that two random words will on average have almost perfect cosine similarity! Anisotropy might be a problem; takings steps to improve isotropy has been found to improve models. From the paper: Our findings offer some new directions for futurework. For one, as noted earlier in the paper, Muet al. (2018) found that making static embeddingsmore isotropic – by subtracting their mean fromeach embedding – leads to surprisingly large improvements in performance on downstream tasks.Given that isotropy has benefits for static embeddings, it may also have benefits for contextualized word representations, although the latter havealready yielded significant improvements despitebeing highly anisotropic. Therefore, adding ananisotropy penalty to the language modelling objective – to encourage the contextualized representations to be more isotropic – may yield even betterresults.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/589573', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/224122/']}
jdg_378566
stackexchange
llm_judgeable_groundtruth_similarity
24584165
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So I want to echo the users' "username" on their profile. It's not working when I user this piece of code. why? Help please i echo'ed this on my page <?php echo "<td>" . $row['username'] . "</td>";?> but didn't work <?phpif (!session_id()) session_start();if (!$_SESSION['logon']){ header("Location:login.php"); die();}$con = mysql_connect("localhost","root","");if (!$con) { die('Could not connect: ' . mysql_error()); }mysql_select_db("test", $con);$result = mysql_query("SELECT * FROM `users` where username='$username'");while($row = mysql_fetch_array($result))$username = $row['username'];?> Now provide the response and nothing else.
Your declaration structure is so clever it's a shame it doesn't work. But EnumSet apparently needs the enum to be fully initialized first. It tries to fetch the array of constants from the enum so that, among other things, it knows how much space is needed for its internal bitset. Here's one workaround. It uses a helper method that creates an ordinary set ( HashSet ) first, and then, in a static initialization block, it iterates the enum constants and replaces all the sets with EnumSet s. public enum BuildingTechTree { // Named constants //Name SoftName Requirements NONE ("NULL", null), BARRACKS ("Barracks", setOf(NONE)), WALLS_SANDBAGS ("Sandbag wall", setOf(NONE)), POWERPLANT ("Power plant", setOf(BARRACKS)), GUARDTOWER ("Guard Tower", setOf(BARRACKS)); private final String softName; private Set<BuildingTechTree> requirements; private BuildingTechTree(String softName, Set<BuildingTechTree> requirements) { this.softName = softName; this.requirements = requirements; } private static Set<BuildingTechTree> setOf(BuildingTechTree... values) { return new HashSet<>(Arrays.asList(values)); } static { for (BuildingTechTree v : values()) { if (v.requirements == null) { v.requirements = EnumSet.noneOf(BuildingTechTree.class); } else { v.requirements = EnumSet.copyOf(v.requirements); } } }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24584165', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3806765/']}
jdg_378567
stackexchange
llm_judgeable_groundtruth_similarity
51859038
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have created an Angular Component Library, which I distribute via NPM (over Nexus) to several similar projects. This contains a PageComponent , which in turn contains a FooterComponent and a NavbarComponent . In NavbarComponent exists a button, which triggers a logout function. This function is to be provided via a PageService of the respective project. For this purpose I created an AbstractPageService in the Angular Component library ( PageService extends AbstractPageService ). At first I solved this via the EventEmitter . But since I had to provide a logout function for each new page, I wanted to solve this via one service per project. I pass the PageService (Project) with using the forRoot() method of Angular Component Library. Everything works as desired, but wanted to know if there is a better solution or if the solution is so recommendable at all? I have the following solution for this: Components Lib - components.module.ts import {ModuleWithProviders, NgModule} from '@angular/core';import {CommonModule} from '@angular/common';import {RouterModule} from '@angular/router';import {FontAwesomeModule} from '@fortawesome/angular-fontawesome';import {NavbarComponent} from './layout/navbar/navbar.component';import {PageComponent} from './layout/page/page.component';import {PageHeaderComponent} from './components/page-header/page-header.component';// ... others ...@NgModule({ imports: [ CommonModule, RouterModule, FontAwesomeModule ], declarations: [ NavbarComponent, PageComponent, // ... others ... ], exports: [ NavbarComponent, PageComponent, // ... others ... ]})export class ComponentsModule { static forRoot(pageService): ModuleWithProviders { return { ngModule: ComponentsModule, providers: [ {provide: 'PageService', useClass: pageService} ] }; }} Component Lib - page.component.ts import {Component, EventEmitter, HostBinding, Inject, Input, Output} from '@angular/core';import {AbstractPageService} from '../../services/abstract-page.service';@Component({ selector: 'dc-page', templateUrl: './page.component.html', styleUrls: ['./page.component.scss']})export class PageComponent { @HostBinding('class') styleClass = 'd-flex flex-column'; @Input() customStyleClass = null; @Input() showLogoutButton = true; // @Output() logoutButtonClick: EventEmitter<any> = new EventEmitter(); constructor(@Inject('PageService') protected pageService: AbstractPageService) { } logout(): void { this.pageService.logout(); }} Component Lib - abstract-page.service.ts import {Injectable} from '@angular/core';@Injectable()export abstract class AbstractPageService { abstract logout(): void;} And here the use in a project: Project - app.module.ts import {BrowserModule} from '@angular/platform-browser';import {NgModule} from '@angular/core';import {AppComponent} from './app.component';import {RouterModule, Routes} from '@angular/router';import {FontAwesomeModule} from '@fortawesome/angular-fontawesome';import {ComponentsModule} from 'components';const appRoutes: Routes = [ {path: '', component: AppComponent}, // otherwise redirect to home {path: '**', redirectTo: ''}];@NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, FormsModule, FontAwesomeModule, RouterModule.forRoot(appRoutes), ComponentsModule.forRoot(PageService), ], providers: [ // {provide: 'PageService', useClass: PageService} ], bootstrap: [AppComponent]})export class AppModule {} Project - page.service.ts import {Injectable} from '@angular/core';import {AbstractPageService} from '../../../projects/components/src/lib/services/abstract-page.service';@Injectable({ providedIn: 'root'})export class PageService extends AbstractPageService { constructor() { super(); } logout() { console.log('Ausloggen!'); }} Now provide the response and nothing else.
I used this approach but ran into one problem: The PageService is not the same singleton instance in the library as in the application. Because it is provided in multiple modules (application module and the library module), it creates a new instance for each module. What I ended up doing was providing my service through a string in the application module: // app.module.ts in the root applicationproviders: [ { provide: 'PageService', useClass: PageService }] Then injecting the service where needed using @Inject() // anywhere in the root application where the service is neededconstructor(@Inject('PageService') private pageService: PageService) {} Then, in the library , I created a simple interface: export interface AbstractPageService { logout(): void;} Then, I can simply inject the service in the library through the Inject() decorator and type it using the interface (without the need to implement the interface in the root application): // anywhere in the library where the service is neededconstructor(@Inject('PageService') private pageService: AbstractPageService) {} Now both the root application and the library use the same singleton instance of the PageService , as provided in the root application.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/51859038', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8581092/']}
jdg_378568
stackexchange
llm_judgeable_groundtruth_similarity
17176871
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 re-write one of our old Servers using ZeroMQ, for now I have the following Server setup, (which works for Zmq requests): using (var context = ZmqContext.Create()) using (var server = context.CreateSocket(SocketType.REP)) { server.Bind("tcp://x.x.x.x:5705"); while (true) { ... } This kind of setup works fine if I use the Zmq client library to connect context.CreateSocket(SocketType.REQ) But unfortunately we've got a lot of legacy code that needs to connect to this server and the sockets are created using .net socket libs: Socket = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); Socket.Connect(ipAddress, port); Is there a way to write a ZeroMQ Server to accept these traditional .net socket connections? Now provide the response and nothing else.
You can achieve this using ZMQ_STREAM sockets . Please note that since zeroMQ 4.x, the RAW router option has been deprecated for a new ZMQ_STREAM socket type, that works the same way as ROUTER + RAW. It seems it is bound to evolve, though. I recently tried ZMQ_STREAM sockets in version 4.0.1. You can open one, use zmq_rcv until you receive the whole message (you have to check it is whole yourself), or zmq_msg_rcv to let ZeroMQ handle it. You will receive an identifier message part, just like the identifier you would find in ROUTER sockets, directly followed by one ONLY body part. There is no empty delimiter between them like there would be using a REQ Socket talking to a ROUTER Socket. So if you route them, be sure to add it yourself. Beware though: if there is latency on the other end or if your message exceeds ZeroMQ ZMQ_STREAM buffers (mine are 8192 bytes long), your message can be interpreted by zeroMQ as a series of messages. In that case, you will receive as many different ZeroMQ messages including both the identifier part and the body part, and it is your job to aggregate them, knowing that if several clients are talking to the STREAM socket, they might get mixed up. I personnally use a hash table using the binary identifier as a key, and delete the entry from the table when I know the message is complete and sent to the next node. Sending through a ZMQ_STREAM with zmq_msg_send or zmq_send works fine as is.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17176871', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16642/']}
jdg_378569
stackexchange
llm_judgeable_groundtruth_similarity
1198898
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I can't figure it out how to solve this problem: Find the Laurent Series of the function $$f(z)=\frac{1}{(z^2+1)^2}$$ valid in $A=\{z \in \mathbb{C} : 0 < |z-i|<2\}$ I think that it is impossible because we have the $-i$ singularity that restrict $A$. Now provide the response and nothing else.
Hint: Your function can be written as: $f(z)=\displaystyle\frac{1}{(z-i)^2}\displaystyle\frac{1}{(z+i)^2}$. The factor $g(z)=\displaystyle\frac{1}{(z+i)^2}=-\left(\displaystyle\frac{1}{z+i}\right)'$.Now you have to compute the power series expansion of the function$\displaystyle\frac{1}{z+i}=\displaystyle\frac{1}{z-i+2i}=\displaystyle\frac{1}{2i}\frac{1}{1+\frac{z-i}{2i}}$ in the form $\sum_{n=0}^\infty a_n (z-i)^n$, and mention where this expansion is valid. Then you differentiate the series term by term, and change the sign.Finally you multiply with the first factor of $f$, $\displaystyle\frac{1}{(z-i)^2}$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1198898', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/209790/']}
jdg_378570
stackexchange
llm_judgeable_groundtruth_similarity
60154
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: Suppose a charged capacitor (parallel plates), the negative and positive charges on two plates attract each other. Which force cause the negative charge carriers (electrons) move through the circuit to the other plate if we connect two plates (from outer sides) with a wire? Now provide the response and nothing else.
Every system likes to decrease its electrostatic energy. The charges on the plates are almost in stable equilibrium. The charges on the opposite plates attract them, and the charges on the same plate repel them with almost the same force. However, a capacitor has fringe fields: These may be negligible when calculating the field inside a capacitor, but they are extremely important when there are wires in play -- by $\vec J=\sigma\vec E$, for a wire (which has high $\sigma$), even a small $\vec E$ can create a large current. And these create the tiny perturbation required to push the charges out of their almost-stable equilibrium. Note that redistribution of surface charges occurs on the wires as well, so it's not just the fringe fields pushing the electrons.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/60154', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/21108/']}
jdg_378571
stackexchange
llm_judgeable_groundtruth_similarity
51064821
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 question about calculating response times with Prometheus summary metrics. I created a summary metric that does not only contain the service name but also the complete path and the http-method. Now I try to calculate the average response time for the complete service.I read the article about "rate then sum" and either I do not understand how the calculation is done or the calculation is IMHO not correct. As far as I read this should be the correct way to calculate the response time per second: sum by(service_id) ( rate(request_duration_sum{status_code=~"2.*"}[5m]) / rate(request_duration_count{status_code=~"2.*"}[5m])) What I understand here is create the "duration per second" (rate sum / rate count) value for each subset and then creates the sum per service_id. This looks absolutely wrong for me - but I think it does not work in the way I understand it. Another way to get an equal looking result is this: sum without (path,host) ( rate(request_duration_sum{status_code=~"2.*"}[5m]) / rate(request_duration_count{status_code=~"2.*"}[5m])) But what is the difference? What is really happening here? And why do I honestly only get measurable values if I use "max" instead of "sum"? If I would ignore everything I read I would try it in the following way: rate(sum by(service_id) request_duration_sum{status_code=~"2.*"}[5m])/rate(sum by(service_id) request_duration_count{status_code=~"2.*"}[5m]) But this will not work at all... (instant vector vs range vector and so on...). Now provide the response and nothing else.
All of these examples are aggregating incorrectly, as you're averaging an average. You want: sum without (path,host) ( rate(request_duration_sum{status_code=~"2.*"}[5m]) )/ sum without (path,host) ( rate(request_duration_count{status_code=~"2.*"}[5m]) ) Which will return the average latency per status_code plus any other remaining labels.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51064821', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1240018/']}
jdg_378572
stackexchange
llm_judgeable_groundtruth_similarity
4253990
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In a survey, people were asked if they owned a goat or a camel. One person in fifteen said they had a goat. One person in eighteen said they had a camel and a tenth of the people had one animal or the other but not both. What proportion of the people owned neither kind of animal? Proportion of people who had a goat = 1/15 Proportion of people who had a camel = 1/18 Proportion of people who had one animal or the other = 1/10 Proportion of people who owned neither kind of animal = 1 - 1/15 - 1/18 - 1/10 = 7/9 I'm told however that the answer is actually, 8/9. Any ideas on where my understanding is breaking down? Now provide the response and nothing else.
Say $90$ people were surveyed (LCM of $18, 15$ and $10$ ). So going by the ratios given, $6$ of them have goats ( $G$ ), $5$ of them have camels ( $C$ ) and $9$ of them have one of the animals but not both. So, $|G| = 6, |C| = 5$ Please note that both the sets $G$ and $C$ also include people who have both animals. So, $(|G| - |G \cap C|) + (|C| - |G \cap C|) = 9$ $\implies |G \cap C| = 1$ So, $|G \cup C| = |G| + |C| - |G \cap C| = 10$ So out of $90$ people, $80$ of them have no animals, which is indeed $8/9$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4253990', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/866990/']}
jdg_378573
stackexchange
llm_judgeable_groundtruth_similarity
30597
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 reading Brian Greene's "Hidden Reality" and came to the part about Hawking Radiation. Quantum jitters that occur near the event horizon of a black hole, which create both positive-energy particles and negative-energy particles, produce the so-called Hawking radiation. However, I do not understand why only the negative-energy particles are being absorbed into the black hole, while the positive-energy particles shoot outward. Shouldn't there be 50/50 chance that each type of particle is being absorbed by the black hole? Also, the book mentions that a negative-energy particle would appear to an observer inside the black hole as positive. Why? Now provide the response and nothing else.
There are two ways to approach your question. The first is to explain what Brian Greene means, and the second is to point out that the "particles being swallowed" explanation is a metaphor and isn't actually how the calculation is done. I'll attempt both, but I'm outside my comfort zone so if others can expand or correct what follows please jump in! When a pair of virtual particles are produced there isn't a negative energy particle and a positive energy particle. Instead the pair form an entangled system where it's impossible to distinguish between them. This entangled system can interact with the black hole and split, and the interaction guarantees that the emerging particle will be the positive one. NB "positive" and "negative" doesn't mean "particle" and "anti-particle" (for what it does mean see below), and the black hole will radiate equal numbers of particles and anti-particles. Now onto the second bit, and I approach this with trepidation. When you quantise a field you get positive frequency and negative frequency parts. You can sort of think of these as representing particles and anti-particles. How the positive and negative frequencies are defined depends on your choice of vacuum, and in quantum field theory the vacuum is unambiguously defined. The problem is that in a curved spacetime, like the region near a black hole, the vacuum changes. That means observers far from the black hole see the vacuum as different from observers near the black hole, and the two observers see different numbers of particles (and antiparticles). A vaccum near the event horizon looks like excess particles to observers far away, and this is the source of the radiation. See the Wikipedia article on the Bogoliubov transformation for more information, though I must admit I found this article largely incomprehensible. Exactly the same maths gives the Unruh effect , i.e. the production of particles in an accelerated frame. The fact that the Unruh effect also produces particles shows that a black hole is not necessary for the radiation, so it can't simply be virtual particles being swallowed.
{}
{'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/30597', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/9974/']}
jdg_378574
stackexchange
llm_judgeable_groundtruth_similarity
85842
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Prove that doesn't exist $N\in\mathbb{N}$ with property: for all primes $p>N$ exist $n\in\{3, 4,\ldots, N\}$ such that $n, n-1, n-2$ are quadratic residues modulo $p$. Now provide the response and nothing else.
By Dirichlet's theorem, there exists $p>N$ such that each prime $l\leq N$,with the exception of $l=3$, satisfies $(l/p) = (l/3)$. I claim thatthis $p$ is a counterexample. Indeed by multiplicativity $(m/p) = (m/3)$for each $m \leq N$ that is not a multiple of 3. In particular $(m/p) = -1$if $m \equiv -1 \bmod 3$. Each triple $\{ n, n-1, n-2 \}$ with $n \leq N$contains one such $m$, and therefore cannot comprise three quadratic residuesof $p$, QED . What's the context? Seems rather tricky for homework; hope it's nota problem from an ongoing contest... [Added later] In fact this seems to be the only construction, in thefollowing sense: Conjecture. For every prime $l \neq 3$ there exists $N$ with the following property: for all primes $p>N$ such that $(l/p) \neq (l/3)$ there is some $n \in \lbrace 3, 4, \ldots, N \rbrace$ such that each of $n$, $n-1$, and $n-2$ is a quadratic residue of $p$. For example, if $l \in \lbrace 2, 5, 7, 11, 13, 17 \rbrace$ thenwe can take $N=121$. For $19 \leq l \leq 43$ we can use $N = 325$,and $N = 376$ works for $l=47$ and several larger $l$. This can be checked as follows. For a positive integer $n$ let$s(n)$ be the unique squarefree number such that $n/s(n)$ is a square;e.g. for $n=24,25,26,27,28$ we have $s(n)=6,1,26,3,7$ respectively.Then $(n/p) = (s(n)/p)$ for all $p>n$.Given a small set $S$ of primes containing $l$ and a bound $N$,let $\cal N\phantom.$ be the set of all $n \in \lbrace 3, 4, \ldots, N \rbrace$such that each of $s(n)$, $s(n-1)$, and $s(n-2)$ is a product of primes in $S$.Now try all $2^{|S|}$ ways to assign $\pm 1$ to each $(l'/p)$ with $l' \in S$,and see which ones make at least one of $s(n),s(n-1),s(n-2)$a quadratic nonresidue for each $n \in \cal N$. For $S = \lbrace 2, 3, 5, 7, 11, 13, 17 \rbrace$ and $N = 121$, we compute$${\cal N} = \lbrace 3, 4, 5, \ldots, 17, 18, 22, 26, 27, 28, 34, 35, 36, 50,51, 52, 56, 65, 66, 100, 121 \rbrace,$$and find that the only choices that work are the two that make$(l/p) = (l/3)$ for each $l \in S - \lbrace 3 \rbrace$. Then if we put $l=19$ into $S$ and increase $N$ to $325$ we find that${\cal N} \ni 325$, with$323 = 17 \cdot 19$, $324 = 18^2$, and $325 = 13 \cdot 5^2$. Sothe only way to avoid $(323/p) = (324/p) = (325/p) = 1$ is to make$(19/p) = +1$. We then incorporate $l=23$ by considering $n=92$,and $l=29$ using $n=290$, "etc." Computation suggests that there arelots of choices to make this work once we get past $l=19$,but I don't know how feasible it might be to prove this. [The exhaustive computation over $2^{|S|}$ choices of $(l'/p)$is what led me to the pattern $(l/p) = (l/3)$ in the first place.Once only two choices remained for $S = \lbrace 2, 3, 5, 7, 11, 13, 17 \rbrace$I thought that a few more primes might whittle it down to zero anddisprove the claim, but I kept seeing only two choices that differedonly in the value of $(3/p)$, and the pattern in the other $(l/p)$ valuessoon became clear.]
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/85842', 'https://mathoverflow.net', 'https://mathoverflow.net/users/20643/']}
jdg_378575
stackexchange
llm_judgeable_groundtruth_similarity
58840973
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Let's consider the following code: int main() { int i = 2; int b = ++i++; return 3;} It compiles with the following with an error: <source>: In function 'int main()':<source>:3:16: error: lvalue required as increment operand 3 | int b = ++i++; | ^~ This sounds fair to me. Postfix increment has higher priority than prefix increment, so the code is parsed as int b = ++(i++); and i is an rvalue. Hence the error. Let's now consider this variant with parenthesis to override default priorities: int main() { int i = 2; int b = (++i)++; return 3;} This code compiles and returns 3. On its own, this sounds fair to me but it seems in contradiction with the first code. The question: why (++i) is an lvalue when i is not? Thanks! UPDATE: the error message shown above was from gcc (x86-64 9.2). Here is the exact rendering: error with gcc Clang x86-64 9.0.0 has a quite different message: error with clang <source>:3:13: error: expression is not assignable int b = ++i++; ^ ~~~ With GCC, you get the impression that the problem is with the postfix operator and you can then wander why ++i is OK while i is not, hence my question. With Clang it is clearer that the problem is with the prefix operator. Now provide the response and nothing else.
i and ++i are both lvalues, but i++ is an rvalue. ++(i++) cannot be valid, as the prefix ++ is being applied to i++ , which is an rvalue. But (++i)++ is fine because ++i is an lvalue. Note that in C, the situation is different; i++ and ++i are both rvalues. (This is an example of why people should stop assuming that C and C++ have the same rules. People insert these assumptions into their questions, which must then be refuted.)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/58840973', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12342718/']}
jdg_378576
stackexchange
llm_judgeable_groundtruth_similarity
524528
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Html.Encode seems to simply call HttpUtility.HtmlEncode to replace a few html specific characters with their escape sequences. However this doesn't provide any consideration for how new lines and multiple spaces will be interpretted (markup whitespace). So I provide a text area for the a user to enter a plain text block of information, and then later display that data on another screen (using Html.Encode ), the new lines and spacing will not be preserved. I think there are 2 options, but maybe there is a better 3rd someone can suggest. One option would be to just write a static method that uses HtmlEncode, and then replaces new lines in the resulting string with <br> and groups of multiple spaces with &nbsp; Another option would be to mess about with the white-space: pre attribute in my style sheets - however I'm not sure if this would produce side effects when Html helper methods include new lines and tabbing to make the page source pretty. Is there a third option, like a global flag, event or method override I can use to change how html encoding is done without having to redo the html helper methods? Now provide the response and nothing else.
HtmlEncode is only meant to encode characters for display in HTML. It specifically does not encode whitespace characters. I would go with your first option, and make it an extension method for HtmlHelper. Something like: public static string HtmlEncode(this HtmlHelper htmlHelper, string text, bool preserveWhitespace){ // ...} You could use String.Replace() to encode the newlines and spaces (or Regex.Replace if you need better matching).
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/524528', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_378577
stackexchange
llm_judgeable_groundtruth_similarity
736474
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 got the following function: public static extern uint FILES_GetMemoryMapping( [MarshalAs(UnmanagedType.LPStr)] string pPathFile, out ushort Size, [MarshalAs(UnmanagedType.LPStr)] string MapName, out ushort PacketSize, ref Mapping oMapping, out byte PagesPerSector); Which I would like to call like this: FILES_GetMemoryMapping(MapFile, out size, MapName, out PacketSize, null, out PagePerSector); Unfortunately, I cannot pass null in a field that requires type ref Mapping and no cast I've tried fixes this. Any suggestions? Now provide the response and nothing else.
I'm assuming that Mapping is a structure? If so you can have two versions of the FILES_GetMemoryMapping() prototype with different signatures. For the second overload where you want to pass null , make the parameter an IntPtr and use IntPtr.Zero public static extern uint FILES_GetMemoryMapping( [MarshalAs(UnmanagedType.LPStr)] string pPathFile, out ushort Size, [MarshalAs(UnmanagedType.LPStr)] string MapName, out ushort PacketSize, IntPtr oMapping, out byte PagesPerSector); Call example: FILES_GetMemoryMapping(MapFile, out size, MapName, out PacketSize, IntPtr.Zero, out PagePerSector); If Mapping is actually a class instead of a structure, just set the value to null before passing it down.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/736474', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/88364/']}
jdg_378578
stackexchange
llm_judgeable_groundtruth_similarity
7510652
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 eclipse 3.7.0 on fedora and pydev 2.2.2 I tried to use the todo tags but it doesnt work.the todo tags on window > preferences looks fine.i can add a using left click beside the line. please advice Now provide the response and nothing else.
The second (assuming you means CONTAINS , and actually put it in a valid query) should be faster, because it can use some form of index (in this case, a full text index). Of course, this form of query is only available if the column is in a full text index. If it isn't, then only the first form is available. The first query, using LIKE, will be unable to use an index, since it starts with a wildcard, so will always require a full table scan. The CONTAINS query should be: SELECT * FROM table WHERE CONTAINS(Column, 'test');
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/7510652', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/285427/']}
jdg_378579
stackexchange
llm_judgeable_groundtruth_similarity
29737384
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 wish to access my current_user variable from my application.js (I renamed my application.js to application.js.erb so the server could understand my ruby code), so i got something like: function hello(){ alert("<%= current_user.name %>"); } But it fails: How can i get session variables like the current_user from devise gem working from a script located in /assets/my_script.js.erb, i think it should not be abled because theese variables might not be accesisible from public sites, or what should do about this? Thanks! Now provide the response and nothing else.
Application.js is not evaluated in the context of any session variables or methods. The simplest way to access username from javascript would be to set a cookie in a before_action on application controller: class ApplicationController < ActionController::Base before_action :set_user private def set_user cookies[:username] = current_user.name || 'guest' endend Then from any js in app/assets you can access the cookie: alert(document.cookie); A more verbose but arguably cleaner method would be to create a route that accesses the current user and returns the username e.g. routes.rb get 'current_user' => "users#current_user" users_controller.rb def current_user render json: {name: current_user.name}end application.js $.get('/current_user', function(result){ alert(result.name);});
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29737384', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/808398/']}
jdg_378580
stackexchange
llm_judgeable_groundtruth_similarity
27745948
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 layout with three spinners. They differ in the option presented in the drop-down. In my onCreateView I have a method to setup the spinners. Inside that method I have something like this: mySpinner = (Spinner) view.findViewById(R.id.my_spinner); ArrayAdapter<String> mySpinner = new ArrayAdapter<String>(getActivity(), R.layout.background, new ArrayList<String>(Arrays.asList(getResources().getStringArray(R.array.spinner_one_data)))); mySpinner.setDropDownViewResource(R.layout.spinner_text); mySpinner.setAdapter(mySpinner); mySpinner.setOnItemSelectedListener(this); As I said, my other two spinners are almost the same but with different options. I know that onItemSelected is called once for every spinner in a "first setup" so I have a flag to prevent this problem. With this flag solution, my spinners are working as expected. The problem is when I select in each spinner an option and then rotate the screen. Now, onItemSelected is called 6 times instead the 3 times that I was expecting (I've set a flag to manage this situation of the 3 times calling). Why Is it happening and hoe should I handle this? Now provide the response and nothing else.
In general, I've found that there are many different events that can trigger the onItemSelected method, and it is difficult to keep track of all of them. Instead, I found it simpler to use an OnTouchListener to only respond to user-initiated changes. Create your listener for the spinner: public class SpinnerInteractionListener implements AdapterView.OnItemSelectedListener, View.OnTouchListener { boolean userSelect = false; @Override public boolean onTouch(View v, MotionEvent event) { userSelect = true; return false; } @Override public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { if (userSelect) { // Your selection handling code here userSelect = false; } }} Add the listener to the spinner as both an OnItemSelectedListener and an OnTouchListener: SpinnerInteractionListener listener = new SpinnerInteractionListener();mSpinnerView.setOnTouchListener(listener);mSpinnerView.setOnItemSelectedListener(listener);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27745948', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1317865/']}
jdg_378581
stackexchange
llm_judgeable_groundtruth_similarity
59236834
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 ASP.NET Core 3.1 C# razor pages application that also uses some Blazor-serverside razor components. I have published it to IIS on Windows 2008 R2 Server.But when browsing the site in Chrome on one andorid mobile phone a message appears periodically: Attemting to reconnect to the server Also when user stays inactive for a while, e.g. turns off the mobile phone display, a message appears Disconnected from server. Reload page ... The site is not in english and those generic messages are not good for end user exprience. Is there any way how to disable those messages, or at least translate them to another language? Now provide the response and nothing else.
There is actually an answer for server-side Blazor as well. According to this: ASP.NET Core Blazor hosting models , one can define a div-element with the id components-reconnect-modal in the body of _Host.cshtml to manipulate the overlay that shows up in case of a connection loss. That would look something like this: <body>...<!-- Blazor overlay --><div id="components-reconnect-modal"></div><app> @(await Html.RenderComponentAsync<App>(RenderMode.ServerPrerendered))</app>...</body> Blazor applies these custom classes depending on the state of the app. According to the documentation these classes are in effect: components-reconnect-show : A lost connection. The client is attempting to reconnect. Show the modal.Then you can apply your custom styling to the screen overlay with CSS. If you want to remove them all to you can just choose to not display them at all. components-reconnect-hide : An active connection is re-established to the server. Hide the modal. components-reconnect-failed : Reconnection failed, probably due to a network failure. To attempt reconnection, call window.Blazor.reconnect() . components-reconnect-rejected : Reconnection rejected. The server was reached but refused the connection, and the user's state on the server is lost. To reload the app, call location.reload() . To hide the overlay completely, for instance you can add this CSS: .components-reconnect-show, .components-reconnect-failed, .components-reconnect-rejected { display: none;} If you want a custom look for the overlay, you can just fill the div in _Host.cshtml with content to your liking: <div id="components-reconnect-modal" class="my-reconnect-modal components-reconnect-hide"><div class="show"> <p> // Message when attempting to connect to server </p></div><div class="failed"> <p> // Message when failing to connect </p></div><div class="rejected"> <p> // Message when refused </p></div> I have no idea if this works client-side however, as I only work with server-side Blazor. I hope this works for you.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/59236834', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2224701/']}
jdg_378582
stackexchange
llm_judgeable_groundtruth_similarity
25101596
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 Python script in my docker container that needs to be executed, but I also need to have interactive access to the container once it has been created ( with /bin/bash ). I would like to be able to create my container, have my script executed and be inside the container to see the changes/results that have occurred (no need to manually execute my python script). The current issue I am facing is that if I use the CMD or ENTRYPOINT commands in the docker file I am unable to get back into the container once it has been created. I tried using docker start and docker attach but I'm getting the error: sudo docker start containerIDsudo docker attach containerID"You cannot attach to a stepped container, start it first" Ideally, something close to this: sudo docker run -i -t image /bin/bash python myscript.py Assume my python script contains something like (It's irrelevant what it does, in this case it just creates a new file with text): open('newfile.txt','w').write('Created new file with text\n') When I create my container I want my script to execute and I would like to be able to see the content of the file. So something like: root@66bddaa892ed# sudo docker run -i -t image /bin/bashbash4.1# lsnewfile.txtbash4.1# cat newfile.txtCreated new file with textbash4.1# exitroot@66bddaa892ed# In the example above my python script would have executed upon creation of the container to generate the new file newfile.txt. This is what I need. Now provide the response and nothing else.
My way of doing it is slightly different with some advantages.It is actually multi-session server rather than script but could be even more usable in some scenarios: # Just create interactive container. No start but named for future reference.# Use your own image.docker create -it --name new-container <image># Now start it.docker start new-container# Now attach bash session.docker exec -it new-container bash Main advantage is you can attach several bash sessions to single container. For example I can exec one session with bash for telling log and in another session do actual commands. BTW when you detach last 'exec' session your container is still running so it can perform operations in background
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/25101596', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2203569/']}
jdg_378583
stackexchange
llm_judgeable_groundtruth_similarity
10695835
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This is the HTML structure: Element link = doc.select("div.subtabs p").first(); That does not seem to work. How do I select that p ? Now provide the response and nothing else.
The DIV with the class="subtabs" is not in fact the parent of the p element but instead is the sibling of p . To retrieve the p , you'll need to first get a reference to the parent DIV that has the id="content": Element link = doc.select("div#content > p").first(); Additionally, you'll need the > symbol to indicate that you're selecting a child of div#content. parent > child: child elements that descend directly from parent, e.g. div.content > p finds p elements; and body > * finds the direct children of the body tag If you get stuck with a JSOUP CSS selector in the future, check out the JSOUP Selector Syntax cookbook , which has some nice examples and explanations.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10695835', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/787563/']}
jdg_378584
stackexchange
llm_judgeable_groundtruth_similarity
567585
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The standard (mathematicians') basis for the $\mathfrak{su}(2)$ Lie algebra is: $$X_j = -i\frac{\sigma_j}2$$ where $\sigma_j$ are the Pauli matrices. In physics, observables correspond to real numbers, so following the standard procedure we convert these to self-adjoint operators, which have real eigenvalues: $$X_j \rightarrow iX_j$$ This is straightforward so far. But the convention used is $X_j \rightarrow i\color{red}\hbar X_j$ - although there seems to be no a priori reason to add this factor here. One reference said something along the lines of "The factor of $\hbar$ is an indicator that we're using quantum calculations", but I find this to be a bit vague. What's the real reason behind this? Now provide the response and nothing else.
I think the physical context of your question isspin angular momentum of elementary particles (for example: an electron)and rotations of this particle in space. Let's begin with spin angular momentum $\bf{S}$ (a vector with 3 components $S_1$ , $S_2$ , $S_3$ ). Physical experiments showed that the measured spincomponent $S_j$ of the particle is either $+\frac{1}{2}\hbar$ or $-\frac{1}{2}\hbar$ .You see, Planck's constant $\hbar$ here (and its extremely smallnumerical value $1.055 \cdot 10^{-34}\rm{\ kg\ m^2/s} $ ) comes from physical experiments. Hence the observable $S_j$ is represented by the self-adjoint operator $$S_j=\frac{1}{2}\hbar\sigma_j.$$ The two eigenvectors of this operator are the measured values. On the other hand you have rotations of the particle in space. These rotationsare represented by unitary elements of the Lie group $SU(2)$ . $$U = e^{\frac{i}{2}(\theta_1\sigma_1+\theta_2\sigma_2+\theta_3\sigma_3)}$$ where $\theta_1$ , $\theta_2$ , $\theta_3$ are arbitrary real parametersencoding the axis and angle of the rotation. These Lie group elements are obviously generated by the 3 self-adjoint generators $$X_j=\frac{1}{2}\sigma_j$$ which spawn the Lie algebra $\mathfrak{su}(2)$ . The definition is chosen withoutthe $i$ so that the $X_j$ will be self-adjoint. You see, the observable $S_j$ and the generator $X_j$ are nearly the same,only different by the factor $\hbar$ : $S_j=\hbar X_j$ . By the way: This is essentially the contents of Noether's theorem ,saying every symmetry transformation (here generated by $X_j$ )corresponds to a conserved physical observable (here $S_j$ ). Now we physicists are lazy people. And therefore we use $S_j$ for bothpurposes ( $S_j$ as the spin observable and $S_j/\hbar$ as the rotation generator).Thus we can write $$U = e^{i(\theta_1 S_1+\theta_2 S_2+\theta_3 S_3)/\hbar}$$
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/567585', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/231159/']}
jdg_378585
stackexchange
llm_judgeable_groundtruth_similarity
6542187
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am new to XML and AJAX and am only a newcomer to Javascript and jQuery. Among other job duties I design our website. A deadline is very near, and the only way I can think of to do this project well is with AJAX. I have a document full of XML objects such as this one repeating: <item> <subject></subject> <date></date> <thumb></thumb></item> I want to create an array of all elements and their child elements. I've been reading jQuery tutorials on AJAX for hours and don't even know where to start because they all assume a certain level of javascript proficiency. If someone could show me the easiest way to loop through all elements and put their children into an array, I'd appreciate it tons. Now provide the response and nothing else.
Using jQuery, $.ajax() your XML file, and on success pass retrieved data with each , like: var tmpSubject, tmpDate, tmpThumb; $.ajax({ url: '/your_file.xml', type: 'GET', dataType: 'xml', success: function(returnedXMLResponse){ $('item', returnedXMLResponse).each(function(){ tmpSubject = $('subject', this).text(); tmpDate = $('date', this).text(); tmpThumb = $('thumb', this).text(); //Here you can do anything you want with those temporary //variables, e.g. put them in some place in your html document //or store them in an associative array }) } });
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6542187', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/812883/']}
jdg_378586
stackexchange
llm_judgeable_groundtruth_similarity
1073956
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 come up with a "smart" and "secure" way of generating about 63million unique codes to be used in a competition. The codes will be about 10 characters long. Has anyone done anything similar or aware of any "hurdles" that might arise from this issues? How do we minimize the probability of someone being able to guess the codes? This project will be done in PHP, but that won't really matter, it's more of the logic that's an issue here. Any feedback would be really appreciated. UPDATE Just to clarify it will be 10 characters of case insensitive Alpha Numeric Values.A-Z0-9 Now provide the response and nothing else.
Syntax : You probably will have people copying these codes, so that means these codes should be easy to copy. 10^10 is too small, as Gamecat points out. kgiannakakis has a better idea, but that causes another problem: "1" looks a lot like "I". "0", "C", "O" and "Q" are also quite similar. This is not a big problem. Define a safe alfabet: "0123456789ABDEFGHJKLMNPRSTUVXYZ" (leaves out COIQ) From the comments: depending on the fonts you pick, 5/S and U/V may also be visually ambiguous; replace as required . This is a 32 symbol (5 bit) code. A 10 character code is a 50 bits number. Those should be fairly trivial to generate, sort, copy, compare etc. Chances of being guessed are about 0.63E-7 Since the codes are too long to remember, users will need a resting point when copying them. So split the string in two or three parts and make sure the input field matches this breakdown. E.g. AKG3L-45TEE => two groups of 5, and even if you can't remember 5 chars it's a lot easier to find the point back where you stopped reading. How to generate them : This is fairly simple. You don't need a particularly sophistciated algorithm to generate candidates. You can generate 10 random numbers per code needed, take 5 bits from each number ( typically the middle bits are best, e.g. (rand()/64) modulo 32 ). Use this value [0-31] as index into your alphabet. Create a database table with this string as a primary key, and insert until the table has 63 million entries. You probably want to add "generated on" and "redeemed on" dates to this table.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1073956', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/104934/']}
jdg_378587
stackexchange
llm_judgeable_groundtruth_similarity
15114396
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: To cite the spec : Block-level boxes are boxes that participate in a block formatting context. Each block-level element generates a principal block-level box that contains descendant boxes and generated content and is also the box involved in any positioning scheme. Some block-level elements may generate additional boxes in addition to the principal box: 'list-item' elements. These additional boxes are placed with respect to the principal box. Are they essentially the same thing? Now provide the response and nothing else.
A principal block-level box is the block-level box generated by a given element that's directly affected by style rules that apply to the element. Most elements generate only one box. For these elements, they are essentially the same thing, since there are no other boxes involved. However, an element can generate more than one box depending on its display type, such as a list item ; when you declare styles for such an element, the styles are typically applied to the principal box and any additional boxes that are generated will be rendered accordingly. For example, a list item has a marker box in addition to the principal box; if you specify list-style-position: outside , the list marker will be placed outside the boundaries of the principal box but the background and borders of the principal box won't be affected. Note that the marker box is still a descendant of the principal box, so inheritable properties such as color will apply to the marker (this is why color: red turns both the text and its bullet marker red). Most other block-level elements, including display: block but excluding display: table (see section 17.4 ), will simply generate a principal block box for their content and nothing else, making them essentially just "block boxes", but only for those elements. In other words, all principal block-level boxes are block-level boxes, but not all block-level boxes are principal, for example anonymous block boxes . Also, inline elements, including inline blocks, do not generate any principal boxes themselves, nor is there such a thing as a principal inline box.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15114396', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1736621/']}
jdg_378588
stackexchange
llm_judgeable_groundtruth_similarity
4818468
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 check if InputStream has been gzipped?Here's the code: public static InputStream decompressStream(InputStream input) { try { GZIPInputStream gs = new GZIPInputStream(input); return gs; } catch (IOException e) { logger.info("Input stream not in the GZIP format, using standard format"); return input; }} I tried this way but it doesn't work as expected - values read from the stream are invalid.EDIT:Added the method I use to compress data: public static byte[] compress(byte[] content) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { GZIPOutputStream gs = new GZIPOutputStream(baos); gs.write(content); gs.close(); } catch (IOException e) { logger.error("Fatal error occured while compressing data"); throw new RuntimeException(e); } double ratio = (1.0f * content.length / baos.size()); if (ratio > 1) { logger.info("Compression ratio equals " + ratio); return baos.toByteArray(); } logger.info("Compression not needed"); return content;} Now provide the response and nothing else.
It's not foolproof but it's probably the easiest and doesn't rely on any external data. Like all decent formats, GZip too begins with a magic number which can be quickly checked without reading the entire stream. public static InputStream decompressStream(InputStream input) { PushbackInputStream pb = new PushbackInputStream( input, 2 ); //we need a pushbackstream to look ahead byte [] signature = new byte[2]; int len = pb.read( signature ); //read the signature pb.unread( signature, 0, len ); //push back the signature to the stream if( signature[ 0 ] == (byte) 0x1f && signature[ 1 ] == (byte) 0x8b ) //check if matches standard gzip magic number return new GZIPInputStream( pb ); else return pb;} (Source for the magic number: GZip file format specification ) Update: I've just dicovered that there is also a constant called GZIP_MAGIC in GZipInputStream which contains this value, so if you really want to, you can use the lower two bytes of it.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4818468', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/592462/']}
jdg_378589
stackexchange
llm_judgeable_groundtruth_similarity
11026200
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 <span> that I want to rotate. I am using HTML5, CSS3, and Internet Explorer 9. I tried the below CSS, but it's not working: -webkit-transform: rotate(-90deg); -moz-transform: rotate(-90deg); How do I rotate the span? Now provide the response and nothing else.
-webkit- and -moz- properties are for webkit browsers (Chrome, Safari) and Gecko browsers (Firefox) respectively. You need to use the equivalent for IE as well. .rotate {/* Safari, Chrome */-webkit-transform: rotate(-90deg);/* Firefox */-moz-transform: rotate(-90deg);/* IE */-ms-transform: rotate(-90deg);/* Opera */-o-transform: rotate(-90deg);/* Older versions of IE */filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);/* CSS3 standard as defined here: http://www.w3.org/TR/css3-transforms/ */transform: rotate(-90deg);} Source
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11026200', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1453386/']}
jdg_378590
stackexchange
llm_judgeable_groundtruth_similarity
134024
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 $\mathbb G = (G, +)$ be a group. We say that $\mathbb G$ is strictly totally orderable (others would say bi-orderable) if there exists a total order $\preceq$ on $G$ such that $x+z \prec y + z$ and $z + x \prec z + y$ for all $x,y,z \in G$ with $x \prec y$. It is not difficult to give a direct proof of the fact that if $\mathbb G$ is abelian and torsion-free then it is strictly totally orderable ( Proof. There is a group embedding of $\mathbb G$ into a divisible group, and then into $(\mathbb Q^\kappa,+)$ for $\kappa := |G|$); the result is credited to F. W. Levi [1]. However, an exercise in Hodges' Model Theory asks for a proof of the same result by the compactness theorem, a proof which I wasn't able to reconstruct. So the questions are: Q1. Could you mention an article or a book where such a proof can be found? Q2. Would you sketch such a proof here? Thanks in advance for any help. References. [1] F. W. Levi, Arithmetische Gesetze im Gebiete diskreter Gruppen , Rend. Circ. Mat. Palermo 35 (1913), 225–236. Now provide the response and nothing else.
A compactness argument which Hodges may have had in mind can go as follows. Since a subgroup of a totally ordered group is also a totally ordered group, it suffices to embed the given abelian torsion-free group $G$ into a totally ordered group, i.e., to show that the theory of totally ordered abelian groups is consistent with the diagram of $G$. By the compactness theorem, it is enough to show that this is true for any finite subset of the diagram. This finite subset only mentions finitely many constants from $G$, hence it suffices to show that every finitely generated subgroup of $G$ is totally orderable. However, every finitely generated abelian torsion-free group is isomorphic to $\mathbb Z^n$ for some $n\in\omega$, which can be given e.g. the lexicographic order. Notice that only the last step used something specific about abelian groups. The same argument shows that a (nonabelian) group is totally orderable if and only if all its finitely generated subgroups are, and likewise for other ordered structures (e.g., semigroups or rings).
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/134024', 'https://mathoverflow.net', 'https://mathoverflow.net/users/16537/']}
jdg_378591
stackexchange
llm_judgeable_groundtruth_similarity
2050309
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 have a JSF managed bean be automatically created? For example I have several session scoped beans. Sometimes it becomes necessary to access these instances in code (rather than just in JSF) this is done by: PageBean pageBean = (PageBean) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("pages"); However if no page has already been visited which calls to '#{pages}' this resolves to null ... is there anyway to get JSF to create a bean when the scope 'begins'? So in this case ideally when a user session begins the 'pages' bean would be instantiated in the session immediately? Now provide the response and nothing else.
Use Application#evaluateExpressionGet() instead. It will create bean when not done yet. FacesContext context = FacesContext.getCurrentInstance();Bean bean = (Bean) context.getApplication().evaluateExpressionGet(context, "#{bean}", Bean.class); Where "bean" is the managed bean name and Bean.class is the appropriate backing bean class. You can if necessary wrap this up in a helper method so that casting is unnecessary (the JSF boys didn't take benefit of generics and the Class parameter in evaluateExpressionGet ): public static <T> T findBean(String managedBeanName, Class<T> beanClass) { FacesContext context = FacesContext.getCurrentInstance(); return beanClass.cast(context.getApplication().evaluateExpressionGet(context, "#{" + managedBeanName + "}", beanClass));} which can be used as: Bean bean = findBean("bean", Bean.class); Or without the type, but with a @SuppressWarnings : @SuppressWarnings("unchecked")public static <T> T findBean(String managedBeanName) { FacesContext context = FacesContext.getCurrentInstance(); return (T) context.getApplication().evaluateExpressionGet(context, "#{" + managedBeanName + "}", Object.class);} which can be used as: Bean bean = findBean("bean"); Update : the above is by the way JSF 1.2 specific. Here's the way for JSF 1.1 or older, using the currently deprecated Application#createValueBinding() : FacesContext context = FacesContext.getCurrentInstance();Bean bean = (Bean) context.getApplication().createValueBinding("#{bean}").getValue(context);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2050309', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/220648/']}
jdg_378592
stackexchange
llm_judgeable_groundtruth_similarity
38872341
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 list of lists: a = [[1, 3, 4], [2, 5, 7]] I want the output in the following format: 1 3 42 5 7 I have tried it the following way , but the outputs are not in the desired way: for i in a: for j in i: print(j, sep=' ') Outputs: 134257 While changing the print call to use end instead: for i in a: for j in i: print(j, end = ' ') Outputs: 1 3 4 2 5 7 Any ideas? Now provide the response and nothing else.
Iterate through every sub-list in your original list and unpack it in the print call with * : a = [[1, 3, 4], [2, 5, 7]]for s in a: print(*s) The separation is by default set to ' ' so there's no need to explicitly provide it. This prints: 1 3 42 5 7 In your approach you were iterating for every element in every sub-list and printing that individually. By using print(*s) you unpack the list inside the print call, this essentially translates to: print(1, 3, 4) # for s = [1, 3, 4]print(2, 5, 7) # for s = [2, 5, 7]
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/38872341', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6557700/']}
jdg_378593
stackexchange
llm_judgeable_groundtruth_similarity
70036953
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 initiate a Spring Boot project using OpenJDK 15, Spring Boot 2.6.0, Springfox 3. We are working on a project that replaced Netty as the web server and used Jetty instead, because we do not need a non-blocking environment. In the code we depend primarily on Reactor API (Flux, Mono), so we can not remove org.springframework.boot:spring-boot-starter-webflux dependencies. I replicated the problem that we have in a new project: https://github.com/jvacaq/spring-fox . I figured out that these lines in our build.gradle file are the origin of the problem. compile("org.springframework.boot:spring-boot-starter-web") { exclude module: "spring-boot-starter-tomcat"}compile("org.springframework.boot:spring-boot-starter-jetty") Here is the build.gradle file: plugins { id 'org.springframework.boot' version '2.6.0' id 'io.spring.dependency-management' version '1.0.11.RELEASE' id 'java'}group = 'com.example'version = '0.0.1-SNAPSHOT'sourceCompatibility = '11'repositories { mavenCentral()}dependencies { compile("org.springframework.boot:spring-boot-starter-web") { exclude module: "spring-boot-starter-tomcat" } compile("org.springframework.boot:spring-boot-starter-jetty") implementation 'org.springframework.boot:spring-boot-starter-webflux' testImplementation 'org.springframework.boot:spring-boot-starter-test' testImplementation 'io.projectreactor:reactor-test' implementation "io.springfox:springfox-boot-starter:3.0.0"}test { useJUnitPlatform()} I issued the command gradle clean bootrun . The result is this error: gradle clean bootrun> Task :bootRun FAILED . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.6.0)2021-11-19 09:41:06.665 INFO 16666 --- [ main] c.e.springfox.SpringFoxApplication : Starting SpringFoxApplication using Java 15.0.2 on advance-Inspiron-5379 with PID 16666 (/home/advance/projects/spring-fox/build/classes/java/main started by advance in /home/advance/projects/spring-fox)2021-11-19 09:41:06.666 INFO 16666 --- [ main] c.e.springfox.SpringFoxApplication : No active profile set, falling back to default profiles: default2021-11-19 09:41:07.294 INFO 16666 --- [ main] org.eclipse.jetty.util.log : Logging initialized @1132ms to org.eclipse.jetty.util.log.Slf4jLog2021-11-19 09:41:07.396 INFO 16666 --- [ main] o.s.b.w.e.j.JettyServletWebServerFactory : Server initialized with port: 80802021-11-19 09:41:07.398 INFO 16666 --- [ main] org.eclipse.jetty.server.Server : jetty-9.4.44.v20210927; built: 2021-09-27T23:02:44.612Z; git: 8da83308eeca865e495e53ef315a249d63ba9332; jvm 15.0.2+7-272021-11-19 09:41:07.417 INFO 16666 --- [ main] o.e.j.s.h.ContextHandler.application : Initializing Spring embedded WebApplicationContext2021-11-19 09:41:07.417 INFO 16666 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 713 ms2021-11-19 09:41:07.474 INFO 16666 --- [ main] org.eclipse.jetty.server.session : DefaultSessionIdManager workerName=node02021-11-19 09:41:07.474 INFO 16666 --- [ main] org.eclipse.jetty.server.session : No SessionScavenger set, using defaults2021-11-19 09:41:07.475 INFO 16666 --- [ main] org.eclipse.jetty.server.session : node0 Scavenging every 660000ms2021-11-19 09:41:07.480 INFO 16666 --- [ main] o.e.jetty.server.handler.ContextHandler : Started o.s.b.w.e.j.JettyEmbeddedWebAppContext@6aa3bfc{application,/,[file:///tmp/jetty-docbase.8080.2024342829220941812/, jar:file:/home/advance/.gradle/caches/modules-2/files-2.1/io.springfox/springfox-swagger-ui/3.0.0/1e665fbe22148f7c36fa8a08e515a0047cd4390b/springfox-swagger-ui-3.0.0.jar!/META-INF/resources],AVAILABLE}2021-11-19 09:41:07.480 INFO 16666 --- [ main] org.eclipse.jetty.server.Server : Started @1318ms2021-11-19 09:41:07.920 INFO 16666 --- [ main] o.e.j.s.h.ContextHandler.application : Initializing Spring DispatcherServlet 'dispatcherServlet'2021-11-19 09:41:07.920 INFO 16666 --- [ main] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'2021-11-19 09:41:07.921 INFO 16666 --- [ main] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms2021-11-19 09:41:07.931 INFO 16666 --- [ main] o.e.jetty.server.AbstractConnector : Started ServerConnector@2643d762{HTTP/1.1, (http/1.1)}{0.0.0.0:8080}2021-11-19 09:41:07.932 INFO 16666 --- [ main] o.s.b.web.embedded.jetty.JettyWebServer : Jetty started on port(s) 8080 (http/1.1) with context path '/'2021-11-19 09:41:07.934 WARN 16666 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException: Cannot invoke "org.springframework.web.servlet.mvc.condition.PatternsRequestCondition.getPatterns()" because "this.condition" is null2021-11-19 09:41:07.949 INFO 16666 --- [ main] o.e.jetty.server.AbstractConnector : Stopped ServerConnector@2643d762{HTTP/1.1, (http/1.1)}{0.0.0.0:8080}2021-11-19 09:41:07.950 INFO 16666 --- [ main] org.eclipse.jetty.server.session : node0 Stopped scavenging2021-11-19 09:41:07.951 INFO 16666 --- [ main] o.e.j.s.h.ContextHandler.application : Destroying Spring FrameworkServlet 'dispatcherServlet'2021-11-19 09:41:07.951 INFO 16666 --- [ main] o.e.jetty.server.handler.ContextHandler : Stopped o.s.b.w.e.j.JettyEmbeddedWebAppContext@6aa3bfc{application,/,[file:///tmp/jetty-docbase.8080.2024342829220941812/, jar:file:/home/advance/.gradle/caches/modules-2/files-2.1/io.springfox/springfox-swagger-ui/3.0.0/1e665fbe22148f7c36fa8a08e515a0047cd4390b/springfox-swagger-ui-3.0.0.jar!/META-INF/resources],STOPPED}2021-11-19 09:41:07.958 INFO 16666 --- [ main] ConditionEvaluationReportLoggingListener :Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.2021-11-19 09:41:07.970 ERROR 16666 --- [ main] o.s.boot.SpringApplication : Application run failedorg.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException: Cannot invoke "org.springframework.web.servlet.mvc.condition.PatternsRequestCondition.getPatterns()" because "this.condition" is null at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:181) ~[spring-context-5.3.13.jar:5.3.13] at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:54) ~[spring-context-5.3.13.jar:5.3.13] at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:356) ~[spring-context-5.3.13.jar:5.3.13] at java.base/java.lang.Iterable.forEach(Iterable.java:75) ~[na:na] at org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:155) ~[spring-context-5.3.13.jar:5.3.13] at org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:123) ~[spring-context-5.3.13.jar:5.3.13] at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:935) ~[spring-context-5.3.13.jar:5.3.13] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:586) ~[spring-context-5.3.13.jar:5.3.13] at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) ~[spring-boot-2.6.0.jar:2.6.0] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:730) ~[spring-boot-2.6.0.jar:2.6.0] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:412) ~[spring-boot-2.6.0.jar:2.6.0] at org.springframework.boot.SpringApplication.run(SpringApplication.java:302) ~[spring-boot-2.6.0.jar:2.6.0] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1301) ~[spring-boot-2.6.0.jar:2.6.0] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1290) ~[spring-boot-2.6.0.jar:2.6.0] at com.example.springfox.SpringFoxApplication.main(SpringFoxApplication.java:10) ~[main/:na]Caused by: java.lang.NullPointerException: Cannot invoke "org.springframework.web.servlet.mvc.condition.PatternsRequestCondition.getPatterns()" because "this.condition" is null at springfox.documentation.spring.web.WebMvcPatternsRequestConditionWrapper.getPatterns(WebMvcPatternsRequestConditionWrapper.java:56) ~[springfox-spring-webmvc-3.0.0.jar:3.0.0] at springfox.documentation.RequestHandler.sortedPaths(RequestHandler.java:113) ~[springfox-core-3.0.0.jar:3.0.0] at springfox.documentation.spi.service.contexts.Orderings.lambda$byPatternsCondition$3(Orderings.java:89) ~[springfox-spi-3.0.0.jar:3.0.0] at java.base/java.util.Comparator.lambda$comparing$77a9974f$1(Comparator.java:469) ~[na:na] at java.base/java.util.TimSort.countRunAndMakeAscending(TimSort.java:355) ~[na:na] at java.base/java.util.TimSort.sort(TimSort.java:220) ~[na:na] at java.base/java.util.Arrays.sort(Arrays.java:1306) ~[na:na] at java.base/java.util.ArrayList.sort(ArrayList.java:1721) ~[na:na] at java.base/java.util.stream.SortedOps$RefSortingSink.end(SortedOps.java:392) ~[na:na] at java.base/java.util.stream.Sink$ChainedReference.end(Sink.java:258) ~[na:na] at java.base/java.util.stream.Sink$ChainedReference.end(Sink.java:258) ~[na:na] at java.base/java.util.stream.Sink$ChainedReference.end(Sink.java:258) ~[na:na] at java.base/java.util.stream.Sink$ChainedReference.end(Sink.java:258) ~[na:na] at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:485) ~[na:na] at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474) ~[na:na] at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913) ~[na:na] at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:na] at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:578) ~[na:na] at springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider.requestHandlers(WebMvcRequestHandlerProvider.java:81) ~[springfox-spring-webmvc-3.0.0.jar:3.0.0] at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195) ~[na:na] at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1625) ~[na:na] at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484) ~[na:na] at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474) ~[na:na] at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913) ~[na:na] at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:na] at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:578) ~[na:na] at springfox.documentation.spring.web.plugins.AbstractDocumentationPluginsBootstrapper.withDefaults(AbstractDocumentationPluginsBootstrapper.java:107) ~[springfox-spring-web-3.0.0.jar:3.0.0] at springfox.documentation.spring.web.plugins.AbstractDocumentationPluginsBootstrapper.buildContext(AbstractDocumentationPluginsBootstrapper.java:91) ~[springfox-spring-web-3.0.0.jar:3.0.0] at springfox.documentation.spring.web.plugins.AbstractDocumentationPluginsBootstrapper.bootstrapDocumentationPlugins(AbstractDocumentationPluginsBootstrapper.java:82) ~[springfox-spring-web-3.0.0.jar:3.0.0] at springfox.documentation.spring.web.plugins.DocumentationPluginsBootstrapper.start(DocumentationPluginsBootstrapper.java:100) ~[springfox-spring-web-3.0.0.jar:3.0.0] at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:178) ~[spring-context-5.3.13.jar:5.3.13] ... 14 common frames omittedFAILURE: Build failed with an exception.* What went wrong:Execution failed for task ':bootRun'.> Process 'command '/home/advance/.sdkman/candidates/java/15.0.2-open/bin/java'' finished with non-zero exit value 1* Try:Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.* Get more help at https://help.gradle.orgDeprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.Use '--warning-mode all' to show the individual deprecation warnings.See https://docs.gradle.org/6.9.1/userguide/command_line_interface.html#sec:command_line_warningsBUILD FAILED in 2s5 actionable tasks: 5 executed How can I solve it? Now provide the response and nothing else.
This problem's caused by a bug in Springfox . It's making an assumption about how Spring MVC is set up that doesn't always hold true. Specifically, it's assuming that MVC's path matching will use the Ant-based path matcher and not the PathPattern-based matcher. PathPattern-based matching has been an option for some time now and is the default as of Spring Boot 2.6. As described in Spring Boot 2.6's release notes , you can restore the configuration that Springfox assumes will be used by setting spring.mvc.pathmatch.matching-strategy to ant-path-matcher in your application.properties file. Note that this will only work if you are not using Spring Boot's Actuator. The Actuator always uses PathPattern-based parsing, irrespective of the configured matching-strategy . A change to Springfox will be required if you want to use it with the Actuator in Spring Boot 2.6 and later.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/70036953', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/306436/']}
jdg_378594
stackexchange
llm_judgeable_groundtruth_similarity
324561
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: what is the difference between convex, non-convex, concave and non-concave functions? how will we come to know that the given function is convex or non-convex? and if a function is non-convex then it will necessarily be concave one?Thanks in advance Now provide the response and nothing else.
A convex function has one minimum - a nice property, as an optimization algorithm won't get stuck in a local minimum that isn't a global minimum. Take $x^2 - 1$, for example: A non-convex function is wavy - has some 'valleys' (local minima) that aren't as deep as the overall deepest 'valley' (global minimum). Optimization algorithms can get stuck in the local minimum, and it can be hard to tell when this happens. Take $x^4 + x^3 -2x^2 -2x$, for example: A concave function is the negative of a convex function. Take $-x^2$, for example: A non-concave function isn't a widely used term, and it's sufficient to say it's a function that isn't concave - though I've seen it used to refer to non-convex functions. I wouldn't really worry about this one.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/324561', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/168985/']}
jdg_378595
stackexchange
llm_judgeable_groundtruth_similarity
45277183
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am new to angular and I would like to put the application on Nginx server on a docker container. 1. Running the angular application through @angular/cli To do that, I did the following steps: 1.1. Installation of @angular/cli and creation of an angular4 application sudo npm install -g @angular/cling new angular4-on-nginx-with-docker 1.2. Serving the application through npm start The angular application is working correctly through npm start Now, I want to avoid the command npm start because I am thinking about developing a dockerized application. To do that, below is: 2. Running the angular application on nginx 2.1. Dockerfile file for nginx FROM debian:jessieMAINTAINER NGINX Docker Maintainers "docker-maint@nginx.com"ENV NGINX_VERSION 1.11.9-1~jessieRUN apt-key adv --keyserver hkp://pgp.mit.edu:80 --recv-keys 573BFD6B3D8FBC641079A6ABABF5BD827BD9BF62 \ && echo "deb http://nginx.org/packages/mainline/debian/ jessie nginx" >> /etc/apt/sources.list \ && apt-get update \ && apt-get install --no-install-recommends --no-install-suggests -y \ ca-certificates \ nginx=${NGINX_VERSION} \ && rm -rf /var/lib/apt/lists/*# forward request and error logs to docker log collectorRUN ln -sf /dev/stdout /var/log/nginx/access.log \ && ln -sf /dev/stderr /var/log/nginx/error.logEXPOSE 80 443CMD ["nginx", "-g", "daemon off;"] 2.2. The config of nginx is below: server { server_name angular4.dev; root /var/www/frontend/src; try_files $uri $uri/ index.html; error_log /var/log/nginx/angular4_error.log; access_log /var/log/nginx/angular4_access.log;} 2.3. The docker-compose.yml version: '2'services: nginx: build: nginx ports: - 88:80 volumes: - ./nginx/frontend:/var/www/frontend - ./nginx/default.conf:/etc/nginx/conf.d/default.conf - ./nginx/logs/nginx/:/var/log/nginx 2.4. building the docker image and running the container docker-compose up -d --build 2.5. Identification of the IP address of the container docker inspect angular4onnginxwithdocker_nginx_1 | grep IPA #"SecondaryIPAddresses": null, #"IPAddress": "", # "IPAMConfig": null, # "IPAddress": "172.18.0.2", Open your browser on 172.18.0.2 The issue I think that npm packages are not accessible... I am not sure what is wrong exactly. But, what I can say is that the page is empty and without having any error message in the console. Below is the code obtained when using nginx <!doctype html><html lang="en"><head> <meta charset="utf-8"> <title>Angular4 on nginx with docker</title> <base href="/"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/x-icon" href="favicon.ico"></head><body> <app-root></app-root></body></html> This the code of the page obtained by the use of the command npm start <!doctype html><html lang="en"><head> <meta charset="utf-8"> <title>Angular4 on nginx with docker</title> <base href="/"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/x-icon" href="favicon.ico"></head><body> <app-root></app-root><script type="text/javascript" src="inline.bundle.js"></script><script type="text/javascript" src="polyfills.bundle.js"></script><script type="text/javascript" src="styles.bundle.js"></script><script type="text/javascript" src="vendor.bundle.js"></script><script type="text/javascript" src="main.bundle.js"></script></body></html> So, what is wrong??? A repo for that example is available on github Now provide the response and nothing else.
If anyone still struggling with production setup of angular 2/4/5 app + Nginx(i.e. Without Docker), then here is the complete solution: Suppose you want to deploy your angular app at HOST: http://example.com and PORT: 8080 Note - HOST and PORT might be different in your case. Make sure you have <base href="/"> in you index.html head tag. Firstly, go to your angular repo (i.e. /home/user/helloWorld) path at your machine. Then build /dist for your production server using the following command: ng build --prod --base-href http://example.com:8080 Now copy /dist (i.e. /home/user/helloWorld/dist) folder from your machine's angular repo to the remote machine where you want to host your production server. Now login to your remote server and add following nginx server configuration. server { listen 8080; server_name http://example.com; root /path/to/your/dist/location; # eg. root /home/admin/helloWorld/dist index index.html index.htm; location / { try_files $uri $uri/ /index.html; # This will allow you to refresh page in your angular app. Which will not give error 404. }} Now restart nginx. That's it !! Now you can access your angular app at http://example.com:8080 Hope it will be helpful.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45277183', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2269738/']}
jdg_378596
stackexchange
llm_judgeable_groundtruth_similarity
101185
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: What is a quick and easy way to validate if the pattern "301 domaname.com 200" is present within BASH when spread across multiple lines of output? I was using something like the following: awk '/301|domain.com|200/' pcregrep -M '301|domain\.com|200' but the order doesn't matter. I'm not sure how to state it so it does. What I thought would work apparently isn't catching the line endings. pcregrep -M '301.*domain\.com.*200' Background: I'm building a small mod_rewrite server and I need a way to monitor what domains are getting redirected to what destinations. As a result I'm assembling a small Nagios check script that will handle this for me. What I have so far is the following: curl qa-mod-rewrite.domain.com -i -I -LHTTP/1.1 301 Moved PermanentlyVia: 1.1 GREGORYConnection: closeProxy-Connection: closeDate: Thu, 14 Nov 2013 16:35:19 GMTLocation: http://qa.domain.com/Content-Type: text/html; charset=iso-8859-1Server: Apache/2.2.3 (CentOS)HTTP/1.1 200 OKVia: 1.1 GREGORYConnection: Keep-AliveProxy-Connection: Keep-AliveContent-Length: 56772Expires: -1Date: Thu, 14 Nov 2013 16:35:03 GMTContent-Type: text/html; charset=utf-8Server: Microsoft-IIS/7.5Cache-Control: no-cache, no-storePragma: no-cacheX-AspNet-Version: 2.0.50727Set-Cookie: cfcausa.qa#sc_wede=1; path=/Set-Cookie: ASP.NET_SessionId=i4z1c4ahqoiw13552z413hbs; path=/; HttpOnlyX-Powered-By: ASP.NET Now provide the response and nothing else.
There's scope for false positive there as 301.*domain\.com.*200 would match for instance on: HTTP/1.1 404 Not foundContent-Length: 301 0X-Pingback: http://blah. domain.com /xmlrpcLast-Modified: Thu, 14 Nov 200 9 19:27:05 GMT You could be a bit more thorough and write it for instance: curl -sIL http://qa-mod-rewrite.domain.com | tr -d '\r' | awk -v RS= ' NR == 1 && $2 == "301" && /\nLocation: [^\n]*domain\.com/ {redir=1} $2 == "200" {end=1} END {exit !(redir*end)}' With variable data: url=$1EXPECTED_REDIRECTION=$2EXPECTED_REDIRECTION_CODE=$3EXPECTED_TERMINAL_CODE=$4export EXPECTED_REDIRECTION EXPECTED_REDIRECTION_CODE EXPECTED_TERMINAL_CODEcurl -sIL "$url" | tr -d '\r' | awk -v RS= ' BEGIN { re = ENVIRON["EXPECTED_REDIRECTION"] gsub(/[][^.$+?\\()]/, "\\&",re) re = "\nLocation: [^\n]*" re } NR == 1 && $2 == ENVIRON["EXPECTED_REDIRECTION_CODE"] && $0 ~ re {redir=1} $2 == $ENVIRON["EXPECTED_TERMINAL_CODE"] {end=1} END {exit !(redir*end)}'
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/101185', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/10554/']}
jdg_378597
stackexchange
llm_judgeable_groundtruth_similarity
8975531
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What is the command to get the number of clients connected to a particular MongoDB server? Now provide the response and nothing else.
connect to the admin database and run db.serverStatus() : > var status = db.serverStatus()> status.connections {"current" : 21, "available" : 15979}> You can directly get by querying db.serverStatus().connections To understand what does MongoDb's db.serverStatus().connections response mean, read the documentation here . connections "connections" : { "current" : <num>, "available" : <num>, "totalCreated" : NumberLong(<num>)}, connections A document that reports on the status of the connections. Use these values to assess the current load and capacity requirements of the server. connections.current The number of incoming connections from clients to the database server . This number includes the current shell session. Consider the value of connections.available to add more context to this datum. The value will include all incoming connections including any shell connections or connections from other servers, such as replica set members or mongos instances. connections.available The number of unused incoming connections available. Consider this value in combination with the value of connections.current to understand the connection load on the database, and the UNIX ulimit Settings document for more information about system thresholds on available connections. connections.totalCreated Count of all incoming connections created to the server. This number includes connections that have since closed.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/8975531', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1029567/']}
jdg_378598
stackexchange
llm_judgeable_groundtruth_similarity
316312
Below is a question asked on the forum meta.stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: A pet peeve of mine on Stack Overflow and in real life is when someone seeking help says, "it's not working" or "I get an error." These are useless descriptions that always require a follow-up question like "How does what's happening differ from what you expect?" or "What's the exact error message you're receiving?" I know there are other heuristics in place to detect bad questions and prompt the user to improve; might it be possible to detect when someone uses a nebulous term like "an error" or "not working" without elaborating? Clarification : I agree with what Ed Cottrell says below that false positives are a big possibility. However, we wouldn't necessarily need to block the questions so much as provide a prompt: We see you've mentioned receiving an error; in order to receive the best answers to your question, make sure you post the full details of the error you've received. Now provide the response and nothing else.
tl; dr this probably can't be done in a useful way (high signal-to-noise ratio), would be very difficult to do, and is probably not a good idea. While I like the idea, I don't think it's feasible. This is awfully hard to implement because English is a difficult language to parse. What about these examples? I get an error and it doesn't work. should probably be blocked. I get an error in my log file "invalid syntax something." Maybe; depends on the something and other details. I get an error 3 times, but the fourth time it works. Close; depends on what other information is provided. I get an error 1064 syntax error. Very close; it would be nice to know the real error message, but a MySQL 1064 is a familiar, specific kind of problem. I get an error. ERROR 1064: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'AS Now we're talking. The user said, I get an error. , but then gave the full error details. I get an error. , followed by huge amounts of code and text, with the specific error message buried somewhere down the post, probably not formatted correctly. As Mr Lister pointed out in the comments, this is very common, but the proposed feature would (1) have a hard time detecting this and (2) likely do little to help with readability of this type of post. Figuring out how to parse the many possibilities is a pretty complex task. Figuring out when the user used a phrase like "an error" without elaborating is a natural-language processing problem, and a really hard one. This proposed feature seems very likely to result in false positives. On the other hand, we have downvotes, close votes, and comments at our disposal to handle and clarify the posts in question already. On top of that, it would be one more thing we're asking users to read before posting. As evidenced by the moderator flag and review queues, the most problematic posts are by people who clearly didn't read and understand most of the instructions presented to them, anyway. In short, this is complicated to implement and, in my opinion, not realistically likely to solve (or significantly improve) the problem that it attempts to address.
{}
{'log_upvote_score': 5, 'links': ['https://meta.stackoverflow.com/questions/316312', 'https://meta.stackoverflow.com', 'https://meta.stackoverflow.com/users/119549/']}
jdg_378599
stackexchange
llm_judgeable_groundtruth_similarity
3677531
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 ActiveRecord model Event with a datetime column starts_at . I would like to present a form, where date and time for starts_at are chosen separately (e.g. "23-10-2010" for date and "18:00" for time). These fields should be backed by the single column starts_at , and validations should preferably be against starts_at , too. I can of course muck around with virtual attributes and hooks, but I would like a more elegant solution. I have experimented with both composed_of ( rdoc ), and attribute-decorator ( lighthouse discussion , github ) without success. Below is a rough outline of what I would like.. class Event < ActiveRecord::Base validates_presence_of :start_dateend# View# On submission this should set start_date.form_for @event do |f| f.text_field :starts_at_date # date-part of start_date f.text_field :starts_at_time_of_day # time-of-day-part of start_date f.submitend Any help appreciated. Now provide the response and nothing else.
Do you have to have a text_field in the view? As far as I can tell, you can have a date_time field and then just use two different input fields to set the different parts of the field. form_for @event do |f| f.date_select :starts_at f.time_select :starts_at, :ignore_date => true f.submitend Since the rails date and time select helpers set five different parameters ( starts_at(1i) for the year part, 2i for the month part, and so on), that means that the date_select only sets them for the date part, while if you pass :ignore_date => true to the time_select , it will only set the hour and minute part. If you must have a text_field I'm not sure how to do it, but it might be possible to do using some jQuery magic before setting the datetime parameters before sending the form.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3677531', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/241542/']}
jdg_378600
stackexchange
llm_judgeable_groundtruth_similarity
2749878
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm developing my first iPhone app and want to allow the user to select the scope of their search in a more complex way than the 'scope buttons' permit. The app is related to wines and I want to the user to be able to select the 'color' (Red, White, Blush, etc.) first, and then select the type/varietal within that category. Right now, I'm using the UISearchBar's scope buttons for the colors and tapping the button opens a view with the selection of colors. This is okay except that once the 'Red' button has been selected, I can't select it a second time to change my choice of type (e.g., change from 'Merlot' to 'Syrrah', etc.) If there's a better way to do this, I'm willing to scrap my method and start from scratch. Thanks! Now provide the response and nothing else.
Since there seemed to be some dispute over my original answer, I decided to do a few tests, including looking at the generated code and monitoring the performance. First of all, here's our test bed, a class with a delegate and another class to consume it: class EventProducer{ public void Raise() { var handler = EventRaised; if (handler != null) handler(this, EventArgs.Empty); } public event EventHandler EventRaised;}class Counter{ long count = 0; EventProducer producer = new EventProducer(); public void Count() { producer.EventRaised += CountEvent; producer.Raise(); producer.EventRaised -= CountEvent; } public void CountWithNew() { producer.EventRaised += new EventHandler(CountEvent); producer.Raise(); producer.EventRaised -= new EventHandler(CountEvent); } private void CountEvent(object sender, EventArgs e) { count++; }} First thing to do is look at the generated IL: .method public hidebysig instance void Count() cil managed{ .maxstack 8 L_0000: ldarg.0 L_0001: ldfld class DelegateTest.Program/EventProducer DelegateTest.Program/Counter::producer L_0006: ldarg.0 L_0007: ldftn instance void DelegateTest.Program/Counter::CountEvent(object, class [mscorlib]System.EventArgs) L_000d: newobj instance void [mscorlib]System.EventHandler::.ctor(object, native int) L_0012: callvirt instance void DelegateTest.Program/EventProducer::add_EventRaised(class [mscorlib]System.EventHandler) L_0017: ldarg.0 L_0018: ldfld class DelegateTest.Program/EventProducer DelegateTest.Program/Counter::producer L_001d: callvirt instance void DelegateTest.Program/EventProducer::Raise() L_0022: ldarg.0 L_0023: ldfld class DelegateTest.Program/EventProducer DelegateTest.Program/Counter::producer L_0028: ldarg.0 L_0029: ldftn instance void DelegateTest.Program/Counter::CountEvent(object, class [mscorlib]System.EventArgs) L_002f: newobj instance void [mscorlib]System.EventHandler::.ctor(object, native int) L_0034: callvirt instance void DelegateTest.Program/EventProducer::remove_EventRaised(class [mscorlib]System.EventHandler) L_0039: ret }.method public hidebysig instance void CountWithNew() cil managed{ .maxstack 8 L_0000: ldarg.0 L_0001: ldfld class DelegateTest.Program/EventProducer DelegateTest.Program/Counter::producer L_0006: ldarg.0 L_0007: ldftn instance void DelegateTest.Program/Counter::CountEvent(object, class [mscorlib]System.EventArgs) L_000d: newobj instance void [mscorlib]System.EventHandler::.ctor(object, native int) L_0012: callvirt instance void DelegateTest.Program/EventProducer::add_EventRaised(class [mscorlib]System.EventHandler) L_0017: ldarg.0 L_0018: ldfld class DelegateTest.Program/EventProducer DelegateTest.Program/Counter::producer L_001d: callvirt instance void DelegateTest.Program/EventProducer::Raise() L_0022: ldarg.0 L_0023: ldfld class DelegateTest.Program/EventProducer DelegateTest.Program/Counter::producer L_0028: ldarg.0 L_0029: ldftn instance void DelegateTest.Program/Counter::CountEvent(object, class [mscorlib]System.EventArgs) L_002f: newobj instance void [mscorlib]System.EventHandler::.ctor(object, native int) L_0034: callvirt instance void DelegateTest.Program/EventProducer::remove_EventRaised(class [mscorlib]System.EventHandler) L_0039: ret } So it turns out that, yes, these do generate identical IL. I was wrong originally. But that's not the whole story . It may be that I'm going off-topic here but I think that it's important to include this when talking about events and delegates: Creating and comparing different delegates is not cheap. When I wrote this, I was thinking that the first syntax was able to cast the method group as a delegate, but it turns out that it's just a conversion. But it's completely different when you actually save the delegate. If we add this to the consumer: class Counter{ EventHandler savedEvent; public Counter() { savedEvent = CountEvent; } public void CountSaved() { producer.EventRaised += savedEvent; producer.Raise(); producer.EventRaised -= savedEvent; }} You can see that this has very different characteristics, performance-wise, from the other two: static void Main(string[] args){ const int TestIterations = 10000000; TimeSpan countTime = TestCounter(c => c.Count()); Console.WriteLine("Count: {0}", countTime); TimeSpan countWithNewTime = TestCounter(c => c.CountWithNew()); Console.WriteLine("CountWithNew: {0}", countWithNewTime); TimeSpan countSavedTime = TestCounter(c => c.CountSaved()); Console.WriteLine("CountSaved: {0}", countSavedTime); Console.ReadLine();}static TimeSpan TestCounter(Action<Counter> action, int iterations){ var counter = new Counter(); Stopwatch sw = new Stopwatch(); sw.Start(); for (int i = 0; i < TestIterations; i++) action(counter); sw.Stop(); return sw.Elapsed;} The results consistently come back as something similar to: Count: 00:00:02.4742007CountWithNew: 00:00:02.4272702CountSaved: 00:00:01.9810367 That's nearly a 20% difference when using a saved delegate vs. creating a new one. Now obviously not every program is going to be adding and removing this many delegates in such a small amount of time, but if you're writing library classes - classes that might be used in ways you cannot predict - then you really want to keep this difference in mind if you ever need to add and remove events (and I've written a lot of code that does this, personally). So the conclusion of this is, writing SomeEvent += new EventHandler(NamedMethod) compiles to the same thing as just SomeEvent += NamedMethod . But if you plan to remove that event handler later, you really should save the delegate . Even though the Delegate class has some special-case code that allows you to remove a referentially-different delegate from the one you added, it has to do a non-trivial amount of work to pull this off. If you're not going to save the delegate, then it makes no difference - the compiler ends up creating a new delegate anyway.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2749878', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/330346/']}
jdg_378601
stackexchange
llm_judgeable_groundtruth_similarity
170923
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: We need to generate a release in 3 weeks, and for the planning we are doing today we don't have coherent logical user stories from the backlog tasks. Is valid to match say each development task is equivalent to an user story? Methodologically what is the correct way of handling this?, because anyway we are going to have standup meetings and we are going to control the progress of the project against those development tasks. For example, we have things like: . Adapt ETL to process numeric lists . Adjust licensing component . Remove DTC and so on. So, for the planning poker and iteration planning is valid to use those tasks? if not, what is the alternative? Now provide the response and nothing else.
You may want to consider a change to your process- generate development tasks from user stories, not the other way around. User stories have a business value built in. For example, the adjustment to the licensing component: If you can express that as a story (As [a type of user], I want [some feature] because it will give me [some business value]), then go ahead and make the adjustment. If you can't find the user and the business value, that should be a clue: don't do that work! Do something else instead.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/170923', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/14457/']}
jdg_378602
stackexchange
llm_judgeable_groundtruth_similarity
12105513
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 these two functions: validateEmail: function(value) { var regex = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;return (regex.test(value)) ? true : false;}validateEmails: function(string) { var self = shareEmail; var result = string.replace(/\s/g, "").split(/,|;/); for(var i = 0;i < result.length;i++) { if(!self.validateEmail(result[i])) { return false; } else { return true; } }} The problem is that when I test the email like this if(!self.validateEmails(multipleEmails)) { i get true or false based only on the first email in the string, but I want to test for any email in the string. Thank you! Now provide the response and nothing else.
The problem is your if/else block; You are returning under both conditions. Which means that it leaves the function after evaluating only one element. I've modified validateEmails to demonstrate what you probably want to do: validateEmail: function(value) { var regex = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/; return (regex.test(value)) ? true : false;}validateEmails: function(string) { var self = shareEmail; var result = string.replace(/\s/g, "").split(/,|;/); for(var i = 0;i < result.length;i++) { if(!self.validateEmail(result[i])) { return false; } } return true;}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12105513', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/553303/']}
jdg_378603
stackexchange
llm_judgeable_groundtruth_similarity
655284
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 seen patterns for translating a string into lower (or upper case) using the translate function for folks stuck using xslt 1.0. Is there a elegant way of just making the first letter of a string lowercase? TestCase => testCase Now provide the response and nothing else.
If your string were, for example, in an attribute called name : <xsl:value-of select="concat(translate(substring(@name, 1, 1), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), substring(@name, 2))"/>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/655284', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/48658/']}
jdg_378604
stackexchange
llm_judgeable_groundtruth_similarity
413100
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: Need to repair a trace on my PCB. The burnt trace has a hairpin turn on it. Instead of following the same hairpin shape, can I just bridge across the undamaged points at the bottom? And also, the printed "TF b=0.4mm" on the PCB, does it have any significance to it? Next to it appears 0.6mm that has the same hairpin shape, but trace looks a bit wider. I have superimposed two pics together. One has light shone through the PCB Now provide the response and nothing else.
Since they're labeled TF , it's safe to state they're t hermal f uses. Therefor, since inductance is likely irrelevant, you could replace them with through-hole fuses of the correct value. The current value depends on copper layer thickness , but for 1 oz. Cu, 0.4 mm would be about 1.5 A and 0.6 mm ~2.5 A... but it would be better to find out what the actual current ratings are. N.B. Since that 0.4 mm trace is thoroughly fried, first fix the issue that burned it out . The fuse has a purpose, and it likely prevented further damage or even a fire, so don't just bypass it.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/413100', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/207796/']}
jdg_378605
stackexchange
llm_judgeable_groundtruth_similarity
381707
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to activate NordVPN CyberSec by completing the following instructions in Debian 9. I should be able to do the changes as root and with sudo like described for Ubuntu in the thread Should I edit my resolv.conf file to fix wrong DNS problem? and in the thread Linux: How do i edit resolv.conf but I cannot. If you are using Linux or Mac OS X, please open the terminal and type in: su You will be asked for your root password, please type it in and press enter rm -r /etc/resolv.conf nano /etc/resolv.conf When the text editor opens, please type in these lines: nameserver 103.86.99.99nameserver 103.86.96.96 Now you have to close and save the file, you can do that by clicking Ctrl + X and pressing Y . Then please continue typing in the terminal: chattr +i /etc/resolv.conf reboot now That is it. Your computer will reboot and everything should work correctly. If you will ever need to change your DNS addresses, please open the terminal and type in the following: su You will be asked for your root password, please type it in and press enter chattr -i /etc/resolv.conf nano /etc/resolv.conf Change DNS addresses, save and close the file. chattr +i /etc/resolv.conf I do the first step as su /root but get the following. Trying to change the file /etc/resolv.conf content there with sudo , I get operation not permitted . root@masi:/etc# ls -la * | grep resolv.conf-rw-r--r-- 1 root root 89 Jan 22 2017 resolv.conf-rw-r--r-- 1 root root 89 Jul 25 17:10 resolv.conf~-rw-r--r-- 1 root root 0 Jan 22 2017 resolv.conf.tmp-rwxr-xr-x 1 root root 1301 Nov 12 2015 update-resolv-confroot@masi:/etc# sudo mv resolv.conf resolv.conf.tmp2mv: cannot move 'resolv.conf' to 'resolv.conf.tmp2': Operation not permitted OS: Debian 9 Now provide the response and nothing else.
As per your steps, you protected the file /etc/resolv.conf from being deleted/overwritten with chattr +i (immutable) So, you won't be able to move it to another file without doing sudo chattr -i /etc/resolv.conf first. From man chattr A file with the 'i' attribute cannot be modified: it cannot be deleted or renamed, no link can be created to this file and no data can be written to the file. Only the superuser or a process possessing the CAP_LINUX_IMMUTABLE capability can set or clear this attribute.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/381707', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/16920/']}
jdg_378606
stackexchange
llm_judgeable_groundtruth_similarity
63008037
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 alertDialog containing a DropdownButton widget. Whenever I click on an option within the dropDown I want it to display the selected value. I have listed the code below along with 2 screenshots. I believe this may be an issue with how flutter builds widget because when I placed the DropdownButton widget outside of the dialog it worked, however placing it within an alertDialog causes it to fail. I also noticed that if I clicked on an option in the DropdownButton and then exited and clicked on the dialog again the selected item would change. However, I want the selected value to change without the user having to tap out of the dialog and then back in. ^ The above image is the dialog when a user first clicks on it. At first the only selected item is "I'm not able to help". This value should change whenever a user clicks on the DropdownMenu widget and selects a different option such as "other". ^ These are the various options a user can click on within the dropdown menu. When a user clicks on it, the menu should update accordingly. CODE: Please note that I have defined _chosenValue as a global variable outside of the build function. void _showDecline() { showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: new Text("Decline Appointment Request"), content: Container( height: 100, width: 200, child: Column( children: <Widget>[ new Text("Please select an option for why you declined."), new DropdownButton<String>( value: _chosenValue, underline: Container(), items: <String>['I\'m not able to help', 'Unclear description', 'Not available at set date and time', 'Other'].map((String value) { return new DropdownMenuItem<String>( value: value, child: new Text(value, style: TextStyle(fontWeight: FontWeight.w500),), ); }).toList(), onChanged: (String value) { setState(() { _chosenValue = value; }); }, ) ], ), ), actions: <Widget>[ // usually buttons at the bottom of the dialog new FlatButton( child: new Text("Close"), onPressed: () {}, }, ), ], ); }, ); } Now provide the response and nothing else.
setState will only update current StatefulWidget's Widget Build function. You should use StatefulBuilder inside showDialog. For your case just add StatefulBuilder as a parent of your DropDown widget, and use StateSetter when you want to update the StatefulBuilder's children.It will only update the widget tree defined under StateFulBuilder builder function. See the full code including stateFulBuilder at DartPad code StateFulBuilderDartPad . For more information on StatefulBuilder head over to StateFulBuilder documentation page.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/63008037', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13090475/']}
jdg_378607
stackexchange
llm_judgeable_groundtruth_similarity
44325896
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Could anyone please let me know how to convert protobuf's ByteString to an octal escape sequence String in java? In my case, I am getting the ByteString value as \376\024\367 so, when I print the string value in console using System.out.println() , I should get "\376\024\367" . Many thanks. Now provide the response and nothing else.
Normally, you'd convert a ByteString to a String using ByteString#toString(Charset) . This method lets you specify what charset the text is encoded in. If it's UTF-8, you can also use the method toStringUtf8() as a shortcut. From your question, though, it sounds like you actually want to produce the escaped format using C-style three-digit octal escapes. AFAIK there's no public function to do this, but you can see the code here . You could copy that code into your own project and use it.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/44325896', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1636958/']}
jdg_378608
stackexchange
llm_judgeable_groundtruth_similarity
12181760
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm developing a site using Bootstrap which has 28 modal windows with information on different products. I want to be able to print the information in an open modal window. Each window has an id . <!-- firecell panel & radio hub --> <div class="modal hide fade" id="fcpanelhub"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">X</button> <h3>5000 Control Panel & Radio Hub</h3> </div> <div class="modal-body"> <img src="../site/img/firecell/firecell-panel-info-1.png" alt=""/><hr/> <img src="../site/img/firecell/firecell-panel-info-2.png" alt=""/><hr/> <img src="../site/img/firecell/firecell-radio-hub-info-1.png" alt=""/><hr/> <img src="../site/img/firecell/firecell-radio-hub-info-2.png" alt=""/> </div> <div class="modal-footer"> <a href="#" class="btn" data-dismiss="modal">Close</a> </div> </div> So if I add in a new button in modal-footer - 'print', and it's clicked I want that modal to print. Would I be right in saying javascript would be used? If so, how do I tell javascript to print only the open modal, and not the others? All help appreciated. Now provide the response and nothing else.
Another solution Here is a new solution based on Bennett McElwee answer in the same question as mentioned below. Tested with IE 9 & 10, Opera 12.01, Google Chrome 22 and Firefox 15.0. jsFiddle example 1.) Add this CSS to your site: @media screen { #printSection { display: none; }}@media print { body * { visibility:hidden; } #printSection, #printSection * { visibility:visible; } #printSection { position:absolute; left:0; top:0; }} 2.) Add my JavaScript function function printElement(elem, append, delimiter) { var domClone = elem.cloneNode(true); var $printSection = document.getElementById("printSection"); if (!$printSection) { $printSection = document.createElement("div"); $printSection.id = "printSection"; document.body.appendChild($printSection); } if (append !== true) { $printSection.innerHTML = ""; } else if (append === true) { if (typeof (delimiter) === "string") { $printSection.innerHTML += delimiter; } else if (typeof (delimiter) === "object") { $printSection.appendChild(delimiter); } } $printSection.appendChild(domClone);} You're ready to print any element on your site! Just call printElement() with your element(s) and execute window.print() when you're finished. Note: If you want to modify the content before it is printed (and only in the print version), checkout this example (provided by waspina in the comments): http://jsfiddle.net/95ezN/121/ One could also use CSS in order to show the additional content in the print version (and only there). Former solution I think, you have to hide all other parts of the site via CSS. It would be the best, to move all non-printable content into a separate DIV : <body> <div class="non-printable"> <!-- ... --> </div> <div class="printable"> <!-- Modal dialog comes here --> </div></body> And then in your CSS: .printable { display: none; }@media print{ .non-printable { display: none; } .printable { display: block; }} Credits go to Greg who has already answered a similar question: Print <div id="printarea"></div> only? There is one problem in using JavaScript : the user cannot see a preview - at least in Internet Explorer!
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/12181760', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1260835/']}
jdg_378609
stackexchange
llm_judgeable_groundtruth_similarity
9838119
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 PhantomJS page.evaluate() to do some scraping. My problem is that the code I pass to the webkit page is sandboxed, and so has no access to the variables of my main phantom script. This makes it hard make the scraping code generic. page.open(url, function() { var foo = 42; page.evaluate(function() { // this code has no access to foo console.log(foo); });} How could I push arguments into the page? Now provide the response and nothing else.
I've had that exact problem. It can be done with a little trickery, because page.evaluate also can accept a string. There are several ways to do it, but I use a wrapper called evaluate , which accepts additional parameters to pass to the function that must be evaluated on the webkit side. You would use it like this: page.open(url, function() { var foo = 42; evaluate(page, function(foo) { // this code has now has access to foo console.log(foo); }, foo);}); And here is the evaluate() function: /* * This function wraps WebPage.evaluate, and offers the possibility to pass * parameters into the webpage function. The PhantomJS issue is here: * * http://code.google.com/p/phantomjs/issues/detail?id=132 * * This is from comment #43. */function evaluate(page, func) { var args = [].slice.call(arguments, 2); var fn = "function() { return (" + func.toString() + ").apply(this, " + JSON.stringify(args) + ");}"; return page.evaluate(fn);}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9838119', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1287968/']}
jdg_378610
stackexchange
llm_judgeable_groundtruth_similarity
25713086
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Find: "Text (Y.m.d) - XXX - YYY - Name.ext" Replace: "Text - XXX - YYY - (d.m.Y) - Name.ext" Where: Text is static across all files upper and lowercase letters only XXX three decimal interger with up to two leading zeroes different across all files (eg. 014) YYY three decimal interger with up to two leading zeroes different across all files (d.m.Y) and (Y.m.d) the date d= number day (with leading zero if <10) m= number of the month (with leading zero <10) Y= four digit year (eg. (07.12.2014) (different across all files and to be changed)) Name: The actual name of the file contains only upper- and lower-case letters and punctuation and maybe & (eg. HTML5 and PHP) Now provide the response and nothing else.
My solution is to cancel the navigation and load the request with loadRequest: again. This will be come the similar behavior like UIWebView which always open new window in the current frame. Implement the WKUIDelegate delegate and set it to _webview.uiDelegate . Then implement: - (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures{ if (!navigationAction.targetFrame.isMainFrame) { [webView loadRequest:navigationAction.request]; } return nil;}
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/25713086', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4016961/']}
jdg_378611
stackexchange
llm_judgeable_groundtruth_similarity
20000195
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: My app use Express and AngularJS. I'm using express to handle basic web seving of the angular code via static. The angular code uses services that hit API endpoints hosted by express. I only want the API endpoints to be accessible after a user has authenticated. How can I accomplish this via PassportJS? Now provide the response and nothing else.
I have uploaded an Angular-Express project on github that I have been working on. It is still work in progress. I hope it helps. It uses PassportJs for user authentication and is a basic example of server side authorization. It demonstrates how to make API calls accessible only to authenticated users, or only to users with admin role. This is achieved in server/routes.js calling the middleware functions ensureAuthenticated , and ensureAdmin which are defined in server/authentication.js in routes.js // anybody can access this app.get('/api/test/users', api.testUsers);// only logged-in users with ADMIN role can access this app.get('/api/users', authentication.ensureAdmin, api.testUsers);// only logged-in users can access thisapp.get('/api/books', authentication.ensureAuthenticated, api.books); in authentication.js ensureAuthenticated: function(req, res, next) { if (req.isAuthenticated()) { return next(); } else { return res.send(401); }},ensureAdmin: function(req, res, next) { // ensure authenticated user exists with admin role, // otherwise send 401 response status if (req.user && req.user.role == 'ADMIN') { return next(); } else { return res.send(401); }},
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/20000195', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/239879/']}
jdg_378612
stackexchange
llm_judgeable_groundtruth_similarity
241512
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: In my design I am using RS232 with DB9 connector in my PCB. idea is to log the data in PC and for programming via serial. Which connector I need to use in my board , it is male DB9 or female DB9. Q1) What connector I need to use in my board male or female Q2) If I use male connector in my board then Pin TO1 will need to connect to pin 2 or pin 3. Now provide the response and nothing else.
The original plan when the D-sub connector family was introduced was that equipment would always have female connectors and cables would always have male connectors. The idea was that pins are easily damaged, and it's usually easier to replace a cable than to replace a connector on a piece of equipment. Designations such as "DCE" (data communications equipment) and "DTE" (data terminal equipment) would indicate whether signals such as TXD and RXD were inputs or outputs on the equipment. However, when the IBM PC came along, they decided to use D-sub connectors for a number of different purposes, so in order to reduce confusion for users, they used a female connector for the printer port and a male connector for the COM (UART) port. As a result, it has become common to use a male connector on DTE and a female connector on DCE. If you want to connect your device to a PC, you should put a female connector on it so that you can use a straight-through male-to-female cable to plug it in. And just to be pedantic, the correct designation is "DE-9". "DB" refers to the larger shell used for the 25-pin connector.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/241512', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/114042/']}
jdg_378613
stackexchange
llm_judgeable_groundtruth_similarity
8836197
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 made some helper functions that run a simulation using a lot of functions inside them. In order to make these helper functions more user friendly I want to give the user the choice of calling the functions with fewer arguments (the arguments that are not passed into the function are assigned a predefined value). For example if I have a function function [res, val, h, v, u] = compute(arg1, arg2, arg3, arg4) if nargin < 4 || isempty(arg4) arg4 = 150; end and the function runsim which is defined like this function [res, val, h, v, u] = runsim(v, arg1, arg2, arg3, arg4) the silly way to do it is if nargin < 5 || isempty(arg4) compute(arg1, arg2, arg3)else compute(arg1, arg2, arg3, arg4)end Another solution would be to change the arguments to vectors but I am not allowed to touch the functions behind the simulation. Is there a Matlab way to handle this situation or do I have to write the same code again and again with fewer arguments? Now provide the response and nothing else.
You can pack and unpack function arguments using cell arrays: a={'foo','bar',42}fun(a{:}) % is the same as:fun('foo','bar',42) The same goes for output arguments: a,b,c=fun(); % or easier:c=cell(3,1);[c{:}]=fun(); Since varargin is also a cell array, you can just pop the field the function you want to execute is in, and then pass the rest of the fields as arguments to the function.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8836197', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/842785/']}
jdg_378614
stackexchange
llm_judgeable_groundtruth_similarity
6602922
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 looking at at some of the java primitive collections ( trove , fastutil , hppc ) and I've noticed a pattern that class variables are sometimes declared as final local variables. For example: public void forEach(IntIntProcedure p) { final boolean[] used = this.used; final int[] key = this.key; final int[] value = this.value; for (int i = 0; i < used.length; i++) { if (used[i]) { p.apply(key[i],value[i]); } }} I've done some benchmarking, and it appears that it is slightly faster when doing this, but why is this the case? I'm trying to understand what Java would do differently if the first three lines of the function were commented out. Note: This seems similiar to this question , but that was for c++ and doesn't address why they are declared final . Now provide the response and nothing else.
Accessing local variable or parameter is a single step operation: take a variable located at offset N on the stack. If you function has 2 arguments (simplified): N = 0 - this N = 1 - first argument N = 2 - second argument N = 3 - first local variable N = 4 - second local variable ... So when you access local variable, you have one memory access at fixed offset (N is known at compilation time). This is the bytecode for accessing first method argument ( int ): iload 1 //N = 1 However when you access field, you are actually performing an extra step. First you are reading " local variable " this just to determine the current object address. Then you are loading a field ( getfield ) which has a fixed offset from this . So you perform two memory operations instead of one (or one extra). Bytecode: aload 0 //N = 0: this referencegetfield total I //int total So technically accessing local variables and parameters is faster than object fields. In practice, many other factors may affect performance (including various levels of CPU cache and JVM optimizations). final is a different story. It is basically a hint for the compiler/JIT that this reference won't change so it can make some heavier optimizations. But this is much harder to track down, as a rule of thumb use final whenever possible.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6602922', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/43665/']}
jdg_378615
stackexchange
llm_judgeable_groundtruth_similarity
40886324
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 create a conditional required validation on a specific field.I try doing this by return Validators.required back in my function, but this doesn't seem to work. How do I go about doing this? Here's my code: private _ansat: AbstractControl = new FormControl('', Validators.required);private _helbred: AbstractControl = new FormControl('', Validators.compose([this.useValidateIfRadio(this._ansat, 0, Validators.required)]) );constructor(private _fb: FormBuilder) { this.myForm = this._fb.group({ ansat: this._ansat, helbred: this._helbred });}useValidateIfRadio (c: AbstractControl, n: number, v) { return function (control) { return new Promise(resolve => { // this.msg = ansatControl.value; console.log(v); if (c.value === n) { resolve(v); } else { resolve(null); } }); }; }; Any help is greatly appreciated. Now provide the response and nothing else.
I had a similar problem but couldn't find a answer. Since nobody has answered this yet I'll provide an example of how I solved my problem, and how you can solve your issue using the same solution. Example: (Phone number is required only if email is not set) export class UserComponent implements OnInit {userForm: FormGroup;constructor(private fb: FormBuilder) {}ngOnInit() { //Create my userForm and and add initial validators this.userForm = this.fb.group({ username: [null, [Validators.required]], name: [null, [Validators.required]], email: [], phoneNumber: [null, [Validators.required, Validators.minLength(4)], }); //Listen to email value and update validators of phoneNumber accordingly this.userForm.get('email').valueChanges.subscribe(data => this.onEmailValueChanged(data));}onEmailValueChanged(value: any){ let phoneNumberControl = this.userForm.get('phoneNumber'); // Using setValidators to add and remove validators. No better support for adding and removing validators to controller atm. // See issue: https://github.com/angular/angular/issues/10567 if(!value){ phoneNumberControl.setValidators([Validators.required, Validators.minLength(4)]); }else { phoneNumberControl.setValidators([Validators.minLength(4)]); } phoneNumberControl.updateValueAndValidity(); //Need to call this to trigger a update}} So in your case you should add a changeListener to "_ansat" equal to my email listener, and then add required to "_helbred" accordingly.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40886324', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2622577/']}
jdg_378616
stackexchange
llm_judgeable_groundtruth_similarity
1163098
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I've been trying to understand the central idea behind the measure theory: to define which subsets of $\Omega$ can be measured, where $\Omega$ is the domain of a function $f$. Once this is established then any function can be approximated by characteristic functions on these sets, which is used to define the integral $\int_\Omega fd\mu$. What confuses me, when studying the literature, is that the tripple $(\Omega,\Sigma,\mu)$ i.e. (the set, the sigma-algebra of its subsets, and a measure function) is always used in the formulation of theorems, but it is somehow implicitly assumed that Theorem(?): The very existence of a sigma-algebra guarantees that one can approximate (i.e. by covering) any subset of $\Omega$. But such a theorem is probably incorrect without assuming additional properties of $\Sigma$. For example, the partition $\Sigma=\{\emptyset,\Omega\}$ is a sigma-algebra but can hardly approximate any subset. Where the assumption that $\Sigma$ can in fact approximatively cover any subset in $\Omega$ comes from? For example, is it implied by the existence of a sigma-algebra on $\Omega$? So, I wonder: is theorem(?) implicit in the definition of measure? and if yes, how is it guaranteed? EDIT1: The background to the question can be found here . Now provide the response and nothing else.
Measure theory makes explicit the distinction between two key concepts: measurability and measure. You may be used to thinking of $$\int f(x) d\mu(x)$$as a single object. Two things are needed for this integral to make sense: $f$ needs to be measurable with respect to a $\sigma$-algebra and $\mu$ needs to be a measure defined on that $\sigma$-algebra. Note crucially that measurability of $f$ is not dependent on any kind of measure. Measurability of a function $f$ is the property that one can distinguish the values that $f$ takes. This is perhaps easiest to understand in the discrete case. Suppose $$\Omega = \{\omega_1,\omega_2\}, \quad \Sigma = \{\emptyset,\{\omega_1\},\{\omega_2\},\{\omega_1,\omega_2\}\}.$$What kind of functions $f : \Omega \rightarrow \mathbb{R}$ are measurable with respect to $\Sigma$? Notice that $f$ can take at most $2$ values. If $f(\omega_1) = 1$ and $f(\omega_2) = 3$, then $f^{-1}(A) = \{\omega_1\}$ if $3 \notin A$, $1 \in A$ and $A$ is measurable. However, if $\Sigma = \{\emptyset, \Sigma\}$, even this function $f$ would not be measurable with respect to $\Sigma$. In fact, the only functions which are measurable with respect to the trivial $\sigma$-algebra are the constant ones. A measure places weights on the sets $E \in \Sigma$. This allows for a notion of approximation. Measures $\mu$ for which $\mu(A) = \inf\{\mu(O) : A \subset O, O \text{ open}\}$ are called outer regular . Measures for which $\mu(A) = \sup\{\mu(K) : K \subset A, K \text{ compact}\}$ are called inner regular . Borel measure on $\mathbb{R}$ is both inner and outer regular. Whether or not the measure is regular depends on the specific $\sigma$-algebra; simply being a $\sigma$-algebra is not sufficient. To summarise: the coarseness or fineness of the $\sigma$-algebra allows for lesser or greater complexity of functions. There is no notion of approximation of sets in $\Sigma$ at this level; either a set is or is not in $\Sigma$, and $f^{-1}(A) \notin \Sigma$ for some measurable $A$ then $\Sigma$ is not rich enough to "support" $f$. Measurability of a function $f$ is not related to the measure. The measure places weights on the $\sigma$ algebra. Whether or not it has certain approximation properties depends on the $\sigma$ algebra and the specific measure. EDIT. For concreteness, let us pass to the case$$f : \Omega \rightarrow \mathbb{R},$$where the image space $\mathbb{R}$ is equipped with the Borel $\sigma$ algebra $\mathcal{B}$ and Lebesgue measure $m$. For any measurable $A \in \mathcal{B}$, define$$f^{-1}(A) = \{\omega \in\Omega : f(\omega) \in A\}.$$ To first answer your questions, $f^{-1}([1/2, 3/2]) = \{\omega_1\}$, and $f^{-1}(A) = \emptyset$ if $1 \notin A$ and $3 \notin A$. This may seem strange, but it is exactly what the definition is telling you. What is the set of all $\omega \in \Omega$ such that $f(\omega) \in [1/2, 3/2]$? That set is the singleton $\{\omega_1\}$. This may be confusing because you are looking at a function which takes on finitely many values (2, in this case) on a continuous space. Hopefully what follows will help clarify this issue. Could you please explain why having a sigma-algebra structure on top of Ω is important in this context? This is a good question. One reason is that having a $\sigma$-algebra structure allows one to talk about sets of a complexity corresponding to the function in question, on an arbitrary space. To illustrate my point, consider the $f$ given by the picture below. Let us agree (despite my horrible picture) that $f : [0,4] \rightarrow \mathbb{R}$ is the function given by$$1\cdot 1_{\color{red}{A}}(x) + 3\cdot 1_{\color{blue}{B}}(x), \quad \color{red}{A} = [0,1) \cup [2,3), \color{blue}{B} = [1,2) \cup [3,4].$$Is $f$ so much different from the $f$ defined on $\Omega = \{\omega_1,\omega_2\}$? In some sense, yes -- the interval $[0,4]$ contains uncountably many points, while the whole space $\Omega$ only contains two. In another sense, no. The "complexity" of the function has changed little. The $\sigma$-algebra $\sigma(f)$ generated by $f$ is defined to be the smallest $\sigma$-algebra with respect to which $f$ is measurable. In this case, it turns out to be$$\sigma(f) = \{\emptyset, A, B, [0,4]\}.$$To see that this is a $\sigma$-algebra, observe that $A^c = B$, $A \cup B = [0,4]$, and $A \cap B = \emptyset$. Thus $A$ and $B$ play the role of $\{\omega_1\}$ and $\{\omega_2\}$ respectively. Is $f$ measurable with respect to this $\sigma$-algebra? Once again, the key is that $f$ takes on finitely many values . Thus $f^{-1}((1,3)) = \emptyset$, while $f^{-1}([1,3]) = [0,4].$ Any other sets can be checked by hand depending on whether or not $1, 3 \in A$. The thrust of this construction of measure is to make precise what you said: one classifies functions based on their domains, not on their images! Indeed. This is the difference between Lebesgue integration and Riemann integration. Whereas to compute$$\int_0^4 f(x) dx$$with a Riemann integral, Riemann would have you subdivide many rectangles in the domain needlessly. Instead it is the image space that we should be subdividing. There are only two divisions to be made: $\{\omega \in [0,4] : f(\omega) = 1\}$ and $\{\omega \in [0,4] : f(\omega) = 3\}$, which are $A$ and $B$ respectively. Thus,\begin{gather*}\int_0^4 f(x) dx = 1\cdot m(A) + 3\cdot m(B) = 1\cdot 2 + 3\cdot 2 = 8.\end{gather*}To come full circle, let us place a measure $\mu$ on $\{\omega_1,\omega_2\}$:\begin{align*}\mu(\{\omega_1\}) &= 2 \\\mu(\{\omega_2\}) &= 2.\end{align*}Then, with $\Omega = \{\omega_1,\omega_2\}$ and $f$ defined as in the original post (pre-edit),$$\int_\Omega f(\omega) d\mu(\omega) = 1\cdot\mu(\omega_1) + 3\cdot\mu(\omega_2) = 8.$$Observe that the two integrals are handled in essentially the exact same way, because Lebesgue integration and the language of $\sigma$-algebras (i.e., breaking a function $f$ up depending on its image , not its domain ) take into account the "complexity" of $f$ and adjust accordingly. Indeed, the Lebesgue integral is defined by the above procedure. In the case of a function that takes on infinitely many values, such as $f(x) = e^{-x^2}$, we first approximate $f$ in a suitable sense by a function which takes on only finitely many values (called a simple function) and then take limits.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1163098', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/210991/']}
jdg_378617
stackexchange
llm_judgeable_groundtruth_similarity
33794
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: This may be a silly question though I am unsure of this is the case for Hebrew. I know often the vowels are not shown in Hebrew in writing. Curious if it changes the words can be interpreted many ways or not. In English for example "rd" could be road, read, rude, rad, rod, etc. Is this also the case in Hebrew? Or does everyone reading understand what the word is, even without context clues. Now provide the response and nothing else.
While there can always be some ambiguity, Hebrew and other Semitic languages have a system of triconsonantal roots , in which each sequence of three consonants suggests the meaning of the word. For example, the root k-t-b, meaning "to write", is used to derive words like kāṯaḇti כתבתי "I wrote", kāṯaḇ כתב "he wrote", kattāḇ כתב "reporter" (m), kəṯāḇ כתב "handwriting", kəṯōḇeṯ כתובת "address", and kəṯīḇ כתיב "spelling" (m). As you can see, several of these have identical or very similar spelling, so there is some amount of guessing based on the context (the sentence "a reporter wrote about his handwriting": "כתב כתב על כתב ידו", has the word "כתב" repeated three times, but one can probably guess it's not saying "a handwriting reporter-ed about his wrote"), but as unlike in English, triconsonantal roots are an inherent part of Hebrew, some of the context is helped by recognizing the k-t-b root. To use your example, the reason "rd" wouldn't be as understandable in English is that the history of English vocabulary includes vowels and has many words with the same consonants, if English had had the same morphological system as Hebrew it's likely we'd have the root r-d connected to, say, the general meaning of "road", and words with an r-d root might include things like "road", "pavement", "asphalt", "carriage tracks", etc., while words like "read" or "rude" could be folded in under other roots with generalized meanings like "to read" or "to insult".
{}
{'log_upvote_score': 5, 'links': ['https://linguistics.stackexchange.com/questions/33794', 'https://linguistics.stackexchange.com', 'https://linguistics.stackexchange.com/users/26844/']}
jdg_378618
stackexchange
llm_judgeable_groundtruth_similarity
2685110
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: What is the result of linear transformation of the circle $L: |z-1|=1$ by $w = \dfrac{i} {z+2i}$? I don't have idea how to step up first on this problem. I have read some texts, but don't found any informations to solve this problems. Do you have any idea? At least giving me step to do. Now provide the response and nothing else.
Let $K$ be a field.As you have already mentioned, a matrix $A \in \operatorname{M}_n(K)$ is diagonalizable (over $K$) if and only if there exists a polynomial $f(t) \in K[t]$ with $f(A) = 0$ such that $f$ decomposes into pairwise different linear factors over $K$. For $A \in G$ and $n := |G|$ we have that $A^n = I$, so that $A$ satisfies the polynomial $f(t) := t^n - 1 \in \mathbb{k}[t]$.The polynomial $f(t)$ decomposes into linear factors because $\mathbb{k}$ is algebraically closed.It follows from $\operatorname{char}(\mathbb{k}) = 0$ that the polynomial $f$ is seperable (because $f(t) = t^n - 1$ and $f'(t) = n t^{n-1}$ are coprime), so that $f(t)$ decomposes into pairwise different linear factors.Thus $A$ is diagonalizable. (To see that $f(t)$ is seperable one can also embed $\mathbb{k}$ into $\mathbb{C}$ because $\mathbb{k}$ is an algebraic closure of $\mathbb{Q} \subseteq \mathbb{C}$.As the roots of unity in $\mathbb{C}$ are pairwise different, the same goes for $\mathbb{k}$.)
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2685110', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/517920/']}
jdg_378619
stackexchange
llm_judgeable_groundtruth_similarity
393919
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: My goal is to allow all users who are members of the "team" group to edit (r/w) the same set of remote files -- normal work collaboration -- using a local mount point. I have tried NFS and SSHFS using ACLs without success yet. Here I am trying to get SSHFS working by making the umask correct (which, in theory, should solve the problems I'm experiencing). Updated description of problem: user1, user2, and user3 all log into the same client computer. All are members of group "team". The client computer mounts a share via SSHFS. Client and server run Arch Linux (updated a couple days ago). The Client runs KDE desktop. The SSHFS mount is done via user3@sshfsrv with option allow_other. On the server, the shared directory has permissions user3 (owner) rwx and group (team) rwx, while other have r-x permissions. The gid sticky bit is set with chmod g+s . We removed all ACLs for the umask-focused configuration. First problem: user2 scans a document with XSane (a Gnome app) and attempts to save it in Shared1 directory, which is part of the SSHFS mount point. The save operation fails due to permissions. A 0 byte file is written. The permissions on that file are owner (user3) rw and group (team) read only (and other none). user2 can save the scanned document to their home directory. The terminal works as expected: In a terminal, user2 can touch a document in the Shared1 directory and the permissions are: -rw-rw---- 1 user3 team 6 Sep 23 19:41 deleteme6.txt We get the correct g+rw permissions. Note that ownership is user3 while this is user2 creating the file. In /etc/fstab, the mount is specified as: user3@sshfsrv:/home/common /home/common fuse.sshfs x-systemd.automount,_netdev,user,follow_symlinks,identityfile=/home/user3/.ssh/id_rsa,allow_other,default_permissions 0 0 In the terminal, and with a text editor (Kate in KDE), the users can collaborate on files that were created in Shared1 as expected. Any user in group "team" can create and save a file in Shared1 via nano text editor, and any other user in the group can edit / update it. Second problem: As a temporary workaround I tested saving the scanned images to user2's home directory, then moving them to the Shared1 directory using Dolphin File manager. Permissions errors prevent this, and sometimes it crashes Dolphin. I can show the same result by moving text files in the terminal: [user2@client2 Shared1]$ echo user2 > /home/user2/MoveMe/deleteme7.txt[user2@client2 Shared1]$ mv /home/user2/MoveMe/deleteme7.txt .mv: preserving times for './deleteme7.txt': Operation not permittedmv: preserving permissions for ‘./deleteme7.txt’: Operation not permitted The two errors above appear to be key to understanding the problem. If I change the mount specification to use user2@sshfsrv those errors go away for user2 but then user1 and user3 experience them. The only user that doesn't have the problem is the one used in the mount specification. (I had expected the allow_other mount option would prevent this, but it doesn't. Also using root in the mount specification doesn't seem to help.) Removing the mount option default_permissions eliminates these errors, but it also eliminates all permissions checking. Any user in any group can read and write files in Shared1, which does not meet our requirements. sftp-server umask setting: As sebasth says below, when sftp-server is used, the umask in /etc/profile or ~/.bashrc isn't used. I found that the following specification in /etc/ssh/sshd_config is a good solution for setting the umask: Subsystem sftp internal-sftp -u 0006 I do not want to use the umask mount option for sshfs (in /etc/fstab) as that does not give the desired behavior. Unfortunately, the above "-u" flag, while required, doesn't (yet) fully resolve my problem as described above. New Update: I have enabled pam_umask, but that alone doesn't resolve the issue. The above "-u" option is still required and I do not see that pam_umask adds anything additional that helps resolve this issue. Here are the configs currently used: /etc/pam.d/system-loginsession optional pam_umask.so/etc/login.defsUMASK 006 The Shared1 directory has these permissions, as shown from the server side. The gid sticky bit is set with chmod g+s . We removed all ACLs. All files within this directory have g+rw permissions. drwxrwsr-x 1 user3 team 7996 Sep 23 18:54 .# cat /etc/groupteam:x:50:user1,user2,user3 Both client and server are running OpenSSH_7.5p1, OpenSSL 1.1.0f dated 25 May 2017. This looks like the latest version. On the server, systemctl status sshd shows Main PID: 4853 (sshd). The main proc status shows a umask of 022. However, I will provide the process info for the sftp subsystem further below, which shows the correct umask of 006. # cat /proc/4853/statusName: sshdUmask: 0022State: S (sleeping)Tgid: 4853Ngid: 0Pid: 4853PPid: 1TracerPid: 0Uid: 0 0 0 0Gid: 0 0 0 0FDSize: 64Groups: NStgid: 4853NSpid: 4853NSpgid: 4853NSsid: 4853VmPeak: 47028 kBVmSize: 47028 kBVmLck: 0 kBVmPin: 0 kBVmHWM: 5644 kBVmRSS: 5644 kBRssAnon: 692 kBRssFile: 4952 kBRssShmem: 0 kBVmData: 752 kBVmStk: 132 kBVmExe: 744 kBVmLib: 6260 kBVmPTE: 120 kBVmPMD: 16 kBVmSwap: 0 kBHugetlbPages: 0 kBThreads: 1SigQ: 0/62965SigPnd: 0000000000000000ShdPnd: 0000000000000000SigBlk: 0000000000000000SigIgn: 0000000000001000SigCgt: 0000000180014005CapInh: 0000000000000000CapPrm: 0000003fffffffffCapEff: 0000003fffffffffCapBnd: 0000003fffffffffCapAmb: 0000000000000000Seccomp: 0Cpus_allowed: 3fCpus_allowed_list: 0-5Mems_allowed: 00000000,00000001Mems_allowed_list: 0voluntary_ctxt_switches: 25nonvoluntary_ctxt_switches: 2 We need to look at the sftp-server process for this client. It shows the expected umask of 006. I'm not sure if the GID is correct. 1002 is the GID for the user3 group. The directory specifies team group (GID 50) rwx. # ps ax | grep sftp*5112 ? Ss 0:00 sshd: user3@internal-sftp# cat /proc/5112/statusName: sshdUmask: 0006State: S (sleeping)Tgid: 5112Ngid: 0Pid: 5112PPid: 5111TracerPid: 0Uid: 1002 1002 1002 1002Gid: 1002 1002 1002 1002FDSize: 64Groups: 47 48 49 50 51 52 1002 NStgid: 5112NSpid: 5112NSpgid: 5112NSsid: 5112VmPeak: 85280 kBVmSize: 85276 kBVmLck: 0 kBVmPin: 0 kBVmHWM: 3640 kBVmRSS: 3640 kBRssAnon: 980 kBRssFile: 2660 kBRssShmem: 0 kBVmData: 1008 kBVmStk: 132 kBVmExe: 744 kBVmLib: 7352 kBVmPTE: 184 kBVmPMD: 12 kBVmSwap: 0 kBHugetlbPages: 0 kBThreads: 1SigQ: 0/62965SigPnd: 0000000000000000ShdPnd: 0000000000000000SigBlk: 0000000000000000SigIgn: 0000000000000000SigCgt: 0000000180010000CapInh: 0000000000000000CapPrm: 0000000000000000CapEff: 0000000000000000CapBnd: 0000003fffffffffCapAmb: 0000000000000000Seccomp: 0Cpus_allowed: 3fCpus_allowed_list: 0-5Mems_allowed: 00000000,00000001Mems_allowed_list: 0voluntary_ctxt_switches: 8nonvoluntary_ctxt_switches: 0 Original Question - can probably skip this after the above updates I am sharing the Shared1 directory from the SSHFS file server to various client machines. All machines use Arch Linux and BTRFS. pwck and grpck report no errors on both client and server. My goal is to allow all users in the team group to have rw permissions in the Shared1 directory. For unknown reasons, I am not able to achieve this goal. Some group members are experiencing permission denied errors (on write), as I will show below. What am I overlooking? (I have checked all the related questions on unix.stackexchange.com and I still did not resolve this issue.) Server: [user2@sshfsrv Shared1]$ cat /etc/profileumask 006[user2@sshfsrv Syncd]$ whoamiuser2[user2@sshfsrv Syncd]$ groupsteam user2[user2@sshfsrv Syncd]$ cat /etc/fuse.conf user_allow_other[root2@sshfsrv Syncd]# cat /proc/18940/statusName: sshdUmask: 0022 Note below that the setgid bit ( chmod g+s ) is initially set: [user1@sshfsrv Syncd]$ ls -latotal 0drwxrws--x 1 user1 limited 170 Aug 29 09:47 .drwxrwxr-x 1 user1 limited 10 Jul 9 14:10 ..drwxrwsr-x 1 user2 team 7892 Sep 22 17:21 Shared1[root@sshfsrv Syncd]# getfacl Shared1/# file: Shared1/# owner: user2# group: team# flags: -s-user::rwxgroup::rwxother::r-x[user2@sshfsrv Shared1]$ umask -Su=rwx,g=rx,o=x[user2@sshfsrv Shared1]$ sudo chmod g+w .[user2@sshfsrv Shared1]$ umask -Su=rwx,g=rx,o=x NOTE: Even after the above step, there are still no group write permissions. [user2@sshfsrv Shared1]$ touch deleteme2.txt[user2@sshfsrv Shared1]$ echo deleteme > deleteme2.txt [user2@sshfsrv Shared1]$ cat deleteme2.txt deleteme[user2@sshfsrv Shared1]$ ls -la deleteme2.txt -rw-r----- 1 user2 team 9 Sep 22 17:55 deleteme2.txt[user2@sshfsrv Shared1]$ getfacl .# file: .# owner: user2# group: team# flags: -s-user::rwxgroup::rwxother::r-x[root@sshfsrv Syncd]# chmod g-s Shared1/[root@sshfsrv Syncd]# ls -ladrwxrwxr-x 1 user2 team 7944 Sep 22 17:54 Shared1 Client [user2@client2 Shared1]$ cat /etc/fstabuser3@sshfsrv:/home/common /home/common fuse.sshfs x-systemd.automount,_netdev,user,follow_symlinks,identityfile=/home/user3/.ssh/id_rsa,allow_other,default_permissions 0 0[user2@client2 Shared1]$ cat /etc/profileumask 006[user2@client2 Shared1]$ cat /etc/fuse.conf user_allow_other[user2@client2 Shared1]$ groupsteam user2[user2@client2 Shared1]$ echo deleteme > deleteme2.txtbash: deleteme2.txt: Permission denied[user2@client2 Shared1]$ touch deleteme3.txttouch: setting times of 'deleteme3.txt': Permission denied[user2@client2 Shared1]$ ls -latotal 19520drwxrwsr-x 1 user2 team 7918 Sep 22 17:51 .drwxrws--x 1 user1 limited 170 Aug 29 09:47 ..-rw-r----- 1 user3 team 0 Sep 22 17:51 deleteme3.txt Now provide the response and nothing else.
The general solution is to add the following line to /etc/ssh/sshd_config on Arch Linux: Subsystem sftp internal-sftp -u 0002 However, the gotcha for me was that users of group "team" had a ForceCommand defined in that same config file. For these users, the ForceCommand was overriding the specification listed above. The solution was to add the same "-u" flag on the ForceCommand Match Group team ForceCommand internal-sftp -u 0002 Then run: systemctl restart sshd.service It is important to note that using the sshfs mount option umask is not recommended. It did not produce the desired behavior for me. References: The umask option for sshfs goes down to the underlying fuse layerwhere it's handled wrongly. afaict the advice is to avoid it. – RalphRönnquist Jun 17 '16 at 7:56 Understanding sshfs and umask https://jeff.robbins.ws/articles/setting-the-umask-for-sftp-transactions https://unix.stackexchange.com/a/289278/15010 EDIT: while this solution works on the command line and with some desktop apps (e.g., KDE's Kate text editor), it does not work correctly with many desktop applications (including KDE's Dolphin file manager, XSane, etc.). So this turned out not to be a good overall solution.
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/393919', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/15010/']}
jdg_378620
stackexchange
llm_judgeable_groundtruth_similarity
38586487
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 don't know what is the real name of what I want to do, but I would like to make a list similar as this website link (Standard Select part at the top) , does anyone can help me? I know it's something easy but I can't find what I want to do it for Xamarin. Maybe I don't search in the right direction, I assume it too! Now provide the response and nothing else.
Unfortunately, it isn't possible to do this anymore. As Brian Terlson (the editor of the EcmaScript Specification) wrote: issue with proxy enumerate trap and for-in, where iimplementations are prevented from pre-populating the list of keys in the object, because the iterator causes observable affects. Which means the iterate must be pulled for every iteration. Last meeting we thought it would be ok if the enumerate trap exhausts the iterator, we thought that would solve the problem. The issue was, now their is an observable difference between an object and proxy of that object, mainly due to delete. (Source: https://github.com/rwaldron/tc39-notes/blob/master/es7/2016-01/2016-01-28.md#5xix-proxy-enumerate---revisit-decision-to-exhaust-iterator via https://ecmascript-daily.github.io/2016/02/10/why-remove-enumerate-and-reflect-enumerate ) So it was removed due to technical challenges that could not be solved in a satisfactory manner. has proxy trap The in operator as such can still be captured using the has proxy trap : var p = new Proxy({}, { has: function(target, prop) { if (prop === 'a') { return true; } return false; }});'a' in p; // true'b' in p; // false Alternative As for (let key in proxy) loops are more of a legacy feature these days, you could use one of the following with the ownKeys proxy trap: Object.keys() (own enumerable properties only) Object.getOwnPropertyNames() (own properties) Reflect.ownKeys() (own properties and Symbols) (Source: https://twitter.com/nilssolanki/status/659839340592422912 ) (but you probably already knew that, seeing that you are working with proxies in the first place)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38586487', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6093604/']}
jdg_378621
stackexchange
llm_judgeable_groundtruth_similarity
1268009
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 "reset" the formatting in my RichTextBox (WinForms, not WPF). I was previously using richTextBox.Text = richTextBox.Text; However, that seems to have suddenly failed me. Now no matter what I set richTextBox.Text to, it retains some of the rtf formatting. I've tried richTextBox.Rtf = richTextBox.Text; However, that complains about an incorrect format. There's gotta be a better way to do this. (Of course, selecting the entire thing, then resetting the back color, fore color, and font works, but that results in a flicker as the entire thing is selected then deselected, plus it's slower and requires a lot more code.) Anyone have any idea? Edit:I've gotten this to work: string tempTxt = richTextBox.Text;richTextBox.Clear();richTextBox.Text = tempTxt; But there has to be a better way, right? Edit 2:To be clear, I wish to remove all formatting while retaining the text. It looks like the code in the first edit will ship, unless anyone else has a more efficient/better coding way. Edit 3: richTextBox.Text = richTextBox.Text.ToString(); doesn't seem to work because it still doesn't clear all the formatting. The reason I don't like the method in the first Edit above is it makes the text box "flash" when it clears it then re-inputs the text. It seems like there should simply be a richTextBox.ResetFormatting() method, or some way to access the same functionality, as the Clear() method clearly (no pun intended) does some sort of formatting reset in addition to simply clearing all the text. To summarize: Is there a way (and if so, what is it) to reset the formatting of the text in a RichTextBox without clearing the text as in the example above (because that produces undesirable flashing)? Now provide the response and nothing else.
Saddly I've done my VERY best effort to slim this down to only the required code. It's still big, but it will work. The RichTextBox api in .Net is very limited, to do anything you almost have to thunk into the Win32 library. I've built a entire library around this thing just so I can toggle bold and determine if bold is actually set across the selection. Usage: RichTextBox te = ...;te.ClearAllFormatting(new Font("Microsoft Sans Serif", 8.25f)); Tons of code: static class RichTextExtensions{ public static void ClearAllFormatting(this RichTextBox te, Font font) { CHARFORMAT2 fmt = new CHARFORMAT2(); fmt.cbSize = Marshal.SizeOf(fmt); fmt.dwMask = CFM_ALL2; fmt.dwEffects = CFE_AUTOCOLOR | CFE_AUTOBACKCOLOR; fmt.szFaceName = font.FontFamily.Name; double size = font.Size; size /= 72;//logical dpi (pixels per inch) size *= 1440.0;//twips per inch fmt.yHeight = (int)size;//165 fmt.yOffset = 0; fmt.crTextColor = 0; fmt.bCharSet = 1;// DEFAULT_CHARSET; fmt.bPitchAndFamily = 0;// DEFAULT_PITCH; fmt.wWeight = 400;// FW_NORMAL; fmt.sSpacing = 0; fmt.crBackColor = 0; //fmt.lcid = ??? fmt.dwMask &= ~CFM_LCID;//don't know how to get this... fmt.dwReserved = 0; fmt.sStyle = 0; fmt.wKerning = 0; fmt.bUnderlineType = 0; fmt.bAnimation = 0; fmt.bRevAuthor = 0; fmt.bReserved1 = 0; SendMessage(te.Handle, EM_SETCHARFORMAT, SCF_ALL, ref fmt); } private const UInt32 WM_USER = 0x0400; private const UInt32 EM_GETCHARFORMAT = (WM_USER + 58); private const UInt32 EM_SETCHARFORMAT = (WM_USER + 68); private const UInt32 SCF_ALL = 0x0004; private const UInt32 SCF_SELECTION = 0x0001; [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)] static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, UInt32 wParam, ref CHARFORMAT2 lParam); [StructLayout(LayoutKind.Sequential, Pack = 4, CharSet = CharSet.Auto)] struct CHARFORMAT2 { public int cbSize; public uint dwMask; public uint dwEffects; public int yHeight; public int yOffset; public int crTextColor; public byte bCharSet; public byte bPitchAndFamily; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string szFaceName; public short wWeight; public short sSpacing; public int crBackColor; public int lcid; public int dwReserved; public short sStyle; public short wKerning; public byte bUnderlineType; public byte bAnimation; public byte bRevAuthor; public byte bReserved1; } #region CFE_ // CHARFORMAT effects const UInt32 CFE_BOLD = 0x0001; const UInt32 CFE_ITALIC = 0x0002; const UInt32 CFE_UNDERLINE = 0x0004; const UInt32 CFE_STRIKEOUT = 0x0008; const UInt32 CFE_PROTECTED = 0x0010; const UInt32 CFE_LINK = 0x0020; const UInt32 CFE_AUTOCOLOR = 0x40000000; // NOTE: this corresponds to // CFM_COLOR, which controls it // Masks and effects defined for CHARFORMAT2 -- an (*) indicates // that the data is stored by RichEdit 2.0/3.0, but not displayed const UInt32 CFE_SMALLCAPS = CFM_SMALLCAPS; const UInt32 CFE_ALLCAPS = CFM_ALLCAPS; const UInt32 CFE_HIDDEN = CFM_HIDDEN; const UInt32 CFE_OUTLINE = CFM_OUTLINE; const UInt32 CFE_SHADOW = CFM_SHADOW; const UInt32 CFE_EMBOSS = CFM_EMBOSS; const UInt32 CFE_IMPRINT = CFM_IMPRINT; const UInt32 CFE_DISABLED = CFM_DISABLED; const UInt32 CFE_REVISED = CFM_REVISED; // CFE_AUTOCOLOR and CFE_AUTOBACKCOLOR correspond to CFM_COLOR and // CFM_BACKCOLOR, respectively, which control them const UInt32 CFE_AUTOBACKCOLOR = CFM_BACKCOLOR; #endregion #region CFM_ // CHARFORMAT masks const UInt32 CFM_BOLD = 0x00000001; const UInt32 CFM_ITALIC = 0x00000002; const UInt32 CFM_UNDERLINE = 0x00000004; const UInt32 CFM_STRIKEOUT = 0x00000008; const UInt32 CFM_PROTECTED = 0x00000010; const UInt32 CFM_LINK = 0x00000020; // Exchange hyperlink extension const UInt32 CFM_SIZE = 0x80000000; const UInt32 CFM_COLOR = 0x40000000; const UInt32 CFM_FACE = 0x20000000; const UInt32 CFM_OFFSET = 0x10000000; const UInt32 CFM_CHARSET = 0x08000000; const UInt32 CFM_SMALLCAPS = 0x0040; // (*) const UInt32 CFM_ALLCAPS = 0x0080; // Displayed by 3.0 const UInt32 CFM_HIDDEN = 0x0100; // Hidden by 3.0 const UInt32 CFM_OUTLINE = 0x0200; // (*) const UInt32 CFM_SHADOW = 0x0400; // (*) const UInt32 CFM_EMBOSS = 0x0800; // (*) const UInt32 CFM_IMPRINT = 0x1000; // (*) const UInt32 CFM_DISABLED = 0x2000; const UInt32 CFM_REVISED = 0x4000; const UInt32 CFM_BACKCOLOR = 0x04000000; const UInt32 CFM_LCID = 0x02000000; const UInt32 CFM_UNDERLINETYPE = 0x00800000; // Many displayed by 3.0 const UInt32 CFM_WEIGHT = 0x00400000; const UInt32 CFM_SPACING = 0x00200000; // Displayed by 3.0 const UInt32 CFM_KERNING = 0x00100000; // (*) const UInt32 CFM_STYLE = 0x00080000; // (*) const UInt32 CFM_ANIMATION = 0x00040000; // (*) const UInt32 CFM_REVAUTHOR = 0x00008000; const UInt32 CFE_SUBSCRIPT = 0x00010000; // Superscript and subscript are const UInt32 CFE_SUPERSCRIPT = 0x00020000; // mutually exclusive const UInt32 CFM_SUBSCRIPT = (CFE_SUBSCRIPT | CFE_SUPERSCRIPT); const UInt32 CFM_SUPERSCRIPT = CFM_SUBSCRIPT; // CHARFORMAT "ALL" masks const UInt32 CFM_EFFECTS = (CFM_BOLD | CFM_ITALIC | CFM_UNDERLINE | CFM_COLOR | CFM_STRIKEOUT | CFE_PROTECTED | CFM_LINK); const UInt32 CFM_ALL = (CFM_EFFECTS | CFM_SIZE | CFM_FACE | CFM_OFFSET | CFM_CHARSET); const UInt32 CFM_EFFECTS2 = (CFM_EFFECTS | CFM_DISABLED | CFM_SMALLCAPS | CFM_ALLCAPS | CFM_HIDDEN | CFM_OUTLINE | CFM_SHADOW | CFM_EMBOSS | CFM_IMPRINT | CFM_DISABLED | CFM_REVISED | CFM_SUBSCRIPT | CFM_SUPERSCRIPT | CFM_BACKCOLOR); const UInt32 CFM_ALL2 = (CFM_ALL | CFM_EFFECTS2 | CFM_BACKCOLOR | CFM_LCID | CFM_UNDERLINETYPE | CFM_WEIGHT | CFM_REVAUTHOR | CFM_SPACING | CFM_KERNING | CFM_STYLE | CFM_ANIMATION); #endregion} More you ask? I use most of this via a small utility class that wraps this for all the styles and font changes. This way you can change font-size and not change font name, etc. class RichTextStyle{ private readonly Control _textEdit; private readonly CHARFORMAT2 _charFormat; public RichTextStyle(RichTextBox te) { _textEdit = te; _charFormat = new CHARFORMAT2(); _charFormat.cbSize = Marshal.SizeOf(_charFormat); SendMessage(te.Handle, EM_GETCHARFORMAT, SCF_SELECTION, ref _charFormat); } private void SetEffect(UInt32 mask, UInt32 effect, bool valid) { CHARFORMAT2 fmt = new CHARFORMAT2(); fmt.cbSize = Marshal.SizeOf(fmt); fmt.dwMask = mask; fmt.dwEffects = valid ? effect : 0; SendMessage(_textEdit.Handle, EM_SETCHARFORMAT, SCF_SELECTION, ref fmt); } private bool GetEffect(UInt32 mask, UInt32 effect) { return (0 != (_charFormat.dwMask & mask)) && (0 != (_charFormat.dwEffects & effect)); } public bool Bold { get { return GetEffect(CFM_BOLD, CFE_BOLD); } set { SetEffect(CFM_BOLD, CFE_BOLD, value); } } public bool Italic { get { return GetEffect(CFM_ITALIC, CFE_ITALIC); } set { SetEffect(CFM_ITALIC, CFE_ITALIC, value); } } // ... etc ... etc ... you get the idea.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1268009', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/134502/']}
jdg_378622
stackexchange
llm_judgeable_groundtruth_similarity
20220758
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 used a custom adapter for populating my Spinner. I have overriden getDropDownView from which I return the view of each row of the dropdown list. Everything works fine except the dropdown list rendered is not getting the width of the Spinner widget. Rather it gets Like this: So the dropdown list is missing the highlighted width. I dont know why this is happening. I want it to get the full width of the spinner. My custom adapter: class CategorySpinnerAdapter extends ArrayAdapter{ private Activity context; ArrayList<Category> categoryList; public CategorySpinnerAdapter(Activity context,int resourceID,ArrayList<Category> categoryList) { super(context,resourceID,categoryList); this.context=context; this.categoryList=categoryList; } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub if(convertView==null) { LayoutInflater inflater=context.getLayoutInflater(); convertView=inflater.inflate(R.layout.category_spinner_row, parent,false); } Category currentCategory=categoryList.get(position); TextView categoryText=(TextView) convertView.findViewById(R.id.spinnerText); categoryText.setText(currentCategory.getCategoryName()); return convertView; } } Code, where I am setting this adapter: Spinner categorySpinner=(Spinner) getActivity().findViewById(R.id.categorySpinner); ArrayList<Category> categoryList=populateCategoryList(); CategorySpinnerAdapter categorySpinnerAdapter=new CategorySpinnerAdapter(getActivity(), android.R.layout.simple_spinner_item,categoryList); categorySpinner.setAdapter(categorySpinnerAdapter); categorySpinner.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) { // TODO Auto-generated method stub ArrayList<Reward> modifiedList=new ArrayList<Reward>(); //test case: category OK int categoryID=position+1; for(int i=0;i<rewardList.size();i++) { if(rewardList.get(i).getCategoryID()==categoryID) { modifiedList.add(rewardList.get(i)); } } adapter.changeDataSet(modifiedList); } @Override public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub //get default ELECTRONICS category 1 data to populate the list ArrayList<Reward> defaultCategorizedList=new ArrayList<Reward>(); //test case: category OK for(int i=0;i<rewardList.size();i++) { if(rewardList.get(i).getCategoryID()==1) { defaultCategorizedList.add(rewardList.get(i)); } } } }); Declaration of the Spinner Item inside the main xml: <Spinner android:id="@+id/categorySpinner" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/customerRewardPointsTextView" android:background="@drawable/btn_dropdown" android:spinnerMode="dropdown" /> layout for the dropdown items, category_spinner_row.xml: <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/category_spinner_background" > <TextView android:id="@+id/spinnerText" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:ellipsize="marquee" android:gravity="center" android:singleLine="true" /></RelativeLayout> How can I fix this issue ? Now provide the response and nothing else.
You can append this function liberally to your Rx operators while you are developing them to see what's happening: public static IObservable<T> Spy<T>(this IObservable<T> source, string opName = null) { opName = opName ?? "IObservable"; Console.WriteLine("{0}: Observable obtained on Thread: {1}", opName, Thread.CurrentThread.ManagedThreadId); return Observable.Create<T>(obs => { Console.WriteLine("{0}: Subscribed to on Thread: {1}", opName, Thread.CurrentThread.ManagedThreadId); try { var subscription = source .Do(x => Console.WriteLine("{0}: OnNext({1}) on Thread: {2}", opName, x, Thread.CurrentThread.ManagedThreadId), ex => Console.WriteLine("{0}: OnError({1}) on Thread: {2}", opName, ex, Thread.CurrentThread.ManagedThreadId), () => Console.WriteLine("{0}: OnCompleted() on Thread: {1}", opName, Thread.CurrentThread.ManagedThreadId) ) .Subscribe(obs); return new CompositeDisposable( subscription, Disposable.Create(() => Console.WriteLine( "{0}: Cleaned up on Thread: {1}", opName, Thread.CurrentThread.ManagedThreadId))); } finally { Console.WriteLine("{0}: Subscription completed.", opName); } }); } Here's an example usage, shows a subtle behaviour difference of Range : Observable.Range(0, 1).Spy("Range").Subscribe(); Gives the output: Range: Observable obtained on Thread: 7Range: Subscribed to on Thread: 7Range: Subscription completed.Range: OnNext(0) on Thread: 7Range: OnCompleted() on Thread: 7Range: Cleaned up on Thread: 7 But this: Observable.Range(0, 1, Scheduler.Immediate).Spy("Range").Subscribe(); Gives the output: Range: Observable obtained on Thread: 7Range: Subscribed to on Thread: 7Range: OnNext(0) on Thread: 7Range: OnCompleted() on Thread: 7Range: Subscription completed.Range: Cleaned up on Thread: 7 Spot the difference? Obviously you can alter this to write to logs or to Debug, or use preprocessor directives to do a lean pass-through subscription on a Release build etc... You can apply Spy throughout a chain of operators. e.g.: Observable.Range(0,3).Spy("Range") .Scan((acc, i) => acc + i).Spy("Scan").Subscribe(); Gives the output: Range: Observable obtained on Thread: 7Scan: Observable obtained on Thread: 7Scan: Subscribed to on Thread: 7Range: Subscribed to on Thread: 7Range: Subscription completed.Scan: Subscription completed.Range: OnNext(1) on Thread: 7Scan: OnNext(1) on Thread: 7Range: OnNext(2) on Thread: 7Scan: OnNext(3) on Thread: 7Range: OnCompleted() on Thread: 7Scan: OnCompleted() on Thread: 7Range: Cleaned up on Thread: 7Scan: Cleaned up on Thread: 7 I'm sure you can find ways of enriching this to suit your purposes.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/20220758', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1096516/']}
jdg_378623
stackexchange
llm_judgeable_groundtruth_similarity
2816293
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm having a problem with optional function parameter in C++ What I'm trying to do is to write function with optional parameter which is passed by reference, so that I can use it in two ways (1) and (2), but on (2) I don't really care what is the value of mFoobar . I've tried such a code: void foo(double &bar, double &foobar = NULL){ bar = 100; foobar = 150;}int main(){ double mBar(0),mFoobar(0); foo(mBar,mFoobar); // (1) cout << mBar << mFoobar; mBar = 0; mFoobar = 0; foo(mBar); // (2) cout << mBar << mFoobar; return 0;} but it crashes at void foo(double &bar, double &foobar = NULL) with message : error: default argument for 'double& foobar' has type 'int' Is it possible to solve it without function overloading? Now provide the response and nothing else.
The default argument of a (mutable) reference must be an l-value. The best I can think of, without overloading, is static double _dummy_foobar;void foo(double &bar, double &foobar = _dummy_foobar)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2816293', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/32312/']}
jdg_378624
stackexchange
llm_judgeable_groundtruth_similarity
922858
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Here's the thing: object[] arrayText = new object[1];if (arrayText[1] == null){ MessageBox.Show("Is null");} We know that is going to be null, but it throws an exception, but I don't want to handle it in a try/catch block because that is nested in a loop and try/catch will slow it down, also it doesn't look really good: object[] arrayText = new object[1];try{ if (arrayText[1] == null) { }}catch (Exception ex){ MessageBox.Show("Is null");} Thanks for you suggestions! Now provide the response and nothing else.
null is not the problem here, but the index is invalid. Arrays in C# are 0-based, so if you create an array with 1 element, only index 0 is valid: array[0] == null You can avoid that by checking the bounds manually before accessing the index: if (index < array.Length) { // access array[index] here} else { // no exception, this is the "invalid" case}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/922858', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/62642/']}
jdg_378625
stackexchange
llm_judgeable_groundtruth_similarity
19104
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: There are Linux programs, for example vlc, that recommend typing ctrl + c twice to kill their execution from a terminal if the program didn't stop after the first one. Why would typing ctrl + c twice work when the first time didn't work? Now provide the response and nothing else.
What it does is entirely application specific. When you press ctrl + c , the terminal emulator sends a SIGINT signal to the foreground application, which triggers the appropriate "signal handler". The default signal handler for SIGINT terminates the application. But any program can install its own signal handler for SIGINT (including a signal handler that does not stop the execution at all). Apparently, vlc installs a signal handler that attempts to do some cleanup / graceful termination upon the first time it is invoked, and falls back to the default behavior of instantly terminating execution when it is invoked for a second time.
{}
{'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/19104', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/8667/']}
jdg_378626
stackexchange
llm_judgeable_groundtruth_similarity
14985518
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 track and log users/visitors that are accessing my website using PHP's $_SERVER['REMOTE_ADDR'] to do so. A typical method for IP address tracking in PHP. However, I am using CloudFlare for caching and such and receiving their IP addresses as CloudFlare's: 108.162.212.* - 108.162.239.* What would be a correct method of retrieving the actual users/visitors IP address while still using CloudFlare? Now provide the response and nothing else.
Extra server variables that are available to cloud flare are: $_SERVER["HTTP_CF_CONNECTING_IP"] real visitor ip address, this is what you want $_SERVER["HTTP_CF_IPCOUNTRY"] country of visitor $_SERVER["HTTP_CF_RAY"] $_SERVER["HTTP_CF_VISITOR"] this can help you know if its http or https you can use it like this: if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) { $_SERVER['REMOTE_ADDR'] = $_SERVER["HTTP_CF_CONNECTING_IP"];} If you do this, and the validity of the visiting IP address is important, you might need to verify that the $_SERVER["REMOTE_ADDR"] contains an actual valid cloudflare IP address, because anyone can fake the header if he was able to connect directly to the server IP.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/14985518', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1804013/']}
jdg_378627
stackexchange
llm_judgeable_groundtruth_similarity
14665234
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Using argparse in relation to Python dependencies between groups using argparse , I have an argument part of some parser group of a parser - for example: group_simulate.add_argument('-P', help='simulate FC port down', nargs=1, metavar='fc_port_name', dest='simulate') How it's possible to use the choices to limit the choices to a list of parameters of the next structure: 1:m:"number between 1 and 10":p:"number between 1 and 4" I have tried to use the range option but I couldn't find a way to create a list of choices that are acceptable examples:legal parameters: test.py -P 1:m:4:p:2 not legal parameters: test.py -P 1:p:2test.py -P abvds Thank you very much for the help guys! Now provide the response and nothing else.
You can define a custom type that will raise an argparse.ArgumentTypeError if the stringdoesn't match the format you need. def SpecialString(v): fields = v.split(":") # Raise a value error for any part of the string # that doesn't match your specification. Make as many # checks as you need. I've only included a couple here # as examples. if len(fields) != 5: raise argparse.ArgumentTypeError("String must have 5 fields") elif not (1 <= int(fields[2]) <= 10): raise argparse.ArgumentTypeError("Field 3 must be between 1 and 10, inclusive") else: # If all the checks pass, just return the string as is return vgroup_simulate.add_argument('-P', type=SpecialString, help='simulate FC port down', nargs=1, metavar='fc_port_name', dest='simulate') UPDATE: here's a full custom type to check the value. All checking is donein the regular expression, although it only gives one generic error messageif any part is wrong. def SpecialString(v): import re # Unless you've already imported re previously try: return re.match("^1:m:([1-9]|10):p:(1|2|3|4)$", v).group(0) except: raise argparse.ArgumentTypeError("String '%s' does not match required format"%(v,))
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14665234', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2034967/']}
jdg_378628
stackexchange
llm_judgeable_groundtruth_similarity
18371090
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 make the ActionBar in the support library fully transparent, however, it seems that changing the background drawable won't suffice since the backgrounds stack. If you put a semi-transparent background you end up with the default background behind it. Does anyone know a way to remove that background? This is what happens: The code for the background drawable: <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <solid android:color="#66336688"/></shape> As you can see, the drawable has a transparent blue that overlaps with the default gray background. Now provide the response and nothing else.
Ok, I found the solution messing around with the SDK.It seems that it is pretty simple, you need to do 3 things: Create a background drawable as shown on my question. Create an ActionBar style like so: <!-- Application theme. --><style name="AppTheme" parent="Theme.AppCompat.Light"> <item name="android:actionBarStyle">@style/MyActionBar</item> <!-- Support library compatibility --> <item name="actionBarStyle">@style/MyActionBar</item></style><!-- ACTION BAR STYLES --><style name="MyActionBar" parent="@style/Widget.AppCompat.ActionBar"> <item name="android:background">@drawable/actionbar_background</item> <item name="android:windowActionBarOverlay">true</item> <!-- Support library compatibility --> <item name="background">@drawable/actionbar_background</item> <item name="windowActionBarOverlay">true</item></style> Use the Window feature for ActionBar overlay using the Support method (ignore Eclipse's warning regarding API level for the constant; I used the SuppressLint annotation to remove the warning): @SuppressLint("InlinedApi") @Override protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);supportRequestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);setContentView(R.layout.activity_home);}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18371090', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2442389/']}
jdg_378629
stackexchange
llm_judgeable_groundtruth_similarity
30594917
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 tried providing getters of class A for my non-member serialize() function` since accessing from members is private. template<typename T>class A{public: A(const T& id) : m_id(id) {} T& getRef() { return m_id; } // not giving good results T getId() { return m_id; } // not giving good results const T& getRef() const { return m_id; } // not giving good resultsprivate: // I would like to keep it private T m_id;}namespace boost { namespace serialization {template<class Archive,typename T>void serialize(Archive &ar, A &a, const unsigned int version){ // ar &BOOST_SERIALIZATION_NVP(a.m_id); // I would like to avoid that it works if m_id is public ar &BOOST_SERIALIZATION_NVP(a.GetRef()); // I want this !}}}// and later I usestd::ofstream ofs("test.xml");boost::archive::xml_oarchive oa(ofs);A<int> a(42);oa << BOOST_SERIALIZATION_NVP(a); Unfortunately the execution keeps telling me uncaught exception of type boost::archive::xml_archive_exception - Invalid XML tag name when I try to use getters either GetRef() or GetId() . It works well if I access directly to m_id when it is public. Are there any nice ways of doing so ? Now provide the response and nothing else.
You can use good old-fashioned friends: Live On Coliru template <typename T>class A { public: A(const T &id) : m_id(id) {} private: template <typename Ar, typename U> friend void boost::serialization::serialize(Ar&,A<U>&,const unsigned); T m_id;};namespace boost {namespace serialization { template <class Archive, typename T> void serialize(Archive &ar, A<T> &a, const unsigned int) { ar & BOOST_SERIALIZATION_NVP(a.m_id); }}} You can use the getRef() approach. This requires no friends (less intrusive) requires make_nvp (because you can't use a.getRef() as an XML element name Sadly, having the reference getter break encapsulation in a horrific way. I'd personally prefer to have m_id public in the first place, instead. Live On Coliru template <typename T>class A {public: A(const T &id) : m_id(id) {} T& getRef() { return m_id; } T const& getRef() const { return m_id; } private: T m_id;};namespace boost {namespace serialization { template <class Archive, typename T> void serialize(Archive &ar, A<T> &a, const unsigned int) { ar & boost::serialization::make_nvp("m_id", a.getRef()); }}} Bonus points: You can use a 'pimpl' style struct. You can forward declare a struct inside A<> : template <typename T>class A {public: struct access; A(const T &id) : m_id(id) {}private: T m_id;}; That's less intrusive than the getRef() approach which simply breaks encapsulation all the way. Now, you can hide the private access inside this class: namespace boost {namespace serialization { template <class Archive, typename T> void serialize(Archive &ar, A<T> &a, const unsigned int version) { A<T>::access::serialize(ar, a, version); }}} Of course you still need to implement it, but this can be done in a separate header and doesn't influence class A<> (or any of its specializations) at all: template <typename T>struct A<T>::access { template <class Archive> static void serialize(Archive &ar, A<T> &a, const unsigned int) { ar & BOOST_SERIALIZATION_NVP(a.m_id); }}; See it Live On Coliru as well
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30594917', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2352158/']}
jdg_378630
stackexchange
llm_judgeable_groundtruth_similarity
121305
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: By "solitaire", let us mean Klondike solitaire of the form "Draw 3 cards, Re-Deal infinite". What is the probability that a solitaire game be winnable? Or equivalently, what is the number of solvable games ? When I came up with the question, it seemed a pretty reasonable thing to ask, and I thought "surely it must have been answered". I have no probability formation (save for an introductory undergraduate-level course), but anyway I started thinking on how could the problem be tackled. Immediately my interest shifted from the answer to the above question, to the methods involved in answering it. I couldn't even begin to figure out how would one go solving this problem! How does one even begin to find the number of solvable games? In the same wikipedia link, it is stated that For a "standard" game of Klondike (of the form: Draw 3, Re-Deal Infinite, Win 52) the number of solvable games (assuming all cards are known) is between 82-91.5%. The number of unplayable games is 0.25% and the number of games that cannot be won is between 8.5-18%. The reference for the thresholds is this paper by Ronald Bjarnason, Prasad Tadepalli and Alan Fern. It came as a surprise to me that the answer is not really known, and that there are only estimates. I tried reading the paper, but I'm too far away from those lines of thinking to understand what they're talking about. There seems to be some programming going around, but what is the big idea behind their approach to the question? I would like to end this question with a couple of lines from the paper (emphasis by me): Klondike Solitaire has become an almost ubiquitous computer application, available to hundreds of millions of users worldwide on all major operating systems, yet theoreticians have struggled with this game, referring to the inability to calculate the odds of winning a randomly dealt game as “ one of the embarrassments of applied mathematics ” (Yan et al., 2005). Now provide the response and nothing else.
The numbers you quote are for "Thoughtful Solitaire", i.e. Klondike Solitare where the positions of all 52 cards are known. So in theory it might be possible to look at all $52!\approx 8 \times 10^{67}$ permutations of the cards and for each one (or for a eighth of them, taking account of the equivalence of suits) see whether it is possible to solve that case or not with any of the many combinations of choices by looking at every combination of choices. In practice neither of those two options are practical. To deal with the excessive number of permutations, one approach would be to take a random sample and to use statistical techniques to provide steadily narrowing confidence intervals around the estimates as the sample gets bigger. To deal with the excessive number of choices, you can apply heuristics which provide good methods for taking decisions without investigating every final result. Doing this trims the decision tree and so shortens the time needed to investigate different possibilities. But even then, the consequences of different decisions in the game can sometimes have such far reaching and complicated consequences that not all initial permutations can be found to be solvable or not within a reasonable time. Ignoring those which do not produce a result quickly enough leads to the wide reported range for the probability.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/121305', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/2614/']}
jdg_378631
stackexchange
llm_judgeable_groundtruth_similarity
3211108
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 couple of questions regarding MySQL indexing: 1) Is there any speed increase when indexing a table stored in memory? 2) When searching my table I match on column field, would indexing every column defeat the purpose of an index? Many thanks. Now provide the response and nothing else.
Indexing any table, either memory or file system based, will speed up queries that select or sort results based on that column. This is because the index works like a tree structure and the search distance depends on the depth of the tree, which increases a lot slower than the row count of the column (logarithmic). Indexing every column does not defeat the purpose of the index, but it will slow up inserts and updates because those changes will cause an update of every index of that table. Also, the indexes take up space on the database server, so that is another drawback to be considered. Other SO questions to read relating to this question: Best practices for indexing What is an index How many indexes are enough
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3211108', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/377945/']}
jdg_378632
stackexchange
llm_judgeable_groundtruth_similarity
12633903
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 using tasks for large/long running workloads that I need to be able to cancel I often use a template similar to this for the action the task executes: public void DoWork(CancellationToken cancelToken){ try { //do work cancelToken.ThrowIfCancellationRequested(); //more work } catch (OperationCanceledException) { throw; } catch (Exception ex) { Log.Exception(ex); throw; }} The OperationCanceledException should not be logged as an error but must not be swallowed if the task is to transition into the cancelled state. Any other exceptions do not need to be dealt with beyond the scope of this method. This always felt a bit clunky, and visual studio by default will break on the throw for OperationCanceledException (though I have 'break on User-unhandled' turned off now for OperationCanceledException because of my use of this pattern). UPDATE: It's 2021 and C#9 gives me the syntax I always wanted: public void DoWork(CancellationToken cancelToken){ try { //do work cancelToken.ThrowIfCancellationRequested(); //more work } catch (Exception ex) when (ex is not OperationCanceledException) { Log.Exception(ex); throw; }} Ideally I think I'd like to be able to do something like this: public void DoWork(CancellationToken cancelToken){ try { //do work cancelToken.ThrowIfCancellationRequested(); //more work } catch (Exception ex) exclude (OperationCanceledException) { Log.Exception(ex); throw; }} i.e. have some sort of exclusion list applied to the catch but without language support that is not currently possible (@eric-lippert: c# vNext feature :)). Another way would be through a continuation: public void StartWork(){ Task.Factory.StartNew(() => DoWork(cancellationSource.Token), cancellationSource.Token) .ContinueWith(t => Log.Exception(t.Exception.InnerException), TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously);}public void DoWork(CancellationToken cancelToken){ //do work cancelToken.ThrowIfCancellationRequested(); //more work} but I don't really like that as the exception technically could have more than a single inner exception and you don't have as much context while logging the exception as you would in the first example (if I was doing more than just logging it). I understand this is a bit of a question of style, but wondering if anyone has any better suggestions? Do I just have to stick with example 1? Now provide the response and nothing else.
So, what's the problem? Just throw away catch (OperationCanceledException) block, and set proper continuations: var cts = new CancellationTokenSource();var task = Task.Factory.StartNew(() => { var i = 0; try { while (true) { Thread.Sleep(1000); cts.Token.ThrowIfCancellationRequested(); i++; if (i > 5) throw new InvalidOperationException(); } } catch { Console.WriteLine("i = {0}", i); throw; } }, cts.Token);task.ContinueWith(t => Console.WriteLine("{0} with {1}: {2}", t.Status, t.Exception.InnerExceptions[0].GetType(), t.Exception.InnerExceptions[0].Message ), TaskContinuationOptions.OnlyOnFaulted);task.ContinueWith(t => Console.WriteLine(t.Status), TaskContinuationOptions.OnlyOnCanceled);Console.ReadLine();cts.Cancel();Console.ReadLine(); TPL distinguishes cancellation and fault. Hence, cancellation (i.e. throwing OperationCancelledException within task body) is not a fault . The main point: do not handle exceptions within task body without re-throwing them.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12633903', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/718033/']}
jdg_378633
stackexchange
llm_judgeable_groundtruth_similarity
32423401
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 set up a form in Django and save the data to my database, without using a ModelForm. My form is working, but the part I am stuck on is how to process the form data and save it within the view. As you can see, after 'if form.is_valid():' I am stuck and cannot think of the right code. # models.pyfrom django.db import modelsclass Listing(models.Model): business_name = models.CharField(max_length=80) business_email = models.EmailField() business_website = models.CharField(max_length=80) business_phone = models.CharField(max_length=80)# forms.pyfrom django import formsclass NewBusinessForm(forms.Form): business_name = forms.CharField(label='Business Name', max_length=100) business_phone = forms.CharField(label='Phone Number', max_length=100) business_email = forms.EmailField(label='Email Address', max_length=100) business_website = forms.CharField(label='Web Site', max_length=100)# views.pyfrom django.shortcuts import renderfrom django.http import HttpResponseRedirectfrom .forms import NewBusinessFormdef new_business(request): if request.method == 'POST': form = NewBusinessForm(request.POST) if form.is_valid(): # process form data return HttpResponseRedirect('/') else: form = NewBusinessForm() return render(request, 'directory/new.html', {'form': form}) Now provide the response and nothing else.
You need to create the object and set all fields manually. Here is an example. def new_business(request): if request.method == 'POST': form = NewBusinessForm(request.POST) if form.is_valid(): # process form data obj = Listing() #gets new object obj.business_name = form.cleaned_data['business_name'] obj.business_email = form.cleaned_data['business_email'] obj.business_phone = form.cleaned_data['business_phone'] obj.business_website = form.cleaned_data['business_website'] #finally save the object in db obj.save() return HttpResponseRedirect('/') .... Note that saving object may fail if field values do not follow the constraint. So you need to take care of that.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/32423401', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/827174/']}
jdg_378634
stackexchange
llm_judgeable_groundtruth_similarity
34632067
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The following is a piece of code from the begining of a program that I am writing (which contains an error). char *name; char *name2; if (argn != 2) { printf("You have to enter the name of the input file"); return 1; } name = malloc(strlen(arg[1]) + 1); name2 = malloc(strlen(arg[1]) + 1); strcpy(name, arg[1]); strcpy(name2, arg[1]); strcat(name2, "-results.pdb"); There is an error here which is with strcat , indeed name2 does not have enough size to carry out the operation above. Yet strcat executes without a problem.However later on in a completely unrelated part of the program an operation with another array that has been initialized after this strcat gives an error.It is an integer array for which I am assigning values to its elements and it gives an error before I can assign all the values. I am assuming that since there is not enough memory in name2 for the operation above this "somehow" affects the next arrays that are initialized. I would like to understand: 1- What is likely happening here so that the extra information that could not be written to name2 affects other arrays declared later? 2- I probably wouldn't be able to backtrace this problem so easily in a more complicated program since error occurs elsewhere rather than in strcat. How can I prevent this kind of sneaky errors like a memory problematic process affecting totally unrelated arrays elsewhere? Now provide the response and nothing else.
Yet strcat executes without a problem. No it doesn't. It returns, but it has planted a time bomb. As you observe later on. What happens is undefined behavior . You have written to memory you were not allowed to write. Whatever was stored there is now garbage and whatever code expects to find meaningful values there is now misbehaving.Especially if malloc internal data was corrupted the observation is random crashes when attempting to realloc or free memory later. The correct way is to allocate the memory with name2 = malloc(strlen(arg[1]) + sizeof "-results.pdb"); This takes care of the "+1" for the terminating NUL, since sizeof "-results.pdb" is 13. Even easier is using asprintf (not ISO C but available on any contemporary Unix), which allocates the memory as needed: asprintf(&name2, "%s-results.psb", arg[1]); There! No strlen, no strcat, no sizeof, no malloc. Just an all-in-one call doing the Right Thing TM .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34632067', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1862919/']}
jdg_378635
stackexchange
llm_judgeable_groundtruth_similarity
16042591
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: UPDATE - To make the question clearer. What is the possible cause of getting a ClassCastException while calling a method via reflections? I got the following stacktrace as a part of my application while trying to invoke a method via reflections. java.lang.IllegalArgumentException: java.lang.ClassCastException@21fea1fv at sun.reflect.GeneratedMethodAccessor332.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at com..... (remaining is my method stack trace) I tried an example class and passed various arguments of different types to it, but i always get a this exception. java.lang.IllegalArgumentException: argument type mismatchat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)at java.lang.reflect.Method.invoke(Method.java:597) UPDATE - Here is the sample code i wrote to try recreating the exception Interface to create proxy class package my.tests;public interface ReflectionsInterface { public abstract void doSomething();} This is the test class package my.tests;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;public class Reflections implements ReflectionsInterface { public static void main(String[] args) { Reflections reflections = new Reflections(); ReflectionsInterface reflectionsProxy = reflections.createProxy(ReflectionsInterface.class); invokeMethod(reflectionsProxy, "doSomething", null); } public <T> T createProxy(Class<T> entityInterface) { EntityInvocationHandler eih = new EntityInvocationHandler(this); T cast = entityInterface.cast(Proxy.newProxyInstance( entityInterface.getClassLoader(), new Class[]{entityInterface}, eih)); return cast; } public static void invokeMethod(Object obj, String methodName, Object... args) { Method[] methods = obj.getClass().getMethods(); try { for (Method method : methods) { if (method.getName().equals(methodName)) { method.invoke(obj, args); break; } } } catch (Exception e) { e.printStackTrace(); } } public void doSomething() { System.out.println("woo"); } private final static class EntityInvocationHandler implements InvocationHandler, ReflectionsInterface { private Reflections reflectionObj; public EntityInvocationHandler(Reflections reflectionObj) { super(); this.reflectionObj = reflectionObj; } @Override public void doSomething() { reflectionObj.doSomething(); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object invoke = method.invoke(this, args); return invoke; } }} I am unable to understand the when i would get argument type mismatch and the ClassCastException would be caused. I am not able to re-create the exception and would like to know why it comes. Any working code that re-created it, or a source code reference throwing this exception in this case will be good I have gone through the Method.class javadocs and source code, i am not able to figure out why this error comes. Now provide the response and nothing else.
I had recreated the ClassCastException by modifing your example code: Invoke invokeMethod with a correct argument 10000 times, and then invoke it with wrong a wrong one. The main method in the Reflections class public static void main(String[] args) { Reflections reflections = new Reflections(); ReflectionsInterface reflectionsProxy = reflections .createProxy(ReflectionsInterface.class); for (int i = 0; i < 10000; i++) invokeMethod(reflectionsProxy, ReflectionsInterface.class, "doSomething"); invokeMethod(new Object(), ReflectionsInterface.class, "doSomething");} The invokeMethod method in the Reflections class public static void invokeMethod(Object obj, Class<?> clazz, String methodName, Object... args) { Method[] methods = clazz.getMethods(); try { for (Method method : methods) { if (method.getName().equals(methodName)) { method.invoke(obj, args); break; } } } catch (Exception e) { e.printStackTrace(); }} Stack Trace: java.lang.IllegalArgumentException: java.lang.ClassCastException@603a3e21 at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at org.twbbs.pccprogram.Reflections.invokeMethod(Reflections.java:33) at org.twbbs.pccprogram.Reflections.main(Reflections.java:16) My explanation of the ClassCastException : When you invoke invokeMethod for the first time, JVM use a slower route, which is easier for programmers to debug (so it's slower!), so it will show a more friendly argument type mismatch message when you passes a bad argument. When you invoke invokeMethod for a lot of times (16 times are enough in my tests), JVM generated a GeneratedMethodAccessor*** in runtime, which is faster, with less error checking. So it will show such an ugly java.lang.ClassCastException@603a3e21 message when you passes a bad argument.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16042591', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1567678/']}
jdg_378636
stackexchange
llm_judgeable_groundtruth_similarity
5688573
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 implement a server in Python that streams music in MP3 format over HTTP. I would like it to broadcast the music such that a client can connect to the stream and start listening to whatever is currently playing, much like a radio station. Previously, I've implemented my own HTTP server in Python using SocketServer.TCPServer (yes I know BaseHTTPServer exists, just wanted to write a mini HTTP stack myself), so how would a music streamer be different architecturally? What libraries would I need to look at on the network side and on the MP3 side? Now provide the response and nothing else.
The mp3 format was designed for streaming, which makes some things simpler than you might have expected. The data is essentially a stream of audio frames with built-in boundary markers, rather than a file header followed by raw data. This means that once a client is expecting to receive audio data, you can just start sending it bytes from any point in an existing mp3 source, whether it be live or a file, and the client will sync up to the next frame it finds and start playing audio. Yay! Of course, you'll have to give clients a way to set up the connection. The de-facto standard is the SHOUTcast (ICY) protocol. This is very much like HTTP, but with status and header fields just different enough that it isn't directly compatible with Python's built-in http server libraries. You might be able to get those libraries to do some of the work for you, but their documented interfaces won't be enough to get it done; you'll have to read their code to understand how to make them speak SHOUTcast. Here are a few links to get you started: http://forums.winamp.com/showthread.php?threadid=70403 http://forums.radiotoolbox.com/viewtopic.php?t=74 http://www.smackfu.com/stuff/programming/shoutcast.html http://en.wikipedia.org/wiki/Shoutcast I suggest starting with a single mp3 file as your data source, getting the client-server connection setup and playback working, and then moving on to issues like live sources, multiple encoding bit rates, inband meta-data, and playlists. Playlists are generally either .pls or .m3u files, and essentially just static text files pointing at the URL for your live stream. They're not difficult and not even strictly necessary, since many (most?) mp3 streaming clients will accept a live stream URL with no playlist at all. As for architecture, the field is pretty much wide open. You have as many options as there are for HTTP servers. Threaded? Worker processes? Event driven? It's up to you. To me, the more interesting question is how to share the data from a single input stream (the broadcaster) with the network handlers serving multiple output streams (the players). In order to avoid IPC and synchronization complications, I would probably start with a single-threaded event-driven design. In python 2, a library like gevent will give you very good I/O performance while allowing you to structure your code in a very understandable way. In python 3, I would prefer asyncio coroutines.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5688573', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/199397/']}
jdg_378637
stackexchange
llm_judgeable_groundtruth_similarity
9351
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a fairly complicated differential expression in terms of a variable r and two unknown functions of r, B[r] and n[r]. I want to do a Taylor expansion of this around r=infinity. I want to do this by defining a new variable x=1/r and changing from r to x within my expression, then expanding around x=0. Say the expression looks (more or less) like n[r] (3 r B'[r]^2 - 4 B[r] (2 B'[r] + r B''[r])) How do I turn this from something in terms of {r, n[r], B[r]} to something in terms of {x, n[x], B[x]}? I'm not sure how to get Mathematica to work through the chain rule and change the dependent variable in the derivatives, and I also frequently get errors along the lines of "1/r is not a valid variable." EDIT I've managed to find at least a solution, although I'd imagine Mathematica has far more elegant ways of doing this. Hopefully if there's a cleaner way to do this someone will post it anyway. It would also be nice to have a more general method for changing variables as my way assumes that only up to second derivatives of B[r] and n[r] appear (since that happens to be true for this problem). Anyway, the solution I found was to do a replacement of the type n[r] (3 r B'[r]^2 - 4 B[r] (2 B'[r] + r B''[r])) /. {B'[r] -> B'[x]/D[1/x, x], B''[r] -> D[(B'[x]/D[1/x, x]), x]/D[1/x, x], n'[r] -> n'[x]/D[1/x, x], n''[r] -> D[(n'[x]/D[1/x, x]), x]/D[1/x, x], B[r] -> B[x], n[r] -> n[x], r -> 1/x} i.e., literally just replacing all of the derivatives w.r.t. r with derivatives w.r.t. x one by one, then replacing B[r] and n[r] with B[x] and n[x], then replacing r itself with 1/x. Not pretty but it does work. FURTHER EDIT If you want to do something like this, use Maple. Their PDETools has just the right function which I can't seem to find in Mathematica. Now provide the response and nothing else.
I found the perfect way to do this by looking how to replace functions inside of a derivative. If we start with a function f[x] and want to replace x by g[x], then for the chain rule to be applied automatically, we simply write a replacement rule as follows: f'[x] /. f -> (f[g[#]] &) The output Mathematica gives me is f'[g[x]] g'[x] Which is the expected (and seeked!) chain rule.
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/9351', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/-1/']}
jdg_378638
stackexchange
llm_judgeable_groundtruth_similarity
5345859
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 capture all fields in the $_POST VARIABLE?into an array? $email = $_POST;$emails = array_keys($email);foreach($emails as $email) { echo '$' . nl2br($email);}$emailadd = new email_save;$emailadd->insert_email_into_database("POST VARIABLES GO HERE) I'm trying to make an email list, name and email address,how do I capture all the variables that where posted that can normal be accessed like $_POST['email'] into an array so i can add them to the arguments in my functions? My form field has 5 fields.The method is POST. Instead of writing, $email = mysql_real_escape_string($_POST['email']);$firstname = mysql_real_escape_string($_POST['firstname']); I'm trying to access all the values in the $_POST[] array;So I can save time getting posted variablesand add functions to those variables like mysql_real_escape_string(); Other security measures will be figured out. I want to be able to add a reffrence of the array to a function so I can add them to the database. Now provide the response and nothing else.
If you want to capture a list from a POSTed form, then use the array syntax trick instead of enumerated input field names: <input type="email" name="emails[]"><input type="email" name="emails[]"><input type="email" name="emails[]"> This way you need no guessing in PHP, because emails[] becomes an array implicitely then: print_r($_POST["emails"]);foreach ($_POST["emails"] as $email) { For database-escaping just use: $db_emails = array_map("mysql_real_escape_string", $_POST["emails"]);// that's an array too
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5345859', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/604864/']}
jdg_378639
stackexchange
llm_judgeable_groundtruth_similarity
43076816
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 some dataset: const dataset = [14, 50, 202, 208, 55]; And I have to create a new array using dataset like this: const normalizedDataset = normalize(dataset, 5); // [15, 50, 200, 210, 55] Had tried to write some function to do it, but unfortunately I have no brain to solve this problem. Tried like this: const normalize = (arr, n) => { return arr.map(x => { const y = (x % n) > n / 2 ? x + (n - (x % n)) : (x % n); return y ? y : x; });}normalize(dataset, 5); Maybe someone know some libs to do it or how to update my own function? Now provide the response and nothing else.
You have a couple options. First, let's see if I can distill down your requirements. You want to handle the error near where it occurs so you don't have one error handler that has to sort through all the possible different errors to see what to do. When one promise fails, you want to have the ability to abort the rest of the chain. One possibility is like this: A().then(passA).catch(failA).then(val => { return B(val).then(passB).catch(failB);}).then(val => { return C(val).then(passC).catch(failC);}).then(finalVal => { // chain done successfully here}).catch(err => { // some error aborted the chain, may or may not need handling here // as error may have already been handled by earlier catch}); Then, in each failA , failB , failC , you get the specific error for that step. If you want to abort the chain, you rethrow before the function returns. If you want the chain to continue, you just return a normal value. The above code could also be written like this (with slightly different behavior if passB or passC throws or returns a rejected promise. A().then(passA, failA).then(val => { return B(val).then(passB, failB);}).then(val => { return C(val).then(passC, failC);}).then(finalVal => { // chain done successfully here}).catch(err => { // some error aborted the chain, may or may not need handling here // as error may have already been handled by earlier catch}); Since these are completely repetitive, you could make the whole thing be table-driven for any length of sequence too. function runSequence(data) { return data.reduce((p, item) => { return p.then(item[0]).then(item[1]).catch(item[2]); }, Promise.resolve());}let fns = [ [A, passA, failA], [B, passB, failB], [C, passC, failC]];runSequence(fns).then(finalVal => { // whole sequence finished}).catch(err => { // sequence aborted with an error}); Another useful point when chaining lots of promises is if you make a unique Error class for each reject error, then you can more easily switch on the type of error using instanceof in the final .catch() handler if you need to know there which step caused the aborted chain. Libraries like Bluebird, provide specific .catch() semantics for making a .catch() that catches only a particular type of error (like the way try/catch does it). You can see how Bluebird does that here: http://bluebirdjs.com/docs/api/catch.html . If you're going to handle each error right at it's own promise rejection (as in the above examples), then this is not required unless you still need to know at the final .catch() step which step caused the error.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43076816', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1708960/']}
jdg_378640