text
stringlengths
64
81.1k
meta
dict
Q: InvalidInputException when running a jar exported from Eclipse I have installed Hadoop 2.6 in centos7 and it's running fine. But when I run a jar exported from Eclipse, it gives the following error: [root@myspark ~]# hadoop jar fengcount.jar intput output1 17/05/26 21:24:51 INFO client.RMProxy: Connecting to ResourceManager at myspark/192.168.44.100:8032 17/05/26 21:24:53 INFO mapreduce.JobSubmitter: Cleaning up the staging area /tmp/hadoop-yarn/staging/root/.staging/job_1495765615548_0004 Exception in thread "main" org.apache.hadoop.mapreduce.lib.input.InvalidInputException: Input path does not exist: hdfs://myspark:54310/user/root/intput at org.apache.hadoop.mapreduce.lib.input.FileInputFormat.singleThreadedListStatus(FileInputFormat.java:321) at org.apache.hadoop.mapreduce.lib.input.FileInputFormat.listStatus(FileInputFormat.java:264) at org.apache.hadoop.mapreduce.lib.input.FileInputFormat.getSplits(FileInputFormat.java:385) at org.apache.hadoop.mapreduce.JobSubmitter.writeNewSplits(JobSubmitter.java:302) at org.apache.hadoop.mapreduce.JobSubmitter.writeSplits(JobSubmitter.java:319) at org.apache.hadoop.mapreduce.JobSubmitter.submitJobInternal(JobSubmitter.java:197) at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1297) at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1294) at java.security.AccessController.doPrivileged(Native Method) at javax.security.auth.Subject.doAs(Subject.java:422) at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1692) at org.apache.hadoop.mapreduce.Job.submit(Job.java:1294) at org.apache.hadoop.mapreduce.Job.waitForCompletion(Job.java:1315) at hdfs.hadoop_hdfs.fengcount.main(fengcount.java:39) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.apache.hadoop.util.RunJar.run(RunJar.java:221) at org.apache.hadoop.util.RunJar.main(RunJar.java:136) The file input/test1.txt actually exists: [root@myspark ~]# hdfs dfs -ls -R drwxr-xr-x - root supergroup 0 2017-05-26 21:02 input -rw-r--r-- 1 root supergroup 16 2017-05-24 01:57 input/test1.txt My code: package hdfs.hadoop_hdfs; import java.io.IOException; import java.util.StringTokenizer; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.util.GenericOptionsParser; public class fengcount { public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException { // TODO Auto-generated method stub Configuration conf=new Configuration(); String[] otherargs=new GenericOptionsParser(conf,args).getRemainingArgs(); if (otherargs.length!=2) { System.err.println("Usage:fengcount<int><out>"); System.exit(2); } @SuppressWarnings("deprecation") Job job=new Job(conf, "fengcount"); job.setJarByClass(fengcount.class); job.setMapperClass(TokerizerMapper.class); job.setCombinerClass(IntSumReducer.class); job.setReducerClass(IntSumReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); FileInputFormat.addInputPath(job, new Path(otherargs[0])); FileOutputFormat.setOutputPath(job, new Path(otherargs[1])); System.exit(job.waitForCompletion(true)?0:1); } // mapper class public static class TokerizerMapper extends Mapper<Object, Text, Text, IntWritable> { private final static IntWritable one = new IntWritable(1); private Text word = new Text(); @Override public void map(Object key, Text value, Context context) throws IOException, InterruptedException { // TODO Auto-generated method stub System.out.println("key=" + key.toString()); System.out.println("value=" + value.toString()); StringTokenizer itr = new StringTokenizer(value.toString()); while (itr.hasMoreTokens()) { word.set(itr.nextToken()); context.write(word, one); } } } //reduce process public static class IntSumReducer extends Reducer<Text, IntWritable, Text, IntWritable> { private IntWritable result = new IntWritable(); @Override public void reduce(Text key, Iterable<IntWritable> values, Reducer<Text, IntWritable, Text, IntWritable>.Context context) throws IOException, InterruptedException { // TODO Auto-generated method stub int sum = 0; for (IntWritable val : values) { sum += val.get(); } result.set(sum); context.write(key, result); } } //mapreduce process } A: From the error log, I could see hdfs://myspark:54310/user/root/intput, I suspect its incorrect. I guess the path ends with input. Good luck!
{ "pile_set_name": "StackExchange" }
Q: adding images to an HTML Canvas Generated by C# Hello so I have an interesting question for everyone. I have a WPF application that generates an html preview of a report based on Database data and user input. My currently dilemma is that I have a HTML canvas that is created by C# as follows: Canvas myCanvas = new Canvas(); myCanvas.Name = "cvsMyCanvas"; myCanvas.width = userDefinedByTtextBox; myCanvas.height = userDefinedByTtextBox; myCanvas.Visibility = Visibility.Collapsed //Don't show the canvas just yet My question is how do I get an image that I have saved locally to the computer on the canvas in a specific position. (i.e. A HTML Image tag object that is generated by C# and use the move to functionality) (This is a rough example of how I think it should work but this is what I need the help on) Example: string htmlImage = "<img id=\"myImage\" src=\"C:\\Temp\\img.png\">"; htmlImage.moveTo(x,y); ...again the above code is an example of what it is I am trying to do. If anyone could help me out that would be great! Also if I did not provide enough information please let me know and I will let provide it. There seems to be some confusion on what it is I am trying to do, it is most likely my fault do to lack of explanation so allow me to elaborate more. I have images saved in a folder in my temp directory I. I am running a WPF application that has a WebBrowser control that I am using to display HTML. The HTML that is used in that WebBrowser is created in the C# code behind. I am trying to create a canvas that is displayed in the WebBrowser with the images that I have saved in my temp folder. The code I have provided above apparently will not work for what I am trying to accomplish because there is no way to create a canvas in C# and use it in HTML. Let me know if this helps shed some light on this predicament or if even more explanation is required. A: If you want to generate HTML5 code from your C#, the HTML code to generate should look like that: context = canvas.getContext('2d'); var image = new Image(); image.src = <your path>; image.onload = function() { context.drawImage(image, x, y, w, y); } Then, just store it in the String or StringBuilder
{ "pile_set_name": "StackExchange" }
Q: How To Assign Drive Letter To Folder on Mac? I dont want to mount a folder or another drive using SMB in Mac OS X. I want to map a folder or another drive like I can in Windows - using a drive letter. When I map I can be sure that if the resource becomes unavailable, the mapping remains. When a user tries to reconnect to an unavailable resource, Windows attempts to bring that resource back before it produces a resource unavailable failure. I could be wrong but with my experience, using CMD-K and doing SMB://myresourcehere on my iMac results in a mount, but once the resource is turned off or resets or sleeps the mount has to be created again. It COULD be something I am doing wrong and I would like to know if that is the case but also, I would like to know IF I can also simply assign a drive letter to a resource such as a folder on the network somewhere? A: The Mac, based on it's unix-oid heritage (BSD/Darwin) knows of one hierarchical filesystem. What you would call "map a drive letter" on windows is done by "mounting" a drive/volume/remote link in this type of environment. see this question here on superuser for more info. A: I dont want to mount a folder or another drive using SMB in Mac OS X. I want to map a folder or another drive like I can in Windows - using a drive letter. When I map I can be sure that if the resource becomes unavailable, the mapping remains. When a user tries to reconnect to an unavailable resource, Windows attempts to bring that resource back before it produces a resource unavailable failure. The quick answer here is. You can't. The Mac OS X does not know what a drive letter is, nor what do with it. The reason Windows does that is a convulted mess, but... Drive letter assignment is the process of assigning alphabetical identifiers to physical or logical disk drives or partitions (drive volumes) in the root filesystem namespace; this usage is now found only in Microsoft operating systems. Unlike the concept of UNIX mount points, where volumes are named and located arbitrarily in a single hierarchical namespace, drive letter assignment allows multiple highest-level namespaces. Drive letter assignment is thus a process of using letters to name the roots of the "forest" representing the file system; each volume holds an independent "tree" (or, for non-hierarchical file systems, an independent list of files). So, how can you reproduce this? Well, using an automount would be fairly close to what you are asking... But that requires editting the autofs file, and requires the username / password to be hard coded... That's bad security... So, as the answerer in the other page said... If it is a network share just drag the mounted disk to the Login Items tab of the Accounts System Preference pane under the account of your user. The disk will then be automatically mounted on the next login. Or, place a alias of the share on their desktop... Have them click on that and it'll prompt for their credentials... And mount the share.... Or... This isn't quite the best way I would recommend to do it, but it'll work... This is an apple script for Map Network Drive tell application "Finder" try mount volume "afp://username@server/directory_to_mount" end try end tell You have to save as application. Set it run everytime you logon computer by Go to system preferences -> accounts -> Login item Alternatively, "GNARLODIOUS" is in (list disks) if the result is false then mount volume "smb://hostname/sharename" as user name "Username" with password "password" end if on idle if "DISKNAME" is not in (list disks) then mount volume "smb://hostname/sharename" as user name "username" with password "password" end if return 60 end idle
{ "pile_set_name": "StackExchange" }
Q: How to check whether a symbolic expression is rational? I'm using Sympy and I haven't found a simple way of testing for x ∈ Q. Context: I have a set of solutions of a set of very simple, 2DoF eigenvalue problems (e.g., ) and I want to check if one of these solutions is rational (or, in other words, if the solution doesn't contains a square root). A direct way of checking is what I would like the best, but I could accept also an answer that deals with finding (not finding) a square root in the solution. A: The function rational = lambda x: all(i.exp.is_Integer for i in x.atoms(Pow)) is a direct translation of your criteria to return True if all powers (if present) are integers. >>> from sympy import Pow, S, sqrt >>> rational = lambda x: all(i.exp.is_Integer for i in x.atoms(Pow)) >>> rational(S.Half) True >>> rational(sqrt(3)) False >>> rational(3/(1+sqrt(3))) False
{ "pile_set_name": "StackExchange" }
Q: How to cube a number I just started using Python today for my class and one of my problems is cubing a number in Python. I know the way to do it is x^3, but that doesn't work in Python. I was just wondering how I would be able to do that. This is what I tried so far, but as you can see, I keep getting syntax errors: >>> def volume (v) : return v^3 volume(4) SyntaxError: invalid syntax A: Python uses the ** operator for exponentiation, not the ^ operator (which is a bitwise XOR): >>> 3*3*3 27 >>> >>> 3**3 # This is the same as the above 27 >>> Note however that the syntax error is being raised because there is no newline before volume(4): >>> def volume(v): ... return v**3 ... volume(4) File "<stdin>", line 3 volume(4) ^ SyntaxError: invalid syntax >>> >>> def volume(v): ... return v**3 ... # Newline >>> volume(4) 64 >>> When you are in the interactive interpreter, the newline lets Python know that the definition of function volume is finished. A: Actually different symbols mean different things in different programming languages. In some languages, ^ means exponent, but in Python, the exponent operator symbol is **: >>> 3**3 27 The ^ symbol is for the bitwise 'xor' operation: >>> 1^1 0 >>> 1^0 1 Read the documentation on the operator module to see how Python really treats these symbols.
{ "pile_set_name": "StackExchange" }
Q: How to handle image not being downloaded I want to handle the case where the download thread doesn't succeed to download the image from a URL, the following code doesn't seems to fit my purpose: dispatch_queue_t DownloadQueue = dispatch_queue_create("Download Pic", NULL); dispatch_async(DownloadQueue, ^{ NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:detailImageURL]]; dispatch_async(dispatch_get_main_queue(), ^{ if ([imageData isKindOfClass:[NSNull class]]) { detailImageView.image = [UIImage imageNamed:@"no_image_available.jpg"]; } else{ UIImage *image = [UIImage imageWithData:imageData]; detailImageView.image = image; } }); }); dispatch_release(DownloadQueue); A: @Rob, thanx, a workaround fix the issue: dispatch_queue_t DownloadQueue = dispatch_queue_create("Download Pic", NULL); dispatch_async(DownloadQueue, ^{ NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:detailImageURL]]; if (imageData == nil) { detailImageView.image = [UIImage imageNamed:@"no_image_available.jpg"]; }else{ dispatch_async(dispatch_get_main_queue(), ^{ UIImage *image = [UIImage imageWithData:imageData]; detailImageView.image = image; }); } }); dispatch_release(DownloadQueue); Before getting in the async block, test if NSData is nil or not.
{ "pile_set_name": "StackExchange" }
Q: Connected, compact, orientable smooth manifold with finite fundamental group The problem is prove that a connected, compact, orientable smooth manifold $M$ with finite fundamental group has $H^{1}_{dR}(M)=0$. The hint is to apply Suppose $\tilde M$ and $M$ are smooth $n$-manifolds and $\pi:\tilde M\to M$ is a smooth $k$-sheeted covering map. If $\tilde M$ and $M$ are oriented and $\pi$ is orientation-preserving, show that $\int_{\tilde M}\pi^*\omega=k\int_{M}\omega$ for any compactly supported $n$-form $\omega$ on $M$. but i don't know how this proves the result! Any tips? A: I honestly don't know what I was thinking when I wrote that hint -- it doesn't seem to be useful at all. A more appropriate hint would have been something like this: "If $\omega$ is a closed $1$-form on $M$, let $\widetilde\omega$ be the pullback of $\omega$ to the universal cover of $M$, and let $\tilde f$ be a potential function for $\omega$. Define $f\colon M\to \mathbb R$ by letting $f(x)$ be the average value of $\tilde f$ over the preimages of $x$, and show that $f$ is a smooth potential function for $\omega$." This answer by @TedShifrin gives a little bit more detail about how to carry out that argument. There's a different proof of this result in the second edition of my Introduction to Smooth Manifolds -- see Corollary 17.18. A: I don't see immediately how to use a hint specifically about top dimensional forms to deal with something related to $1$-forms (unless it was intended for you to deal with $1$-dimensional submanifolds $N$ of $M$, but you would have to prove something like: if $\int_N \omega = 0$ for every submanifold $N$, then $\omega$ is exact. This can be a bit of a hassle), so I'll allow myself to keep the core idea of that hint but to adapt it to the case of $1$-forms, while also trying to keep elementary. From here on, $\omega$ is a closed $1$-form in $M$. Given any path $c: I \to M$ and a fixed point $p \in \pi^{-1}(c(0))$, you can lift it uniquely to the universal cover as a path $\widetilde{c}$ starting from such point $p$. It is trivial, by definition, that $\int_c \omega=\int_{\widetilde{c}} \pi^*\omega$. But the problem is that since we are aiming to gather conclusions about fundamental groups and loops, we want to handle loops, and the lift of a loop $c$ need not be a loop (of course, otherwise everything would be simply connected!). But since there are finitely many points in $\pi^{-1}(c(0))$, we can concatenate the loop $c$ and start at where the lifted path ended each time, until some loop $l$ is formed. So, we get that $n(l)\int_c \omega = \int_l \pi^* \omega$, where we don't even know what $n(l)$ is (only that it is a non-negative integer), but it doesn't matter: since $l$ is a loop and the universal cover is simply connected, this implies that the right side is zero, and thus $\int_c \omega=0$. But this holds for every $c$. Thus, $\omega$ is exact. Note that this also disregards orientability altogether, which is not necessary for the result to hold. There are plenty of other ways to see this. The link provided by Arnaud in the comments of his answer is one of them. For yet another way, we can argue algebraically, since this is immediate from the Hurewicz theorem, the characterization of finite abelian groups, the universal coefficients theorem and the fact that deRham cohomology is isomorphic to real-valued singular cohomology.
{ "pile_set_name": "StackExchange" }
Q: how to change the color of text partially in android I have a sentence that contains message to be posted to the server like wow! superb pic #superb #pic #111 #222 enjoyed the pic I want to extract the hastags and make them colored and leaving the rest of the text intact. I tried the following code but not working. private void spannableOperationOnHastag() { mPostMessage = edPostMessage.getText().toString().trim(); String strPreHash = null; String strHashText = ""; if (mPostMessage.contains("#")) { try { int index = mPostMessage.indexOf("#"); strPreHash = mPostMessage.substring(0, index); SpannableString spannableString = new SpannableString(strPreHash); String strHashDummy=mPostMessage.substring(index, mPostMessage.length()); int hashCount= StringUtils.countMatches(strHashDummy, "#"); // check for number of "#" occurrence and run forloop for getting the number of hastags in the string int hasIndex=0; for (int i = 0; i <hashCount ; i++) { strHashText = strHashText+strHashDummy.substring(hasIndex, strHashDummy.indexOf(' '))+" "; hasIndex =strHashText.indexOf(" "); // updating new space(" ") position in the index variable } SpannableString spannableStringBlue = new SpannableString(strHashText); spannableStringBlue.setSpan(new ForegroundColorSpan(PublishPostActivity.this.getResources().getColor(R.color.blue)), 0, strHashText.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE); edPostMessage.setText(null); // clearing old string edPostMessage.append(spannableString); // setting extracted coloured text edPostMessage.append(spannableStringBlue); } catch (Exception e) { Log.d(TAG, "validatePostMessage() called with " + "e = [" + e + "]"); } } } A: I solved the problem my self . I any one needs it can refer this code :) private void spannableOperationOnHastag() throws Exception{ mPostMessage = edPostMessage.getText().toString()+" "; // extra space for spannable operations List<Integer> listStartPos = new ArrayList<>(); List<Integer> listEndtPos = new ArrayList<>(); if (mPostMessage.contains("#")){ for (int i = 0; i < mPostMessage.length(); i++) { if (mPostMessage.charAt(i) == '#') { listStartPos.add(i); Log.d(TAG, "startIndex of # = " + i); } } for (int i = 0; i < listStartPos.size(); i++) { int endIndex = mPostMessage.indexOf(' ', listStartPos.get(i)); listEndtPos.add(endIndex); Log.d(TAG, "endIndex of # " + (endIndex)); } SpannableString spanned = SpannableString.valueOf(mPostMessage); for (int i = 0; i < listStartPos.size(); i++) { spanned = new SpannableString(spanned); spanned.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.blue)), listStartPos.get(i), listEndtPos.get(i), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); Log.d(TAG, "substring " + mPostMessage.substring(listStartPos.get(i), listEndtPos.get(i) + 1)); } mPostMessage.trim(); // removing extra space. edPostMessage.setText(null); edPostMessage.setText(spanned); } }
{ "pile_set_name": "StackExchange" }
Q: How to sign java applet with .pfx file? I was trying to sign a jar applet archive with our company .pfx certificate using this guide (and few others from the internet): http://www.globalsign.com/support/ordering-guides/SignJavaCodeAppletsPFX.pdf Everything seems to be fine, but when I try t run apple through the browser I see that 'Publisher' is UNKNOWN (untrusted). And when I go to details I'm able to see proper company name and certificate vendor (GlobalSign). Why it's not properly displayed as known/trusted? The one thing which looks suspicious to me is output of command jarsigner -verify -verbose -certs Applet.jar: (...) sm 1936 Wed Apr 13 03:00:50 CEST 2011 org/my/Applet.class X.509, CN=CompanyName, O=CompanyName, L=Tilst, ST=ProperState, C=DK [certificate is valid from 18.02.10 14:58 to 18.02.13 14:58] s = signature was verified m = entry is listed in manifest k = at least one certificate was found in keystore i = at least one certificate was found in identity scope So looks like 'k = at least one certificate was found in keystore' is missing (should be smk and it is sm). Is it signed only partially? Or what? Is it possible that .pfx file given to me by GlobalSign is somehow wrong on not enough to sign applets? For normal executables it was working just fine... Any ideas? ;) EDIT @Jcs Looks like you are totally right. I checked my PFX file with keytool and I get: Your keystore contains 1 entry Alias name: company_alias Creation date: Apr 13, 2011 Entry type: PrivateKeyEntry Certificate chain length: 1 Certificate[1]: So looks like chain is not complete. I'm not sure if it matters, but there are also few extensions like for example: #1: ObjectId: (some_numbers_here) Criticality=true KeyUsage [ DigitalSignature ] #2: ObjectId: (some_numbers_here) Criticality=false AuthorityInfoAccess [ [ accessMethod: (some_numbers_here) accessLocation: URIName: http://secure.globalsign.net/cacert/ObjectSign.crt] ] (...) Question is: is my PFX file totally wrong, or somehow I need to add globalsign root to it? A: Thanks a lot for all, especially Jcs :) I finally discovered that .pfx file was just imported improperly. I asked my boss to import it for me from scratch with all possible paths/chains/certificates included and now it works :) So if anyone will have similar problem my advice is to try to get/import certificate again - it's rather problem with certificate itself than with signing method.
{ "pile_set_name": "StackExchange" }
Q: How to include php code into tpl file whmcs? I cannot seem to figure out how to get this line to work with whmcs. I want to include this in the header & footer.tpl and tried to do this with {php}{/php} but seems not te be working, and I cannot find the correct solution. include_once $_SERVER['DOCUMENT_ROOT'] . '/SafeGuardPro/protect.php'; A: It is already solved. SOlved the issue by enable this: {php} need to be enabled from Admin Area -> General Settings -> Security tab, " Allow Smarty PHP Tags "
{ "pile_set_name": "StackExchange" }
Q: Concatenating every other line with the next In a text document I want to concatenate every other line with the next. I guess sed is the thing to use? How would this be done? A: This is easiest using paste: paste -s -d' \n' input.txt Although there's a Famous Sed One-Liner (38) to emulate this as in potong's answer. A: Unless you're really insistent that it need be sed, just pipe it through paste -d" " - - A: This might work for you: seq 10 | sed '$!N;s/\n/ /' 1 2 3 4 5 6 7 8 9 10 If is not the last line, append the following line to current line and replace the newline by a space.
{ "pile_set_name": "StackExchange" }
Q: C#: Read on subprocess stdout blocks until ANOTHER subprocess finishes? Here is the C# code I'm using to launch a subprocess and monitor its output: using (process = new Process()) { process.StartInfo.FileName = executable; process.StartInfo.Arguments = args; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardInput = true; process.StartInfo.CreateNoWindow = true; process.Start(); using (StreamReader sr = process.StandardOutput) { string line = null; while ((line = sr.ReadLine()) != null) { processOutput(line); } } if (process.ExitCode == 0) { jobStatus.State = ActionState.CompletedNormally; jobStatus.Progress = 100; } else { jobStatus.State = ActionState.CompletedAbnormally; } OnStatusUpdated(jobStatus); } I am launching multiple subprocesses in separate ThreadPool threads (but no more than four at a time, on a quad-core machine). This all works fine. The problem I am having is that one of my subprocesses will exit, but the corresponding call to sr.ReadLine() will block until ANOTHER one of my subprocesses exits. I'm not sure what it returns, but this should NOT be happening unless there is something I am missing. There's nothing about my subprocess that would cause them to be "linked" in any way - they don't communicate with each other. I can even look in Task Manager / Process Explorer when this is happening, and see that my subprocess has actually exited, but the call to ReadLine() on its standard output is still blocking! I've been able to work around it by spinning the output monitoring code out into a new thread and doing a process.WaitForExit(), but this seems like very odd behavior. Anyone know what's going on here? A: I think it's not your code that's the issue. Blocking calls can unblock for a number of reasons, not only because their task was accomplished. I don't know about Windows, I must admit, but in the Unix world, when a child finishes, a signal is sent to the parent process and this wakes him from any blocking calls. This would unblock a read on whatever input the parent was expecting. It wouldn't surprise me if Windows worked similarly. In any case, read up on the reasons why a blocking call may unblock.
{ "pile_set_name": "StackExchange" }
Q: Unfurl a string Given a square string, produce all the output for the string at every stage of unfurling. The string must unfurl in a clockwise direction one quarter turn at a time. Examples Input: A Output: A Note: I'll also accept the input duplicated for this particular test case only if this helps reduce your byte count. Input: DC AB Output: DC AB D ABC ABCD Input: GFE HID ABC Output: GFE HID ABC HG IF ABCDE IH ABCDEFG I ABCDEFGH ABCDEFGHI Input: JIHG KPOF LMNE ABCD Output: JIHG KPOF LMNE ABCD LKJ MPI NOH ABCDEFG NML OPK ABCDEFGHIJ ON PM ABCDEFGHIJKL PO ABCDEFGHIJKLMN P ABCDEFGHIJKLMNO ABCDEFGHIJKLMNOP Rules This is code-golf so the shortest code in bytes wins. Any reasonable format can be used for I/O assuming it is consistent. Spaces must be used to pad the top lines of the output. Must be able to handle input of all printable characters (including space: \x20-\x7e): !"#$%&'()*+,-./0123456789:;?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ Leading/trailing whitespace is allowed. You can assume the string will always be a square. All standard loopholes are forbidden. Inspiration: Write a square program that outputs the number of times it has been “unrolled”. A: SOGL V0.12, 21 20 19 18 17 bytes ø;[;ο⁴№č▓┼№TJι;jI Try it Here! (→ added because this expects input on the stack) Explanation: ø;[;ο⁴№č▓┼№TJι;jI ø; push an empty string below the input stack with the input GFE,HID,ABC [ while [ToS (the array) isn't empty] do ["", [["G","F","E"],["H","I","D"],["A","B","C"]]] stack at the second time looping ; duplicate 2nd from top [[[H,G], [I,F], [D,E]], "ABC"] ο wrap it in an array [[[H,G], [I,F], [D,E]], ["ABC"]] ⁴ duplicate 2nd from top [[[H,G], [I,F], [D,E]], ["ABC"], [[H,G], [I,F], [D,E]]] № reverse vertically [[[H,G], [I,F], [D,E]], ["ABC"], [[D,E], [I,F], [H,G]]] č▓ join the inner arrays (┼ fails otherwise) [[[H,G], [I,F], [D,E]], ["ABC"], ["DE", "IF", "HG"]] ┼ add the 2 parts together [[[H,G], [I,F], [D,E]], ["ABCDE", " IF", " HG"]] № reverse vertically again [[[H,G], [I,F], [D,E]], [" HG", " IF", "ABCDE"]] T print that without popping [[[H,G], [I,F], [D,E]], [" HG", " IF", "ABCDE"]] J take the last line off [[[H,G], [I,F], [D,E]], [" HG", " IF"], "ABCDE"] ι remove the rest of the array [[[H,G], [I,F], [D,E]], "ABCDE"] ;j remove the last line of the original array ["ABCDE", [[H,G], [I,F]]] I rotate it clockwise ["ABCDE", [[I,H], [F,G]]] A: Python 2, 209 207 205 203 202 201 200 196 bytes -4 bytes thanks to @Quelklef! s=input();l=len;k=''.join;exec"print s;s=[x for x in[' '*l(s[0])+k(x[:-1]for x in s[-2::-1])[t::l(s[0])-1]for t in range(l(s[0]))][:-1]+[s[-1]+k(x[-1]for x in s)[-2::-1]]if x.strip()];"*(2*l(s)-1) Try it online! Python 2, 219 217 215 213 212 211 207 bytes s=input();l=len;k=''.join;exec"print'\\n'.join(s);s=[x for x in[' '*l(s[0])+k(x[:-1]for x in s[-2::-1])[t::l(s[0])-1]for t in range(l(s[0]))][:-1]+[s[-1]+k(x[-1]for x in s)[-2::-1]]if x.strip()];"*(2*l(s)-1) Try it online! The first one outputs as a list of Strings, the second one outputs as ASCII-art. A: Charcoal, 42 35 bytes AEθSθW⊟θ«⪫θ¶AEι⮌⪫Eθ§μλωθ⊞υι↙←⮌⪫υωD⎚ Try it online! Link is to verbose version of code. Edit: Saved 7 bytes mostly by switching from character arrays to strings. Explanation: AEθSθ Read the input square as an array of strings into the variable q. W⊟θ« While the last string in the array is not empty, remove it. ⪫θ¶ Print the rest of the array. AEι⮌⪫Eθ§μλωθ Rotate the rest of the array by looping through each character of the last string and joining the lth character of every remaining string in the reversed array. ⊞υι↙←⮌⪫υω Append the previously removed last string to u, which holds the unfurled value, and print it. D⎚ Output the result and then clear the canvas ready for the next iteration. Note that this version outputs the final unfurl on a separate line, if this is undesirable then for 38 bytes: AEθSθW⊟θ«⊞υι←E⁺⟦⪫υω⟧⮌θ⮌κAEι⮌⪫Eθ§μλωθD⎚ Try it online! Link is to verbose version of code. Explanation: ←E⁺⟦⪫υω⟧⮌θ⮌κ reverses the current array, prepends the unfurled line, then reverses the characters in each line, then prints everything upside-down, thus producing the desired result.
{ "pile_set_name": "StackExchange" }
Q: Preloader for SWF with embed bytearray The complied SWF is not showing the preloader until the whole SWF completely loaded. Any hepl would be really appreciated, I googled the whole night couldnt find anything on this, at least for me. A: You can not embed the ByteArray into your main document class, because classes that are referenced from the document class will automatically be included on frame 1. The best way to preload assets is to have a separate Preloader class and Main class. You want your Preloader class to export on frame 1, and your Main class and assets on frame 2. Unfortunately, this is trickier than it should be, but here's how you can do it: Set your document class to Preloader. This class contains your loaderInfo code. However, when you finish loading, do not instantiate Main directly, i.e. do not do var main:Main = new Main(). This will automatically cause Main to be compiled onto frame 1 regardless of what you do. Instead, instantiate it indirectly, like this: nextFrame(); // you sometimes need to do this for the player to register classes exported on frame 2 var mainClass:Class = flash.utils.getDefinitionByName("Main") as Class; var main:Sprite = new mainClass(); addChild(main); This will stop the compiler from automatically yanking Main onto frame 1. Next, if you are using the Flash CS3+ IDE, go to File->Publish Settings->Flash->ActionScript 3.0 settings and change the "Export classes on frame" setting to frame 2. Then, on frame 2 of your movie, place an empty MovieClip. Inside this MovieClip, place a reference to your Main class by putting this code: var dummy:Main;. The reason you have to do this is so that the compiler will still know you are using Main, so it will actually compile it into the movie, otherwise it would not compile it at all. You also don't want to put this on the main timeline, because any code references on the main timeline automatically get yanked onto frame 1. In the IDE, a helpful trick to check that things have exported in their proper place is to check "Generate size report" in Publish Properties->Flash. You can examine the report and will easily notice if junk has exported onto frame 1. If you are using Flash Builder, FlashDevelop, or FDT, the process is basically the same--create separate Preloader and Main classes, and instantiate Main indirectly from Preloader. But to signal the compiler to compile Main on a frame after Preloader, put this metatag above public class Main in Main.as: [Frame(factoryClass="Preloader")] FlashDevelop can also introspect SWF files by click on the + beside it in the Project tab. It will show you what assets have been exported onto which frames. Ideally, you only want the bare minimum of Preloader on frame 1.
{ "pile_set_name": "StackExchange" }
Q: Control results of clicking on expandable listview I need to implement expandable list view to my application. This list will be used to add some ingredients to pizza, so I need to increase the prize when the ingredient is checked and decrease when ingredient is unchecked. I find the code for custom expandable list and modify to match to my needs. thats the code for adapter: public class ExpandableListAdapter extends BaseExpandableListAdapter { private Context _context; private List<String> _listDataHeader; // header titles // child data in format of header title, child title private HashMap<String, List<customPizzaSendInfo>> _listDataChild; public ExpandableListAdapter(Context context, List<String> listDataHeader, HashMap<String, List<customPizzaSendInfo>> listChildData) { this._context = context; this._listDataHeader = listDataHeader; this._listDataChild = listChildData; } @Override public Object getChild(int groupPosition, int childPosititon) { return this._listDataChild.get(this._listDataHeader.get(groupPosition)) .get(childPosititon); } @Override public long getChildId(int groupPosition, int childPosition) { return childPosition; } @Override public View getChildView(int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { final customPizzaSendInfo childText = (customPizzaSendInfo) getChild(groupPosition, childPosition); if (convertView == null) { LayoutInflater infalInflater = (LayoutInflater) this._context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = infalInflater.inflate(R.layout.expander_list_item, null); } CheckBox txtListChild = (CheckBox) convertView .findViewById(R.id.lblListItem); txtListChild.setText(childText.nameString); txtListChild.setChecked(childText.choosen); txtListChild.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked == true) { prizeSmall += childText.priceSmallDouble; prizeBig += childText.priceBigDouble; normalnaButton.setText("Normalna " +String.valueOf(prizeSmall)); duzaButton.setText("Duża " + String.valueOf(prizeBig)); Toast.makeText(getApplicationContext(), Double.toString(childText.priceSmallDouble), Toast.LENGTH_LONG).show(); }else { prizeSmall -= childText.priceSmallDouble; prizeBig -= childText.priceBigDouble; normalnaButton.setText("Normalna " +String.valueOf(prizeSmall)); duzaButton.setText("Duża " + String.valueOf(prizeBig)); Toast.makeText(getApplicationContext(), "unchecked", Toast.LENGTH_LONG).show(); } } }); return convertView; } @Override public int getChildrenCount(int groupPosition) { return this._listDataChild.get(this._listDataHeader.get(groupPosition)) .size(); } @Override public Object getGroup(int groupPosition) { return this._listDataHeader.get(groupPosition); } @Override public int getGroupCount() { return this._listDataHeader.size(); } @Override public long getGroupId(int groupPosition) { return groupPosition; } @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { String headerTitle = (String) getGroup(groupPosition); if (convertView == null) { LayoutInflater infalInflater = (LayoutInflater) this._context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = infalInflater.inflate(R.layout.expander_list_group, null); } TextView lblListHeader = (TextView) convertView .findViewById(R.id.lblListHeader); lblListHeader.setTypeface(null, Typeface.BOLD); lblListHeader.setText(headerTitle); return convertView; } @Override public boolean hasStableIds() { return false; } @Override public boolean isChildSelectable(int groupPosition, int childPosition) { return true; } } this is the code for class which contain data customPizzaSendInfo public class customPizzaSendInfo { public String nameString; public boolean choosen; public Double priceSmallDouble; public Double priceBigDouble; public customPizzaSendInfo(String nameString, boolean choosen, Double priceSmallDouble, Double priceBigDouble) { super(); this.nameString = nameString; this.choosen = choosen; this.priceSmallDouble = priceSmallDouble; this.priceBigDouble = priceBigDouble; } } there are two problems: how update the _listDataChild, cause when I close expander and then open it back I get the result like it was putted in, when I scrool the list, my price increases, so the android interpreting my touch to scroll like I was checking object, but the checkbox doesn't change state, If i try to make on any click litener to monitoring the state of children, I got no reaction, so I decide to make it inside AdapterClass. How to solve it UPDATE I try to update this _listDataChild which keeps data about objects, so I modify the on checkChanged @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked == true) { // //Toast.makeText(getApplicationContext(), Integer.toString(childPosition) + " " + childText.nameString, Toast.LENGTH_LONG).show(); //Toast.makeText(getApplicationContext(), _listDataChild.get("Skonfiguruj Dodatki").get(childPosition).nameString, Toast.LENGTH_LONG).show(); _listDataChild.get("Skonfiguruj Dodatki").get(childPosition).choosen = true; prizeSmall += childText.priceSmallDouble; prizeBig += childText.priceBigDouble; normalnaButton.setText("Normalna " +String.valueOf(prizeSmall)); duzaButton.setText("Duża " + String.valueOf(prizeBig)); Toast.makeText(getApplicationContext(), Double.toString(childText.priceSmallDouble), Toast.LENGTH_LONG).show(); }else { _listDataChild.get("Skonfiguruj Dodatki").get(childPosition).choosen = false; prizeSmall -= childText.priceSmallDouble; prizeBig -= childText.priceBigDouble; normalnaButton.setText("Normalna " +String.valueOf(prizeSmall)); duzaButton.setText("Duża " + String.valueOf(prizeBig)); Toast.makeText(getApplicationContext(), "unchecked", Toast.LENGTH_LONG).show(); } } }); When i scroll the object become unchecked ... SOLUTION How I solve it by add onclick listener in the ExpandableListAdapter and I use advice of @Abd El-Rahman El-Tamawy to update _listDataChild and it works like a charm, here is the code. txtListChild.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getApplicationContext(), Integer.toString(childPosition), Toast.LENGTH_LONG).show(); if(_listDataChild.get("Skonfiguruj Dodatki").get(childPosition).choosen) { _listDataChild.get("Skonfiguruj Dodatki").get(childPosition).choosen = false; } else { _listDataChild.get("Skonfiguruj Dodatki").get(childPosition).choosen = true; } } }); A: You Should save the state of the button in your HashMap also in your onClickListener to enable your adapter to redraw the final state from the HashMap when you collapse and expand the parent again as following @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked == true) { childText. prizeSmall += childText.priceSmallDouble; prizeBig += childText.priceBigDouble; normalnaButton.setText("Normalna " +String.valueOf(prizeSmall)); duzaButton.setText("Duża " + String.valueOf(prizeBig)); Toast.makeText(getApplicationContext(), Double.toString(childText.priceSmallDouble), Toast.LENGTH_LONG).show(); }else { prizeSmall -= childText.priceSmallDouble; prizeBig -= childText.priceBigDouble; normalnaButton.setText("Normalna " +String.valueOf(prizeSmall)); duzaButton.setText("Duża " + String.valueOf(prizeBig)); Toast.makeText(getApplicationContext(), "unchecked", Toast.LENGTH_LONG).show(); } //Get the HashMap Item of the current position and set all its value with the new values this._listDataChild.get("yourCurrentKey").get(position).choosen = !this._listDataChild.get("yourCurrentKey").get(position)..choosen; //Complete saving all your data
{ "pile_set_name": "StackExchange" }
Q: Por que no funciona mi archivo javascript? este es mi código: <script src="resource_path('js/jquery-3.2.1.slim.min.js')"></script> <script type="text/javascript"> $(function () { $('#ModalProducto').on('shown.bs.modal', function (e) { $('.focus').focus(); }) }); @yield('jscript') </script> Descargué el js porque necesito que esto funcione offline, si yo lo dejo de la siguiente forma el codigo funciona: <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script type="text/javascript"> $(function () { $('#ModalProducto').on('shown.bs.modal', function (e) { $('.focus').focus(); }) }); @yield('jscript') </script> Que puedo hacer? trabajo con laravel incluso coloque el js en el webpack pero al parecer algo hago mal porque no me funciona el archivo, podrían ayudarme? A: El helper resource_path() lleva al directorio de resources, el cual no es un directorio público, o al menos no debería serlo, por lo cual no puedes acceder a dicho archivo. Deberías almacenarlo en una ruta similar a public/js/, y utiliza el helper asset() para referenciar el archivo, también debes incluirlo según la sintaxis de blade: {{ asset('/js/jquery.js') }}
{ "pile_set_name": "StackExchange" }
Q: calculating a group element in a discrete log problem An encryption scheme is based on the DLP: $c = a^x mod ~b$, where $x$ is hard to find. How hard is it to find $a$, given all the other values, $c$, $x$ and $b$? Would this make the problem easy to solve? $c^{1/x} = (a^x)^{1/x} mod ~b$ An example would be great to better understand. A: If you know the factorization of $b$, it's easy. One way would be to compute $x^{-1}$, the multiplicative inverse modulo $\phi(b)$, and then compute $c^{x^{-1}} \bmod b$ If you don't know the factorization of $b$, it's hard; in fact, it's essentially the RSA problem.
{ "pile_set_name": "StackExchange" }
Q: Problemas ao usar camera, gerar, editar e salvar imagem Tô tentando criar um app, e parte dele é usar a camera do celular pra tirar uma foto, que automaticamente será diminuída e salva em pastas separadas por ano / mes/ imgHora.jpg. Para versões antigas o código funcionou, mas pra versões mais recentes tá dando erro. Já vi diversas perguntas similares em inglês e português, porém não consegui resolver, se alguém puder me dar um help agradeço. Já tentei usar Provider, mas só piorei tudo. O erro principal é este: android.os.FileUriExposedException: file:///storage/emulated/0/Pictures/CamMur/2018/October/28_182120.jpg exposed beyond app through ClipData.Item.getUri() Referente à: mIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(caminho))); Outra coisa, quero que ao clicar de novo no botão, ele gere uma nova imagem. Se alguém tiver uma solução melhor que esta minha é bem vinda. Sem ele, a primeira vez que entro no programa e clico no botão ele gera uma imagem e salva, mas se eu clicar denovo no botão ele sobrepoem a foto anterior. Intent intent = getIntent(); finish(); startActivity(intent); Código completo: package com.example.admin.camera; import android.Manifest; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Environment; import android.provider.MediaStore; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; public class MainActivity extends AppCompatActivity { public static final int PROCESSO_TIRAR_FOTO = 10; private Context context; private ImageView iv_foto; private Button btn_tf; private int largura; private int altura; private String caminho; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.telainicial); iniciarVariaveis(savedInstanceState); iniciarAcoes(); } @Override //se a tela morrer, faz cast e recria a tela; protected void onSaveInstanceState(Bundle outState) { outState.putInt("largura", largura); outState.putInt("altura", altura); outState.putString("caminho", caminho); super.onSaveInstanceState(outState); } private void iniciarVariaveis(Bundle savedInstanceState) { //bundle variavel de cache context = getBaseContext(); // iv_foto = findViewById(R.id.iv_foto); btn_tf = findViewById(R.id.btn_tf); //Permissão para acessar camera if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.CAMERA}, 0); } // //Analisa savedInstance para recuperar os valores e inicializar as variaveis if (savedInstanceState != null) { altura = savedInstanceState.getInt("altura"); largura = savedInstanceState.getInt("largura"); // caminho = savedInstanceState.getString("caminho"); } else { File path; File dir; String timeYear; String timeMoth; String timeDayHour; String timeAll; timeYear = new SimpleDateFormat("yyyy", Locale.getDefault()).format(new Date()); timeMoth = new SimpleDateFormat("MMMM", Locale.getDefault()).format(new Date()); timeDayHour ="/" + new SimpleDateFormat("dd_HHmmss", Locale.getDefault()).format(new Date()) + ".jpg"; timeAll = "CamMur/" +timeYear + "/" + timeMoth ; //Cria pasta com nome CamMUR e um arquivo temporário foto.jpg path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); dir = new File(path, timeAll); if (!dir.exists()) { if (!dir.mkdirs()) { Log.d("LabCamera", "Pasta não criada"); } } caminho = dir.getPath() + timeDayHour ; } } private void iniciarAcoes() { btn_tf.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = getIntent(); finish(); startActivity(intent); largura = iv_foto.getWidth(); altura = iv_foto.getHeight(); // //chamar camera //não é de forma explicita, pois não sei a classe que chama a camera Intent mIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //saida da foto pro caminho criado; mIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(caminho))); // startActivityForResult(mIntent, PROCESSO_TIRAR_FOTO); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == PROCESSO_TIRAR_FOTO && resultCode == RESULT_OK) { configurarImagem(resultCode); } else { Toast.makeText(context, "Operação Cancelada", Toast.LENGTH_SHORT).show(); } } private void configurarImagem(int resultCode) { int larguraFOTO; int alturaFOTO; //Não gera um bitmap. Ele inicializa a variavel options com as informações // vindas da imagem: altura e largura; BitmapFactory.Options options = new BitmapFactory.Options(); //não consome a foto options.inJustDecodeBounds = true; BitmapFactory.decodeFile(caminho, options); larguraFOTO = options.outWidth; alturaFOTO = options.outHeight; //Divide a largura da foto pela largura do ImageView int escala = Math.min(larguraFOTO /largura, alturaFOTO/altura); options.inJustDecodeBounds = false; options.inSampleSize = escala; //GERA O BITMAP Bitmap bm = BitmapFactory.decodeFile(caminho, options); iv_foto.setImageBitmap(bm); } } Manifest: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.admin.camera"> <uses-permission android:name="android.permission.CAMERA"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity" android:configChanges="orientation" android:screenOrientation="portrait"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> A: Vamos direto no ponto, que está ocasionando o erro. Está faltando a declaração do File Provider. Insira no Manifest.xml: <application> . . . <provider android:name="android.support.v4.content.FileProvider" android:authorities="${applicationId}.provider" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/provider_paths" /> </provider> </application> E crie o arquivo provider_paths e diretório xml (caso não esteja criado). Com o seguinte código: <?xml version="1.0" encoding="utf-8"?> <paths> <external-path name="external_files" path="." /> </paths> Você precisará modificar a chamada da intent da Câmera: mIntent.putExtra(MediaStore.EXTRA_OUTPUT, FileUtil.getUri(getApplicationContext(), new File(caminho))); Para a Activity não ficar gigante, crie uma nova classe contendo o código do FileUtil, com a finalidade de separar o tipo de chamada, pela versão do android no dispositivo: public class FileUtil { public static Uri getUri(Context context, File file) { Uri uri; if (isAndroidMarshmallowOrSuperiorVersion()) { uri = getUriFrom(context, file); } else { uri = Uri.fromFile(file); } return uri; } private static Uri getUriFrom(Context context, File file) { return FileProvider.getUriForFile(context, getAuthority(), file); } @NonNull private static String getAuthority() { return BuildConfig.APPLICATION_ID + ".provider"; } private static boolean isAndroidMarshmallowOrSuperiorVersion() { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M; } }
{ "pile_set_name": "StackExchange" }
Q: Captured a city, but it's completely non-functioning I've just captured my first city, and it's uh... not working. The borders don't extend beyond the single tile where the city is, and I can't build anything. What do I do? In Civ 3, you'd sometimes get a message after capturing a city informing you of a resistance, which you could quell by garrisonning military units there. Is that what's going on? I didn't get any message informing me of it. A: As stated in the comments, a city captured has to go through X turns of resistance before you can do anything with it, and its borders will remain at zero for that duration as well. There is an exception for recapturing a city that you originally owned (planted with a settler) but previously lost. The duration is both on the map screen and the top of the city screen: The formula for duration of resistance (which cannot be reduced by any game mechanic) can be found in the source code under ...\CvGameCoreDLL\CvPlayer.cpp: pNewCity->changeOccupationTimer(((GC.getDefineINT("BASE_OCCUPATION_TURNS") + ((pNewCity->getPopulation() * GC.getDefineINT("OCCUPATION_TURNS_POPULATION_PERCENT")) / 100)) * (100 - iTeamCulturePercent)) / 100); In other words, there is a flat resistance duration plus additional time for each population point modified by how much culture you have in the city. Without mods, using the constants found under \Assets\XML\GlobalDefines.xml, this comes out to be 3 + [Population] * 0.5 * (100 - [Your Culture]) / 100 So for most conquests, you will face resistance of 3 turns plus half the city size.
{ "pile_set_name": "StackExchange" }
Q: Using '_all_docs?keys=' to query db and specifying which fields to return I'd like to do a bulk query to cloudant db. By supplying a list of _ids (primary key), and have db return any documents with matching _ids. This is working as shown below. But I'd like to return _id, _rev and field_name also. Is there a way to do this without using include_docs=true? Request: http://{db-host}/{db-name}/_all_docs?keys=["1e0a2d30d18d95b9bcc05d92c8736eab","181687d2f16debc10f9e365cc4002371"] Response: { "total_rows": 3, "rows": [{ "id": "1e0a2d30d18d95b9bcc05d92c8736eab", "key": "1e0a2d30d18d95b9bcc05d92c8736eab", "value": { "rev": "1-a26b67f478e4f3f8fd49779a66fc7949" } }, { "id": "181687d2f16debc10f9e365cc4002371", "key": "181687d2f16debc10f9e365cc4002371", "value": { "rev": "1-7338901ca1c5c06ef81a6971aa6e8f9d" } }] } A: No. The index of _all_docs does not contain the field_name data. The only way to get it using this view is with include_docs. Otherwise you will have to write (and index) your own view that emits what you want. map: function(doc) { emit(doc._id, { _id: doc._id, _rev: doc._rev, field_name: doc.field_name }); }
{ "pile_set_name": "StackExchange" }
Q: Statsmodels throws "overflow in exp" and "divide by zero in log" warnings and pseudo-R squared is -inf I want to do a Logistic Regression in Python using Statsmodels. X and y have 750 rows each, y is the the binary outcome and in X are the 10 features (including the intecept). Here are the first 12 rows of X (last column is the intercept): lngdp_ lnpop sxp sxp2 gy1 frac etdo4590 geogia \ 0 7.367709 16.293980 0.190 0.036100 -1.682 132.0 1 0.916 1 7.509883 16.436258 0.193 0.037249 2.843 132.0 1 0.916 2 7.759187 16.589224 0.269 0.072361 4.986 132.0 1 0.916 3 7.922261 16.742384 0.368 0.135424 3.261 132.0 1 0.916 4 8.002359 16.901037 0.170 0.028900 1.602 132.0 1 0.916 5 7.929126 17.034786 0.179 0.032041 -1.465 132.0 1 0.916 6 6.594413 15.627563 0.360 0.129600 -9.321 4134.0 0 0.648 7 6.448889 16.037861 0.476 0.226576 -2.356 3822.0 0 0.648 8 8.520786 16.919334 0.048 0.002304 2.349 434.0 1 0.858 9 8.637107 16.991980 0.050 0.002500 2.326 434.0 1 0.858 10 8.708144 17.075489 0.042 0.001764 1.421 465.0 1 0.858 11 8.780480 17.151779 0.080 0.006400 1.447 496.0 1 0.858 peace intercept 0 24.0 1.0 1 84.0 1.0 2 144.0 1.0 3 204.0 1.0 4 264.0 1.0 5 324.0 1.0 6 1.0 1.0 7 16.0 1.0 8 112.0 1.0 9 172.0 1.0 10 232.0 1.0 11 292.0 1.0 This is my code: import statsmodels.api as sm logit = sm.Logit(y, X, missing='drop') result = logit.fit() print(result.summary()) This is the output: Optimization terminated successfully. Current function value: inf Iterations 9 /home/ipattern/anaconda3/lib/python3.6/site-packages/statsmodels/discrete/discrete_model.py:1214: RuntimeWarning: overflow encountered in exp return 1/(1+np.exp(-X)) /home/ipattern/anaconda3/lib/python3.6/site-packages/statsmodels/discrete/discrete_model.py:1264: RuntimeWarning: divide by zero encountered in log return np.sum(np.log(self.cdf(q*np.dot(X,params)))) Logit Regression Results ============================================================================== Dep. Variable: warsa No. Observations: 750 Model: Logit Df Residuals: 740 Method: MLE Df Model: 9 Date: Tue, 12 Sep 2017 Pseudo R-squ.: -inf Time: 11:16:58 Log-Likelihood: -inf converged: True LL-Null: -4.6237e+05 LLR p-value: 1.000 ============================================================================== coef std err z P>|z| [0.025 0.975] ------------------------------------------------------------------------------ lngdp_ -0.9504 0.245 -3.872 0.000 -1.431 -0.469 lnpop 0.5105 0.128 3.975 0.000 0.259 0.762 sxp 16.7734 5.206 3.222 0.001 6.569 26.978 sxp2 -23.8004 10.040 -2.371 0.018 -43.478 -4.123 gy1 -0.0980 0.041 -2.362 0.018 -0.179 -0.017 frac -0.0002 9.2e-05 -2.695 0.007 -0.000 -6.76e-05 etdo4590 0.4801 0.328 1.463 0.144 -0.163 1.124 geogia -0.9919 0.909 -1.091 0.275 -2.774 0.790 peace -0.0038 0.001 -3.808 0.000 -0.006 -0.002 intercept -3.4375 2.486 -1.383 0.167 -8.310 1.435 ============================================================================== The coefficients, std err, p value etc. at the bottom are correct (I know this because I have the "solution"). But as you can see the Current function value is inf which is wrong I think. And I get two warnings. Apparently statsmodels does np.exp(BIGNUMBER), e.g. np.exp(999) and np.log(0) somewhere. Also Pseudo R-squ. is -inf and Log-Likelihood is -inf, which shouldn't be -inf I think. So what am I doing wrong? EDIT: X.describe(): lngdp_ lnpop sxp sxp2 gy1 \ count 750.000000 750.000000 750.000000 750.000000 750.000000 mean 7.766948 15.702191 0.155329 0.043837 1.529772 std 1.045121 1.645154 0.140486 0.082838 3.546621 min 5.402678 11.900227 0.002000 0.000004 -13.088000 25% 6.882694 14.723123 0.056000 0.003136 -0.411250 50% 7.696212 15.680984 0.111000 0.012321 1.801000 75% 8.669355 16.652981 0.203000 0.041209 3.625750 max 9.851826 20.908354 0.935000 0.874225 14.409000 frac etdo4590 geogia peace intercept count 750.000000 750.000000 750.000000 750.000000 750.0 mean 1812.777333 0.437333 0.600263 348.209333 1.0 std 1982.106029 0.496388 0.209362 160.941996 0.0 min 12.000000 0.000000 0.000000 1.000000 1.0 25% 176.000000 0.000000 0.489250 232.000000 1.0 50% 864.000000 0.000000 0.608000 352.000000 1.0 75% 3375.000000 1.000000 0.763000 472.000000 1.0 max 6975.000000 1.000000 0.971000 592.000000 1.0 logit.loglikeobs(result.params): array([ -4.61803704e+01, -2.26983454e+02, -2.66741244e+02, -2.60206733e+02, -4.75585266e+02, -1.76454554e+00, -4.86048292e-01, -8.02300533e-01, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -6.02780923e+02, -4.12209348e+02, -6.42901288e+02, -6.94331125e+02, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, ... (logit.exog * np.array(result.params)).min(0): array([ -9.36347474, 6.07506083, 0.03354677, -20.80694575, -1.41162588, -1.72895247, 0. , -0.9631801 , -2.23188846, -3.4374963 ]) Datasets: X: https://pastebin.com/VRNSepBg y: https://pastebin.com/j2Udyc7m A: I am surprised that it still converges in this case. There can be convergence problems with overflow with exp functions as used in Logit or Poisson when the x values are large. This can often be avoided by rescaling the regressors. However, in this case my guess would be outliers in x. The 6th column has values like 4134.0 while the others are much smaller. You could check the loglikelihood for each observation logit.loglikeobs(result.params) to see which observations might cause problems, where logit is the name that references the model Also the contribution of each predictor might help, for example np.argmax(np.abs(logit.exog * result.params), 0) or (logit.exog * result.params).min(0) If it's just one or a few observations, then dropping them might help. Rescaling the exog will most likely not help for this, because upon convergence it will just be compensated by a rescaling of the estimated coefficient. Also check whether there is not an encoding error or a large value as place holder for missing values. edit Given that the number of -inf in loglikeobs seems to be large, I think that there might be a more fundamental problem than outliers, in the sense that the Logit model is not the correctly specified maximum likelihood model for this dataset. Two possibilites in general (because I haven't seen the dataset): Perfect separation: Logit assumes that the predicted probabilities stay away from zero and one. In some cases an explanatory variable or combination of them allows perfect prediction of the dependent variable. In this case the parameters are either not identified or go to plus or minus infinity. The actual parameter estimates depend on the convergence criteria for the optimization. Statsmodels Logit detects some cases for this and then raises and PerfectSeparation exception, but it doesn't detect all cases with partial separation. Logit or GLM-Binomial are in the one parameter linear exponential family. The parameter estimates in this case only depend on the specified mean function and the implied variance. It does not require that the likelihood function is correctly specified. So it is possible to get good (consistent) estimates even if the likelihood function is not correct for the given dataset. In this case the solution is a quasi-maximum likelihood estimator, but the loglikelihood value is invalid. This can have the effect that the results in terms of convergence and numerical stability depend on the computational details for how the edge or extreme cases are handled. Statsmodels is clipping the values to keep them away from the bounds in some cases but not yet everywhere. The difficulty is in figuring out what to do about numerical problems and to avoid returning "some" numbers without warning the user when the underlying model is inappropriate for or incompatible with the data. Maybe llf = -inf is the "correct" answer in this case, and any finite numbers are just approximation for -inf. Maybe it's just a numerical problem because of the way the functions are implemented in double precision.
{ "pile_set_name": "StackExchange" }
Q: Python-docx: Editing a pre-existing Run import docx doc = docx.Document('CLT.docx') test = doc.paragraphs[12].runs[2].text print(test) doc.save(input('Name of docx file? Make sure to add file extension ')) I've trying to figure out some way to add/edit text to a pre-existing run using python-docx. I've tried test.clear() just to see if I can remove it, but that doesn't seem to work. Additionally, I tried test.add_run('test') and that didn't work either. I know how to add a new run but it will only add it at the end of the paragraph which doesn't help me much. Currently, 'print' will output the text i'd like to alter within the document, "TERMOFINTERNSHIP". Is there something i'm missing? A: The text of a run can be edited in its entirety. So to replace "ac" with "abc" you just do something like this: >>> run.text "ac" >>> run.text = "abc" >>> run.text "abc" You cannot simply insert characters at some location; you need to extract the text, edit that str value using Python str methods, and replace it entirely. In a way of thinking, the "editing" is done outside python-docx and you're simply using python-docx for the "before" and "after" versions. But note that while this is quite true, it's not likely to benefit you much in the general case because runs break at seemingly random locations in a line. So there is no guarantee your search string will occur within a single run. You will need an algorithm that locates all the runs containing any part of the search string, and then allocate your edits accordingly across those runs. An empty run is valid, so run.text == "" may be a help when there are extra bits in the middle somewhere. Also note that runs can be formatted differently, so if part of your search string is bold and part not, for example, your results may be different than you might want.
{ "pile_set_name": "StackExchange" }
Q: Xcopy does not copy all files I wrote a tool for our department that generates a protocol from an Atlassian Datasource. Because in some cases the tool didn't worked when started from the company's netdrive, a colleague wrote the following batch file to simply copy the relevant files locally, which lead to a working program for all. mkdir C:\QuickProtocol\ mkdir C:\QuickProtocol\Templates\ mkdir C:\QuickProtocol\In\ mkdir C:\QuickProtocol\Out\ mkdir C:\QuickProtocol\Templates\Protokoll-Dateien\ XCOPY \\*NetDrivePath*\QuickProtocol.exe C:\QuickProtocol\ /y XCOPY \\*NetDrivePath*\QuickProtocol.pdb C:\QuickProtocol\ /d /y XCOPY \\*NetDrivePath*\Languages.xml C:\QuickProtocol\ /d /y XCOPY \\*NetDrivePath*\PrimeCore.dll C:\QuickProtocol\ /d /y XCOPY \\*NetDrivePath*\Templates C:\QuickProtocol\Templates\ /d /y /s But now a colleague that changed departments, but has still access to the files on the netdrive, tried the batch file again. Strangely in his case, as well as in the case of some other colleagues who reported to him, the batch file only copy's the Templates Folder and creates the directories named above. What could be the reason for this? A: Thanks for all the answers, in my case changing Xcopy to Copy for the few single file Copys helped, at least it seems so. Hopefully it stays this way^^
{ "pile_set_name": "StackExchange" }
Q: Painting over bright color with Kilz and single-coat of one-coat paint: overkill? Underkill? We are expecting to close on a new house Friday, and my out-of-state father-in-law will be there for the weekend only to help us paint a couple of bedrooms. The rooms are bright colors now, and we want to replace the bright colors with a light gray on the wall and a white on the wainscoting. We intend to use a coat of Kilz primer, and he is recommending we use an expensive one-coat paint (Behr Marquee) on top of it. Will a single coat probably suffice? Is it overkill to use an expensive paint+primer on top of a primer? We will be painting with semi-gloss, and I believe that is what is on the walls already. A: I've used the higher end paint+primers from both big orange (Behr) and big blue (Valspar), and found that they cover very well in a single coat. You may have to do a second touch-up coat; especially where you've cut it with a brush, but they cover well in the first coat. If you're doing any patching, or have new drywall or joint compound to cover, you'll want to use a primer first. Otherwise you may be able to skip the primer.
{ "pile_set_name": "StackExchange" }
Q: Automatic date stamp backup bat file changes stamp by itself after second loop So I've been trying to make a automatic backup and date stamp bat program for a folder and its contents. The first time it loops it does exactly what i want it to. But the second time the loop runs, it changes the folder by removing the first 3 numbers and the 0 in 2014. It looks like this. First loop C:\users\username\desktop\05.26.2014\17.11\contents(This is right) Second loop C:\user\username\desktop\6.2.14\17\contents Third loop C:\users\username\desktop\2.1\no time folder\contents There is a time sub folder in the date folder it is also affected by this until it does not generate anymore. Can anyone tell what is causing this, here is what i have in the bat file @echo off set /a x=0 :loop1 timeout /t 600 set day="%date:~-10,2%" set month="%date:~-7,2%" set year="%date:~-4,4%" set hour="%time:~-11,2%" set minute="%time:~-8,2%" set time="%hour%.%minute%" set date="%day%.%month%.%year%" echo d | XCOPY Z:\copydirectory "G:\pastdirectory" /e echo Loop number -^>%x% set /a x=%x%+1 if %x% NEQ 10000 goto loop1 pause Thanks to anyone who answers. Edit: changed variable time to T and variable date to D That seems to have fixed it. A: You should not use " in your set statements. This will put the double-quotes into the actual result. Assuming that your first values were parsed correctly, when you next construct date, the result will be: ""26"."05"."2014"" Then, next time "%date:~-4,4%" will give you "14""". Remove all the quotes from set statements and try again. If you still have issues, you may need to look into delayed variable expansion. Check out the setlocal and endlocal commands.
{ "pile_set_name": "StackExchange" }
Q: A little bit of string cast Update: When a database returns a value through the scalar, it will always be an object. So when the value is returned you should have a preconceived notion of what the type will be. Why would you use ToString(); when you you have a SELECT which passes two parameters. As if it doesn't exist it will always throw a null. So in my refactor I believed the as would be the proper approach. As ToString() will throw an error --- So what form of cast is it comparable to? I've got some code I'm maintaining, but in apart of my refactor I came across a ToString() attached to an ExecuteScalar. My question would be, does the usage of ToString() equate to: (string)command.ExecuteScalar(); Or would it represent this: command.ExecuteScalar() as string; Obviously the as string would fail gracefully, where the cast (string) would actually fall into an InvalidCastException. So when you call: command.ExecuteScalar().ToString(); Which method of casting is it attempting to do? A: No, it doesn't mean either of those - it simply means calling ToString() on whatever the value is. In particular, if the value is not a string, it will convert it to a string anyway - whereas string would fail with InvalidCastException and the as would return null. So for example: object x = 10; string a = x.ToString(); // "10" string b = x as string; // null string c = (string) x; // Bang Of course, ToString() can still throw an exception too - most obviously if the target of the call is a null reference. Personally, I would suggest using a cast if you know what the result type should be - although the result of ExecuteScalar is more commonly a numeric value (e.g. a count) rather than a string. Yes, that means an exception will be thrown if you're wrong - but if your query isn't doing what it's meant to anyway, then stopping due to an exception may well be better than going ahead with a bogus view of the world. (See my blog post on casting vs as for more on this attitude.) A: Neither, because Object.ToString() will returns you a string representation of the object. Regardless whether the query returns a varchar or int.
{ "pile_set_name": "StackExchange" }
Q: SQL, using data from a number of separate tables to receive an output So my tables I'm working with look like the following: Book(BookID, Title) Author(BookID, AuthID) Writer(AuthID, PubID, FirstName, LastName) Publisher(PubID, PubName, Country) And I'd love to change them to make more sense, but I'm not allowed to even change their names at this point. Anyway, I have two separate pieces of code that I want to run together. So it's the result of this: select Book.Title from Book join Author on Book.BookID=Author.BookID group by Book.Title, Book.BookID having count(*) >= 2 with this: select AuthorID from Author join Publisher on Author.PubID=Publisher.Publisher where Publisher.Country like 'Australia' Initially I thought INTERSECT might work but I quickly realised that because they're not matching fields, I need something else. And the fact that Writer and Publisher have to be linked via Author is throwing me off completely. Is there a way to do this save going back to the table and changing it to something less unnecessarily complex? I've been going through the list of statements and whatnot on trying to find a solution, but I'm not sure which one I'm supposed to be looking at. Perhaps something with GROUP in it? So anything, just a point in the right direction would be much appreciated. A: Are you trying to find all books with more than one author published in Australia? If so, the query would look something like this: select b.Title from Book b join Author a on b.BookID = a.BookID join Writer w on w.AuthId = a.AuthId join Publisher p on w.PubId = p.PubId where p.Country like 'Australia' group by b.Title, b.BookID having count(*) >= 2;
{ "pile_set_name": "StackExchange" }
Q: application connect to database I am working on an application that will be used by schools. Each school will set up their on database. And each school will provide their own "settings" file to the application. The settings file will contain the database url for the specific school who made the settings file. This is so that a student using the application can just load a different settings file if they want to connect to a different database. My question is, how do i protect the username and password used to connect to the database? So, that ONLY the application has read and write access to the database. And the application has read and write access to only that specific school? If you need more information, please let me know. Thanks A: Take a look at Jasypt, it is a java library which allows the developer to add basic encryption capabilities to his/her projects with minimum effort, and without the need of having deep knowledge on how cryptography works. In case you use Spring, you can define your db.properties as: jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost/yourdb jdbc.username=userName jdbc.password=ENC(A6L729KukPEx7Ps8didIUWb01fdBRh7d) and configure it with Jasypt and Spring as: <bean class="org.jasypt.spring.properties.EncryptablePropertyPlaceholderConfigurer"> <constructor-arg> <bean class="org.jasypt.encryption.pbe.StandardPBEStringEncryptor"> <property name="config"> <bean class="org.jasypt.encryption.pbe.config.EnvironmentStringPBEConfig"> <property name="algorithm" value="PBEWithMD5AndDES" /> <property name="passwordEnvName" value="APP_ENCRYPTION_PASSWORD" /> </bean> </property> </bean> </constructor-arg> <property name="locations"> <list> <value>classpath:/META-INF/props/db/db.properties</value> </list> </property> </bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> This would hide the actual password (you can do the same for the username) from students, so they would not be able to derive the connection string from looking at the properties file. In case you are not using Spring, here is a Jasypt guide to achive the same "manually"
{ "pile_set_name": "StackExchange" }
Q: Silverlight Async Design Pattern Issue I'm in the middle of a Silverlight application and I have a function which needs to call a webservice and using the result complete the rest of the function. My issue is that I would have normally done a synchronous web service call got the result and using that carried on with the function. As Silverlight doesn't support synchronous web service calls without additional custom classes to mimic it, I figure it would be best to go with the flow of async rather than fight it. So my question relates around whats the best design pattern for working with async calls in program flow. In the following example I want to use the myFunction TypeId parameter depending on the return value of the web service call. But I don't want to call the web service until this function is called. How can I alter my code design to allow for the async call? string _myPath; bool myFunction(Guid TypeId) { WS_WebService1.WS_WebService1SoapClient proxy = new WS_WebService1.WS_WebService1SoapClient(); proxy.GetPathByTypeIdCompleted += new System.EventHandler<WS_WebService1.GetPathByTypeIdCompleted>(proxy_GetPathByTypeIdCompleted); proxy.GetPathByTypeIdAsync(TypeId); // Get return value if (myPath == "\\Server1") { //Use the TypeId parameter in here } } void proxy_GetPathByTypeIdCompleted(object sender, WS_WebService1.GetPathByTypeIdCompletedEventArgs e) { string server = e.Result.Server; myPath = '\\' + server; } Thanks in advance, Mike A: The best would be to use Reactive Extensions. Then (assuming you'd create an extension method IObservable<string> GetPathByTypeId(string typeId) on WS_WebService1SoapClient you can do this: proxy .GetPathByTypeId(TypeId) .Subscribe(server => { //Here you can do stuff with the returned value }); As close to having synchronous call as it gets :) A: Given the asynch nature of Silverlight you cannot return values from myFunction. Instead you can pass an Action which is executed once the service call is complete. See the example code below. I am not sure if it is considered best practice, but I use this "pattern" a lot and it has always worked fine for me. EDIT Updated the code below to include multiple arguments in the callback action. void DoSomething(Guid TypeId, Action<int, bool> Callback) { WS_WebService1.WS_WebService1SoapClient proxy = new WS_WebService1.WS_WebService1SoapClient(); proxy.GetPathByTypeIdCompleted += (s, e) => { string server = e.Result.Server; myPath = '\\' + server; // if (myPath == "\\Server1") { Callback(888, true); } else { Callback(999, false); } }; proxy.GetPathByTypeIdAsync(TypeId); } void CallDoSomething() { DoSomething(Guid.NewGuid(), (returnValue1, returnValue2) => { //Here you can do stuff with the returned value(s) }); }
{ "pile_set_name": "StackExchange" }
Q: Can i extend type cast of common value types (like Int32) with implicid converter to my custom type? What if i need some kind of reference type wrapper for Int32 (the database Id for example). How can i convert Int32 to my class implicitly? A: Create a static implicit converter operator: public class MyClass { .... static public implicit operator MyClass(int value) { // Create a new instance of your class using the value. } ... } Once created, you can do something like this: MyClass myInstance = 48; For more information, see MSDN: Using Conversion Operators (C# Programming Guide)
{ "pile_set_name": "StackExchange" }
Q: Issues with Ubuntu FreeRadius I have a problem with FreeRadius I wrote a script to add users. When I want to restart the service with: service freeradius restart I get the following output: top: Unknown instance: A: Run the server in debug mode /usr/sbin/freeradius -X and examine the output to find out why there server is failing to start.
{ "pile_set_name": "StackExchange" }
Q: Converting XML to DOT I would like to show an XML tree as a tree using GraphViz Dot tool. Then I must convert it to a DOT file. It is what I have tried string dot = "digraph G {" + Environment.NewLine; XML2DOT(XmlRoot, "r"); dot += Environment.NewLine + "}"; .... private void XML2DOT(XmlNode n, string id) { if (n == null) return; string NodeName = n.Name.Replace("-", "_"); if (n.HasChildNodes) { dot += Environment.NewLine + NodeName + id + "[label=\"" + NodeName + "\"];"; } else { dot += Environment.NewLine + "leaf" + id + "[label=\"" + n.InnerText + "\"];"; } int i = 0; foreach (XmlNode item in n.ChildNodes) { string cid = id + i; dot += Environment.NewLine + NodeName + id + " -> " + (item.HasChildNodes ? item.Name.Replace("-", "_") : "leaf") + cid + ";"; XML2DOT(item, cid); i++; } } The input xml is: <?xml version="1.0" encoding="UTF-8"?> <S> <MN clitic="empty" ne_sort="pers"> <PUNC clitic="empty"> <w clitic="empty" gc="Ox" lc="Ox" lemma="#">#</w> </PUNC> <MN clitic="empty" ne_sort="pers"> <N clitic="ezafe"> <w clitic="ezafe" gc="Apsz ; Nasp--- ; Nasp--z ; Ncsp--z" lc="Nasp--z" lemma="مسعود" n_type="prop" ne_sort="pers">مسعود</w> </N> <N clitic="ezafe"> <w clitic="ezafe" gc="Apsy ; Nasp--- ; Nasp--z ; Ncsp--y" lc="Nasp--z" lemma="شجاعی" n_type="prop" ne_sort="pers">شجاعی</w> </N> <N clitic="empty"> <w clitic="empty" gc="Nasp--- ; Nasp--z" lc="Nasp---" lemma="طباطبایی" n_type="prop" ne_sort="pers">طباطبایی</w> </N> </MN> <PUNC clitic="empty"> <w clitic="empty" gc="Ox" lc="Ox" lemma="#">#</w> </PUNC> </MN> </S> And it is what I get: It works as expected, just would like to know a more general and efficient way to do that. A: There's an XML syntax for DOT called DotML at http://martin-loetzsch.de/DOTML/. Generating a generic DotML tree from XML is very straightforward using XSLT. Most of it is just: <xsl:template match="*"> <node id="{generate-id()}" label="{name()}"/> <edge from="{generate-id(..)}" to="{generate-id()}"/> <xsl:apply-templates/> </xsl:template> <xsl:template match="text()"> <node id="{generate-id()}" label="{.}"/> <edge from="{generate-id(..)}" to="{generate-id()}"/> </xsl:template>
{ "pile_set_name": "StackExchange" }
Q: Creating a generalized type for use as a table value parameter I'm finding that there are several points in the stored procedures that I'm creating where I want a stored procedure to accept a list of IDs in various tables that the SP should perform an operation on. I'm considering using Table Value Parameters. What I'm wondering about is whether it's a good practice to create a single Type which just contains a single "ID int" column, and use that as the data type for all of my TVP's, or whether it's a better practice to define a type for each SP, in case I end up in the future wanting to expand the values passed. Does anyone have experience with this? edit In case it makes any difference to your recommendation, the ID lists that I'm passing may be on the order of 150,000 entries. A: What I can offer you in the way of experience is that if you find you need to change the definition of a user defined table type, you will need to drop every reference to the type before you can diddle with it. Down in the Cons section mentioned that great annoyance. So for us, it was worth the code maintenance to define unique table types based on expected usage, even if it matched existing types. YMMV
{ "pile_set_name": "StackExchange" }
Q: Firefox keeps crashing on Ubuntu 14.04 Since yesterday, every time I visit Youtube Firefox crashes. Also, it crashes on some other video streaming sites (or pages that include a video player like jwplayer for example), but not every time. I have started Firefox in save mode, and also reinstalled it. I also uninstalled flash player - still crashing (Note that I use Youtube's HTML5-player as standard). I can't find any solution on the internet. Maybe somebody has some ideas to fix Firefox? I can't even guess what could be the reason for those crashes. Bug report from firefox: BuildID: 20150112203352 CrashTime: 1421759307 EMCheckCompatibility: true FramePoisonBase: 7ffffffff0dea000 FramePoisonSize: 4096 InstallTime: 1421326467 Notes: OpenGL: Intel Open Source Technology Center -- Mesa DRI Intel(R) Haswell Mobile -- 3.0 Mesa 10.1.3 -- texture_from_pixmap ProductID: {ec8030f7-c20a-464f-9b0e-13a3a9e97384} ProductName: Firefox ReleaseChannel: release SecondsSinceLastCrash: 15 StartupTime: 1421759297 Theme: classic/1.0 Throttleable: 1 Vendor: Mozilla Version: 35.0 useragent_locale: chrome://global/locale/intl.properties This report also contains technical information about the state of the application when it crashed. A: If somebody is interested in the solution, here it is: I don't know why but some parts of streamer seemed to be missing on my system. I am sure that neither Ubuntu nor Firefox were updated right before the crashes began, so I can't tell the actual reason why the bug occured. However, solution was quite simple: sudo apt-get install gstreamer1.0-* Downloads and installs a bunch of gstreamer libraries, now everything works fine again.
{ "pile_set_name": "StackExchange" }
Q: How can I extend my usb keyboard/mouse by 15m or troubleshoot my existing attempt? USB max length is apparently 5m. At the moment, I have a 5m usb cable, and on the end of it my keyboard. My keyboard has an internal 1 port usb hub, which I have plugged my mouse into. This setup works fine, 99% of the time - very occasionally they will stop functioning, but for the most part, it's absolutely fine. I previously had no 5m cable and it worked fine for a year. I have a slightly pricy intel motherboard. I want to extend it to about 15m. So I bought some more 5m usb cables, and two powered hubs. I set my pc up as: PC > 5m > USB hub > 5m > USB hub > Keyboard > Mouse This worked, but every 3-4 minutes, the usb hub in the device manager would disappear, my pc would lag, and my keyboard/mouse would turn off. After about 10 seconds, my PC would lag again, and the devices would start working again. The bandwidth usage in device manager for the USB devices showed as 1%, 2%, 4% presumably for the hub, keyboard, mouse. I have tried switching out the cables for other cables, and I have tried these combinations too: PC > USB hub > 5m > USB hub > 5m > Keboard > Mouse and PC > 5m > USB hub > 5m > Keyboard 5m > Mouse I have tried using different ports in my PC and the USB hubs. I am looking for either troubleshooting advice to narrow down the problem, or an alternative more reliable solution that won't cost a fortune. All help appreciated! Wireless keyboard & mouse is a last resort :P A: This information comes from the Wikipedia article for USB, but it would appear the reason is that the roundtrip communication time has a strict limit and that cable length can greatly affect that. Based on the following exerpt it would seem the roundtrip time for your setup is just too long and that the commands are getting dropped. The primary reason for this limit is the maximum allowed round-trip delay of about 1.5 μs. If USB host commands are unanswered by the USB device within the allowed time, the host considers the command lost. When adding USB device response time, delays from the maximum number of hubs added to the delays from connecting cables, the maximum acceptable delay per cable amounts to 26 ns.[38] The USB 2.0 specification requires cable delay to be less than 5.2 ns per meter (192,000 km/s, which is close to the maximum achievable transmission speed for standard copper wire). It would appear that if you purchased a longer cable, instead of going with the hub setup, that it may function better (since the hubs will increase the overall delay per meter). I see that monoprice.com has cables going all the way up to 25m, so there may be a shop you can purchase a similar cable from locally.
{ "pile_set_name": "StackExchange" }
Q: Customize the way TreeSet prints Map.Entry values I have a TreeSet containing Map.Entry<String, Double> values and when I try to use an Iterator to iterate over this structure and to print its key-value pairs, the standard output is something which looks like: Tolkien=40.25 JKRowling=35.5 OBowden=14.0 However I would like to use a custom format for my output and to replace the = sign with -> like: Tolkien -> 40.25, JKRowling -> 35.5, OBowden -> 14.0 This is my code for now: Iterator iterator;. iterator = lib.getSortedBooks().iterator(); while (iterator.hasNext()) { System.out.printf(iterator.next() + " "); } Which is the best way to properly format my output? A: Printing methods in System.out use toString() internally, so when you call toString() you get the same thing that you see in the output. Then just replace that equals sign with the arrow. System.out.printf(iterator.next().toString().replace("=", " -> ") + " "); A more elegant approach (actually the right way to do it since Map.Entry makes no promise as to the toString() format): Map.Entry<K, V> entry = iterator.next(); System.out.printf(entry.getKey() + " -> " + entry.getValue() + " ");
{ "pile_set_name": "StackExchange" }
Q: cocos2d v2.0 upgrade & RootViewController I'm currently upgrading my cocos2d app from 0.99 to 2.0. The app uses ZBarSDK for QR code scanning and the integration was done like that: // present and release the controller [[RootViewController sharedInstance] presentModalViewController: reader animated: YES]; However that doesn't work with the new version of cocos2d. What should I change to make it work with cocos2d 2.0 ? A: Use this code: AppController *app = (AppController*) [[UIApplication sharedApplication] delegate]; [app.navController presentModalViewController: reader animated:YES];
{ "pile_set_name": "StackExchange" }
Q: Why are data members private by default in C++? Is there any particular reason that all data members in a class are private by default in C++? A: The Design and Evolution of C++ 2.10 The Protection Model Before starting work on C with Classes, I worked with operating systems. The notions of protection from the Cambridge CAP computer and similar systems - rather than any work in programming languages - inspired the C++ protection mechanisms. The class is the unit of protection and the fundamental rule is that you cannot grant yourself access to a class; only the declarations placed in the class declaration (supposedly by its owner) can grant access. By default, all information is private. A: Because it's better to be properly encapsulated and only open up the things that are needed, as opposed to having everything open by default and having to close it. Encapsulation (information hiding) is a good thing and, like security (for example, the locking down of network services), the default should be towards good rather than bad. A: Because otherwise there would be no difference at all between class and struct?
{ "pile_set_name": "StackExchange" }
Q: Dart dependency injection of a class with parameters I am trying to learn about dependency injection and trying to use it in Flutter/Dart. I have gone through the library get_it which I find very useful. But I am having a doubt about the dependency injection in a specific situation. If I have a Dart class with parameters like this one for example: class MyClass(){ final String name; MyClass({this.name}) .... .... } In such a class, with parameters, It seems like I cannot use dependency injection? or at least the following using get_it will not work: **** service_locator.dart **** import 'package:get_it/get_it.dart'; GetIt locator = GetIt(); void setupLocator() { locator.registerLazySingleton<MyClass>(() => MyClass()); } This gives error on => MyClass()....since it is expecting a parameter. How to do this kind of injection?. A: You just pass the argument you want to MyClass(). You don’t have to do it inside setUpLocator(). Register the singleton, anywhere in your program, when you know what argument to pass. For example, if you need to register a user object as a singleton, you’ll have to do it after the user logs in and all their info is available in order to properly instantiate your User class.
{ "pile_set_name": "StackExchange" }
Q: Add View to the top of ItemsControl region I have a ItemsControl region in composite Prism MVVM application <ItemsControl Regions:RegionManager.RegionName="NotificationRegion" AllowDrop="True" ClipToBounds="True" HorizontalAlignment="Right" Margin="0,40,20,20" Width="280" /> And now I want to display my NotificationViews in that region like this: I simply navigate to views and they are added to my ItemsControl region. But problem is that new View is always added to the bottom. I really want new views to be displayed at the top. Is there any way to achieve this? Thank you very much in advance. A: I think you'll find this helps: Sorting views in Prism/MEF Basically: public MainView( ) { InitializeComponent( ); ObservableObject<IRegion> observableRegion = RegionManager.GetObservableRegion( ContentHost ); observableRegion.PropertyChanged += ( sender, args ) => { IRegion region = ( (ObservableObject<IRegion>)sender ).Value; region.SortComparison = CompareViews; }; } private static int CompareViews( object x, object y ) { IPositionView positionX = x as IPositionView; IPositionView positionY = y as IPositionView; if ( positionX != null && positionY != null ) { //Position is a freely choosable integer return Comparer<int>.Default.Compare( positionX.Position, positionY.Position ); } else if ( positionX != null ) { //x is a PositionView, so we favour it here return -1; } else if ( positionY != null ) { //y is a PositionView, so we favour it here return 1; } else { //both are no PositionViews, so we use string comparison here return String.Compare( x.ToString( ), y.ToString( ) ); } } You'll notice that the region has a SortComparison property. You just need to create a custom SortComparison for the region which orders your newest views first.
{ "pile_set_name": "StackExchange" }
Q: VSTS Code section does not show I have created VSTS project, added 4 members and made them stakeholders. However no member can see Code section it is just now showing. Please advice. A: Stakeholders don't have access to Code. They need to be at least Basic users.
{ "pile_set_name": "StackExchange" }
Q: FATAL EXCEPTION: main java.lang.NoClassDefFoundError: rx.plugins.RxJavaHooks In my application after successfully login, loading data through retrofit library. from last two days i founded one major issue in my application. below android API level 21 application getting crashes i checked in console and logs. i got "FATAL EXCEPTION" due to no class def found error. same app working above android API level 23. in build.gradle file android { compileSdkVersion 25 buildToolsVersion "25.0.2" defaultConfig { applicationId "com.example.rsukumar.gluser" minSdkVersion 16 targetSdkVersion 25 versionCode 1 versionName "1.0" // Enabling multidex support. multiDexEnabled true } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } } dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') testCompile 'junit:junit:4.12' //dagger 2 compile 'com.google.dagger:dagger:2.0.2' provided 'com.google.dagger:dagger-compiler:2.0' provided 'javax.annotation:jsr250-api:1.0' compile 'com.neenbedankt.gradle.plugins:android-apt:1.8' compile 'com.nineoldandroids:library:2.4.0' compile 'com.daimajia.easing:library:1.0.1@aar' compile 'com.daimajia.androidanimations:library:1.1.3@aar' //retrofit 2 compile 'com.squareup.retrofit:adapter-rxjava:2.0.0-beta2' compile 'com.squareup.retrofit:retrofit:2.0.0-beta2' compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2' } enter image description here My main question is why i'm getting above exception and error? that too in different Android API levels. A: this problem can be related to multidex support for your application. Android Version < 21 do not support Multidex by default. You need to enhance your application. I followed the following instructions to resovle this problem for my applications API Level < 21
{ "pile_set_name": "StackExchange" }
Q: Apache + SSE + PHP I'm using SSE to send some data to browser (web chat). And I faced with some problem. SSE works fine but other requests no. All requests stays at pending status for a very long time, even click on link to another page doesnt work, untill browser stop button would be pressed. I tested it on PHP 5.4.4, 5.4.45 and Apache 2.4 and 2.2... Absolutely same result. I tried to change mpm settings in apache.conf and nothing changed. Anyone have any ideas what could help me? This is the action from controller: /** * @return string */ public function actionIndex() { /** @var SSE $sse */ $sse = \Yii::$app->sse; $sse->addEventListener('message', new MessageEventHandler()); $sse->start(); } And this is message handler: class MessageEventHandler extends SSEBase { public function check() { return true; } public function update() { return 'New message!'; } } And browser side: var sseObject = $.SSE('/notifier', { events: { chat_message: function (e) { console.log(e.data); } } }); sseObject.start(); A: Problem is probably with session lock. PHP writes its session data to a file by default. When a request is made to a PHP script that starts the session (session_start()), this session file is locked. What this means is that if your web page makes numerous requests to PHP scripts, for instance, for loading content via Ajax, each request could be locking the session and preventing the other requests from completing. Combined with fact that SSE connections are persistent, thus session will stay locked. http://konrness.com/php5/how-to-prevent-blocking-php-requests/ Possible solution is to call session_write_close() in actionIndex().
{ "pile_set_name": "StackExchange" }
Q: Subsets of Sample space that are not events In VK Rohatgi, It is written that all the subset of uncountable sample space is not an event . And also it is not easy to find one that is not event please define which type of subsets in sample space that are not events A: A famous counter-example is the Vitali set : https://en.wikipedia.org/wiki/Vitali_set
{ "pile_set_name": "StackExchange" }
Q: Empty request body I generated two projects, one with create-react-app and the other with express generator. I run the first one on localhost:3000 and the second one on localhost:3001. I'am trying to send a POST request, but I receive an empty req.body. Client side: handleSubmit(event) { event.preventDefault(); var data = new FormData(); for (const key of Object.keys(this.state)) { data.append(key, this.state[key]); } const url = "http://localhost:3000/course"; fetch(url, { method: "POST", body: this.state }) .then(response => response.text()) .then(html => console.log(html)); } Server side: app.js app.use(logger("dev")); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, "public"))); app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header( "Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept" ); next(); }); app.use("/course", course); router/course.js router.post("/", function(req, res) { if (!req.body) { var course = new Course(req.body); course .save() .then(item => { res.json({ course: item }); }) .catch(err => { res.status(500).send("Unable to save to database"); }); } res.status(200).send("No data to save"); }); A: body-parser needs Content-Type header to be set to 'Content-Type': 'application/json' in order to know that is has to parse the body Try passing this to the headers fetch('http://localhost:3000/course', { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify(data), });
{ "pile_set_name": "StackExchange" }
Q: how to centralize a textview inside of imageview android I have a LinearLayout and i just want to put a text at the middle of my imageview which is a shape. <LinearLayout android:layout_width="match_parent" android:orientation="horizontal" android:layout_height="wrap_content"> <TextView android:id="@+id/state_area" android:layout_width="wrap_content" android:textColor="#F000" android:layout_height="90dp" android:textSize="40sp" android:layout_marginBottom="24dp" android:layout_gravity="center_horizontal" /> </LinearLayout> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/shape" android:layout_gravity="center" /> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="24dp" android:src="@drawable/shape" android:layout_gravity="center" /> </LinearLayout> The result so far : A: you could just use a textview and set the shape as the background. <TextView android:id="@+id/state_area" android:layout_width="wrap_content" android:textColor="#F000" android:layout_height="90dp" android:background="@drawable/shape" android:textSize="40sp" android:layout_marginBottom="24dp" android:layout_gravity="center_horizontal" />
{ "pile_set_name": "StackExchange" }
Q: Multiplication of the values of two textboxes and displaying result in the third textbox i am developing an inventory system in which i fetch the data from database through textbox1 and the data compatible to the entry in textbox1 appears in textbox8 and textbox10 which are integers. Now i want to multiply textbox8 and textbox10 and the result should be display into textbox7 when the integers appears in textbox8 and textbox10. i am using this piece of code for multiplication of two textboxes and result in the third text box does not appear: private void textBox7_TextChanged(object sender, EventArgs e) { Int32 val1 = Convert.ToInt32(textBox10.Text); Int32 val2 = Convert.ToInt32(textBox8.Text); Int32 val3 = val1 * val2; textBox7.Text = val3.ToString(); } A: You are using the wrong textbox for your TextChanged event. Your textboxes 8 and 10 are changing but you have attached the shown code to textbox7. public MyForm : Form { public MyForm(){ InitializeComponents(); // Here you define what TextBoxes should react on user input textBox8.TextChanged += TextChanged; textBox10.TextChanged += TextChanged; } private void TextChanged(object sender, EventArgs e) { int val1; int val2; if (!int.TryParse(textBox8.Text, out val1) || !int.TryParse(textBox10.Text, out val2)) return; Int32 val3 = val1 * val2; // Here you define what TextBox should show the multiplication result textBox7.Text = val3.ToString(); } } And finally remove the code inside textBox7_TextChanged(object sender, EventArgs e) A: You assigned the event to the wrong control and you're not checking for valid input. You can use int.TryParse to look for valid, numerical input. private void textBox8_TextChanged(object sender, EventArgs e) { Multiply(); } private void textBox10_TextChanged(object sender, EventArgs e) { Multiply(); } public void Multiply() { int a, b; bool isAValid = int.TryParse(textBox8.Text, out a); bool isBValid = int.TryParse(textBox10.Text, out b); if (isAValid && isBValid) textBox7.Text = (a * b).ToString(); else textBox7.Text = "Invalid input"; }
{ "pile_set_name": "StackExchange" }
Q: parsing words from symbols on a list in python I have to train a language model from a dataset of words. To this, I need to arrange all the text in only one column because is the only way the model works. Until now I could split the document into one column as is required using Python without any problem. For example: Original document Zomer, 1951 De wereld bestond uit het wazige blauw van een wolkenloze zomerhemel, het goudgroen van koel, geruststellend naaldbos en het lijnrechte wit van de betonnen weg, die nieuw was, hij stond nog op geen enkele kaart. Document as required Zomer, 1951. De wereld bestond uit het wazige blauw van een wolkenloze zomerhemel, het goudgroen van koel, geruststellend naaldbos en het lijnrechte wit van de betonnen weg, die nieuw was, hij stond nog op geen enkele kaart. The problem started when I tried to take the symbols (comma, colon, semicolon, etc) into a new line and including an additional white space after each full stop (.) For example: Zomer , 1951 . De wereld I haven’t found the appropriate way of doing this. Until now I have tried different ways using functions like .split() and .find(), among others, without any positive result. After opening the file: fileHandle = open("C:\Language Model\Corpora\Computing Clients 3.txt",'r') I have tried with loops and conditions but nothing has worked. And all the results obtained until now are: AttributeError: 'list' object has no attribute 'find' I know maybe I am missing something and that's why I'm asking you for your valuable help since the files are so huge and it would be useless do it manually knowing that Python can do it for me. A: If the name of your file is paragraph.txt then f = open('paragraph.txt', 'r') words = [] lines = f.readlines() for line in lines: words.extend(line.split()) Above lines make a list of all words And these are to remove . and , from those words for i in range(len(words)): words[i] = words[i].replace('.' ,'') words[i] = words[i].replace(',' ,'') #here you can add a line to remove some other character For printing the words : for word in words: print(word)
{ "pile_set_name": "StackExchange" }
Q: iOS Localization (setting it in the app) in my application I must have two languages, but the problem is that they should be switched by pressing a button in the application (on the first screen, or screen settings). As I understand, all the methods of localization (Localizing the Storyboard, Localizing Dynamic Strings) based on the language settings of the iPhone. The only option that comes to my mind - do it by the record in NSUserDefault about language preference, and in ViewDidLoad methods of all ViewControllers check the record about language and in accordance with it set strings, picture and so on. Can it be done on a more clever way? A: Try this: If de is the new language selected by the user. Also assure that you are reinitiating the current view. [[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"de", nil] forKey:@"AppleLanguages"]; See the below link and source code http://learning-ios.blogspot.com/2011/04/advance-localization-in-ios-apps.html and here is the code of one sample app https://github.com/object2dot0/Advance-Localization-in-ios-apps All the best.
{ "pile_set_name": "StackExchange" }
Q: How do empiricists explain zeno's paradox(es)? If Zeno seemed to prove our perceptions cannot be trusted, how, then, can/does an Empiricist justify faith in their perceptions? I'm looking for various solutions (or justifications in the face of the paradoxes to maintain Empiricism) of these issues. A: Not everyone agrees that the paradoxes have been solved, but they aren't strictly empirical problems either. There's a sizable school of thought, myself mostly included, holding that calculus basically solves the problems. Most of Zeno's paradoxes are founded in the claim that one cannot completely infinitely many steps in any finite time - but calculus, and convergence of limits, especially as refined by Weierstrass, tells us that an infinite totality of steps may be traversed in finite time given their convergence in the limit. Thus the puzzle becomes a prompt for calculus to come in, and that's that. From a different direction, note that the paradoxes depend on an infinitely fine-grained world. While quantum mechanics still has a way to go on figuring this out (and may be in practice impeded from ever doing so), it's arguable that the universe operates with a particular resolution. If this is the case (and as far as we know, it might be) then the intial premise of Zeno's paradoxes - that you can cut the universe up as many times as you want in any dimension - falls apart. In the same vein, it's worth noting that Aristotle claimed the ancient Atomists were inspired by Zeno's paradoxes to posit the existence of such limited resolution (On Generation and Corruption 316b34). Last, I'd like to suggest a borderline metaphilosophical perspective: that Zeno's paradoxes are "merely academic". Obviously, whatever Zeno might say, if I jump off a cliff I will in practice hit the ground hard. An empiricist could take this reasoning and say, "look, your little paradoxes are fun to ponder, but watch this: I'm walking. I'm traversing infinitely many points in finite time. Whatever the paradoxes may say, time and time again my perceptions are proving reliable (within reasonable bounds). We can hardly permit our scientific enterprise to be held back by a thought experiment totally divorced from reality!" This last thought reminds me of an apocryphal tale I vaguely recall: a fellow ancient, first confronted with Zeno's paradoxes, offers an incredulous stare. They take a step forward, look about significantly, and declare, "disproved!"
{ "pile_set_name": "StackExchange" }
Q: push from a side bar menu to another view controller in ios I use in my application, the side bar menu like in facebook, so I have different cells in this menu, what I want is to when click on a cell push me to another view controller. I face a problem here which is: the menu is a table view which I don't have it in storyboard, I use some classes from this site:github and I've stucked here, in my application I use a storyboard, but this menu is programmed with code, and doesn't have a view in stroyboard, in the didSelectRowAtIndexPath method: I use like this for(int j=0; j< 9 ; j++) { if(indexPath.row == j) { DetailsSidebarViewController *essayView = [[DetailsSidebarViewController alloc] init]; essayView.detailItem = [jsonResults objectAtIndex:j]; NSLog(@"%@=%d",essayView.detailItem,j); } } and I create a DetailsSidebarViewController as the new view controller when I push from menu item. in this class, I create a method to configure the view, and just I echo the result: - (void)configureView { // Update the user interface for the detail item. if (self.detailItem) { NSLog(@" %@ ", self.detailItem); } } the result is true like I want, but I want to push to another view controller, in fact nothing is happened when I click on an item into the menu. How can I create the new view controller in storyboard? if the menu has not a storyboard, and how can I connect them with segues? In fact, I am blue with it, please help!! A: You should make an instance of the App Delegate class in the Side Menu view controller, and push it from there. You must have a reference to the Side Menu View and a reference to the Center View! Import your App Delegate into the Side Menu controller, and in the didSelectRowAtIndexPath, use: DetailsSidebarViewController *essayView = [[DetailsSidebarViewController alloc] init]; essayView.detailItem = [jsonResults objectAtIndex:indexPath.row]; // note that you don't need the for loop to know what object you need AppDelegate* myAppDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate]; [myAppDelegate.sideMenuViewController toggleSideMenu]; // the idea here is that you have to close the side menu, i.e. it must dissapear [myAppDelegate.centerViewController.navigationController pushViewController:essayView animated:YES]; This is all the code you need. If I may, as a piece of advice, use Mike Frederik's MFSideMenu instead of the library you're using. In my opinion, it has a more simple and a more straightforward implementation, just look into the README file, everything is explained pretty simple, and it has exactly the code you need! Hope this helps, good luck!
{ "pile_set_name": "StackExchange" }
Q: How to render a graph when Mysql data is updated in Vue? I organized like this, Back-end: Nodejs - Insert a data to MYSQL periodically. DB: MYSQL Front-end: Vue.js - Draw and Re-render a Graph with Mysql Data when data is updated. In this situation, do I have to check a MYSQL data per seconds whether it is latest or not? and then I have to render a graph again? Or is there a way like when MYSQL data is updated, triggering a specific methods that is re-render a graph(automatically). I prefer a second way though, I have no idea it is possible. Someone can give an advises me plz? or example? A: What you could do is using socket.io for this. The moment you update your database in Node.js you then also send a notification or the data over a socket, which tells your Vue.js application that it needs to load new data or gives it the data directly. I used the following npm packages for my setup with Vue.js and Node.js: Vue: socket.io-client Node: socket.io I followed these 2 sites when I faced a similar problem to get a hang of sockets: https://socket.io/get-started/chat/#Introduction https://medium.com/@jaouad_45834/basic-chat-web-app-using-express-js-vue-js-socket-io-429588e841f0
{ "pile_set_name": "StackExchange" }
Q: What to pass as a SYS_REFCURSOR argument Here I have a stored procedure in Oracle: CREATE OR REPLACE PROCEDURE StP_COMPS IS CV_1 SYS_REFCURSOR; BEGIN OPEN CV_1 FOR SELECT * FROM COMPUTERS; END; When I execute the procedure like EXEC SP_COMPS I get no error, the SQL Developer just shows "ananymous block completed". Then I change the procedure to a CREATE OR REPLACE PROCEDURE SP_COMPS (cv_1 OUT SYS_REFCURSOR) IS BEGIN OPEN CV_1 FOR SELECT * FROM COMPUTERS; END; and when I execute I get error stating that the number of type of the arguments are wrong. I'm very curious what I could send as an argument to the procedure if it's just an output parameter. I want to get the result set of the query run inside the procedure. What am I doing wrong here? P.S. When I try to run the procedure by right clicking the procedure and selecting Run I get: DECLARE CV_2 sys_refcursor; BEGIN SP_COMPS( CV_2 => CV_2 ); :CV_2 := CV_2; -- <--Can't understand this part END; A: You have a variable, you should execute the procedure like: DECLARE CV_1 SYS_REFCURSOR; BEGIN SP_COMPS(CV_1); --use cv_1 END; UPDATE(after OP update): That's a simple template for testing. As explained here: Easiest method to test an Oracle Stored Procedure, just run that code, and select ref_cursor as type of cv2 variable.
{ "pile_set_name": "StackExchange" }
Q: Sed copy pattern between range only once I am using sed to edit some sql script. I want to copy all the lines from the first "CREATE" pattern until the first "ALTER" pattern. The issue I am having is that sed copies all lines between each set of CREATE and ALTER instead of only the first occurrence (more than once). sed -n -e '/CREATE/,/ALTER/w createTables.sql' $filename A: Perl to the rescue: perl -ne 'print if /CREATE/ .. /ALTER/ && close ARGV' -- "$filename" > createTables.sql It closes the input when the ALTER is matched, i.e. it doesn't read any further. A: Using sed sed -n '/CREATE/,/ALTER/{p;/ALTER/q}' file > createTables.sql or alternatively(note the newline) sed -n '/CREATE/,/ALTER/{w createTables.sql /ALTER/q}' file
{ "pile_set_name": "StackExchange" }
Q: jquery code improvemt. Hover Function, i try to retrieving information about a value in the first function i'am a learner so i need still experience and i have many questions, but today i have only one question about the hover function. is it possible to send the information about a variable from the first hover function into the seconde one? i think you dont need more information. is just changing a part from the src in a tag. i hope you understand me. =) here is the example http://jsbin.com/eporib/edit#javascript,html,live how is look now! box.hover(function(){ var $this = $(this), oldImg = $this.find('img').attr('src'), slicedOldImg = oldImg.slice(0,-5), newImg = slicedOldImg+num6; $this.find('img').attr('src', newImg); $('#hello').append('IN '+newImg); }, function() { var $this = $(this), oldImg = $this.find('img').attr('src'), slicedOldImg = oldImg.slice(0,-5), newImg = slicedOldImg+num1; $this.find('img').attr('src', newImg); $('#hello').append('OUT '+newImg+ '<br />'); }); /*end Hover*/ and how i want it box.hover(function(){ var $this = $(this), oldImg = $this.find('img').attr('src'), slicedOldImg = oldImg.slice(0,-5), newImg = slicedOldImg+num6; $this.find('img').attr('src', newImg); $('#hello').append('IN '+newImg); }, function() { $this.find('img').attr('src', oldImg); //look here, the oldImg is in the first function. // and i want it use it in the second too. $('#hello').append('OUT '+newImg+ '<br />'); }); /*end Hover*/ A: Yes, there are at least two ways you can do this: 1. Using a closure Wrap the whole thing in a closure and use a variable in that closure: (function() { var oldImg; box.hover(function(){ var $this = $(this), slicedOldImg newImg; oldImg = $this.find('img').attr('src'); // Setting it slicedOldImg = oldImg.slice(0,-5); newImg = slicedOldImg+num6; $this.find('img').attr('src', newImg); $('#hello').append('IN '+newImg); }, function() { // Missing `var $this = $(this);` here? if (oldImg) { // Use it $this.find('img').attr('src', oldImg); // and clear it oldImg = undefined; } $('#hello').append('OUT '+newImg+ '<br />'); } ); /*end Hover*/ })(); In that example, we use an anonymous wrapper function that we execute immediately for the closure, but you may well already be doing this code in a closure (a function), so you may not need to add that wrapper. (If the word "closure" is new to you, don't worry, closures are not complicated.) 2. Using data Alternately, you can use data to store the information on the element: box.hover(function(){ var $this = $(this), oldImg = $this.find('img').attr('src'), slicedOldImg = oldImg.slice(0,-5), newImg = slicedOldImg+num6; $this.data("oldImg", oldImg); $this.find('img').attr('src', newImg); $('#hello').append('IN '+newImg); }, function() { // Missing `var $this = $(this);` here? var oldImg = $this.data("oldImg"); if (oldImg) { $this.find('img').attr('src', oldImg); $('#hello').append('OUT '+newImg+ '<br />'); } } ); /*end Hover*/
{ "pile_set_name": "StackExchange" }
Q: MIT-Scratch adding/removing language features I am seeking a way to allow my non-tech users to specify a workflow and execute it (if anyone is interested, I want them to specify and execute test cases). Visual programming seems a good way to go. Can I modify the Scratch IDE to remove some categories (such as sound, motion, etc), and add some of my own? Ditto for individual keywords (obviously, I then need to handle new keywords). I have Googled, but the answer is not immediately apparent. [Update] I have just found Google's Blockly Blockly was influenced by App Inventor, which in turn was influenced by Scratch, which in turn was influenced by StarLogo. It looks very promising. Especially when it says Exportable code. Users can extract their programs as JavaScript, Python, PHP, Dart or other language so that when they outgrow Blockly they can keep learning. Open source. Everything about Blockly is open: you can fork it, hack it, and use it in your own websites. Extensible. Make Blockly fit with your application by adding custom blocks for your API and remove unneeded blocks and functionality. One possible snag is that it is browser based, but if my management don't like that, then I can create a dummy Windows based app consisting of little but a TWebBrowser component. I will investigate and report back - unless someone else posts an acceptable answer first. A: The short answer to your initial question is: no. You can't customize Scratch, or not to the extent that you seem to ask/want. That said, look at: custom blocks. scratch extensions. variants like snap using scratch's source code in squeak to make your own variant. other systems inspired from scratch, like appinventor and blockly. Only the first two are compatible with the scratch web site. A word on the site: depending on your purpose with Scratch, the exchange between users is a powerful part of scratch. Check how cooperation is supported, like the backpack. There's also a good wiki that documents much of the above.
{ "pile_set_name": "StackExchange" }
Q: How can i use session from yii framework into my 3rd party application I use Yii framework and in the framework i use 3rd party application which is mibew Messenger (or chat ). What I need is to pass $_session variable (username and password) from yii framework to Mibew messenger, I need this because I want to be log in automatically when I log in into my yii application. Mibew messenger folder is in the app folder of the application. So how can I use the same session outside of yii framework ? Thanks for the help. A: I think you may do following: 1) In file of 3rd party application where you need to get an access to SESSION: require('/path/to/framework/YiiBase.php'); 2) If you have specific configs for sessions, than you need you configs: $config = require('/path/to/protected/config/main.php'); $session = YiiBase::createComponent($config['components']['session']); 3) For standard sessions (instead step #2) you should try: $session = new CHttpSession(); Than you can work with sessions as in framework: $session[$var_name] or $session->get/set($var_name). I don't check it solution. If there will be an error - write it on comments. UPDATED Just need to do: require('/path/to/framework/YiiBase.php'); $config = require('/path/to/configs_directory/main.php'); Yii::createWebApplication($config); Than you can use all framework features by Yii::app()
{ "pile_set_name": "StackExchange" }
Q: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output - while installing auto-py-to-exe through pip I am trying to download auto-py-to-exe on a different (windows) device than I usually use through pip. However when run I get the error (sorry it is so very very long): ERROR: Command errored out with exit status 1: command: 'c:\users\tom\appdata\local\programs\python\python38-32\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\tom\\AppData\\Local\\Temp\\pip-install-aplljhe0\\gevent\\setup.py'"'"'; __file__='"'"'C:\\Users\\tom\\AppData\\Local\\Temp\\pip-install-aplljhe0\\gevent\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\tom\AppData\Local\Temp\pip-install-aplljhe0\gevent\pip-egg-info' cwd: C:\Users\tom\AppData\Local\Temp\pip-install-aplljhe0\gevent\ Complete output (113 lines): Traceback (most recent call last): File "c:\users\tom\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\msvc.py", line 489, in _find_latest_available_vc_ver return self.find_available_vc_vers()[-1] IndexError: list index out of range During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\users\tom\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\sandbox.py", line 154, in save_modules yield saved File "c:\users\tom\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\sandbox.py", line 195, in setup_context yield File "c:\users\tom\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\sandbox.py", line 250, in run_setup _execfile(setup_script, ns) File "c:\users\tom\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\sandbox.py", line 45, in _execfile exec(code, globals, locals) File "C:\Users\tom\AppData\Local\Temp\easy_install-29et0so1\cffi-1.14.0\setup.py", line 127, in <module> HUB_PRIMITIVES = Extension(name="gevent.__hub_primitives", File "C:\Users\tom\AppData\Local\Temp\easy_install-29et0so1\cffi-1.14.0\setup.py", line 105, in uses_msvc include_dirs=include_dirs) File "c:\users\tom\appdata\local\programs\python\python38-32\lib\distutils\command\config.py", line 225, in try_compile self._compile(body, headers, include_dirs, lang) File "c:\users\tom\appdata\local\programs\python\python38-32\lib\distutils\command\config.py", line 132, in _compile self.compiler.compile([src], include_dirs=include_dirs) File "c:\users\tom\appdata\local\programs\python\python38-32\lib\distutils\_msvccompiler.py", line 360, in compile self.initialize() File "c:\users\tom\appdata\local\programs\python\python38-32\lib\distutils\_msvccompiler.py", line 253, in initialize vc_env = _get_vc_env(plat_spec) File "c:\users\tom\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\msvc.py", line 185, in msvc14_get_vc_env return EnvironmentInfo(plat_spec, vc_min_ver=14.0).return_env() File "c:\users\tom\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\msvc.py", line 843, in __init__ self.si = SystemInfo(self.ri, vc_ver) File "c:\users\tom\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\msvc.py", line 485, in __init__ self.vc_ver = vc_ver or self._find_latest_available_vc_ver() File "c:\users\tom\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\msvc.py", line 492, in _find_latest_available_vc_ver raise distutils.errors.DistutilsPlatformError(err) distutils.errors.DistutilsPlatformError: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/ During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\tom\AppData\Local\Temp\pip-install-aplljhe0\gevent\setup.py", line 427, in <module> run_setup(EXT_MODULES, run_make=_BUILDING) File "C:\Users\tom\AppData\Local\Temp\pip-install-aplljhe0\gevent\setup.py", line 328, in run_setup setup( File "c:\users\tom\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\__init__.py", line 144, in setup _install_setup_requires(attrs) File "c:\users\tom\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\__init__.py", line 139, in _install_setup_requires dist.fetch_build_eggs(dist.setup_requires) File "c:\users\tom\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\dist.py", line 716, in fetch_build_eggs resolved_dists = pkg_resources.working_set.resolve( File "c:\users\tom\appdata\local\programs\python\python38-32\lib\site-packages\pkg_resources\__init__.py", line 780, in resolve dist = best[req.key] = env.best_match( File "c:\users\tom\appdata\local\programs\python\python38-32\lib\site-packages\pkg_resources\__init__.py", line 1065, in best_match return self.obtain(req, installer) File "c:\users\tom\appdata\local\programs\python\python38-32\lib\site-packages\pkg_resources\__init__.py", line 1077, in obtain return installer(requirement) File "c:\users\tom\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\dist.py", line 786, in fetch_build_egg return cmd.easy_install(req) File "c:\users\tom\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\command\easy_install.py", line 679, in easy_install return self.install_item(spec, dist.location, tmpdir, deps) File "c:\users\tom\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\command\easy_install.py", line 705, in install_item dists = self.install_eggs(spec, download, tmpdir) File "c:\users\tom\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\command\easy_install.py", line 890, in install_eggs return self.build_and_install(setup_script, setup_base) File "c:\users\tom\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\command\easy_install.py", line 1158, in build_and_install self.run_setup(setup_script, setup_base, args) File "c:\users\tom\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\command\easy_install.py", line 1144, in run_setup run_setup(setup_script, args) File "c:\users\tom\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\sandbox.py", line 253, in run_setup raise File "c:\users\tom\appdata\local\programs\python\python38-32\lib\contextlib.py", line 131, in __exit__ self.gen.throw(type, value, traceback) File "c:\users\tom\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\sandbox.py", line 195, in setup_context yield File "c:\users\tom\appdata\local\programs\python\python38-32\lib\contextlib.py", line 131, in __exit__ self.gen.throw(type, value, traceback) File "c:\users\tom\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\sandbox.py", line 166, in save_modules saved_exc.resume() File "c:\users\tom\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\sandbox.py", line 141, in resume six.reraise(type, exc, self._tb) File "c:\users\tom\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\_vendor\six.py", line 685, in reraise raise value.with_traceback(tb) File "c:\users\tom\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\sandbox.py", line 154, in save_modules yield saved File "c:\users\tom\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\sandbox.py", line 195, in setup_context yield File "c:\users\tom\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\sandbox.py", line 250, in run_setup _execfile(setup_script, ns) File "c:\users\tom\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\sandbox.py", line 45, in _execfile exec(code, globals, locals) File "C:\Users\tom\AppData\Local\Temp\easy_install-29et0so1\cffi-1.14.0\setup.py", line 127, in <module> HUB_PRIMITIVES = Extension(name="gevent.__hub_primitives", File "C:\Users\tom\AppData\Local\Temp\easy_install-29et0so1\cffi-1.14.0\setup.py", line 105, in uses_msvc include_dirs=include_dirs) File "c:\users\tom\appdata\local\programs\python\python38-32\lib\distutils\command\config.py", line 225, in try_compile self._compile(body, headers, include_dirs, lang) File "c:\users\tom\appdata\local\programs\python\python38-32\lib\distutils\command\config.py", line 132, in _compile self.compiler.compile([src], include_dirs=include_dirs) File "c:\users\tom\appdata\local\programs\python\python38-32\lib\distutils\_msvccompiler.py", line 360, in compile self.initialize() File "c:\users\tom\appdata\local\programs\python\python38-32\lib\distutils\_msvccompiler.py", line 253, in initialize vc_env = _get_vc_env(plat_spec) File "c:\users\tom\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\msvc.py", line 185, in msvc14_get_vc_env return EnvironmentInfo(plat_spec, vc_min_ver=14.0).return_env() File "c:\users\tom\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\msvc.py", line 843, in __init__ self.si = SystemInfo(self.ri, vc_ver) File "c:\users\tom\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\msvc.py", line 485, in __init__ self.vc_ver = vc_ver or self._find_latest_available_vc_ver() File "c:\users\tom\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\msvc.py", line 492, in _find_latest_available_vc_ver raise distutils.errors.DistutilsPlatformError(err) distutils.errors.DistutilsPlatformError: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/ ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. Even though it does state that I need Visual Studio C++ 14.0 my computer won't install it and I have not needed it before. I checked This Stack Overflow Question but it relates to another pip install and has no answers. If the only answer is to install Visual Studio then I am kinda screwed. A: Allow prerelease gevent versions via $ pip install gevent --pre $ pip install auto-py-to-exe Explanation: auto-py-to-exe is installable on Python 3.8 on Windows without any issues (this can be verified e.g. by running pip install auto-py-to-exe --no-deps). However, it requires bottle-websocket to be installed, which in turn has gevent dependency. gevent did not release a stable version that offers prebuilt wheels for Python 3.8 yet (this would be 1.5), so pip doesn't pick up prebuilt wheels and tries to build gevent==1.4 from source dist. Installing the prerelease 1.5 version of gevent avoids this.
{ "pile_set_name": "StackExchange" }
Q: How to find a solution to a differential equation based on another, given solution Let's say I have the DE: $$ (x^2 - 2x)y'' - (x^2 - 2)y' + (2x - 2)y = 0 $$ And I have one possible solution to the DE: $$ y_1(x) = e^x $$ How would I go about solving this? I could solve the actual DE, but then what is the point of supplying a possible solution? Where does the solution $y_1$ come into play? A: You can proceed using Abel's integration identity. In general for differential equations of the form $$ \sum\limits_{k=0}^n a_k(x)y^{(n-k)}(x)=0 $$ we can consider its solutions $y_1(x),\ldots,y_n(x)$ and define so called Wronskian $$ W(y_1,\ldots,y_n)(x)= \begin{pmatrix} y_1(x)&&y_2(x)&&\ldots&&y_n(x)\\ y'_1(x)&&y'_2(x)&&\ldots&&y'_n(x)\\ \ldots&&\ldots&&\ldots&&\ldots\\ y'_1(x)&&y'_2(x)&&\ldots&&y'_n(x)\\ \end{pmatrix} $$ Then we have the following identity $$ \det W(x)=\det W(x_0) e^{-\int\limits_{x_0}^x \frac{a_1(t)}{a_0(t)}dt} $$ In particular for your problem we have the following differential equation $$ \begin{vmatrix} y_1(x)&&y_2(x)\\ y'_1(x)&&y'_2(x) \end{vmatrix}=C e^{-\int\frac{-(x^2-2)}{x^2-2x}dx} $$ with $y_1(x)=e^x$. Which reduces to $$ y'_2(x)e^x-y_2(x)e^x=C e^{\int\frac{x^2-2}{x^2-2x}dx}=C(2x-x^2)e^x $$ After division by $e^{2x}$ we get $$ \frac{y'_2(x)e^x-y_2(x)e^x}{e^{2x}}=C(2x-x^2)e^{-x} $$ which is equivalent to $$ \left(\frac{y_2(x)}{e^x}\right)'=C(2x-x^2)e^{-x} $$ It is remains to integrate $$ \frac{y_2(x)}{e^x}=Cx^2 e^{-x}+D $$ and write down the answer $$ y_2(x)=Cx^2+D e^{x} $$ In fact this is a general solution of original equation. A: $$ (x^2 - 2x)y'' - (x^2 - 2)y' + (2x - 2)y = 0 $$ Let's first notice that $c y_1(x)= c e^x$ is also a solution. To find other solutions let's suppose that $c$ depends of $x$ (this method is named 'variation of constants') : If $y(x)= c(x) e^x$ then your O.D.E. becomes : $$ (x^2 - 2x)(c''+c'+c'+c)e^x - (x^2 - 2)(c'+c)e^x + (2x - 2)ce^x = 0 $$ $$ (x^2 - 2x)(c''+2c'+c) - (x^2 - 2)(c'+c) + (2x - 2)c = 0 $$ Of course the $c$ terms disappear and we get : $$ (x^2 - 2x)(c''+2c') - (x^2 - 2)c' = 0 $$ Let's set $d(x)=c'(x)$ then : $$ (x^2 - 2x)d' = (x^2 - 2)d-(x^2 - 2x)2d $$ $$ (x^2 - 2x)d' = (-x^2 +4x- 2)d $$ $$ \frac{d'}d = \frac{-x^2 +4x- 2}{x^2 - 2x} $$ I'll let search the integral at the right, the answer should be ($C_0$, $C_1$, $C_2$ are constants) : $$ \ln(d)=\ln(x^2-2x)-x+C_0 $$ $$ d=(x^2-2x)e^{-x}C_1 $$ but $c'=d$ so that $$ c=C_2+C_1\int (x^2-2x)e^{-x} dx $$ $$ c=C_2-C_1x^2e^{-x} $$ And we got the wished general solution : $$ y(x)=c(x)e^x=C_2e^x-C_1x^2 $$
{ "pile_set_name": "StackExchange" }
Q: SQL query to split column data into rows I am having sql table in that I am having 2 fields as No and declaration Code Declaration 123 a1-2 nos, a2- 230 nos, a3 - 5nos I need to display the declaration for that code as: Code Declaration 123 a1 - 2nos 123 a2 - 230nos 123 a3 - 5nos I need to split the column data to rows for that code. A: For this type of data separation, I would suggest creating a split function: create FUNCTION [dbo].[Split](@String varchar(MAX), @Delimiter char(1)) returns @temptable TABLE (items varchar(MAX)) as begin declare @idx int declare @slice varchar(8000) select @idx = 1 if len(@String)<1 or @String is null return while @idx!= 0 begin set @idx = charindex(@Delimiter,@String) if @idx!=0 set @slice = left(@String,@idx - 1) else set @slice = @String if(len(@slice)>0) insert into @temptable(Items) values(@slice) set @String = right(@String,len(@String) - @idx) if len(@String) = 0 break end return end; Then to use this in a query you can use an outer apply to join to your existing table: select t1.code, s.items declaration from yourtable t1 outer apply dbo.split(t1.declaration, ',') s Which will produce the result: | CODE | DECLARATION | ----------------------- | 123 | a1-2 nos | | 123 | a2- 230 nos | | 123 | a3 - 5nos | See SQL Fiddle with Demo Or you can implement a CTE version similar to this: ;with cte (code, DeclarationItem, Declaration) as ( select Code, cast(left(Declaration, charindex(',',Declaration+',')-1) as varchar(50)) DeclarationItem, stuff(Declaration, 1, charindex(',',Declaration+','), '') Declaration from yourtable union all select code, cast(left(Declaration, charindex(',',Declaration+',')-1) as varchar(50)) DeclarationItem, stuff(Declaration, 1, charindex(',',Declaration+','), '') Declaration from cte where Declaration > '' ) select code, DeclarationItem from cte A: Declare @t Table([Code] int, [Declaration] varchar(32)); Insert Into @t([Code], [Declaration]) Values(123, 'a1-2 nos, a2- 230 nos, a3 - 5nos') Select x.[Code] ,t.Declaration From ( Select *, Cast('<X>'+Replace(t.[Declaration],',','</X><X>')+'</X>' As XML) As record From @t t )x Cross Apply ( Select fdata.D.value('.','varchar(50)') As Declaration From x.record.nodes('X') As fdata(D) ) t Few times back , I have blogged about the same Split Function in Sql Server using Set base approach Also, please visit Erland Sommarskogblog who is maintaining the answer for the same since the last 15 years.
{ "pile_set_name": "StackExchange" }
Q: Getting Url in the call back function of WebRequesting Let's say I have a web request: WebRequest webRequest = WebRequest.Create(Url); webRequest.BeginGetResponse(this.RespCallback, webRequest); Now is there is any way to retrieve the URL in private void RespCallback(IAsyncResult asynchronousResult) { // here } The idea is I want to provide a sequence id in the url while doing web request and then retrieve it on the call back and match it to know that this call back is from that request. Any ideas? A: This should work: private void RespCallback(IAsyncResult asynchronousResult) { WebRequest wreq = asynchronousResult as WebRequest; Uri wreqUri = wreq.RequestUri; }
{ "pile_set_name": "StackExchange" }
Q: Ошибка запроса в jquery ajax в Laravel Отправляю запрос в базу, кликаю на кнопку сохранить отрабатывает beforeSend лоадер, и запись в базу доходит и записывается, но сам ajax возвращает error, следовательно success не выполняется. Данные в базу пишутся. В чем может быть проблема????? $('#form_update').on('click', '#button_update', function(){ var category = $('input#category_edit').val(); var is_active = $('select#status').val(); var title = $('input#title').val(); var description = $('textarea#description').val(); var status; if(is_active == 1) { status = "Отключено"; }else{ status ="Включено"; } $.ajax({ url: "/admin/categories/update", type: "post", beforeSend: function(){ var bodyH = $(window).height() / 2; $("div#edit_cat").after('<div id="system-load" style="position:fixed;' + 'top:0px; left:600px; width:10%; height:10%;' + 'z-index:99999999; color:#fff; padding-top:' + bodyH + 'px;"' + 'align="center">' + '<img src="/images/preloader.gif"' + ' alt="Пожалуйста, подождите..." /></div>'); $(window).bind('load', function() { $('#system-loading').fadeOut('slow').remove(); $('#sytem-content').animate({opacity: 1}, 'fast'); }); }, dataType: 'json', data: { 'id':item_id, '_token':csrf, 'category':category, 'is_active':is_active, 'title':title, 'description':description, }, succces: function(data){ alert("Ajax запрос выполнен\n"+data.message); $("tr#"+item_id+"> td[class=cat]").text(category); $("tr#"+item_id+"> td[class=status]").text(status); $("#system-load").remove(); }, error: function(xhr,status,error){ alert('Ошибка Ajax-запроса\n'+status+'\n'+error); console.log(status); console.log(error); } }); return false; }); A: У вас есть в $.ajax() параметр dataType: 'json'. Вот что о нем написано в документации: dataType (default: Intelligent Guess (xml, json, script, or html)) Type: String The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). То есть, если вы указали json, то и вернуть должны строго его. Вы же, судя по всему, считаете, что этот параметр обозначает не то, что сервер должен вернуть, а то, что вы ему передаете. Но это не так :) Ну и еще, надо писать не succces, а succcess.
{ "pile_set_name": "StackExchange" }
Q: Cloning Pointers C++ This question is regarding copying and pointer polymorphism. Consider the code below. We have two classes: Base and Derived, which are just regular objects. Then we've got class Foo, which has a pointer to Base as its only member. The typical usage of Foo is described in the main function. The input to Foo::SetMemberX may or may not be a temporary object. The problem is that I want Foo::SetMember to create a proper copy of the passed object, and assign its address as a Base* to Foo::mMember. I've managed to come up with 4 possible solution, none of which seem very elegant to me. The first three are shown in the code below in Foo::SetMember1, Foo::SetMember2, and Foo::SetMember3. The 4th option is to leave the memory allocation to the user (ex. foo.SetMember(new Derived())), which is not very desirable for obvious memory safety issues. Foo should be responsible for memory management, not the user. #include <iostream> template <typename tBase, typename tPointer> void ClonePointer(tBase*& destination, const tPointer* pointer) { destination = static_cast<tBase*>(new tPointer(*pointer)); } // Base can be a virtual class class Base { public: virtual void Function() { std::cout << "Base::Function()" << std::endl; } virtual Base* Clone() const = 0; }; class Derived : public Base { public: virtual void Function() { std::cout << "Derived::Function()" << std::endl; } virtual Base* Clone() const { return new Derived(*this); } }; class Foo { public: Foo() : mMember(NULL) { } ~Foo() { if (mMember != NULL) { delete mMember; mMember = NULL; } } template <typename T> void SetMember1(const T& t) { if (mMember != NULL) { delete mMember; mMember = NULL; } ClonePointer(mMember, &t); } void SetMember2(const Base& b) { mMember = b.Clone(); } template <typename T> void SetMember3(const T& t) { if (mMember != NULL) { delete mMember; mMember = NULL; } mMember = new T(t); } Base& GetMember() { return *mMember; } private: Base* mMember; }; int main(int argc, char** argv) { { Foo f1; Foo f2; Foo f3; // The input may or may not be a tempoary/RValue reference f1.SetMember1(Derived()); f2.SetMember2(Derived()); f3.SetMember3(Derived()); f1.GetMember().Function(); f2.GetMember().Function(); f3.GetMember().Function(); } // Output: // Derived::Function(); // Derived::Function(); // Derived::Function(); system("pause"); // for quick testing } The problem with the first method (Foo::SetMember1) is that I have a random, free, template function, and a template accessore (see the problem with the third method below). The problem with the second method (Foo::SetMember2) is that every derived class must implement its own Clone function. This is too much boilerplate code for the class user, as there will be a lot of classes deriving from Base. If I could somehow automate this, or create a base Cloneable class (without each Base-derived class having to explicitly calling it) with an implemented template Clone function, this would be the ideal solution. The problem with the third method (Foo::SetMember3) is that I'd need a template accessor for Foo. This may not always be possible, especially because of how virtual template methods are not allowed in non-template classes (Foo cannot be a template itself), which is a functionality that might be required. My questions are: Are these the only options I have? Is there a better, more elegant solution to this problem that I'm missing? Is there any way to create a base Cloneable class and derive Base from it, and have cloning automagically happen for DerivedType::Clone()? A: Here's a more or less robust Clonable class that can be inherited to any depth. It uses CRTP and Alecsandrescu-style interleaving inheritance pattern. #include <iostream> // set up a little named template parameters rig template <class X> struct Parent{}; template <class X> struct Self{}; template<class A, class B> struct ParentChild; // can use ...< Parent<X>, Self<Y> >... template<class A, class B> struct ParentChild< Parent<A>, Self<B> > { typedef A parent_type; typedef B child_type; }; // or ...< Self<Y>, Parent<X> > template<class A, class B> struct ParentChild< Self<B>, Parent<A> > { typedef A parent_type; typedef B child_type; }; // nothing, really struct Nada { // except the virtual dtor! Everything clonable will inherit from here. virtual ~Nada() {} }; // The Clonable template. Accepts two parameters: // the child class (as in CRTP), and the parent class (one to inherit from) // In any order. template <class A, class B = Parent<Nada> > class Clonable : public ParentChild<A,B>::parent_type { public: // a nice name to refer to in the child class, instead of Clonable<A,B> typedef Clonable Parent; // this is our child class typedef typename ParentChild<A,B>::child_type child_type; // This is the clone() function returning the cloned object // Non-virtual, because the compiler has trouble with covariant return // type here. We have to implemens something similar, by having non-virtual // that returns the covariant type calling virtual that returns the // base type, and some cast. child_type* clone() { return static_cast<child_type*>(private_clone()); } // forward some constructor, C++11 style template<typename... Args> Clonable(Args&&... args): ParentChild<A,B>::parent_type(args...) {} private: // this is the main virtual clone function // allocates the new child_type object and copies itself // with the copy constructor virtual Nada* private_clone() { // we *know* we're the child_type object child_type* me = static_cast<child_type*>(this); return new child_type(*me); }; }; // Test drive and usage example class Foo : public Clonable < Self<Foo> > { public: Foo (int) { std::cout << "Foo::Foo(int)\n"; } Foo (double, char) { std::cout << "Foo::Foo(double, char)\n"; } Foo (const Foo&) { std::cout << "Foo::Foo(Foo&)\n"; } }; class Bar : public Clonable < Self<Bar>, Parent<Foo> > { public: // cannot say Bar (int i) : Foo(i), unfortunately, because Foo is not // our immediate parent // have to use the Parent alias Bar (int i) : Parent(i) { std::cout << "Bar::Bar(int)\n"; } Bar (double a, char b) : Parent(a, b) { std::cout << "Bar::Bar(double, char)\n"; } Bar (const Bar& b) : Parent(b) { std::cout << "Bar::Bar(Bar&)\n"; } ~Bar() { std::cout << "Bar::~Bar()\n"; } }; int main () { Foo* foo1 = new Bar (123); Foo* foo2 = foo1->clone(); // this is really a Bar delete foo1; delete foo2; } A: For 2nd method, you can use CRTP and you won't need to write clone method in every derived class: struct Base { virtual ~Base() {} virtual Base *clone() const = 0; }; template <typename Derived> struct CloneableBase : public Base { virtual Base *clone() const { return new Derived(static_cast<Derived const&>(*this)); } }; struct Derived: CloneableBase<Derived> {};
{ "pile_set_name": "StackExchange" }
Q: Is there a thought experiment which brings to light the contradiction between General Relativity and Quantum Mechanics? I've been told that GR and QM are not compatible, is there an intuitive reason/thought experiment which demonstrates the issue? (Or one of the issues?) A: The simple thought experiments are not related to the naive reason people give for the incompatibility--- people say that they are incompatible because of renormalizability. This is not easy to explain, and it is in fact false, because N=8 supergravity is with some scientific confidence renormalizable. But it's not a good theory. The reason for the incompatibility is the behavior of black holes--- the fact that they have an entropy which scales as the area, not the volume. In quantum field theory, the fields near the horizon have infinite entropy, as shown by 't Hooft. So you need a different kind of quantum theory, one which is nonlocal enough to allow black holes to have entropy which goes as area. This is the only incompatibility, since string theory is exactly such a quantum theory, and it is a consistent theory of gravity. So there is no further incompatibility left.
{ "pile_set_name": "StackExchange" }
Q: Pattern matching issue in Java I am poor in Regular Expressions. I googled and got basic understanding of it. I have below requirement: My command may contain some strings with "$(VAR_NAME)" pattern. I need to find out whether it has such type of strings or not. If so, I have to resolve those(I know what should I do, if such strings are there). But, problem is, how to find whether command has strings with "$(VAR_NAME)" pattern. There might be multiple or zero of such string patterns in my command. As per my knowledge, I have written below code. If I use, 'pattern1' , in below code, it is matching. But, not with 'pattern' Can someone help in this? Thank you in advance. final String command = "somescript.file $(ABC_PATH1) $(ENV_PATH2) <may be other args too here>"; final String pattern = "\\Q$(\\w+)\\E"; //final String pattern1 = "\\Q$(ABC_PATH1)\\E"; final Pattern pr = Pattern.compile(pattern); final Matcher match = pr.matcher(command); if (match.find()) { System.out.println("Found value: " + match.group(0)); } else { System.out.println("NO MATCH"); } A: Using \Q and \E will mean you cannot setup a capture group for the variable name because the round brackets will be interpreted literally. I'd probably do it like this, just escape the outer $, ( and ). Also if you need multiple matches you need to call find() multiple times, I've used a while loop for this. final String command = "somescript.file $(ABC_PATH1) $(ENV_PATH2) <may be other args too here>"; final String pattern = "\\$\\((\\w+)\\)"; final Pattern pr = Pattern.compile(pattern); final Matcher match = pr.matcher(command); while (match.find()) { System.out.println("Found value: " + match.group(1)); } Output Found value: ABC_PATH1 Found value: ENV_PATH2
{ "pile_set_name": "StackExchange" }
Q: How to find a plaintext sibling in BeautifulSoup 4? For example: <p>I am in a paragraph element!</p> I am plaintext! How can I get the I am plaintext! text in BeautifulSoup 4 by calling find("p")? I have already tried this: from bs4 import BeautifulSoup soup = BeautifulSoup("...", "html.parser") soup.find("p").findNextSibling() # Returns None A: Call .find_next_sibling() with parameter text=True: txt = ''' <p>I am in a paragraph element!</p> I am plaintext!''' from bs4 import BeautifulSoup soup = BeautifulSoup(txt, 'html.parser') print(soup.find('p').find_next_sibling(text=True)) Prints: I am plaintext!
{ "pile_set_name": "StackExchange" }
Q: How to use aggregate function without GROUP BY? SQL> SELECT * FROM student; NAME ID AGE MARK1 MARK2 TOTAL -------------------- ---------- ---------- ---------- ---------- ----------- Ananda 200 22 90 95 Chris 250 18 80 75 Gokul 325 17 50 50 SQL> SELECT MAX(mark1),name FROM student; SELECT MAX(mark1),name FROM student * ERROR at line 1: ORA-00937: not a single-group group function As you can see the error, can anyone suggest me a query to select the Maximum mark from the table and display it along with the corresponding name of the student?? Is it even possible without using GROUP BY clause? As you can see, there's no logical way of using GROUP BY clause here. A: If you want to get the name of the student also, you need to use a join: SELECT T2.Mark,T1.name FROM student T1 JOIN (SELECT MAX(Mark1) as Mark FROM student) T2 on T1.Mark=T2.mark Result: MAXMARK NAME ------------ 90 Ananda Sample result in SQL Fiddle A: I found an easy solution: SELECT mark1,name FROM student WHERE mark1= (SELECT MAX(mark1) FROM student); Result: MARK1 NAME ----- ------- 90 Ananda
{ "pile_set_name": "StackExchange" }
Q: How to make files inside TMPFS more likely to swap I'm using tmpfs for my /tmp directory. How can I make the computer decide to swap out the files inside the /tmp before swapping out anything that is being used by applications? Basically the files inside /tmp should have a higher swappiness compared to the memory being used by processes. It seems this answer https://unix.stackexchange.com/a/90337/56970 makes a lot of sense, but you can't change swappiness for a single directory. I know about cgroups though, but I don't see any way of making tmp into a cgroup? A: If all goes well, your kernel should decide to "do the right thing" all by itself. It uses a lot of fancy heuristics to decide what to swap out and what to keep when there is memory pressure. Those heuristics have been carefully built by really smart people with a lot of experience in memory management and are already good enough that they're pretty hard to improve upon. The kernel uses a combination of things like this to decide what to swap out: How recently the memory has been used. Whether the memory has been modified since it was mapped. So for example a shared library will be pushed out ahead of heap memory because the heap memory is dirty and needs to be written to swap, whereas the shared library mapped memory can be loaded again from the original file on disk in case it is needed again, so no need to write those pages to swap. Here you should realize that tmpfs memory is always dirty (unless it's a fresh page filled with zeros) because it is not backed by anything. Hints from mprotect(). Likely many more. Short answer: no, you can't directly override the kernel's decisions about how to manage memory.
{ "pile_set_name": "StackExchange" }
Q: Adding Custom font family to react native Text not working I am currently trying to add a custom font to a react native app but after trying almost all answers i could find on SO and on google, it still doesn't work. i tried to make react native aware of the font by add "rnpm": { "assets": [ "./assets/fonts/" ] }, to the package.json and then running react-native link and also using the re-run commad. But still doesn't work. Below is the code app.js import React, { useEffect } from 'react'; import { StyleSheet, Text, View, Image } from 'react-native'; import imager from './assets/cars.png'; import * as Font from 'expo-font'; export default function App() { useEffect(() => { async function loadFont() { return await Font.loadAsync({ righteous: require('./assets/fonts/Righteous-Regular.ttf'), }); } loadFont(); }, []); return ( <View style={styles.container}> <Image style={styles.imager} source={imager} /> <Text style={{ fontSize: 30, fontWeight: 'bold', paddingTop: 30, fontFamily: 'righteous', }} > Request Ride </Text> <Text style={{ fontSize: 15, padding: 40, textAlign: 'center' }}> Request a ride and get picked up by a nearby community driver </Text> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center', }, imager: { width: 200, height: 200, shadowColor: 'rgba(0, 0, 0, 0.2)', shadowRadius: 10, shadowOpacity: 1, }, }); I have the font Righteous-Regular.ttf in ./assets/fonts but when i run this code, i get this error fontFamily "righteous" is not a system font and has not been loaded through Font.loadAsync. If you intended to use a system font, make sure you typed the name correctly and that it is supported by your device operating system. If this is a custom font, be sure to load it with Font.loadAsync. I researched but still can't find the solution to this. Please what could be the issue and how do i go about it? A: You are trying to use the font before the font is loaded. You need to do something like this. import React, { useEffect, useState } from 'react'; import { StyleSheet, Text, View, Image } from 'react-native'; import imager from './assets/cars.png'; import * as Font from 'expo-font'; export default function App() { // use state for font status. const [isFontReady, setFontReady] = useState(false) useEffect(() => { async function loadFont() { return await Font.loadAsync({ righteous: require('./assets/fonts/Righteous-Regular.ttf'), }); } // after the loading set the font status to true loadFont().then(() => { setFontReady(true) }); }, []); return ( <View style={styles.container}> <Image style={styles.imager} source={imager} /> {/* render the text after loading */} {isFontReady && <Text style={{ fontSize: 30, fontWeight: 'bold', paddingTop: 30, fontFamily: 'righteous', }} > Request Ride </Text>} <Text style={{ fontSize: 15, padding: 40, textAlign: 'center' }}> Request a ride and get picked up by a nearby community driver </Text> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center', }, imager: { width: 200, height: 200, shadowColor: 'rgba(0, 0, 0, 0.2)', shadowRadius: 10, shadowOpacity: 1, }, }); It is up to you to display the element after the font is installed or to display it with a different font before.
{ "pile_set_name": "StackExchange" }
Q: c# random operators and math problems, do loop Hey guys im trying to work on this assignment i have. I am new to programming and this is my third assignment. Any help would be appreciated. Im not sure if im on the right track or not. here is what i have to do: allow the user to enter a numeric answer to math problem and display their average score. The user will be allowed to answer as many math problems as they choose. After each entry we will display the current average score. The difference between the while loop and the do loop is the while loop tests a condition before running its code block where the do loop will execute its code block and then test a condition. Hence the names of pre-test loop for the while loop and post-test loop for the do loop. Since the do loop is a post-test loop, it will always execute its code block one time at a bare minimum. these are the steps im trying to follow: Inside the Main method block of code we are going to create a do loop. The advantage of a do loop is that it will always execute one time. In this application we will use that advantage to repeat several steps. The following steps are what we want to repeat: Clear the console Display window. (This will keep the display from getting cluttered) Use random object to get/store two random numbers for a math problem. Randomly decide which math operator to use (+-*/)and store the symbol. Display an application header and the math problem formatted. Get the answer from the user and store it in a variable(i.e.“input”). Convert variable(input)from a string to a double or integer. Based on the math symbol calculate the correct answer using random numbers. If user entry matches correct answer,add question point value to points earned total. Add the question point value to the points possible total. Display message with points earned, possible, and the average (earned/possible). Display a message asking the user if they want to quit or get a new math problem. Pause display and get the user response of quit or continue.! using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MathProblems { class Program { static void Main(string[] args) { string input; double totalPoints = 0; double userEarnedPoints = 0; double average = 0; int number1 = 0; int number2 = 0; int operators = 0; int answer = 0; double correctAnswer = 0; int mathProblem = 0; do { Console.Clear(); Random number = new Random(); number1 = number.Next(1, 31); number2 = number.Next(1, 31); operators = number.Next(1, 5); // 1 = add, 2 = minus, 3 = multiply, 4 = divide Console.WriteLine("\tMath Problems\n"); switch (operators) { case 1: answer = number1 + number2; break; case 2: answer = number1 - number2; break; case 3: answer = number1 * number2; break; case 4: answer = number1 / number2; break; default: break; } //if (operators == 1) //{ // Console.WriteLine("{0} + {1} = ", number1, number2); //} //else if (operators == 2) //{ // Console.WriteLine("{0} - {1} = ", number1, number2); //} //else if (operators == 3) //{ // Console.WriteLine("{0} * {1} = ", number1, number2); //} //else if (operators == 4) //{ // Console.WriteLine("{0} / {1} = ", number1, number2); //} //break; } while (true); Console.ReadLine(); A: In order to get user input, you need to do Console.ReadKey() (for a single character) or Console.ReadLine() (for a string of characters terminated by Enter). You can then capture this input in a variable and then do a comparison on it to get the user's answer or to determine if they want to continue or not. You also will need to validate that the input was an integer. You can use int.TryParse() to do this. It will return true if the string was an integer, and will store the integer in the out parameter. You can then compare the userAnswer to the actual answer to see if they got it right. It also looks like you need to increment the total problems and the user score (when they get an answer correct) One way to do this would be: { var rnd = new Random(); var quit = false; var userScore = 0; var totalProblems = 0; var percentCorrect = 0d; while (!quit) { Console.Clear(); var number1 = rnd.Next(1, 31); var number2 = rnd.Next(1, 31); var operation = rnd.Next(1, 5); string operatorString; int answer; totalProblems++; Console.WriteLine("\tMath Problem:"); Console.WriteLine("\t-------------"); switch (operation) { case 1: answer = number1 + number2; operatorString = "+"; break; case 2: answer = number1 - number2; operatorString = "-"; break; case 3: answer = number1 * number2; operatorString = "*"; break; case 4: answer = number1 / number2; operatorString = "/"; break; default: answer = 0; operatorString = "?"; break; } Console.WriteLine("\t{0} {1} {2}", number1, operatorString, number2); Console.Write("\nEnter your answer here (round down if necessary): "); var input = Console.ReadLine(); int inputAsInt; while (!int.TryParse(input, out inputAsInt)) { Console.Write("Answer must be an integer. Try again: "); input = Console.ReadLine(); } if (inputAsInt == answer) { Console.WriteLine("Correct!"); userScore++; } else { Console.WriteLine("Sorry, the correct answer was: {0}", answer); } percentCorrect = Math.Round((double)userScore / totalProblems * 100, 2); Console.WriteLine("\nYou have answered {0} of {1} questions correctly, " + "for a total of {2}%.", userScore, totalProblems, percentCorrect); Console.Write("\nPress 'q' to quit, or any other key to continue... "); if (Console.ReadKey().Key == ConsoleKey.Q) quit = true; } var letterGrade = percentCorrect < 60 ? "F" : percentCorrect < 67 ? "D" : percentCorrect < 70 ? "D+" : percentCorrect < 73 ? "C-" : percentCorrect < 77 ? "C" : percentCorrect < 80 ? "C+" : percentCorrect < 83 ? "B-" : percentCorrect < 87 ? "B" : percentCorrect < 90 ? "B+" : percentCorrect < 93 ? "A-" : "A"; Console.WriteLine("\n\nThank you for playing. You've earned you a letter " + "grade of: {0}", letterGrade); Console.Write("\nPress any key to exit..."); Console.ReadKey(); }
{ "pile_set_name": "StackExchange" }
Q: Matching forward slash in Oracle regexp_like The question that I am going to ask might have been asked before but I am not able to find any satisfactory answer for the problem I am facing. I have written 2 regular expression to find out column in database starting with special character (non alphanumeric), below are the 2 regular expressions, To find records with only special characters, select col_name from tbl_name where regexp_like (col_name, '^[^ 0-9 A-Z a-z]*$'); To find records for which only the first character is non-alphanumeric select col_name from tbl_name where regexp_like(col_name, '^[^ 0-9 A-Z a-z]{1}.*'); But the above queries are not returning me some documents for which the col_name value is forward slash (/) only. I am not able to understand that, why it is not returning any of these records. Also how do I confirm, the above queries are not missing any other non-alphanumeric character. Hope I am clear with my question. A: Try this: regexp_like(col_name,'^[^0-9A-Za-z]') Which won't exclude col_names with leading spaces and only looks at the first character of the col_name.
{ "pile_set_name": "StackExchange" }
Q: .2015: When last did both New/Full moon in a fort-night cause an Eclipse? Going through http://earthsky.org/…/dates-of-next-lunar-and-solar-eclipses I made the (what was for me - momentous) discovery that March 20, 2015 - New moon - is a Solar Eclipse, and that the succeeding April 04, 2015 - Full moon - heralds a Lunar Eclipse. Is it common that both New/Full moon in a fort-night cause an eclipse? When was the last time an Eclipse occurred back-to-back on a consecutive New Moon/Full Moon? A: As written here: Another oddity of nature is that solar eclipses and lunar eclipses tend to come in pairs – a solar eclipse always takes place about two weeks before or after a lunar eclipse. And here: Rules of Eclipses (Solar and Lunar) ... Eclipses tend to go in pairs or threes : solar-lunar-solar. Lunar eclipse always preceeded by or followed by a solar eclipse (two weeks between them) So, seems like a totally common thing. P.S. The previous pair was first lunar on Oct 8, 2014, and then solar on Oct 23rd.
{ "pile_set_name": "StackExchange" }
Q: SearchController changes the size of tableView The size of my tableView mysteriously changes heights when the search controller is active like the images I attached below. The image in the far left is the initial state. Middle image is when the search controller is active and the last image is when the search controller is dismissed. I tried setting the content size of the tableview when the search controller is active, in the viewDidLoad, viewWillAppear and viewDidAppear without any luck. Any idea on how to resolve this problem? P.S. The items you see are just dummy posts. A: Try set edgesForExtendedLayout property to be under Top Bar using code or storyboard
{ "pile_set_name": "StackExchange" }
Q: split a large file by a delimiter- out of memory I want to split a large file to many files based on a delimiter. The delimiter I am aiming in my input file is // (double forward slash in a newline). Part of my file is like .. ... 7141 gatttaggca gtgaaaactt agtagccgac aaggtgaaag atgccgagaa tgtactaagg 7201 gtaaaggcag ctaaaacaga ctttaccgat agcaccaacc tatcggtcat cactcaagac 7261 ggaggctttt atagctttga ggtgagttat cacaccacgc cacaacctct taccattgat 7321 tttggtagag gaatgcccca aggcaataat gtgaaatcgg atattctctt ttctgacaca 7381 ggctgggaat cacctgcggt agcacagatt attatgtcgt ctatct // LOCUS KE150251 6962 bp DNA linear CON 14-JUN-2013 DEFINITION Capnocytophaga granulosa ATCC 51502 genomic scaffold acFDk-supercont1.18/ whole genome shotgun sequence. ... .. I also want to include these slashes as the last line of the generated files. I failed do it by csplit in my Mac, and end up with the following awk script: awk -v RS='^//' '{ outfile = "output_file_" NR; print > outfile}' Input.gbk But I am getting following error: awk(56213,0x7fffb585b3c0) malloc: *** mach_vm_map(size=18446744071562067968) failed (error code=3) *** error: can't allocate region *** set a breakpoint in malloc_error_break to debug awk: out of memory in readrec 1 source line number 1 Thanks for your suggestions! A: I believe since you have NOT closed files(new output files) they are eating up the memory. Could you please try following once. awk -v RS='^//' '{close(outfile)} {outfile = "output_file_" NR; print > outfile}' Input.gbk EDIT: one more try with another approach. Since I believe your file have many lines between // so memory is getting filled up by RS so better to use a flag approach rather than RS approach. awk -v outfile="output_file_1" -v count=1 '/^\/\//{print > outfile; close(outfile);outfile = "output_file_" ++count;next} {print > (outfile)}' Input.gbk Explanation of above approach: Checking for line which starts from // and increment value in outputfile name and reset value of output file name variable, also I am closing output file here else you may get error too many files opened in background too.
{ "pile_set_name": "StackExchange" }
Q: Reac-Bootstrap how to overwrite form-input background I've got a next.js application and am using react-bootstrap. I am trying to overwrite my default form background from that blueish gray (#e8f0fe or rgb(232, 240, 254)) that bootstrap is using for inputs to white. I am currently customizing the bootstrap variables via a custom.bootstrap.scss file $theme-colors: ( 'primary': #e28215, 'secondary': #83b8f3, 'tertiary': #1575e2, 'headings': #2b363f, 'body': #5b6b79, 'inputBorderNormal': #c3ced6, 'inputBorderFocus': #90a3b0, 'darkBG': #2b363f, 'lightBG': #eef0f3, 'input-bg': #fff, 'input-bg-disabled': #fff, ); @import '~bootstrap/scss/bootstrap.scss'; this file is then imported into my index.scss: @import './custom.bootstrap.scss' I am then using the index.scss in my _app.js like this: import '../style/index.scss'; The theming seems to work as my primary button is orange, but I can't get the form background to change (I can't even overwrite it on element level with !important) Please find a repo here Any help appreciated. Cheers A: I have made a code sandbox to demonstrate this https://codesandbox.io/s/sparkling-feather-ppg8q?file=/style/custom.bootstrap.scss There were two changes: 1.instead of importing index.scss import the custom bootstrap file into _app.js import "../style/custom.bootstrap.scss"; Declare the variables directly into the file and apply them. $darkBG: #2b363f; $primary:#e28215; $tertiary: #1575e2; // ... Rest of your colors.. @import '~bootstrap/scss/bootstrap'; body { padding: 20px 20px 60px; margin: 0; background-color: $primary; } form { background-color:$darkBG; } .my-3 { background-color:$tertiary; }
{ "pile_set_name": "StackExchange" }
Q: Papers whose title defines a new terminology To explain a new signal processing technique based on Fourier Transform, Bogert et al went on to define a new vocabulary. The new terminology was published in a paper with the title: The Quefrency Alanysis of Time Series for Echoes: Cepstrum, Pseudo-autocovariance, Cross-Cepstrum, and Saphe Cracking, B.P. Bogert, M.J.R. Healy, J.W. Tukey, Proc. Symp. Time Series Analysis, M. Rosemblatt, Ed., John Wiley & Sons, 1963, pp. 209-243. Spell-checkers are not recommended... :-) ADDED: As we can see, the authors changed the position of the letters in the paper title to reflect the phenomenon analysed (echo in communication). Then, they used these new words to nominate the signal processing technique. The question is: are there another papers with this characteristic (papers where the unusual terminology in the title reflect the phenomenon analysed) ? Only the term Cepstrum has been widely used. BTW, Cepstrum is the result of taking the Inverse Fourier transform (FT) of the logarithm of the spectrum of a signal. There is a complex cepstrum, a real cepstrum, a power cepstrum, and phase cepstrum. The power cepstrum in particular finds applications in the analysis of human speech. ADDED: The idea of the kepstrum appears in the classical work of Poisson (1823), Schwarz (1872), Szego (1915), and Kolmogorov (1939), and has been applied to geophysical problems by Robinson (1954), Bogert et al. (1963), Schafer (1969), Oppenheim and Schafer (1975), Tribolet (1977), and others., M.T. Silvia, E.A. Robinson, Use of Kepstrum in Signal Analysis, Geoexploration, 16, 1978, pp. 55-73. Our word “kepstrum” means the same as their term “complex cepstrum”. Because the kepstrum of a real-time sequence is real, the use of the word “kepstrum” is less confusing than the term “complex cepstrum”., M.T. Silvia, E.A. Robinson, Use of Kepstrum in Signal Analysis, Geoexploration, 16, 1978, pp. 55-73. A: Jean-Pierre Serre: Gèbres, Enseign. Math. (2) 39 (1993), 33–85.
{ "pile_set_name": "StackExchange" }
Q: OSGi bundle imports packages from non-bundle jars: create bundles for them? I am new to OSGi, and am using Equinox. I have done several searches and can find no answer to this. The discussion at OSGI - handling 3rd party JARs required by a bundle helps somewhat, but does not fully answer my question. I have obtained a jar file, rabbitmq-client.jar, that is already packaged as an OSGi bundle (with Bundle-Name and other such properties in its MANIFEST.MF), that I would like to install as a bundle. This jar imports packages org.apache.commons.io and org.apache.commons.io.input from commons-io-1.2.jar. The RabbitMQ client 2.7.1 distribution also includes commons-cli-1.1.jar, so I presume that it is required as well. I examined the manifests of these commons jars and found that they do not appear to be packaged as bundles. That is, their manifests have none of the standard bundle properties. My specific question is: if I install rabbitmq-client.jar as a bundle, what is the proper way to get access to the packages that it needs to import from the commons jars? There are only three alternatives that I can think of, without rebuilding rabbitmq-client.jar. The packages from the commons jars are already included in the Equinox global classpath, and rabbitmq-client.jar will get them automatically from there. I must make another bundle with the two commons jars, export the needed packages, and install that bundle in Equinox. I must put these two commons jars in the global classpath when I start Equinox, and they will be available to rabbitmq-client.jar from there. I have read that one normally does not use the global classpath in an OSGi container. I am not clear on whether items from the global classpath are even available when building individual bundle classpaths. However, I note that rabbitmq-client.jar also imports other packages such as javax.net, which I presume come from the global classpath. Or is there some other bundle that exports them? Thanks for any assistance! A: Solution (2) is the correct way. (1) and (3) will not work because, as you seem to understand already, there is no such thing as a global classpath in OSGi. Each bundle imports all the packages that it needs, and those packages must be exported by another bundle. There is an exception to this, which is all the classes under the java.* namespace... i.e. there is no need to import java.lang, java.util etc. Packages such as javax.net do come from the JRE but they are still not on a "global classpath". There is a special bundle called the System Bundle, which represents the OSGi Framework itself within OSGi. That bundle exports a bunch of packages that come from the JRE such as javax.net, javax.swing, org.w3c.dom, etc. A: I'd also add to what Neil has said that for popular bundles, like commons-io, there's usually no need for option (2), since someone else has already done it. There is a SpringSource repository with many converted bundles. For commons-io you can do even better, since version 1.4 of the 'official' jar on maven central is already a bundle.
{ "pile_set_name": "StackExchange" }
Q: Set display font family in wxhaskell? I'm trying to build a little program to learn some wxHaskell, a haskell library for wxwidgets. It would be beneficial for this particular one if I could set the font of a text field to monospaced, but I have no idea how to do that if it is possible. In wxwidgets there seems to be setFamily and wxFONTFAMILY_TELETYPE, but I can't find anything about this being implemented in wxHaskell, nor how to use it if it were. Is it possible to do this? A: Here's an example, in the change the line in the Hello, World program in the wxHaskell Quick Start from: = do f <- frame [text := "Hello!"] to = do f <- frame [text := "Hello!", font := fontFixed] Found this by digging down in the docs here
{ "pile_set_name": "StackExchange" }
Q: How to display Alpha Beta Pruning algorithm result? Updates Update 1 I tried this (2nd line): I added changing node color as first instruction in alphabeta function. I am getting this result: Green nodes are visited nodes. It looks like, algorithm is going throw nodes correctly, right? But how to output correct values in nodes — I also need to do this? Minimum of children values, maximum of children values (excluding pruned branches). Update 2 I tried to output alpha and beta to the tree nodes and didn't get correct result. This is code (line 18 and 31 were added). This is result of the code: On this image I show strange places: First arrow: why minimum of 7 and 6 is 5? Second arrow: why maximum of 4, 3 and 2 is 5? Strange. Thats why I think, that it is now working correctly. Old question Once upon a time I created similar question here. It was like: "why I get this error?". Lets rollback and created new one. This question will be: "How to display Alpha Beta Pruning algorithm result?" I found pseudocode of this algorithm on the wiki. It can be found here. My realization is below (it is on JavaScript, but I don't think that to answer this question you have to know JS or Java or C++ etc). The question is how to output result of this algorithm on the graph (tree structure)? On start I have this tree structure: NOTE: I have tree structure (some amount of linked nodes), on which I will use alpha beta pruning algorithm, and I have another tree structure (for displaying results, lets call it "graph"). Nodes of tree, which I use to display graph are connected with nodes, which I use to find result of the algorithm. So, code of the alpha beta pruning algroithm is below. Can you clarify what and where I have to output to display process/results of the algorithm correctly, please? My assumption is to output alpha and beta, but I think, it is wrong. I tried it, but it doesn't work. I want to display prunings and fill in all nodes in the tree with correct values. This is my realization of minimax with alpha beta pruning: function alphabeta(node, depth, alpha, beta, isMax, g) { if((depth == 0) || (node.isTerminal == true)) { return node.value; } if(isMax) { console.log('maximizing'); for (var i in node.children) { var child = node.children[i]; console.log(child); alpha = Math.max(alpha, alphabeta(child, depth-1, alpha, beta, false, g)); if(beta <= alpha) { console.log('beta '+beta+' alpha '+alpha); break; } } return alpha; } else { console.log('minimizing'); for (var i in node.children) { console.log('1 child'); var child = node.children[i]; console.log(child); beta = Math.min(beta, alphabeta(child, depth-1, alpha, beta, true, g)); if (beta <= alpha) { console.log('beta '+beta+' alpha '+alpha); break; } } return beta; } } A: Why don't you just store the nodes that are actually visited, and colour those nodes Red. Then you will see which nodes got evaluated compared to the entire tree. E.g. After a long discussion in the comments, I think I can now shed light on this. As the alpha beta goes around the tree, it has three values, when operating on a given node, it has the alpha and beta that were carried down to it from its parent node, and then it has the best value it has found so far. If it finds a value outside the alpha-beta window, it immediately prunes, as it knows that this node is not an optimal move, irrespective of its value. Thus, for some nodes alpha beta never works out the "true value" of the node. Thus, when you are asked to display the "result" of alpha beta, I mistakenly thought that you meant the alpha-beta window, since the "true value" is never necessarily evaluated. You would need to write separate code to print the "true node values". I think that the minimax algorithm will do this for you. Also, be aware when comparing by hand that if you are using a "set" of nodes, the list iterator is not guaranteed to return the nodes in a predictable order, so if inside the nodes you are using sets rather than lists, you might find that its hard to follow by hand. List iterators return in insertion order. Set iterators have no predictable iterator.
{ "pile_set_name": "StackExchange" }
Q: How to Dispose myClass with Garbage Collecter C# I have a class and got a method that doin so many things in memory and need to be disposed when its jobs done.But i have looked for MSDN for solution.There is an example thats not solved my problem.When my Class is instanced and run this method my memory is getting bigger and bigger.How can i Dispose it when its job done ? Here is my CODES ; class Deneme { public Deneme() { } ~Deneme() { GC.Collect(); GC.SuppressFinalize(this); } public void TestMetodu() { System.Windows.Forms.MessageBox.Show("Test"); // This is my method that doing big jobs :) } } Deneme CCCX = new Deneme(); CCCX.TestMetodu(); CCCX = null; So i cant dispose it with this. A: implement IDisposable (with function Dispose) and then wrap the creation of your object in a using statement. (when the object goes out of scope (after the using block), the dispose will be called.) Furthermore, never call GC.Collect(). A: Does your class directly use any unmanaged resources, or hold references to any IDisposable objects? If so, then you should probably implement IDisposable to clean-up those resources, and then wrap all uses of your class in a using block. If your class only uses managed resources, and doesn't hold references to any IDisposable objects, then you should probably let the GC do its job without any interference. Just ensure that the lifetime of any instances of your class are kept as short as possible. A: ~Deneme() { GC.Collect(); GC.SuppressFinalize(this); } You don't need to use GC.Collect() or GC.SuppressFinalize(this);, because at this point, the garbage collector is already collecting the object. You want to use the Dispose method, so you can encapsulate the object use in a using statement. Here is a link that will show you the pattern on how to implement it: http://www.c-sharpcorner.com/UploadFile/Ashish1/dispose02152006095441AM/dispose.aspx link to MSDN: http://msdn.microsoft.com/en-us/library/system.idisposable.dispose.aspx private bool IsDisposed { get;set; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~CLASS_NAME() { Dispose(false); } protected virtual void Dispose(bool disposedStatus) { if (!IsDisposed) { IsDisposed = true; // Released unmanaged Resources if (disposedStatus) { // Released managed Resources } } }
{ "pile_set_name": "StackExchange" }
Q: GitHub for Windows: login failed with .Net 4.5.2 So I recently updated .NET on my computer to 4.5.2 - and I think this is causing an error with GitHub for Windows. As noted here and here, you can install patches, make sure certain DLLs aren't corrupted, re-install, etc. I have done all of these, and none have worked. All of these other questions are also older, and before 4.5.2 was released. For full clarification, the versions of .NET I have installed are: 4.5.2 4.5.1 Multi-Targeting Pack 4.5.1 Multi-Targeting Pack (ENU) 4.5.1 SDK I have reinstalled at least 3 times, and the app still does not work. It was working fine until I upgraded .Net to 4.5.2. What do I do from here? Another symptom I am having is that every repository I try to view says Failure looking for HEAD in this repository, which I take to mean that it cannot access the remote repository. I imagine this is because of the same reason that login is failing. However, if I open the repository in Git Bash, everything is working fine - I can see the remote, push to it, pull from it, everything. The issue lies somewhere within the GitHub for Windows client. I just don't know where... A: Since posting this question, GitHub for Windows released an update that has fixed the issue.
{ "pile_set_name": "StackExchange" }
Q: Did any of TOS 5 year mission first contacts aliens show up in later Star Trek episodes as Borg? Are there any examples of Star Trek TOS aliens being assimulated by the Borg in any of the following versions of the Star Trek TV/Movie franchise? A: By the standards set forth in the question, there are 55 original series species that are "encountered/discovered" during TOS Star Trek. Of those 55 species, only the Romulans meet the criteria of having been discovered or encountered during "first contact" during the TOS Star Trek. having had members of their species assimilated by the Borg. I put quotations around first contact since the Federation had been at War with the Romulans before TOS but had not communicated (beyond trying to blow up their ships) before the 1966 episode of TOS called "Balance of Terror" first aired on September 13, 1966 and was the 14th episode of Star Trek to be aired. The Romulans are identified by the Borg as Species 3783. List of Star Trek Races A: I'm not sure if you are willing to include games in the franchise, here's one example In the Star Trek Game Star Trek: Legacy, the Borg are featured midway through the TOS era as "Assimilated Klingon ships". In the final mission, once the player has completed the primary objective, a confrontation with T'urell ensues; she departs, and the player must destroy a Borg Sphere. Also, same Wiki article has 2 more book examples, one of a race whose creation is mentioned in TOS, and one, of an attempt to assimilate TOS's Spock: The Peter David novel Vendetta reveals that the planet killer weapon from the Original Series episode "The Doomsday Machine" is a prototype for a weapon against the Borg, with a woman whose race were destroyed by the Borg trying to use the weapon against them despite the damage she will cause on her journey due to its need to consume planets. David revisited this concept in a 2007 sequel novel, Before Dishonor, which features the Enterprise-E working with Spock and Seven of Nine to reactive the original planet killer to stop the Borg. In William Shatner's novel The Return, Spock is nearly assimilated by the Borg, but is saved because he mind-melded with V'ger, an earlier form of the Borg. Using the information he subconsciously acquired in the meld, Spock is able to lead a crew of Enterprise officers- consisting of the Enterprise-D senior staff, himself, Admiral McCoy, and the resurrected Kirk- in a Defiant-class ship to destroy the Borg central node, severing all branches of the collective from each other and limiting their future threat. A: We saw a couple of Klingon Borg in at least voyager. Klingons are definitely TOS aliens.
{ "pile_set_name": "StackExchange" }
Q: Issue with html css bullet list vertical The HTML: <ul class="fruits"> <li>Peach</li> <li>Apple</li> <li>Orange</li> <li>Banana</li> <li>Pineapple</li> <li>Strawberry</li> </ul> The CSS: .fruits ul { list-style-type:none; padding:0px; margin:0px; } .fruits ul li { background-image:url('http://www.myurl.co.uk/images/mybullet.png'); background-repeat:no-repeat; background-position:0px 5px; padding-left:14px; } I have other horizontal navigation menus on the page so this needs to be classed as above. When I attempt to try, it defaults back to a bullet list only, and doesn't work. I tried only using < ul > and it worked, but messed the rest of the page up. Any suggestions for a normal vertical bullet list with specific class? A: Try this: ul.fruits { list-style-type:none; padding:0px; margin:0px; } I have made a jsfiddle for you here. I have removed the background styles so don't forget to re-insert them.
{ "pile_set_name": "StackExchange" }
Q: Multiple iOS developer licenses for a company My company has an iOS developer license, and like many others we have reached the 100 UDID limitation. Since I have about 10 more months until the next time I can delete unused UDIDs I tried purchasing another IOS developer license for my company but got rejected from Apple since my company already holds a program enrollment. How can I bypass this issue? I really need more UDIDs so I can send my applications to testers. Do I need to open an individual iOS programing license or is there another way to enroll a company to another iOS license. A: This has been covered here. None of the answers look particularly appealing, but I doubt you'll get other advice.
{ "pile_set_name": "StackExchange" }
Q: Python Pandas working with dataframes in functions I have a DataFrame which I want to pass to a function, derive some information from and then return that information. Originally I set up my code like: df = pd.DataFrame( { 'A': [1,1,1,1,2,2,2,3,3,4,4,4], 'B': [5,5,6,7,5,6,6,7,7,6,7,7], 'C': [1,1,1,1,1,1,1,1,1,1,1,1] } ); def test_function(df): df['D'] = 0 df.D = np.random.rand(len(df)) grouped = df.groupby('A') df = grouped.first() df = df['D'] return df Ds = test_function(df) print(df) print(Ds) Which returns: A B C D 0 1 5 1 0.582319 1 1 5 1 0.269779 2 1 6 1 0.421593 3 1 7 1 0.797121 4 2 5 1 0.366410 5 2 6 1 0.486445 6 2 6 1 0.001217 7 3 7 1 0.262586 8 3 7 1 0.146543 9 4 6 1 0.985894 10 4 7 1 0.312070 11 4 7 1 0.498103 A 1 0.582319 2 0.366410 3 0.262586 4 0.985894 Name: D, dtype: float64 My thinking was along the lines of, I don't want to copy my large dataframe, so I will add a working column to it, and then just return the information I want with out affecting the original dataframe. This of course doesn't work, because I didn't copy the dataframe so adding a column is adding a column. Currently I'm doing something like: add column results = Derive information delete column return results which feels a bit kludgy to me, but I can't think of a better way to do it without copying the dataframe. Any suggestions? A: If you do not want to add a column to your original DataFrame, you could create an independent Series and apply the groupby method to the Series instead: def test_function(df): ser = pd.Series(np.random.rand(len(df))) grouped = ser.groupby(df['A']) return grouped.first() Ds = test_function(df) yields A 1 0.017537 2 0.392849 3 0.451406 4 0.234016 dtype: float64 Thus, test_function does not modify df at all. Notice that ser.groupby can be passed a sequence of values (such as df['A']) by which to group instead of the just the name of a column.
{ "pile_set_name": "StackExchange" }
Q: Python consume an iterator pair-wise I am trying to understand Python's iterators in the context of the pysam module. By using the fetch method on a so called AlignmentFile class one get a proper iterator iter consisting of records from the file file. I can the use various methods to access each record (iterable), for instance the name with query_name: import pysam iter = pysam.AlignmentFile(file, "rb", check_sq=False).fetch(until_eof=True) for record in iter: print(record.query_name) It happens that records come in pairs so that one would like something like: while True: r1 = iter.__next__() r2 = iter.__next__() print(r1.query_name) print(r2.query_name) Calling next() is probably not the right way for million of records, but how can one use a for loop to consume the same iterator in pairs of iterables. I looked at the grouper recipe from itertools and the SOs Iterate an iterator by chunks (of n) in Python? [duplicate] (even a duplicate!) and What is the most “pythonic” way to iterate over a list in chunks? but cannot get it to work. A: First of all, don't use the variable name iter, because that's already the name of a builtin function. To answer your question, simply use itertools.izip (Python 2) or zip (Python 3) on the iterator. Your code may look as simple as for next_1, next_2 in zip(iterator, iterator): # stuff edit: whoops, my original answer was the correct one all along, don't mind the itertools recipe. edit 2: Consider itertools.izip_longest if you deal with iterators that could yield an uneven amount of objects: >>> from itertools import izip_longest >>> iterator = (x for x in (1,2,3)) >>> >>> for next_1, next_2 in izip_longest(iterator, iterator): ... next_1, next_2 ... (1, 2) (3, None)
{ "pile_set_name": "StackExchange" }
Q: not equal sign not working in javascript I am using not equal sign to convert false to true but it is always giving false. I have tried it with 0 and 1 which is working fine. Also when I am changing value "False" to "true" then it is also working but problem is with "false" only. <script type="text/javascript"> var test= "False"; alert(!test) </script> A: You are assigning the string "False", assign the boolean false var test = false; alert(!test);
{ "pile_set_name": "StackExchange" }
Q: MonoDevelop -- GTK Designer just shows a blank square? I am having problems getting the GTK designer to work with MonoDevelop. I tried 2.4 on Arch Linux and it gave this problem. Then I tried 2.2 on OpenBSD and it gives the exact same problem. Both machines are 64bit. Instead of having a window to drag things on I just have a blank square: alt text http://img96.imageshack.us/img96/4766/monodevelop.png The tutorials I've seen look similar to this though: alt text http://monodevelop.com/@api/deki/files/142/=Stetic_Tutorial_06.jpg?size=bestfit&width=700&height=425 So what gives? With my blank square I can't drag anything onto it, not a VBox or other container even. It will not react to anything. Am I missing some sort of GTK# configuration or what? I find it highly improbable that both OSs' packages I tried are broken. Also, I've attached a (huge) bounty to this because this is a pretty big issue for me. The console output from the starting of Mono and including me trying to drag an element onto the gray box is here Update Ok, so I've finally gotten a bit closer to solving the mystery. I use Fluxbox as my window manager usually. Well I tried using both KDE and Gnome-Session and both of them cause MonoDevelop to work properly(though still missing the window border, you could at least drag components onto it). Now my question is what makes Fluxbox not work for it? A: I have the same problem in openSUSE 11.3 x64 KDE using Mono JIT compiler version 2.6.7 (tarball Wed Jul 14 18:00:23 UTC 2010) downloaded from here type -a monodevelop returns: monodevelop is /usr/bin/monodevelop monodevelop is /usr/bin/X11/monodevelop Running monodevelop from terminal gives the following output 1) WARNING: Cannot find Mozilla directory containing libgtkembedmoz.so. Some Addins may not be able to function. Please set MOZILLA_FIVE_HOME to your Mozilla directory. This can be solved by adding an environment variable in your .bashrc file from your home directory. export MOZILLA_FIVE_HOME='/path/to/libgtkembedmoz.so/directory/' To find if that library exists on your systems use: sudo find / -name libgtkembedmoz.so -print (from this bug report this library is contain in the Mozilla's XUL Runner package, but in newer versions I don't know if it's still there, I had to use libgtkembedmoz.so provided by Slickedit which was installed in /opt/slickedit/bin/mozilla/) 2) WARNING [2010-07-29 20:22:37Z]: Inotify watch limit is too low (8192). To resolve this problem read Inotify Watches Limit 3) WARNING [2010-07-29 20:22:37Z]: Error creating composed icon gtk-execute___asm0__debug-overlay-22.png__SmallToolbar at size SmallToolbar. Icon __asm0__debug-overlay-22.png__SmallToolbar is 22x22, expected 16x16. I get the exact same error using Monodevelop 2.4, and I think this could be either from a broken GTK# installation or from a bug in Monodevelop, Your result is the same as mine, see here. I suggest compiling MonoDevelop from Github and/or using a newer version of gtk-sharp/gdk-sharp This part ERROR [2010-07-29 20:22:37Z]: GdkPixbuf-Critical: gdk_pixbuf_composite: assertion `dest_x >= 0 && dest_x + dest_width <= dest->width' failed appears in GTK and GDK crashes, If this does not resolve the problem submitting a bug report is the next option. Although this is somehow strange, since I managed to complete the same tutorial using Kubuntu 10.04 LTS 64 bit a few weeks ago.
{ "pile_set_name": "StackExchange" }
Q: checkcolumn select all; header manipulation, select all function After posting the question ExtJS checkcolumn grid - check columns to left, uncheck columns to right and thinking there were existing questions and answers for a "select all" option, I've read a little deeper and they don't actually cover what I need in relation to my other question's answer. I need to know what code is required to generate a checkbox in each column header that, when selected/deselected, changes the checkboxes in the given column. Existing code for reference: Ext.Loader.setConfig({ enabled: true }); Ext.Loader.setPath('Ext.ux', '../ux'); Ext.require([ 'Ext.ux.CheckColumn' ]); Ext.onReady(function(){ Ext.define('ProcessModel', { extend: 'Ext.data.Model', fields: [ 'Item', 'Phase1', 'Phase2', 'Phase3', 'Phase4', 'Phase5', 'Phase6', 'Phase7', 'Phase8', 'Phase9', 'Phase10' ] }); // create the Data Store var processStore = Ext.create('Ext.data.Store', { model: 'processModel', autoLoad: true, proxy: { // load using HTTP type: 'ajax', url: '<?= $site_url ?>/Production/Processes/<?= $itemId ?>', reader: { type: 'json', model: 'ProcessModel', root: data } } }); function onCheckChange (column, rowIndex, checked, eOpts) { var record = processStore.getAt(rowIndex); var columnIndex = column.getIndex(); for (var i = 1; i <= 10; i++) { if(checked) { if (i <= columnIndex) { record.set('Phase'+i, true); } else { record.set('Phase'+i, false); } } else { if (i >= columnIndex) { record.set('Phase'+i, false); } } } } Ext.create('Ext.grid.Panel', { width: 800, store: processStore, title: 'Processes', tbar: [ { xtype: 'button', text: 'Update', handler: function(){ //TODO: update by POST function } } ], columns: [ { text: 'Item', dataIndex: 'Item' },{ xtype: 'checkcolumn', text: 'Phase 1', dataIndex:'Phase1', listeners: { checkChange: onCheckChange } },{ xtype: 'checkcolumn', text: 'Phase 2', dataIndex:'Phase2', listeners: { checkChange: onCheckChange } },{ xtype: 'checkcolumn', text: 'Phase 3', dataIndex:'Phase3', listeners: { checkChange: onCheckChange } },{ xtype: 'checkcolumn', text: 'Phase 4', dataIndex:'Phase4', listeners: { checkChange: onCheckChange } },{ xtype: 'checkcolumn', text: 'Phase 5', dataIndex:'Phase5', listeners: { checkChange: onCheckChange } },{ xtype: 'checkcolumn',, listeners: { checkChange: onCheckChange } text: 'Phase 6', dataIndex:'Phase6', listeners: { checkChange: onCheckChange } },{ xtype: 'checkcolumn', text: 'Phase 7', dataIndex:'Phase7', listeners: { checkChange: onCheckChange } },{ xtype: 'checkcolumn', text: 'Phase 8', dataIndex:'Phase8', listeners: { checkChange: onCheckChange } },{ xtype: 'checkcolumn', text: 'Phase 9', dataIndex:'Phase9', listeners: { checkChange: onCheckChange } },{ xtype: 'checkcolumn', text: 'Phase 10', dataIndex:'Phase10', listeners: { checkChange: onCheckChange } } ], renderTo: Ext.get('sencha_processes') }); }); Imagined pseudo-code to handle select all function, for the kind of effect I'm looking for: function selectAllInColumn (column, checked, eopts){ var columnIndex = column.getIndex(); for( var i = 0; i < processStore.getCount(); i++) { if(checked) { var record = processStore.getAt(i); for(var j = 1; j <= columnIndex; j++) { record.set('Phase'+columnIndex, true); } for(var j = columnIndex+1; j <= 10; j++) { record.set('Phase'+columnIndex, false); } } else { var record = processStore.getAt(i); for(var j = columnIndex; j <= 10; j++) { record.set('Phase'+columnIndex, false); } } } } A: You can take a look at my variant of generating a checkbox in each column header. Check checkcolumn with select all with the discription or just fiddle with example. My checkcolumn: Ext.define('Fiddle.CheckColumn', { extend: 'Ext.grid.column.CheckColumn', alias: 'widget.fiddlecheckcolumn', renderTpl: [ '<div id="{id}-titleEl" data-ref="titleEl" {tipMarkup}class="', Ext.baseCSSPrefix, 'column-header-inner<tpl if="!$comp.isContainer"> ', Ext.baseCSSPrefix, 'leaf-column-header</tpl>', '<tpl if="empty"> ', Ext.baseCSSPrefix, 'column-header-inner-empty</tpl>">', '<span class="', Ext.baseCSSPrefix, 'column-header-text-container">', '<span class="', Ext.baseCSSPrefix, 'column-header-text-wrapper">', '<span id="{id}-textEl" data-ref="textEl" class="', Ext.baseCSSPrefix, 'column-header-text', '{childElCls}">', '<img class="', Ext.baseCSSPrefix, 'grid-checkcolumn" src="' + Ext.BLANK_IMAGE_URL + '"/>', '</span>', '</span>', '</span>', '<tpl if="!menuDisabled">', '<div id="{id}-triggerEl" data-ref="triggerEl" role="presentation" class="', Ext.baseCSSPrefix, 'column-header-trigger', '{childElCls}" style="{triggerStyle}"></div>', '</tpl>', '</div>', '{%this.renderContainer(out,values)%}' ], constructor : function(config) { var me = this; Ext.apply(config, { stopSelection: true, sortable: false, draggable: false, resizable: false, menuDisabled: true, hideable: false, tdCls: 'no-tip', defaultRenderer: me.defaultRenderer, checked: false }); me.callParent([ config ]); me.on('headerclick', me.onHeaderClick); me.on('selectall', me.onSelectAll); }, onHeaderClick: function(headerCt, header, e, el) { var me = this, grid = headerCt.grid; if (!me.checked) { me.fireEvent('selectall', grid.getStore(), header, true); header.getEl().down('img').addCls(Ext.baseCSSPrefix + 'grid-checkcolumn-checked'); me.checked = true; } else { me.fireEvent('selectall', grid.getStore(), header, false); header.getEl().down('img').removeCls(Ext.baseCSSPrefix + 'grid-checkcolumn-checked'); me.checked = false; } }, onSelectAll: function(store, column, checked) { var dataIndex = column.dataIndex; for(var i = 0; i < store.getCount(); i++) { var record = store.getAt(i); if (checked) { record.set(dataIndex, true); } else { record.set(dataIndex, false); } } } }); A: Worked out how to do it; hard code a checkbox with an id into the header text of each check column, move the scope of the grid and store to be initialised as global (but actually constructed on Ext.ready), then have global functions that operate on the datastore records via for loops: outside of Ext.ready: var processGrid = null; var processStore = null; function headerClick(col, int){ if(document.getElementById(col).checked==true) { selectAllInColumn(int, true); } else { selectAllInColumn(int, false); } } function selectAllInColumn (column, checked, eOpts){ //foreach record in data store for( var i = 0; i < processStore.getCount(); i++) { if(checked) { // get record var record = processStore.getAt(i); // for current column and each preceding column set process step to true and check the header for(var j = 1; j <= column; j++) { document.getElementById('HeaderPhase'+j).checked = true; record.set('Phase'+j, true); } } else { var record = processStore.getAt(i); for(var j = column; j <= 10; j++) { document.getElementById('HeaderPhase'+j).checked = false; record.set('Phase'+j, false); } } } } function startCheckHeaderCheckBox(){ // foreach checkcolumn for(var i = 1; i <= 10; i++) { // start running tally per column var checkedTotal = 0; // foreach record in data store for (var j = 0; j < processStore.getCount();j++) { var record = processStore.getAt(j); if (record.get('Phase'+i) == "true"){ checkedTotal++; } } if(checkedTotal==processStore.getCount()) { document.getElementById('HeaderPhase'+i).checked=true; } else { document.getElementById('HeaderPhase'+i).checked=false; } } } function inProgressCheckHeaderCheckBox(columnIndex){ for( var i = 1; i <=columnIndex; i++) { var checkedTotal = 0; for (var j = 0; j < processStore.getCount(); j++) { var record = processStore.getAt(j); if (record.get('Phase'+i)){ checkedTotal++; } } if(checkedTotal==processStore.getCount()) { document.getElementById('HeaderPhase'+i).checked=true; } } } Inside Ext.ready: // before loading the grid.Panel; onCheckChange called function onCheckChange (column, rowIndex, checked, eOpts) { var record = processStore.getAt(rowIndex); var columnIndex = column.getIndex(); for (var i = 1; i <= 10; i++) { if(checked) { if (i <= columnIndex) { record.set('Phase'+i, 'true'); inProgressCheckHeaderCheckBox(columnIndex); } } else { if (i >= columnIndex) { record.set('Phase'+i, false); document.getElementById('HeaderPhase'+i).checked = false; } } } } // after loading the grid.Panel to govern setting header check boxes on load processStore.on('load', startCheckHeaderCheckBox); // put in each checkColumn, this is the first phase header, change the numbers to match each phase header: 'Phase 1 <br /> <input type="checkbox" id="HeaderPhase1" style="x-grid-checkcolumn" onclick="headerClick(\'HeaderPhase1\', 1)"/>', Hope this helps other people, bear in mind my implementation will need to be tailored to whatever dataset you're using, and is dependent on names and IDs being standardised as Phases/HeaderPhases with numbers appended.
{ "pile_set_name": "StackExchange" }
Q: Using onChange={} and event handlers in ReactJS class App extends Component { constructor(props){ super(props); this.state = { key: myUUID, title: "", author: "", questions: [], answers: [] } } handleChange = (event) => { const target = event.target; const value = target.type === "checkbox" ? target.checked : target.value; const name = target.name; this.setState({ [name]: value }); } Ok so I am trying to make it so when the user types into this input <input type="text" value={this.state.title} onChange={this.handleChange}/> the "value" of it updates to what the user is inputing. Currently when I type in the input box, the characters I type do not show up and the state (title) for this input does not seem to update. I am new to React and JS so any tips/pointers/explanation of what's happening will be much appreciated. Thanks! UPDATE: Here's the render method (there's more in it than just this so I consolidated) render () { //yada yada <div> <form> <div className="Intro"> Give your Quiz a title: <input type="text" value={this.state.title} onChange={this.handleChange}/><br/> Who's the Author? <input type="text" /><br/><br/> </div> <div className="questions"> Now let's add some questions... <br/> {this.addQuestion} </div> </form> <button onClick={this.addQuestion}>Add Question</button> </div> //yada yada } export default App; A: You need to pass in the name prop to your input components. These props should be set to their respective keys in the state. Example: class App extends Component { constructor(props){ super(props); this.state = { key: myUUID, title: "", author: "", questions: [], answers: [] }; } handleChange(event) { const target = event.target; const value = target.type === "checkbox" ? target.checked : target.value; const name = target.name; this.setState({ [name]: value }); } render() { return( <div> <input type="text" value={this.state.title} onChange={this.handleChange} name='title' /> <input type="text" value={this.state.author} onChange={this.handleChange} name='author' /> </div> ); } } Edited for clarity
{ "pile_set_name": "StackExchange" }
Q: ogr2ogr postgres import: check if dataset exists I have a PostGIS database which I update daily with ogr2ogr using CSV files. This works great. Is there a way to check whether the actual value of a column already exists in the table (e.g. "event_id"=abc123 (no primary key)) and if so, that it will not append the dataset to the table. The other datasets that are not in the table should be appended to the table. This is my actual command-line: ogr2ogr -f "PostgreSQL" -append PG:"host=localhost user=user password=pw dbname=test" data.vrt -nln table_name A: What you are looking for is essentially an upsert (albeit without the update part). This is not part of ogr2ogr and is fairly complicated to implement in Postgres, see the docs, for more information than you would ever want to know about upserts. A simple alternative, would be to use a temp table to insert into from ogr2ogr and then run an insert for only those rows where there is no event_id, using either a left join or a not exists clause. INSERT INTO some_table SELECT t.* FROM some_table t LEFT JOIN temp_table tmp ON t.event_id = tmp.event_id WHERE tmp.event_id IS null;
{ "pile_set_name": "StackExchange" }
Q: WFS Spatial Operator Query - Crosses AND Within I'm trying to query my wfs service with a polygon. I want the service to return both features that are inside the polygon and partially inside the polygon. However, when I use the "Within" spatial operator, I only get features that are completely inside. When I use the "Crosses" operator, I only get the features that are partially inside the polygon. I have tried using And/Or to query for features that are either one or the other, but WFS does not support multiple spatial operators in a query. It gives me this error: "Unsupported filter - filter has more than one spatial operator." Does anyone have an idea of how to get around this without sending two separate ajax requests to the service? Here's an example that returns data with the "within" filter. var xml = '<ogc:Filter xmlns="http://www.opengis.net/ogc">\n' + '<ogc:Within>\n' + '<ogc:PropertyName>Shape</ogc:PropertyName>\n' + '<gml:Polygon>\n' + '<gml:outerBoundaryIs>\n' + '<gml:LinearRing>\n' + '<gml:coordinates>' + queryObject.geometryString + '</gml:coordinates>\n' + '</gml:LinearRing>\n' + '</gml:outerBoundaryIs>\n' + '</gml:Polygon>\n' + '</ogc:Within>\n' + '</ogc:Filter>\n' Here's the capabilites of the wfs service: <ogc:SpatialOperators> <ogc:SpatialOperator name="BBOX"/> <ogc:SpatialOperator name="Equals"/> <ogc:SpatialOperator name="Disjoint"/> <ogc:SpatialOperator name="Intersects"/> <ogc:SpatialOperator name="Crosses"/> <ogc:SpatialOperator name="Touches"/> <ogc:SpatialOperator name="Within"/> <ogc:SpatialOperator name="Contains"/> <ogc:SpatialOperator name="Overlaps"/> </ogc:SpatialOperators> A: Here are two rectangles drawn on top of the map of the States. This is WFS 1.0.0 filter with two Intersects combined with OR <ogc:Filter> <ogc:Or> <ogc:Intersects> <ogc:PropertyName>topp:the_geom</ogc:PropertyName> <gml:Polygon> <gml:outerBoundaryIs> <gml:LinearRing> <gml:coordinates decimal="." cs="," ts=" ">-106.20615648060549,39.43168954588457 -106.20615648060549,42.000086140018915 -104.73069460737938,42.000086140018915 -104.73069460737938,39.43168954588457 -106.20615648060549,39.43168954588457</gml:coordinates> </gml:LinearRing> </gml:outerBoundaryIs> </gml:Polygon> </ogc:Intersects> <ogc:Intersects> <ogc:PropertyName>topp:the_geom</ogc:PropertyName> <gml:Polygon> <gml:outerBoundaryIs> <gml:LinearRing> <gml:coordinates decimal="." cs="," ts=" ">-112.65447133396404,35.715711494796594 -112.65447133396404,38.06552114474929 -111.12436272469252,38.06552114474929 -111.12436272469252,35.715711494796594 -112.65447133396404,35.715711494796594</gml:coordinates> </gml:LinearRing> </gml:outerBoundaryIs> </gml:Polygon> </ogc:Intersects> </ogc:Or> </ogc:Filter> Here you can see the result after sendind the request to WFS service at http://demo.opengeo.org/geoserver/wfs. The purple states are a new layer that was fetched from WFS. Thus it is possible to include two spatial filters into one GetFeature request and it works at least with GeoServer WFS. Another thing is that in your case it is not necessary because Intersects filter should do what you want and select all features totally or partly inside the reference geometry. In other words Intersects is "Not Disjoint".
{ "pile_set_name": "StackExchange" }
Q: How to pass multiple arguments to dotCover merge I am writing powershell command to merge two snapshots as following - &$coveragTool merge /Source= $TestResult1;$TestResult2 /Output= TestMergeOutput.dcvr it is giving error as - Parameter 'Source' has invalid value. Invalid volume separator char ':' (0x3A) in path at index 67. where as the document says two files should be separated by a semicolon(;) like this - merge: Merge several coverage snapshots usage: dotCover merge|m <parameters> Valid parameters: --Source=ARG : (Required) List of snapshots separated with semicolon (;) --Output=ARG : (Required) File name for the merged snapshot --TempDir=ARG : (Optional) Directory for the auxiliary files. Set to system temp by default Global parameters: --LogFile=ARG : (Optional) Enables logging and allows specifying a log file name --UseEnvVarsInPaths=ARG : (Optional) [True|False] Allows using environment variables (for example, %TEMP%) in paths. True by default how do i make it correct? A: You cannot pass an unquoted ; as part of an argument, because PowerShell interprets it as a statement separator. Either enclose the argument in "...", or `-escape the ; character selectively; also, the space after = may or may not be a problem. To make the call (at least syntactically) succeed, use the following: & $coveragTool merge /Source="$TestResult1;$TestResult2" /Output=TestMergeOutput.dcvr Alternatively (note the `, ignore the broken syntax highlighting): & $coveragTool merge /Source=$TestResult1`;$TestResult2 /Output=TestMergeOutput.dcvr PowerShell has more so-called metacharacters than cmd.exe, for instance, notably ( ) , { } ; @ $ # in addition to & | < > - see this answer for additional information.
{ "pile_set_name": "StackExchange" }
Q: Why is there a memory leak when I do not .Dispose() Bitmaps that I .Save() to a MemoryStream? Say I create a Bitmap Bitmap bitmap = new Bitmap(320, 200); When I write it to some stream (in my case, it's a HttpResponseStream, as given out by HttpListenerResponse), everything is fine: bitmap.Save(stream, ImageFormat.Png); I don't need to bitmap.Dispose(), the resources used by the bitmap will get cleaned up automatically. The problem with directly writing a Png to a non-seekable stream however is that it might result in A generic error occurred in GDI+, which happened to me when I tried my Asp app on Azure. So this is how my code looks now: using (MemoryStream ms = new MemoryStream()) { bitmap.Save(ms, ImageFormat.Png); ms.WriteTo(stream); } Now unless I bitmap.Dispose() afterwards, this will leak. Rephrased question to get more specific answers: Why does this leaking of Bitmap memory seem to depend on what type of stream I save it to? Update: As I've been asked in comments if I'm sure it's a leak. Calling the above repeatedly in a stress test, my w3wp process will go up to gigs and gigs of memory used until my machine start swapping and it will not clean up. A: Bitmap class utilizes unmanaged resources. These resources are not related to the resources utilized by the memory stream class. You can just wrap the bitmap class in a using statement to dispose of the bitmap instance when you are finished with it. Missed the latter part of your question. One way to "set it and forget it" is by creating a wrapper class that exposes the bitmap instance but implements a destructor that disposes of the bitmap instance. This destructor will mean the bitmap class is disposed of implicitly at garbage collection. As a final note: Any object you instantiate that implements IDisposable MUST be disposed of by your code. Dipose will never be implicitly called. Even in your first example. Just because you save the data to a stream does not meam that memory has then been deallocated. Most of the time it is a good idea to dipose of an object within the same segment of code that instantiated it. This assists in easier to read code by boosting code transparency.
{ "pile_set_name": "StackExchange" }
Q: simple regular expression question How to match aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab where number of a's should be min of 10? I mean i know this way: [a][a][a][a][a][a][a][a][a][a][a][a][a]a*b But there must be a better elegant method where is if my min number of a's become say 100.. What is it? I am trying to match (a^n)b sort of thing where n can be anything EDIT: I forgot to mention this is done using lex and yacc.. where the lex has to return a token to yacc. %{ #include "y.tab.h" %} %% aaaaaaaaaa[a]*b {return ok;} \n {return '\n';} . {return 0;} %% A: Try a{10,} which says a 10 or more times. grep -E "a{10,}" filename matches aaaaaaaaaaaaaaaaaaaaaaaaab but not aaaaaaaaab. A: If your lex is flex, you can use a{10,}. If not so, according to 3. Lex Regular Expressions , you can use a{10}a* instead.
{ "pile_set_name": "StackExchange" }
Q: Bamboo Limit Concurrent Builds Across Branches We have a small number of shared databases for integration tests and a large number of branches that share these. Is there any way to prevent Bamboo from concurrently trying to run multiple branches that use the same database? When builds in multiple branches run in parallel they clobber each other and fail. A: There are outstanding feature requests for this BAM-12071 and BAM-2423 waiting on Atlassian to implement a solution. In the meantime we devised a quick and dirty workaround for this based on using old fashioned file (actually directory) locking. Each resource is defined with a variable name gatekeeper.resource in the job or branch configuration, At the beginning of a build process a "Gatekeeper" stage checks that the required resource is free using a directory name in a common file on a common server. While the directory name exists the resource is in use. The first task of the subsequent build stage creates the resource name as an empty directory, and a final task removes it. Other builds cannot proceed past the first stage until the resource is free, stopping concurrent builds. The downside is that it does tie up a local bamboo agent, and is not completely foolproof but does work for us 99% of the time. It even works across build plans if the resource variable is defined correctly. Its defined as a SSH task against a linux instance: # This Gatekeeper stage prevents concurrent builds against a resource # by looking for a directory instance in a common file area. # If the directory exists the build cannot proceed until it disappears. # The build sleeps as long as the directory exists. # # The first task in the subsequent stage is to create the directory, and # a final task in the build removes it. # As a failsafe a background half-hourly cron job should remove lock # dirs if they exceed 3 x the build time. ######################################################### # Wait for a random number of seconds 20-120 to reduce (but not eliminate) the chance that multiple competing branch # builds triggered by timers both see the dir gone and start the unit test job at once and then proceed to clobber each other (i.e a race condition) # note: bamboo expects output every 3 minutes so do not increase beyond 180 seconds SLEEPYTIME=$(( ( RANDOM % 100 ) + 20 )) echo SLEEPYTIME today is $SLEEPYTIME sleep $SLEEPYTIME # Wait for the Gatekeeper lock dir to disappear... or be older than 3 hours (previous build may have hung) file=/test/atlassian/bamboo-gatekeeper/inuse-${bamboo.gatekeeper.resource} while [ -d "$file" ] do echo $(date +%H:%M:%S) waiting $SLEEPYTIME seconds... sleep $SLEEPYTIME done exit 0 First job task of the build stage (after the Gatekeeper): # This will fail if the lock file (actually a directory!) already exists file=/test/atlassian/bamboo-gatekeeper/inuse-${bamboo.gatekeeper.resource} mkdir "$file" Final step of the build stage following a build (successful or otherwise) file=/test/atlassian/bamboo-gatekeeper/inuse-${bamboo.gatekeeper.resource} rm -rf "$file" There is also a failsafe cron clean up task that removes any resource gateway directories older than a few hours (3 in our case). Should not be necessary but prevents builds being tied up indefinitely in case bamboo itself is restarted without running a final task. # This works in conjunction with bamboo unit tests. It clears any unit test lock files after 3 hours (e.g. build has hung or killed without removing lock file) 15,45 * * * * find /test/atlassian/bamboo-gatekeeper -name inuse* -mmin +180 -delete gatekeeper.resource can be defined as the name of anything you want. In our case it is a database schema used by integration tests. Some of our branches use a common test environment, other branches have their own instance. This solution stops the branches using the common environment from executing concurrently while allowing branches with their own environment to proceed. It is not a complete fix to limit concurrent builds to a specific number, but it is sufficient to get us around this issue until Atlassian implement a permanent solution. I hope it helps others.
{ "pile_set_name": "StackExchange" }
Q: Would like to read in Two columns of dates but only get One I have a text.csv file with 6 columns. I want 2 columns read in as dates for later differences. However, I only get ONE column coming back as a datetime. Any ideas? Also, I have several empty dates that return nan NOT 0(zeros) as in na_values = 0?? import pandas as pd CSV = 'text.csv' df = pd.read_csv(CSV, skiprows = 0, na_values = 0, parse_dates = ['Date of Sign Up', 'Birth Date'], usecols = ['Date of Sign Up', 'A', 'B', 'C', 'D', 'Birth Date']) df.info() # Check info for column types and nan... RangeIndex: 969 entries, 0 to 968 Data columns (total 6 columns): Date of Sign Up 969 non-null datetime64[ns] A 969 non-null object B 969 non-null object C 969 non-null object D 969 non-null object Birth Date 969 non-null object ## <== Why doesn't this column read as datetime? dtypes: datetime64[ns](1), object(5) memory usage: 45.5+ KB A: There is problem some values in Birth Date are contains at least one not parseable datetime, so read_csv silently not parse column. You can check this values by: dates = pd.to_datetime(df['Birth Date'], errors='coerce') print (df.loc[dates.isnull(), 'Birth Date']) Another solution is parse this problematic values to NaT: df['Birth Date'] = pd.to_datetime(df['Birth Date'], errors='coerce') I try test if 0 is correctly parsed to NaT: import pandas as pd temp=u"""Date,a 2017-04-03,0 2017-04-04,1 0,2 2017-04-06,3 2017-04-07,4 2017-04-08,5""" #after testing replace 'pd.compat.StringIO(temp)' to 'filename.csv' df = pd.read_csv(pd.compat.StringIO(temp), na_values = 0, parse_dates=['Date']) print (df) Date a 0 2017-04-03 NaN 1 2017-04-04 1.0 2 NaT 2.0 3 2017-04-06 3.0 4 2017-04-07 4.0 5 2017-04-08 5.0 print (df.dtypes) Date datetime64[ns] a float64 dtype: object If there is a few non parseable values: import pandas as pd temp=u"""Date,a 2017-04-03,0 string,1 0,2 2017-04-06,3 2017-04-07,4 2017-04-08,5""" #after testing replace 'pd.compat.StringIO(temp)' to 'filename.csv' df = pd.read_csv(pd.compat.StringIO(temp), na_values = [0, 'string'], parse_dates=['Date']) print (df) Date a 0 2017-04-03 NaN 1 NaT 1.0 2 NaT 2.0 3 2017-04-06 3.0 4 2017-04-07 4.0 5 2017-04-08 5.0 print (df.dtypes) Date datetime64[ns] a float64 dtype: object
{ "pile_set_name": "StackExchange" }
Q: Python decorator access argument by name I want to make a Python decorator that can take an argument (the name of an argument in the function it is decorating) and use that argument to find the value of the argument in the function. I know that sounds super confusing, ha! But what I want to do would look like this (it's for a Flask web application): This is what I have right now: @app.route('/admin/courses/<int:course_id>') def view_course(course_id): ... view code here And I want to do something like this: @app.route('/admin/courses/<int:course_id>') @access_course_permission(course_id) def view_course(course_id): ... view code here Right now I know I can do something like: def access_course_permission(f): @wraps(f) def decorated_function(*args, **kwargs): # check args[0] right here to find the course ID return f(*args, **kwargs) return decorated_function which works great as long as course_id is always the first parameter. However, it isn't. That's why I want to be able to specify the name. If this is not possible, I guess I could just pass the index of the parameter to the decorator, but that isn't very nice... A: You can use the inspect.getfullargspec() function to access the names used in a function: try: # Python 3 from inspect import getfullargspec except ImportError: # Python 2, use inspect.getargspec instead # this is the same function really, without support for annotations # and keyword-only arguments from inspect import getargspec as getfullargspec from functools import wraps def access_course_permission(argument_name): def decorator(f): argspec = getfullargspec(f) argument_index = argspec.args.index(argument_name) @wraps(f) def wrapper(*args, **kwargs): try: value = args[argument_index] except IndexError: value = kwargs[argument_name] # do something with value return f(*args, **kwargs) return wrapper return decorator The above finds out at what index your specific argument is positioned; this covers both positional and keyword arguments (because in Python, you can pass in a value for a keyword argument by position too). Note however that for your specific example, Flask will call view_course with course_id as a keyword argument, so using kwargs[argument_name] would suffice. You'll have to pass in a string to name that argument: @app.route('/admin/courses/<int:course_id>') @access_course_permission('course_id') def view_course(course_id): # ... view code here Note however, that in Flask you could just access request.view_args, without the need to parse this information out of the function arguments: course_id = requests.view_args[argument_name]
{ "pile_set_name": "StackExchange" }
Q: how to read "%" character from char array and write it to a file using fprintf_s? I have a piece of code where I need to read "%" character from a char array and write it to a file using fprintf_s; FILE *fp = <some valid file ptr>; char sBuf = " %Demo"; fprintf_s(fp, szBuf); The problem here is , fprintf_s asserts while reading % (most likely because it doesn't find a valid format specifier). Is there a way to write the "%" character to the file ? If not by tweaking the above code, it would be great to hear other options. A: Never, ever use a computed string as a format parameter to the scanf/printf family of functions. Either use: fprintf_s(fp, "%s", szBuf); ... or directly use fwrite, as you don't actually format anything here.
{ "pile_set_name": "StackExchange" }
Q: Printing list elements in order, as variables I have a list like so: >>> mylist=['a', 'b', 'c', 'd', 'e'] I want to print statement in the following format. >>> q=('%mylist% OR ' * len(mylist))[:].strip().rstrip('OR').strip() The output of q is: >>> '%mylist% OR %mylist% OR %mylist% OR %mylist% OR %mylist%' But I want really do this: '%a% OR %b% OR %c% OR %d% OR %e%' How can I have this output? I mean I want to do something like: '%mylist[0]% OR %mylist[1]% OR %mylist[2]% OR %mylist[3]% OR %mylist%[4]' A: Use list comprehension and join >>> l = ['a', 'b', 'c', 'd', 'e'] >>> ' OR '.join(['%' + i + '%' for i in l]) '%a% OR %b% OR %c% OR %d% OR %e%' >>> ' OR '.join('%' + i + '%' for i in l) '%a% OR %b% OR %c% OR %d% OR %e%'
{ "pile_set_name": "StackExchange" }