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
60838
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 cone standing on its tip is considered to be in unstable equilibrium as a slightest force could topple it. So, if the cone is stood on its tip with no other force other than gravity (and the corresponding ground reaction force ), will it continue to stand without toppling? Has this been attempted experimentally? Now provide the response and nothing else.
If you made the most perfect cone possible, so that its tip was a single atom, and stood it on the most perfect surface possible (a perfectly smooth, perfectly hard sheet of atoms), and completely removed all forces other than gravity, it would still topple. This is because those atoms are all jiggling around due to thermal motion. This effect fundamentally cannot be removed, and sooner or later it will cause enough of a perturbation to cause the cone to start falling. It might take a fairly long time before this happens, however. A more realistically imperfect cone might have a better chance. A real metal object isn't perfectly smooth. It's fairly likely that the tip of the cone will actually be rounded, even if it appears perfectly sharp under a microscope, and on an even smaller level it will be quite jagged. The same applies to the surface. It's possible that the two will find a way to mesh together such that they balance, especially since neither will really be perfectly hard, so they'll inevitably sink into one another a bit. As for whether the experiment has been done, I'm sure a lot of people have made cones of varying degrees of imperfection and attempted to balance them with varying degrees of success. But the idealised experiment - perfect cone, perfect surface, no other forces - would be rather expensive. Creating and checking the cone tip and the surface would require an electron microscope, but the really hard part is eliminating all other forces. Air movement, seismic vibrations, electromagnetic effects, perhaps even the gravitational field of nearby objects would all have to be accounted for. For these reasons I doubt that version of the experiment has been done. This is going beyond what's practically possible, but in principle, thermal effects could be eliminated (or very nearly eliminated) by cooling the system down to absolute zero. It's impossible to completely reach absolute zero, but we can get very close. But if we do that we run into a different problem: Heisenberg's uncertainty principle. The problem is that in order for the cone to be perfectly balanced, its centre of mass must be exactly above the point of the cone, and also the cone has to not be moving at all, i.e. it must have exactly zero momentum. But if the cone was set up in that way we would know the exact position of the centre of mass, and we'd also know its exact momentum at the same time. Quantum mechanics says this is impossible, and this means that even if you could eliminate thermal effects completely, it would be fundamentally impossible to set the cone up so that it was absolutely, perfectly balanced.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/60838', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/23059/']}
jdg_86941
stackexchange
llm_judgeable_groundtruth_similarity
19914082
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'm fairly new to Git in general, and before I was using Dropbox to sync my files across multiple computers. I am now using GitHub to track versions of my program remotely, and this is working great, however being that it's school related I also have other files that I am maintaining such as the PDF of the assignment and office documents related to the project. When using command line git it is easy enough to initialize and track my entire directory, however afaik I need to use the command line version to sync to GitHub in order to maintain versions of files. The easiest solution that I can see would be to continue using Dropbox to sync and keep my git repository in Dropbox, however if I am on a computer that I cannot use Dropbox on I will only have access to the programming files that netbeans tracks and would have to manually download/upload any other files that I want to sync. So is there a pure NetBeans solution? Or do I need to use a 3rd party Git program or batch script to do this? Now provide the response and nothing else.
Javascript has function scope. This means that for(...) { var j = i;} is equivalent to var j;for(...) { j = i;} In fact, this is how Javascript compilers will actually treat this code. And, of course, this causes your little "trick" to fail, because j will be incremented before the function in setTimeout gets called, i.e. j now doesn't really do anything different than i , it's just an alias with the same scope. If Javascript were to have block scope, your trick would work, because j would be a new variable within every iteration. What you need to do is create a new scope: for(var i = ...) { (function (j) { // you can safely use j here now setTimeout(...); })(i);}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19914082', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/679716/']}
jdg_86942
stackexchange
llm_judgeable_groundtruth_similarity
13446920
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 not talking about the frame property, because from that you can only get the view's size in the xib. I'm talking about when the view is resized because of its constraints (maybe after a rotation, or in response to an event). Is there a way to get its current width and height? I tried iterating through its constraints looking for width and height constraints, but that's not very clean and fails when there are intrinsic constraints (since I can't differentiate between the two). Also, that only works if they actually have width and height constraints, which they don't if they rely on other constraints to resize. Why is this so difficult for me. ARG! Now provide the response and nothing else.
The answer is [view layoutIfNeeded] . Here's why: You still get the view's current width and height by inspecting view.bounds.size.width and view.bounds.size.height (or the frame, which is equivalent unless you're playing with the view.transform ). If what you want is the width and height implied by your existing constraints, the answer is not to inspect the constraints manually, since that would require you to re-implement the entire constraint-solving logic of the auto layout system in order to interpret those constraints. Instead, what you should do is just ask auto layout to update that layout , so that it solves the constraints and updates the value of view.bounds with the correct solution, and then you inspect the view.bounds. How do you ask auto layout to update the layout? Call [view setNeedsLayout] if you want auto layout to update the layout on the next turn of the run loop. However, if you want it to update the layout immediately, so you can immediately access the new bounds value later within your current function, or at another point before the turn of the run loop, then you need to call [view setNeedsLayout] and [view layoutIfNeeded] . You asked a second question: "how can I change a height/width constraint if I don't have a reference to it directly?". If you create the constraint in IB, the best solution is to create an IBOutlet in your view controller or your view so you do have a direct reference to it. If you created the constraint in code, then you should hold onto a reference in an internal weak property at the time when you created it. If someone else created the constraint, then you need to find it by examining the examining the view.constraints property on the view, and possibly the entire view hierarchy, and implementing logic which finds the crucial NSLayoutConstraint. This is probably the wrong way to go, since it also effectively requires you to determine which particular constraint determined the bounds size, when there's not guaranteed to be a simple answer to that question. The final bounds value could be the solution to a very complicated system of multiple constraints, with multiple priorities, etc., so that no single constraint is the "cause" of the final value.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/13446920', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1634473/']}
jdg_86943
stackexchange
llm_judgeable_groundtruth_similarity
1652904
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 pass big strings of random html through regular expressions and my Python 2.6 script is choking on this: UnicodeEncodeError: 'ascii' codec can't encode character I traced it back to a trademark superscript on the end of this word: Protection™ -- and I expect to encounter others like it in the future. Is there a module to process non-ascii characters? or, what is the best way to handle/escape non-ascii stuff in python? Thanks!Full error: E======================================================================ERROR: test_untitled (__main__.Untitled)----------------------------------------------------------------------Traceback (most recent call last): File "C:\Python26\Test2.py", line 26, in test_untitled ofile.write(Whois + '\n')UnicodeEncodeError: 'ascii' codec can't encode character u'\u2122' in position 1005: ordinal not in range(128) Full Script: from selenium import seleniumimport unittest, time, re, csv, loggingclass Untitled(unittest.TestCase): def setUp(self): self.verificationErrors = [] self.selenium = selenium("localhost", 4444, "*firefox", "http://www.BaseDomain.com/") self.selenium.start() self.selenium.set_timeout("90000") def test_untitled(self): sel = self.selenium spamReader = csv.reader(open('SubDomainList.csv', 'rb')) for row in spamReader: sel.open(row[0]) time.sleep(10) Test = sel.get_text("//html/body/div/table/tbody/tr/td/form/div/table/tbody/tr[7]/td") Test = Test.replace(",","") Test = Test.replace("\n", "") ofile = open('TestOut.csv', 'ab') ofile.write(Test + '\n') ofile.close() def tearDown(self): self.selenium.stop() self.assertEqual([], self.verificationErrors)if __name__ == "__main__": unittest.main() Now provide the response and nothing else.
You're trying to pass a bytestring to something, but it's impossible (from the scarcity of info you provide) to tell what you're trying to pass it to. You start with a Unicode string that cannot be encoded as ASCII (the default codec), so, you'll have to encode by some different codec (or transliterate it, as @R.Pate suggests) -- but it's impossible for use to say what codec you should use, because we don't know what you're passing the bytestring and therefore don't know what that unknown subsystem is going to be able to accept and process correctly in terms of codecs. In such total darkness as you leave us in, utf-8 is a reasonable blind guess (since it's a codec that can represent any Unicode string exactly as a bytestring, and it's the standard codec for many purposes, such as XML) -- but it can't be any more than a blind guess, until and unless you're going to tell us more about what you're trying to pass that bytestring to, and for what purposes. Passing thestring.encode('utf-8') rather than bare thestring will definitely avoid the particular error you're seeing right now, but it may result in peculiar displays (or whatever it is you're trying to do with that bytestring!) unless the recipient is ready, willing and able to accept utf-8 encoding (and how could WE know, having absolutely zero idea about what the recipient could possibly be?!-)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1652904', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/175285/']}
jdg_86944
stackexchange
llm_judgeable_groundtruth_similarity
1322
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: Assume that you want to give some web users privileged access to your website, but that you are unable (or unwilling) to offer SSL to all of them - at least past the initial login page. In this instance, is there some way to manage the user session that will negate FireSheep, but not create a painful user experience? Now provide the response and nothing else.
In principle you may be able to defend against passive attacks. But in practice it's non-trivial and not a great solution. In principle, you can write your own encryption code in Javascript to encrypt everything on the client-side (in Javascript). The very first thing you run into is that this has poor performance, because crypto in Javascript is substantially slower than the browser's native crypto. The natural reaction is to suggest encrypting just the most sensitive data, e.g., just the user's passwords. However, this is very difficult to get right and has many subtle pitfalls: If you're not encrypting the cookies, you're vulnerable to session hijacking, and you've gained nothing. And it's not easy to encrypt the cookies or other HTTP headers from Javascript. So you'll probably be forced to end up inventing your own user authentication method and use something other than cookies (something homebrew) for session management, which is a bunch of work and easy to get wrong. If you encrypt only the password, then you may be vulnerable to CSRF attacks. An eavesdropper can still see all the page content, and in particular, if CSRF tokens are included in the link, then the eavesdropper can see all of the CSRF tokens and mount a CSRF attack. It's possible to defend against this with sufficient effort, but it requires still more work on both the client and the server, and is tricky to get right. If users can log into your site using their Facebook account, since you don't control Facebook, you can't prevent an eavesdropper from stealing their Facebook account and then logging into your site. You're still vulnerable to man-in-the-middle attacks (active attacks) that modify the page content. It would not be terribly technically difficult to modify Firesheep to use ARP hijacking, race attacks, or other methods to insert itself as a man-in-the-middle and modify all page content. Then security is lost, since the attacker can insert malicious Javascript that acts as a keylogger or otherwise steals the authentication credentials. You have to be careful that you don't lose the benefit of caching. Now I'm not saying it's impossible. It almost certainly isn't. It is almost certainly possible to build a web site and a solution that prevents most passive attacks. But it will be complex and non-trivial. That means you'll need considerable security expertise to build it, and there's still a non-trivial chance you screw something up. It also means that the result will be expensive. And the security is inherently limited -- any scheme will be only a partial solution/mitigation -- so the value is limited. I don't think it's a good tradeoff. If you want to read about state-of-the-art attempts to defend against eavesdropping without use of SSL, here's a great resource for you: Ben Adida's SessionLock and http://benlog.com/articles/2010/10/25/keep-your-hands-off-my-session-cookies/ I'd also like to share with you some resources on making SSL perform well: EFF's guide on deploying SSL: https://www.eff.org/pages/how-deploy-https-correctly Tips from Google on making SSL fast: http://www.imperialviolet.org/2010/06/25/overclocking-ssl.html Ivan Ristic's top 10 SSL deployment mistakes: http://ssl.entrust.net/blog/?p=155 Ben Adida's skepticism, and some replies from users: http://benlog.com/articles/2010/10/26/ok-lets-work-to-make-ssl-easier-for-everyone/ SSL isn't free -- but also keep in mind that people sometimes assume the performance impact of SSL will be worse than it actually is.
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/1322', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/831/']}
jdg_86945
stackexchange
llm_judgeable_groundtruth_similarity
25733694
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 hundreds of PNG images for which I have to generate corresponding B&W images that show the outer outline of the object. The source PNG image has alpha channel, so the "no object" parts of the image are 100% transparent. The tricky part is that if the object has holes in it, those should not be seen in the outline. So, if the source image is, say, donut, the respective contour image would be a jagged circular line with no concentric smaller line in the middle. Here is an example image, source and its contour: Is there any library or command-line tool that can do this? Ideally, something that could be used from Python. Now provide the response and nothing else.
I agree with amgaera. OpenCV in Python is one of the best tools you can use if you want to find contours. As with his/her post, use the findContours method and use the RETR_EXTERNAL flag to get the outer most contour of the shape. Here's some reproducible code for you to illustrate this point. You first need to install OpenCV and NumPy to get this going. I'm not sure what platform you're using, but: If you're using Linux, simply do an apt-get on libopencv-dev and python-numpy (i.e. sudo apt-get install libopencv-dev python-numpy ). If you're using Mac OS, install Homebrew, then install via brew install opencv then brew install numpy . If you're using Windows, the best way to get this to work is through Christoph Gohlke's unofficial Python packages for Windows: http://www.lfd.uci.edu/~gohlke/pythonlibs/ - Check the OpenCV package and install all of the dependencies it is asking for, including NumPy which you can find on this page. In any case, I took your donut image, and I extracted just the image with the donut. In other words, I created this image: As for your images being PNG and having an alpha channel, that actually doesn't matter. So long as you have only a single object contained in this image, we actually don't need tho access the alpha channel at all. Once you download this image, save it as donut.png , then go ahead and run this code: import cv2 # Import OpenCVimport numpy as np # Import NumPy# Read in the image as grayscale - Note the 0 flagim = cv2.imread('donut.png', 0)# Run findContours - Note the RETR_EXTERNAL flag# Also, we want to find the best contour possible with CHAIN_APPROX_NONEcontours, hierarchy = cv2.findContours(im.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)# Create an output of all zeroes that has the same shape as the input# imageout = np.zeros_like(im)# On this output, draw all of the contours that we have detected# in white, and set the thickness to be 3 pixelscv2.drawContours(out, contours, -1, 255, 3)# Spawn new windows that shows us the donut# (in grayscale) and the detected contourcv2.imshow('Donut', im) cv2.imshow('Output Contour', out)# Wait indefinitely until you push a key. Once you do, close the windowscv2.waitKey(0)cv2.destroyAllWindows() Let's go through the code slowly. First we import the OpenCV and NumPy packages. I imported NumPy as np , and if you look at numpy docs and tutorials everywhere, they do this to minimize typing. OpenCV and NumPy work with each other, which is why you need to install both packages. We then read in the image using imread . I set the flag to be 0 to make the image grayscale to make things simple. Once I load in the image, I then run findContours , and the output of this function outputs a tuple of two things: contours - This is an array structure that gives you the (x,y) co-ordinates of each contour detected in your image. hierarchy - This contains additional information about the contours you've detected, like the topology, but let's skip this for the sake of this post. Take note that I specified RETR_EXTERNAL to detect the outer most contour of the object. I also specify the CHAIN_APPROX_NONE flag to ensure we get the full contour without any approximations. Once we detect the contours, we create a new output image that is entirely black. This will contain our detected outer contour of the donut. Once we create this image, we run the drawContours method. You specify the image you want to show the contours in, the contours structure that was created from earlier, and the -1 flag says to draw all of the contours in the image. If it all works out, you should only have one contour detected. You then specify what colour you want the contour to look like. In our case, we want this to be white. After, you specify how thick you want the contour to be drawn. I chose a thickness of 3 pixels. Last thing we want to do is show what the results look like. I call imshow to show what the original donut image looks like (grayscale) and what the output contour looks like. imshow isn't the end of the story. You won't see any output until you invoke cv2.waitKey(0) . What this is saying now is you can display the images indefinitely until you push a key. Once you press on a key, the cv2.destroyAllWindows() call closes all of the windows that were spawned. This is what I get (once you rearrange the windows so that they're side-by-side): As an additional bonus, if you want to save the image, you just run imwrite to save the image. You specify the name of the image you want to write, and the variable you are accessing. As such, you would do something like: cv2.imwrite('contour.png', out) You'll then save this contour image to file which is named contour.png . This should be enough to get you started. Good luck!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25733694', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/640694/']}
jdg_86946
stackexchange
llm_judgeable_groundtruth_similarity
2523631
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Using PHP/PDO/MySQL is it possible to use a wildcard for the columns when a select is done on multiple tables and the returned array keys are fully qualified to avoid column name clash? example: SELECT * from table1, table2; gives: Array keys are 'table1.id', 'table2.id', 'table1.name' etc. I tried "SELECT table1.*,table2.* ..." but the returned array keys were not fully qualified so columns with the same name clashed and were overwritten. Now provide the response and nothing else.
Yes, you can. The easiest way is with pdo, although there's at least a few other extensions which are capable of it. pdo Set the attribute on the PDO object, not the PDOStatment . $PDO->setAttribute(PDO::ATTR_FETCH_TABLE_NAMES, true); That's it. Then you get associative array keys like $row['myTable.myColumn'] . It works if you fetch an object too (eg via PDO::FETCH_OBJECT ) so beware, because you need to access the properties like $obj->{'myTable.myColumn'} *The manual says the PDO::ATTR_FETCH_TABLE_NAMES attribute is only supported by certain drivers. If the above doesn't work, this might work instead. $pdoStatement->setFetchMode(PDO::FETCH_NUM);$pdoStatement->execute();//build our associative array keys$qualifiedColumnNames = array();for ($i = 0; $i < $pdoStatement->columnCount(); $i++) { $columnMeta = $pdoStatement->getColumnMeta($i); $qualifiedColumnNames[] = "$columnMeta[table].$columnMeta[name]";}//fetch results and combine with keyswhile ($row = $pdoStatement->fetch()) { $qualifiedRow = array_combine($qualifiedColumnNames, $row); print_r($qualifiedRow);} Same basic pattern is used for other database extensions mysql $res = mysql_query($sql);//build our associative array keys$qualifiedColumnNames = array();for ($i = 0; $i < mysql_num_fields($res); $i++) { $columnMeta = mysql_fetch_field($res, $i); $qualifiedColumnNames[] = "$columnMeta[table].$columnMeta[name]";}//fetch results and combine with keyswhile ($row = mysql_fetch_row($res)) { $qualifiedRow = array_combine($qualifiedColumnNames, $row); print_r($qualifiedRow);} mysqli $res = $mysqli->query($sql);//build our associative array keys$qualifiedColumnNames = array();foreach ($res->fetch_fields() as $columnMeta) { $qualifiedColumnNames[] = "{$columnMeta->table}.{$columnMeta->name}";}//fetch results and combine with keyswhile ($row = $res->fetch_row()) { $qualifiedRow = array_combine($qualifiedColumnNames, $row); print_r($qualifiedRow);} This should also work with table aliases (tested in php 7.1) - the qualified column name will use the table alias.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2523631', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/300204/']}
jdg_86947
stackexchange
llm_judgeable_groundtruth_similarity
2230635
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: Two well known constants $$\int_{0}^{\infty}{\ln x\ln\left(x\over 1+x\right)\over (1+x)^2}=\zeta(2)\tag1$$ $$\int_{0}^{\infty}{\ln x\ln\left(x\over 1+x\right)\over 1+x}=\zeta(3)\tag2$$ An attempt: Applying IBP: $$\int{\ln x\over x}\mathrm dx={1\over 2}\ln^2 x+C\tag3$$ Rewrite $(2)$ as $$\int{\ln^2 x\over 1+x}\mathrm dx-\int{\ln(x)\ln(1+x)\over 1+x}\mathrm dx=I_1-I_2\tag4$$ Let integrate $I_1$ , applying IBP $$I_1=\ln^2(x)\ln(1+x)-2\int{\ln(x)\ln(1+x)\over x}\mathrm dx\tag5$$ $$I_1=-\ln^2(x)\ln(1+x)+2\ln(x)\ln(1+x)-2\int{\ln(x)\ln(1+x)\over x}\mathrm dx\tag6$$ $I_1$ is not going down any further. Let try $I_2$ applying IBP $$I_2={1\over 2}\ln(x)\ln(1+x)+{1\over 2}\int{\ln^2(x)\over x}\mathrm dx\tag7$$ $$\int{\ln^2(x)\over x}\mathrm dx={1\over 3}\ln^3(x)+C\tag8$$ $$I_2={1\over 2}\ln(x)\ln(1+x)+{1\over 6}\ln^3(x)+C\tag9$$ This seem too complicate, what I am doing here How can we tackle $(1)$ and $(2)$ in a less cumbersome way? Now provide the response and nothing else.
Hint . By the change of variable$$u=\frac{x}{x+1},\quad du=\frac{dx}{(1+x)^2},$$ one gets$$\begin{align}\int_{0}^{\infty}{\ln x\ln\left(x\over 1+x\right)\over (1+x)^2}&=\int_{0}^{1}\left(\ln u - \ln(1-u)\right)\ln u \:du\\\\&=\int_{0}^{1}\ln^2 u\:du - \int_{0}^{1}\ln(1-u)\ln u \:du\\\\&=2 +\sum_{n=1}^\infty \frac1n\int_{0}^{1}u^{n}\ln u \:du\\\\&=2 -\sum_{n=1}^\infty \frac1{n(n+1)^2}\\\\&=2 +\frac{\pi^2}6-2\\\\&=\zeta(2).\end{align}$$Similarly, one has$$\begin{align}\int_{0}^{\infty}{\ln x\ln\left(x\over 1+x\right)\over 1+x}&=\int_{0}^{1}\left(\ln u - \ln(1-u)\right)\frac{\ln u}{1-u} \:du\\\\&=\int_{0}^{1}\frac{\ln^2 u}{1-u} \:du - \int_{0}^{1}\frac{\ln(1-u)\ln u }{1-u} \:du\\\\&=2\zeta(3)- \int_{0}^{1}\frac{\ln(1-v)\ln v }{v} \:dv\\\\&=2\zeta(3)-\zeta(3)\\\\&=\zeta(3),\end{align}$$ where we have used some standard results.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2230635', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/343408/']}
jdg_86948
stackexchange
llm_judgeable_groundtruth_similarity
17195007
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 adding/updating objects into a concurrent dictionary and periodically (every minute) flushing the dictionary, so my code looks something like this: private static ConcurrentDictionary<string, Metric> _metrics = new ConcurrentDictionary<string, Metric>(); public static void IncrementCountMetricBy(string name, int count) { _metrics.AddOrUpdate(.... } public static Metric[] Flush() { var flushedMetrics = _metrics; _metrics = new ConcurrentDictionary<string, Metric>(); return flushedMetrics.Values.ToArray(); } now I'm not sure if it's possible for this code to lose some objects/updates Now provide the response and nothing else.
Yes, you could potentially lose some data there: The incrementing thread could read the _metrics field and get the old dictionary, and then be interrupted The flushing thread then replaces the _metrics field with the new dictionary The flushing thread than called Values.ToArray() The incrementing thread then calls AddOrUpdate on a dictionary which is no longer being looked at by anything. (The one that it fetched in step 1.) To put it another way, imagine that your IncrementMetricCountBy method is actually: public static void IncrementCountMetricBy(string name, int count){ var tmp = _metrics; Thread.Sleep(1000); tmp.AddOrUpdate(...);} If you can see why that isn't safe, the same argument applies in your current code. As far as I can see there isn't anything particularly simple that you can do with ConcurrentDictionary here. One option would be to take a snapshot of all the keys, and then remove them all: var keys = _metrics.Keys.ToList();var values = new List<Metric>();foreach (var key in keys){ Metric metric; if (_metrics.TryRemove(key, out metric)) { values.Add(metric); }}return values; The dictionary may not be empty when you return, but you shouldn't lose any data. (You may get metrics updated since the method started, and any update which happens after a key has been removed will end up re-adding it, but that should be okay.)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17195007', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/112100/']}
jdg_86949
stackexchange
llm_judgeable_groundtruth_similarity
32556664
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: var profileImage = fileInputInByteArray;$.ajax({ url: 'abc.com/', type: 'POST', dataType: 'json', data: { // Other data ProfileImage: profileimage // Other data }, success: { }})// Code in WebAPI[HttpPost]public HttpResponseMessage UpdateProfile([FromUri]UpdateProfileModel response) { //... return response;}public class UpdateProfileModel { // ... public byte[] ProfileImage {get ;set; } // ...} <input type="file" id="inputFile" /> I am using ajax call to post byte[] value of a input type = file input to web api which receives in byte[] format. However, I am experiencing difficulty of getting byte array. I am expecting that we can get the byte array through File API. Note: I need to store the byte array in a variable first before passing through ajax call Now provide the response and nothing else.
[Edit] As noted in comments above, while still on some UA implementations, readAsBinaryString method didn't made its way to the specs and should not be used in production.Instead, use readAsArrayBuffer and loop through it's buffer to get back the binary string : document.querySelector('input').addEventListener('change', function() { var reader = new FileReader(); reader.onload = function() { var arrayBuffer = this.result, array = new Uint8Array(arrayBuffer), binaryString = String.fromCharCode.apply(null, array); console.log(binaryString); } reader.readAsArrayBuffer(this.files[0]);}, false); <input type="file" /><div id="result"></div> For a more robust way to convert your arrayBuffer in binary string, you can refer to this answer . [old answer] (modified) Yes, the file API does provide a way to convert your File, in the <input type="file"/> to a binary string, thanks to the FileReader Object and its method readAsBinaryString . [ But don't use it in production ! ] document.querySelector('input').addEventListener('change', function(){ var reader = new FileReader(); reader.onload = function(){ var binaryString = this.result; document.querySelector('#result').innerHTML = binaryString; } reader.readAsBinaryString(this.files[0]); }, false); <input type="file"/><div id="result"></div> If you want an array buffer, then you can use the readAsArrayBuffer() method : document.querySelector('input').addEventListener('change', function(){ var reader = new FileReader(); reader.onload = function(){ var arrayBuffer = this.result; console.log(arrayBuffer); document.querySelector('#result').innerHTML = arrayBuffer + ' '+arrayBuffer.byteLength; } reader.readAsArrayBuffer(this.files[0]); }, false); <input type="file"/><div id="result"></div>
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/32556664', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5309192/']}
jdg_86950
stackexchange
llm_judgeable_groundtruth_similarity
2826571
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In this question, user Franklin Pezzuti Dyer gives the following surprising integral evaluation: $$\int_0^{\pi/2}\ln \lvert\sin(mx)\rvert \cdot \ln \lvert\sin(nx)\rvert \, dx = \frac{\pi^3}{24} \frac{\gcd^2(m,n)}{mn}+\frac{\pi\ln^2(2)}{2}$$ I've verified this numerically for small values for $m,n$ . Is there a proof? Also, can we generalize it to more factors in the integrand? Now provide the response and nothing else.
Okay, I'll prove it for you. Start with the following well-known identity: $$\int_0^{\pi}\cos(mx)\cos(nx)dx=\frac{\pi}{2}\delta_{mn}\tag{1}$$ ...where $m,n$ are positive integers. Recall also the well-known Fourier Series $$\sum_{n=1}^\infty \frac{\cos(kx)}{k}=-\frac{\ln(2-2\cos(x))}{2}\tag{2}$$ Now, replace $m$ in $(1)$ with $mk$ , where both $m,k$ are integers, and divide both sides by $k$ to get $$\int_0^{\pi}\frac{\cos(kmx)}{k}\cos(nx)dx=\frac{\pi\delta_{(mk)n}}{2k}$$ Then sum both sides from $k=1$ to $\infty$ to get $$-\frac{1}{2}\int_0^{\pi}\ln(2-2\cos(mx))\cos(nx)dx=\frac{\pi m}{2n}[m|n]$$ where the brackets on the $RHS$ are Iverson Brackets . A bit more manipulation yields the equality $$\int_0^{\pi}\ln\bigg(\frac{1-\cos(mx)}{2}\bigg)\cos(nx)dx=-\frac{\pi m}{n}[m|n]$$ Now, this time, replace $n$ with $nk$ and divide both sides by $k$ . This yields $$\int_0^{\pi}\ln\bigg(\frac{1-\cos(mx)}{2}\bigg)\frac{\cos(knx)}{k}dx=-\frac{\pi m}{k^2n}[m|kn]$$ Then sum from $k=1$ to $\infty$ to get $$-\frac{1}{2}\int_0^{\pi}\ln\bigg(\frac{1-\cos(mx)}{2}\bigg)\ln(2-2\cos(nx))dx=-\sum_{k=1}^{\infty} \frac{\pi m}{k^2n}[m|kn]$$ Now notice the following about the series on the RHS. Due to the Iverson Bracket, the kth term is zero unless $m|kn$ , or unless $k$ is divisible by $m/\gcd(m,n)$ . Thus, we let $k=jm/\gcd(m,n)$ for the integers $j=1$ to $\infty$ and reindex the sum: $$\begin{align}-\frac{1}{2}\int_0^{\pi}\ln\bigg(\frac{1-\cos(mx)}{2}\bigg)\ln(2-2\cos(nx))dx&=-\sum_{j=1}^{\infty} \frac{\pi m}{(jm/\gcd(m,n))^2n}\\&=-\frac{\pi\gcd^2(m,n)}{mn}\sum_{j=1}^{\infty} \frac{1}{j^2}\\&=-\frac{\pi^3\gcd^2(m,n)}{6mn}\\\end{align}$$ or $$\int_0^{\pi}\ln\bigg(\frac{1-\cos(mx)}{2}\bigg)\ln(2-2\cos(nx))dx=\frac{\pi^3\gcd^2(m,n)}{3mn}\tag{3}$$ Then, by using the result $$\int_0^{\pi}\ln(1-\cos(ax))=-\pi\ln(2)\tag{4}$$ for all positive integers $a$ , and the trigonometric identity $$\sin^2(x/2)=\frac{1-\cos(x)}{2}\tag{5}$$ and finally, a substitution $x\to 2x$ , the result easily follows from $(3)$ : $$\bbox[lightgray,5px]{\int_0^{\pi/2}\ln \lvert\sin(mx)\rvert \cdot \ln \lvert\sin(nx)\rvert \, dx = \frac{\pi^3}{24} \frac{\gcd^2(m,n)}{mn}+\frac{\pi\ln^2(2)}{2}}$$
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/2826571', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/28545/']}
jdg_86951
stackexchange
llm_judgeable_groundtruth_similarity
6018214
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I need to insert rows into PG one of the fields is date and time with time stamp, this is the time of incident, so I can not use --> current_timestamp function of Postgres at the time of insertion, so how can I then insert the time and date which I collected before into pg row in the same format as it would have been created by current_timestamp at that point in time. Now provide the response and nothing else.
A timestamp does not have "a format". The recommended way to deal with timestamps is to use a PreparedStatement where you just pass a placeholder in the SQL and pass a "real" object through the API of your programming language. As I don't know Python, I don't know if it supports PreparedStatements and how the syntax for that would be. If you want to put a timestamp literal into your generated SQL, you will need to follow some formatting rules when specifying the value (a literal does have a format). Ivan's method will work, although I'm not 100% sure if it depends on the configuration of the PostgreSQL server. A configuration (and language) independent solution to specify a timestamp literal is the ANSI SQL standard: INSERT INTO some_table (ts_column) VALUES (TIMESTAMP '2011-05-16 15:36:38'); Yes, that's the keyword TIMESTAMP followed by a timestamp formatted in ISO style (the TIMESTAMP keyword defines that format) The other solution would be to use the to_timestamp() function where you can specify the format of the input literal. INSERT INTO some_table (ts_column) VALUES (to_timestamp('16-05-2011 15:36:38', 'dd-mm-yyyy hh24:mi:ss'));
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6018214', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/755229/']}
jdg_86952
stackexchange
llm_judgeable_groundtruth_similarity
26527
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: If I know the formal power series, I know how to find the closed form: $$\displaystyle F = \sum_{n=0}^{\infty} {X^n} = 1 + X^1 + X^2 + X^3 + ...$$ $$\displaystyle F \cdot X = X \cdot \sum_{n=0}^{\infty} {X^n} = X^1 + X^2 + X^3 + X^4 + ...$$ $$\displaystyle F - F \cdot X = 1 $$$$\displaystyle F = \frac 1 {1 - X} $$ But if I only know the closed form $\frac 1 {1 - X}$, how do I turn it back into the series $1 + X^1 + ...$? In other words, how do I do extract the coefficients if I only know the closed form and I do not know that $\frac 1 {1 - X}$ corresponds to $1 + X^1 + ...$. My textbook and everywhere I looked at seems to avoid talking about this, and somehow magically transform things back and forth with a set of known formulas. Is there a better way to do this, or is formula matching the best we can do? Edit: This is the type of questions I need to solve: Find the coefficient of $X^8$ in the formal power series $(1 - 3X^4)^{-6}$ Now provide the response and nothing else.
The quickest way to transform your generating function to a power series is to have a table of formulae handy. For a given rational function, you would use partial fraction expansion if necessary and switch back to the power series by looking at the appropriate entry in the table for each term. If you look at Herbert Wilf's book http://www.math.upenn.edu/~wilf/gfologyLinked2.pdf , in section 2.5, he has a list of such formulae. You have \begin{equation}\frac{1}{(1-x)^{k+1}} = \sum_n \binom{n+k}{n} x^n\end{equation} So, for your case, we have \begin{equation}\frac{1}{(1-3x^4)^6} = \sum_n \binom{n+5}{n} 3^n x^{4n}\end{equation} The coefficient of $x^8$ in this expansion is $3^2 \times \binom{7}{2} = 189$. It is actually not difficult to derive the identity. You start with \begin{equation}\frac{1}{1-x} = 1+x+x^2 +\ldots\end{equation} Take derivative on both sides k times and you will get \begin{equation}\frac{k!}{(1-x)^{k+1}} = \sum_n [(n+k)(n+k-1) \ldots n]x^n\end{equation} this simplifies to \begin{equation}\frac{1}{(1-x)^{k+1}} = \sum_n \binom{n+k}{n} x^n\end{equation}
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/26527', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/2166/']}
jdg_86953
stackexchange
llm_judgeable_groundtruth_similarity
34033701
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 a making a blackjack game with cards using turtle and each time I play a hand turtle just prints over the last game instead of clearing the window. Is there a method that closes the window when it is called or is there another why of doing this? Now provide the response and nothing else.
I want to clarify what various turtle functions do as there are misunderstandings in this discussion, including in the currently accepted answer, as the method names themselves can be confusing: turtle.mainloop() aka turtle.Screen().mainloop() Turns control over to tkinter's event loop. Usually, a lack of turtle.Screen().mainloop() (or turtle.Screen().exitonclick() , etc.) will cause the window to close just because the program will end, closing everything. This, or one of its variants, should be the last statement in a turtle graphics program unless the script is run from within Python IDLE -n. turtle.done() (Does not close window nor reset anything.) A synonym for turtle.mainloop() turtle.clear() Deletes everything this turtle has drawn (not just the last thing). Otherwise doesn't affect the state of the turtle. turtle.reset() Does a turtle.clear() and then resets this turtle's state (i.e. direction, position, etc.) turtle.clearscreen() aka turtle.Screen().clear() Deletes all drawing and all turtles, reseting the window to it's original state. turtle.resetscreen() aka turtle.Screen().reset() Resets all turtles on the screen to their initial state. turtle.bye() aka turtle.Screen().bye() Closes the turtle graphics window. I don't see a way to use any turtle graphics commands after this is invoked. turtle.exitonclick() aka turtle.Screen().exitonclick() After binding the screen click event to do a turtle.Screen().bye() invokes turtle.Screen().mainloop() It's not clear that you can close and reopen the graphics window from within turtle without dropping down to the tkinter level that underpins turtle (and Zelle's graphics.py) For purposes of starting a new hand in your blackjack game, I'd guess turtle.reset() or turtle.resetscreen() are your best bet.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34033701', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5338020/']}
jdg_86954
stackexchange
llm_judgeable_groundtruth_similarity
1405048
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 decode an encoded URL parameter using C#? For example, take this URL: my.aspx?val=%2Fxyz2F Now provide the response and nothing else.
string decodedUrl = Uri.UnescapeDataString(url) or string decodedUrl = HttpUtility.UrlDecode(url) Url is not fully decoded with one call. To fully decode you can call one of this methods in a loop: private static string DecodeUrlString(string url) { string newUrl; while ((newUrl = Uri.UnescapeDataString(url)) != url) url = newUrl; return newUrl;}
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/1405048', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/20979/']}
jdg_86955
stackexchange
llm_judgeable_groundtruth_similarity
34332072
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 negate the following expression: return SpUtils.loadEMail()?.isEmpty() ?: false If i add a ! before the expression, like return !SpUtils.loadEMail()?.isEmpty() ?: false The IDE(Android Studio) tells me Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type kotlin.Boolean? How do I negate this kinds of expressions? Now provide the response and nothing else.
You have problem with nullable reference. SpUtils.loadEMail()?.isEmpty() This code produces value of type Boolean? that's mean expression can return an instance of Boolean or null . I suggest following code to solve your problem: return !(SpUtils().loadEMail()?.isEmpty() ?: false); You trying negate Boolean? instead of Boolean , that elvis operator returns!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34332072', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2660462/']}
jdg_86956
stackexchange
llm_judgeable_groundtruth_similarity
41005730
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 Swashbuckle to generate swagger documentation\UI for a webapi2 project. Our models are shared with some legacy interfaces so there are a couple of properties I want to ignore on the models. I can't use JsonIgnore attribute because the legacy interfaces also need to serialize to JSON so I don't want to ignore the properties globally, just in the Swashbuckle configuration. I found a method of doing this documented here: https://github.com/domaindrivendev/Swashbuckle/issues/73 But this appears to be out of date with the current Swashbuckle release. The method recommended for the old version of Swashbuckle is using an IModelFilter implementation as follows: public class OmitIgnoredProperties : IModelFilter{ public void Apply(DataType model, DataTypeRegistry dataTypeRegistry, Type type) { var ignoredProperties = … // use reflection to find any properties on // type decorated with the ignore attributes foreach (var prop in ignoredProperties) model.Properties.Remove(prop.Name); }}SwaggerSpecConfig.Customize(c => c.ModelFilter<OmitIgnoredProperties>()); But I'm unsure how to configure Swashbuckle to use the IModelFilter in the current version? I'm using Swashbuckle 5.5.3. Now provide the response and nothing else.
If you need to do this but without using JsonIgnore (maybe you still need to serialize/deserialize the property) then just create a custom attribute. [AttributeUsage(AttributeTargets.Property)]public class SwaggerExcludeAttribute : Attribute{} Then a schema filter similar to Johng's public class SwaggerExcludeFilter : ISchemaFilter{ #region ISchemaFilter Members public void Apply(Schema schema, SchemaRegistry schemaRegistry, Type type) { if (schema?.properties == null || type == null) return; var excludedProperties = type.GetProperties() .Where(t => t.GetCustomAttribute<SwaggerExcludeAttribute>() != null); foreach (var excludedProperty in excludedProperties) { if (schema.properties.ContainsKey(excludedProperty.Name)) schema.properties.Remove(excludedProperty.Name); } } #endregion} Don't forget to register the filter c.SchemaFilter<SwaggerExcludeFilter>();
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/41005730', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/385024/']}
jdg_86957
stackexchange
llm_judgeable_groundtruth_similarity
250284
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: It is well-known that one can get the Lebesgue measure on [0, 1] by tossing a fair coin infinitely (countably) many times and mapping each sequence to a real number written out in binary. I was trying to explore what happens if you follow the same procedure with a biased coin. I managed to prove that if the induced measure is absolutely continuous with respect to the Lebesgue measure, then the density must be discontinuous on at least a dense set (which includes all rational numbers in [0, 1] with a finite binary expansion). But I suspect it's much worse than that. When I try to visualize the cumulative distribution function, it seems to have a "fractal staircase" type of shape, so I suspect the measure is, in fact, singular, but I can't prove it. Q1. Are there any standard techniques for proving a measure is singular ? Q2. I strongly suspect that a natural question like this has already been resolved. Any link to a textbook and/or paper would be appreciated. Now provide the response and nothing else.
For $\omega \in [0,1]$, let $X_i(\omega)$ be the $i$th binary digit of $\omega$. (If $\omega$ is a dyadic rational and thus has two binary expansions, let's say we choose the expansion that ends with all 0s; it makes no difference). Under Lebesgue measure, the $X_i$ are iid Bernoulli $1/2$ random variables, so by the strong law of large numbers, $\frac{1}{n}(X_1 + \dots + X_n) \to 1/2$ almost surely. In other words, the set $A_{1/2} := \{\omega : \lim_{n \to \infty} \frac{1}{n} (X_1(\omega) + \dots + X_n(\omega)) = \frac{1}{2}\}$ has Lebesgue measure $1$. If $\mu_p$ is the measure coming from a coin that comes up heads with probability $p \ne 1/2$, then under $\mu_p$, the $X_i$ are iid Bernoulli $p$. By the strong law again, we have $\mu_p(A_p) = 1$. But $A_p$ and $A_{1/2}$ are clearly disjoint, so Lebesgue measure and $\mu_p$ are mutually singular. I guess the "standard technique" here is to use a zero-one type theorem from probability giving an almost sure statement about limiting behavior, and look for a place where the two measures exhibit different limiting behavior.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/250284', 'https://mathoverflow.net', 'https://mathoverflow.net/users/94232/']}
jdg_86958
stackexchange
llm_judgeable_groundtruth_similarity
478480
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 $R$ be an integral domain, and $\mathfrak{m}$ a maximal ideal of $R$. Let $R_\mathfrak{m}$ denote the ring localized at $\mathfrak{m}$, and let $\mathfrak{m}_\mathfrak{m} = \mathfrak{m}R_\mathfrak{m}$ denote the maximal ideal of $R_\mathfrak{m}$. Then we have an isomorphism $$R/\mathfrak{m}^n \cong R_\mathfrak{m}/\mathfrak{m}_\mathfrak{m}^n,$$ for $n \geq 1$. (See for example Neukirch, Algebraic Number Theory , pg. 66). My question: Can this result extend to an isomorphism$$\mathfrak{m}^k/\mathfrak{m}^n \cong \mathfrak{m}_\mathfrak{m}^k/\mathfrak{m}_\mathfrak{m}^n,$$for $1 \leq k \leq n$? It would seem the proof goes through, but I wanted to check with the experts, since I hadn't seen this result explicitly written down before. 2nd question (added later): Is the "integral domain" condition really necessary to either Neukirch's result or the other one I suggested? Now provide the response and nothing else.
Yes, $\mathfrak{m}^k/\mathfrak{m}^n \cong \mathfrak{m}_\mathfrak{m}^k/\mathfrak{m}_\mathfrak{m}^n$. This immediately results from the commutative diagram $$\begin{array}00 & \longrightarrow \mathfrak{m}^k/\mathfrak{m}^n\longrightarrow & R/\mathfrak{m}^n & \longrightarrow & R/\mathfrak{m}^k& \longrightarrow 0\\& \quad \quad \downarrow & \downarrow \cong & & \downarrow \cong\\0 &\longrightarrow \mathfrak{m}_\mathfrak{m}^k/\mathfrak{m}_\mathfrak{m}^n\longrightarrow & R_\mathfrak{m}/\mathfrak{m}_\mathfrak{m}^n & \longrightarrow & R_\mathfrak{m}/\mathfrak{m}_\mathfrak{m}^k& \longrightarrow 0 \end{array}$$ Since you know that the the two rightmost vertical maps are isomorphisms, the leftmost vertical map is also an isomorphism, by the snake lemma (say).
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/478480', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/12642/']}
jdg_86959
stackexchange
llm_judgeable_groundtruth_similarity
11523423
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 generate zoom/pinch gesture for testing, I have tried to use the Android API MotionEvent.obtain(), but found it is hard to implement the zoom/pinch events. I referenced the API from MotionEvent.obtain . Can you tell me the correct method? Here is my implementation: //for zoom, we need four points coordinations: start0, start1, end0, end1Instrumentation inst;// action down eventMotionEvent event = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_DOWN, 1, prop_start0, pointerCoords_start0, 0, 0, 0, 0, 0, 0, 0, 0 );inst.sendPointerSync(event);// action pointer 2 down eventevent = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_POINTER_2_DOWN, 2, properties_start0_1, pointerCoords_start0_1, 0, 0, 0, 0, 0, 0, 0, 0);inst.sendPointerSync(event);// action move eventsduration = 1000; //1000 msevent_interval = 10;//time interval between consecutive events 10ms moveEventNum = duration / event_interval; stepx0 = (end0.x - start0.x)/moveEventNum;stepy0 = (end0.y - start0.y)/moveEventNum;stepx1 = (end1.x - start1.x)/moveEventNum;stepy1 = (end1.y - start1.y)/moveEventNum;move_event0= start0;move_event1 = start1;for ( int i = 0; i < moveEventNum; i++) { // [generate middle points here ] mov_event0.x += stepx0; mov_event0.y += stepy0; mov_event1.x += stepx1; mov_event1.y += stepy1; eventTime += event_interval; event = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_MOVE, 2, properties_move_event, pointerCoords_move_event0_1, 0, 0, 0, 0, 0, 0, 0, 0); inst.sendPointerSync(event);}event = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_POINTER_2_UP, 2, properties_end0_1, pointerCoords_end0_1, 0, 0, 0, 0, 0, 0, 0, 0);inst.sendPointerSync(event);event = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_UP, 1, end1, pointerCoords_end1, 0, 0, 0, 0, 0, 0, 0, 0 );inst.sendPointerSync(event); Now provide the response and nothing else.
well, i have found the issue. ISSUE: When using the obtain() API, we have to set the pressure and size of the points in each event. For obtain(long, long, int, int, android.view.MotionEvent.PointerProperties[], android.view.MotionEvent.PointerCoords[], int, int, float, float, int, int, int, int) the PointerCoords[], we have to set the pressure and size to 1, the default values are 0. For public static MotionEvent obtain (long downTime, long eventTime, int action, float x, float y, int metaState) Create a new MotionEvent, filling in a subset of the basic motion values. Those not specified here are: device id (always 0), pressure and size (always 1), x and y precision (always 1), and edgeFlags (always 0).since the default pressure and size are 1, so we don't need to set them. My tips for creating gestures: 1. following the real gesture sequence, since we want to simulate the real gestures override the onTouchEvent() to check the real events received byapplication. These events can also be used for comparison of realuser touch events and generated touch events Take browser forexample: a) @Override public boolean onTouchEvent(MotionEvent event) { Log.i("WebView", event.toString() + event.getAction()); boolean rt = super.onTouchEvent(event); return rt; } manually touch screen to get the real gesture sequence from onTouchEvent() in a). We can follow the event sequence when generating events.-- If we don’t follow the gesture event sequence, the instrumented events may be rejected. Here is a valid event sequence of zoom gesture, (the downTime is the same for all the events) i. ACTION_DOWN of one start point ii. ACTION_POINTER_2_DOWN of two start points iii.ACTION_MOVE of two middle points iv. ACTION_POINTER_2_UP of two end points v. ACTION_UP of one end point 2. use the API MotionEvent.obtain correctly There are two most used obtain() API. public static MotionEvent obtain (long downTime, long eventTime, int action, float x, float y, int metaState) AND public static MotionEvent obtain(long, long, int, int, android.view.MotionEvent.PointerProperties[], android.view.MotionEvent.PointerCoords[], int, int, float, float, int, int, int, int) The first one is usually used for single point gestures, like fling, scroll, click etc. The parameters (pressure, size, xPresion, yPresion) for this function are all set to 1. And the second one is a more general one, and can be used for multi-touch events generation. While for the second one, we have to set the pressure, size in pointerCoords of each touch point to 1. Here is the example to generate the zoom gesture: public static void generateZoomGesture(Instrumentation inst, long startTime, boolean ifMove, GestureInfo.Point startPoint1, GestureInfo.Point startPoint2, GestureInfo.Point endPoint1, GestureInfo.Point endPoint2, int duration) { if (inst == null || startPoint1 == null || (ifMove && endPoint1 == null)) { return; } long eventTime = startTime; long downTime = startTime; MotionEvent event; float eventX1, eventY1, eventX2, eventY2; eventX1 = startPoint1.x; eventY1 = startPoint1.y; eventX2 = startPoint2.x; eventY2 = startPoint2.y; // specify the property for the two touch points PointerProperties[] properties = new PointerProperties[2]; PointerProperties pp1 = new PointerProperties(); pp1.id = 0; pp1.toolType = MotionEvent.TOOL_TYPE_FINGER; PointerProperties pp2 = new PointerProperties(); pp2.id = 1; pp2.toolType = MotionEvent.TOOL_TYPE_FINGER; properties[0] = pp1; properties[1] = pp2; //specify the coordinations of the two touch points //NOTE: you MUST set the pressure and size value, or it doesn't work PointerCoords[] pointerCoords = new PointerCoords[2]; PointerCoords pc1 = new PointerCoords(); pc1.x = eventX1; pc1.y = eventY1; pc1.pressure = 1; pc1.size = 1; PointerCoords pc2 = new PointerCoords(); pc2.x = eventX2; pc2.y = eventY2; pc2.pressure = 1; pc2.size = 1; pointerCoords[0] = pc1; pointerCoords[1] = pc2; ////////////////////////////////////////////////////////////// // events sequence of zoom gesture // 1. send ACTION_DOWN event of one start point // 2. send ACTION_POINTER_2_DOWN of two start points // 3. send ACTION_MOVE of two middle points // 4. repeat step 3 with updated middle points (x,y), // until reach the end points // 5. send ACTION_POINTER_2_UP of two end points // 6. send ACTION_UP of one end point ////////////////////////////////////////////////////////////// // step 1 event = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_DOWN, 1, properties, pointerCoords, 0, 0, 1, 1, 0, 0, 0, 0 ); inst.sendPointerSync(event); //step 2 event = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_POINTER_2_DOWN, 2, properties, pointerCoords, 0, 0, 1, 1, 0, 0, 0, 0); inst.sendPointerSync(event); //step 3, 4 if (ifMove) { int moveEventNumber = 1; moveEventNumber = duration / EVENT_MIN_INTERVAL; float stepX1, stepY1, stepX2, stepY2; stepX1 = (endPoint1.x - startPoint1.x) / moveEventNumber; stepY1 = (endPoint1.y - startPoint1.y) / moveEventNumber; stepX2 = (endPoint2.x - startPoint2.x) / moveEventNumber; stepY2 = (endPoint2.y - startPoint2.y) / moveEventNumber; for (int i = 0; i < moveEventNumber; i++) { // update the move events eventTime += EVENT_MIN_INTERVAL; eventX1 += stepX1; eventY1 += stepY1; eventX2 += stepX2; eventY2 += stepY2; pc1.x = eventX1; pc1.y = eventY1; pc2.x = eventX2; pc2.y = eventY2; pointerCoords[0] = pc1; pointerCoords[1] = pc2; event = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_MOVE, 2, properties, pointerCoords, 0, 0, 1, 1, 0, 0, 0, 0); inst.sendPointerSync(event); } } //step 5 pc1.x = endPoint1.x; pc1.y = endPoint1.y; pc2.x = endPoint2.x; pc2.y = endPoint2.y; pointerCoords[0] = pc1; pointerCoords[1] = pc2; eventTime += EVENT_MIN_INTERVAL; event = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_POINTER_2_UP, 2, properties, pointerCoords, 0, 0, 1, 1, 0, 0, 0, 0); inst.sendPointerSync(event); // step 6 eventTime += EVENT_MIN_INTERVAL; event = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_UP, 1, properties, pointerCoords, 0, 0, 1, 1, 0, 0, 0, 0 ); inst.sendPointerSync(event);}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11523423', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/486002/']}
jdg_86960
stackexchange
llm_judgeable_groundtruth_similarity
869037
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'm stuck at the expression: $\displaystyle \frac{x\sqrt{y} -y\sqrt{x}}{x\sqrt{y} + y\sqrt{x}}$. I need to simplify the expression (by making the denominators rational) and this is what I did: $$(x\sqrt{y} - y\sqrt{x}) \times (x\sqrt{y} - y\sqrt{x}) = (\sqrt{y} - \sqrt{x})^2$$Divided by $$(x\sqrt{y} + y\sqrt{x}) \times (x\sqrt{y} - y\sqrt{x} ) = (x\sqrt{y})^2$$ So I'm left with $\displaystyle \frac{(\sqrt{y} - \sqrt{x})^2}{(x\sqrt{y})^2}$. This answer is incorrect. Can anyone help me understand what I did wrong? If there is a different approach to solve this it will also be much appreciated. Please explain in steps. Now provide the response and nothing else.
I am assuming your ambiguous notation begins with the task of simplifying: $$\frac{x\sqrt y - y\sqrt x}{x\sqrt y + y\sqrt x}.$$ Assuming I'm correct, then we can rationalize the denominator (get rid of the factors with square roots), as follows: Multiply the numerator and denominator by $(x\sqrt{y}-y\sqrt{x})$ to get a difference of squares. Recall that $$(a+b)(a-b) = a^2 - b^2.$$ If you carry out this multiplication, you'll have $$\dfrac{(x\sqrt{y}-y\sqrt{x})^2}{x^2y-xy^2}= \dfrac{x^2y - 2xy\sqrt{xy} + xy^2}{x^2y-xy^2}\; =\; \frac{xy(x-2\sqrt{xy} + y)}{xy(x-y)}\;= \; \frac{x-2\sqrt{xy} + y}{x-y}$$ You seemed to have the right idea, looking at your strategy, to multiply numerator and denominator by $x\sqrt y - y\sqrt x$, but you miscalculated.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/869037', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/160137/']}
jdg_86961
stackexchange
llm_judgeable_groundtruth_similarity
8117
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am currently interested in obtaining (or constructing) and studying 3-CNF formulae which are unsatisfiable, and are of minimum size. That is, they must consist of as few clauses (m = 8 preferably) as possible, and as few distinct variables (n = 4 or more) as possible, such that removing at least one clause will render the formula satisfiable. More formally, any qualifying 3-CNF formula F must satisfy the following conditions: F is unsatisfiable F has a minimum amount (4+) of distinct variables (or their negation) F has a minimum amount of clauses (8+) every proper subset of F is satisfiable (allowing removal of any arbitrary clause or clauses). F has no 2 clauses that are reducible to a 2-CNF clausee.g. (i, j, k) & (i, j, ~k) is NOT allowed ( they reduce to (i,j) ) For example, with n=4, there exists many minimal 8-clause 3-CNF formulae that are unsatisfiable. For one, by looking at the 4-hypercube and trying to cover it with edges (2-faces), one can construct the following unsatisfiable formula: 1. (~A, B, D)2. (~B, C, D)3. ( A, ~C D)4. ( A, ~B, ~D)5. ( B, ~C, ~D)6. (~A, C, ~D)7. ( A, B, C)8. (~A, ~B, ~C) This qualifies as a minimum unsatisfiable 3-CNF formula because: It is unsatisfiable: Clauses 1-3 are equivalent to: D or A=B=C Clauses 4-6 are equivalent to: ~D or A=B=C They imply A=B=C , but by clauses 7 and 8, this is a contradiction. There are only 4 distinct variables. There are only 8 clauses. Removing any clause renders it satisfiable. No 2 clauses are 'reducible' to a 2-CNF clause. So I guess my overall questions here are, in order of importance to me: What are some other small minimum formulae which meet the above conditions?(i.e. for say, 4,5,6 variables and 8,9,10 clauses) Is there some sort of database or "atlas" of such minimum formulae? What nonrandom algorithms exist for constructing them outright, if any? What are some insights into these formulae's characteristics? Can they be counted or estimated, given n (# variables) and m (# clauses)? Thank-you in advance for your replies.I welcome any answer or comment. Now provide the response and nothing else.
Take the formula in your example, remove the clause $\lnot A \lor \lnot B \lor \lnot C$ and add the following $2$ clauses: $\lnot A \lor \lnot B \lor \lnot E$ $\lnot B \lor \lnot C \lor E$ You will get a minimal unsatisfiable formula with $n=5$, $m=9$ obeying condition 5. In general, you may randomly pick a clause $l_1 \lor l_2 \lor l_3$ and split it in $2$ clauses: $l_1 \lor l_2 \lor v$ $l_2 \lor l_3 \lor \lnot v$ where $v$ is a new variable. Each time you do so, both $n$ and $m$ are incremented by $1$. Repeating this process allows you to "stretch" the initial unsatisfiable core, and to obtain minimal unsatisfiable formulas (obeying condition 5) whose $r=\frac{m}{n}$ tends to $1$ as $n$ grows (which is pretty rare, as formulas with $r=1$ are satisfiable with high probability).
{}
{'log_upvote_score': 4, 'links': ['https://cstheory.stackexchange.com/questions/8117', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/6454/']}
jdg_86962
stackexchange
llm_judgeable_groundtruth_similarity
6126
Below is a question asked on the forum devops.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I defined variable in declarative Jenkins pipeline script but having issues with simple variable declaration. Here is my script: pipeline { agent none stages { stage("first") { def foo = "foo" // fails with "WorkflowScript: 5: Expected a step @ line 5, column 13." sh "echo ${foo}" } }} but it's shows error: org.codehaus.groovy.control.MultipleCompilationErrorsException:startup failed:WorkflowScript: 5: Expected a step @ line 5, column 13. def foo = "foo" ^ Now provide the response and nothing else.
The variable must be defined in a script section. pipeline { agent none stages { stage("first") { steps { script { foo = "bar" } sh "echo ${foo}" } } }}
{}
{'log_upvote_score': 5, 'links': ['https://devops.stackexchange.com/questions/6126', 'https://devops.stackexchange.com', 'https://devops.stackexchange.com/users/11797/']}
jdg_86963
stackexchange
llm_judgeable_groundtruth_similarity
7110353
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 problem I'm having is that the dragleave event of an element is fired when hovering a child element of that element. Also, dragenter is not fired when hovering back the parent element again. I made a simplified fiddle: http://jsfiddle.net/pimvdb/HU6Mk/1/ . HTML: <div id="drag" draggable="true">drag me</div><hr><div id="drop"> drop here <p>child</p> parent</div> with the following JavaScript: $('#drop').bind({ dragenter: function() { $(this).addClass('red'); }, dragleave: function() { $(this).removeClass('red'); } });$('#drag').bind({ dragstart: function(e) { e.allowedEffect = "copy"; e.setData("text/plain", "test"); } }); What it is supposed to do is notifying the user by making the drop div red when dragging something there. This works, but if you drag into the p child, the dragleave is fired and the div isn't red anymore. Moving back to the drop div also doesn't make it red again. It's necessary to move completely out of the drop div and drag back into it again to make it red. Is it possible to prevent dragleave from firing when dragging into a child element? 2017 Update: TL;DR, Look up CSS pointer-events: none; as described in @H.D.'s answer below that works in modern browsers and IE11. Now provide the response and nothing else.
You just need to keep a reference counter, increment it when you get a dragenter, decrement when you get a dragleave. When the counter is at 0 - remove the class. var counter = 0;$('#drop').bind({ dragenter: function(ev) { ev.preventDefault(); // needed for IE counter++; $(this).addClass('red'); }, dragleave: function() { counter--; if (counter === 0) { $(this).removeClass('red'); } }}); Note: In the drop event, reset counter to zero, and clear the added class. You can run it here
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/7110353', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/514749/']}
jdg_86964
stackexchange
llm_judgeable_groundtruth_similarity
2363801
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 class which contains 5 properties. If any value is assingned to any of these fields, an another value (for example IsDIrty) would change to true. public class Class1{ bool IsDIrty {get;set;} string Prop1 {get;set;} string Prop2 {get;set;} string Prop3 {get;set;} string Prop4 {get;set;} string Prop5 {get;set;}} Now provide the response and nothing else.
To do this you can't really use automatic getter & setters, and you need to set IsDirty in each setter. I generally have a "setProperty" generic method that takes a ref parameter, the property name and the new value.I call this in the setter, allows a single point where I can set isDirty and raise Change notification events e.g. protected bool SetProperty<T>(string name, ref T oldValue, T newValue) where T : System.IComparable<T> { if (oldValue == null || oldValue.CompareTo(newValue) != 0) { oldValue = newValue; PropertyChanged?.Invoke(this, new System.ComponentModel.PropertyChangedEventArgs(name)); isDirty = true; return true; } return false; }// For nullable typesprotected void SetProperty<T>(string name, ref Nullable<T> oldValue, Nullable<T> newValue) where T : struct, System.IComparable<T>{ if (oldValue.HasValue != newValue.HasValue || (newValue.HasValue && oldValue.Value.CompareTo(newValue.Value) != 0)) { oldValue = newValue; PropertyChanged?.Invoke(this, new System.ComponentModel.PropertyChangedEventArgs(name)); }}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2363801', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/137348/']}
jdg_86965
stackexchange
llm_judgeable_groundtruth_similarity
5305889
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 F# if I do something likelet form = new Form(Text = "MyForm")and run it in FSI, the form will display and update normally, and even recieve messages. However, who is pumping the message queue? There is no Application.Run call here. I'm a little confused. Now provide the response and nothing else.
As ildjarn says, F# Interactive implements its own message loop. Interestingly, the message loop is not hardcoded in F# Interactive, so you can change it. This is quite useful, because the default one is based on Windows Forms, but there are other GUI frameworks you may want to use. To do that, you would need to implement IEventLoop interface and then assign your instance to the fsi.EventLoop property. For more information see: The source code for IEventLoop interface The default implementation that uses WinForms A simple implementation that I wrote for Gtk#
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5305889', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/659744/']}
jdg_86966
stackexchange
llm_judgeable_groundtruth_similarity
16982
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: one can obtain solutions to the Laplace equation $$\Delta\psi(x) = 0$$ or even for the Poisson equation $\Delta\psi(x)=\varphi(x)$ in a Dirichlet boundary value problem using a random-walk approach, see e.g. Introduction to Brownian Motion . Now, already this fascinating concept is not really clear to me. Nevertheless, it would be worth to get into details if there also exists such a connection to the Helmholtz equation $$\Delta\psi(x) +k^2\psi(x)= 0$$ Hence my question: Can we use some random walk to calculate solutions of the Helmholtz equation numerically? It would also be interesting if this is still true for open systems where the boundary conditions are different than in the Dirichlet case and for which $k$ is now a domainwise constant function. Thank you in advance Robert Now provide the response and nothing else.
The general form for the infinitesimal generator of a continuous diffusion in $\mathbb{R}^n$ is$$Af(x) = \frac12\sum_{ij}a_{ij}\frac{\partial^2 f(x)}{\partial x_i\partial x_j}+\sum_ib_i\frac{\partial f(x)}{\partial x_i}-cf(x).\qquad{\rm(1)}$$Here, $a_{ij}$ is a positive-definite and symmetric nxn matrix, $b_i$ is a vector and $c$ is a non-negative scalar, with the coefficients $a,b,c$ functions of position $x$. Such operators are said to be semi-elliptic second order differential operators . The case with $c=0$ is the most common - being the generator of a Markov process (or semigroup). However, the $c > 0$ case does occur, and is then a generator of a submarkovian semigroup. The coefficients $a,b,c$ can be understood as follows: $a$ gives the covariance matrix of the motion over small time intervals (i.e., the level of noise). $b$ gives the mean over small time intervals (the drift) and $c$ is the rate at which the process is "killed". To be precise, a processes $X_t$ can be modeled formally by adding an additional state $\it\Delta$ called the cemetary . So, we represent the state space for the killed diffusion as $\mathbb{R}^n\cup\{{\it\Delta}\}$. In a small time interval $\delta t$, the process has probability $c\delta t$ of being killed, in which case it jumps to the cemetary, and stays there. So, $X_t={\it\Delta}$ for all $t\ge\tau$ with $\tau$ being the (random) time when the process is killed. The terminology I am using here is taken from Revuz & Yor (Continuous Martingales and Brownian Motion) , and will vary between different authors. Anyway, getting back to PDEs. Suppose we want to solve the PDE $A\psi(x)=0$ on an open domain $U\subseteq\mathbb{R}^n$ with boundary condition $\psi(x)=\psi_0(x)$ for $x$ on the boundary of $U$ ($\partial U$, say). You can do the following. Simulate the process $X_t$ with initial condition $X_0=x$. Wait until the first time $T$ at which it hits the boundary and, when this occurs (if the process doesn't get killed first. i.e., $T < \tau$), take the expected value.$$\psi(x)=\mathbb{E}_x\left[\psi_0(X_T)1_{\{T < \tau\}}\right].\qquad\qquad{\rm(2)}$$Then $\psi$ satisfies the PDE $A\psi=0$. This is all very general. Getting back to the Helmholtz equation, we can let $a_{ij}$ be the identity matrix and $b_i=0$, and $c$ is a constant. In that case our generator becomes $A\psi=\frac12\Delta\psi-c\psi$. [ Edit: This is not quite the same as the Helmholtz equation, which has $c=-k^2$, because here we have $c > 0$. There is a sign difference which changes the behaviour of the solutions. See below] The process then is the following: run a Brownian motion starting from $x$ until the first time $T$ it hits the boundary. Decide if it has not been killed, which has probability $e^{-cT}$ conditional on $T$. If it hasn't, take the value $\psi_0(X_T)$. Finally, take the average of this process (e.g., using Monte Carlo). There is one practical issue here though. Throwing away all the paths on which the process gets killed is a bit wasteful, so you would simply multiply by the probability of not being killed on each path, rather than actually discarding them. i.e., you simulate a regular Brownian motion, and then calculate$$\psi(x)=\mathbb{E}_x\left[\psi_0(X_T)e^{-cT}\right].\qquad\qquad{\rm(3)}$$ We can even go the whole hog and solve $A\psi(x)=\varphi(x)$ for a general $x$-dependent coefficients and source term $\varphi$,$$\begin{align}\psi(x)&=\mathbb{E}_x\left[1_{\{T<\tau\}}\psi_0(X_T)-\int_0^{T\wedge\tau}\varphi(X_t)\,dt\right]\\&=\mathbb{E}_x\left[e^{-\int_0^Tc(\hat X_s)\,ds}\psi(\hat X_T)-\int_0^Te^{-\int_0^tc(\hat X_s)\,ds}\varphi(\hat X_t)\,dt\right].\end{align}\qquad{\rm(4)}$$Here, $X$ is the process killed at (state-dependent) rate $c$, and I'm using $\hat X$ for the process without killing, which requires multiplying by the survival probabilities $e^{-\int c(\hat X_s)\,ds}$ instead. One other area in which you have a '$-cf$' term in the PDE governing diffusions is in finance, and it occurs in two different, but closely related ways. Prices of financial assets are frequently modeled as diffusions (even, jump-diffusions), and the value of a financial derivative would be expressed as the expected value of its future value - under a so-called "risk-neutral measure" or "martingale measure" (which are just a special probability measures). However, you need to take interest rates into account. If the rate is $r$, then you would multiply the future (time $t$) value by $e^{-rt}$ before taking the expected value, which is effectively the same as adding a $-rf(x)$ term to the generator. And, as in the general case above, $r$ can be a function of the market state. The second main way (which occurs to me) in which such terms appear in finance is due to credit risk. If a counterparty has probability $rdt$ of defaulting in any time $t$, then you would have a $-rf(x)$ term occurring in the diffusion. This is more in line with the "killing" idea discussed above, but behaves in much the same way as interest rates. Finally, I'll mention that the PDE in the more general time-dependent situation is of the form $\partial f/\partial t + Af =0$, where $f$ is the expected value of some function of the process at a future time (and not necessarily the first time it hits the boundary). As mentioned in the other answer this is sometimes known as the Feynman-Kac formula , generally by physicists, and also as the Kolmogorov backward equation by mathematicians. Actually, the backward equation in the Wikipedia link doesn't have the $-cf$ term, but it would in the more general case of diffusions with killing. The adjoint PDE applying to probability densities is known as the Fokker-Planck equation by physicists and the Kolmogorov forward equation to mathematicians. Edit: As mentioned above, what we have here does not quite correspond to the Helmholtz equation, because of the sign of $c$, and the behaviour of the solutions does change depending on whether $c$ is positive or negative. In the probabilistic interpretation, $c > 0$ is the rate at which the process is killed. Looking at (3) and (4), we can see that solutions to the PDE will decay exponentially as we move further from the boundary. Furthermore, if the values on the boundary are non-negative, then $\psi$ has to be non-negative everywhere. The probabilistic method naturally leads to $\psi(x)$ being a positive linear combination of its boundary values (i.e., an integral with respect to a measure on the boundary). On the other hand, the Helmholtz equation has oscillating wavelike solutions. The values of $\psi(x)$ can exceed its values on the boundary and, even if $\psi\vert_{\partial U}$ is positive, it is possible for $\psi(x)$ to go negative inside the domain. So, it is not a positive linear combination of its boundary values. We could just try using a negative $c$ in (3) and (4) but, for the reasons just mentioned, this cannot work in general. What happens is that $e^{\vert c\vert T}$ is not integrable. To get around this, it is possible to transform the Helmholtz equation so that the zeroth order coefficient $-c$ is positive. We can make a substitution such as $\psi(x)=\tilde\psi(x)e^{ikS(x)}$, where $S$ is any solution to $\Vert\nabla S\Vert=1$. Then, the Helmholtz equation becomes,$$\frac12\Delta\tilde\psi + ik\nabla S\cdot\nabla\tilde\psi + \frac{ik}{2}(\Delta S)\tilde\psi=0.$$So we have a zeroth order term of the form $-\tilde c\tilde\psi$ for $\tilde c=-ik\Delta S/2$. This is imaginary, so does not make sense as a "killing" rate any more. However, as its real component is nonnegative (zero here), equations such as (3) and (4) above give bounded and well-defined expressions for $\tilde\psi$. A google search gives the following paper which uses such a substitution: Novel solutions of the Helmholtz equation and their application to diffraction . I expect that the papers linked to in the other answer use similar techniques to transform the equation into a form which can be handled by the probabilistic method - although I have not had a chance to look at them yet, and are not free access.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/16982', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/2671/']}
jdg_86967
stackexchange
llm_judgeable_groundtruth_similarity
4236736
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Why one would want to explicitly clear the a vector member variable (of on in a dtor (please see the code below). what are the benefits of clearing the vector, even though it will be destroyed just after the last line of dtor code will get executed? class A{~A(){ values.clear();}private: std::vector < double > values_;}; similar question about a the following code: class B{~B(){ if (NULL != p) { delete p_; p_ = NULL; }}private: A * p_;}; Since there is no way the dtor will get called twice, why to nullify p_ then? Now provide the response and nothing else.
In class A , there is absolutely no reason to .clear() the vector -type member variable in the destructor. The vector destructor will .clear() the vector when it is called. In class B , the cleanup code can simply be written as: delete p_; There is no need to test whether p_ != NULL first because delete NULL; is defined to be a no-op. There is also no need to set p_ = NULL after you've delete d it because p_ can no longer be legitimately accessed after the object of which it is a member is destroyed. That said, you should rarely need to use delete in C++ code. You should prefer to use Scope-Bound Resource Management (SBRM, also called Resource Acquisition Is Initialization) to manage resource lifetimes automatically. In this case, you could use a smart pointer. boost::scoped_ptr and std::unique_ptr (from C++0x) are both good choices. Neither of them should have any overhead compared to using a raw pointer. In addition, they both suppress generation of the implicitly declared copy constructor and copy assignment operator, which is usually what you want when you have a member variable that is a pointer to a dynamically allocated object.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4236736', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/416242/']}
jdg_86968
stackexchange
llm_judgeable_groundtruth_similarity
2797813
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I need to get an argument and convert it to an int. Here is my code so far: #include <iostream>using namespace std;int main(int argc,int argvx[]) { int i=1; int answer = 23; int temp; // decode arguments if(argc < 2) { printf("You must provide at least one argument\n"); exit(0); } // Convert it to an int here} Now provide the response and nothing else.
Since this answer was somehow accepted and thus will appear at the top, although it's not the best, I've improved it based on the other answers and the comments. The C way; simplest, but will treat any invalid number as 0: #include <cstdlib>int x = atoi(argv[1]); The C way with input checking: #include <cstdlib>errno = 0;char *endptr;long int x = strtol(argv[1], &endptr, 10);if (endptr == argv[1]) { std::cerr << "Invalid number: " << argv[1] << '\n';} else if (*endptr) { std::cerr << "Trailing characters after number: " << argv[1] << '\n';} else if (errno == ERANGE) { std::cerr << "Number out of range: " << argv[1] << '\n';} The C++ iostreams way with input checking: #include <sstream>std::istringstream ss(argv[1]);int x;if (!(ss >> x)) { std::cerr << "Invalid number: " << argv[1] << '\n';} else if (!ss.eof()) { std::cerr << "Trailing characters after number: " << argv[1] << '\n';} Alternative C++ way since C++11: #include <stdexcept>#include <string>std::string arg = argv[1];try { std::size_t pos; int x = std::stoi(arg, &pos); if (pos < arg.size()) { std::cerr << "Trailing characters after number: " << arg << '\n'; }} catch (std::invalid_argument const &ex) { std::cerr << "Invalid number: " << arg << '\n';} catch (std::out_of_range const &ex) { std::cerr << "Number out of range: " << arg << '\n';} All four variants assume that argc >= 2 . All accept leading whitespace; check isspace(argv[1][0]) if you don't want that. All except atoi reject trailing whitespace.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/2797813', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/293039/']}
jdg_86969
stackexchange
llm_judgeable_groundtruth_similarity
312262
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: We are going through a large scale DDOS attack, but it isn't the typical bot-net that our Cisco Guard can handle, it is a BitTorrent attack. This is new to me, so I am unsure how to stop it. Here are the statsIIS is processing between 40 and 100 requests per second from BitTorrent clients.We have about 20% of the User Agents, but the other 75% are blank. We want to block the blank user agents at the server level. What is the best approach? Now provide the response and nothing else.
If request filtering can't handle this, you can try ' URL Rewrite ' a free Add-On from Microsoft and pretty helpful anyways. Create a rule like this: <rule name="NoUserAgent" stopProcessing="true"> <match url=".*" /> <conditions> <add input="{HTTP_USER_AGENT}" pattern="^$" /> </conditions> <action type="CustomResponse" statusCode="403" statusReason="Forbidden: Access is denied." statusDescription="You did not present a User-Agent header which is required for this site" /></rule> During a quick test this worked for both an empty User-Agent and a missing one. I'm using the regular expression '^$' which is only valid for an empty string. You can also return a 404 or whatever else you want rather than a 403.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/312262', 'https://serverfault.com', 'https://serverfault.com/users/13586/']}
jdg_86970
stackexchange
llm_judgeable_groundtruth_similarity
5525758
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 profile my application to monitor the effects of a function, both before and after refactoring. I have performed an analysis of my application and having looked at the Summary I've noticed that the Hot Path list does not mention any of my functions used, it only mentions functions up to Application.Run() I'm fairly new to profiling and would like to know how I could get more information about the Hot Path as demonstrated via the MSDN documentation ; MSDN Example: My Results: I've noticed in the Output Window there are a lot of messages relating to a failure when loading symbols, a few of them are below; Failed to load symbols for C:\Windows\system32\USP10.dll. Failed to load symbols for C:\Windows\system32\CRYPTSP.dll.Failed to load symbols for (Omitted)\WindowsFormsApplication1\bin\Debug\System.Data.SQLite.dll.Failed to load symbols for C:\Windows\system32\GDI32.dll. Failed to load symbols for C:\Windows\WinSxS\x86_microsoft.windows.common-controls_6595b64144ccf1df_6.0.7601.17514_none_41e6975e2bd6f2b2\comctl32.dll.Failed to load symbols for C:\Windows\system32\msvcrt.dll. Failed to load symbols for C:\Windows\Microsoft.NET\Framework\v4.0.30319\nlssorting.dll.Failed to load symbols for C:\Windows\Microsoft.Net\assembly\GAC_32\System.Data\v4.0_4.0.0.0__b77a5c561934e089\System.Data.dll. Failed to load symbols forC:\Windows\Microsoft.Net\assembly\GAC_32\System.Transactions\v4.0_4.0.0.0__b77a5c561934e089\System.Transactions.dll.Unable to open file to serialize symbols: Error VSP1737: File could not be opened due to sharing violation: - D:\(Omitted)\WindowsFormsApplication1110402.vsp (Formatted using code tool so it's readable) Thanks for any pointers. Now provide the response and nothing else.
The "Hot Path" shown on the summary view is the most expensive call path based on the number of inclusive samples (samples from the function and also samples from functions called by the function) and exclusive samples (samples only from the function). A "sample" is just the fact the function was at the top of the stack when the profiler's driver captured the stack (this occurs at very small timed intervals). Thus, the more samples a function has, the more it was executing. By default for sampling analysis, a feature called " Just My Code " is enabled that hides functions on the stack coming from non-user modules (it will show a depth of 1 non-user functions if called by a user function; in your case Application.Run ). Functions coming from modules without symbols loaded or from modules known to be from Microsoft would be excluded. Your "Hot Path" on the summary view indicates that the most expensive stack didn't have anything from what the profiler considers to be your code (other than Main ). The example from MSDN shows more functions because the PeopleTrax.* and PeopleNS.* functions are coming from "user code". "Just My Code" can be turned off by clicking the "Show All Code" link on the summary view, but I would not recommend doing so here. Take a look at the " Functions Doing The Most Individual Work " on the summary view. This displays functions that have the highest exclusive sample counts and are therefore, based on the profiling scenario, the most expensive functions to call. You should see more of your functions (or functions called by your functions) here. Additionally, the " Functions " and " Call Tree " view might show you more details (there's a drop-down at the top of the report to select the current view). As for your symbol warnings, most of those are expected because they are Microsoft modules (not including System.Data.SQLite.dll). While you don't need the symbols for these modules to properly analyze your report, if you checked "Microsoft Symbol Servers" in "Tools -> Options -> Debugging -> Symbols" and reopened the report, the symbols for these modules should load. Note that it'll take much longer to open the report the first time because the symbols need to be downloaded and cached. The other warning about the failure to serialize symbols into the report file is the result of the file not being able to be written to because it is open by something else that prevents writing. Symbol serialization is an optimization that allows the profiler to load symbol information directly from the report file on the next analysis. Without symbol serialization, analysis simply needs to perform the same amount of work as when the report was opened for the first time. And finally, you may also want to try instrumentation instead of sampling in your profiling session settings. Instrumentation modifies modules that you specify to capture data on each and every function call (be aware that this can result in a much, much larger .vsp file). Instrumentation is ideal for focusing in on the timing of specific pieces of code, whereas sampling is ideal for general low-overhead profiling data collection.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5525758', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/218159/']}
jdg_86971
stackexchange
llm_judgeable_groundtruth_similarity
133939
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 two discrete random variavles; $X$ and $Y$ with: And I want to calculate $Cov(Y,Y+e^X)$, and I've tried the following: \[ScriptCapitalD] = EmpiricalDistribution[{1/8, 2/8, 5/8} -> {1, 2, 3}];\[ScriptCapitalD]1 = EmpiricalDistribution[{1/5, 4/5} -> {-1, 1}];Covariance[\[ScriptCapitalD]1, \[ScriptCapitalD]1 + e^\[ScriptCapitalD]] But this doesnt return any value, what am I doing wrong? I have also tried calculating stuff like $P(X=3,Y=1)$ and $P(X\cdot Y \geq 2)$ without any luck Now provide the response and nothing else.
This solution uses built-in functions : dx = EmpiricalDistribution[{1/8, 2/8, 5/8} -> {1, 2, 3}];dy = EmpiricalDistribution[{1/5, 4/5} -> {-1, 1}];Covariance[ TransformedDistribution[{y, y + Exp[x]}, {x \[Distributed] dx, y \[Distributed] dy}], 1, 2](* 16/25 *)
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/133939', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/45377/']}
jdg_86972
stackexchange
llm_judgeable_groundtruth_similarity
19046969
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using an UITextView that will be expandable by taping a "more" button. The problem is the following: On iOS6 I use this, self.DescriptionTextView.text = @"loong string";if(self.DescriptionTextView.contentSize.height>self.DescriptionTextView.frame.size.height) { //set up the more button} The problem is that on iOS7 the contentSize.height returns a different value (far smaller) than the value it returns on iOS6. Why is this? How to fix it? Now provide the response and nothing else.
The content size property no longer works as it did on iOS 6. Using sizeToFit as others suggest may or may not work depending on a number of factors. It didn't work for me, so I use this instead: - (CGFloat)measureHeightOfUITextView:(UITextView *)textView{ if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) { // This is the code for iOS 7. contentSize no longer returns the correct value, so // we have to calculate it. // // This is partly borrowed from HPGrowingTextView, but I've replaced the // magic fudge factors with the calculated values (having worked out where // they came from) CGRect frame = textView.bounds; // Take account of the padding added around the text. UIEdgeInsets textContainerInsets = textView.textContainerInset; UIEdgeInsets contentInsets = textView.contentInset; CGFloat leftRightPadding = textContainerInsets.left + textContainerInsets.right + textView.textContainer.lineFragmentPadding * 2 + contentInsets.left + contentInsets.right; CGFloat topBottomPadding = textContainerInsets.top + textContainerInsets.bottom + contentInsets.top + contentInsets.bottom; frame.size.width -= leftRightPadding; frame.size.height -= topBottomPadding; NSString *textToMeasure = textView.text; if ([textToMeasure hasSuffix:@"\n"]) { textToMeasure = [NSString stringWithFormat:@"%@-", textView.text]; } // NSString class method: boundingRectWithSize:options:attributes:context is // available only on ios7.0 sdk. NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]; [paragraphStyle setLineBreakMode:NSLineBreakByWordWrapping]; NSDictionary *attributes = @{ NSFontAttributeName: textView.font, NSParagraphStyleAttributeName : paragraphStyle }; CGRect size = [textToMeasure boundingRectWithSize:CGSizeMake(CGRectGetWidth(frame), MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil]; CGFloat measuredHeight = ceilf(CGRectGetHeight(size) + topBottomPadding); return measuredHeight; } else { return textView.contentSize.height; }}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/19046969', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1028028/']}
jdg_86973
stackexchange
llm_judgeable_groundtruth_similarity
1536428
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 out the beast forum written in rails and will use this as an example of a problem I keep facing. The forum has a topics/show action and view with a form at the bottom to create a new post within the topic. Submitting the form goes to posts/create and if the validation passes redirects back to topics/show and works fine, however if the validation fails (leaving out the body field) you're redirected to the same topics/show and back to the form, with no validation errors... normally if validation fails you're left on whatever/create with render :action => new. Are the validations being lost in the redirect, and what's the best method of getting it working? See code below: PostsController.rb def create @post = current_user.reply @topic, params[:post][:body] respond_to do |format| if @post.new_record? format.html { redirect_to forum_topic_path(@forum, @topic) } format.xml { render :xml => @post.errors, :status => :unprocessable_entity } else flash[:notice] = 'Post was successfully created.' format.html { redirect_to(forum_topic_post_path(@forum, @topic, @post, :anchor => dom_id(@post))) } format.xml { render :xml => @post, :status => :created, :location => forum_topic_post_url(@forum, @topic, @post) } end end end TopicsController.rb def show respond_to do |format| format.html do if logged_in? current_user.seen! (session[:topics] ||= {})[@topic.id] = Time.now.utc end @topic.hit! unless logged_in? && @topic.user_id == current_user.id @posts = @topic.posts.paginate :page => current_page @post = Post.new end format.xml { render :xml => @topic } end end topics/show view <% form_for :post, :url => forum_topic_posts_path(@forum, @topic, :page => @topic.last_page) do |f| %> <%= f.error_messages %> <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr> <td rowspan="2" width="70%"> <%= f.text_area :body, :rows => 8 %> </td> <td valign="top"> <%= render :partial => "posts/formatting" %> </td> </tr> <tr> <td valign="bottom" style="padding-bottom:15px;"> <%= submit_tag I18n.t('txt.views_topics.save_reply', :default => 'Save reply') %> </td> </tr> </table> <% end %> Many thanks. Now provide the response and nothing else.
I think you have two problems here. Keeping validation errors through a redirect Repopulating the form fields so the user doesn't have to enter all the information again. Both of these things are connected. Validation errors are usually displayed through the error_msg_for method which acts on an object. Usually provided by the controller as the an instance variable of object that could not be saved. That same instance variable is used to repopulate the form. During a redirect the controller will usually instantiate an instance variable using the params hash. So any information used to determine why a save failed is lost. Normal resources will render on save failure and redirect on success, this causes two things happen. The instance of the object is passed to error_msg_for creating that nice uniform error box. The instance of the object is used to populate the fields of the form, allowing your user to edit only what is necessary. I don't know Beast so well, so I'm not sure if the form to create threads is an active record model. But the following will give you an idea how to work around your problem. It would involve modifying your local copy of the Beast plugin, so if you're using a tool to keep it updated, your changes might get lost. I've been using these following methods to get your validation problems. Assuming the form you're talking about is based on a nmodel they should provide you with everything you need to repopulate a form. Essentially you store a shallow copy of the object with the errors in the flash hash, using clone_with_errors. You have to use a shallow copy or else you'll run into problems when displaying errors for records with multiple associations. Then I use my_error_msg_for which takes the same options as the standard error_msg_for to build the error messages html. I only wrote it because for some reason the standard error_msg_for method didn't work with objects stored in the hash. It's almost identical to the official source version of error_msg_for which was troubling. /app/controllers/examples_controller.rb class ExamplesController < ApplicationController def update ... if @example.save regular action else flash[:errors] = clone_with_errors(@example) respond_to do |format| format.html redirect_to(@example) end endend /app/views/examples/show.html.erb <div id="error"> <% if flash[:errors] && !flash[:errors].empty? then -%> <p ><%= my_error_msg_for flash[:errors] %></p> <% end -%></div>... Here's the code you need to make it all work. application_controller.rb def clone_with_errors(object) clone = object.clone object.errors.each{|field,msg| clone.errors.add_to_base(msg)} return clone end application_helper.rb def _error_msg(*params) options = params.extract_options!.symbolize_keys if object = options.delete(:object) objects = [object].flatten else objects = params.collect {|object_name| instance_variable_get("@#{object_name}") }.compact end count = objects.inject(0) {|sum, this| sum + this.errors.count } unless count.zero? html = {} [:id, :class].each do |key| if options.include?(key) value = options[key] html[key] = value unless value.blank? else html[key] = 'errorExplanation' end end options[:object_name] ||= params.first options[:header_message] = "#{pluralize(count, 'error')} prohibited this #{options[:object_name].to_s.gsub('_', ' ')} from being saved" unless options.include?(:header_message) && !options[:header_messag].nil? options[:message] ||= 'There were problems with the following fields:' unless options.include?(:message) && !options[:message].nil? error_messages = objects.sum {|this| this.errors.full_messages.map {|msg| content_tag(:li, msg) } }.join contents = '' contents << content_tag(options[:header_tag] || :h2, options[:header_message]) unless options[:header_message].blank? contents << content_tag(:p, options[:message]) unless options[:message].blank? contents << content_tag(:ul, error_messages) content_tag(:div, contents, html) else '' end end def my_error_msg_for(params) _error_msg_test :object_name => params[:object].class.name.gsub(/([a-z])([A-Z])/,'\1 \2').gsub(/_/, " "), :object => params[:object], :header_message => params[:header_message], :message => params[:message] end
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1536428', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/146210/']}
jdg_86974
stackexchange
llm_judgeable_groundtruth_similarity
14459828
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 just discovered the pypi web UI have a field 'Bug tracker URL' in edit of egg metadata. This field exists so I guess it is supported in setup.py but I can't find anything about this using google. So the question how do I set up this field in my setup.py so when doing a dist release on pypi it can be automaticly filled. Now provide the response and nothing else.
The entry is called bugtrack_url , but it's not being picked up from setup.py . From context and code I understand it was intended to be used through-the-web on PyPI only, as per-project metadata, and not the usual per-release information. The field is now considered a legacy field (hardcoded to None ) and you instead add such information through the Project-URL list , which you can set in setuptools via the project_urls entry : project_urls={ 'Documentation': 'https://packaging.python.org/tutorials/distributing-packages/', 'Funding': 'https://donate.pypi.org', 'Say Thanks!': 'http://saythanks.io/to/example', 'Source': 'https://github.com/pypa/sampleproject/', 'Tracker': 'https://github.com/pypa/sampleproject/issues', }, This option was finally added to setuptools in November 2017 , and landed in version 38.3.0.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14459828', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/622081/']}
jdg_86975
stackexchange
llm_judgeable_groundtruth_similarity
7962312
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: ReentrantReadWriteLock has a fair and non-fair(default) mode, but the document is so hard for me to understand it. How can I understand it? It's great if there is some code example to demo it. UPDATE If I have a writing thread, and many many reading thread, which mode is better to use? If I use non-fair mode, is it possible the writing thread has little chance to get the lock? Now provide the response and nothing else.
Non-fair means that when the lock is ready to be obtained by a new thread, the lock gives no guarantees to the fairness of who obtains the lock (assuming there are multiple threads requesting the lock at the time). In other words, it is conceivable that one thread might be continuously starved because other threads always manage to arbitrarily get the lock instead of it. Fair mode acts more like first-come-first-served, where threads are guaranteed some level of fairness that they will obtain the lock in a fair manner (e.g. before a thread that started waiting long after). Edit Here is an example program that demonstrates the fairness of locks (in that write lock requests for a fair lock are first come, first served). Compare the results when FAIR = true (the threads are always served in order) versus FAIR = false (the threads are sometimes served out of order). import java.util.concurrent.locks.ReentrantReadWriteLock;public class FairLocking { public static final boolean FAIR = true; private static final int NUM_THREADS = 3; private static volatile int expectedIndex = 0; public static void main(String[] args) throws InterruptedException { ReentrantReadWriteLock.WriteLock lock = new ReentrantReadWriteLock(FAIR).writeLock(); // we grab the lock to start to make sure the threads don't start until we're ready lock.lock(); for (int i = 0; i < NUM_THREADS; i++) { new Thread(new ExampleRunnable(i, lock)).start(); // a cheap way to make sure that runnable 0 requests the first lock // before runnable 1 Thread.sleep(10); } // let the threads go lock.unlock(); } private static class ExampleRunnable implements Runnable { private final int index; private final ReentrantReadWriteLock.WriteLock writeLock; public ExampleRunnable(int index, ReentrantReadWriteLock.WriteLock writeLock) { this.index = index; this.writeLock = writeLock; } public void run() { while(true) { writeLock.lock(); try { // this sleep is a cheap way to make sure the previous thread loops // around before another thread grabs the lock, does its work, // loops around and requests the lock again ahead of it. Thread.sleep(10); } catch (InterruptedException e) { //ignored } if (index != expectedIndex) { System.out.printf("Unexpected thread obtained lock! " + "Expected: %d Actual: %d%n", expectedIndex, index); System.exit(0); } expectedIndex = (expectedIndex+1) % NUM_THREADS; writeLock.unlock(); } } }} Edit (again) Regarding your update, with non-fair locking it's not that there's a possibility that a thread will have a low chance of getting a lock, but rather that there's a low chance that a thread will have to wait a bit. Now, typically as the starvation period increases, the probability of that length of time actually occuring decreases...just as flipping a coin "heads" 10 consecutive times is less likely to occur than flipping a coin "heads" 9 consecutive times. But if the selection algorithm for multiple waiting threads was something non-randomized, like "the thread with the alphabetically-first name always gets the lock" then you might have a real problem because the probability does not necessarily decrease as the thread gets more and more starved...if a coin is weighted to "heads" 10 consecutive heads is essentially as likely as 9 consecutive heads. I believe that in implementations of non-fair locking a somewhat "fair" coin is used. So the question really becomes fairness (and thus, latency ) vs throughput. Using non-fair locking typically results in better throughput but at the expense of the occasional spike in latency for a lock request. Which is better for you depends on your own requirements.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7962312', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/342235/']}
jdg_86976
stackexchange
llm_judgeable_groundtruth_similarity
1268337
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 $f: \mathbb R \rightarrow \mathbb [0, \infty)$ be a convex function. If $f$ is twice-differentiable, then$$ (f^2)'' = (2ff')' = 2(f')^2 + 2f f'', $$which is $\geq 0 $ since $f, f'' \geq 0.$But how can I prove that $f^2$ is convex without smoothness assumptions? Recall the definition of convexity: $\forall t \in (0,1), \forall x,y \in \mathbb R,$$$ f((1-t)x+ty) \leq (1-t) f(x) + t f(y). $$Squaring both sides I get$$ f^2((1-t)x+ty) \leq (1-t)^2 f^2(x) + t^2 f^2(y) + 2t(1-t)f(x)f(y).$$Now, from the fact that $t \in (0,1)$ and the inequality $2t(1-t) \leq t^2 + (1-t)^2 \leq 1 $ I get$$ f^2((1-t)x+ty) \leq (1-t)f^2(x) + tf^2(y) + f(x)f(y). $$But that's a $f(x)f(y)$ too much... Now provide the response and nothing else.
Suppose $\phi$ is non decreasing and convex on $[0,\infty)$, then$\phi(f(\lambda x + (1-\lambda)y))\le \phi(\lambda f(x) + (1-\lambda)f(y)) \le \lambda \phi(f(x))+ (1-\lambda)\phi(f(y))$. Hence $\phi \circ f$ is convex. Here we take $\phi(x) = x^2$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1268337', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/234884/']}
jdg_86977
stackexchange
llm_judgeable_groundtruth_similarity
5206010
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 enabled https in tomcat and have a self-signed certificate for server auth. I have created an http client using Apache httpClient. I have set a trust manager loading the server certificate. The http client can connect with server no problem. To see what is going on I enabled debugging: System.setProperty("javax.net.debug", "ssl"); I saw the following which I can not understand at all: ***adding as trusted cert: Subject: CN=Me, OU=MyHouse, O=Home, L=X, ST=X, C=BB Issuer: CN=Me, OU=MyHouse, O=Home, L=X, ST=X, C=BB Algorithm: RSA; Serial number: 0x4d72356b Valid from Sat Mar 05 15:06:51 EET 2011 until Fri Jun 03 16:06:51 EEST 2011 My certificate is displayed and is added to truststore (as I see). Then: trigger seeding of SecureRandomdone seeding SecureRandom Here is the part from debugging traces I do not get: trustStore is: C:\Program Files\Java\jre6\lib\security\cacertstrustStore type is : jkstrustStore provider is : init truststoreadding as trusted cert: Subject: CN=SwissSign Platinum CA - G2, O=SwissSign AG, C=CH Issuer: CN=SwissSign Platinum CA - G2, O=SwissSign AG, C=CH Algorithm: RSA; Serial number: 0x4eb200670c035d4f Valid from Wed Oct 25 11:36:00 EEST 2006 until Sat Oct 25 11:36:00 EEST 2036adding as trusted cert: Subject: [email protected], CN=http://www.valicert.com/, OU=ValiCert Class 1 Policy Validation Authority, O="ValiCert, Inc.", L=ValiCert Validation Network Issuer: [email protected], CN=http://www.valicert.com/, OU=ValiCert Class 1 Policy Validation Authority, O="ValiCert, Inc.", L=ValiCert Validation Network Algorithm: RSA; Serial number: 0x1 Valid from Sat Jun 26 01:23:48 EEST 1999 until Wed Jun 26 01:23:48 EEST 2019 It seems that it also uses the default java trust store! My question is why does this happen? In my code I specify explicitly a specific trust-store to use (via truststoremanagers). I was expecting only this to be used. It seems that both my truststore and java's default is being used. Is this how it is supposed to work? UPDATE: I tried the following: System.out.println("TMF No:"+tmf.getTrustManagers().length);System.out.println("Class is "+tmf.getTrustManagers()[0].getClass().getName()); I thought that I should see 2 trust managers, since 2 keystores (mine and java's default appear to be used). But the result was only 1 trust manager! TMF No:1Class is com.sun.net.ssl.internal.ssl.X509TrustManagerImpl UPDATE2: As you see in the code bellow I specify my keystore.My expectation is that only this should be used (not this and cacert as well) HttpClient client = new DefaultHttpClient(); SSLContext sslContext = SSLContext.getInstance("TLS"); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); KeyStore ks = KeyStore.getInstance("JKS"); File trustFile = new File("clientTrustStore.jks"); ks.load(new FileInputStream(trustFile), null); tmf.init(ks); sslContext.init(null, tmf.getTrustManagers(),null); SSLSocketFactory sf = new SSLSocketFactory(sslContext); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Scheme scheme = new Scheme("https", sf, 443); client.getConnectionManager().getSchemeRegistry().register(scheme); httpGet = new HttpGet("https://localhost:8443/myApp"); HttpResponse httpResponse = client.execute(httpGet); Does not make sense to me. Now provide the response and nothing else.
I put together this test app to reproduce the issue using the HTTP testing framework from the Apache HttpClient package: ClassLoader cl = HCTest.class.getClassLoader();URL url = cl.getResource("test.keystore");KeyStore keystore = KeyStore.getInstance("jks");char[] pwd = "nopassword".toCharArray();keystore.load(url.openStream(), pwd);TrustManagerFactory tmf = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm());tmf.init(keystore);TrustManager[] tm = tmf.getTrustManagers();KeyManagerFactory kmfactory = KeyManagerFactory.getInstance( KeyManagerFactory.getDefaultAlgorithm());kmfactory.init(keystore, pwd);KeyManager[] km = kmfactory.getKeyManagers();SSLContext sslcontext = SSLContext.getInstance("TLS");sslcontext.init(km, tm, null);LocalTestServer localServer = new LocalTestServer(sslcontext);localServer.registerDefaultHandlers();localServer.start();try { DefaultHttpClient httpclient = new DefaultHttpClient(); TrustStrategy trustStrategy = new TrustStrategy() { public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { for (X509Certificate cert: chain) { System.err.println(cert); } return false; } }; SSLSocketFactory sslsf = new SSLSocketFactory("TLS", null, null, keystore, null, trustStrategy, new AllowAllHostnameVerifier()); Scheme https = new Scheme("https", 443, sslsf); httpclient.getConnectionManager().getSchemeRegistry().register(https); InetSocketAddress address = localServer.getServiceAddress(); HttpHost target1 = new HttpHost(address.getHostName(), address.getPort(), "https"); HttpGet httpget1 = new HttpGet("/random/100"); HttpResponse response1 = httpclient.execute(target1, httpget1); System.err.println(response1.getStatusLine()); HttpEntity entity1 = response1.getEntity(); EntityUtils.consume(entity1); HttpHost target2 = new HttpHost("www.verisign.com", 443, "https"); HttpGet httpget2 = new HttpGet("/"); HttpResponse response2 = httpclient.execute(target2, httpget2); System.err.println(response2.getStatusLine()); HttpEntity entity2 = response2.getEntity(); EntityUtils.consume(entity2);} finally { localServer.stop();} Even though, Sun's JSSE implementation appears to always read the trust material from the default trust store for some reason, it does not seem to get added to the SSL context and to impact the process of trust verification during the SSL handshake. Here's the output of the test app. As you can see, the first request succeeds whereas the second fails as the connection to www.verisign.com is rejected as untrusted. [[ Version: V1 Subject: CN=Simple Test Http Server, OU=Jakarta HttpClient Project, O=Apache Software Foundation, L=Unknown, ST=Unknown, C=Unknown Signature Algorithm: SHA1withDSA, OID = 1.2.840.10040.4.3 Key: Sun DSA Public Key Parameters:DSA p: fd7f5381 1d751229 52df4a9c 2eece4e7 f611b752 3cef4400 c31e3f80 b6512669 455d4022 51fb593d 8d58fabf c5f5ba30 f6cb9b55 6cd7813b 801d346f f26660b7 6b9950a5 a49f9fe8 047b1022 c24fbba9 d7feb7c6 1bf83b57 e7c6a8a6 150f04fb 83f6d3c5 1ec30235 54135a16 9132f675 f3ae2b61 d72aeff2 2203199d d14801c7 q: 9760508f 15230bcc b292b982 a2eb840b f0581cf5 g: f7e1a085 d69b3dde cbbcab5c 36b857b9 7994afbb fa3aea82 f9574c0b 3d078267 5159578e bad4594f e6710710 8180b449 167123e8 4c281613 b7cf0932 8cc8a6e1 3c167a8b 547c8d28 e0a3ae1e 2bb3a675 916ea37f 0bfa2135 62f1fb62 7a01243b cca4f1be a8519089 a883dfe1 5ae59f06 928b665e 807b5525 64014c3b fecf492a y: f0cc639f 702fd3b1 03fa8fa6 676c3756 ea505448 23cd1147 fdfa2d7f 662f7c59 a02ddc1a fd76673e 25210344 cebbc0e7 6250fff1 a814a59f 30ff5c7e c4f186d8 f0fd346c 29ea270d b054c040 c74a9fc0 55a7020f eacf9f66 a0d86d04 4f4d23de 7f1d681f 45c4c674 5762b71b 808ded17 05b74baf 8de3c4ab 2ef662e3 053af09e Validity: [From: Sat Dec 11 14:48:35 CET 2004, To: Tue Dec 09 14:48:35 CET 2014] Issuer: CN=Simple Test Http Server, OU=Jakarta HttpClient Project, O=Apache Software Foundation, L=Unknown, ST=Unknown, C=Unknown SerialNumber: [ 41bafab3]] Algorithm: [SHA1withDSA] Signature:0000: 30 2D 02 15 00 85 BE 6B D0 91 EF 34 72 05 FF 1A 0-.....k...4r...0010: DB F6 DE BF 92 53 9B 14 27 02 14 37 8D E8 CB AC .....S..'..7....0020: 4E 6C 93 F2 1F 7D 20 A1 2D 6F 80 5F 58 AE 33 Nl.... .-o._X.3]HTTP/1.1 200 OK[[ Version: V3 Subject: CN=www.verisign.com, OU=" Production Security Services", O="VeriSign, Inc.", STREET=487 East Middlefield Road, L=Mountain View, ST=California, OID.2.5.4.17=94043, C=US, SERIALNUMBER=2497886, OID.2.5.4.15="V1.0, Clause 5.(b)", OID.1.3.6.1.4.1.311.60.2.1.2=Delaware, OID.1.3.6.1.4.1.311.60.2.1.3=US Signature Algorithm: SHA1withRSA, OID = 1.2.840.113549.1.1.5 Key: Sun RSA public key, 2048 bits modulus: 20699622354183393041832954221256409980425015218949582822286196083815087464214375375678538878841956356687753084333860738385445545061253653910861690581771234068858443439641948884498053425403458465980515883570440998475638309355278206558031134532548167239684215445939526428677429035048018486881592078320341210422026566944903775926801017506416629554190534665876551381066249522794321313235316733139718653035476771717662585319643139144923795822646805045585537550376512087897918635167815735560529881178122744633480557211052246428978388768010050150525266771462988042507883304193993556759733514505590387262811565107773578140271 public exponent: 65537 Validity: [From: Wed May 26 02:00:00 CEST 2010, To: Sat May 26 01:59:59 CEST 2012] Issuer: CN=VeriSign Class 3 Extended Validation SSL SGC CA, OU=Terms of use at https://www.verisign.com/rpa (c)06, OU=VeriSign Trust Network, O="VeriSign, Inc.", C=US SerialNumber: [ 53d2bef9 24a7245e 83ca01e4 6caa2477]Certificate Extensions: 10[1]: ObjectId: 1.3.6.1.5.5.7.1.1 Criticality=falseAuthorityInfoAccess [ [accessMethod: 1.3.6.1.5.5.7.48.1 accessLocation: URIName: http://EVIntl-ocsp.verisign.com, accessMethod: 1.3.6.1.5.5.7.48.2 accessLocation: URIName: http://EVIntl-aia.verisign.com/EVIntl2006.cer]]...]Exception in thread "main" javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated at com.sun.net.ssl.internal.ssl.SSLSessionImpl.getPeerCertificates(SSLSessionImpl.java:345) at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:128) at org.apache.http.conn.ssl.SSLSocketFactory.createLayeredSocket(SSLSocketFactory.java:446)...
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5206010', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/384706/']}
jdg_86978
stackexchange
llm_judgeable_groundtruth_similarity
1122588
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have some commands in the [Run] section of my Inno Setup script. Right now, if any of them returns a failure code (non-zero return value), the setup continues without any warning to the user. The desired behavior is to have the setup fail and roll back. How do I enable this? I couldn't find any flag for the Run entry that would force this behavior. Am I missing something? Now provide the response and nothing else.
As far as I'm concerned, you have to use [Code] section for that, run the files with Exec function, check ResultCode upon return and run your uninstall script.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1122588', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/38087/']}
jdg_86979
stackexchange
llm_judgeable_groundtruth_similarity
339384
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: For example, to keep a CPU on in Android, I can use code like this: PowerManager powerManager = (PowerManager)getSystemService(POWER_SERVICE);WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "abc");wakeLock.acquire(); but I think the local variables powerManager and wakeLock can be eliminated: ((PowerManager)getSystemService(POWER_SERVICE)) .newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakelockTag") .acquire(); similar scene appears in iOS alert view, eg: from UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"my title" message:@"my message" delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil];[alert show];-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{ [alertView release];} to: [[[UIAlertView alloc] initWithTitle:@"my title" message:@"my message" delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil] show];-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{ [alertView release];} Is it a good practice to eliminate a local variable if it is just used once in the scope? Now provide the response and nothing else.
Code is read much more often than it is written, so you should take pity on the poor soul who will have to read the code six months from now (it may be you) and strive for the clearest, easiest to understand code. In my opinion, the first form, with local variables, is much more understandable. I see three actions on three lines, rather than three actions on one line. And if you think you are optimizing anything by getting rid of local variables, you are not. A modern compiler will put powerManager in a register 1 , whether a local variable is used or not, to call the newWakeLock method. The same is true for wakeLock . So you end up with the same compiled code in either case. 1 If you had a lot of intervening code between the declaration and the use of the local variable, it might go on the stack, but it is a minor detail.
{}
{'log_upvote_score': 9, 'links': ['https://softwareengineering.stackexchange.com/questions/339384', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/196142/']}
jdg_86980
stackexchange
llm_judgeable_groundtruth_similarity
22732756
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 that a single equality sign means assignment; double means equality; and triple means equality and the same type. What I don't understand why the typescript linter would want me to use triple equality signs in this case: function gcf(a: number, b: number): number{ return (b == 0) ? (a) : (gcf(b, a % b));} TsLint: == should be === I know that 0 is a number and I also know that b is a number (or else I'll get a compilation error). So why would I want to use triple equality signs in this case? Now provide the response and nothing else.
Types can't save you from all errors caused by == . Particularly since undefined and null are compatible with all types. e.g. the following is an incorrect if : var foo:number = null; if (foo == undefined) { console.log('is undefined'); // actually null } For more info on why these are equal https://stackoverflow.com/a/359509/95190 Personally : I have had this rule disabled and never had any issues. I don't compare with true/false/null/undefined , just if them. And typescript prevents comparing strings and numbers so that is not an error I need to deal with.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/22732756', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/886079/']}
jdg_86981
stackexchange
llm_judgeable_groundtruth_similarity
35855748
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: For example: 'hello'.count('e') Is this O(n)? I'm guessing the way it works is it scans 'hello' and increments a counter each time the letter 'e' is seen. How can I know this without guessing? I tried reading the source code here , but got stuck upon finding this: def count(s, *args): """count(s, sub[, start[,end]]) -> int Return the number of occurrences of substring sub in string s[start:end]. Optional arguments start and end are interpreted as in slice notation. """ return s.count(*args) Where can I read about what's executed in s.count(*args) ? edit: I understand what *args does in the context of Python functions. Now provide the response and nothing else.
str.count is implemented in native code, in the stringobject.c file, which delegates to either stringlib_count , or PyUnicode_Count which itself delegates to stringlib_count again. stringlib_count ultimately uses fastsearch to search for occurrences of the substring in the string and counting those. For one-character strings (e.g. your 'e' ), it is short-circuited to the following code path: for (i = 0; i < n; i++) if (s[i] == p[0]) { count++; if (count == maxcount) return maxcount; }return count; So yes, this is exactly as you assumed a simple iteration over the string sequence and counting the occurences of the substring. For search strings longer than a single character it gets a bit more complicated, due to handling overlaps etc., and the logic is buried deeper in the fastsearch implementation. But it’s essentially the same: a linear search through the string. So yes, str.count is in linear time, O(n). And if you think about it, it makes a lot of sense: In order to know how often a substring appears in a string, you need to look at every possible substring of the same length. So for a substring length of 1, you have to look at every character in the string, giving you a linear complexity. Btw. for more information about the underlying fastsearch algorithm, see this article on effbot.org . For Python 3, which only has a single Unicode string type, the links to the implementations are: unicode_count which uses stringlib_count which uses fastsearch .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35855748', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5956132/']}
jdg_86982
stackexchange
llm_judgeable_groundtruth_similarity
13740
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to use FindClusters to segment data points into similar numbers but so far I couldn't get it work for this example: l = {110, 111, 115, 117, 251, 254, 254, 259, 399, 400, 401, 402, 542, 546, 549, 554, 660, 660, 660, 660};FindClusters[l](*-> {{110, 111, 115, 117, 251, 254, 254, 259, 399, 400, 401, 402, 542, 546, 549, 554, 660, 660, 660, 660}}*) If I set the N parameter (to specify: Exactly N clusters), it works: FindClusters[l, 5](*-> {{110, 111, 115, 117}, {251, 254, 254, 259}, {399, 400, 401, 402}, {542, 546, 549, 554}, {660, 660, 660, 660}}*) However, my intent was to use FindClusters to figure out N. Now provide the response and nothing else.
Use the Bray-Curtis distance Total[Abs[u-v]]/Total[Abs[u+v]] : FindClusters[{110, 111, 115, 117, 251, 254, 254, 259, 399, 400, 401, 402, 542, 546, 549, 554, 660, 660, 660, 660}, DistanceFunction -> BrayCurtisDistance](*{{110, 111, 115, 117}, {251, 254, 254, 259}, {399, 400, 401, 402}, {542, 546, 549, 554}, {660, 660, 660, 660}}*) Edit: Here you have an experimental setup to test the FindClusters[] options in problems like yours: l1 = RandomInteger[{100, 1000}, 10];l2 = Join @@ (IntegerPart /@ RandomVariate[NormalDistribution[#, 10], 10] & /@ l1);l3 = FindClusters[l2, DistanceFunction -> CanberraDistance];Framed@Show[MapIndexed[ Graphics[{ColorData[3][#2[[1]]], Line[{{#, 0}, {#, 1}}] & /@ #1}] &, l3], PlotRange -> {0, 1}, AspectRatio -> 1/5]
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/13740', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/4283/']}
jdg_86983
stackexchange
llm_judgeable_groundtruth_similarity
105140
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 was copying hundreds of files to another computer using the scp command that I got the stalled error . Now I am going to copy the files again. Is there any way to avoid copying the already copied files? Now provide the response and nothing else.
You can use rsync for it. rsync is really designed for this type of operation. Syntax: rsync -avh /source/path/ host:/destination/path or rsync -a --ignore-existing /local/directory/ host:/remote/directory/ When you run it first time it will copy all content then it will copy only new files. If you need to tunnel the traffic through a SSH connection (for example, for confidentiality purposes), as indicated by you originally asking for a SCP-based solution, simply add -e ssh to the parameters to rsync . For example: rsync -avh -e ssh /source/path/ host:/destination/path
{}
{'log_upvote_score': 7, 'links': ['https://unix.stackexchange.com/questions/105140', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/10867/']}
jdg_86984
stackexchange
llm_judgeable_groundtruth_similarity
85175
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: What is the meaning of platform independence? I am taking the case of Java. Can I run a Java application on Linux that built on Windows platform? Or the reverse? Can I use a same (or exact) programming algorithm on both operating systems? In my view File Types are platform independent like Videos, Images, Documents etc. Now provide the response and nothing else.
Platform independence in software means that you can run the same code with little or no modification on multiple platforms. The devil is in the details: It depends on what you define as "the platform". In some cases, this may be a specific hardware machine configuration. In other cases, it may be a "generic PC". In other cases, it may be a virtual machine and run time environment (which is the case with Java). Nothing is "perfectly" platform-independent - there are always a few corner cases that can catch you out. For example, if you hard code file path separators rather than using the platform-independent File.pathSeparator in Java then your code won't work on both Windows and Linux. As a programmer, you need to watch out for these things, always using the platform-independent option where possible and test properly on different platforms if you care about portability. There are always some constraints on specific platforms that cannot be ignored. Examples are things like the maximum length of filenames or the available RAM on a system. No matter how much you try to be platform-independent, your code may fail if you try to run it on a platform that is too tightly constrained. It's important to note that some languages are platform-independent at the source code level (C/C++ is a good example) but lose platform independence once the code is compiled (since native code is platform-specific). Java retains platform independence even after code is compiled because it compiles to platform-independent bytecode (the actual conversion to native code is handled at a later time after the bytecode is loaded by the JVM). There are occasional bugs in language implementations that only occur on certain platforms. So even if your code is theoretically 100% portable, you still need to test it on different platforms to make sure you aren't running into any unusual bugs! In the specific case of Java: Java code is platform-independent in the sense that the same Java application or algorithms (typically compiled to Java bytecode and packaged in a .jar file) will run identically on Windows and Linux. Java libraries (e.g. all the nice open-source toolsets) are usually platform-independent, as long as they are written in pure Java. Most libraries try to stick with pure Java in order to maintain platform independence, but there are some cases where this is not possible (e.g. if the library needs to interface directly with a special hardware or call a C/C++ library that uses native code). The Java platform /runtime environment is platform-independent in the sense that the same libraries (images, networking, File IO, etc.) are available and work in the same way on all platforms. This is done deliberately in order to allow applications that use these libraries to be able to run on any platform. For example, the Java libraries that access the filesystem know the fact that Windows and Linux use different filename path separators, and take account of this for you. Of course, this means that under the hood the run time environment does make use of platform-specific features, so you need a different JRE for each platform. You can see a list of some of the available platforms on the Java download site: http://www.oracle.com/technetwork/java/javase/downloads/jdk-6u26-download-400750.html The JVM itself (i.e. the Java Virtual Machine that is responsible for JIT compiling and running Java bytecode) is platform-independent in the sense that it is available on many platforms (everything from mainframes to mobile phones). However specific versions of the JVM are needed for each underlying platform to take account of different native instruction codes and machine capabilities (so you can't run a Linux JVM on Windows and Vice Versa). The JVM is packaged as part of the Java platform/runtime environment as above. Overall, Java is probably about as close to true platform independence as you can get, but as you can see there is still quite a bit of platform-specific work done under the hood. If you stick to 100% pure Java code and libraries, my experience is that you can count on Java as being "effectively" platform-independent and it generally lives up to the Write Once Run Anywhere promise. But you should still test it!!
{}
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/85175', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/28252/']}
jdg_86985
stackexchange
llm_judgeable_groundtruth_similarity
12393470
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: restkit is using in a different way the oauth2 protocol, I need to change the code to be able to use it in my way: From: // OAuth 2 valid requestif (self.authenticationType == RKRequestAuthenticationTypeOAuth2) { NSString *authorizationString = [NSString stringWithFormat:@"OAuth2 %@", self.OAuth2AccessToken]; [_URLRequest setValue:authorizationString forHTTPHeaderField:@"Authorization"];} to: // OAuth 2 valid requestif (self.authenticationType == RKRequestAuthenticationTypeOAuth2) { NSString *authorizationString = [NSString stringWithFormat:@"Bearer %@", self.OAuth2AccessToken]; [_URLRequest setValue:authorizationString forHTTPHeaderField:@"Authorization"];} Use of "Bearer" instead of "Oauth2" .... I'm using CocoaPods to import restkit in my project. Can I fork Restkit repository on github and use the fork via CocoaPod instead of the official version? Now provide the response and nothing else.
You certainly can. Take a look at https://github.com/CocoaPods/CocoaPods/wiki/Dependency-declaration-options If RestKit included its .podspec file in the repository then you could just change your Podfile to point to your fork i.e. pod 'RestKit', :git => 'https://github.com/you/RestKit.git' Unfortunately RestKit does not include its .podspec . Instead copy RestKit.podspec from https://github.com/CocoaPods/Specs/blob/master/RestKit/0.10.2/RestKit.podspec and add it to your project. Edit the .podspec to use your fork as its source. You can then specify a local .podspec in your Podfile : pod 'RestKit', :podspec => 'local/path/to/RestKit.podspec' Alternately you might just add this .podspec to your fork and use the former dependency declaration.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/12393470', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1298865/']}
jdg_86986
stackexchange
llm_judgeable_groundtruth_similarity
13693638
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 try my hat at programming a game. My game will need to run the A* path finding algorithm on a traditional game grid. Like this for example: (S=Start, G=Goal, X=Wall) -------------------------------| | | | | | | | | G| |-------------------------------| | | | | | | | | | |-------------------------------| | X| X| X| X| | | | | |-------------------------------| | | | | X| | | | | |-------------------------------| S| | | | | | | | | |------------------------------- To implement A*, I will need to be able to get the "neighbors" of any node. (For Example, Start has 3 neighbors (Above, Diagonal, and Right).) The ways that come to mind to map this at a data layer is a 2 dimensional array or a linked list. The array seems like the most performant and easy to pull off. So if S was [0][4] , then its neighbors would be [0 + 1][4] (Right), [0][4 - 1] (Above), [0 + 1][4 - 1] (Diagonal) But having done .NET application development for a few years, basic arrays seem a bit old school to me. So before I go down that road, I thought I would ask if there is a nice .NET collection type I can use to map out a grid (at the data layer, not the UI). Now provide the response and nothing else.
First of all you should use session object from container. So your action should look more like: /** * @Route("/api/logout") */public function logoutAction(){ $session = $this->get('session'); $session->clear(); return $this->render('PassportApiBundle:Login:logout.html.twig');} And then in your test you can inject service into "client's container". So: public function testLogout(){ $sessionMock = $this->getMockBuilder('Symfony\Component\HttpFoundation\Session') ->setMethods(array('clear')) ->disableOriginalConstructor() ->getMock(); // example assertion: $sessionMock->expects($this->once()) ->method('clear'); $client = static::createClient(); $container = $client->getContainer(); $container->set('session', $sessionMock); $crawler = $client->request('GET', '/api/logout'); $this->assertTrue($client->getResponse()->isSuccessful());} With this code you can do everything you want with your session service. But You have to be aware two things: This mock will be set ONLY for one request (if you want use it in next one, you should set up it again). It's because the client restart kernel and rebuild container between each request. Session handling in Symfony 2.1 is little different than Symfony 2 edit: I've added an assertion
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13693638', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16241/']}
jdg_86987
stackexchange
llm_judgeable_groundtruth_similarity
105933
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: Suppose I have a polynomial Root representing an algebraic number. I want to represent it as a product of several polynomial Root s (if possible) such that the largest degree among the factors is as small as possible. For example, Root[-1 - #1 + 3 #1^3 - #1^4 + #1^5 - 3 #1^6 + 2 #1^7 + #1^9 &, 1] has to be represented as Root[1 + # + #^3 &, 1] Root[1 - # + #^3 &, 1] . The second problem is the same, but replacing "product" with "sum". For example, Root[8 - 4 #1 + 24 #1^2 - 15 #1^3 + 3 #1^5 + 6 #1^6 + #1^9 &, 1] has to be represented as Root[1 + # + #^3 &, 1] + Root[1 - # + #^3 &, 1] . How can I implement solutions to these problems in Mathematica ? Now provide the response and nothing else.
A constructive approach The problem can be solved if the form of the solution is given. Define the two factors using a hint (that these should be cubic equations) in the original post y1 = x^3 - p1 x + q1y2 = x^3 - p2 x + q2 Build a companion matrix of the polynomial $p(x)$ CompanionMatrix[p_,x_]:=Module[{n,w=CoefficientList[p,x]},w=-w/Last[w]; n=Length[w]-1; SparseArray[{{i_,n}:>w[[i]],{i_,j_}/;i==j+1->1},{n,n}]] The roots of a polynomial equation $p_A(x)=0$ are given by theeigenvalues of its companion matrix $A$ . If $a$ is a root of $p_A(x)$ (with companion matrix $A$ ) and $b$ is a root of $p_B(x)$ (withcompanion matrix $B$ ) then $a b$ is an eigenvalue of $A\otimes B$ and $a+b$ is an eigenvalue of $A\otimes I+I\otimes B$ , where $\otimes$ is the direct product of matrices. Let us focus on the product case and, therefore, determine the characteristic equation of the direct product of companion matrices (a1=CompanionMatrix[y1,x])//MatrixForm(a2=CompanionMatrix[y2,x])//MatrixForm y3=CharacteristicPolynomial[KroneckerProduct[a1,a2],x] y4=y3 Sign[CoefficientList[y3,x]//Last] The sum is treated similarly. We find out that the resulting characteristic polynomial is y4=-q1^3 q2^3 + p1 p2 q1^2 q2^2 x + (-p2^3 q1^2 - p1^3 q2^2 + 3 q1^2 q2^2) x^3 + p1 p2 q1 q2 x^4 + p1^2 p2^2 x^5 - 3 q1 q2 x^6 - 2 p1 p2 x^7 + x^9 Notice the relatively simple form in the case of trinomial equations. Now, your polynomial is z = -1 - #1 + 3 #1^3 - #1^4 + #1^5 - 3 #1^6 + 2 #1^7 + #1^9 &@x We demand that the two polynomials ( y3 and z ) are equal for any value of x r = SolveAlways[z == y4, {x}] Several solutions are obtained. Take, for instance, the first one {y1, y2} /. r[[1]](*{1/q2 + x/q2^(2/3) + x^3, q2 - q2^(2/3) x + x^3}*) Setting q2=1 we obtain the OP result. Comment on the method MA has a nice RootApproximant function, which operates by virtue of the LLL algorithm. One may be tempted to follow this route and implement some kind of this experimental mathematics approach. In contrast, the presented solution is fully constructive (in fact, algebraic) and does not require arbitrary precision computations. Answer to the 1st challenge question y1=x^5+ m x^3+n x^2+p1 x+q1;y2=x^3+ p2 x+q2;a1=CompanionMatrix[y1,x];a2=CompanionMatrix[y2,x];y3=CharacteristicPolynomial[KroneckerProduct[a1,a2],x];y4=y3 Sign[CoefficientList[y3,x]//Last];z=-282300416-64550400 #-34426880 #^2-14185880 #^3+8564800 #^4+4231216 #^5-972800 #^6-367820 #^7+27360 #^8+2600 #^9+1680 #^10+100 #^11-240 #^12+40 #^13+#^15&@x;r=SolveAlways[y4==z,{x}]({y1,y2}/.r[[1]])/.q2->1Out[1]= {656-150 x+80 x^2-20 x^3+x^5,1+x+x^3} Notice that in the characteristic equation the highest order term canbe negative, whereas I assume that in the given equation z it isalways 1. Therefore, in order to use SolveAlways y3 is multipliedby the sign. From the shown solutions, one can see that there is somearbitrariness in the results. But this is, of course, expected. Asfor the shown solution in radicals, one probably needs to guess thefield extension. One can create a Module as to fully automate the derivation. But isthere a pressing need? Answer to the 2st challenge question Here I demonstrate that the method can be used to write a root $P$ in terms of three roots of lower-order polynomials as $P=Q+R S$ . Additionally, the computation is done in a more structured form Define a generic polynomial with 1 as the leading coefficient pX[a_,n_]:=x^n+Sum[a[i]x^i,{i,0,n-1}] Define two modules that split a root in terms of a sum or a product pSum[pA_,pB_,y_]:=Module[{mA,mB,mAB,nA,nB,p}, nA=Exponent[pA,y]; nB=Exponent[pB,y]; mA=CompanionMatrix[pA,y]; mB=CompanionMatrix[pB,y]; mAB=KroneckerProduct[mA,IdentityMatrix[nB]]+KroneckerProduct[IdentityMatrix[nA],mB]; p=CharacteristicPolynomial[mAB,y]; p Sign[CoefficientList[p,y]//Last]]pProduct[pA_,pB_,y_]:=Module[{mA,mB,mAB,p}, mA=CompanionMatrix[pA,y]; mB=CompanionMatrix[pB,y]; mAB=KroneckerProduct[mA,mB]; p=CharacteristicPolynomial[mAB,y]; p Sign[CoefficientList[p,y]//Last]] Construct a working example for polynomials of the degrees 3, 2, 2respectively. {nQ,nR,nS}={3,2,2};nT=nR nS; pP[0]=(RootReduce[Root[#^3+#+3&,1]+Root[#^2+#+5&,1]Root[#^2+#+7&,1]]//First)@xOut[1]= 1984051825-172403780 x-281288553 x^2+14148329 x^3+17544721 x^4-310509 x^5-619703 x^6-4623 x^7+13443 x^8+244 x^9-167 x^10-3 x^11+x^12 Do the first part , namely, split the root of a 12th order equationinto a sum of 3rd and 4th order roots (sol[1]=SolveAlways[pP[0]==pSum[pX[q,nQ],pX[t,nT],x],x])//Transpose//TableFormrule[1]=q[2]->0;sol[1,1]=First[sol[1]]/.rule[1];AppendTo[sol[1,1],rule[1]];{pX[q,nQ],pX[t,nT]}/.sol[1,1]Out[2]= {3+x+x^3,1225-35 x-58 x^2-x^3+x^4} Do the second part , split the 4th order root into a product of 2roots of quadratic equations (sol[2]=SolveAlways[(pX[t,nT]/.sol[1,1])==pProduct[pX[r,nR],pX[s,nS],x],x])//Transpose//TableFormrule[2]=s[1]->1;sol[2,1]=First[sol[2]]/.rule[2];AppendTo[sol[2,1],rule[2]];{pX[r,nR],pX[s,nS]}/.sol[2,1]Out[3]= {5+x+x^2,7+x+x^2} The coefficients in rule[1] and rule[2] have been selected as tomatch the original equation. However, other choices are possible.
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/105933', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/7288/']}
jdg_86988
stackexchange
llm_judgeable_groundtruth_similarity
39315156
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 a newbie and learning python. Can someone help me- how to install xgboost in python. Im using Mac 10.11. I read online and did the below mentioned step, but not able to decode what to do next: pip install xgboost - Now provide the response and nothing else.
It's a little more complicated if you want to use multi-threading. For the record, I am using a Mac with OS X 10.10 (Yosemite). It took me a while to work through the various issues, but it is now running nicely in my Anaconda (Py36) environment. For multi-threading you need to do the following first (install homebrew if you have not done so): brew install gcc --without-multilib You might get some warnings to unlink directories or delete them if you have other versions installed; follow the warnings/instructions. Next get the xgboost files from Github. I downloaded it to Anaconda/pkgs directory. git clone --recursive https://github.com/dmlc/xgboost The next series of steps differ from the documentation on the xgboost site, and I cobbled it together from lots of sources and also experimenting. The problem is that some key lines in the make files are commented out and also not fully specified. cd xgboost; cp make/config.mk ./config.mk Now, use your favorite editor (I used vi), and go into the file that you copied from /make to /xgboost vi config.mk Uncomment the lines near the top of the file: export CC = gcc export CXX = g++ Change them to the following: export CC = gcc-6export CXX = g++-6 It is possible that simply uncommenting the lines solves the problem. It did not for me; I needed to add the -6 to both lines. Save the file. Also, make changes to the file xgboost/Makefile ; change lines: export CC = $(if $(shell which clang), clang, gcc)......export CXX = $(if $(shell which clang++), clang++, g++) to the following: export CC = $(if $(shell which clang), clang, gcc-6)......export CXX = $(if $(shell which clang++), clang++, g++-6) Again, I used vi for this editing. Save the file and now you need to run a cleaning step since you changed the Makefile. make clean_all && make -j4 This should configure it cleanly and build the library. You still need to install it. cd python-package; python setup.py install Now restart Python/Anaconda and you should be able to import the library.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39315156', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6792706/']}
jdg_86989
stackexchange
llm_judgeable_groundtruth_similarity
33546581
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 generating a complicated Mongo query depending on multiple parameters. One of criterion that I want to make with Criteria helper class is: {"field1": {$exists: true, $ne: false}} I tried to make it with: Criteria.where("field1").is(Criteria.where("$ne").is(false).and("$exists").is(true)) But it generates: { "field1" : { $java : org.springframework.data.mongodb.core.query.Criteria@23864e60 } So, how to achieve the exact query that i need? I can't hardcode that query string, because these type criterions are generated dynamically for field1,...fieldN and then combined with $or : statusCriteria = statusCriteria.orOperator(criterias.toArray(new Criteria[criterias.size()])); Now provide the response and nothing else.
Since you can’t use Criteria.and() to add multiple criteria into the same field, use Criteria.andOperator() as follows: Query query = new Query();query.addCriteria( new Criteria().andOperator( Criteria.where("field1").exists(true), Criteria.where("field1").ne(false) ));List<Foo> result = mongoTemplate.find(query, Foo.class);System.out.println("query - " + query.toString());for (Foo foo : result) { System.out.println("result - " + foo);}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/33546581', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1277815/']}
jdg_86990
stackexchange
llm_judgeable_groundtruth_similarity
7489164
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: We have a table with places and their latitudes and longitudes. We are trying to create a function in SQL Server 2008 to list places within next 25 kilometers using a specific latitude and longitude as centre point. I was wandering if this is a good way to start and test our function and getting current distance between a centre point (current location) and a target location (@latitude/@longitude): ALTER FUNCTION [dbo].[GetDistanceFromLocation]( @myCurrentLatitude float, @myCurrentLongitude float, @latitude float, @longitude float)RETURNS intASBEGIN DECLARE @radiusOfTheEarth int SET @radiusOfTheEarth = 6371--km DECLARE @distance int SELECT @distance = ( @radiusOfTheEarth * acos( cos( radians(@myCurrentLatitude) ) * cos( radians( @latitude ) ) * cos( radians( @longitude ) - radians(@myCurrentLongitude) ) + sin( radians(@myCurrentLatitude) ) * sin( radians( @latitude ) ) ) ) RETURN @distanceEND Is it correct or we are missing something? Now provide the response and nothing else.
It looks like you are using the great-circle distance formula, which is probably accurate enough for you, although you'll have to be the judge of that. If you want to check the results of your formula, you can use the geography data type: declare @geo1 geography = geography::Point(@lat1, @long1, 4326), @geo2 geography = geography::Point(@lat2, @long2, 4326)select @geo1.STDistance(@geo2) and since you are doing a proximity search , you may want to investigate the geography data type further.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7489164', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/66708/']}
jdg_86991
stackexchange
llm_judgeable_groundtruth_similarity
69479400
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 triggering a workflow run via github's rest api. But github doesn't send any data in the response body (204).How do i get the run id of the trigger request made?I know about the getRunsList api, which would return runs for a workflow id, then i can get the latest run, but this can cause issues when two requests are submitted at almost the same time. Now provide the response and nothing else.
This is not currently possible to get the run_id associated to the dispatch API call in the dispatch response itself, but there is a way to find this out if you can edit your worflow file a little. You need to dispatch the workflow with an input like this: curl "https://api.github.com/repos/$OWNER/$REPO/actions/workflows/$WORKFLOW/dispatches" -s \ -H "Authorization: Token $TOKEN" \ -d '{ "ref":"master", "inputs":{ "id":"12345678" } }' Also edit your workflow yaml file with an optionnal input (named id here). Also, place it as the first job, a job which has a single step with the same name as the input id value (this is how we will get the id back using the API!): name: ID Exampleon: workflow_dispatch: inputs: id: description: 'run identifier' required: falsejobs: id: name: Workflow ID Provider runs-on: ubuntu-latest steps: - name: ${{github.event.inputs.id}} run: echo run identifier ${{ inputs.id }} The trick here is to use name: ${{github.event.inputs.id}} https://docs.github.com/en/actions/creating-actions/metadata-syntax-for-github-actions#inputs Then the flow is the following: run the dispatch API call along with the input named id in this case with a random value POST https://api.github.com/repos/$OWNER/$REPO/actions/workflows/$WORKFLOW/dispatches in a loop get the runs that have been created since now minus 5 minutes (the delta is to avoid any issue with timings): GET https://api.github.com/repos/$OWNER/$REPO/actions/runs?created=>$run_date_filter example in the run API response, you will get a jobs_url that you will call: GET https://api.github.com/repos/$OWNER/$REPO/actions/runs/[RUN_ID]/jobs the job API call above returns the list of jobs, as you have declared the id jobs as 1st job it will be in first position. It also gives you the steps with the name of the steps. Something like this: { "id": 3840520726, "run_id": 1321007088, "run_url": "https://api.github.com/repos/$OWNER/$REPO/actions/runs/1321007088", "run_attempt": 1, "node_id": "CR_kwDOEi1ZxM7k6bIW", "head_sha": "4687a9bb5090b0aadddb69cc335b7d9e80a1601d", "url": "https://api.github.com/repos/$OWNER/$REPO/actions/jobs/3840520726", "html_url": "https://github.com/$OWNER/$REPO/runs/3840520726", "status": "completed", "conclusion": "success", "started_at": "2021-10-08T15:54:40Z", "completed_at": "2021-10-08T15:54:43Z", "name": "Hello world", "steps": [ { "name": "Set up job", "status": "completed", "conclusion": "success", "number": 1, "started_at": "2021-10-08T17:54:40.000+02:00", "completed_at": "2021-10-08T17:54:42.000+02:00" }, { "name": "12345678", <=============== HERE "status": "completed", "conclusion": "success", "number": 2, "started_at": "2021-10-08T17:54:42.000+02:00", "completed_at": "2021-10-08T17:54:43.000+02:00" }, { "name": "Complete job", "status": "completed", "conclusion": "success", "number": 3, "started_at": "2021-10-08T17:54:43.000+02:00", "completed_at": "2021-10-08T17:54:43.000+02:00" } ], "check_run_url": "https://api.github.com/repos/$OWNER/$REPO/check-runs/3840520726", "labels": [ "ubuntu-latest" ], "runner_id": 1, "runner_name": "Hosted Agent", "runner_group_id": 2, "runner_group_name": "GitHub Actions"} The name of the id step is returning your input value, so you can safely confirm that it is this run that was triggered by your dispatch call Here is an implementation of this flow in python , it will return the workflow run id: import randomimport stringimport datetimeimport requestsimport time# edit the following variablesowner = "YOUR_ORG" repo = "YOUR_REPO"workflow = "dispatch.yaml"token = "YOUR_TOKEN"authHeader = { "Authorization": f"Token {token}" }# generate a random idrun_identifier = ''.join(random.choices(string.ascii_uppercase + string.digits, k=15))# filter runs that were created after this date minus 5 minutesdelta_time = datetime.timedelta(minutes=5)run_date_filter = (datetime.datetime.utcnow()-delta_time).strftime("%Y-%m-%dT%H:%M") r = requests.post(f"https://api.github.com/repos/{owner}/{repo}/actions/workflows/{workflow}/dispatches", headers= authHeader, json= { "ref":"master", "inputs":{ "id": run_identifier } })print(f"dispatch workflow status: {r.status_code} | workflow identifier: {run_identifier}")workflow_id = ""while workflow_id == "": r = requests.get(f"https://api.github.com/repos/{owner}/{repo}/actions/runs?created=%3E{run_date_filter}", headers = authHeader) runs = r.json()["workflow_runs"] if len(runs) > 0: for workflow in runs: jobs_url = workflow["jobs_url"] print(f"get jobs_url {jobs_url}") r = requests.get(jobs_url, headers= authHeader) jobs = r.json()["jobs"] if len(jobs) > 0: # we only take the first job, edit this if you need multiple jobs job = jobs[0] steps = job["steps"] if len(steps) >= 2: second_step = steps[1] # if you have position the run_identifier step at 1st position if second_step["name"] == run_identifier: workflow_id = job["run_id"] else: print("waiting for steps to be executed...") time.sleep(3) else: print("waiting for jobs to popup...") time.sleep(3) else: print("waiting for workflows to popup...") time.sleep(3)print(f"workflow_id: {workflow_id}") gist link Sample output $ python3 github_action_dispatch_runid.pydispatch workflow status: 204 | workflow identifier: Z7YPF6DD1YP2PTMget jobs_url https://api.github.com/repos/OWNER/REPO/actions/runs/1321463229/jobsget jobs_url https://api.github.com/repos/OWNER/REPO/actions/runs/1321463229/jobsget jobs_url https://api.github.com/repos/OWNER/REPO/actions/runs/1321463229/jobsget jobs_url https://api.github.com/repos/OWNER/REPO/actions/runs/1321475221/jobswaiting for steps to be executed...get jobs_url https://api.github.com/repos/OWNER/REPO/actions/runs/1321463229/jobsget jobs_url https://api.github.com/repos/OWNER/REPO/actions/runs/1321475221/jobswaiting for steps to be executed...get jobs_url https://api.github.com/repos/OWNER/REPO/actions/runs/1321463229/jobsget jobs_url https://api.github.com/repos/OWNER/REPO/actions/runs/1321475221/jobswaiting for steps to be executed...get jobs_url https://api.github.com/repos/OWNER/REPO/actions/runs/1321463229/jobsget jobs_url https://api.github.com/repos/OWNER/REPO/actions/runs/1321475221/jobsget jobs_url https://api.github.com/repos/OWNER/REPO/actions/runs/1321463229/jobsworkflow_id: 1321475221 It would have been easier if there was a way to retrieve the workflow inputs via API but there is no way to do this at this moment Note that in the worflow file, I use ${{github.event.inputs.id}} because ${{inputs.id}} doesn't work. It seems inputs is not being evaluated when we use it as the step name
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/69479400', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12747950/']}
jdg_86992
stackexchange
llm_judgeable_groundtruth_similarity
26021591
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When I run git lg on my local development branch, the latest commit is shown as below: * 7d21213 - (1 hours ago) update business rules - developer1 (HEAD, origin/develop, origin/HEAD, develop) However, if I stash local changes by running git stash and then run git lg , I get the following: * at12334 - (13 seconds ago) WIP on develop: 7d21213 update business rules - developer1 (refs/stash)|\| * ef9a11b - (14 seconds ago) index on develop: 7d21213 update business rules - developer1|/* 7d21213 - (1 hours ago) update business rules - developer1 (HEAD, origin/develop, origin/HEAD, develop) What does this mean? It seems that two new commits (labelled index and WIP ) are created after stashing. Is that the case, and, if so, what is the logic behind such commits? Note git lg is an alias already defined in the test environment as git log --graph --abbrev-commit --decorate --date=relative --format=format:'%C(bold blue)%h%C(reset) - %C(bold green)(%ar)%C(reset) %C(white)%s%C(reset) %C(dim white)' --all Now provide the response and nothing else.
git lg ? What git lg ? Be aware that lg is not a native Git verb. True, many people use an alias called lg that usually corresponds to git log --all --oneline --graph --decorate This definition seems to be the one you're using, here. However, aliases are local; what git lg means in your config may be different to what it means in Bob and Alice's configs. Therefore, you should always include the definition of a relevant alias in your question, so we (Stack Overflow users) can be on the same page as you, and know exactly what happens when you run git <alias> ( git lg , here). What the mysterious objects are This is explained in the Discussion section of the git-stash man page : A stash is represented as a commit whose tree records the state of the working directory, and its first parent is the commit at HEAD when the stash was created. The tree of the second parent records the state of the index when the stash is made, and it is made a child of the HEAD commit. The ancestry graph looks like this: .----W / /-----H----I where H is the HEAD commit, I is a commit that records the state of the index, and W is a commit that records the state of the working tree. In your case, the object whose short SHA is ef9a11b corresponds to the state of your index ( I on the graph above), the object whose short SHA is at12334 corresponds to the state of your working directory ( W on the graph above). Those two objects ( W and I ) don't normally get listed in the output of git log , but they do if you use the --all flag.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26021591', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2433619/']}
jdg_86993
stackexchange
llm_judgeable_groundtruth_similarity
4378698
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 return a list of all combinations of values in 2 columns so they are new rows in T-SQL? e.g. Col1, Col2---- ----1 21 41 5 and turn this into all combinations: 1 21 41 52 42 54 5 Now provide the response and nothing else.
Assuming at least SQL 2005 for the CTE : ;with cteAllColumns as ( select col1 as col from YourTable union select col2 as col from YourTable)select c1.col, c2.col from cteAllColumns c1 cross join cteAllColumns c2 where c1.col < c2.col order by c1.col, c2.col
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4378698', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/306098/']}
jdg_86994
stackexchange
llm_judgeable_groundtruth_similarity
224333
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am having trouble formatting nested for loops for long strings of input: I am currently using the below nested for loops to name output files from a separate program that I have omitted: #!/bin/bashfor hemi in lh rhdo for measure in thickness area volume meancurv gauscurv foldind curvind do echo ${hemi}"--"${measure} donedone I would like to be able to format the loops like below to facilitate running multiple different loops with much longer array lists that may need to be modified. Only needing to modify the list in one place will greatly reduce the chance for errors/omissions etc: #!/bin/bashhemi=( lh rh )measure=( thickness area volume meancurv gauscurv foldind curvind )for((i=${hemi[${i}]};i<2;i++));do for((j=${measure[${j}]};j<7;j++));do echo ${hemi[${i}]}"--"${measure[${j}]} donedone This is the output I am getting and I am not able to figure out what I am doing wrong: lh--thicknesslh--arealh--volumelh--meancurvlh--gauscurvlh--foldindlh--curvind./for_loop_testing.sh: line 7: ((: j=: syntax error: operand expected (error token is "=") Now provide the response and nothing else.
Let me offer a simplified version: for i in "${hemi[@]}"; do for j in "${measure[@]}"; do echo "$i--$j" donedone The point is that "${array[@]}" expands to all array elements, so here we just iterate over all elements, put them into variables i and j , and later print them. As a side note: don't forget to put double quotes around variables and arrays, especially if any element can contain whitespaces.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/224333', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/129191/']}
jdg_86995
stackexchange
llm_judgeable_groundtruth_similarity
6264576
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 determine number of integer digits and the number of digits after decimal in a number like 234.12413 in Java. Now provide the response and nothing else.
A double is not always an exact representation. You can only say how many decimal places you would have if you converted it to a String. double d= 234.12413;String text = Double.toString(Math.abs(d));int integerPlaces = text.indexOf('.');int decimalPlaces = text.length() - integerPlaces - 1; This will only work for numbers which are not turned into exponent notation. You might consider 1.0 to have one or no decimal places.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6264576', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/672764/']}
jdg_86996
stackexchange
llm_judgeable_groundtruth_similarity
59344
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'm choosing components to set up a pc aimed to run large symbolic computations in Mathematica 9.0 under Windows 7 64 Bit Pro. I have a limited budget therefore I'm considering this system: Mother Board Asrock Z97 Extreme 4 cpu Intel Haswell Core i5-4690K (AVX2, BMI, TSX) ram HyperX Fury Memory Black Memorie RAM, 32 GB, 1866 MHz HX318C10FBK2/16 and I have no chance to buy a second machine if the first prove to be badly effective. At present moment, I have no money for a GPU video card. May be in future I can add one. Does Mathematica's standard licence allow the use of all features of this hardware ? Does the hardware lack some major features Mathematica could make use of ? Thanks !! Now provide the response and nothing else.
Memory size and speed are critical for only a few programs such as databases, video or audio processing, Mathematica, and similar applications that use the functional programming model. Because it's usually not critical for performance, memory is always the hardware component that is least well documented by PC manufacturers. It is also where they try to save a few bucks. Default memory speeds are always very conservative because memory issues are so hard to isolate. This means that almost any memory over-clocking will get you a measurable improvement for very little risk. Once you have the additional processors to enable parallelism, memory is the primary tuning knob that you want to adjust in order to speed up Mathematica. 32 gigabytes of memory is a goodly amount by today’s standards, but you might actually be happier with 16 gigabytes of slightly faster memory that can be over-clocked to improve buffer transfer speed and random access speed. 1866 is fairly slow memory by today's standards. The newest DDR4 memory is now available at 3300, but that won't work with a Z97 motherboard. If you’re interested in a few, or a lot, of over-clocking options then read on. The Z97 chipset over-clocks well and "enthusiast" motherboards such as the one you mentioned have an overwhelming array of over-clocking settings that you can tweak until you run out of patience. The memory and motherboard makers will each have forums with posts that discuss dozens of settings that will work, but may interact weirdly. They can advise you on the free benchmark programs that you can use to measure results. Tweak memory before you tweak the CPU. Be VERY cautious when applying more voltage. Go slow. Measure the result. The last time I built a serious machine I spent a week tweaking memory, but the results were about 150% over default memory speed. If that sounds like too much work, and it is a lot of work, just go with 32 gigabytes of slightly slower memory and apply a few of the simplest memory setting tweaks. Sometimes this can be as simple as clicking a BIOS option labeled AutoOverClock enable. Note: Once you have your system be sure to modify the Windows swapfile size from "system determined" to a pre-allocated swapfile that is either 1X, 1.5X, or 2X your total RAM size. It can be split over 2 disks.Personal note: I am a rank amateur with Mathematica, but I do hardware/software performance tuning for a living. Memory constrained applications were common 35 years ago, but are now very rare.
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/59344', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/12659/']}
jdg_86997
stackexchange
llm_judgeable_groundtruth_similarity
7473081
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using openrowset to import a csv file into SQL Server. One of the columns in the csv file contains numbers in scientific notation (1.08E+05) and the column in the table it is being inserted By default it is importing the value as 1 and ignoring the .08E+05. I have tried using cast() and convert() to convert the value directly when the query is executed as well as setting up the datatype in the table as a character string and importing it as such. All of these methods have the same behavior where the .08E+05 is ignored. Is there a way to have the value imported as 108000 instead of 1 without the .08E+05 without having to change the csv file itself? Setting up the datatype as a varchar and reading in the csv file appears to have the same effect with the following code: CREATE TABLE #dataTemp (StartDate datetime, Value varchar(12))SET @insertDataQuery = 'SELECT Date, CSVValue from OpenRowset(''MSDASQL'', ''Driver={Microsoft Text Driver (*.txt; *.csv)}; DefaultDir=' SET @insertDataQuery = @insertDataQuery + 'C:\Data\;'',''SELECT * FROM '+ '11091800.csv' + ''')'INSERT INTO #dataTemp EXEC(@insertDataQuery)SELECT * FROM #dataTemp Not all of the values in the CSV file have the scientific notation and the value without it, e.g. 81000 come across without issue. Now provide the response and nothing else.
For BULK INSERT methodologies I've often found it simpler to first move the data into a table of all varchars, then get rid of extraneous things like quoted delimiters and fix formatting. I remember having a heck of a time getting rid of the scientific notation, you can just play with the varchar table until you get it right. I remember attempting all kinds of precision/scale combinations until I finally found one that was compatible. I think for me it was FLOAT then DECIMAL(24,12) ... SELECT CONVERT(DECIMAL(24, 12), CONVERT(FLOAT, '1.08E+05')); EDIT adding what I did to try to repro and/or demonstrate a less convoluted way. I created a very simple CSV file: StartDate,Value20110808,8100020110808,1.08E+05 Then I ran the following code (for some reason I can't get MSDASQL to run on my machine to save my life): CREATE TABLE #dataTemp(StartDate DATETIME, Value VARCHAR(32));BULK INSERT #dataTemp FROM 'C:\data\whatever.csv' WITH (ROWTERMINATOR='\n', FIELDTERMINATOR=',', FIRSTROW = 2);SELECT * FROM #dataTempGOSELECT StartDate, CONVERT(INT, CONVERT(FLOAT, Value)) FROM #dataTemp;GODROP TABLE #dataTemp; Results: StartDate Value----------------------- --------2011-08-08 00:00:00.000 810002011-08-08 00:00:00.000 1.08E+05StartDate (No column name)----------------------- ----------------2011-08-08 00:00:00.000 810002011-08-08 00:00:00.000 108000
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7473081', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/78736/']}
jdg_86998
stackexchange
llm_judgeable_groundtruth_similarity
3914956
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 $y$ be an integer.Prove that $$(2y-1)^2 -4$$ is not a perfect square. I Found this question in a discrete math book and tried solving it by dividing the question into two parts: $$y = 2k , y = 2k + 1$$ But that got me nowhere. Now provide the response and nothing else.
For the sake of contradiction write $(2y-1)^2-4=n^2$ where $n$ is an integer. Equivalently $$4=(2y-1-n)(2y-1+n).$$ Difference between the two factors is $2n$ , i.e. even. Only ways to factor $4$ with factors that differ by even number are $(-2)\cdot(-2)$ and $2 \cdot 2$ , both cases are impossible as they imply $n=0$ and $(2y-1)^2=4$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3914956', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/837846/']}
jdg_86999
stackexchange
llm_judgeable_groundtruth_similarity
279210
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: For example, this is the gate charge curve of a p-MOSFET: Let's say this p-Mosfet works as a simple high-side switch for a load. This load will have significantly more resistance than the mosfet in it's ON-State, so the voltage across the MOSFET will be very small. I assume the ID is the current that will flow in ON state and that VDS is the voltage in OFF state here, is that correct? Also, how would this curve change if the Id was very low, 1mA? (For example, we're switching a 24V supply for a 24k Ohm load, the voltage drop across this particular p-mosfet would be in the vicinity of 5mV in that case. In other words, I need to know how the total gate charge to switch the MOSFET will change if I'm switching a load with much more resistance than the R_DS_ON. Now provide the response and nothing else.
how would this curve change if the Id was very low, 1mA? (For example, we're switching a 24V supply for a 24k Ohm load... how the total gate charge to switch the MOSFET will change if I'm switching a load with much more resistance than the R_DS_ON. The Gate charge graphs supplied in most datasheets don't cover this scenario, so I decided to do my own tests. The answer is:- probably not much. I tested a BS107 on a 12V supply with various loads ranging from 0.1mA to 100mA, driving the Gate with 10uA constant current to measure the accumulated charge. At all load currents the time for the Gate to reach +5V was 84us, showing that the same amount of charge was accumulated. However there was a noticeable change in the 'plateau' voltage that occurs due to Miller effect as the Drain voltage goes down, which ranged from 1.8V at 0.1mA to 3V at 100mA. Here is the scope trace for 1mA load current, showing Gate voltage plateauing just below 2V. At lower and higher currents the waveform was the same except for the plateau being at different voltages. While the Gate voltage is plateauing the FET is operating in its linear region dissipating high power, so when switching high current you need to get through it quickly. However at low current the plateau voltage is lower and dissipation is less of a concern, so you might be able to get away with weaker and/or lower voltage Gate drive.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/279210', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/135086/']}
jdg_87000
stackexchange
llm_judgeable_groundtruth_similarity
1555039
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In here: http://ocw.mit.edu/courses/mathematics/18-06sc-linear-algebra-fall-2011/positive-definite-matrices-and-applications/symmetric-matrices-and-positive-definiteness/MIT18_06SCF11_Ses3.1sum.pdf A positive definite matrix is a symmetric matrix A for which all eigenvalues are positive. - Gilbert Strang I have heard of positive definite quadratic forms, but never heard of definiteness for a matrix. Because definiteness is higher dimensional analogy for whether ifsomething is convex (opening up) or concave (opening down). It doesnot make sense to me to say a matrix is opening up, or matrix isopening down. Therefore it does not make sense to say that a matrix has definiteness. In addition, when we say $M \in \mathbb{R}^{n \times n}$ positivedefinite, what is the first thing we do? We plug $M$ into a function(al)$x^T (\cdot) x$ and check whether the function is positive for all $x \in \mathbb{R}^n$. Clearly, that means we are defining thisdefiniteness with respect to $x^T (\cdot) x$ and NOT $M$ itself. Furthermore, when matrix have complex eigenvalues, then we ditch thenotion of definiteness property all together. Clearly, definitenessis a flimsy property for matrices if we can just throw it away when it becomes inconvenient. I will grant you that if we were to define positive definite matrices, we should only define with respect to symmetric matrices. This is the definition on Wikipedia, the definition used by numerous linear algebra books and many applied math books. But then when confronted with a matrix of the form $$\begin{bmatrix} 1 & -1 \\ 0 & 1 \end{bmatrix}$$ I still firmly believe that this matrix is not positive definite because it is not symmetric. Because to me positive definiteness implies symmetry. To what degree is it widely agreed upon in the math community that a positive definite matrix is defined strictly with respect to symmetric matrices and why only with respect to symmetric matrices? Now provide the response and nothing else.
The positive definiteness (as you already pointed out) is a property of quadratic forms. However, there is a "natural" one-to-one correspondence between symmetric matrices and quadratic forms, so I really cannot see any reason why not to "decorate" symmetric matrices with positive definiteness (and other similar adjectives) just because it is in "reality" the form they define which actually has this property. I can see this one-to-one correspondence as one of the reasons why the symmetry should be implicitly assumed when talking about positive definite matrices. One can of course devise a different name for this property, but why? In addition, positive definite matrix is a pretty standard term so if you continue reading on matrices I'm sure you will find it more and more often. Some authors (not only on Math.SE) allow positive definite matrices to be nonsymmetric by saying that $M$ is such that $x^TMx>0$ for all nonzero $x$. In my opinion this adds more confusion than good (not only on Math.SE). Also note that (with a properly "fixed" inner product) such a definition would not even make sense in the complex case if the matrix was allowed to be non-Hermitian ($x^*Mx$ is real for all $x$ if and only if...). Anyway, for real matrices, it of course makes sense to study nonsymmetric matrices giving a positive definite quadratic form through $x^TMx$ (which effectively means that the symmetric part is positive definite). However, I find denoting them as positive definite quite unlucky.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1555039', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/105951/']}
jdg_87001
stackexchange
llm_judgeable_groundtruth_similarity
3402178
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I just had some weird behavior from a version of g++ for Windows that I got with Strawberry Perl. It allowed me to omit a return statement. I have a member function that returns a structure consisting of two pointers, called a boundTag : struct boundTag Box::getBound(int side) { struct boundTag retBoundTag; retBoundTag.box = this; switch (side) { // set retBoundTag.bound based on value of "side" }} This function gave me some bad output, and I discovered that it had no return statement. I had meant to return retBoundTag but forgot to actually write the return statement. Once I added return retBoundTag; everything was fine. But I had tested this function and gotten correct boundTag output from it. Even now, when I remove the return statement, g++ compiles it without warning. WTF? Does it guess to return retBoundTag ? Now provide the response and nothing else.
Omitting the return statement in a non-void function [Except main() ] and using the returned value in your code invokes Undefined Behaviour . ISO C++-98[Section 6.6.3/2] A return statement with an expression can be used only in functions returning a value; the value of the expression is returned to the caller of the function. If required, the expression is implicitly converted to the return type of the function in which it appears. A return statement can involve the construction and copy of a temporary object ( class.temporary ). Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function . For example int func(){ int a=10; //do something with 'a' //oops no return statement}int main(){ int p=func(); //using p is dangerous now //return statement is optional here } Generally g++ gives a warning: control reaches end of non-void function . Try compiling with -Wall option.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3402178', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/410312/']}
jdg_87002
stackexchange
llm_judgeable_groundtruth_similarity
58075461
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Problem: Give the first proper noun: Milk Give the second proper noun: float The words together form: Milkfloat noun1 = input("Give the first proper noun: ")noun2 = input("Give the second proper noun: ")print("The words together form: "='noun1'+'noun2') "='noun1'+'noun2' This doesn't work. Can anyone help? Thanks in advance. Now provide the response and nothing else.
When using Flutter Official path_provider package, getExternalStorageDirectory() will always return path to /storage/emulated/0/ your-package-name /files. To get /storage/emulated/0/ , you can used a Third-party package ext_storage . Below code will return your desired Directory path var externalDirectoryPath = await ExtStorage.getExternalStorageDirectory(); print(path); // /storage/emulated/0 Now to create a Folder, you can use the below function: //this will create a Folder in the storage/emulated/0new Directory(externalDirectoryPath +'/YourfolderName') .create() .then((Directory directory) { print(directory.path); });; '
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/58075461', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11209149/']}
jdg_87003
stackexchange
llm_judgeable_groundtruth_similarity
10646775
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 highlight the current menu you have click. I'm using CSS, but it is now working. here is my css code: #sub-header ul li:hover{ background-color: #000;}#sub-header ul li:hover a{ color: #fff; }#sub-header ul li.active{ background-color: #000; }#sub-header ul li.active a{ color: #fff; } here is my html: <div id="sub-header"> <ul> <li> <a href="index.php">Home</a> </li> <li> <a href="contact.php">Contact Us</a> </li> <li> <a href="about.php">About Us</a> </li> </ul></div> This is what I like when I hover and if the menu is active Hover is okay, The problem is when I after click the menu the black ground is not display @Jonathan, I have already solve it and it is more simply than what you have gave. this is my answer: $(function(){ // this will get the full URL at the address bar var url = window.location.href; // passes on every "a" tag $("#sub-header a").each(function() { // checks if its the same on the address bar if(url == (this.href)) { $(this).closest("li").addClass("active"); } });}); then on my css file: .active { background-color: #000; }/* to override the existing css for "a" tag */#sub-header .active a{ color: #fff; } Now provide the response and nothing else.
Add a class to the body of each page: <body class="home"> Or if you're on the contact page: <body class="contact"> Then take this into consideration when you're creating your styles: #sub-header ul li:hover,body.home li.home,body.contact li.contact { background-color: #000;}#sub-header ul li:hover a,body.home li.home a,body.contact li.contact a { color: #fff; } Lastly, apply class names to your list items: <ul> <li class="home"><a href="index.php">Home</a></li> <li class="contact"><a href="contact.php">Contact Us</a></li> <li class="about"><a href="about.php">About Us</a></li></ul> This point, whenever you're on the body.home page, your li.home a link will have default styling indicating it is the current page.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10646775', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/879766/']}
jdg_87004
stackexchange
llm_judgeable_groundtruth_similarity
4350552
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: There are two different statements that are supposed to be equivalent reformulations of the Triangle Removal Lemma from combinatorics. One says that given any $f(n)\in o(n^3)$ , there is some $g(n)\in o(n^2)$ such that any $n$ -vertex graph with at most $f(n)$ triangles can be made triangle-free by removing at most $g(n)$ edges. Another states that for every $\epsilon > 0$ , there is some $\delta(\epsilon)>0$ such that any graph on $n$ vertices with at most $\delta n^3$ triangles can be made triangle-free by eliminating at most $\epsilon n^2$ edges. Now in this question , the second of these was shown to imply the first. As inept as this sounds, I was simply unable to see why the first implies the second. More generally, I have a major lack of intuition as to why these might be equivalent statements: the first says that for any $f(n)$ (which controls the triangles) there is some $g(n)$ (controlling the edges) whereas the second version says that for every $\epsilon$ (controlling the edges ) there is some $\delta$ (controlling the triangles ), thus my intuition is crying out to me saying that the quantifiers have been reversed so these statements can't possibly encode the same information. Could someone explain why first of these statements implies the second and, if possible, why my (intuitive/soft) concern about quantifier reversal isn't correct? Now provide the response and nothing else.
Why the quantifiers cannot be any other way First of all, let me address what's going on with quantifier reversal. We may check that out of 8 possibilities for the quantifiers (we may put $\forall$ or $\exists$ on each variable, and we can put them in either order): The only interesting way to state the first lemma is $\forall f(n) \in o(n^3)$ $\exists g(n) \in o(n^2)$ . The only interesting way to state the second lemma is $\forall \epsilon>0$ $\exists \delta>0$ . I will not check all $16$ cases here, they're mostly boring, but here is why neither lemma can be stated in the form of the other. If we state the first lemma as $\forall g(n) \in o(n^2)$ $\exists f(n) \in o(n^3)$ , we state a much weaker result. The proof is: for any $g(n) \in o(n^2)$ , pick $f(n) = g(n)$ . It is true that in an $n$ -vertex graph with at most $g(n)$ triangles, we can delete at most $g(n)$ edges and get a triangle-free graph: delete an arbitrary edge from each triangle. If we state the second lemma as $\forall \delta>0$ $\exists \epsilon>0$ , we also state a much weaker result. The proof is: for any $\delta>0$ , pick $\epsilon = \frac12$ . It is true that in an $n$ -vertex graph with any number of triangles you like, we can delete at most $\frac12n^2$ edges and get a triangle-free graph: delete all the edges. Why these quantifiers actually make sense together Okay, but why is this happening? The reason is that there are extra quantifiers hidden inside the $o(n^2)$ and $o(n^3)$ : We can unpack " $f(n) \in o(n^3)$ " as "for every $\delta>0$ , there is an $n_0$ such that if $n>n_0$ , then $f(n) \le \delta n^3$ . Since we assume we are given an $f(n) \in o(n^3)$ , this definition lets us pick any $\delta>0$ we like and assume our graph has at most $\delta n^3$ triangles - just by taking $n$ large enough. This is a lot like proving $\exists \delta > 0$ , which also lets us pick $\delta$ . We can unpack " $g(n) \in o(n^2)$ " as "for every $\epsilon>0$ , there is an $n_0$ such that if $n>n_0$ , then $g(n) \le \epsilon n^2$ . In order to construct $g(n)$ , we must make sure that for all $\epsilon>0$ , there is a large enough $n$ that we only delete at most $\epsilon n^2$ edges. From point 1, "large enough $n$ " means "we can pick the $\delta>0$ we want". These hidden quantifiers inside the little-o statements of the first lemma are actually the quantifiers corresponding to the visible quantifiers of the second lemma. Why the first lemma implies the second This is a bit long, and essentially the reason for that is we need triangle removal to give us a "nice" dependency between triangles and edges. The $o(n^3)$ and $o(n^2)$ only say what is going on as $n \to \infty$ , and we'll need to work to fill in the gaps. Let $\epsilon>0$ . Define $f(n)$ as follows: for each $n$ , $f(n)$ is the largest value $t \in \{0,\dots,\binom n3\}$ such that the statement "If an $n$ -vertex graph has at most $t$ triangles, it can be made triangle-free by removing at most $\frac14\epsilon n^2$ edges" holds. If $f(n)$ were $o(n^3)$ , then the first lemma would actually give us much more: a function $g(n)$ which is $o(n^2)$ , and can replace $\frac14\epsilon n^2$ in the statement above. Eventually, for large enough $n$ , $g(n)$ is less than $\frac14\epsilon n^2 - 1$ . At this point, if a graph has at most $f(n)+1$ triangles, it can also be made triangle-free by removing at most $\frac14\epsilon n^2$ edges: remove a single edge from some triangle (leaving at most $f(n)$ triangles), then remove $g(n)$ more edges to destroy all remaining triangles. This contradicts our choice of $f(n)$ : for this $n$ , it could have been $1$ higher! Therefore $f(n)$ is not $o(n^3)$ . In other words, there is a $\delta>0$ such that for infinitely many values of $n$ we have $f(n) > \delta n^3$ . But we need the proof to work for arbitrary $n$ , not just for these special values. So take any $n$ and take any $n$ -vertex graph with at most $\delta n^3$ triangles, then choose some $m > 10n$ such that $f(m) > \delta m^3$ . Write $m = qn + r$ with $0 \le r < n$ , noting that our choice of $m$ means $q \ge 10$ . From $G$ , construct an $m$ -vertex graph $H$ by replacing every vertex of $G$ by $q$ vertices and every edge by a copy of $K_{q,q}$ , then adding $r$ isolated vertices. Each triangle in $G$ corresponds to a complete tripartite graph $T \cong K_{q,q,q}$ in $H$ , with $q^3$ triangles, and there are no other triangles in $H$ , thus $H$ has at most $\delta n^3 q^3 \le \delta m^3$ triangles. Therefore it is possible to remove $\frac14 \epsilon m^2$ edges from $H$ to make it triangle-free. Now we try to imitate that edge deletion in $G$ , with some loss of efficiency. Delete from $G$ every edge such that the corresponding copy of $K_{q,q}$ in $H$ lost at least $\frac13 q^2$ of its edges. This cannot delete more than $\epsilon n^2$ edges, because then we'd be deleting $(\frac13q^2)(\epsilon n^2) > \frac14 \epsilon m^2$ edges from $H$ . (Here we use $m < qn+n$ and $q \ge 10$ .) Now we must check that this destroys every triangle in $G$ . Each triangle in $G$ , again, corresponds to a complete tripartite graph $T \cong K_{q,q,q}$ in $H$ , with $q^3$ triangles, and each edge of $T$ is contained in only $q$ of those triangles, so at least $q^2$ of the $3q^2$ edges in $T$ are deleted when $H$ is made triangle-free. By averaging, one of the three copies of $K_{q,q}$ in $T$ loses at least $\frac13 q^2$ of its edges. Therefore one of the edges of this triangle in $G$ will be deleted by the rule in the previous paragraph. So we've successfully removed all triangles from $G$ with only $\epsilon n^2$ deleted edges.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4350552', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/405188/']}
jdg_87005
stackexchange
llm_judgeable_groundtruth_similarity
3370004
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 know that what is static block in c or c++ with an example? I know what is static but what is the difference between static and static block? Now provide the response and nothing else.
Another alternative is that you might be looking for the analogy of a staticblock in Java. A block of code that is run when the application is loaded.There is no such thing in C++ but it can be faked by using the constructor of astatic object. foo.cpp:struct StaticBlock { StaticBlock(){ cout << "hello" << endl; }}static StaticBlock staticBlock;void main(int, char * args[]){} HOWEVER. I've been bitten by this before as it's a subtle edge case of the C++standard. If the static object is not reachable by any code called by main theconstructor of the static object may or may not be called. I found that with gcc hello will get output and with visual studio it willnot.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3370004', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/223622/']}
jdg_87006
stackexchange
llm_judgeable_groundtruth_similarity
50484447
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 anyway to explicitly cast/coerce sbyte[] or byte[] to a bool[] char[] to a short[] / ushort[] In CIL you regularly see something such as stelem Type sbyte (ldloc pArray) ldc_i4 1 ldc_i4 0 which is doing pArray[1] = true where pArray is a one-dimensional array of type bool[] . I want to replicate this in c# by doing (sbyte[])pArray[1] = 1; Unfortunately this is not allowed by the C# compiler. Now provide the response and nothing else.
Undocumented trick, play at your own risk: (shown for example here and in many other places) [StructLayout(LayoutKind.Explicit)]public struct ConvSByteBool{ [FieldOffset(0)] public sbyte[] In; [FieldOffset(0)] public bool[] Out;} and then: var bytes = new sbyte[] { -2, -1, 0, 1, 2 };var conv = new ConvSByteBool { In = bytes }.Out;bool b1 = conv[0]; // truebool b2 = conv[1]; // truebool b3 = conv[2]; // falsebool b4 = conv[3]; // truebool b5 = conv[4]; // true Note that this trick is tottally incompatible with generics. No Conv<T, U> ! The trick works best when the size of the element in source and target is the same ( sizeof(sbyte) == sizeof(bool) ). Otherwise there are some limitations (described in the linked question above).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50484447', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6555213/']}
jdg_87007
stackexchange
llm_judgeable_groundtruth_similarity
3430181
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: First question Please, could you explain me how simpliest ACL could be implemented in MVC. Here is the first approach of using Acl in Controller... <?phpclass MyController extends Controller { public function myMethod() { //It is just abstract code $acl = new Acl(); $acl->setController('MyController'); $acl->setMethod('myMethod'); $acl->getRole(); if (!$acl->allowed()) die("You're not allowed to do it!"); ... }}?> It is very bad approach, and it's minus is that we have to add Acl piece of code into each controller's method, but we don't need any additional dependencies! Next approach is to make all controller's methods private and add ACL code into controller's __call method. <?phpclass MyController extends Controller { private function myMethod() { ... } public function __call($name, $params) { //It is just abstract code $acl = new Acl(); $acl->setController(__CLASS__); $acl->setMethod($name); $acl->getRole(); if (!$acl->allowed()) die("You're not allowed to do it!"); ... }}?> It is better than previous code, but main minuses are... All controller's methods should be private We have to add ACL code into each controller's __call method. The next approach is to put Acl code into parent Controller, but we still need to keep all child controller's methods private. What is the solution? And what is the best practice?Where should I call Acl functions to decide allow or disallow method to be executed. Second question Second question is about getting role using Acl. Let's imagine that we have guests, users and user's friends. User have restricted access to viewing his profile that only friends can view it. All guests can't view this user's profile. So, here is the logic.. we have to ensure that method being called is profile we have to detect owner of this profile we have to detect is viewer is owner of this profile or no we have to read restriction rules about this profile we have to decide execute or not execute profile method The main question is about detecting owner of profile. We can detect who is owner of profile only executing model's method $model->getOwner(), but Acl do not have access to model. How can we implement this? Now provide the response and nothing else.
First part/answer (ACL implementation) In my humble opinion, the best way to approach this would be to use decorator pattern , Basically, this means that you take your object, and place it inside another object, which will act like a protective shell. This would NOT require you to extend the original class. Here is an example: class SecureContainer{ protected $target = null; protected $acl = null; public function __construct( $target, $acl ) { $this->target = $target; $this->acl = $acl; } public function __call( $method, $arguments ) { if ( method_exists( $this->target, $method ) && $this->acl->isAllowed( get_class($this->target), $method ) ){ return call_user_func_array( array( $this->target, $method ), $arguments ); } }} And this would be how you use this sort of structure: // assuming that you have two objects already: $currentUser and $controller$acl = new AccessControlList( $currentUser );$controller = new SecureContainer( $controller, $acl );// you can execute all the methods you had in previous controller // only now they will be checked against ACL$controller->actionIndex(); As you might notice, this solution has several advantages: containment can be used on any object, not just instances of Controller check for authorization happens outside the target object, which means that: original object is not responsible for access control, adheres to SRP when you get "permission denied", you are not locked inside a controller, more options you can inject this secured instance in any other object, it will retain the protection wrap it & forget it .. you can pretend that it is the original object, it will react the same But , there are one major issue with this method too - you cannot natively check if secured object implements and interface ( which also applies for looking up existing methods ) or is part of some inheritance chain. Second part/answer (RBAC for objects) In this case the main difference you should recognize is that you Domain Objects (in example: Profile ) itself contains details about owner. This means, that for you to check, if (and at which level) user has access to it, it will require you to change this line: $this->acl->isAllowed( get_class($this->target), $method ) Essentially you have two options: Provide the ACL with the object in question. But you have to be careful not to violate Law of Demeter : $this->acl->isAllowed( get_class($this->target), $method ) Request all the relevant details and provide the ACL only with what it needs, which will also make it a bit more unit-testing friendly: $command = array( get_class($this->target), $method );/* -- snip -- */$this->acl->isAllowed( $this->target->getPermissions(), $command ) Couple videos that might help you to come up with your own implementation: Inheritance, Polymorphism, & Testing Don't Look For Things! Side notes You seem to have the quite common ( and completely wrong ) understanding of what Model in MVC is. Model is not a class . If you have class named FooBarModel or something that inherits AbstractModel then you are doing it wrong. In proper MVC the Model is a layer, which contains a lot of classes. Large part of the classes can be separated in two groups , based on the responsibility: - Domain Business Logic ( read more : here and here ): Instances from this group of classes deal with computation of values, check for different conditions, implement sales rules and do all the rest what you would call "business logic". They have no clue how data is stored, where it is stored or even if storage exists in first place. Domain Business object do not depend on database. When you are creating an invoice, it does not matter where data comes from. It can be either from SQL or from a remote REST API, or even screenshot of a MSWord document. The business logic does no change. - Data Access and Storage Instances made from this group of classes are sometimes called Data Access Objects. Usually structures that implement Data Mapper pattern ( do not confuse with ORMs of same name .. no relation ). This is where your SQL statements would be (or maybe your DomDocument, because you store it in XML). Beside the two major parts, there is one more group of instances/classes, that should be mentioned: - Services This is where your and 3rd party components come in play. For example, you can think of "authentication" as service, which can be provided by your own, or some external code. Also "mail sender" would be a service, which might knit together some domain object with a PHPMailer or SwiftMailer, or your own mail-sender component. Another source of services are abstraction on to on domain and data access layers. They are created to simplify the code used by controllers. For example: creating new user account might require to work with several domain objects and mappers . But, by using a service, it will need only one or two lines in the controller. What you have to remember when making services, is that the whole layer is supposed to be thin . There is no business logic in services. They are only there to juggle domain object, components and mappers. One of things they all have in common would be that services do not affect the View layer in any direct way, and are autonomous to such an extent, that they can be ( and quit often - are ) used outside the MVC structure itself. Also such self-sustained structures make the migration to a different framework/architecture much easier, because of extremely low coupling between service and the rest of application.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/3430181', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/227523/']}
jdg_87008
stackexchange
llm_judgeable_groundtruth_similarity
2467544
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 invoke the main method which is static. I got the object of type Class , but I am not able to create an instance of that class and also not able to invoke the static method main . Now provide the response and nothing else.
// String.class here is the parameter type, that might not be the case with youMethod method = clazz.getMethod("methodName", String.class);Object o = method.invoke(null, "whatever"); In case the method is private use getDeclaredMethod() instead of getMethod() . And call setAccessible(true) on the method object.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/2467544', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/260654/']}
jdg_87009
stackexchange
llm_judgeable_groundtruth_similarity
233507
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 log out user from a web site if he is using basic authentication? Killing session is not enough, since, once user is authenticated, each request contains login info, so user is automatically logged in next time he/she access the site using the same credentials. The only solution so far is to close browser, but that's not acceptable from the usability standpoint. Now provide the response and nothing else.
Basic Authentication wasn't designed to manage logging out. You can do it, but not completely automatically. What you have to do is have the user click a logout link, and send a ‘401 Unauthorized’ in response, using the same realm and at the same URL folder level as the normal 401 you send requesting a login. They must be directed to input wrong credentials next, eg. a blank username-and-password, and in response you send back a “You have successfully logged out” page. The wrong/blank credentials will then overwrite the previous correct credentials. In short, the logout script inverts the logic of the login script, only returning the success page if the user isn't passing the right credentials. The question is whether the somewhat curious “don't enter your password” password box will meet user acceptance. Password managers that try to auto-fill the password can also get in the way here. Edit to add in response to comment: re-log-in is a slightly different problem (unless you require a two-step logout/login obviously). You have to reject (401) the first attempt to access the relogin link, than accept the second (which presumably has a different username/password). There are a few ways you could do this. One would be to include the current username in the logout link (eg. /relogin?username), and reject when the credentials match the username.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/233507', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/31141/']}
jdg_87010
stackexchange
llm_judgeable_groundtruth_similarity
4488338
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I know how to setting proxy manually and to use it in my WebView. Settings -> Wireless Networks ->mobile networks-> access point names->telkila. Now enter the proxy server address and port (which will be 80).WebView.enablePlatformNotifications(); But can i set the proxy setting from code?So my user didn't have to set manually? Thanks Now provide the response and nothing else.
There is no legal way to change your webview proxy settings programmatically. But it's possible to use java reflection to change mProxyHost value from android.net.http.RequestQueue class. It's private value and there is no setters for it, so reflection seems to be the only possible variant. I used it in my project and it works. Here is the sample of my method: private boolean setProxyHostField(HttpHost proxyServer) { // Getting network Class networkClass = null; Object network = null; try { networkClass = Class.forName("android.webkit.Network"); Field networkField = networkClass.getDeclaredField("sNetwork"); network = getFieldValueSafely(networkField, null); } catch (Exception ex) { Log.e(ProxyManager.class.getName(), "error getting network"); return false; } if (network == null) { Log.e(ProxyManager.class.getName(), "error getting network : null"); return false; } Object requestQueue = null; try { Field requestQueueField = networkClass .getDeclaredField("mRequestQueue"); requestQueue = getFieldValueSafely(requestQueueField, network); } catch (Exception ex) { Log.e(ProxyManager.class.getName(), "error getting field value"); return false; } if (requestQueue == null) { Log.e(ProxyManager.class.getName(), "Request queue is null"); return false; } Field proxyHostField = null; try { Class requestQueueClass = Class.forName("android.net.http.RequestQueue"); proxyHostField = requestQueueClass .getDeclaredField("mProxyHost"); } catch (Exception ex) { Log.e(ProxyManager.class.getName(), "error getting proxy host field"); return false; } synchronized (synchronizer) { boolean temp = proxyHostField.isAccessible(); try { proxyHostField.setAccessible(true); proxyHostField.set(requestQueue, proxyServer); } catch (Exception ex) { Log.e(ProxyManager.class.getName(), "error setting proxy host"); } finally { proxyHostField.setAccessible(temp); } } return true;}private Object getFieldValueSafely(Field field, Object classInstance) throws IllegalArgumentException, IllegalAccessException { boolean oldAccessibleValue = field.isAccessible(); field.setAccessible(true); Object result = field.get(classInstance); field.setAccessible(oldAccessibleValue); return result; }
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4488338', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/430926/']}
jdg_87011
stackexchange
llm_judgeable_groundtruth_similarity
5983776
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've seen two approaches to handling enums with properties. Is one better than the other? As a property: public enum SEARCH_ENGINE { GOOGLE("http://www.google.com"), BING("http://www.bing.com"); private final String url; private SEARCH_ENGINE(String url) { this.url = url; } public String getURL() { return url; }} As a method: public enum SEARCH_ENGINE { GOOGLE { public String getURL() {return "http://www.google.com";} }, BING { public String getURL() {return "http://www.bing.com";} }; public abstract String getURL();} Now provide the response and nothing else.
The first clearly looks cleaner to me - it makes use of the commonality that each element of the enum will have a fixed String URL which is known at initialization. You're effectively repeating that "logic" in each implementation in the second version. You're overriding a method to provide the same logic ("just return a string which is known at compile-time") in each case. I prefer to reserve overriding for changes in behaviour . I suggest making the url field private though, in the first.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5983776', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/724835/']}
jdg_87012
stackexchange
llm_judgeable_groundtruth_similarity
738889
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The question asks to prove: $$ \frac{\tan A}{1-\cot A}+ \frac{\cot A}{1-\tan A}=\sec A \csc A + 1$$ using only: $$ \sin^2A+\cos^2A=1\;\; \text{ & }\; \;\tan^2 A+1=\sec^2 A\;\; \text{ & } \;\; \cot^2 A+1=\csc^2 A $$ My solution is join the two fractions, then multiplying numerator and denominator by $\tan^2 A$ to have only tangent functions: $$\frac{\tan A-\tan^2 A +\cot A-\cot^2 A}{ 2-\cot A-\tan A } \rightarrow \frac{\tan^3 A-\tan^4 A+\tan{A}-1}{2\tan^2 A -\tan A -\tan^3 A}$$ This then apparently factorises (I would never have spotted the top, it's only after trying it on Mathematica that I realised it did) to give: $$ \frac{-(\tan A-1)^2(\tan^2 A+\tan A+1)}{-\tan A(\tan A-1)^2} =\cot A(\tan^2 A+\tan A+1)=1+\cot A+\tan A$$ which then simplifies down to the required result, but needless to say this isn't very elegant and not inline with the previous problems that whilst not easy didn't involve factoring a quartic which leads me to believe there is certainly an easier way to do it hence the question, I just can't seem to see it (I've done too many for today!). Now provide the response and nothing else.
I can't think of an "elegant" solution, but typically just converting everything to sin/cos is the way to go. For example, let $x=\sin(A)$ and $y=\cos(A)$. Then,$$ \frac{x/y}{1-y/x}+\frac{y/x}{1-x/y} = \frac{x^2/y}{x-y} - \frac{y^2/x}{x-y} = \frac{x^3-y^3}{xy(x-y)} = \frac{x^2+xy+y^2}{xy} = 1 + \frac{x^2+y^2}{xy}.$$ Now making use of the trig identity, we obtain simply $1+\frac{1}{xy}$, which is the result we want.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/738889', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/115937/']}
jdg_87013
stackexchange
llm_judgeable_groundtruth_similarity
43880426
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/Django proyect. Due to some rolls back, and other mixed stuff we ended up in a kind of odd scenario. The current scenario is like this: DB has the correct tables DB can't be rolled back or dropped Code is up to date Migrations folder is behind the DB by one or two migrations. (These migrations were applied from somewhere else and that "somewhere else" doesn't exist anymore) I add and alter some models I run makemigrations New migrations are created, but it's a mix of new tables and some tables that already exist in the DB. If I run migrate it will complain that some of the tables that I'm trying to create already exist. What I need: To be able to run the migrations and kind of "ignore" the existing tables and apply the new ones. Or any alternative way to achieve this. Is that possible? Now provide the response and nothing else.
When you apply a migration, Django inserts a row in a table called django_migrations . That's the only way Django knows which migrations have been applied already and which have not. So the rows in that table have to match the files in your migrations directory. If you've lost the migration files after they were applied, or done anything else to get things out of sync, you'll have problems.. because the migration numbers in your database refer to different migration files than the ones in your project. So before you do anything else, you need to bring things back into sync by deleting the django_migrations table rows for any migration files that you've lost somehow and can't get back. The table should contain rows for only those migrations that you do have and that were actually applied to the database correctly . Now you need to deal with any changes in your database that Django Migrations doesn't know about.. and for that there are a few options: If things worked out such that the database changes that were already applied to the database are in different migration files than the ones that weren't, then you can fix it by running your migrations one at a time using the --fake option on any changes that are in reality already in the database. The fake option just writes the row to the django_migrations table marking the migration as done. Only do this if the database does in fact already have all the changes contained in that migration file. And those migration files that contain only changes which have not been applied to the database, run without the --fake option and Django will apply them. eg: # database already has itmanage.py migrate myapp 0003 --fake # need itmanage.py migrate myapp 0004# database already has itmanage.py migrate myapp 0005 --fake If you have migration files where some but not all of the changes have been applied, then you have a bigger problem. In that case, there are several ways to go about it (choose ONLY ONE): Edit the migration files to put changes that have already been applied (whether Django did it or you did it manually does not matter) into lower number migrations, and put everything you need done into higher numbered files. Now you can --fake the lower number ones, and run the higher numbered ones as normal. Let's say you have 10 changes you made to your models, and 5 of those changes are actually in the database already, but Django doesn't know about them.. so when you run makemigrations , a new migration is created with all 10 changes. This will normally fail because the database server can't for example add a column that already exists. Move these already-applied changes out of your new migration file, into the previous (already applied) migration file. Django will then assume that these were applied with the previous migration and will not try to apply them again. You can then migrate as normal and the new changes will be applied. If you don't want to touch your older migration file, a cleaner way to do this is to first run makemigrations --empty appname to create an empty migration file. Then run makemigrations which will create another migration with all the changes that Django thinks need to be done. Move the already done migrations from that file into the empty migration you created.. then --fake that one. This will put Django's understanding of what the database looks like will be in sync with reality and you can then migrate as normal, applying the changes in the last migration file. Get rid of any new migrations you just created using makemigrations. Now, comment out or put back anything in your models that has not been applied to the database, leaving your code matching what's actually in the database. Now you can do makemigrations and migrate appname --fake and you will get things back in sync. Then uncomment your new code and run 'makemigrations' then migrate as normal and the changes will be applied. If the changes are small (for example, adding a few fields), sometimes this is easiest. If the changes are large, it isn't.... You can go ahead and (carefully) make the database changes yourself, bringing the database up to date. Now just run migrate --fake and if you didn't mess up then everything will be ok. Again, this is easy for smaller changes, not as easy for complicated ones. You can run manage.py sqlmigrate > mychanges.sql . This generates mychanges.sql containing all the SQL Django WOULD have executed against the database. Now edit that file to remove any changes that have already been applied, leaving what needs to be done. Execute that SQL using pgadmin or psql (you're using postgresql I hope). Now the changes have all been made.. so you can run manage.py migrate --fake , this will bring Django into sync with reality and you should be all set. If your SQL skills are sufficient, this is probably the most straightforward solution. I should add two warnings: First, if you apply a later migration, eg 0003_foobar.py, and then things don't work out and you decide to try going back and apply 0002_bazbuz.py, then Django will TAKE STUFF OUT OF YOUR DATABASE. For example a column you might have added in 0003 will be dropped along with its data. Since you say you can't lose data, be very careful about going back. Second, do not rush into running --fake migrations. Make sure that the entire migration you are about to fake is actually in the database already. Else it gets very confusing. If you do regret faking migrations and don't want to roll back, you can erase django's knowledge of the faked migration by deleting that row from the django_migrations table. It is ok to do this.. if you understand what you are doing. If you know that the migration really was not applied, then it's ok.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/43880426', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7776359/']}
jdg_87014
stackexchange
llm_judgeable_groundtruth_similarity
2575044
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 come up with a language syntax. I have read a bit about these three, and can't really see anything that one can do that another can't. Is there any reason to use one over another? Or is it just a matter of preference? Now provide the response and nothing else.
You have to think about EBNF and ABNF as extensions that help you just to be more concise and expressive while developing your grammars. For example think about an optional non-terminal symbol, in a BNF grammar you would define it by using intermediate symbols like: A ::= OPTIONAL OTHEROPTIONAL ::= opt_part | epsilon while with EBNF you can do it directly using optional syntax: A ::= [opt_part] OTHER Then since there's no way to express precedence in a BNF you have to use always intermediate symbols also for nested choices: BNFA ::= B CB ::= a | b | cEBNFA ::= (a | b | c) C This is true for many syntax issues that are allowed in an EBNF or ABNF grammar, thanks to syntactic sugar but not with a normal BNF . ABNF extends EBNF , allowing you to do more complicated things, like specifying how many occurrence of a symbol can be found together (i.e. 4*DIGIT ) So choosing an ABNF or an EBNF as language of choice for your grammar will make your work easier, since you will be more expressive without filling you grammar with useless symbols that will be generated anyway by your parser generator, but you won't care about them!
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2575044', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2147/']}
jdg_87015
stackexchange
llm_judgeable_groundtruth_similarity
9469870
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Some MMO Real Time Strategy games such as Travian or oGame are coded in PHP. Could you briefly explain how such a game works behind the scenes ? How does the game make real time DB updates without player requests ? Also, what kind of server load / bandwidth would one have to expect when running a RTS game such as Travian with 1000 active players ? Now provide the response and nothing else.
Even though this topic is rather old, I do think I still have a 'better' (if I may say so myself) answer to your question then the vague "the updates are done by cronjobs" answer. Travian i.e. gives you the illusion of it being real-time through the use of javascript. What actually happens in the back is the following: Player A sends an attack to player B. In the MySQL database this is recorded with a timestamp of arrival. Every time player A changes or refreshes a page a script gets launched (by using includes) that checks for any activity in regards to this player (reinforcements arriving, attacks arriving at targets etc.). The script obviously checks the current time and looks at all activities with a timestamp that is less than the current one. This means the action should have taken place. Right at that moment the action actually gets processed. This also means that if neither player A nor player B ever log in again that the attack will never be calculated, unless someone else also attacks player B - then all activities for player B and the attacking player will be processed.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9469870', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1127635/']}
jdg_87016
stackexchange
llm_judgeable_groundtruth_similarity
919119
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 want to prove the following: Let $G$ be a group of order $2^nm$, where $m$ is odd, having a cyclic Sylow $2$-subgroup. Then $G$ has a normal subgroup of order $m$. ATTEMPT: We will show that $G$ has a subgroup of order $m$.Let $\theta:G\to \text{Sym}(G)$ be the homomorphism which is defined as$$ \theta(g)=t_g, \quad \forall g\in G$$where $t_g:G\to G$ is defined as:$$ t_g(x)=gx, \quad \forall x\in G.$$Let $g$ be an element of order $2^n$ in $G$.(There exists such an element since $G$ has a cyclic Sylow $2$-subgroup.) The cyclce representation of $t_g$ is a product of $m$ disjoint cycles each of length $2^n$.Therefore $t_g$ is an odd permutation. Thus the homomorphism $\epsilon\circ \theta:G\to\{\pm 1\}$, where $\epsilon:\text{Sym}\to\{\pm 1\}$ is the sign homomorphism, is a surjection. By the First Isomprphism Theorem, we conclude that the kernel $K$ of $\epsilon\circ \theta$ is of order $2^{n-1}m$. If $n$ were equal to $1$ then we are done. If $n>1$ then note that any Sylow $2$-subgroup of $K$ is also cyclic.This is because each Sylow $2$-subgroup of $K$ is contained in a Sylow $2$-subgroup of $G$, where the latter is cyclic. Now we can inductively show that $K$ has a subgroup of order $m$. What I am struggling with is showing the normality. Can anybody please help me with this. Thanks. Now provide the response and nothing else.
Claim: If a group of order $2^nm$, $m$ odd, has cyclic Sylow-2 subgroup, then $G$ has unique subgroup of order $m$. Proof: Induction on $n$- for $n=1$, as you showed, the kernel $K$ has order $m$, which is a normal subgroup. If there is another subgroup $H$ of order $m$, then the product $KH$ is a subgroup (since $K\trianglelefteq G$) of odd order (equal to $|H|.|K|/|H\cap K|$), and is bigger than $m$ (since $H\neq K$), which is impossible since the largest odd order dividing $|G|$ is $m$. Suppose theorem is proved for groups of order $2m, 2^2m, \cdots, 2^{n-1}m$ (containing cyclic Sylow-$2$). Let $|G|=2^nm$, with cyclic Sylow-2. As you noted, kernel $K$ has order $2^{n-1}m$, which contains unique subgroup of order $m$ (by induction), say it is $L$. Thus $L$ is characteristic in $K$ and as $K$ is normal in $G$, it follows that $L\trianglelefteq G$. Again, as in previous paragraph (at the starting of proof), we can conclude that $G$ has unique subgroup of order $m$, a stronger conclusion than you expected. (Very Simple Exercise: $H$ is characteristic in $K$ and $K\trianglelefteq G$ $\Rightarrow$ $H\trianglelefteq G$. Just apply definition otherwise see this )
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/919119', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/88582/']}
jdg_87017
stackexchange
llm_judgeable_groundtruth_similarity
353414
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How can we evaluate $$\int_0^\pi\frac{1}{1+(\tan x)^\sqrt2}\ dx$$ Can you keep this at Calculus 1 level please? Please include a full solution if possible. I tried this every way I knew and I couldn't get it. Now provide the response and nothing else.
Indeed this was a Putnam question. The $\sqrt{2}$ is pretty much irrelevant. Notice $$I=\int_0^\pi\frac{dx}{1+\tan(x)^{\sqrt2}}=\int_\pi^0\frac{d(\frac{\pi}{2}-u)}{1+(\tan(\frac{\pi}{2}-u))^{\sqrt2}}=\int_0^\pi\frac{du}{1+\cot(u)^{\sqrt2}}$$ and $$\frac{1}{1+\tan(x)^{\sqrt2}}=\frac{\cos(x)^{\sqrt2}}{\cos(x)^{\sqrt2}+\sin(x)^{\sqrt2}},\qquad\frac{1}{1+\cot(u)^{\sqrt2}}=\frac{\sin(u)^{\sqrt2}}{\sin(u)^{\sqrt2}+\cos(u)^{\sqrt2}}.$$ so $$2I=\int_0^\pi\frac{dv}{1+\tan(v)^{\sqrt2}}+\int_0^\pi\frac{dv}{1+\cot(u)^{\sqrt2}}$$ $$=\int_0^\pi\left[\frac{\cos(v)^{\sqrt2}}{\cos(v)^{\sqrt2}+\sin(v)^{\sqrt2}}+\frac{\sin(v)^{\sqrt2}}{\sin(v)^{\sqrt2}+\cos(v)^{\sqrt2}}\right]dv=\int_0^\pi\frac{\cos(v)^{\sqrt2}+\sin(v)^{\sqrt2}}{\cos(v)^{\sqrt2}+\sin(v)^{\sqrt2}}dv $$ which is $\int_0^\pi1dv=\pi$. Ultimately, this is a symmetry argument.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/353414', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/64460/']}
jdg_87018
stackexchange
llm_judgeable_groundtruth_similarity
16082275
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 class that will contains static values accessable from all project. Pseudocode: class Constants: constant String API_URL : "http://api.service.com" constant Integer SOME_VALUE : 7 How can I do this with Objective-C ? Now provide the response and nothing else.
You could do it using preprocessors: #define API_URL @"http://api.service.com"#define SOME_VALUE (7) Accessing defines would be simple: [object do:API_URL]; Or you could use constants NSString * const apiURL = @"http://api.service.com";NSNumber * const someValue = @7; Accessing consts would be like accessing variables, So the string would just be a simple call. The NSNumber is an object wrapper for primitives so you'd need to access it like: someValue.intValue
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16082275', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/223386/']}
jdg_87019
stackexchange
llm_judgeable_groundtruth_similarity
35362460
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This is how example of my state looks: const INITIAL_STATE = { contents: [ {}, {}, {}, etc.. ], meta: {}} I need to be able and somehow replace an item inside contents array knowing its index, I have tried: return { ...state, contents: [ ...state.contents[action.meta.index], { content_type: 7, content_body: { album_artwork_url: action.payload.data.album.images[1].url, preview_url: action.payload.data.preview_url, title: action.payload.data.name, subtitle: action.payload.data.artists[0].name, spotify_link: action.payload.data.external_urls.spotify } } ] } where action.meta.index is index of array item I want to replace with another contents object, but I believe this just replaces whole array to this one object I'm passing. I also thought of using .splice() but that would just mutate the array? Now provide the response and nothing else.
Note that Array.prototype.map() ( docs ) does not mutate the original array so it provides another option: const INITIAL_STATE = { contents: [ {}, {}, {}, etc.. ], meta: {} } // Assuming this action object design { type: MY_ACTION, data: { // new content to replace }, meta: { index: /* the array index in state */, } } function myReducer(state = INITIAL_STATE, action) { switch (action.type) { case MY_ACTION: return { ...state, // optional 2nd arg in callback is the array index contents: state.contents.map((content, index) => { if (index === action.meta.index) { return action.data } return content }) } } }
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35362460', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/911930/']}
jdg_87020
stackexchange
llm_judgeable_groundtruth_similarity
31109
Below is a question asked on the forum datascience.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Using Embedding layer in Keras on a fairly small vocabulary (~300), I am looking at how to choose the output of this layer (dense vector) when given a 300 dimension vector. I think that the embedded vector need to have a minimum length to be able to map a given vocabulary. Now provide the response and nothing else.
The ratio of vocabulary vs embedding length to determine the size of other layers in a neural network doesn't really matter. Word embeddings are always around 100 and 300 in length, longer embedding vectors don't add enough information and smaller ones don't represent the semantics well enough. What matters more is the network architecture, the algorithm(s) and the dataset size. A simple way to understand this concept is that a bidirectional LSTM model with 50 neurons (nodes) followed by a fully connected layer of 70 neurons will outperform a simple MLP of 1000 neurons (nodes) connected to a embedding layer simply due to its architecture. Adding dropout will improve performance as well. In addition, even if the vocabulary is just 300 words, using pre-trained embeddings will probably yield better results than training the embeddings directly on the dataset. The same applies to data size, a dataset with more samples will make a better classifier than a dataset with just a couple thousand samples. In summary, it is preferable to try many architectures and cross-validate them (and/or ensemble them depending if you have a large enough dataset) with the smallest number of neurons possible and then start building up in size, depending on what computational resources you have and the speed of development you need. Large models slow down development speed whereas small models speed it up. This goes whether your vocabulary is the size of common crawl or just 300. As usual, try feature engineering (sentence length, special characters, etc.) and increase the dataset size as doing so often helps in whatever task you're trying to predict.
{}
{'log_upvote_score': 4, 'links': ['https://datascience.stackexchange.com/questions/31109', 'https://datascience.stackexchange.com', 'https://datascience.stackexchange.com/users/9461/']}
jdg_87021
stackexchange
llm_judgeable_groundtruth_similarity
165721
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 nucleus consists of protons and neutrons. Both are extremely heavy compared to electrons. Then how come they are contained within an extremely tiny space? And why does the atom consist of 99.999% empty space? I do not understand the mathematics regarding this one bit. Please give me an explanation of this phenomenon in words as far as possible :) Now provide the response and nothing else.
Suppose we have two particles that attract each other. This could be an electron attracted to the nucleus by the electromagnetic force, or two nucleons attracted by the strong force, but let's keep it general for now. Suppose these two particles are separated by a distance $r$: If the particles were for example an electron and a proton there would be an attraction between them and as we decrease $r$ the energy $E$ will decrease according to: $$ E = -\frac{A}{r} $$ for some constant $A$ that tells us how strong the attractive force between the particles is. The particles want to reduce their energy, so they will try and make the distance $r$ between them as small as possible i.e. they will try to merge together. But Heisenberg's uncertainty principle tells us that: $$ \Delta x \Delta p \ge \frac{\hbar}{2} $$ that is, if we localise a particle to within a distance $\Delta x$ its momentum becomes uncertain by an amount $\Delta p$. In our system of two particles we can, in an arm waving way, say that the uncertainty in position is around the distance between the particles. A quick rearrangement of the equation above tells us that the momentum uncertainty is related to $r$ by: $$ \Delta p \ge \frac{\hbar}{2r} $$ The reason this matters is that the energy of a system is related to its momentum by: $$ E = \frac{p^2}{2m} $$ and if we take the $\Delta p$ we calculated above and put it in this equation we get: $$ E = \frac{\hbar^2}{8r^2m} $$ So as we move the particles together the uncertainty principle means their energy increases, and this opposes the attractive force between the particles. The particles are going to end up at a distance where these two effects balance out, i.e. $$ \frac{A}{r} = \frac{\hbar^2}{8r^2m} $$ and rearranging this for $r$ gives: $$ r = \frac{\hbar^2}{8Am} $$ Since this is a very approximate argument let's ignore the constants and just write: $$ r \propto \frac{1}{Am} $$ And this immediately tells us why nuclei are smaller than atoms. The mass of nucleons is about 2,000 times greater than the mass of electrons, and our equation tells us that size reduces as mass increases. Also nuclear forces are stronger than electromagnetic forces, i.e. the constant $A$ is greater for nuclear forces, and the equation tells us that as $A$ increases $r$ decreases. Both effects mean the size of nuclei is going to be smaller than the size of atoms.
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/165721', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/73443/']}
jdg_87022
stackexchange
llm_judgeable_groundtruth_similarity
526592
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I'm making a backup script for ldap. I want the errors to go to a file in /var/log and the output to go to another file in the backup folder. Currently I'm redirecting to a temp file and then sending the temp file to the log. I'd rather do this as a 1 liner though... /usr/bin/ldapsearch -x -LLL -b "dc=contoso,dc=com" "(objectclass=*)" -h ldap.server -v 2>>/tmp/ldaptmp.err | gzip -c > /mnt/backups/ldap/`date +\%Y\%m\%d`.ldif.gz || logger -t ldapbackup -p local6.err error exit $?cat /tmp/ldaptmp.err | grep -v "ldap_initialize( ldap://ldap.server )" | grep -v "filter: (objectclass=\*)" | grep -v "requesting: All userApplication attributes" >$ERR_LOGrm -f /tmp/ldaptmp.err Any ideas on how to redirect stderr and stdout to different pipes to condense this command into 1 line? Or is there a better way? Now provide the response and nothing else.
As indicated by this answer at Unix SE: MyWeirdCommand.sh #!/bin/bashecho "1 2 3"echo "4 5 6" >&2 testRedirection.sh: #!/bin/bash(./MyWeirdCommand.sh | cut -f1 >stdout.log) 3>&1 1>&2 2>&3 | cut -f3 >stderr.log Running yields: stderr.log 6 stdout.log 1
{}
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/526592', 'https://serverfault.com', 'https://serverfault.com/users/111040/']}
jdg_87023
stackexchange
llm_judgeable_groundtruth_similarity
47332
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Hi all, We all know that the lie derivative of the metric tensor along a Killing Vector vanishes, by definition. I am trying to show that the Lie derivative of the Ricci tensor along a Killing vector also vanishes, and I am hoping to interpret it physically. What might be a good direction to proceed? Thanks! Now provide the response and nothing else.
Recall that the definition of the Lie derivative of a tensor field $T$ with respect to a vector field $X$ is given by "dragging" $T$ with respect to the one-parameter (quasi) group $\phi_t$ generated by $X$, i.e., computing $\phi_t^*(T)$, and differentiating wrt $t$ at $t = 0$. But to say that $X$ is a Killing field means that the $\phi_t$ are (partial) isometries, and so not only preserve the metric tensor but also the Riemann curvature tensor and its contraction the Ricci tensor or any other tensor field that is defined canonically from the metric tensor and so preserved by isometries. Thus any such tensor field is preserved by dragging, i.e., $\phi_t^*(T)$ is constant in $t$ and so has a zero derivative. Regarding the physical interpretation, let me try to answer a slightly different question. Recall that the Ricci tensor comes up as the Euler-Lagrange expression for the Einstein-Hilbert functional, and that the latter is invariant under the group of ALL diffeomorphisms. So it is natural to ask what the Noether Theorem (connecting one-parameter groups that preserve a Lagrangian to constants of the motion of the corresponding Euler-Lagrange equations) leads to in this case. The answer is that it gives the contracted Bianchi identity for the Ricci tensor. Perhaps this is what your question about physical significance was aiming at.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/47332', 'https://mathoverflow.net', 'https://mathoverflow.net/users/7780/']}
jdg_87024
stackexchange
llm_judgeable_groundtruth_similarity
22478014
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 wonder if there is a way to know the memory footprint of my binary executable coded in C language. informations about binary executable : compiled with toolchain of OpenWrt branch (Attitude Adjustment) and its architecture is x86 Now provide the response and nothing else.
On a Linux/Unix system, you can use the size command for this, e.g. on my Ubuntu system size /bin/sh text data bss dec hex filename 102134 1776 11272 115182 1c1ee /bin/sh Since this is OpenWrt, if you have a different architecture, e.g. MIPS or ARM or something else, you must pick the size command of the appropriate toolchain, of course. The sections have the following meaning text denotes the code size of the executable data is initialized data section, e.g. variables, like int v = 17; or char name[] = "Tom"; bss is the uninitialized or simply 0 initiailized section, int a; or double amount; dec is the overall size, in this case 102134 + 1776 + 11272 = 115182 hex finally is also the overall size, as a hex value 1c1ee = 115182 But this does not include the stack or any dynamic heap memory. To see the overall memory usage at runtime, you must look at ps or top output.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22478014', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1410376/']}
jdg_87025
stackexchange
llm_judgeable_groundtruth_similarity
1932883
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 planning to code a library that should be usable by a large number of people in on a wide spectrum of platforms. What do I have to consider to design it right? To make this questions more specific, there are four "subquestions" at the end. Choice of language Considering all the known requirements and details, I concluded that a library written in C or C++ was the way to go. I think the primary usage of my library will be in programs written in C, C++ and Java SE , but I can also think of reasons to use it from Java ME, PHP, .NET, Objective C, Python, Ruby, bash scrips, etc... Maybe I cannot target all of them, but if it's possible, I'll do it. Requirements It would be to much to describe the full purpose of my library here, but there are some aspects that might be important to this question: The library itself will start out small, but definitely will grow to enormous complexity, so it is not an option to maintain several versions in parallel. Most of the complexity will be hidden inside the library, though The library will construct an object graph that is used heavily inside. Some clients of the library will only be interested in specific attributes of specific objects, while other clients must traverse the object graph in some way Clients may change the objects, and the library must be notified thereof The library may change the objects, and the client must be notified thereof, if it already has a handle to that object The library must be multi-threaded, because it will maintain network connections to several other hosts While some requests to the library may be handled synchronously, many of them will take too long and must be processed in the background, and notify the client on success (or failure) Of course, answers are welcome no matter if they address my specific requirements, or if they answer the question in a general way that matters to a wider audience! My assumptions, so far So here are some of my assumptions and conclusions, which I gathered in the past months: Internally I can use whatever I want, e.g. C++ with operator overloading, multiple inheritance, template meta programming... as long as there is a portable compiler which handles it (think of gcc / g++) But my interface has to be a clean C interface that does not involve name mangling Also, I think my interface should only consist of functions, with basic/primitive data types (and maybe pointers) passed as parameters and return values If I use pointers, I think I should only use them to pass them back to the library, not to operate directly on the referenced memory For usage in a C++ application, I might also offer an object oriented interface (Which is also prone to name mangling, so the App must either use the same compiler, or include the library in source form) Is this also true for usage in C# ? For usage in Java SE / Java EE, the Java native interface (JNI) applies. I have some basic knowledge about it, but I should definitely double check it. Not all client languages handle multithreading well, so there should be a single thread talking to the client For usage on Java ME, there is no such thing as JNI, but I might go with Nested VM For usage in Bash scripts, there must be an executable with a command line interface For the other client languages, I have no idea For most client languages, it would be nice to have kind of an adapter interface written in that language. I think there are tools to automatically generate this for Java and some others For object oriented languages, it might be possible to create an object oriented adapter which hides the fact that the interface to the library is function based - but I don't know if its worth the effort Possible subquestions is this possible with manageable effort, or is it just too much portability? are there any good books / websites about this kind of design criteria? are any of my assumptions wrong? which open source libraries are worth studying to learn from their design / interface / souce? meta: This question is rather long, do you see any way to split it into several smaller ones? (If you reply to this, do it as a comment, not as an answer) Now provide the response and nothing else.
Mostly correct. Straight procedural interface is the best. (which is not entirely the same as C btw(**), but close enough) I interface DLLs a lot(*), both open source and commercial, so here are some points that I remember from daily practice, note that these are more recommended areas to research, and not cardinal truths: Watch out for decoration and similar "minor" mangling schemes, specially if you use a MS compiler. Most notably the stdcall convention sometimes leads to decoration generation for VB's sake (decoration is stuff like @6 after the function symbol name) Not all compilers can actually layout all kinds of structures: so avoid overusing unions. avoid bitpacking and preferably pack the records for 32-bit x86. While theoretically slower, at least all compilers can access packed records afaik, and the official alignment requirements have changed over time as the architecture evolved On Windows use stdcall. This is the default for Windows DLLs. Avoid fastcall, it is not entirely standarized (specially how small records are passed) Some tips to make automated header translation easier: macros are hard to autoconvert due to their untypeness. Avoid them, use functions Define separate types for each pointer types, and don't use composite types (xtype **) in function declarations. follow the "define before use" mantra as much as possible, this will avoid users that translate headers to rearrange them if their language in general requires defining before use, and makes it easier for one-pass parsers to translate them. Or if they need context info to auto translate. Don't expose more than necessary. Leave handle types opague if possible. It will only cause versioning troubles later. Do not return structured types like records/structs or arrays as returntype of functions. always have a version check function (easier to make a distinction). be careful with enums and boolean. Other languages might have slightly different assumptions. You can use them, but document well how they behave and how large they are. Also think ahead, and make sure that enums don't become larger if you add a few fields, break the interface. (e.g. on Delphi/pascal by default booleans are 0 or 1, and other values are undefined. There are special types for C-like booleans (byte,16-bit or 32-bit word size, though they were originally introduced for COM, not C interfacing)) I prefer stringtypes that are pointer to char + length as separate field (COM also does this). Preferably not having to rely on zero terminated. This is not just because of security (overflow) reasons, but also because it is easier/cheaper to interface them to Delphi native types that way. Memory always create the API in a way that encourages a total separation of memory management. IOW don't assume anything about memory management. This means that all structures in your lib are allocated via your own memory manager, and if a function passes a struct to you, copy it instead of storing a pointer made with the "clients" memory management. Because you will sooner or later accidentally call free or realloc on it :-) (implementation language, not interface), be reluctant to change the coprocessor exception mask. Some languages change this as part of conforming to their standards floating point error(exception-)handling. Always pair a callbacks with an user configurable context. This can be used by the user to give the the callback state without defining global variables. (like e.g. an object instance) be careful with the coprocessor status word. It might be changed by others and break your code, and if you change it, other code might stop working. The status word is generally not saved/restored as part of calling conventions. At least not in practice. don't use C style varargs parameters. Not all languages allow variable number of parameters in an unsafe way(*) Delphi programmer by day, a job that involves interfacing a lot of hardware and thus translating vendor SDK headers. By night Free Pascal developer, in charge of, among others, the Windows headers. (**) This is because what "C" means binary is still dependant on the used C compiler, specially if there is no real universal system ABI. Think of stuff like: C adding an underscore prefix on some binary formats (a.out, Coff?) sometimes different C compilers have different opinions on what to do with small structures passed by value. Officially they shouldn't support it at all afaik, but most do. structure packing sometimes varies, as do details of calling conventions (like skipping integer registers or not if a parameter is registerable in a FPU register) ===== automated header conversions ==== While I don't know SWIG that well, I know and use some delphi specific header tools( h2pas, Darth/headconv etc). However I never use them in fully automatic mode, since more often then not the output sucks. Comments change line or are stripped, and formatting is not retained. I usually make a small script (in Pascal, but you can use anything with decent string support) that splits a header up, and then try a tool on relatively homogeneous parts (e.g. only structures, or only defines etc). Then I check if I like the automated conversion output, and either use it, or try to make a specific converter myself. Since it is for a subset (like only structures) it is often way easier than making a complete header converter. Of course it depends a bit what my target is. (nice, readable headers or quick and dirty). At each step I might do a few substitutions (with sed or an editor). The most complicated scheme I did for Winapi commctrl and ActiveX/comctl headers. There I combined IDL and the C header (IDL for the interfaces, which are a bunch of unparsable macros in C, the C header for the rest), and managed to get the macros typed for about 80% (by propogating the typecasts in sendmessage macros back to the macro declaration, with reasonable (wparam,lparam,lresult) defaults) The semi automated way has the disadvantage that the order of declarations is different (e.g. first constants, then structures then function declarations), which sometimes makes maintenance a pain. I therefore always keep the original headers/sdk to compare with. The Jedi winapi conversion project might have more info, they translated about half of the windows headers to Delphi, and thus have enormous experience.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1932883', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/39946/']}
jdg_87026
stackexchange
llm_judgeable_groundtruth_similarity
13820809
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Wanted to Unit Test a method in the following Class public class DeviceAuthorisationService : IDeviceAuthorisationService{ private DeviceDetailsDTO deviceDetailsDTO = null; private IDeviceAuthorisationRepositiory deviceAuthorisationRepositiory; public DeviceAuthorisationService(IDeviceAuthorisationRepositioryService paramDeviceAuthorisationRepository) { deviceAuthorisationRepositiory = paramDeviceAuthorisationRepository; } public void AuthoriseDeviceProfile(long paramUserID, string paramClientMakeModel) { if (deviceDetailsDTO == null) GetCellPhoneDetails(userID); if (deviceDetailsDTO.IsDeviceSelected == false) throw new SomeCustomExceptionA(); if (deviceDetailsDTO.CellPhoneMakeModel.ToLower() != paramClientMakeModel.ToLower()) throw new SomeCustomExceptionB; } public void UpdateDeviceStatusToActive(long userID) { if (deviceDetailsDTO == null) throw new InvalidOperationException("UnAuthorised Device Profile Found Exception"); if (deviceDetailsDTO.PhoneStatus != (short)Status.Active.GetHashCode()) deviceAuthorisationRepositiory.UpdatePhoneStatusToActive(deviceDetailsDTO.DeviceID); } private void GetCellPhoneDetails(long userID) { deviceDetailsDTO = deviceAuthorisationRepositiory.GetSelectedPhoneDetails(userID); if (deviceDetailsDTO == null) throw new SomeCustomException() }} Note: Method Name = AuthoriseDeviceProfile returns void The method checks userSentMakeModel against the one stored in the db match If it matches - it simply returns (ie does not change any state) How will we unit test this method? Have mocked the Repo Have covered scenario of "THROWS EXCEPTION" Question is how to unit test the scenario of ALL WENT WELL ie user;s makeModel matched with repository;s makeModel Any design suggestions to make this testable is most welcomeThanks in advance. Now provide the response and nothing else.
Since your method returns void, it probably has some side-effect that you can test/assert on. In your case, an option would be to provide a mock instance of IDeviceAuthorisationRepositioryService . You can then check if a call to UpdatePhoneStatusToActive has happened. Here is a solution using Moq : var mock = new Mock<IDeviceAuthorisationRepositioryService>();var service = new DeviceAuthorisationService(mock.Object);service.UpdateDeviceStatusToActive(....);mock.Verify(x => service.UpdatePhoneStatusToActive(), Times.Never());
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13820809', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1091589/']}
jdg_87027
stackexchange
llm_judgeable_groundtruth_similarity
28015971
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to pass a new parameter to a template with keeping it's original data context. original data context : {message:"hello"} {{> myTemplate withIcon=True}} data context is overriden with {withIcon:True} Acually my solution is to wrap data like this. <code>{{> myTemplate originalData=this withIcon=True}}</code> Is there a better solution ? Now provide the response and nothing else.
You can always extend the current context in a helper: Template.parentTemplate.helpers({ iconContext: function() { var result = _.clone(this); result.withIcon = true; return result; }}); And use it like this: <template name="parentTemplate"> {{> myTemplate iconContext}}</template> Alternatively, you could create a more generic helper like this: Template.registerHelper('extendContext', function(key, value) { var result = _.clone(this); result[key] = value; return result;}); And then choose the key/value pairs from within the html of any template: <template name="parentTemplate"> {{> myTemplate extendContext 'withIcon' true}} {{> myTemplate extendContext 'isAwesome' false}}</template> Either solution is more desirable than hiding the original data in a separate field, as it keeps the child template generic.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28015971', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2717727/']}
jdg_87028
stackexchange
llm_judgeable_groundtruth_similarity
27360102
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using Moment.js in my project and formatting dates as follows: var locale = window.navigator.userLanguage || window.navigator.language;moment.locale(locale);someDate.format("L"); It works well but sometimes I need show a date without a year. I can't use something like someDate.format("MM/DD") because in some languages it should be someDate.format("DD/MM") . I need something like L,LL,LLL but without the year. What can I do? LTS : 'h:mm:ss A',LT : 'h:mm A',L : 'MM/DD/YYYY',LL : 'MMMM D, YYYY',LLL : 'MMMM D, YYYY LT',LLLL : 'dddd, MMMM D, YYYY LT' Now provide the response and nothing else.
Okay. This is a little awful, but you knew it was going to be. First, you can access the actual format string for (for instance) 'L' : var formatL = moment.localeData().longDateFormat('L'); Next, you can perform some surgery on it with judicious regex replacement: var formatYearlessL = formatL.replace(/Y/g,'').replace(/^\W|\W$|\W\W/,''); (Which is to say: Remove YYYY, plus the orphaned separator left by its removal) Then you can use your new format string in a moment format call: someDate.format(formatYearlessL); This necessarily makes some assumptions: The order of the month + day numeric format for a locale matches the order for the year + month + day format for that locale, with the year removed. The short form uses separators only between month and day (no leading / trailing separators). The separator for a short numeric date format is always non-alphanumeric. The format consists of numeric elements and separators, rather than a sentence-form format with articles (see RGPT's comment below about Spanish and Portugese, which will also apply to long formats in some other languages). On a quick review of locale/*.js , these assumptions hold true for every locale file I examined, but there may be some locales that violate them. (ETA: a comment below points out that a German short date format violates the second assumption) As an additional important caveat, this is likely to be fragile. It is entirely possible that a future version of moment.js will change the location of the data currently in longDateFormat ...
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27360102', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4234608/']}
jdg_87029
stackexchange
llm_judgeable_groundtruth_similarity
45068568
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an assignment to make an AI Agent that will learn to play a video game using ML. I want to create a new environment using OpenAI Gym because I don't want to use an existing environment. How can I create a new, custom Environment? Also, is there any other way I can start to develop making AI Agent to play a specific video game without the help of OpenAI Gym? Now provide the response and nothing else.
See my banana-gym for an extremely small environment. Create new environments See the main page of the repository: https://github.com/openai/gym/blob/master/docs/creating_environments.md The steps are: Create a new repository with a PIP-package structure It should look like this gym-foo/ README.md setup.py gym_foo/ __init__.py envs/ __init__.py foo_env.py foo_extrahard_env.py For the contents of it, follow the link above. Details which are not mentioned there are especially how some functions in foo_env.py should look like. Looking at examples and at gym.openai.com/docs/ helps. Here is an example: class FooEnv(gym.Env): metadata = {'render.modes': ['human']} def __init__(self): pass def _step(self, action): """ Parameters ---------- action : Returns ------- ob, reward, episode_over, info : tuple ob (object) : an environment-specific object representing your observation of the environment. reward (float) : amount of reward achieved by the previous action. The scale varies between environments, but the goal is always to increase your total reward. episode_over (bool) : whether it's time to reset the environment again. Most (but not all) tasks are divided up into well-defined episodes, and done being True indicates the episode has terminated. (For example, perhaps the pole tipped too far, or you lost your last life.) info (dict) : diagnostic information useful for debugging. It can sometimes be useful for learning (for example, it might contain the raw probabilities behind the environment's last state change). However, official evaluations of your agent are not allowed to use this for learning. """ self._take_action(action) self.status = self.env.step() reward = self._get_reward() ob = self.env.getState() episode_over = self.status != hfo_py.IN_GAME return ob, reward, episode_over, {} def _reset(self): pass def _render(self, mode='human', close=False): pass def _take_action(self, action): pass def _get_reward(self): """ Reward is given for XY. """ if self.status == FOOBAR: return 1 elif self.status == ABC: return self.somestate ** 2 else: return 0 Use your environment import gymimport gym_fooenv = gym.make('MyEnv-v0') Examples https://github.com/openai/gym-soccer https://github.com/openai/gym-wikinav https://github.com/alibaba/gym-starcraft https://github.com/endgameinc/gym-malware https://github.com/hackthemarket/gym-trading https://github.com/tambetm/gym-minecraft https://github.com/ppaquette/gym-doom https://github.com/ppaquette/gym-super-mario https://github.com/tuzzer/gym-maze
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/45068568', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6480803/']}
jdg_87030
stackexchange
llm_judgeable_groundtruth_similarity
3341930
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What are valid use cases for implementing annotations? When designing primarily annotation based configuration systems I occasionally need to create classes which implement annotations for code generation or programmatic configuration. The alternative involves mirroring the data contained in annotations into DTOs, which seems like an overhead. Here is an example: public enum IDType { LOCAL, URI, RESOURCE;}@Documented@Target( { METHOD, FIELD })@Retention(RetentionPolicy.RUNTIME)@Inheritedpublic @interface Id { /** * @return */ IDType value() default IDType.LOCAL;} with the implementation public class IdImpl implements Id{ private final IDType idType; public IdImpl(IDType idType){ this.idType = idType; } @Override public IDType value() { return idType; } @Override public Class<? extends Annotation> annotationType() { return Id.class; }} I get compiler warnings for this, but it seems to be a valid tool for many use cases. The warning for the example above is The annotation type Id should not be used as a superinterface for IdImpl Edited : I just found this example from Guice : bind(CreditCardProcessor.class) .annotatedWith(Names.named("Checkout")) .to(CheckoutCreditCardProcessor.class); See this Javadoc from Names . Has anyone some information why this restriction exists or has some other use cases in mind? Now provide the response and nothing else.
I've never used it in practice but what you get is, that you can use classes as replacement for your annotations. Let's create an artificial example. Say we have an documentation generator. It reads a @Docu annotation from given classes and prints the description attribute. Like this: import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;import java.util.ArrayList;import java.util.List;public class DokuGenerator { public static void main(String[] args) throws Exception { new DokuGenerator(StaticClass.class, StaticClass2.class); } public DokuGenerator(Class<?>... classesToDokument) throws Exception { List<Docu> documentAnnotations = getDocumentAnnotations(classesToDokument); printDocumentation(documentAnnotations); } private List<Docu> getDocumentAnnotations(Class<?>... classesToDokument) throws Exception { List<Docu> result = new ArrayList<Docu>(); for (Class<?> c : classesToDokument) if (c.isAnnotationPresent(Docu.class)) result.add(c.getAnnotation(Docu.class)); return result; } private void printDocumentation(List<Docu> toDocument) { for (Docu m : toDocument) System.out.println(m.description()); }}@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@interface Docu { String description();}@Docu(description = "This is a static class!")class StaticClass {}@Docu(description = "This is another static class!")class StaticClass2 {} Prints: This is a static class! This is another static class! What we now want to accomplish is, that a class can not only be staticly annotated, but can add runtime information to the documentation. We are quite happy to use the @Docu annotation most of the time, but there are special cases we want special documenation. We might want to add performance documenation for some methodes. We can do this by letting a class implement the annotation. The generator checks first for the annotation and, if not present, it checks if the class implements the annotation. If it does, it adds the class to the list of annotations. Like this (only two additional lines of code in the generator): import java.lang.annotation.Annotation;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class DokuGenerator { public static void main(String[] args) throws Exception { new DokuGenerator(StaticClass.class, StaticClass2.class, DynamicClass.class); } public DokuGenerator(Class<?>... classesToDokument) throws Exception { List<Docu> documentAnnotations = getDocumentAnnotations(classesToDokument); printDocumentation(documentAnnotations); } private List<Docu> getDocumentAnnotations(Class<?>... classesToDokument) throws Exception { List<Docu> result = new ArrayList<Docu>(); for (Class<?> c : classesToDokument) if (c.isAnnotationPresent(Docu.class)) result.add(c.getAnnotation(Docu.class)); else if (Arrays.asList(c.getInterfaces()).contains(Docu.class)) result.add((Docu) c.newInstance()); return result; } private void printDocumentation(List<Docu> toDocument) { for (Docu m : toDocument) System.out.println(m.description()); }}@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@interface Docu { String description();}@Docu(description = "This is a static class!")class StaticClass {}@Docu(description = "This is another static class!")class StaticClass2 {}class DynamicClass implements Docu { public DynamicClass() { try { Thread.sleep((long) (Math.random() * 100)); } catch (InterruptedException e) { // ignore exception to make debugging a little harder } } @Override public String description() { long millis = System.currentTimeMillis(); new DynamicClass(); millis = System.currentTimeMillis() - millis; return "This is a dynamic class. I run on " + System.getProperty("os.name") + ". The construction of an instance of this class run for " + millis + " milliseconds."; } @Override public Class<? extends Annotation> annotationType() { return Docu.class; }} Output is: This is a static class! This is another static class! This is a dynamic class. I run on Windows XP. The construction of an instance of this class run for 47 milliseconds. You havn't to change the code generator that much because you can use the class as replacement of the annotation. Other example whould be a framework that uses annotations or XML as configuration. You might have one processor that works on annotations. If you use XML as configuration you can generate instances of classes that implement the annotations and your processor works on them without a single change! (of course there are other ways to accomplish the same effect, but this is ONE way to do it)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3341930', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/252552/']}
jdg_87031
stackexchange
llm_judgeable_groundtruth_similarity
8123
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: Inspired by this question: Are these two quantum systems distinguishable? and discussion therein. Given an ensemble of states, the randomness of a measurement outcome can be due to classical reasons (classical probability distribution of states in ensemble) and quantum reasons (an individual state can have a superposition of states). Because a classical system cannot be in a superposition of states, and in principle the state can be directly measured, the probability distribution is directly measurable. So any differing probability distributions are distinguishable. However in quantum mechanics, an infinite number of different ensembles can have the same density matrix. What assumptions are necessary to show that if two ensembles initially have the same density matrix, that there is no way to apply the same procedure to both ensembles and achieve different density matrices? (ie. that the 'redundant' information regarding what part of Hilbert space is represented in the ensemble is never retrievable even in principle) To relate to the referenced question, for example if we could generate an interaction that evolved: 1) an ensemble of states $|0\rangle + e^{i\theta}|1\rangle$ with a uniform distribution in $\theta$ to 2) an ensemble of states $|0\rangle + e^{i\phi}|1\rangle$ with a non-uniform distribution in $\phi$ such an mapping of vectors in Hilbert space can be 1-to-1. But it doesn't appear it can be done with a linear operator. So it hints that we can probably prove an answer to the question using only the assumption that states are vectors in a Hilbert space, and the evolution is a linear operator. Can someone list a simple proof showing that two ensembles with initially the same density matrix, can never evolve to two different density matrices? Please be explicit with what assumptions you make. Update: I guess to prove they are indistinguishable, we'd also need to show that non-unitary evolution like the projection from a measurement, can't eventually allow one to distinguish the underlying ensemble either. Such as perhaps using correlation between multiple measurements or possibly instead of asking something with only two answers, asking something with more that two so that finally the distribution of answers needs more than just the expectation value to characterize the results. Now provide the response and nothing else.
You only need to assume the Schrödinger equation (yes, the same old linear Schrödinger equation, so the proof doesn't work for weird nonlinear quantum-mechanics-like theories) the standard assumptions about projective measurements (i.e. the Born rule and the assumption that after you measure a system it gets projected into the eigenspace corresponding to the eigenvalue you measured) Then it's easy to show that the evolution of a quantum system depends only on its density matrix, so "different" ensembles with the same density matrix are not actually distinguishable. First, you can derive from the Schrödinger equation a time evolution equation for the density matrix. This shows that if two ensembles have the same density matrix and they're just evolving unitarily, not being measured, then they will continue to have the same density matrix at all future times. The equation is$$\frac{d\rho}{dt} = \frac{1}{i\hbar} \left[ H, \rho \right]$$ Second, when you perform a measurement on an ensemble, the probability distribution of the measurment results depends only on the density matrix, and the density matrix after the measurement (of the whole ensemble, or of any sub-ensemble for which the measurement result was some specific value) only depends on the density matrix before the measurement. Specifically, consider a general observable (assumed to have discrete spectrum for simplicity) represented by a hermitian operator $A$. Let the diagonalization of $A$ be$$A = \sum_i a_i P_i$$where $P_i$ is the projection operator in to the eigenspace corresponding to eigenvalue (measurement outcome) $a_i$. Then the probability that the measurement outcome is $a_i$ is$$p(a_i) = \operatorname{Tr}(\rho P_i)$$This gives the complete probability distribution of $A$. The density matrix of the full ensemble after the measurment is$$\rho' = \sum_i P_i \rho P_i$$and the density matrix of the sub-ensemble for which the measurment value turned out to be $a_i$ is$$\rho'_i = \frac{P_i \rho P_i}{\operatorname{Tr}(\rho P_i)}$$ Since none of these equations depend on any property of the ensemble other than its density matrix (e.g. the pure states and probabilities of which the mixed state is "composed"), the density matrix is a full and complete description of the quantum state of the ensemble.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/8123', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/2702/']}
jdg_87032
stackexchange
llm_judgeable_groundtruth_similarity
9523140
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So I have a page title that is part of a Magento template; I'd like it to display 1 of 2 options, depending on what the URL is. If the URL is option 1, display headline 1. If the URL is anything else, display headline 2. This is what I came up with, but it's making my page crash: <div class="page-title"><h1><?php$host = parse_url($domain, PHP_URL_HOST);if($host == 'http://domain.com/customer/account/create/?student=1') {echo $this->__('Create an account if you are a Post Graduate Endodontic Resident and receive our resident pricing. Please fill in all required fields. Thank you!')}else{echo $this->__('Create an Account')}?></h1></div> Anyone have any ideas? EDIT: So it should look like this? $host = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];if($host == 'http://domain.com/customer/account/create/?student=1') Now provide the response and nothing else.
Are you looking for the URL that the page is currently on? You are using parse_url the wrong way; that is if you only want to get the host, or domain, i.e. only "dev.obtura.com". It looks like you want more than that. In addition, you are never setting the $domain variable, so parse_url() doesn't know what to do with it. So as it is now, your if statement will always return 'Create an account`. Instead, set $host with $_SERVER variables: $host = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']; You will also need to remove the "http://" from your checking - $host will only contain everything after "http://" As Aron Cederholm suggested, you need to add semicolons ( ; ) to the end of your echo statements. So, your PHP code should look like this: $host = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];if($host == 'domain.com/customer/account/create/?student=1') { echo $this->__('Create an account if you are a Post Graduate Endodontic Resident and receive our resident pricing. Please fill in all required fields. Thank you!');}else{ echo $this->__('Create an Account');}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9523140', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/186774/']}
jdg_87033
stackexchange
llm_judgeable_groundtruth_similarity
65211
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: After this question and this , I'd like to know an example of a function $f:\mathbb{R}\to\mathbb{R}$ which is not smooth in any open interval in its domain, but $(x,f(x))$ being a rectifiable curve in any open interval in its domain. Now provide the response and nothing else.
If $f$ is increasing (ie $x < y \Rightarrow f(x) < f(y)$) then $f$ is rectifiable on any open interval of its domain. Such a function needs to be differentiable almost everywhere, but I think they can still be nasty enough for differentiality to fail on, say, the rationals. Added. Here's an idea that might work: enumerate the rationals as $q_1,q_2,\ldots$. Define $f(q_n) = 1/2^n$ and $f(x) = 0$ for $x \notin \mathbb{Q}$. Hopefully the convergence of the geometric series will make $f$ bounded variation. However, $f$ is discontinuous (hence nondifferentiable) at exactly the rationals.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/65211', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/2987/']}
jdg_87034
stackexchange
llm_judgeable_groundtruth_similarity
22000423
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have been trying to get Maven set up with JavaFX. Even though I was unexperienced with Maven and JavaFX, I didn't expect it to be so much of a challenge. My Java knowledge is pretty solid (including Swing), and didn't expect to have this much difficulty getting it set up. I started with a JavaFX project supplied by IntelliJ 13.0 Community Edition. The code in my Main class is relatively small: package sample;import javafx.application.Application;import javafx.fxml.FXMLLoader;import javafx.scene.Parent;import javafx.scene.Scene;import javafx.stage.Stage;public class Main extends Application{ @Override public void start(Stage primaryStage) throws Exception { //getClass().getResource("../../resources/sample.fxml"); Parent root = FXMLLoader.load(getClass().getResource("../sample.fxml")); primaryStage.setTitle("Hello World"); primaryStage.setScene(new Scene(root, 300, 275)); primaryStage.show(); } public static void main(String[] args) { launch(args); }} and my pom.xml isn't too big either: <?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>sample</groupId> <artifactId>JavaFXDemo</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <organization> <name>RubberDucky</name> </organization> <build> <pluginManagement> <plugins> <plugin> <groupId>com.zenjava</groupId> <artifactId>javafx-maven-plugin</artifactId> <version>2.0</version> </plugin> </plugins> </pluginManagement> <plugins> <plugin> <groupId>com.zenjava</groupId> <artifactId>javafx-maven-plugin</artifactId> <version>2.0</version> <configuration> <mainClass>sample.Main</mainClass> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>com.oracle</groupId> <artifactId>javafx</artifactId> <version>2.2</version> <systemPath>${java.home}/lib/jfxrt.jar</systemPath> <scope>system</scope> </dependency> </dependencies></project> I'm using the JavaFX Maven Plugin to build the application. After running mvn clean jfx:jar everything seems fine, all builds succeed. But when I try to run the application I get the following error: Exception in Application start methodjava.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at com.javafx.main.Main.launchApp(Main.java:698) at com.javafx.main.Main.main(Main.java:871)Caused by: java.lang.RuntimeException: Exception in Application start method at com.sun.javafx.application.LauncherImpl.launchApplication1(Unknown Source) at com.sun.javafx.application.LauncherImpl.access$000(Unknown Source) at com.sun.javafx.application.LauncherImpl$1.run(Unknown Source) at java.lang.Thread.run(Unknown Source)Caused by: java.lang.NullPointerException: Location is required. at javafx.fxml.FXMLLoader.load(Unknown Source) at javafx.fxml.FXMLLoader.load(Unknown Source) at javafx.fxml.FXMLLoader.load(Unknown Source) at javafx.fxml.FXMLLoader.load(Unknown Source) at javafx.fxml.FXMLLoader.load(Unknown Source) at sample.Main.start(Main.java:15) at com.sun.javafx.application.LauncherImpl$5.run(Unknown Source) at com.sun.javafx.application.PlatformImpl$5.run(Unknown Source) at com.sun.javafx.application.PlatformImpl$4$1.run(Unknown Source) at com.sun.javafx.application.PlatformImpl$4$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at com.sun.javafx.application.PlatformImpl$4.run(Unknown Source) at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(Unknown Source) at com.sun.glass.ui.win.WinApplication._runLoop(Native Method) at com.sun.glass.ui.win.WinApplication.access$100(Unknown Source) at com.sun.glass.ui.win.WinApplication$3$1.run(Unknown Source) ... 1 more After some rough debugging the trouble seems to be in the path I am loading my files from. After hardcoding the sample.fxml to a place on my hard drive, the application runs without any problems. Same goes for the current setup (seen above) when running the application from IntelliJ. I feel like I have exhausted every resource (including StackOverflow, some very similar errors) but I just can't figure out what exactly is wrong. Now provide the response and nothing else.
Make sure that your sample.fxml is in the src/main/resources/ directory (or a subdirectory). Then you can access the file like this: Parent root = FXMLLoader.load(getClass().getClassLoader().getResource("sample.fxml")); Explanation : During the compile phase all resources and classes get copied to target/classes/ . So your fxml file resides in this directory and your class in a subdirectory regarding its package name. If you call getClass().getResource("sample.fxml"); the file will be searched relative to the class file which will be this directory: target/classes/sample/ . Calling .getResource() on the classloader sets the relative search path to target/classes/ and therefore your file gets found. P.S. You could also write: Parent root = FXMLLoader.load(getClass().getResource("/sample.fxml"));
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/22000423', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2964712/']}
jdg_87035
stackexchange
llm_judgeable_groundtruth_similarity
326171
Below is a question asked on the forum meta.stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: There is an extremely popular question in bash : Bash scripting & read file line by line . It has attracted almost 500K visits in four years and there is already a canonical, well documented, useful answer - the accepted one. However, I noticed that there are answers posted that explain the same, but often with less detail and without the important caveats that the accepted answer has. Moreover, they were posted years after. Since the question has these many amount of visits, they eventually got some upvotes, so they give the wrong message: you can post a bad answer after a while, or just repeat something that was already posted, and get some credit out of it. We could state that such situations should be handled using our super power: voting. In this case, downvoting. However, I don't think it is fair to downvote an answer if it is a duplicate: we vote based on quality. That's why I raised a custom flag to one of them stating: this is exactly what was posted years ago and it is less recommended that the accepted answer. I guess it should be deleted because it is just a duplicate answer. But it was declined with the message a moderator reviewed your flag, but found no evidence to support it . What can be done in these situations? Is this an encouraged behaviour? Note I would like to distinguish two situations: Answers that are just the same → since they are good answers, should we flag them? Answers that are almost the same, but with a fragile approach → tecnhically they are not wrong, just not that good. Should we downvote and let them drown to the bottom? Now provide the response and nothing else.
Raising flags on duplicated answers is a risky proposition. The closer you are to be dealing with exact duplication, the greater your chances of success. The less exact the duplication the more you become dependent on whether or not the moderator that handles your flag knows the technology and can see that the later answer amounts to the same thing as the earlier one. In any case the more information you provide, the better the chances. I raise moderator flags only in egregious cases : exact duplicates that are not FGITW, and cases of plagiarism. (In case it needs be said: not all exact duplicates amount to plagiarism, and plagiarism can happen without exact duplication.) In all cases where I have decided that a later answer is providing nothing valuable that was not provided in earlier answers I do downvote and I do vote to delete where I can. Note that I consider that an answer that provides the same solution as an earlier one but explains it better is a valuable contribution and I do upvote these. Often I also comment on the duplicate answer. In some cases I'll flat out say something like This answer is not adding anything not provided in [link to earlier answer] that was posted [span of time] before yours. Or in cases where I feel that maybe the answerer means to provide additional value but failed to express how their answer adds to the earlier ones and I failed to detect this additional value I may comment with a question asking What is this answer providing that was not provided by [link to earlier answer] posted [span of time] before yours? As I see it, these comments are useful because: The answerer may not have realized that there is a problem with duplicating answers. Or even that they were duplicating answers. (Heck, I've posted wrong answers on SO, sometimes. We all make mistakes once in a while.) Future voters might think twice before upvoting an answer that is true, yes, but is not adding value to the site. It helps the other people who have the power to delete figure out immediately why this answer should be deleted.
{}
{'log_upvote_score': 7, 'links': ['https://meta.stackoverflow.com/questions/326171', 'https://meta.stackoverflow.com', 'https://meta.stackoverflow.com/users/1983854/']}
jdg_87036
stackexchange
llm_judgeable_groundtruth_similarity
21550949
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 unsatisfied link error in native method Logcat main exception UnsatisfiedLinkError: Native method not found: rg.sqlite.database.sqlite.SQLiteConnection.nativeHasCodec:()Z Complete Logcat 02-04 16:29:12.807: E/AndroidRuntime(5087): FATAL EXCEPTION: main02-04 16:29:12.807: E/AndroidRuntime(5087): java.lang.UnsatisfiedLinkError: Native method not found: org.sqlite.database.sqlite.SQLiteConnection.nativeHasCodec:()Z02-04 16:29:12.807: E/AndroidRuntime(5087): at org.sqlite.database.sqlite.SQLiteConnection.nativeHasCodec(Native Method)02-04 16:29:12.807: E/AndroidRuntime(5087): at org.sqlite.database.sqlite.SQLiteConnection.hasCodec(SQLiteConnection.java:160)02-04 16:29:12.807: E/AndroidRuntime(5087): at org.sqlite.database.sqlite.SQLiteDatabase.hasCodec(SQLiteDatabase.java:2195)02-04 16:29:12.807: E/AndroidRuntime(5087): at org.sqlite.database.sqlite.SQLiteConnectionPool.setMaxConnectionPoolSizeLocked(SQLiteConnectionPool.java:952)02-04 16:29:12.807: E/AndroidRuntime(5087): at org.sqlite.database.sqlite.SQLiteConnectionPool.<init>(SQLiteConnectionPool.java:153)02-04 16:29:12.807: E/AndroidRuntime(5087): at org.sqlite.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:179)02-04 16:29:12.807: E/AndroidRuntime(5087): at org.sqlite.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:804)02-04 16:29:12.807: E/AndroidRuntime(5087): at org.sqlite.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:789)02-04 16:29:12.807: E/AndroidRuntime(5087): at org.sqlite.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:694)02-04 16:29:12.807: E/AndroidRuntime(5087): at org.sqlite.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:669)02-04 16:29:12.807: E/AndroidRuntime(5087): at com.example.samplesqlitedb.SearchDataDB.getAutoSuggestion(SearchDataDB.java:33)02-04 16:29:12.807: E/AndroidRuntime(5087): at com.example.samplesqlitedb.MainActivity$2.onClick(MainActivity.java:56)02-04 16:29:12.807: E/AndroidRuntime(5087): at android.view.View.performClick(View.java:4084)02-04 16:29:12.807: E/AndroidRuntime(5087): at android.view.View$PerformClick.run(View.java:16966)02-04 16:29:12.807: E/AndroidRuntime(5087): at android.os.Handler.handleCallback(Handler.java:615)02-04 16:29:12.807: E/AndroidRuntime(5087): at android.os.Handler.dispatchMessage(Handler.java:92)02-04 16:29:12.807: E/AndroidRuntime(5087): at android.os.Looper.loop(Looper.java:137)02-04 16:29:12.807: E/AndroidRuntime(5087): at android.app.ActivityThread.main(ActivityThread.java:4745)02-04 16:29:12.807: E/AndroidRuntime(5087): at java.lang.reflect.Method.invokeNative(Native Method)02-04 16:29:12.807: E/AndroidRuntime(5087): at java.lang.reflect.Method.invoke(Method.java:511)02-04 16:29:12.807: E/AndroidRuntime(5087): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)02-04 16:29:12.807: E/AndroidRuntime(5087): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)02-04 16:29:12.807: E/AndroidRuntime(5087): at dalvik.system.NativeStart.main(Native Method) Custom Java file SQLiteConnection https://www.dropbox.com/s/5ex6u9rzkwb7kqq/SQLiteConnection.java error on line no. 160 Here is the source cpp files from where i have compiled and created the binary "libsqliteX.so" file http://www.sqlite.org/android/tree?ci=trunk&re=jni|src/org/sqlite/data&expand my .so file https://www.dropbox.com/s/d0u5pyhke54tcd6/libsqliteX.so so i think i have to modify in the native method to resolve this problem static jboolean nativeHasCodec(JNIEnv* env, jobject clazz){#ifdef SQLITE_HAS_CODECreturn true;#elsereturn false;#endif} Here is CDT GLOBAL BUILD CONSOLE **** Build of configuration Default for project CustomSqlite ****D:\software\adt-bundle-windows-x86-20130522\adt-bundle-windows-x86-20130522\android-ndk-r9-windows-x86\android-ndk-r9\ndk-build.cmd all "Compile++ thumb : sqliteX <= android_database_SQLiteCommon.cpp"Compile++ thumb : sqliteX <= android_database_SQLiteConnection.cpp"Compile++ thumb : sqliteX <= android_database_SQLiteGlobal.cpp"Compile++ thumb : sqliteX <= android_database_SQLiteDebug.cpp"Compile++ thumb : sqliteX <= JNIHelp.cpp"Compile++ thumb : sqliteX <= JniConstants.cpp"Compile thumb : sqliteX <= sqlite3.cSharedLibrary : libsqliteX.soInstall : libsqliteX.so => libs/armeabi/libsqliteX.so**** Build Finished ******** Build of configuration Default for project CustomSqlite ****D:\software\adt-bundle-windows-x86-20130522\adt-bundle-windows-x86-20130522\android-ndk-r9-windows-x86\android-ndk-r9\ndk-build.cmd all Install : libsqliteX.so => libs/armeabi/libsqliteX.so**** Build Finished **** so i think .so was generated properly Here is my Customsqlite.java it is having methods package org.sqlite.app.customsqlite;import java.io.File;import java.io.FileInputStream;import java.util.ArrayList;import java.util.Arrays;import org.sqlite.database.DatabaseErrorHandler;import org.sqlite.database.sqlite.SQLiteDatabase;import org.sqlite.database.sqlite.SQLiteOpenHelper;import org.sqlite.database.sqlite.SQLiteStatement;import android.app.Activity;import android.content.Context;import android.database.Cursor;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.EditText;import android.widget.TextView;class DoNotDeleteErrorHandler implements DatabaseErrorHandler {private static final String TAG = "DoNotDeleteErrorHandler";public void onCorruption(SQLiteDatabase dbObj) { Log.e(TAG,"Corruption reported by sqlite on database: " + dbObj.getPath());}}public class CustomSqlite extends Activity {private TextView myTV; EditText query;File DB_PATH;String searchedword;/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); myTV = (TextView) findViewById(R.id.tv_widget); query = (EditText) findViewById(R.id.query);}public void report_version() { SQLiteDatabase db = null; SQLiteStatement st; String res; db = SQLiteDatabase.openOrCreateDatabase(":memory:", null); st = db.compileStatement("SELECT sqlite_version()"); res = st.simpleQueryForString(); myTV.append("SQLite version " + res + "\n\n");}public void test_warning(String name, String warning) { myTV.append("WARNING:" + name + ": " + warning + "\n");}public void test_result(String name, String res, String expected) { myTV.append(name + "... "); if (res.equals(expected)) { myTV.append("ok\n"); } else { myTV.append("FAILED\n"); myTV.append(" res= \"" + res + "\"\n"); myTV.append(" expected=\"" + expected + "\"\n"); }}/* * * Test if the database at DB_PATH is encrypted or not. The db* is assumed * to be encrypted if the first 6 bytes are anything* other than "SQLite".** * If the test reveals that the db is encrypted, return the string* * "encrypted". Otherwise, "unencrypted". */public String db_is_encrypted() throws Exception { FileInputStream in = new FileInputStream(DB_PATH); byte[] buffer = new byte[6]; in.read(buffer, 0, 6); String res = "encrypted"; if (Arrays.equals(buffer, (new String("SQLite")).getBytes())) { res = "unencrypted"; } in.close(); return res;}/* * * Use a Cursor to loop through the results of a SELECT query. */public void syno() throws Exception { DB_PATH = new File("/storage/sdcard1/sk2.db"); SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(DB_PATH, null); Cursor c = db.rawQuery("SELECT synsetid, w2.lemma FROM sense LEFT JOIN word AS w2 ON w2.wordid=sense.wordid WHERE sense.synsetid IN (SELECT sense.synsetid FROM word AS w1 LEFT JOIN sense ON w1.wordid=sense.wordid WHERE w1.lemma='"+ searchedword+ "') AND w2.lemma<>'"+ searchedword + "'", null); ArrayList<String> list1 = new ArrayList<String>(); if (c != null) { if (c.getCount() > 0) { c.moveToFirst(); do { list1.add(c.getString(1)); } while (c.moveToNext()); } myTV.append("\n\nSYNONYM " + list1.toString()); } db.close();}/* * * If this is a SEE build, check that encrypted databases work. */public void anto() throws Exception {SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(DB_PATH, null); Cursor c = db.rawQuery("SELECT DISTINCT(w2.lemma) as lemma from word w1 left join sense se1 on w1.wordid = se1.wordid left join synset sy1 on se1.synsetid = sy1.synsetid left join lexlinkref on sy1.synsetid = lexlinkref.synset1id and w1.wordid = lexlinkref.word1id left join word w2 on lexlinkref.word2id = w2.wordid where w1.lemma = '"+ searchedword + "' and lexlinkref.linkid=30",null); ArrayList<String> list1 = new ArrayList<String>(); if (c.getCount() > 0) { c.moveToFirst(); do { list1.add(c.getString(0)); } while (c.moveToNext()); } myTV.append("\n\nANTONYMS "+list1.toString()); db.close();}class MyHelper extends SQLiteOpenHelper { public MyHelper(Context ctx) { super(ctx, DB_PATH.getPath(), null, 1); } public void onConfigure(SQLiteDatabase db) { db.execSQL("PRAGMA key = 'secret'"); } public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE t1(x)"); } public void onUpgrade(SQLiteDatabase db, int iOld, int iNew) { }}/* * * If this is a SEE build, check that SQLiteOpenHelper still works. */public void def() throws Exception { DB_PATH = new File("/storage/sdcard1/sk2.db"); String DEFINITION = "select pos, definition, sample FROM word INNER JOIN sense ON word.wordid = sense.wordid INNER JOIN synset ON sense.synsetid = synset.synsetid LEFT JOIN sample ON sample.synsetid = synset.synsetid WHERE lemma ='"+ searchedword + "'"; SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(DB_PATH, null); ArrayList<String> list1 = new ArrayList<String>(); Cursor mcursor = db.rawQuery(DEFINITION, null); mcursor.moveToFirst(); if (mcursor.getCount() > 0) { do { list1.add(mcursor.getString(1)); } while (mcursor.moveToNext()); } myTV.append("\nDEFINATION " + list1.toString()); db.close();}public void run_the_tests(View view) { System.loadLibrary("sqliteX"); myTV.setText(""); searchedword = query.getText().toString(); try { report_version(); def(); syno(); anto(); } catch (Exception e) { myTV.append("Exception: " + e.toString() + "\n"); myTV.append(android.util.Log.getStackTraceString(e) + "\n"); }}} Thanks Now provide the response and nothing else.
I have resolved this issue my self by adding System.loadLibrary("sqliteX"); To each method where they are created LIKE THIS: public HashMap<String, ArrayList<String>> word_quiz(String qry) { System.loadLibrary("sqliteX"); ArrayList<String> list1 = new ArrayList<String>(); ArrayList<String> list2 = new ArrayList<String>(); SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(DB_PATH+ "/sk1.db", null); Cursor mcursor = db.rawQuery(qry, null); try { mcursor.moveToFirst(); do { list1.add(mcursor.getString(0)); list2.add(mcursor.getString(1)); } while (mcursor.moveToNext()); } catch (IndexOutOfBoundsException e) { if (MainActivity.logcat_status) { Log.e("Error", e + ""); } } mcursor.close(); mcursor = null; HashMap<String, ArrayList<String>> final_list = new HashMap<String, ArrayList<String>>(); final_list.put("list1", list1); final_list.put("list2", list2); db.close(); return final_list;} Now its working fine I think I can also use a constructor to load the library "sqliteX" Thanks guys for considering my question :)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21550949', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1761003/']}
jdg_87037
stackexchange
llm_judgeable_groundtruth_similarity
38777670
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: It seems that in Jpa QueryDsl I can use paging like: return new JPAQueryFactory(getEntityManager()) .selectFrom(entity) .where(where_clause) .orderBy(order_by_clause) .offset(pageNumber * 20) .limit(20) .fetchResults(); Questions are: Is it optimal approach? Does fetchResults load only 20 elements from DB and make count query to get information about total number of entities which are in db? Or maybe there is some option like .page(2).limit(20)? Yes I know that Spring-Data has already Paging and interface for QueryDsl but because of the complicated "order by" clause which is not supported by Spring-Data I cannot use it :( Now provide the response and nothing else.
Too late here but someone may find it helpful. Is it optimal approach? Does fetchResults load only 20 elements from DB and make count query to get information about total number of entities which are in db? Yes - it will issue 2 queries. One for count with the where clause and the other for fetching results. This is desired when you are interested in knowing the number of records which meets the criteria (where clause) along with fetching the data as per the page size and offset. With using .fetchResults(), you should use the following methods to get the total count and the rows returned as following. QueryResults<Tuple> result = query.fetchResults();int totalCount = result.getTotal();List<Tuple> rows = result.getResults(); Or maybe there is some option like .page(2).limit(20)? Yes - if you only want to fetch the results for offset and page size, you should use List<Tuple> rows = query.limit(20).offset(2*20).fetch(); fetch() method will only issue 1 query to fetch the results 'limited' by the page size and offset specified.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38777670', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2864125/']}
jdg_87038
stackexchange
llm_judgeable_groundtruth_similarity
110969
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I've obtained a logistic regression model (via train ) for a binary response, and I've obtained the logistic confusion matrix via confusionMatrix in caret . It gives me the logistic model confusion matrix, though I'm not sure what threshold is being used to obtain it. How do I obtain the confusion matrix for specific threshold values using confusionMatrix in caret ? Now provide the response and nothing else.
Most classification models in R produce both a class prediction and the probabilities for each class. For binary data, in almost every case, the class prediction is based on a 50% probability cutoff. glm is the same. With caret , using predict(object, newdata) gives you the predicted class and predict(object, new data, type = "prob") will give you class-specific probabilities (when object is generated by train ). You can do things differently by defining your own model and applying whatever cutoff that you want. The caret website also has an example that uses resampling to optimize the probability cutoff. tl;dr confusionMatrix uses the predicted classes and thus a 50% probability cutoff Max
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/110969', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/49674/']}
jdg_87039
stackexchange
llm_judgeable_groundtruth_similarity
8427107
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 template function used to dump data of any standard type into a binary output stream. template<typename T> static voiddump ( const T& v, ostream& o ) { o.write ( reinterpret_cast<const char*>(&v), sizeof(T));} Instead of the reinterpret_cast I could also use a C-style (const char*). Is there any particular reason to use reinterpret_cast? I read a few other posts where reinterpret_cast was frowned upon. But the above usage is legal and cannot be replaced with anything else, right? Now provide the response and nothing else.
The problem with C-Style casts is that they do a lot under the hood. See here for a detailed explanation: http://anteru.net/2007/12/18/200/ You should try to always use the C++-casts, makes life easier in the long run. The main problem with C-style casts in this case is that you could have written (char*)(&v) while with reinterpret_cast , you would need an additional const_cast , so it's a bit safer. Plus you can easily find reinterpret_cast with a regex, which is not possible for the C-style casts.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8427107', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1087135/']}
jdg_87040