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 | 21626048 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How do i pass jinja2 data into javascript. I have a Flask REST url as /logs/<test_case_name> I am trying use .getJSON() to query the above URL and hence would want to pass the jinja2 data which has the testcasename to .getJSON function. sample code: <script type="text/javascript"> alert({{name}});</script> It doesn't work.Any suggestions please?
Now provide the response and nothing else.
| other than encapsulating the variable in a string, an alternate is jquery for profit: its generally a bad idea to mix template language with javascript. An alternative would be to use html as a proxy - store the name in an element like so <meta id="my-data" data-name="{{name}}" data-other="{{other}}"> then in the javascript do var djangoData = $('#my-data').data(); this has advantage in: javascript no longer tied to the .html page jquery coerces data implicitly | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/21626048', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1336292/']} | jdg_379141 |
stackexchange | llm_judgeable_groundtruth_similarity | 32752437 |
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 app can create a custom album in the standard iOS photos application, but I have been unable to find a way for the app to gather all the images from that album to be displayed within the app. Currently, the app is able to gather images from all the albums, just not one is particular. let resultCollections = PHAssetCollection.fetchAssetCollectionsWithType( .Album, subtype: .AlbumRegular, options: nil) resultCollections.enumerateObjectsUsingBlock({ (object, index, stop) -> Void in let collection = object as! PHAssetCollection let result = PHAsset.fetchAssetsInAssetCollection(collection, options: nil) result.enumerateObjectsUsingBlock({ (object, index, stop) -> Void in let asset = object as! PHAsset self.images.append(asset) }) }) I have seen other questions that might be marked as duplicates, however the majority of them are talking about opening a UIPickerView to a custom album. This is a possible duplicate of How to fetch all images from custom Photo Album - swift however, it was never answered. So, how can an iOS app gather all images from a particular photos album?
Now provide the response and nothing else.
| Add fetchOptions like below let fetchOptions = PHFetchOptions()fetchOptions.predicate = NSPredicate(format: "title = %@", YourAlbumTitle)let resultCollections = PHAssetCollection.fetchAssetCollectionsWithType(.Album, subtype: .AlbumRegular, options: fetchOptions) Actually, the album title isn't a unique value, they can be duplicated. so I recommend using localIdentifier like below if your app access multiple albums. let fetchOptions = PHFetchOptions()fetchOptions.predicate = NSPredicate(format: "localIdentifier = %@", YourAlbumLocalIdentifier)let resultCollections = PHAssetCollection.fetchAssetCollectionsWithType(.Album, subtype: .AlbumRegular, options: fetchOptions) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32752437', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4096899/']} | jdg_379142 |
stackexchange | llm_judgeable_groundtruth_similarity | 16749907 |
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 small bit of javascript intended to open two or more tabs. This works fine in FF and IE, but chrome opens the second one in a new window instead of tab. It isn't dependant on the url as I've tried it with two identical url's. First opens in tab, second one in new window. Here's my code snippet: for(var i=0 ; i<sites.length ;i++){ window.open(sites[i].Url);}
Now provide the response and nothing else.
| Chrome automatically opens a URL in a new tab only if it's user generated action, limited to one tab per user action. In any other case, the URL will be opened in a new window (which, BTW, is blocked by default on Chrome). window.open must be called within a callback which is triggered by a user action (e.g. onclick) for the page to open in a new tab instead of a window. In your example, you attempt to open N tabs upon user action. But only the first one is opened in a new tab (because it's a user generated action). Following that, any other URL will be opened in a new window. Similar question: force window.open() to create new tab in chrome (see answer by maclema) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16749907', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1151653/']} | jdg_379143 |
stackexchange | llm_judgeable_groundtruth_similarity | 32174 |
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have been searching for the mechanism of the Mozingo reduction on Google but I haven't found anything relevant. Is the mechanism known? If so, what is it; if not, what hypothetical mechanisms can we consider?
Now provide the response and nothing else.
| Here is the reaction scheme for the Mozingo reaction (or Mozingo reduction) taken from this Wikipedia link . The reduction works for both aldehydes and ketones and involves two steps. First, the carbonyl compound is converted into a thioketal (or thioacetal). The mechanism for this step is analogous to the mechanism for ketal or acetal formation (see here ) except sulfur replaces oxygen as the nucleophile attacking the carbonyl. In a second step, the thioketal is subsequently reduced to the corresponding methylene compound. The reduction can be a standard Raney nickel hydrogenolysis or hydrazine can be used at higher temperatures. The mechanism of reactions on metal surfaces or at higher temperatures are usually not well understood. Note however that a typical $\ce{C-S}$ bond is around $\pu{20 kcal/mol}$ weaker than a $\ce{C-C}$ bond. It is also known that sulfur is readily bound at metal surfaces (catalyst poisoning by sulfur being an example). The complexation of sulfur and the metal likely weakens the $\ce{C-S}$ bond further. Whether a $\ce{C-S^.}$ radical is formed that reacts with a hydrogen radical complexed at the metal surface, or whether the hydride anion is generated at the metal surface and displaces the sulfur at the weakened $\ce{C-S}$ bond is not known. The Mozingo reaction is complementary to the Clemmensen (run under acidic conditions) and Wolff-Kishner (run under basic conditions) reductions in that it can be performed under neutral conditions. So if acid- or base-sensitive functional groups are present in the starting carbonyl compound, the Mozingo reaction is likely the pathway of choice to reduce the carbonyl. | {} | {'log_upvote_score': 5, 'links': ['https://chemistry.stackexchange.com/questions/32174', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/5591/']} | jdg_379144 |
stackexchange | llm_judgeable_groundtruth_similarity | 1435339 |
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:
When you add the digits of any number that is divisible by three, that sum of those digits also appears to be divisible by three (with no remainder) . For example a number (which I randomly grab from the top of my head) : 289752 whose digits sum to 33 (2+8+9+7+5+2=33) That sum 33 is divisible by three and so is the original number 289752 . This is not the case when dividing by 2, for example 12 is divisible by two but when its digits are summed (1+2=3) you receive 3 which is NOT divisible by 2. I have yet to be able to find a counter example for this phenomenon of division by 3. Why does this happen?
Now provide the response and nothing else.
| Let $n=d_0+d_1\times 10+d_2\times 10^2+\cdots d_n\times10^n$ where $d_i$ are the digits. We note that $10\equiv 1 \pmod{3}$, and thus $10^k\equiv 1\pmod{3}$, so $$n\equiv d_0+d_1+\cdots+d_n \pmod{3}$$ So $n\equiv 0 \pmod{3}$ iff $d_0+d_1+\cdots+d_n\equiv 0 \pmod{3}$ If you don't know modular stuff, wikipedia has an article I'm sure. Just google it. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1435339', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/43411/']} | jdg_379145 |
stackexchange | llm_judgeable_groundtruth_similarity | 29411486 |
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 lists the current overloads of std::abs in C++. I'm wondering why not just define the following template and let go all the ugly C-style overloads? template <typename T> inlineT abs(const T& v) { return v < 0 ? -v : v; }
Now provide the response and nothing else.
| See LWG issue 2192 . Currently, std::abs(x-y) < 2 fails if x and y are unsigned. This catches a subtle programming error. With the proposed change, it compiles but does entirely the wrong thing. abs(3u-4u) would be much larger than 2, in fact it's UINT_MAX . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/29411486', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1348273/']} | jdg_379146 |
stackexchange | llm_judgeable_groundtruth_similarity | 55178179 |
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 SQL, there's no sorting function to sort a string. I have this function, however there seems to be a problem with it. Any help would be appreciated. ALTER FUNCTION [dbo].[Sorting] (@str VARCHAR(5000))returns VARCHAR(5000) BEGIN DECLARE @len INT, @cnt INT =1, @str1 VARCHAR(5000)='', @output VARCHAR(5000)='' SELECT @len = Len(@str) WHILE @cnt <= @len BEGIN SELECT @str1 += Substring(@str, @cnt, 1) + ',' SET @cnt+=1 END SELECT @str1 = LEFT(@str1, Len(@str1) - 1) SELECT @output += Sp_data FROM (SELECT Split.a.value('.', 'VARCHAR(5000)') Sp_data FROM (SELECT Cast ('<M>' + Replace(@str1, ',', '</M><M>') + '</M>' AS XML) AS Data) AS A CROSS APPLY Data.nodes ('/M') AS Split(a)) A ORDER BY Sp_data RETURN @output END
Now provide the response and nothing else.
| I believe the source of the problem is in the line user_query = (username_info) It should be user_query = (username_info,) The trailing comma is the syntactic difference between an expression in parentheses and a tuple . Another issue with code is the query: find_user = ("SELECT * FROM useraccess WHERE user_type = ?") Which should be: find_user = ("SELECT * FROM useraccess WHERE user_type = %s") | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/55178179', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11083663/']} | jdg_379147 |
stackexchange | llm_judgeable_groundtruth_similarity | 12589764 |
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 javascript calendar that is sending me a unixtimestamp. I am in Singapore. I want this timestamp to be interpreted as a Singapore timestamp and then converted to utc for comparisons with the db. I cant, for the life of myself, figure out how to tell django that this time stamp is from the current timezone, Singapore. When i do a print statement of the timestamp, it adds 8 hours to the time (which means that django thinks I input the time in utc and is localizing it to the Singaporean context) Among many other things, I tried: start=datetime.datetime.fromtimestamp(int(start_date)).replace(tzinfo=get_current_timezone()) The start_date is 1325376000 (which translates to 2012-01-01 00:00:00) However,when i print the output of this I get 2012-01-01 08:00:00+06:55. I dont even know where +06:55 is coming from when singapore is +08:00. I am SO lost. Thanks for your help. settings.py: TIME_ZONE = 'Asia/Singapore' USE_TZ = True
Now provide the response and nothing else.
| Assuming you've got pytz installed: from datetime import datetimeimport pytzlocal_tz = pytz.timezone("Asia/Singapore") utc_dt = datetime.utcfromtimestamp(timestamp).replace(tzinfo=pytz.utc)local_dt = local_tz.normalize(utc_dt.astimezone(local_tz)) For example: >>> from datetime import datetime>>> import pytz>>> local_tz = pytz.timezone("Asia/Singapore")>>> utc_dt = datetime.utcfromtimestamp(1325376000).replace(tzinfo=pytz.utc)>>> utc_dtdatetime.datetime(2012, 1, 1, 0, 0, tzinfo=<UTC>)>>> local_dt = local_tz.normalize(utc_dt.astimezone(local_tz))>>> local_dtdatetime.datetime(2012, 1, 1, 8, 0, tzinfo=<DstTzInfo 'Asia/Singapore' SGT+8:00:00 STD>)>>> local_dt.replace(tzinfo=None)datetime.datetime(2012, 1, 1, 8, 0) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12589764', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/566376/']} | jdg_379148 |
stackexchange | llm_judgeable_groundtruth_similarity | 6569405 |
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 get active process name in C#? I know that I must use this code: [DllImport("user32.dll")]private static extern IntPtr GetForegroundWindow(); but I don't know how use it.
Now provide the response and nothing else.
| As mentioned in this answer , you have to use GetWindowThreadProcessId() to get the process id for the window and then you can use the Process : [DllImport("user32.dll")]public static extern IntPtr GetWindowThreadProcessId(IntPtr hWnd, out uint ProcessId);[DllImport("user32.dll")]private static extern IntPtr GetForegroundWindow();string GetActiveProcessFileName(){ IntPtr hwnd = GetForegroundWindow(); uint pid; GetWindowThreadProcessId(hwnd, out pid); Process p = Process.GetProcessById((int)pid); p.MainModule.FileName.Dump();} Be aware that this seems to throw an exception (“A 32 bit processes cannot access modules of a 64 bit process”) when run from a 32-bit application when the active process is 64-bit. EDIT: As Damien pointed out, this code is prone to race conditions, because the process that had the active window at the time when GetForegroundWindow() was called might not exist anymore when GetWindowThreadProcessId() is called. Even worse situation would be if the same hwnd would be assigned to another window at that time, but I guess this should be really rare. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6569405', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/827816/']} | jdg_379149 |
stackexchange | llm_judgeable_groundtruth_similarity | 1885785 |
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 wondering whether the C++ string is considered small enough to be more efficient when passed by value than by reference.
Now provide the response and nothing else.
| No. Pass it by reference: void foo(const std::string& pString); In general, pass things by-reference if they have a non-trivial copy-constructor, otherwise by-value. A string usually consists of a pointer to data, and a length counter. It may contain more or less, since it's implementation defined, but it's highly unlikely your implementation only uses one pointer. In template code, you may as well use const T& , since the definition of the function will be available to the compiler. This means it can decide if it should be a reference or not for you. (I think) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1885785', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/257581/']} | jdg_379150 |
stackexchange | llm_judgeable_groundtruth_similarity | 15672151 |
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 2.7 method that sometimes calls sys.exit(1) Is it possible to make a unit test that verifies this line of code is called when the right conditions are met?
Now provide the response and nothing else.
| Yes. sys.exit raises SystemExit , so you can check it with assertRaises : with self.assertRaises(SystemExit): your_method() Instances of SystemExit have an attribute code which is set to the proposed exit status, and the context manager returned by assertRaises has the caught exception instance as exception , so checking the exit status is easy: with self.assertRaises(SystemExit) as cm: your_method()self.assertEqual(cm.exception.code, 1) sys.exit Documentation : Exit from Python. This is implemented by raising the SystemExit exception ... it is possible to intercept the exit attempt at an outer level. | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/15672151', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/825706/']} | jdg_379151 |
stackexchange | llm_judgeable_groundtruth_similarity | 15873904 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am working with Chrome extension's content script to create a complex display that is added on web pages. I have first tested it directly integrated on a website, but now I need to put it in an extension. The thing is that the content script API for Chrome only allows to inject javascript. That means that, to inject complex HTML layouts I would need to write it entirely with JS objects, which is long to write, hard to maintain and absolutely not designer-friendly. I'm wondering if anyone know or can think of a clever way to get a better workflow on this.
Now provide the response and nothing else.
| It's relatively easy to add whole web pages by having your content script inject them in an iframe. Just follow these guidelines: Place the *.htm or *.html files in your extension's source folder(s). Place any *.css and *.js files, that the HTML uses, in the extension folder(s) too. Declare the HTML file(s) as resources. EG: "web_accessible_resources": ["Embedded_Hello_world.htm"] Do not use any inline , or external server, javascript in your HTML files. This avoids problems with the Content Security Policy (CSP) . This question doesn't cover communicating with the page/iframe, but if you want to do that, it is a bit more involved. Search here on SO; it's been covered many times. Example: You can see this in action by: Creating a new extension folder. Download jQuery into it. Create the 5 files as specified below. Load the unpacked extension (You can see similar steps in this answer .) Reload this page in Chrome; you'll see the "Hello World" page, embedded at the top. Create these files in the extension folder: manifest.json: { "manifest_version": 2, "content_scripts": [ { "js": [ "iframeInjector.js" ], "matches": [ "https://stackoverflow.com/questions/*" ] } ], "description": "Inject a complete, premade web page", "name": "Inject whole web page", "version": "1", "web_accessible_resources": ["Embedded_Hello_world.htm"]} iframeInjector.js: var iFrame = document.createElement ("iframe");iFrame.src = chrome.extension.getURL ("Embedded_Hello_world.htm");document.body.insertBefore (iFrame, document.body.firstChild); Embedded_Hello_world.htm: <!DOCTYPE html><html><head> <title>Embedded Hello World</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <link href="HelloWorld.css" rel="stylesheet" type="text/css"> <script type="text/javascript" src="jquery.min.js"></script> <script type="text/javascript" src="HelloWorld.js"></script></head><body><p>Hello World!</p></body></html> HelloWorld.css: body { color: red; background-color: lightgreen;} HelloWorld.js: $(document).ready (jQueryMain);function jQueryMain () { $("body").append ('<p>Added by jQuery</p>');} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15873904', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1203633/']} | jdg_379152 |
stackexchange | llm_judgeable_groundtruth_similarity | 1100100 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there a FFT-based 2D cross-correlation or convolution function built into scipy (or another popular library)? There are functions like these: scipy.signal.correlate2d - "the direct method implemented by convolveND will beslow for large data" scipy.ndimage.correlate - "The array is correlated with the given kernel usingexact calculation (i.e. not FFT)." scipy.fftpack.convolve.convolve , which I don't really understand, but seems wrong numarray had a correlate2d() function with an fft=True switch , but I guess numarray was foldedinto numpy, and I can't find if this function was included.
Now provide the response and nothing else.
| I found scipy.signal.fftconvolve , as also pointed out by magnus , but didn't realize at the time that it's n -dimensional. Since it's built-in and produces the right values, it seems like the ideal solution. From Example of 2D Convolution : In [1]: a = asarray([[ 1, 2, 3], ...: [ 4, 5, 6], ...: [ 7, 8, 9]])In [2]: b = asarray([[-1,-2,-1], ...: [ 0, 0, 0], ...: [ 1, 2, 1]])In [3]: scipy.signal.fftconvolve(a, b, mode = 'same')Out[3]: array([[-13., -20., -17.], [-18., -24., -18.], [ 13., 20., 17.]]) Correct! The STSCI version, on the other hand, requires some extra work to make the boundaries correct? In [4]: stsci.convolve2d(a, b, fft = True)Out[4]: array([[-12., -12., -12.], [-24., -24., -24.], [-12., -12., -12.]]) (The STSCI method also requires compiling, which I was unsuccessful with (I just commented out the non-python parts), has some bugs like this and modifying the inputs ([1, 2] becomes [[1, 2]]), etc. So I changed my accepted answer to the built-in fftconvolve() function.) Correlation, of course, is the same thing as convolution, but with one input reversed: In [5]: aOut[5]: array([[3, 0, 0], [2, 0, 0], [1, 0, 0]])In [6]: bOut[6]: array([[3, 2, 1], [0, 0, 0], [0, 0, 0]])In [7]: scipy.signal.fftconvolve(a, b[::-1, ::-1])Out[7]: array([[ 0., -0., 0., 0., 0.], [ 0., -0., 0., 0., 0.], [ 3., 6., 9., 0., 0.], [ 2., 4., 6., 0., 0.], [ 1., 2., 3., 0., 0.]])In [8]: scipy.signal.correlate2d(a, b)Out[8]: array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [3, 6, 9, 0, 0], [2, 4, 6, 0, 0], [1, 2, 3, 0, 0]]) and the latest revision has been sped up by using power-of-two sizes internally (and then I sped it up more by using real FFT for real input and using 5-smooth lengths instead of powers of 2 :D ). | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1100100', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/125507/']} | jdg_379153 |
stackexchange | llm_judgeable_groundtruth_similarity | 38803 |
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Norbert Blum recently posted a 38-page proof that $P \ne NP$. Is it correct? Also on topic: where else (on the internet) is its correctness being discussed? Note: the focus of this question text has changed over time. See question comments for details.
Now provide the response and nothing else.
| As noted here before, Tardos' example clearly refutes the proof; it gives a monotone function, which agrees with CLIQUE on T0 and T1, but which lies in P. This would not be possible if the proof were correct, since the proof applies to this case too. However, can we pinpoint the mistake? Here is, from a post on the lipton's blog, what seems to be the place where the proof fails: The single error is one subtle point in the proof of Theorem 6, namely in Step 1, on page 31 (and also 33, where the dual case is discussed) - a seemingly obvious claim that $C'_g$ contains all the corresponding clauses contained in $CNF'(g)$ etc, seems wrong. To explain this in more detail, we need to go into the proof and approximation method of Berg and Ulfberg, which restates the Razborov's original proof of the exponential monotone complexity for CLIQUE in terms of DNF/CNF switches. This is how I see it: To every node/gate $g$ of a logic circuit $\beta$ (containing binary OR/AND gates only), a conjunctive normal form $CNF(g)$, a disjunctive normal form $DNF(g)$, and approximators $C^k_g$ and $D^r_g$ are attached. $CNF$ and $DNF$ are simply the corresponding disjunctive and conjunctive normal forms of the gate output. $D^r_g$ and $C^k_g$ are also disjunctive and conjunctive forms, but of some other functions, "approximating" the gate output. They are however required to have bounded number of variables in each monomial for $D^r_g$ (less than a constant r) and in each clause for $C^k_g$ (less than a constant k). There is notion of an "error" introduced with this approximation. How is this error computed? We are only interested in some set T0 of inputs on which our total function takes value 0, and T1 of inputs on which our total function takes value 1 (a "promise") . Now at each gate, we look only at those inputs from T0 and T1, which are correctly computed (by both $DNF(g)$ and $CNF(g)$, which represent the same function - output of gate $g$ in $\beta$) at gate output, and look how many mistakes/errors are for $C^k_g$ and $D^r_g$, compared to that. If the gate is a conjunction, then the gate output might compute more inputs from T0 correctly (but the correctly computed inputs from T1 are possibly decreased). For $C^k_g$, which is defined as a simple conjunction, there are no new errors however on all of these inputs. Now, $D^r_g$ is defined as a CNF/DNF switch of $C^k_g$, so there might be a number of new errors on T0, coming from this switch. On T1 also, there are no new errors on $C^k_g$ - each error has to be present on either of gate inputs, and similarly on $D^r_g$, switch does not introduce new errors on T1. The analysis for OR gate is dual. So the number of errors for the final approximators is bounded by number of gates in $\beta$, times the maximal possible number of errors introduced by a CNF/DNF switch (for T0), or by a DNF/CNF switch (for T1). But the total number of errors has to be "large" in at least one case (T0 or T1), since this is a property of positive conjunctive normal forms with clauses bounded by $k$, which was the key insight of Razborov's original proof (Lemma 5 in the Blum's paper). So what did Blum do in order to deal with negations (which are pushed to the level of inputs, so the circuit $\beta$ is still containing only binary OR/AND gates)? His idea is to preform CNF/DNF and DNF/CNF switches restrictively, only when all variables are positive. Then the switches would work EXACTLY like in the case of Berg and Ulfberg, introducing the same amount of errors. It turns out this is the only case which needs to be considered. So, he follows along the lines of Berg and Ulfberg, with a few distinctions. Instead of attaching $CNF(g)$, $DNF(g)$, $C^k_g$ and $D^r_g$ to each gate $g$ of circuit $\beta$, he attaches his modifications, $CNF'(g)$, $DNF'(g)$, ${C'}^k_g$ and ${D'}^r_g$, i.e. the "reduced" disjunctive and conjunctive normal forms, which he defined to differ from $CNF(g)$ and $DNF(g)$ by "absorption rule", removing negated variables from all mixed monomials/clauses (he also uses for this purpose operation denoted by R, removing some monomials/clauses entirely; as we discussed before, his somewhat informal definition of R is not really the problem, R can be made precise so it is applied at each gate but what is removed depends not only on previous two inputs but on the whole of the circuit leading up to that gate), and their approximators ${C'}^r_g$ and ${D'}^r_g$, that he also introduced. He concludes, in Theorem 5, that for a monotone function, reduced $CNF'$ and $DNF'$ will really compute 1 and 0 on sets T1 and T0, at root node $g_0$ (whose output is the output of the whole function in $\beta$). This theorem is, I believe, correct. Now comes the counting of errors. I believe the errors at each node are meant to be computed by comparing reduced $CNF'(g)$ and $DNF'(g)$ (which are now possibly two different functions), to ${C'}^r_g$ and ${D'}^k_g$ as he defined them. The definitions of approximators parrot definitions of $CNF'$ and $DNF'$ (Step 1) when mixing variables with negated ones, but when he deals with positive variables, he uses the switch like in the case of Berg and Ulfberg (Step 2). And indeed, in Step 2 he will introduce the same number of possible errors like before (it is the same switch, and all the involved variables are positive). But the proof is wrong in Step 1. I think Blum is confusing $\gamma_1$, $\gamma_2$, which really come, as he defined them, from previous approximators (for gates $h_1$, $h_2$), with positive parts of $CNF'_\beta(h_1)$ and $CNF'_\beta(h_2)$. There is a difference, and hence, the statement "$C_g'$ contains still all clauses contained in $CNF'_\beta(g)$ before the approximation of the gate g which use a clause in $\gamma_1'$ or $\gamma_2'$" seems to be wrong in general. | {} | {'log_upvote_score': 8, 'links': ['https://cstheory.stackexchange.com/questions/38803', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/46348/']} | jdg_379154 |
stackexchange | llm_judgeable_groundtruth_similarity | 56926998 |
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 building a Discord bot and I want to have an if statement that will only proceed if the message author has an administrator role in the guild. I've tried having role-specific permissions, but this means that there will have to be the exact same name role on all servers that the bot is on. How can I check if the message author has an admin role? (The role has the administrator permission.)
Now provide the response and nothing else.
| Some of the following code must be modified to use in the newest major Discord.js version (v12 at the time of this edit) due to the implementation of Managers. There's really three different questions needed to be addressed here. They're all related, but each have different direct answers. How do I check if the message author has an Admin role ? The GuildMember that sent a message is accessed via the Message#member property, as opposed to Message#author which returns a User . Remember, a member has roles and permissions, not a user. A Collection of a member's roles can be retrieved with GuildMember#roles . You can search for a role two main ways: ID: Map#has() Property: Collection#find() So, tying this all together: if (message.member.roles.has'roleIDHere')) console.log('User is an admin.'); or if (message.member.roles.find(role => role.name === 'Admin')) console.log('User is an admin.'); How do I check if the message author's role has the Administrator permission ? Again, we need to use the GuildMember from Message#member . And again, we need to use the GuildMember#roles collection. And... déjà vu... you can search through a Collection with Collection#find() . This time, you should specifically check Role#hasPermission() in the predicate function. For example: if (message.member.roles.find(role => role.hasPermission('Administrator'))) console.log('User is an admin.'); You can apply this concept to any specific role, too. Best method for this situation... How do I check if the message author has the Administrator permission ? We continue to use Message#member to access the GuildMember. However, you can check all of a member's permissions at once via the GuildMember#hasPermission() method. Consider this short example: if (message.member.hasPermission('ADMINISTRATOR')) console.log('User is an admin.'); Quick, right? Make sure you check that the message your client receives is not a DM before attempting to check if the user is an Admin. Message#member is undefined when the message isn't sent in a guild, and trying to use properties of it will throw an error. Use this condition, which will stop if the message is a DM: if (!message.guild) return; | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/56926998', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11557518/']} | jdg_379155 |
stackexchange | llm_judgeable_groundtruth_similarity | 40158818 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm getting a strange issue that I'm hoping has an extremely simple solution. I'm trying to send a POST request to a server. I have tried this using fetch and using XMLHttpRequest with no luck. My xhr request looks like the following: var xhr = new XMLHttpRequest();xhr.open("POST", location);xhr.withCredentials = true;xhr.setRequestHeader('Content-Type', 'application/json');xhr.send(JSON.stringify(obj)); My fetch request looks like the following: fetch(location, { credentials: 'include', method: 'post', body: JSON.stringify({obj}), headers: { 'Content-Type': 'application/json' }) .then((response) => { if (response.ok){ response = response.json(); } else { response = {}; } window.console.debug(response); }) .then((json) =>{ window.console.debug(json); }) .catch((error) => { window.console.debug(error); }); Both of these have the same outcome. If I leave it like above, the credentials don't get sent so it sends an OPTIONS request and I get a 401. My Chrome Network tab Request Headers for the message looks like this: Accept:*/*Accept-Encoding:gzip, deflate, sdchAccept-Language:en-US,en;q=0.8Access-Control-Request-Headers:content-typeAccess-Control-Request-Method:POSTConnection:keep-aliveHost:192.168.146.101:8005Origin:http://localhost:8555Referer:http://localhost:8555/User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 If I remove the header lines, the content-type is the wrong type (obviously) and so I get a 415. The chrome network tab Request Headers message looks like this: Accept:*/*Accept-Encoding:gzip, deflateAccept-Language:en-US,en;q=0.8Authorization:Basic YWRtaW46YWRtaW4=Connection:keep-aliveContent-Length:504Content-Type:text/plain;charset=UTF-8Host:192.168.146.101:8005Origin:http://localhost:8555Referer:http://localhost:8555/User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 For some reason, when I add a header, it strips the credentials. I've tried sending the encoded user:pass in the header as well like this (but obviously with the real username/password): var xhr = new XMLHttpRequest();xhr.open("POST", location);xhr.withCredentials = true;xhr.setRequestHeader('Content-Type', 'application/json');xhr.setRequestHeader('Authorization', 'Basic ' + window.btoa('user:pass');xhr.send(JSON.stringify(obj)); This is happening in all browsers.Thanks for any and all help!
Now provide the response and nothing else.
| Instead of relying on moduleNameMapper you can specify a custom transform where you return the image path instead of its source. A working example can be found under Mocking CSS Modules , pasting it below to make things easier. // fileTransformer.jsconst path = require('path');module.exports = { process(src, filename, config, options) { return 'module.exports = ' + JSON.stringify(path.basename(filename)) + ';'; },}; and // package.json (for custom transformers and CSS Modules){ "jest": { "moduleNameMapper": { "\\.(css|less)$": "identity-obj-proxy" }, "transform": { "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/fileTransformer.js" } }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40158818', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1892835/']} | jdg_379156 |
stackexchange | llm_judgeable_groundtruth_similarity | 11497 |
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'm confused how $$\dot{\mathbf{r}}_{j}=\sum_{k}\frac{\partial\mathbf{r}_{j}}{\partial q_{k}}\dot{q}_k+\frac{\partial\mathbf{r}_{j}}{\partial t}$$ leads to the relation, $$\frac{\partial\dot{\mathbf{r}}_{i}}{\partial\dot{q}_{j}}=\frac{\partial\mathbf{r}_{i}}{\partial q_{j}}$$ Sources suggest that while differentiating the first equation the generalized velocity and generalized positions are considered as independent of each other, i.e., $(\dot{q_1},\dot{q_2},...,\dot{q_n})$ is independent of $(q_1,q_2,...,q_n)$. I don't understand how they are independent.
Now provide the response and nothing else.
| Starting with the following definition of $\mathbf{r}_j$ in terms of generalized coordinates $$\mathbf{r}_{j}=\mathbf{r}_{j}(q_1, q_2, \ldots, q_n,t) \; ,$$ it is clear that taking the total derivative with respect to time, we arrive at the following relation $$\dot{\mathbf{r}}_{j}=\sum_{k}\frac{\partial\mathbf{r}_{j}}{\partial q_{k}}\dot{q}_k+\frac{\partial\mathbf{r}_{j}}{\partial t} \; .$$ But because of the appearance of $\dot{q}_k$ , $\dot{\mathbf{r}}_{j}$ also depends on $\dot{q}_k$ . Therefore, it makes sense to take partial derivatives of $\dot{\mathbf{r}}_{j}$ with respect to the $\dot{q}_k$ and from the relation above, we indeed get the relation you find. While $\dot{q}_k$ is the time derivative of $q_k$ , it can not be expressed as a function of the $q_j$ . The derivative is an operator, not a function from tuples of real numbers to real numbers so that does not count. Physically, you could say the difference is in the fact that a real function on n-tuples only involves information of what happens in that point at that specific instant. A derivative however involves information about what happens at a point at an instant but also at a different point an infinitesimal instant before that . Or another way of seeing this is that the state of a classical system is completely specified when one gives the positions and velocities at one instant . If only positions where sufficient, the equations of motion would be first order equations and the time derivative would really be dependent on the positions at one instant, because it would be fully determined by them. This is not the case with the classical second order equations we have for most classical systems of point particles. | {} | {'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/11497', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/966/']} | jdg_379157 |
stackexchange | llm_judgeable_groundtruth_similarity | 65384637 |
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 currently working on a React Native (Expo) App and I am facing some performance issues. I have not found any answer yet for my problem so I hope someone can help me. My problem is that whenever I launch the app on my physical device (Galaxy S9+) and navigate to different screens, I notice JS frames dropping from 60 all the way to like 10-30. I have a main drawer navigator, a bottom tab navigator and some stack navigators. I have basic View, Text, ... component so I don't think it is due to heavy components.(I am using react-navigation v5 ) I also have to mention that I don't really see any lack of performance or JS FPS drops on an iOS simulator.
Now provide the response and nothing else.
| Android devices are a lot more sensitive to unoptimized JavaScript code because they typically have far worse JS performance when compared to iOS devices, so you have less headroom to write inefficient code. The same code running on iOS can feel smooth and on Android it can end up frequently dropping frames. It's recommended to use React Devtools to understand the source of slow rendering performance in React apps, and I think this is a fine option here and something you certainly should do. Another thing you can do is switch to createNativeStackNavigator wherever you are using createStackNavigator , and that will help push some of your performance concerns a little bit down the road. You can also learn more about this navigator in this YouTube video . I'd personally do both of the above right now: 1) profile your React rendering performance and find where you're doing unnecessary / extra work, eliminate that. 2) switch to using createNativeStackNavigator . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/65384637', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12291641/']} | jdg_379158 |
stackexchange | llm_judgeable_groundtruth_similarity | 24868800 |
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 create a simple real-time search with angularjs client side, and java server side, i want to use the similar effect than onKeyUp in dom and ajax but in angular js, <div ng-app="MyModule" ng-controller="MainCtrl"> <input class="form-control field span12" id="objctf" rows="4" ng-model="keywords" /> <a href="/adminpanel?q=" class="btn btn-primary">Manage</a> <div> <p ng-show="loading">Loading...</p> <p ng-hide="loading">Response: {{response}}</p> <p ng-hide="loading">writed: {{keywords}}</p> </div> </div>var MainCtrl = function($scope, $http) {$scope.keywords = "debut";alert ('en mode ajax '+$scope.keywords);$scope.response = $http.post('/api/member/getuser', { "username" : $scope.keywords }); };
Now provide the response and nothing else.
| Add ng-change to your input like so: <input class="form-control field span12" id="objctf" rows="4" ng-model="keywords" ng-change="search()" /> Create a method to handle the change on the controller: myApp.controller('someCtrl', ['$scope', 'someService', function($scope, someService){ $scope.search = function(){ someService.search($scope.keywords).then(function(response){ $scope.response = response.data; }); };}]); Finally, create a service to make the call to the server: myApp.service('someService', ['$http', function($http){ return { search: function(keywords){ return $http.post('/api/member/getuser', { "username" : keywords }); } }}]); Handling things in this fashion, you'll gain a re-usable search method whose results can be persisted through routes if needs be. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24868800', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3074941/']} | jdg_379159 |
stackexchange | llm_judgeable_groundtruth_similarity | 22155374 |
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 came across thins site which states that insertion at the back of STL vector can either be O(1) or O(n). I believe insertion at the end should be O(1) for a vector. Could anyone clarify this and tell me what the author means by O(n). The author states that for STL vector insertion at the back Back: O(1) or O(n) . Which one is it ?
Now provide the response and nothing else.
| The complexity is required to be amortized constant. That means that not every insertion necessarily takes the same length of time, but over the long term, it averages out to a constant regardless of the size of collection. It does that by allocating a larger block when the current block gets full, and copying the data from the current block to a new one. The "trick" is that the block sizes increase in a geometric progression, so as the collection gets larger, copies happen progressively less often. If you wanted to badly enough, you could actually make the time literally constant, not just amortized constant. When you need to allocate a larger block, you'd allocate a new block twice the size of the old one, insert the new item in its correct place in the new block, and copy exactly one item from the old block to the new one. Every time you inserted an item, you'd copy exactly one more item from the old block to the new one. Every insertion would require inserting one new item and copying one old item, so the complexity would be constant. This would have a couple of disadvantages though. First, it would obviously keep both the old block and the new block in use instead of releasing the old block (almost) immediately after allocating the new one. Second, it would lose temporal locality, so when it copied one item from the old block to the new one, chances are pretty good that it wouldn't be in the cache. By copying the entire old block to the new one at once, you get much better cache utilization (at least as a rule). | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22155374', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1305891/']} | jdg_379160 |
stackexchange | llm_judgeable_groundtruth_similarity | 26573368 |
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 wanted to try some new package. I installed it, it required a lot of dependencies, so it installed plenty of other packages. I tried it and I am not impressed - now I would like to uninstall that package including all the dependencies! Is there any way to remove given packages including all dependencies which are not needed by any other package in the system? I looked at ?remove.packages but there is no option to do this.
Now provide the response and nothing else.
| Here is some code that will all you to remove a package and its unneeded dependencies. Note that its interpretation of "unneeded" dependent packages is the set of packages that this package depends on but that are not used in any other package. This means that it will also default to suggesting to uninstall packages that have no reverse dependencies. Thus I've implemented it as an interactive menu (like in update.packages ) to give you control over what to uninstall. library("tools")removeDepends <- function(pkg, recursive = FALSE){ d <- package_dependencies(,installed.packages(), recursive = recursive) depends <- if(!is.null(d[[pkg]])) d[[pkg]] else character() needed <- unique(unlist(d[!names(d) %in% c(pkg,depends)])) toRemove <- depends[!depends %in% needed] if(length(toRemove)){ toRemove <- select.list(c(pkg,sort(toRemove)), multiple = TRUE, title = "Select packages to remove") remove.packages(toRemove) return(toRemove) } else { invisible(character()) }}# Exampleinstall.packages("YplantQMC") # installs an unneeded dependency "LeafAngle"c("YplantQMC","LeafAngle") %in% installed.packages()[,1]## [1] TRUE TRUEremoveDepends("YplantQMC")c("YplantQMC","LeafAngle") %in% installed.packages()[,1]## [1] FALSE FALSE Note: The recursive option may be particularly useful. If package dependencies further depend on other unneeded packages, setting recursive = TRUE is vital. If dependencies are shallow (i.e., only one level down the dependency tree), this can be left as FALSE (the default). | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26573368', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/684229/']} | jdg_379161 |
stackexchange | llm_judgeable_groundtruth_similarity | 54866 |
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:
Very basic question: I can't get my head around the Cantor space . It has a basis of clopen sets. Finite unions of closed sets are closed, and unions of open sets are open, so a finite union of basis elements of a Cantor space is clopen. The only open sets in a Cantor space that are not closed, if there are any, are infinite unions of basis elements. An example of an open set that's not closed is ... what? Not a homework question; I managed to stump myself. Thanks for your help.
Now provide the response and nothing else.
| Hint: Look at the complement of a point—the Cantor space is not discrete. Later: Since the Cantor set is homeomorphic to a countable product $\prod_{n=1}^{\infty} \mathbb{Z}/2\mathbb{Z}$ of the cyclic group of order two (use the identification of the cantor set with the points in $[0,1]$ whose infinite ternary expansion contains no $1$), it is homogeneous. This means in particular that the Cantor set has no isolated points and hence it has no open points. Now note that a basic open set is of the form $\prod_{n=1}^{\infty} X_n$ with all but finitely many $X_n = \mathbb{Z}/2\mathbb{Z}$. But this means that a basic open set contains a space homeomorphic to the entire Cantor space, hence non-empty open sets are uncountable (in fact of cardinality $\mathfrak{c}$). In particular we see that a convergent sequence (which is of course closed) can't be open. Passing to complements we get an open set that's not closed, as required. [Meta: Thanks to ccc for pointing this out and to Brian for making me think again.] | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/54866', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/1813/']} | jdg_379162 |
stackexchange | llm_judgeable_groundtruth_similarity | 31711 |
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 am taking a security class. The slides say that smartcards usually use one of three types of authentication protocols: static, dynamic and challenge response. What is the difference between these?
Now provide the response and nothing else.
| Warning: the terminology is a bit fuzzy, so there cannot be a completely authoritative and clear-cut answer. A static authentication protocol means that the device which does the authentication does not compute anything. If embeds some secret value but can, at best, show it. The human user, when he types his password in a login page or interface, is a static authentication device. The smallest, dumbest, cheapest kind of smartcard does the same: after having been duly unlocked (users typed his PIN code), the card spouts a secret value always the same. A dynamic authentication protocol is the opposite: the device computes things. There are many types and sub-types of dynamic authentication protocols: The protocol can be a challenge-response : the system which runs the authentication submits a challenge , e.g. a random sequence of bytes, to which the device responds by computing a cryptographic function which uses both the challenge and a secret data contained in the device. The cryptographic function can be, for instance, a MAC which the device computes over the challenge, with the secret as key; the authenticating system will verify that MAC (this scenario assumes that the secret value is known to both the smartcard and the authenticating system). Another kind of challenge-response is based on digital signatures : this requires heavier computations (hence a less cheap smart card) but means that the authenticating server needs not know the secret value which is embedded in the smart card. Some cards generate one-time passwords . This can be viewed as a challenge-response protocol in which the challenge is not sent by the server, but is a publicly known everchanging value (e.g. a counter, as in HOTP , or the current time, as in TOTP ). RSA SecurID tokens are of that type. Devices which use that kind of protocol must maintain some permanent state which resists resets (e.g. a battery-powered internal clock, or a counter value stored in EEPROM); but they are easier to integrate into existing systems (as with RSA SecurID tokens, the user just has to type what is displayed on his token; he does not have to plug the token in his desktop machine). | {} | {'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/31711', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/9499/']} | jdg_379163 |
stackexchange | llm_judgeable_groundtruth_similarity | 2569710 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am asked to determine whether or not a function can have all of its partial derivatives exist at a point but not be continuous at that point. I have tried to construct a counterexample but am unsure whether or not I have succeeded. Consider the following function: $$ f(x,y) = \left\{ \begin{array}{cc}x & y=0 \\0 & \text{otherwise}\end{array}\right.$$ Let $(x_0,y_0) \not= 0$ then we can compute the partials of $f$ at this point. Doing so is not difficult we just have to make sure we are careful about the partials with respect to $y$. $$\begin{align*}f_x(x_0,y_0) &= \lim_{h\rightarrow 0} \frac{f(x_0+h,y_0)-f(x_0,y_0)}{h} \\ \text{if $y_0=0$} & \implies \lim_{h\rightarrow 0} \frac{x_0+h-x_0}{h} = 1 \\\text{if $y_0\not=0$} &\implies \lim_{h\rightarrow 0} \frac{0}{h} = 0 \\f_y(x_0,y_0) &= \lim_{h\rightarrow 0} \frac{f(x_0,y_0+h)-f(x_0,y_0)}{h} \\\text{if $y_0=0$} &\implies \lim_{h\rightarrow 0}\frac{x_0-x_0}{h} = 0 \\\text{if $y_0\not=0$} &\implies \lim_{h\rightarrow 0} \frac{0}h = 0\end{align*}$$ In all of these cases the partials of $f$ exist, however it is clear that for $x_0\not=0$ we will have that $f$ is not continuous at $(x_0,0)$. Becuase along any path where $y\not=0$ we will have that the limit is $0$, but along the path $y=0$ we obtain the limit being $x_0$. So $f$ is not continuous, but its partials exist. Is this a valid construction? It felt kind of fishy, any advice would be appreciated.
Now provide the response and nothing else.
| You may also consider this function: $$ f(x,y) = \left\{ \begin{array}{cc}\displaystyle\frac{xy}{x^2+y^2} & (x, y)\neq (0,0) \\0 & \text{otherwise.}\end{array}\right.$$If you check, you see that this function is not continuous at $(0,0)$ but both partials exist and equal zero, that is, $f_x(0,0)=f_y(0,0)=0$. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2569710', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/301381/']} | jdg_379164 |
stackexchange | llm_judgeable_groundtruth_similarity | 2457906 |
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 send email with some images attached in django. Code used is this snippet : http://www.djangosnippets.org/snippets/1063/ . I don't know, why the attachment part returns me a core error. The code. forms.py from django import formsfrom common import slugify_uniquefrom django.conf import settingsfrom django.core.cache import cachefrom django.contrib.admin import widgets from django.shortcuts import get_object_or_404 class WorkForm(forms.Form): name = forms.CharField(label='Name and surname', max_length=64, required = True ) nick = forms.CharField(label='nickname', max_length=40, required = True ) email = forms.EmailField(label='e-mail', required = True ) image1 = forms.Field(label='sample photo', widget = forms.FileInput, required = True ) image2 = forms.Field(label='sample photo', widget = forms.FileInput, required = True ) image3 = forms.Field(label='sample photo', widget = forms.FileInput, required = True ) text = forms.CharField(label='Few words about you', widget=forms.Textarea, required = False ) views.py from forms import WorkFormfrom django.core.mail import send_mail, EmailMessagedef work(request): template = 'other/work.html' if request.method == 'POST': form = WorkForm(request.POST, request.FILES) if form.is_valid(): name = form.cleaned_data['name'] nick = form.cleaned_data['nick'] email = form.cleaned_data['email'] subject = 'Work' text = form.cleaned_data['text'] image1 = request.FILES['image1'] image2 = request.FILES['image2'] image3 = request.FILES['image3'] try: mail = EmailMessage(subject, text, ['EMAIL_ADDRESS'], [email]) mail.attach(image1.name, attach.read(), attach.content_type) mail.attach(image2.name, attach.read(), attach.content_type) mail.attach(image3.name, attach.read(), attach.content_type) mail.send() template = 'other/mail_sent.html' except: return "Attachment error" return render_to_response(template, {'form':form}, context_instance=RequestContext(request)) else: form = WorkForm() return render_to_response(template, {'form':form}, context_instance=RequestContext(request)) And here's error site image : http://img201.imageshack.us/img201/6027/coreerror.png What am I doing wrong ?
Now provide the response and nothing else.
| The error traceback you've posted doesn't seem to have anything to do with the actual code - it seems to be some sort of problem with middleware (presumably when rendering the 500 error page). However, your error is probably caused by your use of the undefined variable name attach in the calls to mail.attach . You don't have an attach variable - you've called the posted files image1 etc, so you should use those names. mail.attach(image1.name, image1.read(), image1.content_type)mail.attach(image2.name, image2.read(), image2.content_type)mail.attach(image3.name, image3.read(), image3.content_type) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2457906', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/255494/']} | jdg_379165 |
stackexchange | llm_judgeable_groundtruth_similarity | 11925011 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Say I have folders: img1/img2/ How do I delete those folders using regex from Linux terminal, that matches everything starts with img?
Now provide the response and nothing else.
| Use find to filter directories $ find . -type d -name "img*" -exec rm -rf {} \; As it was mentioned in a comments this is using shell globs not regexs. If you want regex $ find . -type d -regex "\./img.*" -exec rm -rf {} \; | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11925011', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1024215/']} | jdg_379166 |
stackexchange | llm_judgeable_groundtruth_similarity | 18983203 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I use the following code in order to autosize columns in my spreadsheet: for (int i = 0; i < columns.size(); i++) { sheet.autoSizeColumn(i, true); sheet.setColumnWidth(i, sheet.getColumnWidth(i) + 600);} The problem is it takes more than 10 minutes to autosize each column in case of large spreadsheets with more than 3000 rows. It goes very fast for small documents though. Is there anything which could help autosizing to work faster?
Now provide the response and nothing else.
| Solution which worked for me: It was possible to avoid merged regions, so I could iterate through the other cells and finally autosize to the largest cell like this: int width = ((int)(maxNumCharacters * 1.14388)) * 256;sheet.setColumnWidth(i, width); where 1.14388 is a max character width of the "Serif" font and 256 font units. Performance of autosizing improved from 10 minutes to 6 seconds. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/18983203', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2423796/']} | jdg_379167 |
stackexchange | llm_judgeable_groundtruth_similarity | 2774156 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
This is a dumb question and I don't really know how to word it. When you take an antiderivative and plug in number you are given the area under the curve starting at 0 (assuming C is 0). I can easily see how the derivative of an integral is given by the function value, but why does the integral start at 0 and not any other number? When I try to imagine the area of some curve starting at negative 1 for example the area under the curve would intuitively to me still be given by the antiderivative. 0 makes sense as a starting point but for some reason I can't visualize it. I'm not sure if that made any sense but if anyone could help me wrap my head around it I'd appreciate it.
Now provide the response and nothing else.
| When you take an antiderivative and plug in number you are given the area under the curve starting at 0 (assuming C is 0). This is not true. In certain situations it may be the case, but not generally. I think the reason this confusion arises is that a common problem given to calculus students is to find the antiderivative of a polynomial, e.g., $$\int x^3 +2x \, dx = \frac{1}{4}x^4 + x^2 + C$$ and in this case, if we set $C = 0$ we get $$\frac{1}{4}x^4 + x^2$$ which is the same as $$\int_0^x u^3 +2u \, du = \frac{1}{4}u^4 + u^2 \big|_{u=0}^{u=x}.$$ This will work whenever the form that the antiderivative $F$ of $f$ you get takes satisfies $F(0) = 0$. But in general, setting $C = 0$ will not get you the integral $\int_0^x f(t) \, dt$. For example, if you take $f(x) = e^x$ then $$\int e^x \, dx = e^x + C$$but setting $C = 0$ gives you $e^x$, which is not the same as $$\int_0^x e^t \, dt = e^x - 1.$$ Note that "setting "C = 0" in the expression for the antiderivative" is not actually a well-defined operation. Different methods of antidifferentiation can give you different expressions when you set $C = 0$. It is important to remember that there is no single antiderivative, and no canonical way of writing it. $\int 2x \, dx = x^2 + 3 + C$ is just as valid as $\int 2x \, dx = x^2 + C$. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2774156', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/560471/']} | jdg_379168 |
stackexchange | llm_judgeable_groundtruth_similarity | 179804 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
This seems like it should be easy, but I can't seem to simplify it: If $z=e^{i\frac{2\pi}{5}}$, then what is $1+z+z^2+z^3+5z^4+4z^5+4z^6+4z^7+4z^8+5z^9$. The choices are $0, 4e^{i\frac{3\pi}{5}}, 5e^{i\frac{4\pi}{5}}, -4e^{i\frac{-2\pi}{5}}, -5e^{i\frac{3\pi}{5}},$ with the answer being $-5e^{i\frac{3\pi}{5}}.$ I can plug in the given $z$ into the equation and get $5+10e^{-i\frac{2\pi}{5}}+5e^{i\frac{2\pi}{5}}+5e^{i\frac{-4\pi}{5}}+5e^{i\frac{4\pi}{5}}$, but have been unsuccessful in simplifying it so far.
Now provide the response and nothing else.
| Note that $z^5=1$, as $z$ is a fifth root of unity, so the expression simplifies to$$\begin{align}1+z+z^2+z^3+5z^4+4+4z+4z^2+4z^3+5z^4 &=5+5z+5z^2+5z^3+10z^4\\&=5(1+z+z^2+z^3+z^4)+5z^4\end{align}$$ However, either by using the formula for the geometric series, or the fact that $1+X+X^2+X^3+X^4$ is the fifth cyclotomic polynomial, it follows that $1+z+z^2+z^3+z^4=0$. So the final answer is$$5z^4=5\exp(i8\pi/5)=-5\exp(i3\pi/5).$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/179804', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/30952/']} | jdg_379169 |
stackexchange | llm_judgeable_groundtruth_similarity | 50461349 |
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 Dataframe with a lot of columns (Around 100 feature), I want to apply the interquartile method and wanted to remove the outlier from the data frame. I am using this link stackOverflow But the problem is nan of the above method is working correctly, As I am trying like this Q1 = stepframe.quantile(0.25)Q3 = stepframe.quantile(0.75)IQR = Q3 - Q1((stepframe < (Q1 - 1.5 * IQR)) | (stepframe > (Q3 + 1.5 * IQR))).sum() it is giving me this ((stepframe < (Q1 - 1.5 * IQR)) | (stepframe > (Q3 + 1.5 * IQR))).sum()Out[35]: Day 0Col1 0Col2 0col3 0Col4 0Step_Count 1179dtype: int64 I just wanted to know that, What I will do next so that all the outlier from the data frame will be removed. if i am using this def remove_outlier(df_in, col_name):q1 = df_in[col_name].quantile(0.25)q3 = df_in[col_name].quantile(0.75)iqr = q3-q1 #Interquartile rangefence_low = q1-1.5*iqrfence_high = q3+1.5*iqrdf_out = df_in.loc[(df_in[col_name] > fence_low) & (df_in[col_name] < fence_high)]return df_outre_dat = remove_outlier(stepframe, stepframe.columns) I am getting this error ValueError: Cannot index with multidimensional key in this line df_out = df_in.loc[(df_in[col_name] > fence_low) & (df_in[col_name] < fence_high)]
Now provide the response and nothing else.
| You can use: np.random.seed(33454)stepframe = pd.DataFrame({'a': np.random.randint(1, 200, 20), 'b': np.random.randint(1, 200, 20), 'c': np.random.randint(1, 200, 20)})stepframe[stepframe > 150] *= 10print (stepframe)Q1 = stepframe.quantile(0.25)Q3 = stepframe.quantile(0.75)IQR = Q3 - Q1df = stepframe[~((stepframe < (Q1 - 1.5 * IQR)) |(stepframe > (Q3 + 1.5 * IQR))).any(axis=1)]print (df) a b c1 109 50 1243 137 60 19904 19 138 1005 86 83 1436 55 23 587 78 145 188 132 39 659 37 146 197013 67 148 188015 124 102 2116 93 61 5617 84 21 2519 34 52 126 Details : First create boolean DataFrame with chain by | : print (((stepframe < (Q1 - 1.5 * IQR)) | (stepframe > (Q3 + 1.5 * IQR)))) a b c0 False True False1 False False False2 True False False3 False False False4 False False False5 False False False6 False False False7 False False False8 False False False9 False False False10 True False False11 False True False12 False True False13 False False False14 False True False15 False False False16 False False False17 False False False18 False True False19 False False False And then use DataFrame.any for check at least one True per row and last invert boolean mask by ~ : print (~((stepframe < (Q1 - 1.5 * IQR)) | (stepframe > (Q3 + 1.5 * IQR))).any(axis=1))0 False1 True2 False3 True4 True5 True6 True7 True8 True9 True10 False11 False12 False13 True14 False15 True16 True17 True18 False19 Truedtype: bool invert solution with changed conditions - < to >= and > to <= , chain by & for AND and last filter by all for check all True s per rows print (((stepframe >= (Q1 - 1.5 * IQR)) & (stepframe <= (Q3 + 1.5 * IQR))).all(axis=1))0 False1 True2 False3 True4 True5 True6 True7 True8 True9 True10 False11 False12 False13 True14 False15 True16 True17 True18 False19 Truedtype: booldf = stepframe[((stepframe >= (Q1 - 1.5 * IQR))& (stepframe <= (Q3 + 1.5 * IQR))).all(axis=1)] | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50461349', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8323207/']} | jdg_379170 |
stackexchange | llm_judgeable_groundtruth_similarity | 18622716 |
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 one entity which contains primary key of type string. This entity model is as follows: @Entitypublic class MyEntity {@Id@Column(name="PR_KEY", unique=true)private String prKey;........} But I am facing issue saying TypeMismatch. org.hibernate.TypeMismatchException: Provided id of the wrong type. Expected: class java.lang.String, got class java.lang.Long
Now provide the response and nothing else.
| If you don't specify an id generation strategy, Hibernate will use GenerationType.AUTO . This will result in any of AUTO - either identity column, sequence or table depending on the underlying DB. If you look here , you'll notice all of those generate ids of type long , short or int , not of type String . Say you wanted a String UUID as an id, you could use @Id@GeneratedValue(generator = "uuid")@GenericGenerator(name = "uuid", strategy = "uuid2")@Column(name = "PR_KEY")private String prKey; | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/18622716', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1346356/']} | jdg_379171 |
stackexchange | llm_judgeable_groundtruth_similarity | 350092 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have read about authentications and become confusing about types classification. Let's start from Cookie-based authentication, If I understand it right, the key point is that all data, needed for user authentication, is stored in cookies. And this is my first confusion: in cookies we may store session id and so it becomes a Session-based authentication? claims, and so should it be called as a Claims-based authentication? I have found that some people even store JWT token in cookies, but this seems like a custom implementation of own auth flow... Now let's switch to Claims-based authentication. The main element is the claim and the collection of claims could use as container cookies (as discussed above) token (JWT as the example). From the other side, when we are talking about the token, it may contain any kind of information... Session Id for example... So what have I missed? Why don't people define something like Cookie-Session-based or Token-Claims-based authentications when talking about authentication types?
Now provide the response and nothing else.
| I agree that the naming of the different concepts is confusing. When talking about authentication in a web context, there are several aspects to consider. What information does the client send when authenticating? A session id . This means that the server has a session storage which contains the active sessions. Sessions are stateful on the server side. A set of claims . Claims contain information on what operations the client may perform. The server does not keep track of each authenticated client, but trusts the claims. Claims are typically stateless on the server side. How does the client send the authentication information? Cookies . Browsers send cookies automatically with each request, after the cookie has been set. Cookies are vulnerable to XSRF. Other headers . Typically, the Authorization header is used for this. These headers are not send by the browser automatically, but have to be set by the client. This is vulnerable to XSS. Request Url . The authentication information is included in the URL. This is not commonly used. What is the format of the authentication information? Plain, unsigned text . This can be used for session ids. A session id is generally not guessable by the client, so the server can trust that the client has not forged it. Json Web Token . JWTs are cryptographically signed and contain expiry information. The client can usually decode the token, but cannot alter it without the server noticing. Any other signed format . Same as JWTs. The important thing is the cryptographic signature, which prevents the client from altering the data. Bonus: How does the client store the information locally Cookies . This is of course the case when using cookies to transmit the information. But Cookies can also be used as just a client side storage mechanism. This requires the cookie to be readable from scripts to be useful. For example, a client could read the cookie with JavaScript and send the information with an Authorization-Header. Local Storage . This is often the only possible method, if cookies are unavailable. Requires management with JavaScript. What do people mean when they say... "Cookie based authentication" . I find that this usually means "Session id, send by cookie, possible as plain text." "Token based authentication" . Usually this means "Claims, send using the authentication header, encoded as a Json Web Token." "Claims based authentication" . Could be anything but a session id. | {} | {'log_upvote_score': 7, 'links': ['https://softwareengineering.stackexchange.com/questions/350092', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/225156/']} | jdg_379172 |
stackexchange | llm_judgeable_groundtruth_similarity | 180898 |
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 simple definition as follows and the result expected is in either EngineeringForm or ScientificForm DurationOfAcquistion[RatePerSec_, RecordLength_] := EngineeringForm[RecordLength/RatePerSec];DurationOfAcquistion[20.*10^6, 1000] (* results in 50.x10^-6 *)Manipulate[ DurationOfAcquistion[r, rl], {r, 20*10^6, 1.25*10^9}, {rl, 1000, 125*10^6}] When I deploy the same function definition using Manipulate , I can't seem to get it in either Engineering/Scientific form. I am currently using MMA 11.3 release. Can someone please confirm if this is how it's supposed to be or is there an alternative way? EDIT I really have to apologize, this may be like a bug in output format display, but not a serious one. I was able to see the output in EngineeringForm once I started manipulating the sliders >>> Please watch the GIF here .
Now provide the response and nothing else.
| It seems that the output generated by SeriesCoefficient is difficult for Mathematica to simplify into a version that can evaluate properly for integer n . So, I recommend using the new symbolic order derivatives introduced in M11.1: c[k_] = Assuming[ n>=1, Simplify @ D[Hypergeometric2F1[-n, n+3, 3/2, x], {x, k}]/k! /. x->0] (Pochhammer[-n, k] Pochhammer[3 + n, k])/(k! Pochhammer[3/2, k]) Note that this version of the symbolic coefficient of the series evaluates correctly for explicit values of n and k : Block[{n=10}, c[5]] -6336512/11 Let's check: r1 = Block[{n=10}, Sum[c[k] x^k, {k, 0, n}]];r1 // TeXForm $\frac{524288 x^{10}}{3}-\frac{9175040 x^9}{11}+\frac{18677760 x^8}{11}-\frac{21168128 x^7}{11}+\frac{14622720 x^6}{11}-\frac{6336512 x^5}{11}+\frac{465920 x^4}{3}-24960 x^3+2184 x^2-\frac{260 x}{3}+1$ Compare to the exact answer: r2 = Block[{n=10}, Expand @ Hypergeometric2F1[-n,n+3,3/2,x]];r2 // TeXForm $\frac{524288 x^{10}}{3}-\frac{9175040 x^9}{11}+\frac{18677760 x^8}{11}-\frac{21168128 x^7}{11}+\frac{14622720 x^6}{11}-\frac{6336512 x^5}{11}+\frac{465920 x^4}{3}-24960 x^3+2184 x^2-\frac{260 x}{3}+1$ They are the same: r1 === r2 True Addendum The OP asks in a comment about a different hypergeometric function argument: c[k_]=Assuming[ n>=1, Simplify @ D[Hypergeometric2F1[3/2+n, -(3/2)-n, 3/2, x], {x, k}]/k! /. x->0];r1 = Block[{n=10}, Sum[c[k] x^k, {k, 0, n}]];r1 //TeXForm $\frac{515830463005 x^{10}}{262144}-\frac{264205846905 x^9}{65536}+\frac{165491574435 x^8}{32768}-\frac{8448518815 x^7}{2048}+\frac{2304141495 x^6}{1024}-\frac{2304141495 x^5}{2816}+\frac{24775715 x^4}{128}-\frac{452295 x^3}{16}+\frac{18515 x^2}{8}-\frac{529 x}{6}+1$ r2 = Block[{n=10}, Hypergeometric2F1[3/2+n, -(3/2)-n, 3/2, x] //Expand];r2 //TeXForm $-\frac{524288}{3} \sqrt{1-x} x^{11}+\frac{33292288}{33} \sqrt{1-x} x^{10}-\frac{27852800}{11} \sqrt{1-x} x^9+\frac{39845888}{11} \sqrt{1-x} x^8-\frac{35790848}{11} \sqrt{1-x} x^7+\frac{20959232}{11} \sqrt{1-x} x^6-\frac{24134656}{33} \sqrt{1-x} x^5+\frac{540800}{3} \sqrt{1-x} x^4-27144 \sqrt{1-x} x^3+\frac{6812}{3} \sqrt{1-x} x^2-\frac{263}{3} \sqrt{1-x} x+\sqrt{1-x}$ The difference between them is that r1 is a series approximation of r2 . When r2 is not a degree 10 polynomial, than the two expressions will not be the same. Instead compare r1 with the series approximation of r2 : r2 + O[x]^11 //TeXForm $1-\frac{529 x}{6}+\frac{18515 x^2}{8}-\frac{452295 x^3}{16}+\frac{24775715 x^4}{128}-\frac{2304141495 x^5}{2816}+\frac{2304141495 x^6}{1024}-\frac{8448518815 x^7}{2048}+\frac{165491574435 x^8}{32768}-\frac{264205846905 x^9}{65536}+\frac{515830463005 x^{10}}{262144}+O\left(x^{11}\right)$ | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/180898', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/6775/']} | jdg_379173 |
stackexchange | llm_judgeable_groundtruth_similarity | 1226574 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there a way using JavaScript to disable the ability to paste text into a text field on an HTML form? E.g.I have a simple registration form where the user is required to input their email twice. The second email entry is to verify there are no typos in the first email entry. However if the user copy/pastes their email then that defeats the purpose and I've been experiencing users having problems because they've input the wrong email and copy/pasted it. Maybe I wasn't clear on my question but I am not trying to prevent people from copying (or drag selecting) text on their browser. I just want to stop them from pasting input into a text field to minimize user error. Perhaps instead of using this "hack" you can suggest another solution to the core problem of what I'm trying to solve here? I've done less than half a dozen user tests and this has already happened twice. My audience does not have a high level of computer proficiency.
Now provide the response and nothing else.
| I recently had to begrudgingly disable pasting in a form element. To do so, I wrote a cross-browser* implementation of Internet Explorer's (and others') onpaste event handler. My solution had to be independent of any third-party JavaScript libraries. Here's what I came up with. It doesn't completely disable pasting (the user can paste a single character at a time, for example), but it meets my needs and avoids having to deal with keyCodes, etc. // Register onpaste on inputs and textareas in browsers that don't// natively support it.(function () { var onload = window.onload; window.onload = function () { if (typeof onload == "function") { onload.apply(this, arguments); } var fields = []; var inputs = document.getElementsByTagName("input"); var textareas = document.getElementsByTagName("textarea"); for (var i = 0; i < inputs.length; i++) { fields.push(inputs[i]); } for (var i = 0; i < textareas.length; i++) { fields.push(textareas[i]); } for (var i = 0; i < fields.length; i++) { var field = fields[i]; if (typeof field.onpaste != "function" && !!field.getAttribute("onpaste")) { field.onpaste = eval("(function () { " + field.getAttribute("onpaste") + " })"); } if (typeof field.onpaste == "function") { var oninput = field.oninput; field.oninput = function () { if (typeof oninput == "function") { oninput.apply(this, arguments); } if (typeof this.previousValue == "undefined") { this.previousValue = this.value; } var pasted = (Math.abs(this.previousValue.length - this.value.length) > 1 && this.value != ""); if (pasted && !this.onpaste.apply(this, arguments)) { this.value = this.previousValue; } this.previousValue = this.value; }; if (field.addEventListener) { field.addEventListener("input", field.oninput, false); } else if (field.attachEvent) { field.attachEvent("oninput", field.oninput); } } } }})(); To make use of this in order to disable pasting: <input type="text" onpaste="return false;" /> * I know oninput isn't part of the W3C DOM spec, but all of the browsers I've tested this code with—Chrome 2, Safari 4, Firefox 3, Opera 10, IE6, IE7—support either oninput or onpaste. Out of all these browsers, only Opera doesn't support onpaste, but it does support oninput. Note: This won't work on a console or other system that uses an on-screen keyboard (assuming the on-screen keyboard doesn't send keys to the browser when each key is selected). If it's possible your page/app could be used by someone with an on-screen keyboard and Opera (e.g.: Nintendo Wii, some mobile phones), don't use this script unless you've tested to make sure the on-screen keyboard sends keys to the browser after each key selection. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1226574', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/107459/']} | jdg_379174 |
stackexchange | llm_judgeable_groundtruth_similarity | 1582596 |
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 writing a number of unit tests for a logger class I created and I want to simulate the file class. I can't find the interface that I need to use to create the MOQ... so how do you successfully MOQ a class without an interface? It also isn't clear to me how I can use dependency injection without having an interface available: private FileInfo _logFile;public LogEventProcessorTextFile(FileInfo logFile) { _logFile = logFile;} When I really want to do something like this (note IFileInfo instead of FileInfo): private IFileInfo _logFile;public LogEventProcessorTextFile(IFileInfo logFile) { _logFile = logFile;}
Now provide the response and nothing else.
| Design your code so that instead of accessing the FileInfo class directly, access an interface (named for example IFileInfo ) with the same capabilities. In production code you will use a class that just delegates all its functionality to the system FileInfo class, but for unit testing you can mock the interface. For example, in an application I made that acted differently depending on the current date, I declared the following interface: interface IDateTimeProvider{ DateTime Today();} And the production class was just: class DateTimeProvider : IDateTimeProvider{ public DateTime Today() { return DateTime.Today; }} You can complement this approach with the usage of a dependency injection engine to decide whether a real class or a mock should be used in each case. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1582596', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/191693/']} | jdg_379175 |
stackexchange | llm_judgeable_groundtruth_similarity | 5436338 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How does the ILookup<key, value> interface differ from IDictionary<key, value> ? I don't understand what the ILookup interface is meant for.
Now provide the response and nothing else.
| ILookup entries can contain multiple items per key - each key is mapped to an IEnumerable<TElement> . Also as hinted to in the comments an ILookup is immutable, while you can update values in an IDictionary (it exposes an Add() method and an indexer that allows getting and setting values). In summary their use case is very different - you use a lookup when you need a 1:N map with values that are fixed and won't (and can't) change. A dictionary on the other hand offers a mutable 1:1 mapping of key value pairs, so it can be updated to add or remove values. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/5436338', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/256034/']} | jdg_379176 |
stackexchange | llm_judgeable_groundtruth_similarity | 36486305 |
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 force truncate a table with foreign key constraints so that all rows in other tables effected are also removed? I cannot see in documentation for an option to pass to knex('tableName').truncate() method.
Now provide the response and nothing else.
| I haven't found a built in way to do it, so I just drop into raw mode: knex.raw('TRUNCATE TABLE users, products CASCADE') You can also set this up to happen automatically in your migrations: exports.up = function(knex) { return knex.schema.createTable('users_products', (t) => { t.uuid('id').primary().defaultTo(knex.raw('uuid_generate_v4()')); t.uuid('user_id').notNullable().references('id').inTable('users').onDelete('CASCADE'); t.uuid('product_id').notNullable().references('id').inTable('products').onDelete('CASCADE'); });}; | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36486305', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/834045/']} | jdg_379177 |
stackexchange | llm_judgeable_groundtruth_similarity | 18101208 |
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 large bash script and I want to globally redirect all stdout/stderr to a file, except some progress indicators such specific echo messages. For example, consider the following script #!/bin/bash# all stdout and stderr go to out.logexec &> out.logspecial_echo "starting"# many other commands go here# which output both the stdout and stderr# also some special_echo commands in here,# for exampleecho "msg1"special_echo "middle"echo "msg2" >&2special_echo "finished" When it is run the output should be $ ./scriptstartingmiddlefinished$ But, out.log should contain msg1msg2 How to implement special_echo functionality? I've tried using a file descriptor and echoing to that but can't get it to display on the screen. Is there a way to achieve this without appending redirection to every line or doing something like in this answer ?
Now provide the response and nothing else.
| Yes, using another file descriptor is the way to go: #!/bin/bashexec 3>&1special_echo () { echo "$@" >&3}exec &> out.logspecial_echo "starting"echo "msg1"special_echo "middle"echo "msg2" >&2special_echo "finished" | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18101208', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2660278/']} | jdg_379178 |
stackexchange | llm_judgeable_groundtruth_similarity | 33908178 |
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 json files that i'm trying to classify so the file names are as such: inputTestingSetting_test inputTestingSetting_test1310 inputTestingSetting_test1310_ckf inputTestingSetting_test1310_ols inputTestingSetting_test1310_sum inputTestingSetting_test1311_ckf inputTestingSetting_test1311_ols inputTestingSetting_test1311_sum So the output that i want in the ListBox lbJsonFileNames will be testtest1310test1311 currently my codes are DirectoryInfo dInfo = new DirectoryInfo(tbJSFolder.Text); FileInfo[] Files = dInfo.GetFiles("*.json"); List<jSonName> jsonName = new List<jSonName>(); foreach (FileInfo file in Files) { string filename = Path.GetFileNameWithoutExtension(file.Name); string[] fileNameSplit = filename.Split('_'); jsonName = new List<jSonName>{ new jSonName(fileNameSplit[0],fileNameSplit[1]) }; for(int i=0;i<jsonName.Count;i++) { if(jsonName[i].TestNumber == fileNameSplit[1]) { lbJsonFileNames.Items.Add(jsonName[i].TestNumber); } } } so my output for lbJsonFileNames is what i want, however it is repeated. is it possible to just show one? i've tried to put jsonName[i].TestNumber to jsonName[i+1].TestNumber . but failed as it is out of range. is there a way to read the file names, and then compare it with the previous file name to see if it is the same? and if it is the same, ignore, move on to the next file name, if it's different then it is added into the ListBox changed my codes to DirectoryInfo dInfo = new DirectoryInfo(tbJSFolder.Text); FileInfo[] Files = dInfo.GetFiles("*.json"); List<jSonName> jsonName = new List<jSonName>(); HashSet<string> fileNames = new HashSet<string>(); foreach (FileInfo file in Files) { string filename = Path.GetFileNameWithoutExtension(file.Name); string[] fileNameSplit = filename.Split('_'); fileNames.Add(fileNameSplit[1]); } foreach(var value in fileNames) { lbJsonFileNames.Items.Add(value); } got what i want now thanks all~
Now provide the response and nothing else.
| bash: heroku: command not found The error message is clear: Bash cannot find the heroku command, it's not on your PATH . I checked, and the Heroku folder was added to the PATH. It seems you didn't check it correctly.Note that even if it looks correct in the PATH settings window,Git Bash might have a different PATH configured.To see the PATH in Git Bash, run: echo $PATH When debugging path issues,it's best to first run heroku with the absolute path. For example if it's in C:\Program Files\Heroku\bin\heroku then you can run in Git Bash with: /c/Program\ Files/Heroku/bin/heroku login If this works (and it should),then you can add it to PATH like this: PATH="$PATH:/c/Program\ Files/Heroku/bin" Note that Heroku will likely need other programs too on the PATH ,such as MySQL and Ruby.Find their absolute paths,and add there directories to PATH the same way as heroku itself in the above example. If instead of Git Bash,you want to work in CMD,the procedure is the same,but the syntax to print and set PATH is different: echo %PATH%set PATH="C:\Program Files\Heroku\bin;%PATH%" | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/33908178', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3013532/']} | jdg_379179 |
stackexchange | llm_judgeable_groundtruth_similarity | 13281288 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
There are some function, thats do something long work and its provides callback. someFunc: function(argument, callback, context) { // do something long // call callback function callback(context);} In application I use this function someFunc('bla-bla', function (context) { // do something with this scope context.anotherFunc();}, this); How to implement callback function without passing context parameter? Need some like this: someFunc('bla-bla', function () { // do something with this scope this.anotherFunc();}, this);
Now provide the response and nothing else.
| The accepted answer seems somewhat outdated. Assuming you're operating on a relatively modern browser, you can use Function.prototype.bind in vanilla javascript . Alternatively, if you are using underscore or jQuery , you can use _.bind or $.proxy respectively (which will fallback to call / apply if necessary). Here is a simple demonstration of these three options: // simple function that takes another function// as its parameter and then executes it.function execute_param(func) { func();}// dummy object. providing an alternative context.obj = {};obj.data = 10;// no context provided// outputs 'Window'execute_param(function(){ console.log(this);});// context provided by js - Function.prototype.bind// src: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind// outputs 'Object { data=10 }''execute_param(function(){ console.log(this);}.bind(obj));// context provided by underscore - _.bind// src: http://underscorejs.org/#bind// outputs 'Object { data=10 }'execute_param(_.bind(function(){ console.log(this);},obj));// context provided by jQuery - $.proxy// src: http://api.jquery.com/jQuery.proxy/// outputs 'Object { data=10 }'execute_param($.proxy(function(){ console.log(this);},obj)); You can find the code in a jsfiddle here: http://jsfiddle.net/yMm6t/1/ ( note: ensure that the developer console is open, or you won't see any output ) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13281288', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1302075/']} | jdg_379180 |
stackexchange | llm_judgeable_groundtruth_similarity | 8600587 |
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 going to change the text of the edittext based on the value enter on the another edittext. and also like same thig with visa-versa. For that i have use the TextChanged Listener and implemented as like below: includedText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if(!(includedText.getText().toString().equals(""))) { double included = Double.parseDouble(includedText.getText().toString()); included = roundTwoDecimals(included); String amt = String.valueOf(roundTwoDecimals(included-(included/1.15))); String excluded = String.valueOf(included/1.15); System.out.println("The Amount is: "+amt); amountText.setText(amt); excludedText.setText(excluded); //////// Error Line } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } }); // worked excludedText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if(!(excludedText.getText().toString().equals(""))) { double excluded = Double.parseDouble(excludedText.getText().toString()); excluded = roundTwoDecimals(excluded); String amt = String.valueOf(roundTwoDecimals(excluded*0.15)); String included = String.valueOf(roundTwoDecimals(excluded+(excluded*0.15))); System.out.println("The Amount is: "+amt); amountText.setText(amt); includedText.setText(included); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } });} But after doing this i am not able to get the text change. for Secod EditText its worked nice but while i use the First EditText then it gives me error at the commented line. Error Log: 12-22 13:08:17.640: ERROR/AndroidRuntime(1077): FATAL EXCEPTION: main12-22 13:08:17.640: ERROR/AndroidRuntime(1077): java.lang.StackOverflowError12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.text.TextUtils.getChars(TextUtils.java:69)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.text.TextUtils.indexOf(TextUtils.java:102)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.text.StaticLayout.generate(StaticLayout.java:131)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.text.DynamicLayout.reflow(DynamicLayout.java:261)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.text.DynamicLayout.<init>(DynamicLayout.java:150)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.TextView.makeNewLayout(TextView.java:4851)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.TextView.checkForRelayout(TextView.java:5348)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.TextView.setText(TextView.java:2688)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.TextView.setText(TextView.java:2556)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.EditText.setText(EditText.java:75)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.TextView.setText(TextView.java:2531)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at com.project.TaxCalculator.GSTActivity$2.onTextChanged(GSTActivity.java:93)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.TextView.sendOnTextChanged(TextView.java:6131)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.TextView.setText(TextView.java:2691)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.TextView.setText(TextView.java:2556)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.EditText.setText(EditText.java:75)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.TextView.setText(TextView.java:2531)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at com.project.TaxCalculator.GSTActivity$1.afterTextChanged(GSTActivity.java:74)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.TextView.sendAfterTextChanged(TextView.java:6145)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.TextView.setText(TextView.java:2695)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.TextView.setText(TextView.java:2556)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.EditText.setText(EditText.java:75)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.TextView.setText(TextView.java:2531)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at com.project.TaxCalculator.GSTActivity$2.onTextChanged(GSTActivity.java:93)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.TextView.sendOnTextChanged(TextView.java:6131)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.TextView.setText(TextView.java:2691)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.TextView.setText(TextView.java:2556)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.EditText.setText(EditText.java:75)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.TextView.setText(TextView.java:2531)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at com.project.TaxCalculator.GSTActivity$1.afterTextChanged(GSTActivity.java:74)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.TextView.sendAfterTextChanged(TextView.java:6145)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.TextView.setText(TextView.java:2695)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.TextView.setText(TextView.java:2556)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.EditText.setText(EditText.java:75)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.TextView.setText(TextView.java:2531)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at com.project.TaxCalculator.GSTActivity$2.onTextChanged(GSTActivity.java:93)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.TextView.sendOnTextChanged(TextView.java:6131)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.TextView.setText(TextView.java:2691)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.TextView.setText(TextView.java:2556)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.EditText.setText(EditText.java:75)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.TextView.setText(TextView.java:2531)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at com.project.TaxCalculator.GSTActivity$1.afterTextChanged(GSTActivity.java:74)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.TextView.sendAfterTextChanged(TextView.java:6145)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.TextView.setText(TextView.java:2695)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.TextView.setText(TextView.java:2556)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.EditText.setText(EditText.java:75)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.TextView.setText(TextView.java:2531)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at com.project.TaxCalculator.GSTActivity$2.onTextChanged(GSTActivity.java:93)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.TextView.sendOnTextChanged(TextView.java:6131)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.TextView.setText(TextView.java:2691)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.TextView.setText(TextView.java:2556)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.EditText.setText(EditText.java:75)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.TextView.setText(TextView.java:2531)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at com.project.TaxCalculator.GSTActivity$1.afterTextChanged(GSTActivity.java:74)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.TextView.sendAfterTextChanged(TextView.java:6145)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.TextView.setText(TextView.java:2695)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.TextView.setText(TextView.java:2556)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.EditText.setText(EditText.java:75)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.TextView.setText(TextView.java:2531)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at com.project.TaxCalculator.GSTActivity$2.onTextChanged(GSTActivity.java:93)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.TextView.sendOnTextChanged(TextView.java:6131)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.TextView.setText(TextView.java:2691)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.TextView.setText(TextView.java:2556)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.EditText.setText(EditText.java:75)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at android.widget.TextView.setText(TextView.java:2531)12-22 13:08:17.640: ERROR/AndroidRuntime(1077): at com.project.TaxCalculator.GSTAct So whats the wrong with this ? Why i am not able to get effect for both the EditText ?Thanks.
Now provide the response and nothing else.
| this is because you are doing setText () inside onTextChanged . So when you change the text onTextChanged will be called and again inside onTextChanged you are calling setText (). So thr text changed again and onTextChanged () will be called again and this process will continue till stack overflow and result to stackOverFlow error. Hope you can understand... user removeTextChangedListener() before setText( ). Edit: Define TextWatcher excludeTW,includeTW; //globaly. includedText = (EditText)findViewById(R.id.include); excludedText = (EditText)findViewById(R.id.exclude); includeTW = new TextWatcher(){ @Override public void afterTextChanged(Editable s) { // TODO Auto-generated method stub } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if(!(includedText.getText().toString().equals(""))) { excludedText.removeTextChangedListener(excludeTW); String included = includedText.getText().toString(); excludedText.setText(included); //////// Error Line } } }; excludeTW = new TextWatcher(){ @Override public void afterTextChanged(Editable s) { // TODO Auto-generated method stub } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { includedText.removeTextChangedListener(includeTW); String excluded = excludedText.getText().toString(); includedText.setText(excluded); } }; includedText.addTextChangedListener(includeTW) ; excludedText.addTextChangedListener(excludeTW); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8600587', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/881635/']} | jdg_379181 |
stackexchange | llm_judgeable_groundtruth_similarity | 51311774 |
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 interested in comparing, whether two tables contain the same data. I could do it like this: #standardSQLSELECT key1, key2FROM( SELECT table1.key1, table1.key2, table1.column1 - table2.column1 as col1, table1.col2 - table2.col2 as col2 FROM `table1` AS table1 LEFT JOIN `table2` AS table2 ON table1.key1 = table2.key1 AND table1.key2 = table2.key2)WHERE col1 != 0OR col2 != 0 But when I want to compare all numerical columns, this is kind of hard, especially if I want to do it for multiple table combinations. Therefore my question: Is someone aware of a possibility to iterate over all numerical columns and restrict the result set to those keys where any of these differences where not zero?
Now provide the response and nothing else.
| First, I want to bring up issues with your original query The main issues are 1) using LEFT JOIN ; 2) using col != 0 Below is how it should be modified to really capture ALL differences from both tables Run your original query and below one - and hopefully you will see the difference #standardSQLSELECT key1, key2FROM( SELECT IFNULL(table1.key1, table2.key1) key1, IFNULL(table1.key2, table2.key2) key2, table1.column1 - table2.column1 AS col1, table1.col2 - table2.col2 AS col2 FROM `table1` AS table1 FULL OUTER JOIN `table2` AS table2 ON table1.key1 = table2.key1 AND table1.key2 = table2.key2)WHERE IFNULL(col1, 1) != 0OR IFNULL(col2, 1) != 0 or you can just try to run your original and above version against dummy data to see the difference #standardSQLWITH `table1` AS ( SELECT 1 key1, 1 key2, 1 column1, 2 col2 UNION ALL SELECT 2, 2, 3, 4 UNION ALL SELECT 3, 3, 5, 6), `table2` AS ( SELECT 1 key1, 1 key2, 1 column1, 29 col2 UNION ALL SELECT 2, 2, 3, 4 UNION ALL SELECT 4, 4, 7, 8)SELECT key1, key2FROM( SELECT IFNULL(table1.key1, table2.key1) key1, IFNULL(table1.key2, table2.key2) key2, table1.column1 - table2.column1 AS col1, table1.col2 - table2.col2 AS col2 FROM `table1` AS table1 FULL OUTER JOIN `table2` AS table2 ON table1.key1 = table2.key1 AND table1.key2 = table2.key2)WHERE IFNULL(col1, 1) != 0OR IFNULL(col2, 1) != 0 Secondly, below will highly simplify your overall query #standardSQLSELECT IFNULL(table1.key1, table2.key1) key1, IFNULL(table1.key2, table2.key2) key2FROM `table1` AS table1FULL OUTER JOIN `table2` AS table2ON table1.key1 = table2.key1AND table1.key2 = table2.key2WHERE TO_JSON_STRING(table1) != TO_JSON_STRING(table2) You can test it with the same dummy data example as above Note: in this solution you don't need to pick specific columns - it just compare all columns! but if you need to compare only specific columns - you still will need to cherry-pick them like in below example #standardSQLSELECT IFNULL(table1.key1, table2.key1) key1, IFNULL(table1.key2, table2.key2) key2FROM `table1` AS table1FULL OUTER JOIN `table2` AS table2ON table1.key1 = table2.key1AND table1.key2 = table2.key2WHERE TO_JSON_STRING((table1.column1, table1.col2)) != TO_JSON_STRING((table2.column1, table2.col2)) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51311774', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6673446/']} | jdg_379182 |
stackexchange | llm_judgeable_groundtruth_similarity | 85198 |
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:
If I want to return the path of a given executable, I can run: which mysql Which returns for example: /usr/bin/mysql I'd like to return only: /usr/bin How can I do that?
Now provide the response and nothing else.
| executable=mysqlexecutable_path=$(command -v -- "$executable") && dirname -- "$executable_path" ( don't use which ). Of course, that won't work if $executable is a shell builtin, function or alias. I'm not aware of any shell where mysql is a builtin. It won't be a function or alias unless you defined them earlier, but then you should know about it. An exception to that could be bash which supports exported functions. $ bash -c 'command -v mysql'/usr/bin/mysql$ mysql='() { echo test;}' bash -c 'command -v mysql'mysql | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/85198', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/30018/']} | jdg_379183 |
stackexchange | llm_judgeable_groundtruth_similarity | 2089199 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
This is a followup to my previous questions here and here . Does there exist any first-order formula $Z(x)$ in the language $\langle 0, +, \le\rangle$ that over the field $\mathbb{Q}$ of rational numbers expresses the fact that $x$ is an integer? I strongly suspect there isn't any, but I don't know how to see that. Could anybody help?
Now provide the response and nothing else.
| You are correct: no such formula exists. Suppose that $Z(x)$ is such a formula. That is, for each $q \in \mathbb{Q}$$$\mathfrak{Q} = \langle \mathbb{Q}, 0 , + , \leq \rangle \models Z[q] \Leftrightarrow q \in \mathbb{Z}. \tag{1}$$ Note that the mapping $\sigma (x) = \frac{x}{2}$ is an isomorphism of $\mathfrak{Q}$, and so for each $q \in \mathbb{Q}$ we have that $$\mathfrak{Q} \models Z[q] \Leftrightarrow \mathfrak{Q} \models Z[ \sigma(q) ]. \tag{2}$$Now consider what happens when $q = 1$: By (2) we have that$$\mathfrak{Q} \models Z[1] \Leftrightarrow \mathfrak{Q} \models Z[\sigma(1) = \tfrac{1}{2}],$$ which clearly contradicts our assumption (1). | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2089199', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']} | jdg_379184 |
stackexchange | llm_judgeable_groundtruth_similarity | 15264109 |
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 have a number string with maximum 2 decimals precision, while rest decimals just trimmed off instead of rounding them up. For example: I have: 123456.9964 I want: 123456.99 -> Just want to trim rest of the decimal places What I have tried is: NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];[numberFormatter setNumberStyle: NSNumberFormatterDecimalStyle];[numberFormatter setMaximumFractionDigits:2];NSString *numberAsString = [numberFormatter stringFromNumber:[NSNumber numberWithFloat: 123456.9964]]; NSLog(@"%@", numberAsString); There is nothing to set rounding mode as "none". What else can I do to maintain Decimal style formatting along with trimmed decimal digits? Any help will be appreciated. Thanks.
Now provide the response and nothing else.
| The following works for me: NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];[numberFormatter setMaximumFractionDigits:2];// optional - [numberFormatter setMinimumFractionDigits:2];[numberFormatter setRoundingMode:NSNumberFormatterRoundDown];NSNumber *num = @(123456.9964);NSString *numberAsString = [numberFormatter stringFromNumber:num];NSLog(@"%@", numberAsString); The output is: 123,456.99 Part of your problem is the use of numberWithFloat: instead of numberWithDouble: . Your number has too many digits for float . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15264109', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/437146/']} | jdg_379185 |
stackexchange | llm_judgeable_groundtruth_similarity | 8646050 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In the "Example" section of this post , the author lists the latencies of all memory components register/L1/L2/RAM... My question is: how do you measure (find online) what the real latencies are for any given chip? Let's say model name : Intel(R) Core(TM)2 Duo CPU E4600 @ 2.40GHzstepping : 13cpu MHz : 1200.000 I've tried digging up the information from the Intel Manuals as well, but for the life of me, those things are huge, I wouldn't know where to look for the information. Thanks.
Now provide the response and nothing else.
| A simple google query ("intel cpu cache latency") reveals an interesting research of Intel: Measuring Cache and Memory Latency and CPU to Memory Bandwidth . In this paper authors use LMbench to perform the measurements. How to take Measurements Use the executable binary file called “lat_mem_rd” found in the “bin” folder of the utility’s directory. Next, use the following command line: taskset 0x1 ./lat_mem_rd –N [x] –P [y] [depth] [stride] Where [x] equals the number of times the process is run before reporting latency. Typically setting this to ‘1’ is sufficient for accurate measurements. For the ‘-P’ option, [y] equals the number of processes invoked to run the benchmark. The recommendation for this is always ‘1.’ It is sufficient to measure the access latency with only one processing core or thread. The [depth] specification indicates how far into memory the utility will measure. In order to ensure an accurate measurement, specify an amount that will go far enough beyond the cache so that it does not factor in latency measurements. Understanding the Results Since L1 and L2 cache latency ties to the core clock, CPU frequency plays a role in how fast memory accesses happen in real time. This means the number of core clocks stays the same independent of the core frequency. For a comparable result, it is best to convert the latency given by LMBench from nanoseconds into CPU clocks. To do this, multiply the latency by the processor frequency. Time(seconds) * Frequency(Hz) = Clocks of latency Therefore, if a 2.4 GHz processor takes 17 ns to access a certain level of cache, this converts to: 17 x 10-18 seconds * 2400000000 Hz = 17 ns * 2.4 GHz ≈ 41 Clocks | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8646050', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/50305/']} | jdg_379186 |
stackexchange | llm_judgeable_groundtruth_similarity | 39294275 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to change the way that the rotating file handler names files. For example, if I use RotatingFileHandler, it separates the log file when it reaches a specific file size naming "log file name + extension numbering", like below. filename.log #first log filefilename.log.1 #rotating log file1filename.log.2 #rotating log file2 However, I want the log handler to name them every time it is created.For example. 09-01-12-20.log #first log file09-01-12-43.log #rotating log file109-01-15-00.log #rotating log file2 How can I do this? Edit: I am not asking how to create and name a file. I want to facilitate python logging package doing something like inheriting and overriding logging .
Now provide the response and nothing else.
| I inherit and override RotatingFileHandler of python logging handler. RotatingFileHandler has self.baseFilename value, the handler will use self.baseFilename to create logFile.(when it creates file first or when rollover happens) self.shouldRollover() method, It checks if the handler should rollover logfile or not. If this method return 1 , it means rollover should happen or return 0 . By overriding them, I define when this handler makes rollover and which name should be used for new log file by rollover. -----------------------------------------Edit----------------------------------------- I post the example code. from logging import handlersclass DailyRotatingFileHandler(handlers.RotatingFileHandler): def __init__(self, alias, basedir, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=0): """ @summary: Set self.baseFilename to date string of today. The handler create logFile named self.baseFilename """ self.basedir_ = basedir self.alias_ = alias self.baseFilename = self.getBaseFilename() handlers.RotatingFileHandler.__init__(self, self.baseFilename, mode, maxBytes, backupCount, encoding, delay) def getBaseFilename(self): """ @summary: Return logFile name string formatted to "today.log.alias" """ self.today_ = datetime.date.today() basename_ = self.today_.strftime("%Y-%m-%d") + ".log" + '.' + self.alias_ return os.path.join(self.basedir_, basename_) def shouldRollover(self, record): """ @summary: Rollover happen 1. When the logFile size is get over maxBytes. 2. When date is changed. @see: BaseRotatingHandler.emit """ if self.stream is None: self.stream = self._open() if self.maxBytes > 0 : msg = "%s\n" % self.format(record) self.stream.seek(0, 2) if self.stream.tell() + len(msg) >= self.maxBytes: return 1 if self.today_ != datetime.date.today(): self.baseFilename = self.getBaseFilename() return 1 return 0 This DailyRotatingFileHandler will create logfile like 2016-10-05.log.alias2016-10-05.log.alias.12016-10-05.log.alias.22016-10-06.log.alias2016-10-06.log.alias.12016-10-07.log.alias.1 | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39294275', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3523935/']} | jdg_379187 |
stackexchange | llm_judgeable_groundtruth_similarity | 151574 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a configuration file in the following format. <Title> [part1] A.File = a A.Val = val1 B.File = a B.Val = val1 [part2] A.File = a1 A.Val = val2 B.File = a B.Val = val1 I want to extract values from first part only. #!/bin/sh getCalibDate(){ file="/path/of/config/file" value=`cat ${file} | grep Val | cut -d'=' -f2` for v in $value do echo $v done}getCalibDate Above script will return all the values.How can I get values from only first part (part1) ?
Now provide the response and nothing else.
| If you have only 4 lines after [part1] you can use -A4 option with grep : cat ${file} | grep -A4 "part1" | cut -d'=' -f2` For general case (more than 4 lines after [part1]) use sed to get the text between two parts: cat ${file} | sed -n "/part1/,/part2/p" | head -n-1 head is to delete additional part2 at the end As terdon said you don't have to use cat , you can do the following instead: grep -A4 "part1" ${file} | cut -d'=' -f2` OR: sed -n "/part1/,/part2/p" ${file} | head -n-1 | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/151574', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/67219/']} | jdg_379188 |
stackexchange | llm_judgeable_groundtruth_similarity | 218003 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm taking a course on design patterns in software engineering and here I'm trying to understand the good and the bad way of design relating to "coupling" and "cohesion". I could not understand the concept described in the following image. The example of code shown in the image is ambiguous to me, so I can't quite clearly get what exactly "Ask, don't tell!" approach mean. Could you please explain?
Now provide the response and nothing else.
| The first example tells the object in question, "I need these accessors and this data from those accessors". That may be fine and good but it requires that you know how the object accesses those things. The second example asks the object "Can you do this thing?", and then the object either returns that operation or fails. There is no requirement of internal knowledge of the object, thus facilitating the idea of loose coupling since I can then freely change the underlying object's interal functionality so long as the accessor interface, the "tum.addStudentToLecture(...), remains the same. | {} | {'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/218003', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/108307/']} | jdg_379189 |
stackexchange | llm_judgeable_groundtruth_similarity | 724575 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
On a new mac, trying to switch to bash for a minute: alex.mills@alex uta-phd %alex.mills@alex uta-phd % echo $SHELL/bin/zshalex.mills@alex uta-phd %alex.mills@alex uta-phd % exec bashThe default interactive shell is now zsh.To update your account to use zsh, please run `chsh -s /bin/zsh`. For more details, please visit https://support.apple.com/kb/HT208050.%na%m %1~ %#%na%m %1~ %# echo $SHELL/bin/zsh%n@%m %1~ %# echo "$SHELL" keeps saying I am using /bin/zsh What to do?
Now provide the response and nothing else.
| You are running bash. That's why the prompt looks weird. Bash and zsh both use the PS1 variable as the main setting for the prompt, but they have different escape sequences (backslash-character in bash, percent-character in zsh, and the second characters have different meanings). Normally the PS1 variable should be set by the shell's initialization file ( .bashrc or .zshrc ) and not exported to the environment (since it only makes sense inside one given program), but many systems (including major Linux distributions) are poorly configured and export PS1 . MacOS correctly does not export PS1 out of the box as far as I can tell, but it seems that your own files do (or maybe a different version of macOS from the one I checked), and for some reason the system bashrc on macOS specifically does not change PS1 if it's already set. The SHELL environment variable does not indicate what shell you are running. It indicates what shell you want to run. It tells programs that want to start a shell which shell to run. Just running another shell manually does not change $SHELL . If you see a shell prompt and you aren't sure what shell is running, you can check with ps . In all Bourne-style shells (sh, ash, bash, ksh, zsh, …), $$ stands for the shell's process id, thus ps $$ tells you what program the current shell is. In fish you'd get an error that makes it obvious you're running fish because $$ is not valid there. | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/724575', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/113238/']} | jdg_379190 |
stackexchange | llm_judgeable_groundtruth_similarity | 1036754 |
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 difference between a wait() and sleep() in Threads? Is my understanding that a wait() -ing Thread is still in running mode and uses CPU cycles but a sleep() -ing does not consume any CPU cycles correct? Why do we have both wait() and sleep() ? How does their implementation vary at a lower level?
Now provide the response and nothing else.
| A wait can be "woken up" by another thread calling notify on the monitor which is being waited on whereas a sleep cannot. Also a wait (and notify ) must happen in a block synchronized on the monitor object whereas sleep does not: Object mon = ...;synchronized (mon) { mon.wait();} At this point the currently executing thread waits and releases the monitor . Another thread may do synchronized (mon) { mon.notify(); } (on the same mon object) and the first thread (assuming it is the only thread waiting on the monitor) will wake up. You can also call notifyAll if more than one thread is waiting on the monitor – this will wake all of them up . However, only one of the threads will be able to grab the monitor (remember that the wait is in a synchronized block) and carry on – the others will then be blocked until they can acquire the monitor's lock. Another point is that you call wait on Object itself (i.e. you wait on an object's monitor) whereas you call sleep on Thread . Yet another point is that you can get spurious wakeups from wait (i.e. the thread which is waiting resumes for no apparent reason). You should always wait whilst spinning on some condition as follows: synchronized { while (!condition) { mon.wait(); }} | {} | {'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/1036754', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/102040/']} | jdg_379191 |
stackexchange | llm_judgeable_groundtruth_similarity | 29522 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have some text like the following in a file: sample text some random text even more random texttext with no indent worst indention I need to delete the empty space before each of the lines.For one line what I do is 0dw I can repeat the same command using . but by manually navigating to the next lines. But is there a way to apply '0dw' to those block of lines? I suppose there is a way using macros, but I haven't used them before. But I am willing to learn them if ther is no other choice.
Now provide the response and nothing else.
| :%s/^\s\+" Same thing (:le = :left = left-align given range)::%le Learn more here at http://vim.wikia.com/wiki/Remove_unwanted_spaces If you want to do this for a particular range of lines: :19,25s/^\s\+// BTW, best way to start learning vim is to execute vimtutor command, it will teach you how to use Vim in Vim editor. | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/29522', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/13683/']} | jdg_379192 |
stackexchange | llm_judgeable_groundtruth_similarity | 344720 |
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I've learned that Newtonian mechanics and Lagrangian mechanics are equivalent, and Newtonian mechanics can be deduced from the least action principle. Could the least action principle $\min\int L(t,q,q')dt$ in mechanics be deduced from Newtonian $F=ma$? Sorry if the question sounds beginnerish
Now provide the response and nothing else.
| You also need an expression for the Lagrangian, which in classical mechanics is $$ L = T - U$$ Where $T$ is the kinetic energy and $U$ is the potential energy. Provided that you can associate a potential $U$ to the force $\vec{F}$ such that $\vec{F} = - \vec{\nabla} U$ (such a force is said to be conservative), the principle of least action and Newton second's law are equivalent. The demonstration for a single particle in 1D ($T = m v_x^2 /2$, $F = -dU(x)/dx$) is actually a good exercise. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/344720', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/158306/']} | jdg_379193 |
stackexchange | llm_judgeable_groundtruth_similarity | 2853474 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Can I get the browser time zone in ASP.NET or do I have to rely on JS operations to retrieve the information
Now provide the response and nothing else.
| There is no “Accept-Timezone” header (or the like) - the HTTP standard does not contain any facility to allow the browser to automatically tell the server what time zone the user cares about. The basic approach is to use a date and read the TZ info from it. Since there's no standard (cross-browser time zone naming functions - you have to resort to something like (yikes!): function getTimezoneName() { tmSummer = new Date(Date.UTC(2005, 6, 30, 0, 0, 0, 0)); so = -1 * tmSummer.getTimezoneOffset(); tmWinter = new Date(Date.UTC(2005, 12, 30, 0, 0, 0, 0)); wo = -1 * tmWinter.getTimezoneOffset(); if (-660 == so && -660 == wo) return 'Pacific/Midway'; if (-600 == so && -600 == wo) return 'Pacific/Tahiti'; if (-570 == so && -570 == wo) return 'Pacific/Marquesas'; if (-540 == so && -600 == wo) return 'America/Adak'; if (-540 == so && -540 == wo) return 'Pacific/Gambier'; if (-480 == so && -540 == wo) return 'US/Alaska'; if (-480 == so && -480 == wo) return 'Pacific/Pitcairn'; if (-420 == so && -480 == wo) return 'US/Pacific'; if (-420 == so && -420 == wo) return 'US/Arizona'; if (-360 == so && -420 == wo) return 'US/Mountain'; if (-360 == so && -360 == wo) return 'America/Guatemala'; if (-360 == so && -300 == wo) return 'Pacific/Easter'; if (-300 == so && -360 == wo) return 'US/Central'; if (-300 == so && -300 == wo) return 'America/Bogota'; if (-240 == so && -300 == wo) return 'US/Eastern'; if (-240 == so && -240 == wo) return 'America/Caracas'; if (-240 == so && -180 == wo) return 'America/Santiago'; if (-180 == so && -240 == wo) return 'Canada/Atlantic'; if (-180 == so && -180 == wo) return 'America/Montevideo'; if (-180 == so && -120 == wo) return 'America/Sao_Paulo'; if (-150 == so && -210 == wo) return 'America/St_Johns'; if (-120 == so && -180 == wo) return 'America/Godthab'; if (-120 == so && -120 == wo) return 'America/Noronha'; if (-60 == so && -60 == wo) return 'Atlantic/Cape_Verde'; if (0 == so && -60 == wo) return 'Atlantic/Azores'; if (0 == so && 0 == wo) return 'Africa/Casablanca'; if (60 == so && 0 == wo) return 'Europe/London'; if (60 == so && 60 == wo) return 'Africa/Algiers'; if (60 == so && 120 == wo) return 'Africa/Windhoek'; if (120 == so && 60 == wo) return 'Europe/Amsterdam'; if (120 == so && 120 == wo) return 'Africa/Harare'; if (180 == so && 120 == wo) return 'Europe/Athens'; if (180 == so && 180 == wo) return 'Africa/Nairobi'; if (240 == so && 180 == wo) return 'Europe/Moscow'; if (240 == so && 240 == wo) return 'Asia/Dubai'; if (270 == so && 210 == wo) return 'Asia/Tehran'; if (270 == so && 270 == wo) return 'Asia/Kabul'; if (300 == so && 240 == wo) return 'Asia/Baku'; if (300 == so && 300 == wo) return 'Asia/Karachi'; if (330 == so && 330 == wo) return 'Asia/Calcutta'; if (345 == so && 345 == wo) return 'Asia/Katmandu'; if (360 == so && 300 == wo) return 'Asia/Yekaterinburg'; if (360 == so && 360 == wo) return 'Asia/Colombo'; if (390 == so && 390 == wo) return 'Asia/Rangoon'; if (420 == so && 360 == wo) return 'Asia/Almaty'; if (420 == so && 420 == wo) return 'Asia/Bangkok'; if (480 == so && 420 == wo) return 'Asia/Krasnoyarsk'; if (480 == so && 480 == wo) return 'Australia/Perth'; if (540 == so && 480 == wo) return 'Asia/Irkutsk'; if (540 == so && 540 == wo) return 'Asia/Tokyo'; if (570 == so && 570 == wo) return 'Australia/Darwin'; if (570 == so && 630 == wo) return 'Australia/Adelaide'; if (600 == so && 540 == wo) return 'Asia/Yakutsk'; if (600 == so && 600 == wo) return 'Australia/Brisbane'; if (600 == so && 660 == wo) return 'Australia/Sydney'; if (630 == so && 660 == wo) return 'Australia/Lord_Howe'; if (660 == so && 600 == wo) return 'Asia/Vladivostok'; if (660 == so && 660 == wo) return 'Pacific/Guadalcanal'; if (690 == so && 690 == wo) return 'Pacific/Norfolk'; if (720 == so && 660 == wo) return 'Asia/Magadan'; if (720 == so && 720 == wo) return 'Pacific/Fiji'; if (720 == so && 780 == wo) return 'Pacific/Auckland'; if (765 == so && 825 == wo) return 'Pacific/Chatham'; if (780 == so && 780 == wo) return 'Pacific/Enderbury' if (840 == so && 840 == wo) return 'Pacific/Kiritimati'; return 'US/Pacific';} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2853474', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/127257/']} | jdg_379194 |
stackexchange | llm_judgeable_groundtruth_similarity | 5314886 |
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 samples I've seen so far look like this: Write your code like this... public class Samurai { public IWeapon Weapon { get; private set; } public Samurai(IWeapon weapon) { Weapon = weapon; }} And Ninject can map the interface to the concrete type like this... public class WarriorModule : NinjectModule { public override void Load() { Bind<IWeapon>().To<Sword>(); }} So when I say var samurai = kernel.Get<Samurai>(); in my Samurai object my IWeapon is automatically a Sword. That's cool, but what if I want just the ISword without the Samurai and the concrete sword is marked as internal? Currently, I use a home made dependency resolver where I could say var sword = DependencyResolver.Current.Resolve<ISword>(); and it gives me back a Sword cast as ISword. My concrete classes are marked as internal so the developer must go through my dependency resolver to create an instance. Does Ninject have anything similar to this? And a bonus question, I decorate my Interfaces with a custom "DefaultConcreteType" attribute which my dependency resolver can use if no mapping exists. Does Ninject have anything like that either? Thanks
Now provide the response and nothing else.
| When you bind an interface to a concrete type, you can ask for an instance of that interface and obtain the concrete type. In your example, you could do this: var sword = kernel.Get<ISword>(); And this would give you a concrete Sword object. You can do a lot more with the binding system, too. You could even Bind<ISword>().ToMethod(MySwordFactory); and write a method to get Swords based on the requesting context. Another thing you can do is to change how binding works based on the type it's being injected into. For example, you could expose a property on a custom class like so: public class MyClass { [Inject] public ISword Sword { get; set; }} And then you could bind to a specific ISword implementation based on the MyClass: Bind<ISword>().To<Sword>().WhenInjectedInto<MyClass>(); There are a lot more options, but this should give you a rough overview. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5314886', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/64279/']} | jdg_379195 |
stackexchange | llm_judgeable_groundtruth_similarity | 33388558 |
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 work with documents such as: { "foo" : { "objectid" : "39", "stuff" : "65" }, "yearpublished" : ["1979"], "bar" : "1263"} yearpublished is an array and I would like to group my collection by the first value in this array and then count the amount of documents related. I have written this query: db.foobar.aggregate([ { $group : { _id : '$yearpublished', count: { $sum: 1 } }}]) and get: { "result" : [ { "_id" : ["1923"], "count" : 1.0000000000000000 }, { "_id" : ["1864"], "count" : 1.0000000000000000 } ]} But I'm looking for this kind of result (i. e. first element only): { "result" : [ { "_id" : "1923", "count" : 1.0000000000000000 }, { "_id" : "1864", "count" : 1.0000000000000000 } ]} I've also tried _id : { $first: '$yearpublished.0' }, or _id : { $first: '$yearpublished[0]' }, without success. How can I group by the first element of the array yearpublished ?
Now provide the response and nothing else.
| Unfortunately right now the only way to do this is to extract the $first element from the array after processing $unwind . Then of course you would have to $group again: db.foobar.aggregate([ { "$unwind": "$yearpublished" }, { "$group": { "_id": "$_id", "yearpublished": { "$first": "$yearpublished" } }}, { "$group": { "_id": "$yearpublished", "count": { "$sum": 1 } }}]) Thats the only current way to get the "first" element from an array, by deconstructing it and using the operator to get the entry. Future releases will have $arrayElemAt which can do this by index within a single stage: db.foobar.aggregate([ { "$group": { "_id": { "$arrayElemAt": [ "$yearpublished", 0 ] }, "count": { "$sum": 1 } }}]) But presently the aggregation framework does not deal with "dot notation" index usage such as standard "projection" with .find() does, and will not, hence the new operations. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33388558', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2377449/']} | jdg_379196 |
stackexchange | llm_judgeable_groundtruth_similarity | 721634 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $*$ be a binary operation acting on a set $S$, such that $$(a*b)*a=b,$$ for all $a,b\in S$. Prove that $$a*(b*a)=b,$$ for all $a,b \in S$.
Now provide the response and nothing else.
| We have that$$a*(b*a)=\big((b*a)*b\big)*(b*a)=b$$Note that the second "=" holds since$$(c*b)*c=b,$$where $c=b*a$. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/721634', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/33907/']} | jdg_379197 |
stackexchange | llm_judgeable_groundtruth_similarity | 20847681 |
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 page where one controller shows all of the logged in user's teams, and another controller allows the user to update a team. When the user updates the team name, I want the controller that displays all the teams to notice that a team has been updated and update it's variable accordingly. I've been googling around and it seems there's lots of questions and lots of different ways to do this. Ideally i'd like to be able to just update a factory variable and all the controllers would notice that the value has been updated. Not sure if that is how angular works though. Example: var myapp= angular.module('myapp', []);...// This gets the teams that a user is associated withmyezteam.factory('teams', function($http) { // Get the teams associated with the logged in user return { getTeams: function(callback) { $http.get(baseUrl+'v1/teams/all' + apiKey) .success(function(response) { callback(response); }); } }}); Controller which gets all the teams // This controller is used to set the user profile linksmyapp.controller('TemplateProfileController', ['$scope', '$http'', 'teams', function($scope, $http, teams) { // Gets all of a user's teams from the "teams" factory getTeams = function() { teams.getTeams(function(response) { $scope.teams = response; }); } $scope.teams = getTeams(); // Call on page load}]); Controller which handles the editing of a team // Controller for editing a teammyapp.controller('EditTeamController', ['$scope', '$http', '$routeParams', 'teams', function($scope, $http, $routeParams, teams) { // Get the team that we're editing getTeam = function() { $http.get(baseUrl+'v1/teams/' + $routeParams.id + apiKey) .success(function(response) { $scope.team = response; }); } // Update the team and refresh the list of all teams $scope.updateTeam = function() { $http.post(baseUrl+'v1/teams' + apiKey, $scope.team) .success(function(response) { // NEED TO SOMEONE TRIGGER THE TempalteProfileController to get the teams from the factory again }) } getTeam(); // Call on page load;}]);
Now provide the response and nothing else.
| This is actually very simple to do as long as you understand the difference between variables and objects. Say I have a service that keeps track of a counter and provides a way to increment it: app.factory("mySharedService", function(){ var values = { mySharedValue: 0 }; return{ getValues: function(){ return values; }, incrementValue: function(){ values.mySharedValue++; } };}); Notice that rather than just declaring a simple variable, I declare an object and hang my actual value from the object. This object reference will remain the same for the lifetime of the service and only the values inside of it will change. This means any controller who calls getValues() will receive the same object reference and can use that in their scope: app.controller('Controller1', function($scope, mySharedService) { $scope.values = mySharedService.getValues();});app.controller('Controller2', function($scope, mySharedService) { $scope.values = mySharedService.getValues();});app.controller('Controller3', function($scope, mySharedService) { $scope.values = mySharedService.getValues();}); Whenever the value in mySharedValue changes, all controllers will see it equally (because they are all sharing the same object reference). This means that any bindings in that controller will update instantly, and you can use $scope.$watch() just like you do with any other scope variable. Here is an example plunker: http://plnkr.co/edit/FA3MbfQQpiOtp5mGqqAq?p=preview EDIT: If you want to preserve encapsulation and only able to edit value through the provided methods you could do something like: app.factory("mySharedService", function(){ var mySharedValue = 0; var values = { getMySharedValue: function(){ return mySharedValue; } }; return{ getValues: function(){ return values; }, incrementValue: function(){ mySharedValue++; } };}); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20847681', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/222403/']} | jdg_379198 |
stackexchange | llm_judgeable_groundtruth_similarity | 38112 |
Below is a question asked on the forum emacs.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Qt supports Emacs-style keybindings , however for only up to four keys. To make a point why this limit should be increased it would be useful to show examples of Emacs-style keybindings with even more keys than that. Are there any known examples for this or maybe even a way to programmatically find long key sequences defined in Emacs keymaps? edit: I thought this was common knowledge, but a key sequence is a set of keys as read in by read-key-sequence . Try F1 k for your candidate and see whether it describes your command or an unrelated one preceding it.
Now provide the response and nothing else.
| I tested with the following script, (key-description (car (sort (let (keyseqs) (mapatoms (lambda (sym) (when (commandp sym) (let ((where (where-is-internal sym nil nil t))) (when where (setq keyseqs (append keyseqs where))))))) keyseqs) (lambda (a b) (< (length b) (length a)))))) And the longest I get with my .emacs.d is C-x c C-x r i which is some helm command, and with emacs -q I get C-x a i l which runs the command inverse-add-mode-abbrev . | {} | {'log_upvote_score': 6, 'links': ['https://emacs.stackexchange.com/questions/38112', 'https://emacs.stackexchange.com', 'https://emacs.stackexchange.com/users/10/']} | jdg_379199 |
stackexchange | llm_judgeable_groundtruth_similarity | 3135679 |
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 HttpClient on Android to connect to https://someUrl.com/somePath . The problem is that the site's certificate is for *.someUrl.com, not someUrl.com, so I get an SSLException. Lame on the part of the site, yes, but unless I can get it fixed, I'm stuck. Is there a way I can get HttpClient to relax and accept the certificate?
Now provide the response and nothing else.
| This is my (edited) solution: class MyVerifier extends AbstractVerifier { private final X509HostnameVerifier delegate; public MyVerifier(final X509HostnameVerifier delegate) { this.delegate = delegate; } @Override public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException { boolean ok = false; try { delegate.verify(host, cns, subjectAlts); } catch (SSLException e) { for (String cn : cns) { if (cn.startsWith("*.")) { try { delegate.verify(host, new String[] { cn.substring(2) }, subjectAlts); ok = true; } catch (Exception e1) { } } } if(!ok) throw e; } }}public DefaultHttpClient getTolerantClient() { DefaultHttpClient client = new DefaultHttpClient(); SSLSocketFactory sslSocketFactory = (SSLSocketFactory) client .getConnectionManager().getSchemeRegistry().getScheme("https") .getSocketFactory(); final X509HostnameVerifier delegate = sslSocketFactory.getHostnameVerifier(); if(!(delegate instanceof MyVerifier)) { sslSocketFactory.setHostnameVerifier(new MyVerifier(delegate)); } return client;} It has the advantage of not changing the default behavior unless there is a wildcard domain, and in that case it revalidates as though the 2 part domain (e.g., someUrl.com) were part of the certificate, otherwise the original exception is rethrown. That means truly invalid certs will still fail. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3135679', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12034/']} | jdg_379200 |
stackexchange | llm_judgeable_groundtruth_similarity | 302730 |
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:
As a good programmer one should write robust codes that will handle every single outcome of his program. However, almost all functions from the C library will return 0 or -1 or NULL when there's an error. It's sometimes obvious that error checking is needed, for example when you try to open a file. But I often ignore error checking in functions such as printf or even malloc because I don't feel necessary. if(fprintf(stderr, "%s", errMsg) < 0){ perror("An error occurred while displaying the previous error."); exit(1);} Is it a good practice to just ignore certain errors, or is there a better way to handle all the errors?
Now provide the response and nothing else.
| In general, code should deal with exceptional conditions wherever it is appropriate. Yes, this is a vague statement. In higher level languages with software exception handling this is often stated as "catch the exception in the method where you can actually do something about it." If a file error occurred, maybe you let it bubble up the stack to the UI code that can actually tell the user "your file failed to save to disk." The exception mechanism effectively swallows up "every little error" and implicitly handles it at the appropriate place. In C, you do not have that luxury. There are a few ways to handle errors, some of which are language/library features, some of which are coding practices. Is it a good practice to just ignore certain errors, or is there a better way to handle all the errors? Ignore certain errors? Maybe. For example, it is reasonable to assume that writing to standard output will not fail. If it does fail, how would you tell the user, anyway? Yes, it is a good idea to ignore certain errors, or code defensively to prevent them. For example, check for zero before dividing. There are ways to handle all, or at least most, errors: You can use jumps, similar to gotos, for error handling . While a contentious issue among software professionals, there are valid uses for them especially in embedded and performance-critical code (e.g. Linux kernel). Cascading if s: if (!<something>) { printf("oh no 1!"); return;}if (!<something else>) { printf("oh no 2!"); return;} Test the first condition, e.g. opening or creating a file, then assume subsequent operations succeed. Robust code is good, and one should check for and handle errors. Which method is best for your code depends on what the code does, how critical a failure is, etc. and only you can truly answer that. However, these methods are battle-tested and used in various open source projects where you can take a look to see how real code checks for errors. | {} | {'log_upvote_score': 6, 'links': ['https://softwareengineering.stackexchange.com/questions/302730', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/153287/']} | jdg_379201 |
stackexchange | llm_judgeable_groundtruth_similarity | 57909923 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
#include <iostream>struct uct{ uct() { std::cerr << "default" << std::endl; } uct(const uct &) { std::cerr << "copy" << std::endl; } uct( uct&&) { std::cerr << "move" << std::endl; } uct(const int &) { std::cerr << "int" << std::endl; } uct( int &&) { std::cerr << "int" << std::endl; } template <typename T> uct(T &&) { std::cerr << "template" << std::endl; }};int main(){ uct u1 ; // default uct u2( 5); // int uct u3(u1); // template, why?} coliru Template overload of the constructor fits to both declarations ( u2 and u3 ). But when int is passed to the constructor, a non-template overload is chosen. When the copy constructor is called, a template overload is chosen. As far as I know, a non-template function is always preferred to a template function during overload resolution. Why is the copy constructor handled differently?
Now provide the response and nothing else.
| As far as I know non-template function is always preferred to template function during overload resolution. This is true, only when the specialization and the non template are exactly the same. This is not the case here though. When you call uct u3(u1) The overload sets gets uct(const uct &)uct(uct &) // from the template Now, since u1 is not const it would have to apply a const transformation to call the copy constructor. To call the template specialization it needs to do nothing since it is an exact match. That means the template wins as it is the better match. To stop this one thing you can do is use SFINAE to limit the template function to only be called when T is not a uct . That would look like template <typename T, std::enable_if_t<!std::is_same_v<uct, std::decay_t<T>>, bool> = true>uct(T &&) { std::cerr << "template" << std::endl; } | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/57909923', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5447906/']} | jdg_379202 |
stackexchange | llm_judgeable_groundtruth_similarity | 24077524 |
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 program which loads many fxml files when executed. The application will be finished in a short time, and loading the application just takes too long. There are many fxml files (20+) and all these fxml files are loaded with Java code. There will be a point that the application is finished and ready for use, but all files will be loaded with every execution of the program. Can the fxml files only be compiled once, because they won't be changed when finished? The java code will of course be compiled once, it's only the fxml files. The application now takes 25 seconds to start, with 14 seconds loading the fxml. Is there a way to make all this faster? EDIT #1: Are there any tools that are provided for free and that make the execution of applications (Java) much faster? Or is the execution time merely dependent on the way the program is written? Which design patterns could help fastening up the execution time of your application? EDIT #2: The following code will explain my problem in a nutshell: package main;..............public class MainClass { .... .... List<InformationController> controllerList; public mainClass(List<InformationControllers> controllerList) { this.controllerList = otherClass.getControllerList(); loadFXMLFiles(); } public void loadFXMLFiles() { for(InformationController controller : controllerList) { controller.loadFXML(); } doOtherStuff(); } ....} All those InformationControllers have their loading of other fxml files too, so it's actually a tree of fxml files that is loaded. This is loaded at every start of the application, so is there a way to do this loading only once maybe?
Now provide the response and nothing else.
| On How to Speed up FXML Performance I'll make this answer community wiki, if anybody else has further ideas, please edit it and add them. One should NOT use the static FXMLLoader.load() but should instead create an instance of FXMLLoader and reuse that one using the instance loader.load() method. The reason is that the FXML-Loader caches, e.g. class lookups, and hence is faster on loading the next FXML-File. Use a tool to compile the FXML to Java, such as Tom Schindl's FXML compiler or the NetBeans FXML to Java converter . Don't load any more FXML than you need to at any given time, e.g. if you aren't going to be displaying it right now, don't load it. Load the FXML in a background thread (doesn't work for some control types, e.g. Tooltip, in Java 8). Load an initial login or splash screen first and then load the rest of the FXML while the splash or login screen is displayed. I load FXML in some apps after the credentials are accepted at the login screen. Reduce the complexity of your application UI by removing unnecessary nodes. Ensure you aren't doing unnecessary work (e.g. reading a database) on the JavaFX UI thread in the initialize methods of your controllers. The FXMLLoader.load() documentation in JavaFX 8 includes a reference to FXML templates, but I don't think that was ever implemented, so maybe it won't help you. I heard mention that referring to static methods from FXML is slow. Use the latest development version of JavaFX . Once you have loaded a node hierarchy from FXML, reuse the hierarchy later rather than throwing it away and loading a new one (e.g. if you have a dialog window with contents constructed using FXML, when the user closes the dialog, just hide it and when you need to show a similar dialog again, just show the hidden dialog rather than constructing a whole new dialog and scene graph). Reflection is why FXML is Slow I think the key reason the Java 8 FXML implementation is slow is that it relies so heavily on reflection and reflection is slow as described in the reflection tutorial : Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24077524', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1418052/']} | jdg_379203 |
stackexchange | llm_judgeable_groundtruth_similarity | 36308465 |
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 two classes (Model and User) but I have a problem so I have tried to explain it in a simple example : class person{ protected static $todo ="nothing"; public function __construct(){} public function get_what_todo() { echo self::$todo; }}class student extends person{ protected static $todo ="studing";}$s = new student();$s->get_what_todo(); // this will show the word (nothing) //but I want to show the word (studing) Please give me a solution but without writing any function in the student class I only want to make declarations there :) and thank you :)
Now provide the response and nothing else.
| The principle is called " late static binding ", and was introduced in PHP 5.3.0; with the self keyword to access the property defined in the calling class within the inheritance tree, or static to access the property defined in the child class within that inheritance tree. class person{ protected static $todo ="nothing"; public function __construct(){} public function get_what_todo() { echo static::$todo; // change self:: to static:: }}class student extends person{ protected static $todo ="studying";}class teacher extends person{ protected static $todo ="marking";}class guest extends person{}$s = new student();$s->get_what_todo(); // this will show the "studying" from the instantiated child class$t = new teacher();$t->get_what_todo(); // this will show the "marking" from the instantiated child class$g = new guest();$g->get_what_todo(); // this will show the "nothing" from the parent class, // because $todo is not overriden in the child class | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/36308465', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6012309/']} | jdg_379204 |
stackexchange | llm_judgeable_groundtruth_similarity | 17832 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
What are "things to think about" and best practices to migrate a large number of users from using local profiles to roaming ones?
Now provide the response and nothing else.
| I've done this several times, typically copying the "My Documents" and "Desktop" into redirected folders by hand during the process. I like doing this in migrations because it preserves the user's look and feel of their environment, as well as their data files. If you're copying around registry hives (NTUSER.DAT) as files into the new profiles, be sure that you modify the permission on the root of the hive to allow the domain user account access. You can get some really, really strange behaviour if you don't do this. (Microsoft Outlook 2003 displays a funny error message to the effect of "Outlook Failed to Start" when this happens, as an example.) | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/17832', 'https://serverfault.com', 'https://serverfault.com/users/1825/']} | jdg_379205 |
stackexchange | llm_judgeable_groundtruth_similarity | 4470700 |
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 program which outputs various results onto a command line console. How do I save the output to a text file using a StreamReader or other techniques? System.Collections.Generic.IEnumerable<String> lines = File.ReadAllLines(@"C:\Test\ntfs8.txt");foreach (String r in lines.Skip(1)){ String[] token = r.Split(','); String[] datetime = token[0].Split(' '); String timeText = datetime[4]; String actions = token[2]; Console.WriteLine("The time for this array is: " + timeText); Console.WriteLine(token[7]); Console.WriteLine(actions); MacActions(actions); x = 1; Console.WriteLine("================================================");}if (x == 2){ Console.WriteLine("The selected time does not exist within the log files!");}System.IO.StreamReader reader = ;string sRes = reader.ReadToEnd();StreamWriter SW;SW = File.CreateText("C:\\temp\\test.bodyfile");SW.WriteLine(sRes);SW.Close();Console.WriteLine("File Created");reader.Close();
Now provide the response and nothing else.
| Try this example from this article - Demonstrates redirecting the Console output to a file using System;using System.IO;static public void Main (){ FileStream ostrm; StreamWriter writer; TextWriter oldOut = Console.Out; try { ostrm = new FileStream ("./Redirect.txt", FileMode.OpenOrCreate, FileAccess.Write); writer = new StreamWriter (ostrm); } catch (Exception e) { Console.WriteLine ("Cannot open Redirect.txt for writing"); Console.WriteLine (e.Message); return; } Console.SetOut (writer); Console.WriteLine ("This is a line of text"); Console.WriteLine ("Everything written to Console.Write() or"); Console.WriteLine ("Console.WriteLine() will be written to a file"); Console.SetOut (oldOut); writer.Close(); ostrm.Close(); Console.WriteLine ("Done");} | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/4470700', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/411517/']} | jdg_379206 |
stackexchange | llm_judgeable_groundtruth_similarity | 6050384 |
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 jQuery Mobile app consists of a single index.html page and contains only one page with a link on startup: <div data-role="page"> <div data-role="content"> <a id="startPageLink" href="startPage">start</a> </div></div> When the user clicks on the start link, I want to load the content for the startPage from my JSON api asynchronously. On the callback I would like to create all the required DOM elements for startPage via JavaScript and add the content to it. I have created a createStartPage(data) method for this. What is the right way to implement such dynamically created pages, so that opening index.html#startPage also works? I think there should be a way to hook into $.mobile.changePage() to include custom loading/page-creation code, but I did not find anything. Or is there a better solution for this problem?
Now provide the response and nothing else.
| I had some time to mess around with this and I've found a solution that works (tested). SOME NOTES: the javascript encapsulated in $(document).ready(); is for dynamically creating a page if the user navigates to your index.html file with a hash mark already appended (i.e. index.html#some_hash_mark). The function, create_page(page_id) is for creating a page from a link (or programatically if you like). Note that the jquery core script and the jquery mobile css are loaded before the $(document).ready() statement but that the jquery mobile script is loaded after. See that the body tag has been given an id that is refrenced when appending pages to it. Document Sample <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><link rel="stylesheet" type="text/css" href="http://code.jquery.com/mobile/1.0a4.1/jquery.mobile-1.0a4.1.min.css"/><script type="text/javascript" charset="utf-8" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script><script>$(document).ready(function() { //check if hash exists and that it is not for the home screen if (window.location.hash != '' && window.location.hash != '#page_0') { //set whatever content you want to put into the new page var content_string = 'Some ' + window.location.hash + ' text...<br><br><a href="#page_0">go to home screen</a>'; //append the new page onto the end of the body $('#page_body').append('<div data-role="page" id="' + window.location.hash.replace('#','') + '"><div data-role="content">' + content_string + '</div></div>'); //add a link on the home screen to navaigate to the new page (just so nav isn't broken if user goes from new page to home screen) $('#page_0 div[data-role="content"]').append('<br><br><a href="#' + window.location.hash.replace('#','') + '">go to ' + window.location.hash.replace('#','') + ' page</a>'); }});function create_page(page_id) { //set whatever content you want to put into the new page var string = 'FOO BAR page...<br><br><a href="#page_0">return to home screen</a>'; //append the new page onto the end of the body $('#page_body').append('<div data-role="page" id="' + page_id + '"><div data-role="content">' + string + '</div></div>'); //initialize the new page $.mobile.initializePage(); //navigate to the new page $.mobile.changePage("#" + page_id, "pop", false, true); //add a link on the home screen to navaigate to the new page (just so nav isn't broken if user goes from new page to home screen) $('#page_0 div[data-role="content"]').append('<br><br><a href="#' + page_id + '">go to ' + page_id + ' page</a>'); //refresh the home screen so new link is given proper css $('#page_0 div[data-role="content"]').page();}</script><title>Fixed Headers Example</title><script src="http://code.jquery.com/mobile/1.0a4.1/jquery.mobile-1.0a4.1.min.js"></script></head><body id="page_body"><div data-role="page" id="page_0"><div data-role="content">Some #page_0 text...<br><br><a href="javascript: create_page('foo_bar_page');">create new page</a></div></div></body></html> | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6050384', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/176336/']} | jdg_379207 |
stackexchange | llm_judgeable_groundtruth_similarity | 51696655 |
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 python and I have a scenario where there are multiple parquet files with file names in order. ex: par_file1,par_file2,par_file3 and so on upto 100 files in a folder. I need to read these parquet files starting from file1 in order and write it to a singe csv file. After writing contents of file1, file2 contents should be appended to same csv without header. Note that all files have same column names and only data is split into multiple files. I learnt to convert single parquet to csv file using pyarrow with the following code: import pandas as pd df = pd.read_parquet('par_file.parquet') df.to_csv('csv_file.csv') But I could'nt extend this to loop for multiple parquet files and append to single csv.Is there a method in pandas to do this? or any other way to do this would be of great help. Thank you.
Now provide the response and nothing else.
| I ran into this question looking to see if pandas can natively read partitioned parquet datasets. I have to say that the current answer is unnecessarily verbose (making it difficult to parse). I also imagine that it's not particularly efficient to be constantly opening/closing file handles then scanning to the end of them depending on the size. A better alternative would be to read all the parquet files into a single DataFrame, and write it once: from pathlib import Pathimport pandas as pddata_dir = Path('dir/to/parquet/files')full_df = pd.concat( pd.read_parquet(parquet_file) for parquet_file in data_dir.glob('*.parquet'))full_df.to_csv('csv_file.csv') Alternatively, if you really want to just append to the file: data_dir = Path('dir/to/parquet/files')for i, parquet_path in enumerate(data_dir.glob('*.parquet')): df = pd.read_parquet(parquet_path) write_header = i == 0 # write header only on the 0th file write_mode = 'w' if i == 0 else 'a' # 'write' mode for 0th file, 'append' otherwise df.to_csv('csv_file.csv', mode=write_mode, header=write_header) A final alternative for appending each file that opens the target CSV file in "a+" mode at the onset, keeping the file handle scanned to the end of the file for each write/append (I believe this works, but haven't actually tested it): data_dir = Path('dir/to/parquet/files')with open('csv_file.csv', "a+") as csv_handle: for i, parquet_path in enumerate(data_dir.glob('*.parquet')): df = pd.read_parquet(parquet_path) write_header = i == 0 # write header only on the 0th file df.to_csv(csv_handle, header=write_header) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51696655', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10183474/']} | jdg_379208 |
stackexchange | llm_judgeable_groundtruth_similarity | 25497525 |
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 submit form with a click button, once the submit form its clicked, I want to change a series of images within my html site. As of now I am using the following JS code but I am having trouble defining the appropriate success response. <script type=text/javascript> $(function() {$("#valueme").click(function() { $.ajax({ type: "GET", url: $SCRIPT_ROOT + "/mypythonscript/", contentType: "application/json; charset=utf-8", data: { input1: $('input[name="input1"]').val(), input2: $('input[name="input2"]').val(), }, success: function(data) { //$ ('#photo_link1_div').text(data.photo_link1); //$ ('#photo_link2_div').text(data.photo_link2); } }); }); });</script> The data that mypythonscript returns is a dictionary with the links to all the images that I want to change in the html site, i.e., mypythonscript returns {photolink1:'../static/img/myphoto1.jgp',photolink2:'../static/img/myphoto2.jgp'} . Using such data I'd like to change the background images in my html by changing the DIVs background image urls. As of now the DIVs in my html look like (ideally I do not have to change this part but rather the JS part): <div id="photo_link1_div" style="background-image: url(../static/img/anotherphotowanttochange.jpg); background-repeat: no-repeat; width: 200px; height: 310px; background-size: 100% auto;" align="center"></div>
Now provide the response and nothing else.
| I'm surprised at how difficult it was to find the answer to this question. Most answers on the various forums are incorrect (I tested them with two iperf3 nodes and found that the solutions didn't work or only limited one direction of traffic (only incoming or only outgoing). A P2P application that has much more symmetric data usage than traditional client/server applications so traffic must be limited in both directions. The best way I've found is to limit network bandwidth (both incoming and outgoing) for a Docker container is to use Linux's own traffic control settings within the running container. Execute the tc commands inside the container before you start your P2P application. For example, you could create a start-up script like the following, copy it into your docker image and invoke it as the ENTRYPOINT. Dockerfile (snippet): COPY start-my-p2p.sh /RUN chmod +x /start-my-p2p.sh ENTRYPOINT /start-my-p2p.sh Put something like this in your start-my-p2p.sh (the tc cmdlines are probably what you've been searching the Internet for): #/bin/sh# Limit all incoming and outgoing network to 1mbit/stc qdisc add dev eth0 handle 1: ingresstc filter add dev eth0 parent 1: protocol ip prio 50 u32 match ip src 0.0.0.0/0 police rate 1mbit burst 10k drop flowid :1tc qdisc add dev eth0 root tbf rate 1mbit latency 25ms burst 10k`# Now start your p2p applicationmyp2pservice -d IMPORTANT: When starting the container you'll need to use --cap-add=NET_ADMIN : docker run --rm -it --cap-add=NET_ADMIN -p6969:p6969 myimage | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25497525', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1205745/']} | jdg_379209 |
stackexchange | llm_judgeable_groundtruth_similarity | 912479 |
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's the difference between ECMAScript and JavaScript? From what I've deduced, ECMAScript is the standard and JavaScript is the implementation. Is this correct?
Now provide the response and nothing else.
| I think a little history lesson is due. JavaScript was originally named Mocha and changed to Livescript but ultimately became JavaScript. It's important to note that JavaScript came before ECMAscript and the history will tell you why. To start from the beginning, JavaScript derived its name from Java and initially Brendan Eich (the creator of JS) was asked to develop a language that resembled Java for the web for Netscape. Eich, however decided that Java was too complicated with all its rules and so set out to create a simpler language that even a beginner could code in. This is evident in such things like the relaxing of the need to have a semicolon. After the language was complete, the marketing team of Netscape requested Sun to allow them to name it JavaScript as a marketing stunt and hence why most people who have never used JavaScript think it's related to Java. About a year or two after JavaScript's release in the browser, Microsoft's IE took the language and started making its own implementations such as JScript. At the same time, IE was dominating the market and not long after Netscape had to shut its project. Before Netscape went down, they decided to start a standard that would guide the path of JavaScript, named ECMAScript. ECMAScript had a few releases and in 1999 they released their last version (ECMAScript 3) before they went into hibernation for the next 10 years. During this 10 years, Microsoft dominated the scenes but at the same time they weren't improving their product and hence Firefox was born (led by Eich) and a whole heap of other browsers such as Chrome, Opera. ECMAScript released its 5th Edition in 2009 (the 4th edition was abandoned) with features such as strict mode. Since then, ECMAScript has gained a lot of momentum and is scheduled to release its 6th Edition in a few months from now with the biggest changes its had thus far. You can use a list of features for ECMAScript 6 here http://kangax.github.io/es5-compat-table/es6/ and also the browser support. You can even start writing Ecmascript 6 like you do with CoffeeScript and use a compiler to compile down to Ecmascript 5. Whether ECMAScript is the language and JavaScript is a dialect is arguable, but not important. If you continue to think like this it might confuse you. There is no compiler out there that would run ECMAScript, and I believe JavaScript is considered the Language which implements a standard called ECMAScript. There are also other noticeable languages that implement ECMAScript such as ActionScript (used for Flash) | {} | {'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/912479', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1463/']} | jdg_379210 |
stackexchange | llm_judgeable_groundtruth_similarity | 83147 |
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 remember hearing Joel Spolsky mention in podcast 014 that he'd barely ever used a foreign key (if I remember correctly). However, to me they seem pretty vital to avoid duplication and subsequent data integrity problems throughout your database. Do people have some solid reasons as to why (to avoid a discussion in lines with Stack Overflow principles)? Edit: "I've yet to have a reason to create a foreign key, so this might be my first reason to actually set up one."
Now provide the response and nothing else.
| Reasons to use Foreign Keys: you won't get Orphaned Rows you can get nice "on delete cascade" behavior, automatically cleaning up tables knowing about the relationships between tables in the database helps the Optimizer plan your queries for most efficient execution, since it is able to get better estimates on join cardinality. FKs give a pretty big hint on what statistics are most important to collect on the database, which in turn leads to better performance they enable all kinds of auto-generated support -- ORMs can generate themselves, visualization tools will be able to create nice schema layouts for you, etc. someone new to the project will get into the flow of things faster since otherwise implicit relationships are explicitly documented Reasons not to use Foreign Keys: you are making the DB work extra on every CRUD operation because it has to check FK consistency. This can be a big cost if you have a lot of churn by enforcing relationships, FKs specify an order in which you have to add/delete things, which can lead to refusal by the DB to do what you want. (Granted, in such cases, what you are trying to do is create an Orphaned Row, and that's not usually a good thing). This is especially painful when you are doing large batch updates, and you load up one table before another, with the second table creating consistent state (but should you be doing that sort of thing if there is a possibility that the second load fails and your database is now inconsistent?). sometimes you know beforehand your data is going to be dirty, you accept that, and you want the DB to accept it you are just being lazy :-) I think (I am not certain!) that most established databases provide a way to specify a foreign key that is not enforced, and is simply a bit of metadata. Since non-enforcement wipes out every reason not to use FKs, you should probably go that route if any of the reasons in the second section apply. | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/83147', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3394/']} | jdg_379211 |
stackexchange | llm_judgeable_groundtruth_similarity | 186581 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Suppose $G$ is a finite group and $A$ is the set of all character values of $G$. By character values, I mean entries of the character table of $G$. Let $\Gamma = \operatorname{Gal}({\mathbb{Q}(A)}/{\mathbb{Q}})$. Then $\Gamma$ has an action on the set of all conjugacy classes of $G$. Considering orbits, we get an equivalence relation on $G$. There is another equivalence relation on $G$ in which elements $x$ and $y$ are equivalent if and only if the cyclic subgroups generated by $x$ and $y$ are conjugate subgroups of $G$. My question is about the relationship between the classes defined by the two relations. In an exact phrase: Question: Is it true that both equivalence relations coincide? Any suggestions, comments or references to this problem are highly appreciated. Regards, Alireza
Now provide the response and nothing else.
| The answer is yes, and this is not difficult to see, but first you have to show that you have indeed an action of $\Gamma$ on the conjugacy classes. Let $\varepsilon$ be a primitive $|G|$-th roots of unity and let $\widehat{\Gamma}=\operatorname{Gal}(\mathbb{Q}(\varepsilon)/\mathbb{Q})$. Then $\mathbb{Q}(A)\subseteq \mathbb{Q}(\varepsilon)$ and $\Gamma$ is a homomorphic image of $\widehat{\Gamma}$ with kernel the Galois group of the extension $\mathbb{Q}(\varepsilon)/\mathbb{Q}(A)$. The action of $\Gamma$ on the conjugacy classes of $G$ is induced by the action of $\widehat{\Gamma}$ on the conjugacy classes of $G$. This action is defined as follows: For $\alpha\in \widehat{\Gamma}$, there is $k\in \mathbb{Z}$ such that $\varepsilon^{\alpha} = \varepsilon^k$. Then for $g\in G$, we set $g^{\alpha}=g^k$, which defines an action of $\widehat{\Gamma}$ on $G$ and thus on its conjugacy classes. That the orbits of this action are the same as the equivalence classes of the second relation follows from the well known fact that $\widehat{\Gamma} \cong (\mathbb{Z}/|G|\mathbb{Z})^*$ naturally (and some elementary considerations: if $x$ and $y$ generate the same cyclic subgroup, then $x=y^k$, where we may assume that $k$ is prime to $|G|$). The action of $\widehat{\Gamma}$ on the conjugacy classes factors through $\Gamma$ since $\operatorname{Gal}(\mathbb{Q}(\varepsilon)/\mathbb{Q}(A))$ fixes the conjugacy classes. This follows since the characters separate the conjugacy classes. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/186581', 'https://mathoverflow.net', 'https://mathoverflow.net/users/60642/']} | jdg_379212 |
stackexchange | llm_judgeable_groundtruth_similarity | 53943098 |
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 this simple code and have problem with swift data type, want to map this array from ["a", "b", nil, "c", "d", nil] to ["a", "b", "z", "c", "d", "z"] so, this is my current code import Foundationlet array1 = ["a", "b", nil, "c", "d", nil]let newArray = array1.map { (currentIndex: Any) -> String in if currentIndex == nil { return "z" } return currentIndex as! String}print(newArray) I am grateful if you try to solve the code. thank you.
Now provide the response and nothing else.
| If you declare currentIndex as Any then you cannot compare it against nil anymore. The correct type in your case would be String? : let newArray = array1.map { (currentIndex: String?) -> String in if currentIndex == nil { return "z" } return currentIndex!} However, the compiler can infer that automatically from the context: let newArray = array1.map { currentIndex -> String in if currentIndex == nil { return "z" } return currentIndex!} Better use the nil-coalescing operator ?? , and avoid force-unwrapping: let newArray = array1.map { currentIndex in currentIndex ?? "z"} or shorter: let newArray = array1.map { $0 ?? "z" } | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/53943098', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5834822/']} | jdg_379213 |
stackexchange | llm_judgeable_groundtruth_similarity | 2060578 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Possible Duplicate: C Programming: Forward variable argument list. What I'd like to do is send data to a logging library (that I can't modfify) in a printf kind of way. So I'd like a function something like this: void log_DEBUG(const char* fmt, ...) { char buff[SOME_PROPER_LENGTH]; sprintf(buff, fmt, <varargs>); log(DEBUG, buff);} Can I pass varargs to another vararg function in some manner?
Now provide the response and nothing else.
| You can't forward the variable argument list, since there's no way to express what's underneath the ... as a parameter(s) to another function. However you can build a va_list from the ... parameters and send that to a function which will format it up properly. This is what vsprintf is for. Example: void log_DEBUG(const char* fmt, ...) { char buff[SOME_PROPER_LENGTH]; va_list args; va_start(args, fmt); vsprintf(buff, fmt, args); va_end(args); log(DEBUG, buff);} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2060578', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/157525/']} | jdg_379214 |
stackexchange | llm_judgeable_groundtruth_similarity | 125863 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a bag of about 50 non-rechargeable AA batteries (1.5 V) that I have collected over the years. I bought a multimeter recently and would like to know the best way to test these batteries to determine which ones I should keep and which I should toss. Sometimes a battery will be useless for certain high-power devices (e.g. children's toys) but are still perfectly suitable for low-power devices such as TV remote controls. Ideally, I'd like to divide the batteries into several arbitrary categories: As-new condition (suitable for most devices) Suitable for low-powered devices such as remote controls Not worth keeping Should I be measuring voltage, current, power or a combination of several of these? Is there a simple metric I can use to determine what to keep and what to toss?
Now provide the response and nothing else.
| **WARNING: Lithium Ion cells ** While this question relates to non-rechargeable AA cells it is possible that someone may seek to extend the advice to testing other small cells. In the case Of Li-Ion rechargeable cells (AA, 18650, other) this can be a very bad idea in some cases. Shorting Lithium Ion cells as in test 2 is liable to be a very bad idea indeed. Depending on design, some Li-Ion cells will provide short circuit current of many times the cell mAh rating - eg perhaps 50+ amps for an 18650 cell, and perhaps 10's of amps for an AA size Li-Ion cell. This level of discharge can cause injury and worst case may destroy the cell, in some uncommon cases with substantial release of energy in the form of flame and hot material. AA non-rechargeable cells: 1) Ignore the funny answers Generally speaking, if a battery is more than 1 year old then only Alkaline batteries are worth keeping. Shelf life of non-Alkaline can be some years but they deteriorate badly with time. Modern Alkaline have gotten awesome, as they still retain a majority of charge at 3 to 5 years. Non brand name batteries are often (but not always) junk. Heft battery in hand. Learn to get the feel of what a "real" AA cell weighs. An Eveready or similar Alkaline will be around 30 grams/one ounce. An AA NiMH 2500 mAh will be similar. Anything under 25g is suspect. Under 20g is junk. Under 15g is not unknown. 2) Brutal but works Set multimeter to high current range (10A or 20A usually). Needs both dial setting and probe socket change in most meters. Use two sharpish probes. If battery has any light surface corrosion scratch a clean bright spot with probe tip. If it has more than surface corrosion consider binning it. Some Alkaline cells leak electrolyte over time, which is damaging to gear and annoying (at least) to skin. Press negative probe against battery base. Move slightly to make scratching contact. Press firmly. DO NOT slip so probe jumps off battery and punctures your other hand. Not advised. Ask me how I know. Press positive probe onto top of battery. Hold for maybe 1 second. Perhaps 2. Experience will show what is needed. This is thrashing the battery, decreasing its life and making it sad. Try not to do this often or for very long. Top AA Alkaline cells new will give 5-10 A. (NiMH AA will approach 10A for a good cell). Lightly used AA or ones which have had bursts of heavy use and then recovered will typically give a few amps. Deader again will be 1-3A. Anything under 1 A you probably want to discard unless you have a micropower application. Non Alkaline will usually be lower. I buy ONLY Alkaline primary cells as other "quality" cells are usually not vastly cheaper but are of much lower capacity. Current will fall with time. A very good cell will fall little over 1 to maybe 2 seconds. More used cells will start lower and fall faster. Well used cells may plummet. I place cells in approximate order of current after testing. The top ones can be grouped and wrapped with a rubber band. The excessively keen may mark the current given on the cell with a marker. Absolute current is not the point - it serves as a measure of usefulness. 3) Gentler - but works reasonably well. Set meter to 2V range or next above 2V if no 2V range. Measure battery unloaded voltage. New unused Alkaline are about 1.65V. Most books don't tell you that. Unused but sat on the shelf 1 year + Alkaline will be down slightly. Maybe 1.55 - 1.6V Modestly used cells will be 1.5V+ Used but useful may be 1.3V - 1.5V range After that it's all downhill. A 1V OC cell is dodo dead. A 1.1V -.2V cell will probably load down to 1V if you look at it harshly. Do this a few times and you will get a feel for it. 4) In between. Use a heavyish load and measure voltage. Keep a standard resistor for this. SOLDER the wires on that you use as probes. A twisted connection has too much variability. Resistor should draw a heavy load for battery type used. 100 mA - 500 mA is probably OK. Battery testers usually work this way. 5) Is this worth doing? Yes, it is. As well as returning a few batteries to the fold and making your life more exciting when some fail to perform, it teaches you a new skill that can be helpful in understanding how batteries behave in real life and the possible effect on equipment. The more you know, the more you get to know, and this is one more tool along the path towards knowing everything :-). [The path is rather longer than any can traverse, but learning how to run along it can be fun]. | {} | {'log_upvote_score': 7, 'links': ['https://electronics.stackexchange.com/questions/125863', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/51673/']} | jdg_379215 |
stackexchange | llm_judgeable_groundtruth_similarity | 495864 |
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 databinding my xaml to some data I often use the "get" part of a property to do some logic. Like giving to sum of totals of a list or a check if something is positive. For example: public List<SomeClass> ListOfSomeClass{get;set;}public double SumOfSomeClass{ get { return ListOfSomeClass.Sum(s => s.Totals); }}public bool SumPositive{ get { if(SumOfSomeClass >= 0) return true; else return false; }} This way I can bind to SumPositive and SumOfSomeClass. Is this considered good practice? Even if it gets more complex than this? Or would it be better call a method and return the outcome? What about calls to another class or even a database?
Now provide the response and nothing else.
| Property getters are expected to be fast and idempotent (i.e. no destructive actions should be performed there). Though it's perfectly fine to iterate over an in-memory collection of objects, I wouldn't recomment doing any kind of heavy lifting in either get or set parts. And speaking of iterating, I'd still cache the result to save a few milliseconds. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/495864', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/31722/']} | jdg_379216 |
stackexchange | llm_judgeable_groundtruth_similarity | 50363553 |
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 process in my Task Manager, which is end-able, but keeps starting up again. No Anti Virus has found this ad-ware virus yet, and I'm starting to think the only way to stop it from opening is to filter out its name in a program. This is a very brief example of what I want If process.XXX Alive = True; { Get process.XXX.PID; PID.End(); } Please ask me for any additional information. Edit: Changed 'id' to 'pid'
Now provide the response and nothing else.
| Unfortunately, you cannot schedule a work at specific time as of now. If you have time critical implementation then you should use AlarmManager to set alarm that can fire while in Doze to by using setAndAllowWhileIdle() or setExactAndAllowWhileIdle() . You can schedule a work, with onetime initial delay or execute it periodically, using the WorkManager as follows: Create Worker class: public class MyWorker extends Worker { @Override public Worker.WorkerResult doWork() { // Do the work here // Indicate success or failure with your return value: return WorkerResult.SUCCESS; // (Returning RETRY tells WorkManager to try this task again // later; FAILURE says not to try again.) }} Then schedule OneTimeWorkRequest as follows: OneTimeWorkRequest mywork= new OneTimeWorkRequest.Builder(MyWorker.class) .setInitialDelay(<duration>, <TimeUnit>)// Use this when you want to add initial delay or schedule initial work to `OneTimeWorkRequest` e.g. setInitialDelay(2, TimeUnit.HOURS) .build();WorkManager.getInstance().enqueue(mywork); You can setup additional constraints as follows: // Create a Constraints that defines when the task should runConstraints myConstraints = new Constraints.Builder() .setRequiresDeviceIdle(true) .setRequiresCharging(true) // Many other constraints are available, see the // Constraints.Builder reference .build(); Then create a OneTimeWorkRequest that uses those constraints OneTimeWorkRequest mywork= new OneTimeWorkRequest.Builder(MyWorker.class) .setConstraints(myConstraints) .build();WorkManager.getInstance().enqueue(mywork); PeriodicWorkRequest can be created as follows: PeriodicWorkRequest periodicWork = new PeriodicWorkRequest.Builder(MyWorker.class, 12, TimeUnit.HOURS) .build(); WorkManager.getInstance().enqueue(periodicWork); This creates a PeriodicWorkRequest to run periodically once every 12 hours. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/50363553', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_379217 |
stackexchange | llm_judgeable_groundtruth_similarity | 1901745 |
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 a multi-language web site, can I rely on the javascript confirm to translate the text of the Ok/Cancel buttons? If so, is it related to the browser or OS language setting?
Now provide the response and nothing else.
| The OK/Cancel button in Internet Explorer will obey the Operating System UI language settings. The technical reason is that IE is using the MessageBox Win32 API call to display its Javascript dialog box. That API relies on the OS UI language and not the browser UI language, as it is owned by the OS. As for 3rd party browsers, it really depends if they are using MessageBox or not to display their box. If they are, it will obey to the Operating System language, if not, it will obey to the browser UI language. EDIT: Firefox and Chrome are not using MessageBox so technically they should be following the browser UI language settings, though I don't have a french install to test it on . CONFIRMED If you must localize your buttons, your best bet would be a modal DHTML dialog. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1901745', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12601/']} | jdg_379218 |
stackexchange | llm_judgeable_groundtruth_similarity | 449136 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to build the following circuit Except mine is a 24V ~20A (500W) motor, so I need to swap the components. I'm currently looking into transistors and I've stopped on the 2N6284 (NPN) transistor, which is rated at 100V 20A. This basically means it's good to up to 2000W (right?), but it says the maximum power dissipation is 160W. Now this makes no sense so I'm guessing it's how much of the 2000W going through it will be lost as heat? I've looked all over the data sheet and there are a lot of things I don't understand on top of which is this diagram that suggests that temperature increases as power dissipation decreases? Isn't the relationship supposed to go the other way around, the more power lost as heat the higher the temperature? If any of my assumptions is correct then how can I calculate how much power will be lost running my 500W motor at 24 volts?
Now provide the response and nothing else.
| First, the power burnt up in a component is equal to the voltage drop of that component times the current going through it. The transistor has a \$V_{CE}\$ of 3V when the collector current is 20A, so that works out to 60W. Second, the power derating curve works by telling you the dissipation you can allow for a given case temperature. You read across until you find your design case temperature, then up to find the allowable dissipation (or, usually, the other way -- in your case you'd start at 60W, then read across to find that you should design for a case temperature of around 135 degrees C). Third, you'll need heat sinking to keep the case temperature down -- that thing won't dissipate 60W by itself. Fourth (and beyond what you were asking), you need a base current of 200mA to maintain that 3V \$V_{CE}\$ , and that's pushing into a base at a voltage of 4V. You are not going to do that with a microprocessor GPIO pin. | {} | {'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/449136', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/164399/']} | jdg_379219 |
stackexchange | llm_judgeable_groundtruth_similarity | 22750852 |
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 convert a Long into a List[Int] where each item in the list is a single digit of the original Long. scala> val x: Long = 123412341Lx: Long = 123412341scala> x.toString.split("").toListres8: List[String] = List("", 1, 2, 3, 4, 1, 2, 3, 4, 1)scala> val desired = res8.filterNot(a => a == "")desired: List[String] = List(1, 2, 3, 4, 1, 2, 3, 4, 1) Using split("") results in a "" list element that I'd prefer not to have in the first place. I could simply filter it, but is it possible for me to go from 123412341L to List(1, 2, 3, 4, 1, 2, 3, 4, 1) more cleanly?
Now provide the response and nothing else.
| If you want the integer values of the digits, it can be done like so: scala> x.toString.map(_.asDigit).toListres65: List[Int] = List(1, 2, 3, 4, 1, 2, 3, 4, 1) Note the difference that the .map(_.asDigit) makes: scala> x.toString.toListres67: List[Char] = List(1, 2, 3, 4, 1, 2, 3, 4, 1)scala> res67.map(_.toInt)res68: List[Int] = List(49, 50, 51, 52, 49, 50, 51, 52, 49) x.toString.toList is a List of Chars, i.e. List('1','2','3',...) . The toString rendering of the list makes it look the same, but the two are quite different -- a '1' character, for example, has integer value 49. Which you should use depends on whether you want the digit characters or the integers they represent. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22750852', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/409976/']} | jdg_379220 |
stackexchange | llm_judgeable_groundtruth_similarity | 34397982 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have the following Pandas DataFrame object df . It is a train schedule listing the date of departure, scheduled time of departure, and train company. import pandas as pddf = Year Month DayofMonth DayOfWeek DepartureTime Train OriginDatetime1988-01-01 1988 1 1 5 1457 BritishRail Leeds1988-01-02 1988 1 2 6 1458 DeutscheBahn Berlin1988-01-03 1988 1 3 7 1459 SNCF Lyons1988-01-02 1988 1 2 6 1501 BritishRail Ipswich1988-01-02 1988 1 2 6 1503 NMBS Brussels.... Now, let's say I wanted to select all items "DeutscheBahn" in the column "Train". I would use DB = df[df['Train'] == 'DeutscheBahn'] Now, how can I select all trains except DeutscheBahn and British Rails and SNCF. How can I simultaneously choose the items not these? notDB = df[df['Train'] != 'DeutscheBahn'] and notSNCF = df[df['Train'] != 'SNCF'] but I am not sure how to combine these into one command. df[df['Train'] != 'DeutscheBahn', 'SNCF'] doesn't work.
Now provide the response and nothing else.
| df[~df['Train'].isin(['DeutscheBahn', 'SNCF'])] isin returns the values in df['Train'] that are in the given list, and the ~ at the beginning is essentially a not operator. Another working but longer syntax would be: df[(df['Train'] != 'DeutscheBahn') & (df['Train'] != 'SNCF')] | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/34397982', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4797818/']} | jdg_379221 |
stackexchange | llm_judgeable_groundtruth_similarity | 6562407 |
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 found that in Google+ Project's page that buttons are all made from divs like: <div role="button"></div> I'd like to know, is this just for semantic purposes, or does it influence the style or event handling of the <div> ? I tried to simulate a button "click" with the jQuery click event, but it didn't work.
Now provide the response and nothing else.
| It tells accessibility (and other) software what the purpose of the div is. More here in the draft role attribute specification . Yes, it's just semantic. Sending a click event to the button should work. An earlier version of this answer (back in 2011) said: ...but jQuery's click function doesn't do that; it triggers only the event handlers that have been hooked up to the element with jQuery , not handlers hooked up in other ways. ...and provided the sample code and output below. I cannot replicate the output now (two years later). Even if I go back to earlier versions of jQuery, they all trigger jQuery handlers, DOM0 handlers, and DOM2 handlers. The order isn't necessarily the same between a real click and jQuery's click function. I've tried jQuery versions 1.4, 1.4.1, 1.4.2, 1.4.3, 1.4.4, 1.5, 1.5.1, 1.5.2, 1.6, and more recent releases such as 1.7.1, 1.8.3, 1.9.1, and 1.11.3 (the current 1.x release as of this writing). I can only conclude that it was a browser thing, and I don't know what browser I was using. (Right now I'm using Chrome 26 and Firefox 20 to test.) Here's a test which shows that indeed, jQuery handlers, DOM0 handlers, and DOM2 handlers are all (as of this writing!) triggered by jQuery's click : jQuery(function($) { var div; $("<p>").text("jQuery v" + $.fn.jquery).appendTo(document.body); // Hook up a handler *not* using jQuery, in both the DOM0 and DOM2 ways div = document.getElementById("theDiv"); div.onclick = dom0Handler; if (div.addEventListener) { div.addEventListener('click', dom2Handler, false); } else if (div.attachEvent) { div.attachEvent('onclick', dom2Handler); } // Hook up a handler using jQuery $("#theDiv").click(jqueryHandler); // Trigger the click when our button is clicked $("#theButton").click(function() { display("Triggering <code>click</code>:"); $("#theDiv").click(); }); function dom0Handler() { display("DOM0 handler triggered"); } function dom2Handler() { display("DOM2 handler triggered"); } function jqueryHandler() { display("jQuery handler triggered"); } function display(msg) { $("<p>").html(msg).appendTo(document.body); }}); <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script><div id="theDiv">Try clicking this div directly, and using the button to send a click via jQuery's <code>click</code> function.</div><input type='button' id='theButton' value='Click Me'> | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6562407', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/325241/']} | jdg_379222 |
stackexchange | llm_judgeable_groundtruth_similarity | 11632402 |
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 user editable google map where users can draw an overlay polygon onto the map using the drawing manager. This works fine and the console logs the lat lngs I need. However, I need to add a button that will clear the map of the polygon so they can draw again if a mistake was made. My implementation code is pasted below: geocoder = new google.maps.Geocoder(); var latlng = new google.maps.LatLng(<?php echo $latitude ?>, <?php echo $longitude ?>); var myOptions = { zoom: <?php echo $zoomlevel ?>, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); marker = new google.maps.Marker({ map:map, draggable:true, animation: google.maps.Animation.DROP, position: latlng }) pos = marker.position; //alert(pos); document.getElementById("gpsite-surgery-latitude").value = pos.lat(); document.getElementById("gpsite-surgery-longitude").value = pos.lng(); google.maps.event.addListener(marker, "dragend", function() { var myLatLng = marker.latLng; pos = marker.position; //alert(pos); document.getElementById("gpsite-surgery-latitude").value = pos.lat(); document.getElementById("gpsite-surgery-longitude").value = pos.lng(); }) google.maps.event.addListener(map, 'zoom_changed', function() { document.getElementById("gpsite-surgery-zoomlevel").value = map.getZoom(); }); var drawingManager = new google.maps.drawing.DrawingManager({ drawingMode: google.maps.drawing.OverlayType.MARKER, drawingControl: true, drawingControlOptions: { position: google.maps.ControlPosition.TOP_CENTER, drawingModes: [google.maps.drawing.OverlayType.POLYGON] }, polygonOptions: { fillColor: '#ffff00', fillOpacity: 0.4, strokeWeight: 3, clickable: true, zIndex: 1, editable: false } }); google.maps.event.addListener(drawingManager, 'polygoncomplete', function (polygon) { var coordinates = (polygon.getPath().getArray()); console.log(coordinates); }); drawingManager.setMap(map); }); There is also a marker on the map, you can ignore this.
Now provide the response and nothing else.
| Examine this code, it sounds exactly like what you are talking about, a button to delete the shape http://gmaps-samples-v3.googlecode.com/svn-history/r282/trunk/drawing/drawing-tools.html Edit: above link is broken but I was able to find that code here . // globals var drawingManager; var selectedShape; ... function clearSelection() { if (selectedShape) { selectedShape.setEditable(false); selectedShape = null; } } function setSelection(shape) { clearSelection(); selectedShape = shape; shape.setEditable(true); selectColor(shape.get('fillColor') || shape.get('strokeColor')); } function deleteSelectedShape() { if (selectedShape) { selectedShape.setMap(null); } } google.maps.event.addListener(drawingManager, 'overlaycomplete', function(e) { if (e.type != google.maps.drawing.OverlayType.MARKER) { // Switch back to non-drawing mode after drawing a shape. drawingManager.setDrawingMode(null); // Add an event listener that selects the newly-drawn shape when the user // mouses down on it. var newShape = e.overlay; newShape.type = e.type; google.maps.event.addListener(newShape, 'click', function() { setSelection(newShape); }); setSelection(newShape); } }); // Clear the current selection when the drawing mode is changed, or when the // map is clicked. google.maps.event.addListener(drawingManager, 'drawingmode_changed', clearSelection); google.maps.event.addListener(map, 'click', clearSelection); google.maps.event.addDomListener(document.getElementById('delete-button'), 'click', deleteSelectedShape); buildColorPalette(); } | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11632402', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1359584/']} | jdg_379223 |
stackexchange | llm_judgeable_groundtruth_similarity | 47442632 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Let's say you pass through a Python list to an HTML file using Flask. How do you loop through that list by writing Python code in the HTML file?
Now provide the response and nothing else.
| Instead of binding the drawer's model directly to $store.state.sidebar , use a computed setter in the drawer component. Note that you must pass in the new value from the drawer itself, don't just toggle whatever's already in the store. <template> <v-navigation-drawer v-model="drawer" ...></template><script> export default { computed: { drawer: { get () { return this.$store.state.sidebar }, set (val) { this.$store.commit('sidebar', val) } } } }</script> // vuex mutationsidebar (state, val) { state.sidebar = val} https://v2.vuejs.org/v2/guide/computed.html#Computed-Setter https://vuex.vuejs.org/en/forms.html Another option is to bind the prop and event separately <template> <v-navigation-drawer :value="$store.state.sidebar" @input="$store.commit('sidebar', $event)" ...></template> https://v2.vuejs.org/v2/guide/components.html#Using-v-model-on-Components | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/47442632', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8992955/']} | jdg_379224 |
stackexchange | llm_judgeable_groundtruth_similarity | 40183 |
Below is a question asked on the forum politics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Where I live (and perhaps in may other place across the world), in order for a party / person to be able to become a candidate in some elections (European Parliament, local, general/parliamentary, presidential), they must raise a certain amount of signature (actually some identification information from national ID + signature). While one is allowed to sign only once for a certain party, I am wondering why there is no "obfuscation" (security) in place to make harder for someone to know your political option, basically who you will most probably vote for in those elections. Somehow it seems to contradict the idea of secret ballot . Question: How does having to sign to support someone for elections fit with having a secret ballot?
Now provide the response and nothing else.
| Per the wiki article you linked to in your question, secret ballots were introduced to fight things like vote buying, intimidation, and blackmailing. In principle, one is a public display of opinion (free or not is completely irrelevant), while the other is a private vote -- even if you publicly say that you voted for this or that (freely or not is also irrelevant), no one can check that you actually did vote like that. On the topic of ballot option endorsements, things are trickier. And I should note in passing that it's not unheard of to sign for a ballot option that you do not approve of, in the interest of giving a voice to the entire political spectrum, and face intimidation before doing so or repercussion after having done so. In France, for instance, there was a time when the extreme right polled around 10-15% across the whole country, but because they'd rarely have a majority in municipalities and the like, they struggled to get the needed 500 signatures by elected officials to put a Presidential candidate forward. In large part, this was because a lot of intimidation was going on against the mayors who would provide their endorsement in the name of putting all relevant choices on the ballot. The Communist party, by contrast, basically polled epsilon across the country except in a few concentrated areas where they scored very well, and they were on good enough terms with the socialists that they'd get the 500 signatures without any problems. Countering that problem is a lot trickier. Frankly the main thing that immediately springs to mind is some kind of first round of voting where only those allowed to endorse candidates would get to vote. But then there's a natural counter argument to do so, which is that: If as a candidate or a promoter of some cause you can't get a large enough number of people to publicly endorse that you're a sensible ballot option, then you or your cause probably do not deserve to be on the ballot at all. (In other words, the exact same type of criteria that guards communities that allow referendums by popular support against voting constantly on pointless topics.) Another thing that springs to mind is an open ballot. The problem there is that the gate is wide open to interpret whatever voters filled in (think typos, difficult to read handwriting, etc.). | {} | {'log_upvote_score': 5, 'links': ['https://politics.stackexchange.com/questions/40183', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/11278/']} | jdg_379225 |
stackexchange | llm_judgeable_groundtruth_similarity | 157133 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have an application server which we start by running this below command and as soon as we run the below commnad, it will start my application server /opt/data/bin/test_start_stop.sh start And to stop my application server, we do it like this - /opt/data/bin/test_start_stop.sh stop So as soon as my application server is running and if I do ps aux , this is what I get - user@machineA:/home/user$ ps aux | grep gld_httpuser 20426 0.0 0.0 8114 912 pts/4 S+ 13:33 0:00 grep gld_httpuser 40509 0.1 0.9 3878120 1263552 ? Sl Sep22 1:53 /opt/data/bin/gld_http Now I am trying to make a shell script in which I need to stop my application server and then I will check whether my process is running after stopping the server or not, if my process is still running, then I need to do kill -9 of my application pid. And I am not sure how to get the pid of my process in the shell script and then kill it. Below is my shell script which I have as of now which will shut down my app server and then check whether my process is still running or not and if by any chance it is still running, then I need to get the pid of my process and do kill -9 on that pid. #!/bin/bash/opt/data/bin/test_start_stop.sh stopif ps aux | grep -v "grep" | grep "gld_http"then echo "Server is still running" # now get the pid of my gld_http process and invoke kill -9 on itelse echo "Server is stopped"fi How can I get the pid of my process and do kill -9 on it in my above shell script? UPDATE:- So my final script will look like this - #!/bin/bash/opt/data/bin/test_start_stop.sh stopif ps aux | grep -v "grep" | grep "gld_http"then echo "Server is still running" # Getting the PID of the process PID=`pgrep gld_http` # Number of seconds to wait before using "kill -9" WAIT_SECONDS=10 # Counter to keep count of how many seconds have passed count=0 while kill $PID > /dev/null do # Wait for one second sleep 1 # Increment the second counter ((count++)) # Has the process been killed? If so, exit the loop. if ! ps -p $PID > /dev/null ; then break fi # Have we exceeded $WAIT_SECONDS? If so, kill the process with "kill -9" # and exit the loop if [ $count -gt $WAIT_SECONDS ]; then kill -9 $PID break fi done echo "Process has been killed after $count seconds." else echo "Server is stopped"fi
Now provide the response and nothing else.
| First of all; "kill -9" should be a last resort. You can use the kill command to send different signals to a process. The default signal sent by kill is 15 (called SIGTERM). Processes usually catch this signal, clean up and then exit. When you send the SIGKILL signal ( -9 ) a process has no choice but to exit immediately. This may cause corrupted files and leave state files and open sockets that might cause problems when you restart the process. The -9 signal can not be ignored by a process. This is how I would do it: #!/bin/bash# Getting the PID of the processPID=`pgrep gld_http`# Number of seconds to wait before using "kill -9"WAIT_SECONDS=10# Counter to keep count of how many seconds have passedcount=0while kill $PID > /dev/nulldo # Wait for one second sleep 1 # Increment the second counter ((count++)) # Has the process been killed? If so, exit the loop. if ! ps -p $PID > /dev/null ; then break fi # Have we exceeded $WAIT_SECONDS? If so, kill the process with "kill -9" # and exit the loop if [ $count -gt $WAIT_SECONDS ]; then kill -9 $PID break fidoneecho "Process has been killed after $count seconds." | {} | {'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/157133', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/64455/']} | jdg_379226 |
stackexchange | llm_judgeable_groundtruth_similarity | 5822 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
How can I manipulate the "from" field in an email and make the "to" user see something different then the actual. Example: really from From: [email protected] but they see From: Tremayne "Top Dog" Stamper I've heard its from manipulating SMTP, but really not sure how accurate that is or how it can be done
Now provide the response and nothing else.
| At its base, SMTP is just a text based protocol with no real verification. Here's an example: === Trying g3.example.net:25...=== Connected to g3.example.net.<- 220 home.example.net ESMTP Exim 4.68 Thu, 07 May 2009 11:03:21 -0400 -> EHLO g3.example.net<- 250-home.example.net Hello g3.example.net [192.168.0.4]<- 250-SIZE 52428800<- 250-PIPELINING<- 250-AUTH CRAM-SHA1 CRAM-MD5 MSN<- 250-STARTTLS<- 250 HELP -> MAIL FROM:<[email protected]><- 250 OK -> RCPT TO:<[email protected]><- 250 Accepted -> DATA<- 354 Enter message, ending with "." on a line by itself -> Date: Thu, 07 May 2009 11:03:21 -0400 -> To: [email protected] -> From: [email protected] -> Subject: test Thu, 07 May 2009 11:03:21 -0400 -> X-Mailer: swaks v20070921.0-dev jetmore.org/john/code/#swaks -> -> This is a test mailing -> -> .<- 250 OK id=KJA4HL-0006M6-8T -> QUIT<- 221 home.example.net closing connection=== Connection closed with remote host. The "MAIL FROM:" line defines the SMTP envelope sender, and the From: is defined in the message DATA. There are ways to protect against this, but they are defined in the mail server logic, not in the protocol itself. For instance I, as a mail provider, may require a user to authenticate using a user@domain type username. Then my mail server might require that any mail they send have an envelope-sender and a From: header that matches the user they authenticated as. Additional technologies like DKIM and SPF can help in this area also. | {} | {'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/5822', 'https://serverfault.com', 'https://serverfault.com/users/2049/']} | jdg_379227 |
stackexchange | llm_judgeable_groundtruth_similarity | 71052 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
What are the pros and cons of choosing a local domain name such as mycompany.local versus a publicly registered domain name such as mycompany.com (assuming that your org has registered the public name)?When would you choose one over the other? UPDATE Thanks to Zoredache and Jay for pointing me to this question , which had the most useful responses. That also led me to find this Microsoft Technet article , which states: It is best to use DNS names that are registered with an Internet authority in the Active Directory namespace. Only registered names are guaranteed to be globally unique. If another organization later registers the same DNS domain name, or if your organization merges with, acquires, or is acquired by other company that uses the same DNS names, then the two infrastructures cannot interact with one another. Note Using single label names or unregistered suffixes, such as .local, is not recommended. Combining this with mrdenny's advice, I think the right approach is to use either: Registered domain name that willnever be used publicly (e.g.mycompany.org, mycompany.info, etc). Subdomain of an existing public domain name which will neverbe used publicly (e.g.corp.mycompany.com). The "never used publicly" part is a business decision so its probably best to get sign off from those in the company authorized to reserve domain names and subdomains. E.g. you don't want to use a registered name or subdomain that the marketing dept later wants to use for some public marketing campaign.
Now provide the response and nothing else.
| Below is an excerpt from my answer to a similar question found at: Top level domain/domain suffix for private network? . Microsoft has recommended either a dedicated, registered domain name that is not available on the Internet a subdomain of your public domain name for use as the Active Directory forest root domain name ever since they released Active Directory in Windows 2000 Server. To me, the main benefit of using a subdomain of your public domain name is a consistency of namespace, resulting in one less thing that you, other administrators, and users have to remember. Use a subdomain of your company's registered domain for internal machines whose names you do not want available on the Internet. (Then, of course, only host those names on your internal DNS servers.) Here are some examples for the fictitious Example Corporation. Internet-facing servers: www.example.com mail.example.com dns1.example.com Internal machines: dc1.corp.example.com dns1.corp.example.com client1.corp.example.com I used "corp" to signify that this subdomain described machines on the internal corporate network, but you could use anything you want here, such as "internal": client1.internal.example.com. | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/71052', 'https://serverfault.com', 'https://serverfault.com/users/2424/']} | jdg_379228 |
stackexchange | llm_judgeable_groundtruth_similarity | 31363216 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I know there are other topics on this, but I can't seem to find out how to implement it. I'm trying to limit a UITextField to only five characters. Preferably alphanumeric, - , . , and _ . I've seen this code: func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool{ let maxLength = 4 let currentString: NSString = textField.text let newString: NSString = currentString.stringByReplacingCharactersInRange(range, withString: string) return newString.length <= maxLength} and func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { let length = count(textField.text.utf16) + count(string.utf16) - range.length return length <= 10} How can I actually implement it? Which "textfield" should I swap out for my custom named UITextField?
Now provide the response and nothing else.
| Your view controller should conform to UITextFieldDelegate , like below: class MyViewController: UIViewController, UITextFieldDelegate {} Set the delegate of your textfield: myTextField.delegate = self Implement the method in your view controller: textField(_:shouldChangeCharactersInRange:replacementString:) All together: class MyViewController: UIViewController, UITextFieldDelegate // Set delegate to class@IBOutlet var mytextField: UITextField // textfield variableoverride func viewDidLoad() { super.viewDidLoad() mytextField.delegate = self // set delegate}func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool{ let maxLength = 4 let currentString: NSString = textField.text let newString: NSString = currentString.stringByReplacingCharactersInRange(range, withString: string) return newString.length <= maxLength} For Swift 4 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { let maxLength = 1 let currentString: NSString = (textField.text ?? "") as NSString let newString: NSString = currentString.replacingCharacters(in: range, with: string) as NSString return newString.length <= maxLength} For Swift 5 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { let maxLength = 1 let currentString = (textField.text ?? "") as NSString let newString = currentString.replacingCharacters(in: range, with: string) return newString.count <= maxLength} Allowing only a specified set of characters to be entered into a given text field func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { var result = true if mytextField == textField { if count(string) > 0 { let disallowedCharacterSet = NSCharacterSet(charactersInString: "0123456789.-").invertedSet let replacementStringIsLegal = string.rangeOfCharacterFromSet(disallowedCharacterSet) == nil result = replacementStringIsLegal } } return result} How to program an iOS text field that takes only numeric input with a maximum length | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/31363216', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4538482/']} | jdg_379229 |
stackexchange | llm_judgeable_groundtruth_similarity | 669995 |
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:
A while back, I was curious about how the optimal angle (ie. max range) for a projectile (with no drag and so forth, so HS physics conditions) would change if it is thrown from a height $h$ . So I started working on this, and about $1.5$ pages into my $4$ page solution [full of ugly trig and differentiation, I did not think to use Wolfram :( ...], I decided to assume $v$ (the velocity with which projectile is thrown) to be equal to $\sqrt{g}$ . I did this because this simplified the trig a bit and I thought that the optimal angle would be independent of $v$ . Because it is well known that when $h=0$ , optimal angle is $\theta=45^\circ$ irrespective of $v$ , so I thought the same would hold for any arbitratry $h$ . So after some more messy math I got optimal angle $\theta$ is: $\sin^2\theta = \frac{1}{2(h+1)} \iff \cos2\theta = \frac{h}{h+1}$ Then I looked up the solution and found this Physics Stack Exchange answer, which gave the answer: $\cos2\theta=\frac{gh}{v^2+gh}$ So my answer is the correct when $v=\sqrt g$ but I was surprised when I saw that the answer depends on launch velocity. Of course I looked at the math again (with my good friend Wolfram, this time) to see that the answer did infact depend on $v$ also. But I still do not understand why this is the case. I mean this is not the case when $h=0$ . Also, it seems to me like increasing the velocity would just scale the answer by a positive factor, so I am not sure why the velocity is important here. So, Tldr; I want to understand intuitively/qualitatively (I understand it mathematically) why the optimal angle for maximising range in a projectile is not independent of the launch velocity.
Now provide the response and nothing else.
| Let's take an extreme situation where $h$ is very high. According to both formula, the best angle should be zero, especially if $v$ is low, so path (1) gives the best range. If the angle were independent of velocity it would be zero degrees even if $v$ were increased. But if $v$ becomes very large, so that $h$ looks small, it's better for the angle to be like path (2). The projectile is now spending nearly all the time above $h$ . This is similar to a projectile launched from a lower height - an angle near 45 degrees would be best. So the best angle needs to depend on velocity as well as the height of projection. | {} | {'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/669995', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/287211/']} | jdg_379230 |
stackexchange | llm_judgeable_groundtruth_similarity | 170392 |
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:
Doing R&D work, I often find myself writing programs that have some large degree of randomness in their behavior. For example, when I work in Genetic Programming, I often write programs that generate and execute arbitrary random source code. A problem with testing such code is that bugs are often intermittent and can be very hard to reproduce. This goes beyond just setting a random seed to the same value and starting execution over. For instance, code might read a message from the kernal ring buffer, and then make conditional jumps on the message contents. Naturally, the ring buffer's state will have changed when one later attempts to reproduce the issue. Even though this behavior is a feature it can trigger other code in unexpected ways, and thus often reveals bugs that unit tests (or human testers) don't find. Are there established best practices for testing systems of this sort? If so, some references would be very helpful. If not, any other suggestions are welcome!
Now provide the response and nothing else.
| It is useful to add hooks, as suggested, to recreate exact states. Also instrument the system so that it can dump its "seeds" (in your case, including the PRNG seed as well as the kernel ring buffer, and any other sources of nondeterministic input.) Then run your tests both with true random input, and regression-style with any previously-discovered interesting cases. In the particular case of your access to the kernel, I'd recommend making a mock in any case. Use the mock to force equivalence classes that are less likely to show up in practice, in the spirit of "empty" and "full" for containers, or "0, 1, 2^n, 2^n+1, many" for countable things. Then you can test with the mock and with the real thing, knowing that you have handled and tested the cases you've thought of so far. Basically, what I'm suggesting amounts to a mix of deterministic and nondeterministic inputs, with the deterministic ones being a mix of those you can think of and those you were surprised by. | {} | {'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/170392', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/69146/']} | jdg_379231 |
stackexchange | llm_judgeable_groundtruth_similarity | 1739675 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How can I efficiently implement a list data structure where I can have 2 views to the head and end of the list, that always point to a head a tail of a list without expensive calls to reverse.i.e: start x = []end x = reverse start -- []start1 = [1,2,3] ++ startend start1 -- [3,2,1] end should be able to do this without invoking 'reverse' but simply looking at the given list from the perspective of the list being in reverse automatically. The same should hold if I create new lists from concatenations to start.
Now provide the response and nothing else.
| You could always just use Data.Sequence . Alternatively, a well-known implementation of a purely functional queue is to use two lists. One for enqueue and another for dequeue. Enqueue would simply cons with the enqueue list. Dequeue takes the head of the dequeue list. When the dequeue list is shorter than the enqueue list, refill it by reversing the enqueue list. See Chris Okasaki's Purely Functional Datastructures. Even though this implementation uses reverse , the amortized time cost of this is insignificant asymptotically. It works out so that for every enqueue, you incur a time debt of Θ(1) for the dequeue list refill. The expected time of a dequeue is therefore at most twice that of an enqueue. This is a constant factor, so the worst-case cost of both operations is O(1). | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1739675', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/172776/']} | jdg_379232 |
stackexchange | llm_judgeable_groundtruth_similarity | 8447384 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have the following query: public IEnumerable<Team> GetAllTeamsWithMembers(int ownerUserId) { return _ctx.Teams .Include(x => x.TeamMembers) .Where(x => x.UserId == ownerUserId) .OrderBy(x => x.Name).ToList(); } How do I go about ordering the teams by their name, and then have all the child members of each team sorted by their name? It seems that do this I need to create a new DTO class and use a select. I'd like to use the EF entities already created, in this case Team has a navigation property to Members. I return IEnumerable<Team> out from my repository layer. There doesn't seem to be a neat way of ordering child collections in EF. Can anyone help?
Now provide the response and nothing else.
| You could load the data and sort in memory after loading it. IEnumerable<Team> teams = _ctx.Teams .Include(x => x.TeamMembers) .Include(x => x.TeamMembers.Select(u => u.User)) .Where(x => x.UserId == ownerUserId) .OrderBy(x => x.Name).ToList();foreach (var team in teams){ team.TeamMembers = team.TeamMembers.OrderBy(m => m.Name); foreach (var teamMember in team.TeamMembers) { teamMember.Users = teamMember.Users.OrderBy(u => u.Name); }} Or you could use Projections and use the Change Tracking of EF to sort your collection. Here is an example of filtering an Include but the same works for Ordering. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8447384', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/306098/']} | jdg_379233 |
stackexchange | llm_judgeable_groundtruth_similarity | 14473684 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What would the Big O notation be for the following nested loops? for (int i = n; i > 0; i = i / 2){ for (int j = n; j > 0; j = j / 2){ for (int k = n; k > 0; k = k / 2){ count++; } } } My thoughts are:each loop is O(log2(n)) so is it as simple as multiply O(log2(n)) * O(log2(n)) * O(log2(n)) = O(log2(n)^3)
Now provide the response and nothing else.
| Yes, that is correct. One way to figure out the big-O complexity of nested loops whose bounds do not immediately depend on one another is to work from the inside out. The innermost loop does O(log n) work. The second loop runs O(log n) times and does O(log n) work each time, so it does O(log 2 n) work. Finally, the outmost loop runs O(log n) times and does O(log 2 n) work on each iteration, so the total work done is O(log 3 n). Hope this helps! | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14473684', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1758558/']} | jdg_379234 |
stackexchange | llm_judgeable_groundtruth_similarity | 53596283 |
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 dataframe: id rev names34e A su,ra,ve,ra,de,ra45e R ra,su,su,ve,de55e G su,ra,de41e M su,de,mu,er,su Now I need to delete the duplicates, the output should be as below: id rev names34e A su,ra,ve,de45e R ra,su,ve,de55e G su,ra,de41e M su,de,mu,er How can this be done?
Now provide the response and nothing else.
| If column contains strings first split , convert to set s and join : df['names'] = df['names'].apply(lambda x: ','.join(set(x.split(',')))) If column contains lists converting to set and list is necessary: df['names'] = df['names'].apply(lambda x: list(set(x))) If order is important use pandas.unique : df['names'] = df['names'].apply(lambda x: ','.join(pd.unique(x.split(','))))df['names'] = df['names'].apply(lambda x: list(pd.unique(x))) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/53596283', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_379235 |
stackexchange | llm_judgeable_groundtruth_similarity | 58057769 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
TrendingViewModelTest @RunWith(JUnit4::class)class TrendingViewModelTest { private lateinit var trendingRepository: TrendingRepository private lateinit var trendingViewModel: TrendingViewModel @get:Rule val schedulers = RxImmediateSchedulerRule() @Before fun setUp() { trendingRepository = mock(TrendingRepository::class.java) trendingViewModel = TrendingViewModel(trendingRepository) } @Test fun testWithNetwork() { trendingViewModel.isConnected = true trendingViewModel.fetchTrendingRepos() verify(trendingRepository, times(1)).getTrendingRepos() } //...} TrendingViewModel fun fetchTrendingRepos() {if (isConnected) { loadingProgress.value = true compositeDisposable.add( trendingRepository.getTrendingRepos().subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ response -> run { loadingProgress.value = false }, { error -> loadingProgress.value = false } ) )} RxImmediateSchedulerRule: class RxImmediateSchedulerRule : TestRule { override fun apply(base: Statement?, description: Description?): Statement { return object : Statement() { @Throws(Throwable::class) override fun evaluate() { RxJavaPlugins.setIoSchedulerHandler { Schedulers.trampoline() } RxJavaPlugins.setComputationSchedulerHandler { Schedulers.trampoline() } RxJavaPlugins.setNewThreadSchedulerHandler { Schedulers.trampoline() } RxAndroidPlugins.setInitMainThreadSchedulerHandler { Schedulers.trampoline() } try { base?.evaluate() } finally { RxJavaPlugins.reset() RxAndroidPlugins.reset() } } } }} TrendingRepositoryImpl: class TrendingRepositoryImpl @Inject constructor( val apiService: GitHubApi, val trendingDao: AppDao) : TrendingRepository { override fun getTrendingRepos(): Single<List<TrendingRepo>> { return apiService.getTrendingGits() }} TrendingRepository: interface TrendingRepository { fun getTrendingRepos(): Single<List<TrendingRepo>>} Inside fetchTrendingRepos() an Rxjava call is initiated, it also hooks onto 'AndroidSchedulers.mainThread()' that might be the reason causing it. java.lang.RuntimeException: Method getMainLooper in android.os.Looper not mocked. at android.os.Looper.getMainLooper(Looper.java) at androidx.arch.core.executor.DefaultTaskExecutor.isMainThread(DefaultTaskExecutor.java:77) at androidx.arch.core.executor.ArchTaskExecutor.isMainThread(ArchTaskExecutor.java:116) at androidx.lifecycle.LiveData.assertMainThread(LiveData.java:461) at androidx.lifecycle.LiveData.setValue(LiveData.java:304) at androidx.lifecycle.MutableLiveData.setValue(MutableLiveData.java:50) at com.manoj.trendgitz.mvvm.ui.TrendingViewModel.fetchTrendingRepos(TrendingViewModel.kt:32) at com.manoj.trendgitz.TrendingViewModelTest.testWithNetwork(TrendingViewModelTest.kt:52) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.junit.runner.JUnitCore.run(JUnitCore.java:137) at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68) at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47) at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242) at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Now provide the response and nothing else.
| As you update LiveData value, you should add @get:Rule var rule: TestRule = InstantTaskExecutorRule() also. Don't forget to add following to build.gradle file: dependencies { // ... testImplementation "androidx.arch.core:core-testing:2.1.0"} Also, change your test code accordingly to avoid NullPointerException : @Testfun testWithNetwork() { trendingViewModel.isConnected = true Mockito.`when`(trendingRepository.fetchTrendingRepos()).thenReturn(Single.just(listOf<TrendingRepo>())) trendingViewModel.fetchTrendingRepos() verify(trendingRepository, times(1)).getTrendingRepos()} Mockito.when() lets you to do different actions every time your mock method is called. If you don't use it, you may see possible NullPointerException depending on your test function. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/58057769', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5351055/']} | jdg_379236 |
stackexchange | llm_judgeable_groundtruth_similarity | 1054989 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've read in blogs that the database should not be hit when the unit tests run. I understand the theory, however say i have complex store procedures that are part of a business domain operation. I want to write a set of unit tests for the code related to the business operation, however if i mock the database i have the feeling that im not "really" testing all the parts that are part of the operation. For example someone could create a bug in one of the database code and the tests will still be running ok. I would like to know if this guideline about unit tests is good in practice.I've seen the concept of "integration tests" however im not sure about what tools to use to do integration tests. For example ¿Is it ok to create an integration test using a test framework like Nunit? Thanks Hugo
Now provide the response and nothing else.
| You are simply in a semantic grey area. System tests cover the whole system from end-to-end. Unit tests can be used to describe a sub-segment of the end-to-end cycle. In that case your unit tests of your application code would/might not hit the database, but you would/might have unit tests that covered your database stored procedures... Basically divide your application into things to be tested along partitions that make sense. If you choose the wrong partition line you end up with a big code maintenance problem with mock objects and test scaffolding and stuff... A common way with web apps is to write a series of unit tests that test the data access layer... Then write a series of unit tests that test the application layer (including the data layer) ... And finally write some browser-based system tests... The trick is to only put information in and out of the middle set - the application layer - through the API and not burrow into the database to see if something worked. That way your tests won't break if you change the data schema. But sometimes (as I actually currently doing as I write this) you HAVE to look into the database to make a meaningful and robust test suite (I am testing server-server transfer protocols). Focus on the way that gets maximum code coverage and stability for your application, whilst writing the least amount of testing scaffolding, and avoiding brittleness in your test suite. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1054989', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/48025/']} | jdg_379237 |
stackexchange | llm_judgeable_groundtruth_similarity | 3300389 |
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:
Does the infinite sum $\sum_{n = 1}^{\infty} \left( 1-\frac{\ln(n)}{n} \right)^{n}$ converge or diverge? I've applied root, ratio and Gauss's test but it didn't help.
Now provide the response and nothing else.
| $$\begin{split}\left( 1 - \frac{\ln n}n\right)^n &= \exp\left(n\left(\ln\left(1-\frac {\ln n}n\right)\right)\right)\\&= \exp\left(n\left(-\frac {\ln n}n +\mathcal O\left(\frac{\ln n}n\right)^2\right)\right)\\&=\exp\left(-\ln n +\mathcal O\left (\frac{(\ln n)^2}n\right)\right)\\&=\frac 1 n\exp\left( \mathcal O\left (\frac{(\ln n)^2}n\right)\right)\\&=\frac 1 n +\mathcal O\left(\frac{\ln n}n\right)^2\end{split}$$ The sum of the first terms diverges (Harmonic series) while the sum of the second terms converges. Therefore the whole series diverges. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3300389', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/690661/']} | jdg_379238 |
stackexchange | llm_judgeable_groundtruth_similarity | 1859564 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Given an $n$-th root of unity $\zeta$, consider the $\mathbb Z$-module $M := \mathbb Z[\zeta]$. Does this module have a special name? Does a basis exist for every $n$? And if so, is there an algorithm to find a basis given an $n$? I was just playing around with this, and noticed that for $n=3$ we have e.g. the basis $(1,\zeta)$ because $1+\zeta = -\zeta^2$. For $n=4$ we obviously have the basis $(1,i)$, but I was unable to generalize this for an arbitrary $n$.
Now provide the response and nothing else.
| I don't know if you consider this a special name, but the ring $\mathbb{Z}[\zeta]$ is the ring of integers for the number field $\mathbb{Q}(\zeta)$. This is (IMO, anyway) a nontrivial fact, but you can find its proof in Neukirch (see below), or (for the case $n$ prime) in Samuel's ''Algebraic Theory of Numbers''— this link might also be helpful to you. Correspondingly, it is free as a $\mathbb{Z}$-module, and its rank is given by the degree $[\mathbb{Q}(\zeta):\mathbb{Q}] = \varphi(n)$, where $\varphi$ is the Euler totient function. The basis for $\mathbb{Z}[\zeta]$ as a $\mathbb{Z}$-module is given by $1, \zeta, \zeta^{2}, \ldots, \zeta^{d-1}$, where $d = \varphi(n)$. As a reference, see Neukirch's ''Algebraic Number Theory'', page 60, Proposition 10.2. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1859564', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/109451/']} | jdg_379239 |
stackexchange | llm_judgeable_groundtruth_similarity | 14736328 |
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 searching the net and stackoverflow for an example of somebody inserting content into the response using a servlet filter, but can only find examples of people capturing/compressing the output and/or changing the headers. My goal is to append a chunk of HTML just before the closing </body> of all HTML responses. I'm working on a solution that extends the HttpServletResponseWrapper to use my own PrintWriter, then overriding the write methods thereon. Inside the write method I'm storing the last 7 characters to see if it's equal to the closing body tag, and then I write my HTML chunk plus the closing body tag, before continuing normal write operations for the rest of the document. I feel that somebody must have solved this problem already, and probably more elegantly than I will. I'd appreciate any examples of how to use a servlet filter to insert content into a response. UPDATED Responding to a comment, I am also trying to implement the CharResponseWrapper from http://www.oracle.com/technetwork/java/filters-137243.html . Here is my code: PrintWriter out = response.getWriter();CharResponseWrapper wrappedResponse = new CharResponseWrapper( (HttpServletResponse)response);chain.doFilter(wrappedRequest, wrappedResponse);String s = wrappedResponse.toString();if (wrappedResponse.getContentType().equals("text/html") && StringUtils.isNotBlank(s)) { CharArrayWriter caw = new CharArrayWriter(); caw.write(s.substring(0, s.indexOf("</body>") - 1)); caw.write("WTF</body></html>"); response.setContentLength(caw.toString().length()); out.write(caw.toString());}else { out.write(wrappedResponse.toString());}out.close(); I am also wrapping the request, but that code works and shouldn't affect the response.
Now provide the response and nothing else.
| The codebase I am using, calls the getOutputStream method, instead of getWriter when it processes the response, so the examples included in the other answer doesn't help. Here is a more complete answer that works with both the OutputStream and the PrintWriter, even erroring correctly, if the writer is accessed twice. This is derived from the great example, DUMP REQUEST AND RESPONSE USING JAVAX.SERVLET.FILTER . import javax.servlet.*;import javax.servlet.http.*;import java.io.*;public class MyFilter implements Filter{ private FilterConfig filterConfig = null; private static class ByteArrayServletStream extends ServletOutputStream { ByteArrayOutputStream baos; ByteArrayServletStream(ByteArrayOutputStream baos) { this.baos = baos; } public void write(int param) throws IOException { baos.write(param); } } private static class ByteArrayPrintWriter { private ByteArrayOutputStream baos = new ByteArrayOutputStream(); private PrintWriter pw = new PrintWriter(baos); private ServletOutputStream sos = new ByteArrayServletStream(baos); public PrintWriter getWriter() { return pw; } public ServletOutputStream getStream() { return sos; } byte[] toByteArray() { return baos.toByteArray(); } } public class CharResponseWrapper extends HttpServletResponseWrapper { private ByteArrayPrintWriter output; private boolean usingWriter; public CharResponseWrapper(HttpServletResponse response) { super(response); usingWriter = false; output = new ByteArrayPrintWriter(); } public byte[] getByteArray() { return output.toByteArray(); } @Override public ServletOutputStream getOutputStream() throws IOException { // will error out, if in use if (usingWriter) { super.getOutputStream(); } usingWriter = true; return output.getStream(); } @Override public PrintWriter getWriter() throws IOException { // will error out, if in use if (usingWriter) { super.getWriter(); } usingWriter = true; return output.getWriter(); } public String toString() { return output.toString(); } } public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; } public void destroy() { filterConfig = null; } public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { CharResponseWrapper wrappedResponse = new CharResponseWrapper( (HttpServletResponse)response); chain.doFilter(request, wrappedResponse); byte[] bytes = wrappedResponse.getByteArray(); if (wrappedResponse.getContentType().contains("text/html")) { String out = new String(bytes); // DO YOUR REPLACEMENTS HERE out = out.replace("</head>", "WTF</head>"); response.getOutputStream().write(out.getBytes()); } else { response.getOutputStream().write(bytes); } }} | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14736328', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/448016/']} | jdg_379240 |
Subsets and Splits