text
stringlengths
64
81.1k
meta
dict
Q: How to reference the first parameter of a Windows batch file in an IF condition? I'm very new in cmd batch files. I have code: @echo off if {%1} =="1" ( goto 1cmd ) if {%1} =="2" ( goto 2cmd ) if {%1} =="3" ( goto 3cmd ) if {%1} =="" ( echo qwerty ) :1cmd call D:\test\1\1.cmd goto end :2cmd call D:\test\2\2.cmd goto end :3cmd call D:\test\3\3.cmd goto end :end File is named a.bat. No matter what parameter I type, a.bat always calls 1.cmd. What is the reason? A: Is this working ? @ECHO OFF if "%~1" =="1" ( goto 1cmd ) if "%~1" =="2" ( goto 2cmd ) if "%~1" =="3" ( goto 3cmd ) if {%1} =="" ( echo qwerty ) exit /b 0 :1cmd call D:\test\1\1.cmd goto end :2cmd call D:\test\2\2.cmd goto end :3cmd call D:\test\3\3.cmd goto end
{ "pile_set_name": "StackExchange" }
Q: What does Arch Linux offer? I use Macs, Ubuntu, FreeBSD, OpenBSD, and Fedora for different purposes. I'm fairly busy and trying out a new distro takes a lot of time, but I hear lots of good things about Arch Linux from people I admire. I do mostly scientific computing (and some web development), and use Linux as both a desktop and a server. Does Arch offer anything I'm not already getting from one of my current installs? I'm particularly interested in the differences between Arch and Debian A: I myself have migrated to Arch some months ago, and form my experience I could give you some advices: You need a lot of free time to install it, afterwards it's just a little more than a regular distro (Fedora, Ubuntu, OpenSuse). It is fast. Since it is a rolling release you don't need to bother yourself with huge changes and huge download time. You decide in the first place what program you want to install. But you have to have a lot of time to put in it, reading configuration files, official documents, wiki and so on (although most of this is just at the installation phase). To sum it up, I think that it isn't the distro that you want to work on day to day, but for a personal use and for hobbie it is Great & Fun. A: Is there any merit in trying Arch? Of course there is. Provided you: Are prepared to read all of the excellent documentation that the community had provided; Are willing to assume complete responsibility for your system and not expect to have your hand held; Are comfortable with the (admittedly infrequent) occasions where newer packages cause issues, or even breakage, that comes with a rolling release. Whether or not there are advantages to you depends entirely on your needs and inclinations. Arch means having the the newest packages, but that comes at a cost in terms of attentiveness to your system. There is no particular "magic" to Arch (and no inherent "coolness" either); it's a distro like any other that scratches an itch... A: I have been running Slackware releases for some years. I made my development machine into an Arch box a couple of years ago. I think that Arch holds your hand a bit more than Slackware, in that pacman can detect missing packages, where installpkg doesn't. To me, it also seemed easier to have a custom kernel on Slackware than on Arch: I gave up on custom kernels and just went with the Arch rolling release kernel. I don't think Arch takes that much extra time, I would gladly have an Arch desktop (as long as I get to run pacman -Syu once a week), and I would gladly spend 100% of my time in Arch or Slackware. But my tastes in user interface differ wildly from The Norm, and I do like to have total control over compilers, configurations, etc.
{ "pile_set_name": "StackExchange" }
Q: json-schema - allow for logical-OR in required properties An alternate title for this question would be "required property combinations". Say I am working with a json-schema like so: { "$schema": "http://json-schema.org/draft-07/schema#", "title": "JSON schema for NLU (npm-link-up) library.", "type": "object", "additionalProperties": false, "required": [ "list", "packages", "deps" ], // ... } what I want to do, is make one of "list", "packages", "deps", to be required. That is one, but no more than one, should be present. So it might be something like: { "$schema": "http://json-schema.org/draft-07/schema#", "title": "JSON schema for NLU (npm-link-up) library.", "type": "object", "additionalProperties": false, "required": [ { "min": 1, "max": 1, "selection": ["list", "packages", "deps"] } ], } or { "$schema": "http://json-schema.org/draft-07/schema#", "title": "JSON schema for NLU (npm-link-up) library.", "type": "object", "additionalProperties": false, "required": [ { "operator": "or", "selection": ["list", "packages", "deps"] } ], } is this possible? A: There are four boolean combinator keywords in JSON Schema: allOf - AND anyOf - OR oneOf - XOR (eXclusive OR) not - NOT What you want can be done like this ... { "$schema": "http://json-schema.org/draft-07/schema#", "title": "JSON schema for NLU (npm-link-up) library.", "type": "object", "additionalProperties": false, "oneOf": [ { "required": ["list"] }, { "required": ["packages"] }, { "required": ["deps"] } ] }
{ "pile_set_name": "StackExchange" }
Q: Calculate pay periods based on 14 day pay period - PHP/SQL I have a database that collects user input on their time in/out. I am collecting this information like so: user_id clock_in clock_out 612 1383710400 1383728400 612 1384315200 1384333200 508 1383710400 1383738400 While looping, I calculate the hours of each object like so: $total=(($e->clock_out-$e->clock_in)/60/60); Where I am stuck I'm a bit stuck on how to group them into pay periods. I know that there are 26 pay periods in a year. I also know our starting pay period for this year was 01.13.14 - 01.26.14. What I have tried: I thought to try just gathering the week of the year date('W',$e->clock_in) while looping through the database results but I am not sure how to group them. Question: Is grouping/sorting possible while looping during a foreach? Do you suggest a different approach on grouping/sorting the data into pay periods? Please let me know if more code is needed, etc. Thank you! A: Assuming those are standard Unix timestamps, you can trivially extract/mangle dates any way you want. If your workweek corresponds to a standard calendar week, it's even easier: SELECT user_id, clock_in-clock_out FROM yourtable GROUP BY WEEK(FROM_UNIXTIME(clock_in)) This will just group by single weeks, but this is just to give you a general idea. MySQL has a very wide variety of date/time functions that can be used for this: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_week
{ "pile_set_name": "StackExchange" }
Q: What is faster in Python3? len or dictionary lookup? What is faster (Python3)? if len(interval) <= 2: return 1 or: if interval in intervaldict: return intervaldict[interval] Does in depend on the length of the string or the length of the dictionary? I did some simple test and it looks like len is more expensive, which seems counterintuitive to me. A: The len solution is marginally slower because there is more involved. You can see this by breaking down the code with dis.dis: >>> import dis >>> dct = {1:1, 2:2} >>> dis.dis('1 in dct') 1 0 LOAD_CONST 0 (1) 3 LOAD_NAME 0 (dct) 6 COMPARE_OP 6 (in) 9 RETURN_VALUE >>> dis.dis('len(dct) <= 2') 1 0 LOAD_NAME 0 (len) 3 LOAD_NAME 1 (dct) 6 CALL_FUNCTION 1 (1 positional, 0 keyword pair) 9 LOAD_CONST 0 (2) 12 COMPARE_OP 1 (<=) 15 RETURN_VALUE >>> Notice that the len solution has an extra name lookup for len as well as a function call. These each take time. But, as you can see from the timeit.timeit tests below, the performance difference is pretty insignificant: >>> import timeit >>> dct = {1:1, 2:2} >>> timeit.timeit('1 in dct', 'from __main__ import dct') 0.24376701508152573 >>> timeit.timeit('len(dct) <= 2', 'from __main__ import dct') 0.4435952055358978 >>> Also, these stats will not change depending on the dictionary's length because both len and in have O(1) (constant) complexity with dictionaries. A: See Python's Time Complexity len on a list is O(1) in all cases whereas lookup in a dictionary is amortized worst case O(n). Complexity and runtime are different. For some situation a dictionary look up will take longer, but it may happen so rarely and only for such large size dictionaries that it will not be the most performant for your uses.
{ "pile_set_name": "StackExchange" }
Q: Problems with Loading an Image for a GUI when the classes are in a package I've been programming in Java for a little while now but have never really done much with the swing packages. I am currently designing a GUI for an A.I. call and response program despite the relative complexity (for me at least) of the rest of what I have been doing, this image loading problem, which seemed extremely simple to implement is stumping me. The below classes work if not in a package, which is what really confuses me. I've tried several different implementation suggestions (one from Head First Java, one from the docs.oracle.com tutorials and another using what http://leepoint.net/notes-java/GUI-lowlevel/graphics/45imageicon.html suggests). package CaRII; import java.util.*; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class P{ public static void main(String [] args){ P p = new P(); p.go(); } public void go(){ JFrame frame = new JFrame("CaRRI: Call and Response Intelligent Improviser"); PBackground mainPanel = new PBackground(); frame.getContentPane().add(BorderLayout.CENTER, mainPanel); frame.setSize(800,500); frame.setVisible(true); } } package CaRII; import java.awt.*; import javax.swing.*; public class PBackground extends JPanel{ public Image backgroundImage; public PBackground(){ backgroundImage = Toolkit.getDefaultToolkit().createImage("CaRIIBackGround.jpg"); } public PBackground(LayoutManager layout){ backgroundImage = Toolkit.getDefaultToolkit().createImage("CaRIIBackGround.jpg"); } public void paint(Graphics g){ g.drawImage(backgroundImage,0,0,null); } } Like I said the strange thing is that it doesn't display the image if these two classes are in package CaRRI; but if I compile and run them without the package declaration they run fine(albiet the image not loading until the window resizes... but i have seen solutions online for that so I will be able to sort that once I get it loading within the package). I have been writing in XCode and JEdit and the image is stored within the package folder inside source (/src/CaRII/P.java ... /src/CaRII/CaRIIBackGround.jpg), I have also tried storing the image in a resources folder within /src/ and using ImageIcon(getClass().getResource("/resources/CaRIIBackGround.jpg)).getImage(); but that that causes another error when run Exception in thread "main" java.lang.NullPointerException at javax.swing.ImageIcon.<init>(ImageIcon.java:181) at CaRII.PBackground.<init>(PBackground.java:19) at CaRII.P.go(P.java:21) at CaRII.P.main(P.java:15) Any help would be much appreciated as despite its simplicity this has been stumping me all morning and I have a lot of other classes to write. Thanks (Heres the image(im a new user so i cant post images but this is a link to it)) http://imageshack.us/photo/my-images/189/cariibackground.jpg A: package CaRII; import java.awt.*; import java.awt.image.BufferedImage; import javax.swing.*; import java.net.URL; import javax.imageio.ImageIO; public class P{ public static void main(String [] args){ SwingUtilities.invokeLater(new Runnable() { public void run() { P p = new P(); p.go(); } }); } public void go(){ try { JFrame frame = new JFrame("CaRRI: Call and Response Intelligent Improviser"); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); PBackground mainPanel = new PBackground(); frame.getContentPane().add(BorderLayout.CENTER, mainPanel); //frame.setSize(800,500); frame.pack(); frame.setMinimumSize(frame.getSize()); frame.setLocationByPlatform(true); frame.setVisible(true); } catch(Exception e) { e.printStackTrace(); } } } class PBackground extends JPanel{ public BufferedImage backgroundImage; public PBackground() throws Exception { URL url = new URL("http://desmond.imageshack.us/Himg189/" + "scaled.php?server=189&filename=cariibackground.jpg&res=medium"); // You might form that URL using something like.. //URL url = this.getClass().getResource("/CaRIIBackGround.jpg"); backgroundImage = ImageIO.read(url); Dimension d = new Dimension( backgroundImage.getWidth(), backgroundImage.getHeight()); setPreferredSize(d); } /* What was this supposed to achieve? public PBackground(LayoutManager layout){ backgroundImage = Toolkit.getDefaultToolkit().createImage("CaRIIBackGround.jpg"); } */ // Don't override paint() in a Swing panel! //public void paint(Graphics g){ @Override public void paintComponent(Graphics g) { // USE the ImageObserver! //g.drawImage(backgroundImage,0,0,null); g.drawImage(backgroundImage,0,0,getWidth(),getHeight(),this); } }
{ "pile_set_name": "StackExchange" }
Q: Did anything significant happened in 1960s that involve neutron? I am playing with Ngram viewer and I plugged in several subatomic particles and saw this graph (see attached). The term "proton" was used starting the 1920 and neutron was discovered in 1932, which is consistent with the starting points in the graph. But neutron has a peak around the 1960s. Did anything significant happened that year about neutron? A: Google Ngrams are based on searching mentions in book hits from the corresponding time period. By looking at the titles and contexts where the word is mentioned one can usually figure out what the dominant reason for its occurence is. Here is the Ngram for neutron and here are the book hits for the 6 year range around the spikes in 1957 and 1961. Radiochemistry, chemistry of radioactive materials, and other nuclear reactor related contexts seem to dominate: "fissionable nuclides and for fast neutron fission", "Reactors for University Research", "Radiochemistry of Iron", "A Glossary of Terms in Nuclear Science and Technology", "Radiochemistry of the Transcurium Elements", "Radiochemistry of Silicon", "Radiochemistry of Osmium", "condensate from the dissolution of neutron-activated uranium metal", etc. So it seems the spikes are due to the rise of nuclear power in late 1950-s, which created the need for technological literature on how different materials behave in radioactive conditions, measurement standards, etc. All of that mentioned fission chain reactions and their neutron multiplication factors, among other things. In 1955 the "First Geneva Conference" of the UN met to discuss nuclear power, in 1957 EURATOM and the International Atomic Energy Agency (IAEA) were launched. Calder Hall, the first commercial nuclear power plant, opened in UK in 1956, the Shippingport in Pennsylvania, the first commercial one in the US, opened in 1957. The U.S. Army had a nuclear power program since 1954, its nuclear power plant at Fort Belvoir, Virginia, opened in 1957 even before Shippingport. Army's experimental nuclear reactor at the National Reactor Testing Station in Idaho had a steam explosion and meltdown, which killed its three operators, in January 1961, see History of Nuclear Power.
{ "pile_set_name": "StackExchange" }
Q: Where was Luke's Jedi Temple/Academy located? In The Force Awakens and The Last Jedi, it was mentioned that Luke Skywalker took on students and started teaching them the ways of the Force before Kylo Ren killed them all and left Luke for dead. Specifically in The Last Jedi, we see a few shots of the place where this happened. It looks like some sort of Jedi Temple. The thing is, I don't know where all this happened, and I can't find any information on it. I know in Legends, Luke rebuilt the Jedi Order on Yavin 4; is there any indication of where this training was going on in the new canon? A: There's no indications where the scenes we've only gotten bits and pieces of in TFA and TLJ actually happened. While George Lucas wanted it to be Ahch-to, it seems unlikely Luke would hide on a planet Kylo Ren knows. Furthermore, Leia would also likely have searched the ruins of the Academy for her brother. Another strike against the Ahch-to is that Ahch-to appears to have only one moon (per the Junior Novelization), while the Temple had at least 2 It's possible Episode IX will tell us definitively, but no canon sources have to date.
{ "pile_set_name": "StackExchange" }
Q: Validation : how to check if the file being uploaded is in excel format? - Apache POI Is there any way I can check if the file being uploaded is in excel format? I am using Apache POI library to read excel, and checking the uploaded file extension while reading the file. Code snippet for getting the extension String suffix = FilenameUtils.getExtension(uploadedFile.getName()); courtesy BalusC : uploading-files-with-jsf String fileExtension = FilenameUtils.getExtension(uploadedFile.getName()); if ("xls".equals(fileExtension)) { //rest of the code } I am sure, this is not the proper way of validation. Sample code for browse button <h:inputFileUpload id="file" value="#{sampleInterface.uploadedFile}" valueChangeListener="#{sampleInterface.uploadedFile}" /> Sample code for upload button <h:commandButton action="#{sampleInterface.sampleMethod}" id="upload" value="upload"/> User could change an extension of a doc or a movie file to "xls" and upload,then it would certainly throw an exception while reading the file. Just hoping somebody could throw some input my way. A: You can't check that before feeding it to POI. Just catch the exception which POI can throw during parsing. If it throws an exception then you can just show a FacesMessage to the enduser that the uploaded file is not in the supported excel format.
{ "pile_set_name": "StackExchange" }
Q: Mysql Date and Time fields and GMT offset I have a 3 fields. 1. Date (as DATE) 2. Time (as TIME) 3. GMT Offset (as TIME) I need to add the 3 fields together to retrieve a final DATETIME field in which to work with. i) How do I do that and cope with overlapping days when the GMT offset carries the date into a new day? ii) Is it more efficient to store the Date and Time as a single DATETIME field? And if so, what about the GMT offset? Keep it as a TIME field, or perhaps something else? A: My opinion is that it is better to store the first two fields as a DATATIME (MyDateTime) field. Then, it's a matter of using SELECT TIMESTAMPADD(HOUR,GMT_Offset,MyDateTime) to put it together. Of course, if you want, you could just throw it all of them into a single expression: SELECT TIMESTAMPADD(HOUR,GMT_Offset,TIMESTAMP(MyDate,MyTime)) I am assuming that MyDate and MyTime are already in GMT.
{ "pile_set_name": "StackExchange" }
Q: Java - size of compression output-byteArray When using the deflate-method of java.util.zip.Deflater, a byte[] has to be supplied as the argument, how big should that byte[] be initialized to? I've read there's no guarantee the compressed data will even be smaller that the uncompressed data. Is there a certain % of the input I should go with? Currently I make it twice as big as the input A: After calling deflate, call finished to see if it still has more to output. eg: byte[] buffer = new byte[BUFFER_SIZE]; while (!deflater.finished()) { int n = deflater.deflate(buffer); // deal with the n bytes in out here } If you just want to collect all of the bytes in-memory you can use a ByteArrayOutputStream. eg: byte[] buffer = new byte[BUFFER_SIZE]; ByteArrayOutputStream baos = new ByteArrayOutputStream(); while (!deflater.finished()) { int n = deflater.deflate(buffer); baos.write(buffer, 0, n); } return baos.toByteArray(); A: Why does Java misspell the class as "deflater"? The word is "deflator". Jeez! Sorry, had to get that off my chest. As noted, the expected use is to keep calling deflate until you get all of the output from the compression. However, if you really want to do it in a single call, then there is a bound on the amount by which deflate can expand the data. There is a function in zlib that Java unfortunately does not make available called deflateBound() which provides that upper bound. You can just use the conservative bound from that function, with the relevant line copied here: complen = sourceLen + ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5;
{ "pile_set_name": "StackExchange" }
Q: How to find the perfect matching? If $G(A,B,E)$ is a simple , connected bipartite graph with $n$ vertices in both of its vertex classes, and if we let the degrees in one class be different. How can we show that $G$ contains a perfect matching? What I know from this information: That $G$ has no loops so we can apply the first Gallai theorem : $\alpha + \tau = 2n$ (applied to this case). Also, since it is a bipartite we can use Konig's theorem : $\nu = \tau$ and $\alpha = \rho$ . And if I am right the question basically asks either to show that $\nu = n$ or I need to show that $|A| = |B|$ and prove Hall's theorem for this $G$. Now, my main question here is how can I apply Hall's theorem here to show that this graph $G(A,B,E)$ contains a matching covering $A$ or $B$? I am not sure how can I show that $\forall x \subsetneq A :|N(x)| \leq |x|$ here.(Hall's theorem; $N$ refers to the neighborhood) Any hint is greatly appreciated. A: I suppose you can procede inductively. Since all vertices say in $A$ have different degrees and it is connected, then we have in $A$ vertex $v$ with degree $1$. Say it is connected with $u$ in $B$. Now repeat everything in $A'=A\setminus \{v\}$ (and $B'=B\setminus\{u\}$). You can see that vertices in $A'$ have again different degrees ($u$ was connected to all vertices in $A$, othervise $G$ would not be connected graph).
{ "pile_set_name": "StackExchange" }
Q: What's the number of poker hands where one of the cards is Ace of clubs and none of the other cards can be Aces or clubs There are $5$ cards in a poker hand. Fix one of them to be Ace of clubs. Then there are $12$ ranks and $3$ suits left. First we choose $4$ ranks out $12.$ Then we choose $1$ suit out of $3$ for each chosen rank, like so: $\binom{12}4 \binom31^4$ but this doesn't agree with the given answer. What might have gone wrong? A: Once you have chosen the ace of clubs, you only need to worry about picking the other 4 cards. There are $12$ other cards that are clubs in the deck which you cannot pick, and $3$ aces that are also off limits, so from $51$ cards ($52$ originally minus the ace you took) you can only pick $51-15=36$, now just pick the remaining four cards out of this bunch $$\binom {36}{4}$$
{ "pile_set_name": "StackExchange" }
Q: Does the US Fifth Amendment only apply to criminal trials? Do any laws protect a person in civil court when testimony would implicate them in a crime? Suppose someone is accused of burglary. This person is asked to appear in civil court regarding an unrelated event that occurred at the same time as the burglary but in a different location. If the person is pleading the fifth in the criminal proceedings (or plans to), can this person decline to answer questions in the civil court about their whereabouts during the events? Can they answer questions selectively? Does their role in the civil proceedings (witness, defendant, etc.) affect the answer? A: The Fifth Amendment always protects someone from being forced to testify against themselves if it would implicate them in a crime (see, among others, Ohio v. Reiner, 532 U.S. 17). Any person can assert the privilege, regardless of their role in the trial, with the possible exception of the plaintiff (who is the one person who wanted to go to court). Like always with the Fifth Amendment, they can answer some questions but not others (but if they do answer a question, they need to fully answer it). In civil cases, the Fifth Amendment itself does not keep the jury from making adverse inferences against whoever invoked the privilege; if you refuse to testify, they can assume that it's because testifying would be extremely damaging in that particular case. However, most states have rules against that, and so invoking the privilege in state courts generally works like it does in a criminal case (where the jury basically ignores that the question was even asked). In federal courts, if a case is being heard under diversity jurisdiction (plaintiff and defendant are from different states but the claim is not a federal claim) the state rule is supposed to apply; if the claim is a federal claim, the federal rule applies and adverse inferences are allowed. While the Fifth Amendment can be invoked by anyone, there may be consequences. In many states (where adverse inference isn't allowed), a witness who will just invoke the Fifth and answer no questions can't be called, because it's a complete waste of time. If the plaintiff invokes the Fifth to not answer key questions, then the court can potentially dismiss the case; they have the right to assert the privilege, but their lawsuit might suffer for it. In federal court, another possibility that's been done several times before is that the civil case is just put on hold until the criminal matter is resolved. Sources: “The Fifth Amendment Can & Will Be Used Against You In a (Federal) Court of Law” Taking the 5th: How to pierce the testimonial shield Plaintiff as Deponent: Invoking the Fifth Amendment
{ "pile_set_name": "StackExchange" }
Q: Run-Time error on add method VBA My function's intent is explained in the docstring. However, when I run it, I get a "Run-Time error '91': Object variable or With block variable not set", and a line of code is highlighted, as indicated below. I cannot find the source of this issue, especially since I am rather new to VBA. Any help would be greatly appreciated! '==============================|Range_Collection FUNCTION|==============================' ' Given a collection and a range, add each value in that range to the collection, except ' for False values. Function Range_Collection(col As Collection, rng As Range) As Collection Dim Val As Variant For Each Val In rng If Not Val.Value = False Then col.Add Val.Value ;************** THIS CODE IS HIGHLIGHTED************ End If Next Val Set Range_Collection = col End Function A: Let's say your worksheet looks like this This is what I get when I run the code Further to my comment, see this The syntax is col.add "Item","Key". The key has to be unique. If you have duplicate values then then use OERN as I suggested or use a unique key. Sub Sample() Dim c As New Collection For Each itm In Range_Collection(c, Range("A1:A5")) Debug.Print itm Next End Sub Function Range_Collection(col As Collection, rng As Range) As Collection Dim rVal As Variant For Each rVal In rng If Not rVal.Value = False Then On Error Resume Next col.Add rVal.Value, CStr(rVal.Value) On Error GoTo 0 End If Next rVal Set Range_Collection = col End Function
{ "pile_set_name": "StackExchange" }
Q: Performance of an ordered list in Firebase If I want to maintain an ordered list in Firebase, it seems like the best way to do it is to manually assign a priority to each item in my list. That means if I insert or remove an item from the list, I have to update the priorities of all the items following it. For an item at the beginning of the list, this means updating every item in the list. Is there a better performing data structure or algorithm to use in this case? A: You can create an ordered list by setting the priority of elements appropriately. Items in a list are ordered lexigraphically by priority, or if the priority can be parsed to a number, by numeric value. If you want to insert items into the middle of an existing list, modifying the priorities of the existing items would work, but would be horribly inefficient. A better approach is just to pick a priority between the two items where you want to insert the value and set that priority for the new item. For example, if you had element 1 with priority "a", and element 2 with priority "b", you could insert element 3 between the two with priority "aa" (or "aq", "az", etc). In our experience, most times when you create an ordered list, you don't necessarily know the position in the list you want to insert the item beforehand. For example, if you're creating a Leader Board for a game, you don't know in advance that you want to place a new score 3rd in the list, rather you know you want to insert it at whatever position score 10000 gets you (which might happen to be third). In this case, simply setting the priority to the score will accomplish this. See our Leader Board example here: https://www.firebase.com/tutorial/#example-leaderboard
{ "pile_set_name": "StackExchange" }
Q: Does Congress not have to approve the US withdrawal from the Iran deal? How is Trump able to withdraw from the Iran deal without Congressional approval? A: From Wikipedia: Under U.S. law, the JCPOA is a non-binding political commitment. According to the U.S. State Department, it specifically is not an executive agreement or a treaty. There are widespread incorrect reports that it is an executive agreement. In contrast to treaties, which require two-thirds of the Senate to consent to ratification, political commitments require no congressional approval, and are not legally binding as a matter of domestic law (although in some cases they may be binding on the U.S. as a matter of international law). It was not approved by Congress in general (as laws must be) nor approved by the Senate (as treaties must be). Barack Obama signed it on his own authority as president. Donald Trump withdrew from it under his authority as president, since he replaced Barack Obama. Congress did pass provisions requiring that the president review the deal and certify that it was working. Obama did this regularly. At the beginning of his administration Trump also did these certifications, apparently on the advice of Secretary of State Rex Tillerson. He stopped certifying this October 13th, 2017. Anyway, these provisions restricted the president's acceptance of the deal, not withdrawal. Presumably Obama thought that he was going to be replaced by a president who would choose to stay in the deal. So he wasn't so worried about forcing that. In addition, it's not clear that he had sufficient congressional support to make a more permanent deal, either by treaty or by passing a law removing the sanctions.
{ "pile_set_name": "StackExchange" }
Q: mw wp form datepicker のjs引数の書き方を教えてください wordpressのプラグイン「mw wp form」の日付(datepicker)で、期間を指定したいのですが、うまく反映されません。 例えば、本日〜2017年7月20日までしか選択出来ないようにする場合、 [mwform_datepicker name="" size="" js='"minDate": "0","maxDate": "new Date( 2017, 7, 20 )"'] のように、jsの引数の部分を "minDate": "0","maxDate": "new Date( 2017, 7, 20 )" と記述しました。 minDateの方はちゃんと本日以前は選択出来ないようになったのですが、maxDateは指定出来ていないようで、7月20日以降も選択できてしまいます。 どなたかご教授お願いします。 A: JavaScript では、 "new Date( 2017, 7, 20 )" のようにダブルクォーテーションで囲うと、文字列になります。 Date オブジェクトを生成する場合は、クォートせずに Date コンストラクタを呼び出します。 new Date( 2017, 7, 20 )
{ "pile_set_name": "StackExchange" }
Q: Ruby: For a 2D array,why are nested while loops overwriting elements defined previously? Context: Im trying to populate a 2D array with while loops ,after witch I want to try and do it with {} block format. The point is to understand how these two syntax structures can do the same thing. I have been reviewing this code and scouring the internet for the past hour and Ive decided that I'm simply not getting something, but I dont understand what that is. The outcome should be => [["A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8"] => ..(Sequentially).. =>["H1", "H2", "H3", "H4", "H5", "H6", "H7", "H8"]] The code is as follows: char= ('A'..'H').to_a num= (1..8).to_a arr=Array.new(8,Array.new(8)) x=0 while x <8 y=0 while y < 8 arr[x][y] = char[x] + num[y].to_s y+=1 end x+=1 end arr Thank you in advance, I appreciate your patience and time. ####Edit#### The source of the confusion was due to a lack of understanding of the reference concept. Referencing allows us, by using the Array.new(n,Array.new(n)) method scheme, to access the values of the nested arrays that share a reference to their data via their parent array. This question is addressed directly here: Creating matrix with `Array.new(n, Array.new)` . Although I thought it was a issue with my while loops, the problem was indeed how I created the matrix. A: Your code is not working due to call to reference. Ruby is pass-by-value, but all the values are references. https://stackoverflow.com/a/1872159/3759158 Have a look at the output 2.4.3 :087 > arr = Array.new(8,Array.new(8)) => [[nil, nil, nil, nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil, nil, nil, nil]] 2.4.3 :088 > arr[0][0] = 'B' => "B" 2.4.3 :089 > arr => [["B", nil, nil, nil, nil, nil, nil, nil], ["B", nil, nil, nil, nil, nil, nil, nil], ["B", nil, nil, nil, nil, nil, nil, nil], ["B", nil, nil, nil, nil, nil, nil, nil], ["B", nil, nil, nil, nil, nil, nil, nil], ["B", nil, nil, nil, nil, nil, nil, nil], ["B", nil, nil, nil, nil, nil, nil, nil], ["B", nil, nil, nil, nil, nil, nil, nil]] This is happen because of call by object on array object you can see this in effect by a simple example a = [] b = a b << 10 puts a => [10] and very same thing is happening with your code. Instead of all that try this : ('A'..'H').map{|alph| (1..8).map{|num| "#{alph}#{num}"}}
{ "pile_set_name": "StackExchange" }
Q: Information required on TDataSetProvider in Delphi I have Midas project that uses a TDataSetProvider in one of RemoteDataModules in the Server Currently I am making use of the following events BeforeApplyUpdates - to create an Object BeforeUpdateRecord - to use the object AfterApplyUpdates - to destory the object Question: Will ‘ AfterApplyUpdates’ always be called even if the is an update error ? A: If you look at the sourcecode: function TCustomProvider.DoApplyUpdates(const Delta: OleVariant; MaxErrors: Integer; out ErrorCount: Integer; var OwnerData: OleVariant): OleVariant; begin SetActiveUpdateException(nil); try try if Assigned(FOnValidate) then FOnValidate(Delta); DoBeforeApplyUpdates(OwnerData); Self.OwnerData := OwnerData; try Result := InternalApplyUpdates(Delta, MaxErrors, ErrorCount); finally OwnerData := Self.OwnerData; Self.OwnerData := unassigned; end; except on E: Exception do begin SetActiveUpdateException(E); raise; end; end; finally try DoAfterApplyUpdates(OwnerData); finally SetActiveUpdateException(nil); end; end; end; Yoy see that DoAfterApplyUpdates is called in the finally block. This means it is always called regardles of any exception.
{ "pile_set_name": "StackExchange" }
Q: With FileStreamResult, how is the MemoryStream closed? The following code works, but I'm wondering if the MemoryStream created is closed properly. How should this be performed or does FileStreamResult handle it for me? public FileStreamResult DownloadBudgetedRoleOpportunities( Guid projectGuid, IEnumerable<Guid> guidRequiredRoles) { var rolebroker = new ProjectRoleBudgetBroker(); var memstream = rolebroker.CreateBudgetedRoleOpportunies( projectGuid, guidRequiredRoles); var fsr = new FileStreamResult ( memstream, "application/csv" ) { FileDownloadName = "RoleOpportunities.csv" }; // memstream.Close(); throws exception return fsr; } A: The FileStreamResult will do that for you. When in doubt always check the code, because the code never lies and since ASP.NET MVC is open source it's even more easy to view the code. A quick search on Google for FileStreamResult.cs lets you verify that in the WriteFile method the stream is correctly disposed using the using statement. (no pun intended) protected override void WriteFile(HttpResponseBase response) { // grab chunks of data and write to the output stream Stream outputStream = response.OutputStream; using (FileStream) { byte[] buffer = new byte[_bufferSize]; while (true) { int bytesRead = FileStream.Read(buffer, 0, _bufferSize); if (bytesRead == 0) { // no more data break; } outputStream.Write(buffer, 0, bytesRead); } } } A: You have access to source code, so you can check yourself ;-) protected override void WriteFile(HttpResponseBase response) { Stream outputStream = response.OutputStream; using (this.FileStream) { byte[] buffer = new byte[4096]; while (true) { int count = this.FileStream.Read(buffer, 0, 4096); if (count != 0) outputStream.Write(buffer, 0, count); else break; } } }
{ "pile_set_name": "StackExchange" }
Q: python pandas variable assignment I have an issue with python pandas variable assignment: I have a tuple like asd=('prostate1.csv','dtime','status1','age','hg','sz','sg','pf','rx') reading the file is just fine: prostate_dataset=pd.read_csv(asd[0]) but trimming the dataset doesn't work seamlessly: prostate_dataset=prostate_dataset[[for x in asd[1:]]] what I want to get is like this: prostate_dataset=prostate_dataset[[asd[1],asd[2],asd[3],asd[4],asd[5],asd[6],asd[7],asd[8]]] I've tried: act='\',\''.join(asd[1:]) prostate_dataset=prostate_dataset[[act]] but it didn't work because the back slash sign still included Thanks in advance A: Turn it into a list to filter your df: prostate_dataset=prostate_dataset[list(asd[1:])] should work: In [157]: asd=('prostate1.csv','dtime','status1','age','hg','sz','sg','pf','rx') list(asd[1:]) Out[157]: ['dtime', 'status1', 'age', 'hg', 'sz', 'sg', 'pf', 'rx'] The thing to understand here is that your slicing on the tuple will return the tuple with the values in the slice range but to index the df you should pass a list of the column names that you are interested in.
{ "pile_set_name": "StackExchange" }
Q: How to pass json array and its object and keys of object in flutter.? [enter image description here][1]I want to parse json Array and its object and keys in object of array.? how can i parse.? http.Response response=await http.get("api url"); List resJson=json.decode(response.body); Map decode=jsonDecode(response.body); List<Task> task =new List<Task>(); for(var task in decode['rows']){ print(task['Task']); } i want to parse this array.. "rows":[ { "Task" { "title":"aamir" },"Category Type":{ id:"123" } { "number":3, "word":"SES" } ] } A: The JSON you have added isn't valid If this is the JSON you want to parse - { "rows": [{ "Task": { "title": "aamir" }, "Category Type": { "id": "123" } }] } You can parse it like this - for(int i = 0 ; i < rows.length ; i++) { var task = rows[i]["Task"]; String title = task["title"]; String id = rows[i]["Category Type"]["id"];
{ "pile_set_name": "StackExchange" }
Q: Encrypted PDF won't write to disk I have some code that is encrypting a pdf, and for some reason as soon as I encrypt the pdf, the writing hangs. If I comment out pdf_writer.encrypt(password) there is no problem and things are written properly. I've tried running the script with the highest privileges and modifying the folder options, but maybe I'm missing something simple. with open(filename, 'rb') as pdf_file: pdf_reader = PyPDF2.PdfFileReader(pdf_file) pdf_writer = PyPDF2.PdfFileWriter() for page_number in range(pdf_reader.numPages): pdf_writer.addPage(pdf_reader.getPage(page_number)) pdf_writer.encrypt(password) filename_encrypted = filename.parents[0] / f "{filename.stem}_encrypted.pdf" with open(filename_encrypted, 'wb') as pdf_file_encrypted: pdf_writer.write(pdf_file_encrypted) Any help would be greatly appreciated. A: I couldn't figure out why things weren't working with PyPDF2, so I just tried another module called pikepdf and things worked just fine. This actually seems like a much better module than PyPDF2 anyway. import pikepdf filename = pathlib.Path(r"path\to\pdf\test.pdf") password = 'password' with Pdf.open(filename) as pdf: filename_encrypted = filename.parents[0] / f"{filename.stem}_encrypted.pdf" pdf.save(filename_encrypted, encryption=Encryption(user=password, owner=password))
{ "pile_set_name": "StackExchange" }
Q: OPEN GL Android - How to convert a Bitmap object to a drawable texture I'm trying to implement a Grid of scrollable images in OPEN GL 2.0. I already have the view implemented using Canvas Drawing, but for performance reasons I decided to transition to OGL. In my implementation, at each frame I draw a list of Bitmap objects, each Bitmap is a cached row of image thumbnails. Now how do I go about converting those Bitmaps to textures I can use with OGL? A: GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureID); GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0); ..where textureID is the unique ID for the texture (usually aquired from glGenTextures(), or otherwise from just keeping your own system of assigning each new texture a new ID number). bitmap is the Bitmap object. An example of useage in my texture class: public class Texture { protected String name; protected int textureID = -1; protected String filename; public Texture(String filename){ this.filename = filename; } public void loadTexture(GL10 gl, Context context){ String[] filenamesplit = filename.split("\\."); name = filenamesplit[filenamesplit.length-2]; int[] textures = new int[1]; //Generate one texture pointer... //GLES20.glGenTextures(1, textures, 0); // texturecount is just a public int in MyActivity extends Activity // I use this because I have issues with glGenTextures() not working textures[0] = ((MyActivity)context).texturecount; ((MyActivity)context).texturecount++; GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textures[0]); //Create Nearest Filtered Texture GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST); GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR); //Different possible texture parameters, e.g. GLES20.GL_CLAMP_TO_EDGE GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_REPEAT); GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_REPEAT); Bitmap bitmap = FileUtil.openBitmap(name, context); GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0); bitmap.recycle(); textureID = textures[0]; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getTextureID() { return textureID; } public void setTextureID(int textureID) { this.textureID = textureID; } }
{ "pile_set_name": "StackExchange" }
Q: How can I concatenate two counters (custom) I have two counters with me, so let's suppose for simplicity: a = "this" : 2 , "is" : 3 b = "what" : 3 , "is" : 2 Now I want to concatenate the two counters like this: concatenatedCounter = "this" : 2 , "is" : 3,2 , "what" : 3 Is there any way of doing it in Python? Edit 1 : Solved the first issue, below is the new issue, please help :) In the above result if I want the defaultdict to contain { 'this' : [2,0],'is':[3,2],'what' : [0,3]}), what changs would I need to make? A: use collections.defaultdict: In [38]: a = {"this" : 2 , "is" : 3} In [39]: b = {"what" : 3 , "is" : 2} In [40]: from collections import defaultdict In [41]: collected_counter=defaultdict(list) In [42]: for key,val in a.items(): collected_counter[key].append(val) ....: In [43]: for key,val in b.items(): collected_counter[key].append(val) ....: In [44]: collected_counter Out[44]: defaultdict(<type 'list'>, {'this': [2], 'is': [3, 2], 'what': [3]}) Update: >>> keys=a.viewkeys() | b.viewkeys() >>> collected_counter=defaultdict(list) >>> for key in keys:     collected_counter[key].append( a.get(key,0) ) ...      >>> for key in keys:     collected_counter[key].append( b.get(key,0) ) ...      >>> collected_counter defaultdict(<type 'list'>, {'this': [2, 0], 'is': [3, 2], 'what': [0, 3]})
{ "pile_set_name": "StackExchange" }
Q: Get the difference between to dates in minutes with Date-FNS - NaN Error I'm using the Date-FNS library to get the difference between to dates in minutes. Why does minutesDifference return NaN? My goal is to get number of minutes between the given dates. Here is the link to the Date-FNS doc. getDateTime: function () { var now = new Date() var year = now.getFullYear() var month = now.getMonth() var day = now.getDate() var hour = now.getHours() var minute = now.getMinutes() var dateTime = year + ', ' + month + ', ' + day + ', ' + hour + ', ' + minute + ', 0' var minutesDifference = differenceInMinutes(new Date(2018, 2, 30, 22, 55, 0), new Date(dateTime)) return minutesDifference }, A: Your value of dateTime is a string which is incorrect, you are passing 1 single param and not 6 different params to Date(). Just do differenceInMinutes(new Date(2018, 2, 30, 22, 55, 0), new Date()) new Date will take the current date/timestamp by default so you dont need to pass any params to it. Please refer the docs: Date - JavaScript | MDN
{ "pile_set_name": "StackExchange" }
Q: how to resolve this emulator: ERROR: unknown skin name 'WVGA800' solution i am trying to start the android emulator from eclipse classic (juno) and it keeps giving me this error: ERROR: unknown skin name 'WVGA800' I developed my software using eclipse indigo, but since I installed eclipse juno and imported the same project it started to give me this error. any idea why? and how to resolve this issue? A: My solution was to create a new custom virtual device from the android virtual device manager and use that. A: For me on Mac OS X this error went away when I selected the skin in advanced setting it was saying is unknown. A: I had the problem and fixed it... Here the main idea of the issue is that the emulator can't find your android-sdk base directory.. so what is the fix? here I will explain.. Find where you have installed your sdk. To do so go to Start->All Programs->Android SDK Tools->SDK Manager.. You will see that the path is written on the top of the window.. copy it somewhere so we need it later.. call it "SDK Path" Go to Start and Right Click on Computer and select "Properties".. Then select the last option on the left menu which is "Advanced System Settings".. Go to the "Advanced" tab and click on the "Environment Variables.." on the first list see if there is a variable called "ANDROID_SDK_ROOT".. If it's there then check if the value is the same as the "SDK Path" we copied in the step 1.. if they are not the same then change the value of it to the SDK Path...and check if your problem is solved. if not then go to step 3.. If the "ANDROID_SDK_ROOT" matches the SDK Path or your problem didn't solve in step 2 then the problem is probably caused by your username.. This was my actual problem. my username had special characters in it like ( !,@,#,... ) or even spaces in some times. Speaking technically as I am myself a programmer, when the emulator program was trying to open the path, it was giving out an error because it couldn't open it because of the special characters..Guessing that the SDK is installed in your Local App Data folder ( Users\\AppData\Local ) as mine was, you should access it with another Enviroment Variable called "LOCALAPPDATA" which links to your Local App Data folder.. So in your SDK Path change the "drive:\Users\\AppData\Local" to "%localappdata" and your problem will be solved .. For example mine was "C:\Users\MiNuS !3\AppData\Local\Android\android-sdk" and I changed it to "%localappdata%\Android\android-sdk"... (without the double quotations).. The same problem is present in some other java programs. I had the problem with the Zend Studio too... Hope it will solve your problem, Good Luck
{ "pile_set_name": "StackExchange" }
Q: XSLT: How to preserve whitespace between elements? I have a new requirement to make transformed XML a bit more readable, ie preserving the cr, tabs and other white space between elements. I can't seem to figure out how to preserve the whitespace. Can someone please help ? XML File <?xml version="1.0" encoding="utf-8"?> <Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"> <Fragment> </Fragment> </Wix> XSL File: <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:m="http://schemas.microsoft.com/wix/2006/wi"> <xsl:preserve-space elements="*" /> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:template match="/m:Wix"> <xsl:message>Matched Wix</xsl:message> <xsl:copy> <!-- Insert the new include processing instruction --> <xsl:processing-instruction name="include"> <xsl:text>$(sys.CURRENTDIR)src/includes/globals.wxi </xsl:text> </xsl:processing-instruction> <!-- place the existing children into the output --> <xsl:apply-templates select="@* | *"/> </xsl:copy> </xsl:template> </xsl:stylesheet> Current Output: <?xml version="1.0" encoding="UTF-8"?><Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"><?include $(sys.CURRENTDIR)src/includes\globals.wxi ?><Fragment> </Fragment></Wix> Desired Output: <?xml version="1.0" encoding="UTF-8"?> <Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"> <?include $(sys.CURRENTDIR)src/includes\globals.wxi ?> <Fragment> </Fragment> </Wix> A: There are three whitespace text nodes in your input: the two that are siblings of the Fragment element, and the one that is a child of the Fragment element. The first two are not copied to your output because your template for the m:Wix element ignores them: it does <xsl:apply-templates select="@* | *"/> which only selects element children, not text node children. The whitespace text content of Fragment is processed, and is retained in your output. Now: you say two things in your question: (a) you want to make the output readable, and (b) you want to preserve the whitespace present in the input. I would suggest that (b) is not the best way of achieving (a). The best way of achieving (a) is to ignore the whitespace present in the input, and use xsl:output indent="yes" to add new whitespace in the output. However, if you do want to copy the whitespace from the input to the output, you need to use select="node()" rather than select="*" when processing the children of an element.
{ "pile_set_name": "StackExchange" }
Q: How do I invoke an extension method using reflection? I appreciate that similar questions have been asked before, but I am struggling to invoke the Linq Where method in the following code. I am looking to use reflection to dynamically call this method and also dynamically build the delegate (or lambda) used in the Where clause. This is a short code sample that, once working, will help to form part of an interpreted DSL that I am building. Cheers. public static void CallWhereMethod() { List<MyObject> myObjects = new List<MyObject>(){new MyObject{Name="Jon Simpson"}}; System.Delegate NameEquals = BuildEqFuncFor<MyObject>("Name", "Jon Simpson"); object[] atts = new object[1] ; atts[0] = NameEquals; var ret = typeof(List<MyObject>).InvokeMember("Where", BindingFlags.InvokeMethod, null, InstanceList,atts); } public static Func<T, bool> BuildEqFuncFor<T>(string prop, object val) { return t => t.GetType().InvokeMember(prop,BindingFlags.GetProperty, null,t,null) == val; } A: As others said, extensions methods are compiler magic, you can alway use VS right click, go to definition to find the real type that implements the static method. From there, it gets fairly hairy. Where is overloaded, so you need to find the actual definition that matches the signature you want. GetMethod has some limitations with generic types so you have to find the actual one using a search. Once you find the method, you must make the MethodInfo specific using the MakeGenericMethod call. Here is a full working sample: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; namespace ConsoleApplication9 { class Program { class MyObject { public string Name { get; set; } } public static void CallWhereMethod() { List<MyObject> myObjects = new List<MyObject>() { new MyObject { Name = "Jon Simpson" }, new MyObject { Name = "Jeff Atwood" } }; Func<MyObject, bool> NameEquals = BuildEqFuncFor<MyObject>("Name", "Jon Simpson"); // The Where method lives on the Enumerable type in System.Linq var whereMethods = typeof(System.Linq.Enumerable) .GetMethods(BindingFlags.Static | BindingFlags.Public) .Where(mi => mi.Name == "Where"); Console.WriteLine(whereMethods.Count()); // 2 (There are 2 methods that are called Where) MethodInfo whereMethod = null; foreach (var methodInfo in whereMethods) { var paramType = methodInfo.GetParameters()[1].ParameterType; if (paramType.GetGenericArguments().Count() == 2) { // we are looking for Func<TSource, bool>, the other has 3 whereMethod = methodInfo; } } // we need to specialize it whereMethod = whereMethod.MakeGenericMethod(typeof(MyObject)); var ret = whereMethod.Invoke(myObjects, new object[] { myObjects, NameEquals }) as IEnumerable<MyObject>; foreach (var item in ret) { Console.WriteLine(item.Name); } // outputs "Jon Simpson" } public static Func<T, bool> BuildEqFuncFor<T>(string prop, object val) { return t => t.GetType().InvokeMember(prop, BindingFlags.GetProperty, null, t, null) == val; } static void Main(string[] args) { CallWhereMethod(); Console.ReadKey(); } } } A: Extension methods are really just static methods underwater. An extension method call like foo.Frob(arguments) is really just SomeClass.Frob(foo, arguments). In the case of the Where method, you're looking for System.Linq.Enumerable.Where. So get the typeof Enumerable and invoke Where on that.
{ "pile_set_name": "StackExchange" }
Q: How do I trigger a collider on a child game object from the parent game object? I have an enemy, which has a rag doll component. It has a few child object,s and each child has its own collider. I don't want to add a script for every child, as the OnCollisionEnter method will be the same. How can I do I trigger OnCollisionEnter with just one script, from the parent game object? A: If you want to set the object up just by placing one script, and have all the logic contained in that one script, you can create a class that forwards the collision event to the parent object with gameObject.sendMessage(), or even just a reference to a public method of your parent object's script. Instead of manually adding this class to the limbs of your ragdoll, you can use gameObject.AddComponent() to add the class dynamically. Using gameObject.GetComponentsInChildren() will get you an array of all child objects that can get collisions, that you can then iterate over to add the forwarding script.
{ "pile_set_name": "StackExchange" }
Q: Multiple versions of AngularJS in one page What issues might I experience in having two different versions of AngularJS loaded into one page? Obviously this seems like a stupid thing to do, but my use case is a page that uses AngularJS incorporating a third-party component that drags in its preferred version of AngularJS. Update: Found some info: https://groups.google.com/forum/#!msg/angular/G8xPyD1F8d0/u1QNDNvcwW4J https://github.com/angular/angular.js/pull/1535 A: Angular is really not prepared to co-exist with other version. But it's feasible. First of all load angular library and make sure that before loading window.angular is empty: <script src="vendor/angular/1.2.0/angular.min.js"></script> <script src="app/app2.js"></script> <script> var angular2 = angular; window.angular = null; // here we're cleaning angular reference </script> <script src="vendor/angular/1.0.5/angular.js"></script> <script src="app/app1.js"></script> <script> var angular1 = angular; </script> Note that each application (app1.js, app2.js) for each version of angular should be loaded immediately after loading angular library. Each JavaScript file of the application shoud be wrapped in self executing function (function(angular) { ... })(angular). Look at the example of app2.js: (function(angular) { angular.module('myApp2', []). controller('App2Ctrl', function($scope) { $scope.$watchCollection('[a, b, c]', function() { console.log(angular.version.full); }); }); })(angular); Note that here I'm using $watchCollection which is only available for angular 1.2.x. By providing scope of anonymous function for each file you are forcing application to reach angular property instead of window.angular property. Finally you have to bootstrap the application using manuall method: <body> <div id="myApp1" ng-controller="App1Ctrl"> </div> <div id="myApp2" ng-controller="App2Ctrl"> </div> <script> angular1.bootstrap(document.getElementById('myApp1'), ['myApp1']); angular2.bootstrap(document.getElementById('myApp2'), ['myApp2']); </script> </body> Working plunker here. After running please check console window to see logged versions of angular used. A: Great question! Like you, we were unable to uncover much on this topic...we are in the process of deploying a version of Angular with our product which will be embedded within client websites that could also have Angular already loaded. Here is what we have done: Modify the Angular source - do not use "window.angular" or "angular" in your implementation, choose some other variable or object property to house it. If you do use "window.angular" and/or "angular", it could break both applications if the versions are different. Rename all delivered objects (directives, etc); otherwise, the other version of angular could attempt to process your directives. Rename all CSS classes used by Angular (ng-cloak, etc). This will allow you to style your version of Angular separately from the other version. Manually bootstrap your application, as described by 'kseb' above. If you are going to completely name space AngularJS as I have described here, take care to not do a global search and replace because angular does need a "window" reference for registering events, and a few other places. I just finished doing this at work and I am in the process of testing. I will update this answer with my results.
{ "pile_set_name": "StackExchange" }
Q: Windows Printer via Samba - browse not available Recently installed Kubuntu 12.10 on a Dell XPS system. Overall happy, but I cannot access my Windows printers. Samba is correctly installed and works for browsing and accessing Windows directories on the MSHOME workgroup. When trying to add my existing (and working) printers to Kubuntu, I select the "Windows Printer via SAMBA" option and the "browse" box on the right is not available (gray). When entering the printer name directly, as soon as I have entered "smb://MSHOME/x", "x" being just about anything, the "next" button at the bottom is available and enables me to select a printer. which of course will not work! (no correct Windows server or printer is selected). I tried just about all options, including providing proper authentication data but nothing seems to enable the "browse" box to become active. Sounds to me like a bug in the add printer feature, no? Note: Entering the exact path to the printer enables to select, enable and print, but it may not be easy in a larger network environment. Thanks, -Patrick A: got the very same problem here with both kubuntu 12.10 and mint 14 KDE I found a (quite improvised) way to tweak it by installing system-config-printer-gnome (just go to Muon package manager and search for it) then running "system-config-printer" from the terminal: you'll have network printer browsing just as you have in ubuntu... after installing it from here you'll find your network printer perfectly installed when checking back to system config>printers by the way, when you're done with installation you can remove the system-config-printer-gnome package without affecting your new settings (that's because it's just a tool to work on CUPS in a simple graphic way) hope it could help
{ "pile_set_name": "StackExchange" }
Q: I can't update a specific slide and I get a "Powerpoint content error" I have a excel sheet with one chart which is the source. My target is a powerpoint presentation with 3 slides. I need to update slide #3 with the Chart in the excel file. After executing the application and when I try to open the pptx file I get a "Powerpoint found a problem with content". After I repair I notice that I always get a blank slide in Slide #2 which shows I am not updating the correct slide. What should I do to go to the slide based on slide no. (I don't have chart titles in the powerpoint slide and the excel chart) and why am I getting a invalid content error. I Would greatly appreciate your help. Thanks using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using OpenXmlPkg = DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Presentation; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Spreadsheet; namespace ExportChart { class Program { static void Main(string[] args) { string SourceFile = "Projected Sales.xlsx"; string TargetFile = "Projected Sales.pptx"; string targetppt = "Generatedppt.pptx"; ChartPart chartPart; ChartPart newChartPart; SlidePart slidepartbkMark = null; string chartPartIdBookMark = null; File.Copy(TargetFile, targetppt, true); //Powerpoint document using (OpenXmlPkg.PresentationDocument pptPackage = OpenXmlPkg.PresentationDocument.Open(targetppt, true)) { OpenXmlPkg.PresentationPart presentationPart = pptPackage.PresentationPart; var secondSlidePart = pptPackage.PresentationPart.SlideParts.Skip(1).Take(1); foreach (var slidepart in pptPackage.PresentationPart.SlideParts) { slidepartbkMark = slidepart; if (slidepart.GetPartsCountOfType<ChartPart>() != 0) { chartPart = slidepart.ChartParts.First(); chartPartIdBookMark = slidepart.GetIdOfPart(chartPart); slidepart.DeletePart(chartPart); slidepart.Slide.Save(); } //return; } newChartPart = slidepartbkMark.AddNewPart<ChartPart>(chartPartIdBookMark); ChartPart saveXlsChart = null; using (SpreadsheetDocument xlsDocument = SpreadsheetDocument.Open(SourceFile.ToString(), true)) { WorkbookPart xlsbookpart = xlsDocument.WorkbookPart; foreach (var worksheetPart in xlsDocument.WorkbookPart.WorksheetParts) { if (worksheetPart.DrawingsPart != null) if (worksheetPart.DrawingsPart.ChartParts.Any()) { saveXlsChart = worksheetPart.DrawingsPart.ChartParts.First(); } } newChartPart.FeedData(saveXlsChart.GetStream()); slidepartbkMark.Slide.Save(); xlsDocument.Close(); pptPackage.Close(); } } } } } A: If there is anybody who is looking how to identify a slide with a slide number you need to do the following //Get the relationship id SlideIdList s = documentPart.Presentation.SlideIdList; SlideId nslideid = (SlideId)s.ElementAt(slideno-1); //slide no is the number of the slide string slidRelId = nslideid.RelationshipId; Next iterate through each slide using a loop. Within the foreach loop add the following code to see if a slide has a particular relationship id // get the relationshipid of the current slide string thisSlideno = documentPart.GetIdOfPart(slidePart); if (thisSlideno == slidRelId) { //do your actions } I hope this is helpful
{ "pile_set_name": "StackExchange" }
Q: Маршрутизация между двумя итерфейсами Есть сервер с двумя сетевыми картами. eth1 смотрит в сеть 192.168.1.0 eth2 в 192.168.2.0 Есть два компьютера, comp1 подключен напрямую к серверу через eth1, comp2 подключен напрямую через eth2. Прописал статические маршруты на сервере и на двух компах. Итог: сервер пингует всех, а компы друг друга не могут. comp1 пингует интерфейс eth2, а comp2 не видит. comp2 пингует интерфейс eth1, а comp1 не видит. Что я упустил? A: на «среднем» компьютере должна быть разрешена передача пакетов между интерфейсами: $ echo 1 | sudo tee /proc/sys/net/ipv4/ip_forward для того, чтобы эта настройка применялась и после перезагрузки, раскомментируйте (или добавьте, если нет) строку в /etc/sysctl.conf: net.ipv4.ip_forward=1 убедитесь, что на прохождение пакетов не оказывают влияние правила netfilter-а. просмотреть их можно командой: $ sudo iptables-save на «клиентских» компьютерах убедитесь, что сеть и маска сети установлены такие же, как и на соответствующих интерфейсах «среднего» компьютера. на «клиентских» компьютерах должен быть либо добавлен маршрут по умолчанию через «средний» компьютер, либо добавлен конкретный маршрут ко второй сети, проходящий через «средний» компьютер.
{ "pile_set_name": "StackExchange" }
Q: Image with 100% width and a maximum and minimum height set without stretching img I can't figure out how to make the image not stretch but instead just cover the area. I am trying to make a image slider with css with an image that has 100% witdh and min / max height. Here is my html: <div id="container"> <div class="slider"> <ul> <li> <input type="radio" id="input1" class="input" checked/> <label for="input1" id="label1" class="label"></label> <img src="img/img-1.jpg" alt="img-1" id="img-1"/> </li> <li> <input type="radio" id="input2" class="input"/> <label for="input2" id="label2" class="label"></label> <img src="img/img-2.jpg" alt="img-2" id="img-2"/> </li> </ul> </div> </div> I've tried many things with css but this is the closest i got: @import "reset.css"; body { font-size: 100%; } #container { height: 100%; background: #cccccc; } .slider { max-height: 600px; min-width: 100%; background: red; } .slider img { width: 100%; min-height: 200px; max-height: 600px; } I hope you can help me. Thanks in advance A: Without distorting the image the only option is to scale and crop. This can be achieved by putting the image inside of a div and setting the height of the div to crop the image. Like this: div{ width: 100%; height: 80%; min-height: 200px; max-height: 400px; overflow: hidden; text-align: center; } img{ width: 100%; } http://jsfiddle.net/8szsq/1/ ...Or you wanted the opposite (fixed width crop height) div{ width: 100%; height: 80%; min-height: 200px; max-height: 400px; overflow: hidden; } img{ width: 600px; } http://jsfiddle.net/8szsq/2/
{ "pile_set_name": "StackExchange" }
Q: Calling a function that returns its updated output python So I'm completely having a brain fart but I'm attempting to call a function that returns its own updated input in a for loop that has to run 30 times. I have the for loop part down I'm just not sure how to call the function correctly. def miniopoloy_turn(state, cash) return state, cash so the function returns its updated state and cash values after running, but how would I then run the function again with the updated output inside a for loop? A: It sounds like you need to simply store the returned values in local variables and re-run the function as many times as necessary: # 1. set up initial values state = ... cash = ... # 2. run the function iteratively for i in xrange(30): state, cash = miniopoly_turn(state, cash) print state, cash # 3. profit!
{ "pile_set_name": "StackExchange" }
Q: Sending data from angular to express nodejs server running on different domain So I am trying to send some data I have in angular to my nodejs server. Let me start with my code: index.html <body ng-app="starter"> <ion-pane> <ion-header-bar class="bar-stable"> <h1 class="title">Ionic Blank Starter</h1> </ion-header-bar> <ion-content> </ion-content> </ion-pane> <div ng-controller="myCtrl"> <form> <input type="text" ng-model="message"> <input type="submit" value="Submit" ng-click="submit()"> </form> </div> </body> Here is a text box with data, then the submit button will send the message and deviceID to the server. app.js var app = angular.module('starter', []); app.controller('myCtrl', function($scope, $http) { var devToken; var push = new Ionic.Push({ "debug": true }); push.register(function(token) { devToken = token; console.log("Device token:", token.token); }); $scope.submit = function() { var message = "Hello"; $http({ method: 'POST', url: 'http://127.0.0.1:8080', token: devToken, message: message }) } }) As you can see, I am trying to grab a message and the deviceID and post it to my express server. server.js var express = require('express'); var bodyParser = require('body-parser'); var apns = require('apns'); var gcm = require('node-gcm'); var app = express(); var sender = new gcm.Sender('AIzaS.........plD2s8'); var registrationTokens = []; registrationTokens.push('Insert Device ID here that is passed from app.js'); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); app.get('/', function(req, res) { console.log("DEVICE ID == " + req.body.devToken); sender.send("Hello", { registrationTokens: registrationTokens }); }) app.listen(8080, function() { console.log('running on port 8080'); }); SO to recap, I am needing help getting my data when submitted to be available on my nodejs express server (which runs at a different domain/port than the Angular app). Can anyone help me figure out how to get my data from angular to express nodejs? Any help is appreciated. thanks A: You need to create a route to capture the post: app.post('/', function(req, res) { console.log(req.body); ... }); Then the front end could pass whatever you want $http.post("/", {message:message, devToken:devToken}).success(function(message, status) { console.log('Message posted'); }) If the backend is not on the same origin as the OP states in the comments, you would need to enable cross origin requests. 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(); }); Note: don't use * for production unless really want to allow requests from anywhere.
{ "pile_set_name": "StackExchange" }
Q: Wicket dropdown menu without form - click option redirects to another page I created Select dropdown menu. I can create SelectOptions, in which I add components, that will be shown in this menu. I am trying to add the links (final Link myLink = new Link("myLink") { ... }) into this options, it doesn't work. It just shows names of the links, after clicking the option is selected, but not redirected. This is example of my HTML code: <select wicket:id="projectLinks"> <option wicket:id="myLink">Create Project</option> </select> JAVA code: Select<Link> select = new Select<Link>("projectLinks"); select.add(new SelectOption<Link>("myLink", new Model(myLink))); Could you provide me any easy example of DropDown menu without Form, which options just redirect me to another page after clicking them? A: You can add an AjaxFormComponentUpdatingBehavior to your dropdown to cause the selection to trigger an action, such as page redirection. DropDownChoice projectLinksDropDown = new DropDownChoice("projectLinks", new Model(selectedProjectLink), projectLinkOptionList); projectLinksDropDown.add(new AjaxFormComponentUpdatingBehavior("onChange") { @Override protected void onUpdate(AjaxRequestTarget target) { selectedProjectLink = (ProjectLink) getFormComponent().getConvertedInput(); setResponsePage(selectedProjectLink.getRedirectPage()); } } this.add(projectLinksDropDown); The cool thing with the AjaxFormComponentUpdatingBehavior that I am not taking advantage of in my example above is that you can do partial page refresh to hide/show/update panels without having to perform a full page redirect. Have fun!
{ "pile_set_name": "StackExchange" }
Q: why do matrix product states work at critical point? Matrix product states satisfy the entanglement area law, which should be a property of gapped states. But usually, MPS work well in 1D quantum phase transition problems. As far as I know, entanglement at critical point should satisfy the log-divergence. So why do MPS work well at a critical point? And I also hope to know the reason why MPS fail in 2D? Thanks A: In order to capture a system with a entanglement which scales like $S\sim\log(L)$, the bond dimension has to (roughly) grow like $D\sim e^S\sim \mathrm{poly(L)}$. Thus, the computational resources required will still scale polynomially with the system size, even for critical systems.
{ "pile_set_name": "StackExchange" }
Q: Eclipse breakpoint events In my Eclipse plugin, I would like to be notified when a breakpoint is created, removed or disabled. Is there an event that I can subscribe to for this? Thanks, Alan A: I haven't used it, but from the docs it looks like you might be interested in IBreakpointManager. It looks like you should add an IBreakpointListener or an IBreakpointsListener to this. Have a look at this help section: http://help.eclipse.org/galileo/index.jsp?topic=/org.eclipse.platform.doc.isv/guide/debug_breakpoints.htm
{ "pile_set_name": "StackExchange" }
Q: Stackoverflow's Animated Required Fields Validation Method? I am developing an ASP.NET website. Currently I am doing required field validations by simply adding a required field validater and Validation summary control at the top of the page. But I saw an interesting validation in stackoverflow. When you click submit button its popup with a little animation. I am guessing that it done by using jquery. I want that exact validation method. Whole validation thing with the shaking effect. I am not familiar with Jquery. Any resource will useful. Thank you very much. Here is the Link https://stackoverflow.com/contact Here is the screen shot http://i62.tinypic.com/ofd4b4.jpg A: Take a look at this answer for form validation using jQuery As for your actual question, the code below will do the job. Check the jsfiddle I created to see the results of the code below. Note: In order for this to work, you must use the proper jQuery version. The version I am using for the fiddle is jQuery 1.9.1 with jQuery UI 1.9.2 HTML <form id="myForm"> <input id="myTextID" type="text" placeholder="Enter Text Here" /> <div class="alert"> <div class="alert-point"></div><span>No text was input</span> <div class="close">X</div> </div> <br/> <br/> <br/> <select id="mySelectID"> <option>Select something</option> <option>Some option</option> <option>Some other option</option> </select> <div class="alert"> <div class="alert-point"></div><span>You must select an option. Note the first option is not a valid one</span> <div class="close">X</div> </div> <br/> <br/> <br/> <input id="myButtonID" type="button" value="Submit" class="submit" /> </form> <p>If no text is entered in the input box above and/or no selection is made (meaning the default selection is ignored) when the button is clicked, the error will show up</p> The HTML is in a specific order: Form includes all the elements necessary. Input(or select, etc.) followed by div(with class of .alert). The <br/> tags can be removed and CSS could be played with to make it prettier (in terms of code, layout and appearance), however I simply wanted to show the logic behind it all The div tags with class="alert" have 3 sections. Triangle (class .alert-point) Alert message (in span tag) X button to close the alert (I used a div tag for this as I thought it to be easiest) The 3 inner components to the alert are all set to display inline-block CSS input, select { position:relative; float:left; } .alert { padding:10px; background-color:#C44D4D; position:relative; color:white; font:13px arial, sans-serif; font-weight:bold; display:none; float:left; opacity:0; margin-left:7px; margin-top:2px; } .alert-point { width: 0; height: 0; border-left: 10px solid transparent; border-right: 10px solid transparent; border-top: 10px solid #C44D4D; position:absolute; left:-10px; top:0px; } .alert>span { line-height:24px; } .alert>.close { background-color:none; border:1px solid rgba(255, 255, 255, 0.3); margin-left:10px; width:20px; height:20px; line-height:20px; text-align:center; color:white; display:inline-block; cursor:pointer; } .submit { cursor:pointer; } The CSS simply positions the elements using float:left; and position:relative; The div tags with class .alert are set to display:none; and opacity:0; so that when the document loads, all the alerts are not visible (opacity set to 0 for animations in jQuery, default would otherwise be 1) The rest of the CSS simply improves the appearance. JS $("#myButtonID").click(function () { var numShakes = 3; //full cycles var distance = 10; //in pixels var cycleSpeed = 1000; //in milliseconds if ($("#myTextID").val() === "") { $("#myTextID").next("div").css({ display: "inline-block" }); $("#myTextID").next("div").animate({ opacity: 1 }, 500, function () { $(this).effect("shake", { direction: "left", times: numShakes, distance: distance }, cycleSpeed); }); } if ($("#mySelectID")[0].selectedIndex === 0) { $("#mySelectID").next("div").css({ display: "inline-block" }); $("#mySelectID").next("div").animate({ opacity: 1 }, 500, function () { $(this).effect("shake", { direction: "left", times: numShakes, distance: distance }, cycleSpeed); }); } }); $(".close").click(function () { $(this).parent().animate({ opacity: 0 }, 1000, function () { $(this).css("display", "none"); }); }); The jQuery code has 2 functions: Button click function (that processes the form validation) Div click function (that processes the close alert) Button click function This function declares 3 variables off the bat to be used in the shake function later. Play with these values as you wish. - numShakes determines the number of times the shake effect will run - distance determines the distance in pixels that the object will move in the given direction (left to right is default) - cycleSpeed determines the speed of the shake effect After these 3 variables are declared, each if statement represents a different input item. If you have more inputs, copy and paste the if statement, and then change what I mention later in that statement. The if statement is structured like so: The if statement determines if a value was input, selected, etc. So in the first if statement we get the value of the input with the id of #myTextID and if this is set to "", in other words, nothing was input, then do the following. This should work for any fields where input is based on keyboard input (in terms of text or numbers) We then get the next div element that follows the #myTextID element in the DOM, which is of course our div with class .alert, and we change its CSS to display:inline-block; (this could be set to block as well if you'd like, I have it set to inline-block because I was testing things out and never changed it back. The reason we are doing this is so that the element now shows up in the document (but it is still invisible - opacity:0 in the CSS document) We now grab that same item and we use the animate function to set its opacity to 1 after 500 milliseconds. After the 500 milliseconds is up, we run our animation end function which is set to our shake function. This function grabs the same item we've been working with and uses the effect method. From the effect method, we are using the "shake" effect. We also plug in those variables we declared at the beginning of the click function Repeat for all your inputs changing, as I mentioned earlier I would mention, the id of the items (there are 3 ids to change per if statement). You should also make sure that you're searching for the proper "0 input" value (meaning that the user hasn't yet input a value into the required field). As we can see the second if statement uses a different condition than the first one. The link I provided above should help you with what to check for form validation Finally, the div click function, which closes the alert. This function simply animates the opacity back down to 0 and following this animation (once the animation has been completed), we set its display back to "none" Hope that helps! EDIT - Added explanations below each section of code
{ "pile_set_name": "StackExchange" }
Q: Position of observer (lat/lon) I'm playing around with pyephem and jplephem and I can't seem to figure out how to track the path of an observer (or given lat/lon/date) in time with these package. What I would like to do is record the position (x,y,x) over time of a supplied lat/long/date on Earth with respect to the Sun. Imagine the path generated by a tracer on the surface of Earth w.r.t. the Sun. Is there a way to easily get the position of a point on Earth's surface with respect to Earth's barycenter at a given time? Thanks in advance. A: The PyEphem library is built atop an astronomy library called libastro that, alas, does not provide access to its underlying vectors. And jplephem doesn't know anything about the position of the planets in the Solar System. But the Skyfield astronomy library, for which jplephem was written, does both. Here is how you would find out the x,y,z position of an Earth location relative to the sun: from skyfield.api import load, Topos # Let's consider 72 hours starting at midnight UTC on January 2. duration_hours = 72 ts = load.timescale() t = ts.utc(2018, 1, 2, range(duration_hours)) # Load a planetary ephemeris. planets = load('de421.bsp') earth, sun = planets['earth'], planets['sun'] # Print where the US Naval Observatory was each hour relative to the Sun. usno = Topos('38.9215 N', '77.0669 W', elevation_m=92.0) result = sun.at(t).observe(earth + usno) for time, position_au in zip(t, result.position.au.T): print(time.utc_jpl(), position_au) The resulting lines look like: A.D. 2018-Jan-04 21:00:00.0000 UT [-0.24130305 0.87456403 0.37915831] A.D. 2018-Jan-04 22:00:00.0000 UT [-0.2420075 0.87440863 0.37908723] A.D. 2018-Jan-04 23:00:00.0000 UT [-0.24271409 0.87425296 0.37901595] Here's Skyfield's home page: http://rhodesmill.org/skyfield/
{ "pile_set_name": "StackExchange" }
Q: Avoid too much conversion I have some parts in my current Go code that look like this: i := int(math.Floor(float64(len(l)/4))) The verbosity seems necessary because of some function type signatures like the one in math.Floor, but can it be simplified? A: In general, the strict typing of Go leads to some verbose expressions. Verbose doesn't mean stuttering though. Type conversions do useful things and it's valuable to have those useful things explicitly stated. The trick to simplification is to not write unneeded type conversions, and for that you need to refer to documentation such as the language definition. In your specific case, you need to know that len() returns int, and further, a value >= 0. You need to know that 4 is a constant that will take on the type int in this expression, and you need to know that integer division will return the integer quotient, which in this case will be a non-negative int and in fact exactly the answer you want. i := len(l)/4 This case is an easy one.
{ "pile_set_name": "StackExchange" }
Q: Preinstalled python on mac a cpython? As the title says,I want to know if the python which comes pre installed on mac is cpython. I mean logic says it probably is,but I couldn't find it being written anywhere officially so wanted to confirm. I want to download a few things and for compatibility they require the installed python to be cpython/iron python. A: With command Python --version you get the information like that: [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin It is almost affirmative that it is cpython with gcc as compiler. An alternative(which is more official) is to check with python code: import platform platform.python_implementation() The function python_implementation: Returns a string identifying the Python implementation. Possible return values are: ‘CPython’, ‘IronPython’, ‘Jython’, ‘PyPy’
{ "pile_set_name": "StackExchange" }
Q: Pass data.table column by name in function I want to pass a column name to a function and use column indexing and the setorder function: require(data.table) data(iris) top3 = function(t, n) { setorder(t, n, order=-1) return ( t[1:3, .(Species, n)]) } DT = data.table(iris) top3(DT, Petal.Width) However, this returns an error: Error in setorderv(x, cols, order, na.last) : some columns are not in the data.table: n,1 I think I'm misunderstanding how passing bare column names works in R. What are my options? A: You can do top3 = function(DT, nm) eval(substitute( DT[order(-nm), .(Species, nm)][, head(.SD, 3L)] )) top3(DT, Petal.Width) Species Petal.Width 1: virginica 2.5 2: virginica 2.5 3: virginica 2.5 I would advise against (1) setorder inside a function, since it has side effects; (2) indexing with 1:3 when you may use this on a data.table with fewer than three rows in the future, to strange effect; (3) fixing 3 instead of making it an argument to the function; and (4) using n for name... just my personal preference to reserve n for counts.
{ "pile_set_name": "StackExchange" }
Q: shortest path between all points problem, floyd warshall Mr. Rowan plans to make a walking tour of Paris. However, since he is a little lazy, he wants to take the shortest path that goes through all the places he wants to visit. He plans to take a bus to the first place and another one back from the last place, so he is free to choose the starting and ending places. Can you help him? Input The first line of input contains the number of places to visit (n). Then, in the following n lines, you find the coordinates of each place to visit. Here is an example: 3 132 73 49 86 72 111 Output For each test case, your program should output one line containing the minimum distance that Mr. Rowan must walk to visit all places assuming that the walking distance from one place to another is the Euclidean distance. The algorithm should output a number in fixed-point notation with exactly 3 digits to the right of the decimal point and no leading space. There are at most 12 places to visit. Example Example input: 3 132 73 49 86 72 111 Example output: 104.992 i've been working on this code, for my homework, but i cant make it work, im start wondering if this is the best approach.. the problem is the floyd-warshall function, that does nothing on float **path structure.. dont know why.. path is the same before and after the floydwarshall(path, n, next); #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <float.h> /*Implementing of http://en.wikipedia.org/wiki/Floyd–Warshall_algorithm*/ struct point { float x; float y; }; float cost(struct point* a, struct point* b) { return sqrt(pow((*a).x - (*b).x, 2) + pow((*a).y - (*b).y, 2)); } float** f2dmalloc(int n, int m){ int i; float **ptr; ptr = malloc(n * sizeof(float *)); for (i = 0; i < n; i++) { ptr[i] = calloc(m, sizeof(float)); } return ptr; } void floydwarshall(float **path, int n, float ** next){ int i, j, k; float a, b; for (k = 0; k < n; k++) { for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { a = path[i][j]; b = path[i][k] + path[k][j]; path[i][j] = ((a) < (b) ? a : b); next[i][j] = k; } } } } int main (int argc, const char* argv[]) { int i; int j; int n; float temp; float mininum; scanf("%d", &n); /* A 2-dimensional matrix. At each step in the algorithm, path[i][j] is the shortest path from i to j using intermediate vertices (1..k−1). Each path[i][j] is initialized to cost(i,j). */ float ** path; float ** next; struct point* points; path = f2dmalloc(n, n); next = f2dmalloc(n, n); points = malloc(n * sizeof(struct point)); for (i = 0; i < n; i++){ scanf("%f %f", &(points[i].x), &(points[i].y)); } for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { path[i][j] = cost(&points[i], &points[j]); } } temp = 0; for (i = 0; i < n; i++) { mininum = FLT_MAX; for (j = 0; j < n; j++) { printf("%.3f\t", path[i][j]); if (path[i][j] < mininum && path[i][j] != 0){ mininum = path[i][j]; } } printf("\tminimum - %.3f\n", mininum); temp += mininum; } floydwarshall(path, n, next); for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { printf("%.3f\t", next[i][j]); } printf("\n"); } /* temp = 0; for (i = 0; i < n; i++) { mininum = FLT_MAX; for (j = 0; j < n; j++) { printf("%.3f\t", path[i][j]); if (path[i][j] < mininum && path[i][j] != 0){ mininum = path[i][j]; } } printf("\tminimum - %.3f\n", mininum); temp += mininum; } printf("%.3f\n", temp); */ return 0; } A: Floyd-Warshall solves the problem: For each pair of points, find the shortest path joining them. (It needs to join these two points. It doesn't need to do anything else. It will only visit other points if that produces a shorter path.) In the present case, since you can always go directly from any point to any other, the shortest path is always the direct one: just go from A to B. (Which is why calling floydwarshall doesn't change anything.) But the problem you're trying to solve seems to be the travelling salesman problem: find a path that visits all your points and is as short as possible. These are entirely different problems, and you'll need to do something quite different to solve the problem you've been asked to solve.
{ "pile_set_name": "StackExchange" }
Q: Where does the Calypso's Compass lead me to? I've gotten it only a couple times, but each time I try to follow it, I die in the harder areas. What does it evetually lead me to, and would I be able to find whatever it is without having the compass, just by searching every room of the castle? A: The compass leads you to a secret room that contains 2 chests. The chests usually contain blueprints or stat upgrades. From my experience they were good blueprints (armor I was not finding in the area normally). You will not be able to locate the room without the compass. edit: user2339067 says he was able to get to the room without the compass, so it might be possible. I have yet to find/confirm this information independently with any other online resources. A: Some additional information: You can find the room without the compass, there will however not be ANY indications for it except for seeing an up arrow in a random location in the room. Source: I found it randomly when I did not have the compass
{ "pile_set_name": "StackExchange" }
Q: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server 2008 in .net application I am using .net application by sql server 2008 remote access. The error in application are "An error occurred while establishing a connection to server. When connecting to SQL Server 2008, this failure may caused by the fact that under the default settings SQL Server does not allow remote connections. (Provider:Named pipes Provider error:-40 - Could not open a connection to sql server. A: Your SQl server is ether doesn't allow your remote access so if you want to access remote server allow tcp/ip connections or your connection string is wrong. In either case you should post your connection string without servername username password in here so we can check the validity. Just one note, allowing external tcp/ip connections to SQL-SERVER is not secure because anyone can access the server from now on. I would advice to limit access in firewall or managed switch by restricting access to IIS or application server IP.
{ "pile_set_name": "StackExchange" }
Q: How to convert the time zone to local? I get dates on the site for some events: >>> parse(event.find_element_by_xpath('../td[@data-dt]').get_attribute('data-dt')) datetime.datetime(2019, 11, 26, 19, 15, tzinfo=<StaticTzInfo 'Z'>) How can I convert this time to a local time zone, so that I can count down to the start of the event? A: I found a solution: from tzlocal import get_localzone parse(event.find_element_by_xpath('../td[@data-dt]').get_attribute('data-dt')).astimezone(get_localzone())
{ "pile_set_name": "StackExchange" }
Q: Use select() within Qt for monitoring of multiple ports, or is there a better way? I have a need for a very simple server program which executes one of five different activities, based on client connections. Since this is for a demo, I don't need any complex network handling, my intention was just to open up five server sockets (say 10001 thru 10005 inclusive) and simply await incoming connections. Upon the server receiving an incoming connection on (for example) the first socket 10001, it would immediately accept and close the connection, then execute the first action. Ditto for the other sockets. That way, I could demo the actions from another window simply by executing: telnet 127.0.0.1 10001 Normally, I would use select() with a very short timeout value (i.e., not too onerous on the event processing thread) to await and detect which port was being connected to but, since this is a Qt application, I'm not sure that will work so well with the Qt event model. What would be the best way of doing this with Qt (5.5, if it matters)? Is the use of a small-timeout select() actually going to work or do I need to go heavyweight with five separate QTcpServer objects, each with their own infrastructure (callbacks and such)? A: If I properly understand, you want handle all requests in one place. In Qt you can use signal/slot for it. Connect signals from all QTcpServer objects to one slot, something like: // Method to fully start a server on specific port. QTcpServer *MyClass::StartServer(int port) { QTcpServer *server = new QTcpServer(); server->listen(QHostAddress::Any, port); connect(server, SIGNAL(newConnection()), this, SLOT(HandleConn())); return server; } // Method to start all servers, serverArr is an array of QTcpServer // items (in the object, obviously). void MyClass::StartAllServers() { for (size_t i = 0; i < sizeof(serverArr) / sizeof(*serverArr); i++) serverArr[i] = StartServer(10000 + i); } // Callback to handle connections. void MyClass::HandleConn() { // This will call doAction with parameter based on which QTcpServer // has caused the callback. QTcpServer *source = static_cast<QTcpServer*>(sender()); for (size_t i = 0; i < sizeof(serverArr) / sizeof(*serverArr); i++) if (source == serverArr[i]) doAction(i); // Action done, so just accept and close connection. QTcpSocket *socket = source->nextPendingConnection(); socket->close(); }
{ "pile_set_name": "StackExchange" }
Q: Did I make a mistake when finding the intervals this function is continous on? I was given a function f given by $f(x) = \begin{cases} \frac{x^2 - a^2}{x - a \;} \textit{if} \; x \neq a, \\ 2a \; \textit{if} \; x=a \\ \end{cases}$, and told to find the intervals over which $f$ is continous, in terms of $a$. I just figured it is continous everywhere except $a$, so the intervals would be $]-\infty, a[$ and $]a, \infty[$. However, my textbook gives the answer, without working, as $]-\infty, -a[$ and $]-a, \infty[$. I'm like 99% sure this is a mistake by the textbook author, not me, but continuty and the like is not my strong side, so I just want to make sure I didn't make a mistake here. Thanks in advance! A: It is $$\frac{x^2-a^2}{x-a}=x+a$$ if $x\neq$ $a$ and $$\lim_{x\to a}\frac{x^2-a^2}{x-a}=2a$$ thus our function is continous for all real $x$
{ "pile_set_name": "StackExchange" }
Q: Search from bottom with multiple criteria I am trying to search a data table in excel and find the bottom most row that meets a specific criteria. I thought I could use this LOOKUP trick but it only returns a #DIV/0 error. This is what I tried: =LOOKUP(2,1/AND(ABS(Data!$I$2:$I$976-Calc!$D$2)<Calc!$F$1,Calc!$A6=Data!$J$2:$J$976),Data!$G$2:$G$976) The criteria is that the value in column Data!I needs to be within a certain range of the value in Calc!D2 and the value in column Data!J needs to be equal to the value in the value in Calc!A6 I'd like to avoid VBA if I can (which is why I'm on SU and not SO). A: You can use an array formula which is entered by pressing ctrl+shift+enter To find the row in question you would use: > =max(if(ABS(Data!$I$2:$I$976-Calc!$D$2)<Calc!$F$1,if(Data!$J$2:$J$976=Calc!$A6,row(Data!$I$2:$I$976),0),0)) if you want to return a specific cell wrap the below formula around it with the column you are interested in, in place of A =indirect("A" & formula here)
{ "pile_set_name": "StackExchange" }
Q: extract data before and after tag using selenium How to extract text before and after tag using selenium and xpath in JAVA. I have following code <tr> <td> This is my amount <br> $3.2 </td> <tr> I want result like "This is my amount" "$3.2" each field in a column of table A: you can use getText() which will return entire element text. For <Br> it will have line break in returning text so you can spilt text by '\n' if want each line text.
{ "pile_set_name": "StackExchange" }
Q: Strange behavior of INCLUDE in Entity Framework This works: using (var dbContext = new SmartDataContext()) { dbContext.Configuration.ProxyCreationEnabled = false; var query = dbContext.EntityMasters.OfType<Person>(); if (includeAddress) query.Include(p => p.Addresses); if (includeFiles) query.Include(p => p.FileMasters); output.Entity = query.Include(s=>s.Addresses).FirstOrDefault<Person>(e => e.EntityId == id); } while this doesn't: using (var dbContext = new SmartDataContext()) { dbContext.Configuration.ProxyCreationEnabled = false; var query = dbContext.EntityMasters.OfType<Person>(); if (includeAddress) query.Include(p => p.Addresses); if (includeFiles) query.Include(p => p.FileMasters); output.Entity = query.FirstOrDefault<Person>(e => e.EntityId == id); } I am trying to include Addresses, Files based on boolean flags coming from function. However it seems, EF not including them when using IF condition. This is related to my previous question which actually worked using Include. A: You need to assign the result of Include back to query query = query.Include(p => p.Addresses);
{ "pile_set_name": "StackExchange" }
Q: How can I order items in my DOM when they aren't ngRepeated in AngularJS? I have a controller that contains 2 different controllers: a users and classes model. I'd like them to stay on the top according to the chronological order in which they were opened (e.g. if you open Users then Classes, Classes should appear above Users, even though in the html template, the Users section appears first). Here's a JSBin: http://jsbin.com/IQUDEdI/10/edit When you click a checkbox to open one section, it unshifts it to array $scope.openSections. I realized that ngFilter doesn't work unless it's within a ngRepeat (right?). If there's not a built-in way to do it (I was looking at ngSwitch, but that doesn't look like what I want), I was going to create (or rather modify) a directive on section that would do a $(body).prepend(element) or something, although I'm not sure if that'd 100% work. Does anyone know the best way to go about doing this? Thanks in advance A: This is a very nice question. Basically, we need a directive which can show, hide and sort a list of sections on every change. Our directive must "know" all the sections it contains in order to sort them. Oh, there is such a directive : ngRepeat, But how can we provide it a list of sections? If these "sections" are just DOM nodes there is no way to pass them into ngRepeat. So, I tried to create a directive (container) which collects all the DOM NODES , watch the collection and on change sorts, shows or hides the relevant sections. But that kind of manipulation of DOM nodes is a real pain and I felt it's a wrong way to go. And then I saw the light! Just refactor the markup a little bit by using ngInclude to declare the templates. then use ngRepeat to iterate these templates, so nice. Now it's a great win: No custom directive needed. All the benefits of ngRepeat / ngInclude goodies No need to set a different watch on each section, ngRepeat will take care of it. simple and clear! Here is a plunker: Declaring templates: <script type="text/ng-template" id="users.section"> <div ng-controller='usersviewer'> <legend>Users</legend> <li ng-repeat='user in users'>{{user.name}}</li> </div> </script> <script type="text/ng-template" id="classes.section"> <div ng-controller='classesviewer'> <legend>Classes</legend> <li ng-repeat="class in classes">{{class}}</li> </div> </script> Using ngRepeat to do all the "magic": <div class='section' ng-repeat="include in openSections" ng-include="include + '.section'"> </div> Bonus - refactored the css to match ngInclude animations: .section { background:darkgray; color:white; /* Default fully visible value */ opacity: 1; height: 100px; overflow:hidden; } .section.ng-leave { /* Declare transitions */ display:block !important; transition: all 0.2s; /* Value when fully visible */ opacity: 1; height: 100px; } .section.ng-leave-active { /* Value when invisible */ opacity: 0; height: 0px; } .section.ng-enter { /* Declare transitions */ transition: all 0.2s; display:block !important; /* Value when invisible */ opacity: 0; height:0px; } .section.ng-enter-active { /* Value when fully visible */ opacity: 1; height: 100px; }
{ "pile_set_name": "StackExchange" }
Q: VSTS : automatically rebase/merge and requeue build validation gate in case of build expiration We recently made a change to our build validation gate on PRs such that the builds expire "immediately" if another commit makes it into master branch before the current PR completes. See here. Even though this change ensures that the master is always accurate/buildable/healthy, this seems to have few negative effects on developer productivity : team members have to continuously keep an eye on their PRs to requeue builds validations. Not only they have to requeue builds manually, but prior to doing that they have to manually rebase their branch before requeueing. as we move towards more smaller/shippable checkins in to master, the no. of times this occurring is expected to increase. I want to automate (1) and (2). Is there a way I can setup VSTS build validation such that for all open PRs, upon build expiry, it automatically rebases/remerges the source branch with master and then requeues the build ? A: I've run into this exact problem at my organization. Setting Build expiration to Immediately becomes too burdensome when there are multiple PRs all trying to get into the same time. AFAIK - there's no way to automatically trigger a rebuild of all PRs targeting master whenever master is updated. I'm sure the basics are there if you want to hook into VSTS events and write the code yourself. But there's nothing out-of-box last time I looked. What my organization did was to accept a compromise. We configure PRs so the build expires after 1 hour. This way there's no contention when multiple PRs are trying to be merged at the same time. However, this has the downside you describe in your original question VSTS : Invalidating builds on existing PRs when another commit makes it into master branch where it's possible for the target branch (ie master) to become broken because of a quick merger of two incompatible PRs. We've ended up just embracing this limitation We have a trigger on all of our branches (feature, master, etc) that whenever new commits are added, we automatically trigger a new build. This way if a PR managed to break master we get an email about it within a few minutes. If the main branch (ie master) becomes broken, all new PRs will start failing builds. Thus, no new PRs can be merged in. This usually gets everyone's attention so the problem quickly bubbles up to the surface - and the whole team starts working to fix master. Before we deploy master we run a full VSTS build, including unit tests. This way, if the main branch is broken (by two incompatible PRs or for any other reason) we make sure we halt the deployment. So, unfortunately, we can't guarantee that master is always a 100% in a good state. Getting to 100% is just has too much negative impact on our workflow and productivity. So we embrace our limitations and make sure we are notified asap and can handle the situation when the branch breaks.
{ "pile_set_name": "StackExchange" }
Q: Simple C# login with 3 attempts with id case sensivtive/insensitive i need c# code in which user can login with 3 attempts and user id should be case insensitive and password should be case sensitive would you please any one help. The code is given below: C# code: <code> //Login Attempts counter int loginAttempts = 0; //Simple iteration upto three times for (int i = 0; i < 3; i++) { Console.WriteLine("Enter username"); string username = Console.ReadLine(); Console.WriteLine("Enter password"); string password = Console.ReadLine(); if (username != "EDUAdmin" || password != "edu@123") loginAttempts++; else break; } //Display the result if (loginAttempts > 2) Console.WriteLine("Login failure"); else Console.WriteLine("Login successful"); Console.ReadKey(); </code> A: Please see comments under Question for clarification. //Login Attempts counter int loginAttempts = 0; //Simple iteration upto three times for (int i = 0; i < 3; i++) { Console.WriteLine("Enter username"); string username = Console.ReadLine(); Console.WriteLine("Enter password"); string password = Console.ReadLine(); if (username.ToLower() != "eduadmin" || password != "edu@123") loginAttempts++; else break; } //Display the result if (loginAttempts > 2) Console.WriteLine("Login failure"); else Console.WriteLine("Login successful"); Console.ReadKey();
{ "pile_set_name": "StackExchange" }
Q: Color of div based on parent element's class I have a table where the first cell of each row contains a div which spans the entire row. I want the background of each div to be a different color based on the class of the containing row. Is this possible? Something along the lines of: tr.even div.myDivClass{ background-color: red; } tr.odd div.myDivClass{ background-color: green; } Here is simplified version of the table: <table> <tr class="even"> <td colspan="14"> <div class="myDivClass"></div> </td> </tr> <tr class="odd"> <td colspan="14"> <div class="myDivClass"></div> </td> </tr> <tr class="even"> <td colspan="14"> <div class="myDivClass"></div> </td> </tr> <tr class="odd"> <td colspan="14"> <div class="myDivClass"></div> </td> </tr> </table> A: If you want alternate colors (which is what your code is doing), you could simply use the following without defining any classes: tr:nth-of-type(even) { background-color: red; } tr:nth-of-type(odd) { background-color: green; } If you want it to be 'any' color, then I don't see a problem with your code.
{ "pile_set_name": "StackExchange" }
Q: How do I landscape a sloping and flood-susceptible yard? My wife and I just moved into a house in Arkansas a few months ago and have noticed a few drainage issues with the back yard, it has roughly a 5 to 10 degree slope (east to west) and is fenced in. The soil is fairly hard and seems clay like at the surface. There is also a lack of grass at the moment. The rain water will pool against the fence on the low side (West) of the yard and takes quite a while to soak into the soil in numerous places. The slope also causes loose silt and dirt to migrate towards the west side of the yard (down sloped side) during heavy rains. I would like to fix this issue. The first thought is to till the land, fill in the low spots with some top soil, level the land slightly, and plant seed. I'm thinking that will help absorb the water faster. I would like to stray from such ideas as dry wells and re grading the land as I think they would be too costly. My problems arises from the underground sprinkling system in the yard and some stray wires I found running underneath the cement slab patio to some point in the yard (I presume it is a wire for the underground sprinkler system). I have not followed the wires yet but they are only a few inches below the ground (if that) and are rather small in diameter. I have read the sprinkler system should be around a foot underground, should I be concerned with that if hand till the lawn with one of those cultivating tools from Lowe's? Possibly using a rototiller? Is there a company or anything out there that can give me an idea where the sprinkler system runs (short of marking the heads and guessing/trial and error) and where these stray wires go to (something like a digger hotline, Arkansas one call only does utility type lines)? Lastly, how do I prevent the rain from washing the new seed and soil towards the down hill side of the yard? A: My thought is that your best strategy is to get some organic matter and a little sand into that dense clay. Organic matter is a sponge; it will readily absorb and then release water. Sand and other aggregate is more like a sieve; it creates spaces in the soil in which water can collect, making the soil itself more absorbent. Both of them will also make the soil softer, allowing grass to sink its roots deeper and thus grow healthier. The carbon compounds and nitrates in the organic matter are natural fertilizer to your lawn as well. If there's little or no grass in the area, it's not going to hurt much just to till it all up. Sprinkler lines CAN be a concern; your average sprinkler line will be between 6 and 12" beneath the surface; your average rototiller will chew up any heads you hit, and can even grind up the entire line beneath. As was said in the comment, sprinkler lines are relatively cheap; HOWEVER, you'll have to consider whether it's worth it to you to replace any lines you hit (in addition to materials cost, you'll either need to get dirty and wet to actually do the job, or pay a crew to do it for you). Generally you don't want to just chew up PVC or nylon into your topsoil, either. Most systems I've seen are extremely simple; just find each head and connect the dots. To be absolutely sure since you're digging around anyway, you can dig down to the T-joint under each head and see which way the pipe(s) run. By doing this you'll also see how deeply the line was trenched. Much more important than sprinkler lines is other utilities. Make sure you know exactly where any buried electrical, gas, CATV and water supply pipes are located on your property. Most relatively new neighborhoods should have one dedicated utility easement that carries all these conduits from central service points through to all the properties. Older developments that were built before the advent of certain modern conveniences, or even newer houses that weren't built as part of a large coherent development project, can have these lines practically anywhere on the property. If you call, they will come out and marke the lines for free. If you hit one and come out to have them fix it, it can cost you hundreds.
{ "pile_set_name": "StackExchange" }
Q: Drupal Webform missing edit link for fields from CiviCRM database Webform Form Components page does not show option to edit individual fields that are from CiviCRM database. Drupal fields work OK. This was working previously but is not working after upgrading versions. I have multiple instances and some forms show edit option and others do not. A: Version incompatibility introduced in Webform version 7.x-4.12 and webform civicrm 7.x-4.13. Upgrade webform civicrm to 7.x-4.14 solves problem. Drupal issue https://www.drupal.org/node/2600878 details this.
{ "pile_set_name": "StackExchange" }
Q: Lipschitz continuous gradient. Finding the best/smallest $\beta$ for a function $f$ to be $\beta$-smooth Consider a function $f(x, y): \mathbb{R}^2 \rightarrow \mathbb{R}$ where $f(x, y) = \frac{5}{2}x^2 + xy + \frac{5}{2}y^2$. By definition the gradient of a function $f$ is Lipschitz continuous with parameter $\beta > 0$ if: \begin{align} \tag 1 \|\nabla f(x) - \nabla f(y)\| \leq \beta\|x- y\| \end{align} Here $x$ and $y$ denote any two points in the domain of function $f$. The function $f$ with this property is also $\beta$-smooth. Here the norm $\| \|$ denotes a euclidean norm. I tried looking at this post for hints on how to find $\beta$ but it didn't give me any insights to apply them for my function in question. Here is what I have tried so far: \begin{align} \nabla f &= \begin{bmatrix} 5x+ y \\ x + 5y \end{bmatrix} \end{align} Now lets consider two points $a = (a_1, a_2)$ and $b = (b_1, b_2)$ for our function $f$. Now the left hand-side of equation ($1$) without the norm becomes \begin{align} \nabla f(a) - \nabla f(b) &= \begin{bmatrix} 5a_1 + a_2 - 5b_1 - b_2\\ a_1 + 5a_2 - b_1 - 5b_2 \end{bmatrix} \end{align} Applying the euclidean norms of equation (1) leaving $\beta$ alone on the right hand side we have: \begin{align} \frac{\|\nabla f(a) - \nabla f(b)\|}{\|a- b\|} = \frac{\sqrt{(5a_1 + a_2 - 5b_1 - b_2)^2 + (a_1 + 5a_2 - b_1 - 5b_2)^2}}{\sqrt{(a_1 - b_1)^2 + (a_2- b_2)^2}} \leq \beta \end{align} So the smallest $\beta$ value will occur when we have equality. I tried expanding the above expression but it only gets more messy. I think my approach is wrong. What form would $\beta$ be? Is it a constant? From the above expression it seems to depend on the coordinates of the selected two points but according to the definition it should be independent of the chosen points. What would be the right way to calculate $\beta$? Any help building up the intuition with this simple example would be greatly appreciated! Thanks! A: Hint: the derivative $\nabla f$ is a linear map; indeed, the matrix for the map is $A = \begin{pmatrix} 5 & 1 \\ 1 & 5 \end{pmatrix}$. Thus $$\| \nabla f(x) - \nabla f(y)\| = \| A(x-y)\| \le \|A\| \| x-y\|.$$ Now you just need to bound (or explicitly find) the matrix norm of $A$.
{ "pile_set_name": "StackExchange" }
Q: Null Exception in Android AsyncTask onPostExecution I followed a tutorial online. However I can't get it to work and I keep getting a NullPointerException. The app spends about 2-3 minutes attempt to connect to my server and then just shuts down. I think the problem is in Array Adapter. The Array Adapter has 13 Objects but its show null on setting it to a spinner Please Help me sort out the issue i'm new to android so need some help. My code MainActivity public class MainActivity extends Activity { Spinner SID; Spinner SName; Spinner SMailID; Button Btngetdata; ArrayList<String> Name = new ArrayList<String>(); List<String> UID = new ArrayList<String>(); List<String> MailID = new ArrayList<String>(); //URL to get JSON Array private static String url = "http://api.androidhive.info/contacts/"; //JSON Node Names private static final String TAG_USER = "contacts"; private static final String TAG_ID = "id"; private static final String TAG_NAME = "name"; private static final String TAG_EMAIL = "email"; JSONArray user = null; @SuppressWarnings("unused") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Spinner SID = (Spinner) findViewById(R.id.listID); Spinner SName = (Spinner) findViewById(R.id.listName); Spinner SMailID = (Spinner) findViewById(R.id.listMailID); Btngetdata = (Button)findViewById(R.id.btngetData); Btngetdata.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new JSONParse().execute(); } }); } private class JSONParse extends AsyncTask<String, String, JSONObject> { private ProgressDialog pDialog; @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(MainActivity.this); pDialog.setMessage("Getting Data ..."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); } @Override protected JSONObject doInBackground(String... args) { JSONParser jParser = new JSONParser(); // Getting JSON from URL JSONObject json = jParser.getJSONFromUrl(url); return json; } @SuppressWarnings("deprecation") @Override protected void onPostExecute(JSONObject json) { pDialog.dismiss(); if(json != null) { try { // Getting JSON Array user = json.getJSONArray(TAG_USER); JSONObject c = user.getJSONObject(0); for (int i = 0; i < user.length(); i++) { UID.add(user.getJSONObject(i).getString(TAG_ID.toString())); Name.add(user.getJSONObject(i).getString(TAG_NAME.toString())); MailID.add(user.getJSONObject(i).getString(TAG_EMAIL.toString())); } //Set JSON Data in TextView ArrayAdapter<String> IDAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, UID); IDAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); SID.setAdapter(IDAdapter); ArrayAdapter<String> NameSource = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, Name); NameSource.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); SName.setAdapter(NameSource); ArrayAdapter<String> MailIDSource = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, MailID); MailIDSource.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); SMailID.setAdapter(MailIDSource); } catch (JSONException e) { e.printStackTrace(); } } else { AlertDialog alertDialog = new AlertDialog.Builder( MainActivity.this).create(); // Setting Dialog Title alertDialog.setTitle("Alert Dialog"); // Setting Dialog Message alertDialog.setMessage("Welcome to AndroidHive.info"); // Setting Icon to Dialog alertDialog.setIcon(null); // Setting OK Button alertDialog.setButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // Write your code here to execute after dialog closed Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show(); } }); // Showing Alert Message alertDialog.show(); } } } } This is the ERROR i get 11-26 23:38:06.038: E/AndroidRuntime(26316): FATAL EXCEPTION: main 11-26 23:38:06.038: E/AndroidRuntime(26316): java.lang.NullPointerException 11-26 23:38:06.038: E/AndroidRuntime(26316): at learn2crack.asynctask.MainActivity$JSONParse.onPostExecute(MainActivity.java:122) 11-26 23:38:06.038: E/AndroidRuntime(26316): at learn2crack.asynctask.MainActivity$JSONParse.onPostExecute(MainActivity.java:1) 11-26 23:38:06.038: E/AndroidRuntime(26316): at android.os.AsyncTask.finish(AsyncTask.java:631) 11-26 23:38:06.038: E/AndroidRuntime(26316): at android.os.AsyncTask.access$600(AsyncTask.java:177) 11-26 23:38:06.038: E/AndroidRuntime(26316): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644) 11-26 23:38:06.038: E/AndroidRuntime(26316): at android.os.Handler.dispatchMessage(Handler.java:99) 11-26 23:38:06.038: E/AndroidRuntime(26316): at android.os.Looper.loop(Looper.java:137) 11-26 23:38:06.038: E/AndroidRuntime(26316): at android.app.ActivityThread.main(ActivityThread.java:4745) 11-26 23:38:06.038: E/AndroidRuntime(26316): at java.lang.reflect.Method.invokeNative(Native Method) 11-26 23:38:06.038: E/AndroidRuntime(26316): at java.lang.reflect.Method.invoke(Method.java:511) 11-26 23:38:06.038: E/AndroidRuntime(26316): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 11-26 23:38:06.038: E/AndroidRuntime(26316): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 11-26 23:38:06.038: E/AndroidRuntime(26316): at dalvik.system.NativeStart.main(Native Method) A: You have already declared public class MainActivity extends Activity { Spinner SID; Spinner SName; Spinner SMailID; So Change this Spinner SID = (Spinner) findViewById(R.id.listID); Spinner SName = (Spinner) findViewById(R.id.listName); Spinner SMailID = (Spinner) findViewById(R.id.listMailID); // becomes local to onCreate. to SID = (Spinner) findViewById(R.id.listID); SName = (Spinner) findViewById(R.id.listName); SMailID = (Spinner) findViewById(R.id.listMailID);
{ "pile_set_name": "StackExchange" }
Q: Why does an executable give an error when opened in $tool? I have an executable that runs in the operating system, but when when I open it in $tool I get an error. What is going on? A: This is caused by a differences in the operating system's loader and the file format parsing code in the tool you are using. Malicious program authors often exploit differences between an executable file format's specification and how the file format is actually used by the loader in practice. If there are differences between the file format specification and the operating system loader, there exist executables which will run but are not legal according to the specification! For example, up until Windows Vista a PE executable can be missing several header fields and the Window's loader will still load it. It's likely your tool was written by looking at the file format specification and not at the implementation of the loader and thus cannot necessarily handle all executables which are successfully loaded by the operating system. In reality an executable file format is specified in three categories of places: the formal file format specification the implementation of the operating system's loader the implementation of third party tools These three things often differ in very subtle ways and malicious program authors take advantage of this fact. Just remember that the ultimate arbiter for whether something is a valid executable or not is the loader. If the executable runs but your tools are failing, your tools do not take into account the real-world behavior of the operating system loader. The best work documenting this phenomena that I am aware of is by Ange Albertini for the PE executable file format.
{ "pile_set_name": "StackExchange" }
Q: Issues with calling a function that has to wait for a server response So I have the following code in my view controller that works perfectly. I make the json request, the server call is made and I get the response no issues. My function is called on a button click: @IBAction func buttonClick(sender: AnyObject) { var postsEndpoint = "http://test.com/test" let test = ["Blah":"test"] request(.POST, postsEndpoint, parameters: test as! [String : AnyObject] , encoding: .JSON) .responseJSON { (request, response, data, error) in if let anError = error { // got an error in getting the data, need to handle it println("error calling POST on /posts") println(error) } else if let data: AnyObject = data { let post = JSON(data) // now we have the results, let's just print them though a tableview would definitely be better UI: println("The post is: " + post.description) } } } So now I want to make a class that I can use for calling all my services. So I have then created a function in this class that I am calling from my view controller using let invoke = WebServiceCall() let jsonrequest = invoke.InvokeService() So my class and function are class WebServiceCall{ var post:JSON = nil func InvokeService(type : String) ->JSON{ var postsEndpoint = "http://test.com/test" let test = ["Blah":"test"] request(.POST, postsEndpoint, parameters: test as! [String : AnyObject] , encoding: .JSON) .responseJSON { (request, response, data, error) in if let anError = error { // got an error in getting the data, need to handle it println("error calling POST on /posts") println(error) } else if let data: AnyObject = data { self.post = JSON(data) // now we have the results, let's just print them though a tableview would definitely be better UI: println("The post is: " + post.description) } } return self.post } I think my issue is that the function is called but because there is no completion handler to wait for the response that I never get the data returned. I have googled completion handlers but I am getting confused. Any help would be great thx A: var post:JSON = nil func InvokeService(type : String) ->JSON{ var postsEndpoint = "http://test.com/test" let test = ["Blah":"test"] request(.POST, postsEndpoint, parameters: test as! [String : AnyObject] , encoding: .JSON) .responseJSON { (request, response, data, error) in if let anError = error { // got an error in getting the data, need to handle it println("error calling POST on /posts") println(error) } else if let data: AnyObject = data { self.post = JSON(data) // now we have the results, let's just print them though a tableview would definitely be better UI: println("The post is: " + post.description) } } return self.post } Change this to var post:JSON = nil func InvokeService(type : String, compHandler: (NSRequest, NSresponse, NSData, NSError) -> Void){ var postsEndpoint = "http://test.com/test" let test = ["Blah":"test"] request(.POST, postsEndpoint, parameters: test as! [String : AnyObject] , encoding: .JSON) .responseJSON { (request, response, data, error) in compHandler(request, response, data, error) } } And then you can call this method NOTE: This code has not been tested. so maybe you need to change a little bit.
{ "pile_set_name": "StackExchange" }
Q: Angular 7 Set Background Image from API data I have a couple of cards that pull data from an API and then loop over the data to display the cards in the front end. each card has an image associated to it that I'd like to set as a background image for each specific card. <div *ngFor ='let package of packages; let i = index' [attr.data-index]="i"> <div class="card"> <div class="card-header" style="background-image:url("{{packages[i].destinations.image}}")">{{packages[i].destinations.destname}}</div> <div class="price">{{packages[i].destinations.hotelrating}}</div> </div> </div> this is obviously not working. i search on the forum but cannot find any method that shows how to handle setting background images for cards getting the data from an API A: What you are missing is adding a dynamic CSS style attribute. Angular supports adding dynamic CSS style attributes to any element while at runtime. For that, you can use the one of the below arrangements: <div [ngStyle]="{background: 'url('+ packages[i].destinations.image + ')'}"></div> Or <div [style.background]="'url('+ packages[i].destinations.image + ')'"></div> Or else if you want add dynamic css class depending upon conditions you can use below : <div [ngClass]="{ 'class1': condition, 'class2': !condition }"
{ "pile_set_name": "StackExchange" }
Q: Get specific numbers from string In my current project I have to work alot with substring and I'm wondering if there is an easier way to get out numbers from a string. Example: I have a string like this: 12 text text 7 text I want to be available to get out first number set or second number set. So if I ask for number set 1 I will get 12 in return and if I ask for number set 2 I will get 7 in return. Thanks! A: This will create an array of integers from the string: using System.Linq; using System.Text.RegularExpressions; class Program { static void Main() { string text = "12 text text 7 text"; int[] numbers = (from Match m in Regex.Matches(text, @"\d+") select int.Parse(m.Value)).ToArray(); } }
{ "pile_set_name": "StackExchange" }
Q: How to deal with questions for which the correct answer is simply "no"? I encountered How can I set Dkim in phpmailer? recently. The correct answer is simply: You can't. Oh, of course I might quote some parts of feature request on Drupal.org and describe with detail why it was moved from 6 to 7 branch, but it really looks like a material for commentary more than an answer. On the other hand, question seems legit, if not of high quality. No close reason really really fits. So what should I do when I see questions like that? A: It will vary by question, but "no" answers are perfectly acceptable. Explain why it can't be done. Suggest alternate solutions. If possible, outline how a patch could be done.
{ "pile_set_name": "StackExchange" }
Q: Instanciando uma classe podendo utilizá-la em todas as funções da mesma classe Gostaria de saber se eu posso instanciar uma outra classe apenas uma vez e utilizá-la em todos as outras funções da minha classe atual. Código de exemplo: require ('model.php'); class search{ function __construct(){ $objModel = new Model();} function insert(){ $nome = "Alguém"; $objModel->inserir($nome);} function select(){ $idade = 30; $objModel->buscar($idade);} } Quando tento fazer isso retorna um erro informando que as variáveis $objModel que estão dentro dos métodos não foram inicializadas. Gostaria de resolver isso sem ter que colocar um $objModel = new Model() em cada função, se é que é possível. A: Tente declarar a variável $objModel como um atributo da classe e fazer chamada usando o $this->objModel: class search{ private $objModel; function __construct(){ $this->objModel = new Model(); } function insert(){ $nome = "Alguém"; $this->objModel->inserir($nome); } function select(){ $idade = 30; $this->objModel->buscar($idade); } }
{ "pile_set_name": "StackExchange" }
Q: Civivolunteer Declaration of CRM_Volunteer_Permission Line 221 ClassLoader.php Drupal 7.67 Civicrm 5.15.2 Civivolunteer 4.7.31-2.3.1 I am getting the following message on a number of screens: Warning: Declaration of CRM_Volunteer_Permission::check($permissions) should be compatible with CRM_Core_Permission::check($permissions, $contactId = NULL) in require_once() (line 221 of /home/mysite/public_html/members/drupal/sites/all/modules/civicrm/CRM/Core/ClassLoader.php). The biggest issue is the volunteer sign up screen. Any ideas? A: Its a compatibility issue of Civi-Volunteer extension with latest version of CiviCRM. The new version of Civi-Volunteer is still not available but this issue is already fixed in code repository. You can apply patch from here. Cheers Pradeep
{ "pile_set_name": "StackExchange" }
Q: Spring MVC 3.2.4 @RequestMapping don't work Try to create restful service with spring mvc, but can't get access to it. After read tons of answers here all seems right, maybe you can see something. 21.09.2013 10:50:33 org.springframework.web.servlet.DispatcherServlet noHandlerFound WARNING: No mapping found for HTTP request with URI [/rest/book] in DispatcherServlet with name 'mvc-dispatcher' web.xml <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0" metadata-complete="true"> <servlet> <servlet-name>mvc-dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextClass</param-name> <param-value> org.springframework.web.context.support.AnnotationConfigWebApplicationContext </param-value> </init-param> <init-param> <param-name>contextConfigLocation</param-name> <param-value> ru.expbrain.flib.config.RestConfig </param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>mvc-dispatcher</servlet-name> <url-pattern>/rest/*</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.hmtl</welcome-file> </welcome-file-list> </web-app> RestConfig.java package ru.expbrain.flib.config; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration @EnableWebMvc @ComponentScan(basePackages = {"ru.expbrain.flib.rest.controller"}) public class RestConfig extends WebMvcConfigurerAdapter { } BookController.java package ru.expbrain.flib.rest.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import ru.expbrain.flib.rest.entity.Book; import java.util.concurrent.atomic.AtomicLong; @Controller public class BookController { private final AtomicLong counter = new AtomicLong(); @RequestMapping(value="/book", method = RequestMethod.GET) public @ResponseBody Book greeting(@RequestParam(value="content", required=false, defaultValue="World") String name) { return new Book(counter.incrementAndGet(), name); } } Try to get content over path, btw root context path go to / http://localhost:9080/rest/book A: Thank you Sotirios Delimanolis for testing. This was some problem with caching... can't explain what happen, because it wasn't repair with cleaning... but recreate the project help and all seems fine.
{ "pile_set_name": "StackExchange" }
Q: How to use a String instead of an Interger with an IF statement in a C# Console program? I have been learning the basics of C# with a Console Application. I was wondering if anyone knew how to use an IF statement with a String instead of an integer. It's a bit annoying and I need it so I can compare a value the user has outputted to the console. This is because the Console.ReadLine(); only likes Strings and not Integers. Below is my code: string num = Console.ReadLine(); if (num == 9) { Console.WriteLine("Ooh my number is 9"); } Any help is appreciated! A: You should always validate integer user input with TryParse int.TryParse Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the operation succeeded. string value = Console.ReadLine(); if(!int.TryParse(value, out var num)) { Console.WriteLine("You had one job!"); } else if (num == 9) { Console.WriteLine("Ooh my number is 9"); }
{ "pile_set_name": "StackExchange" }
Q: Set Focus on a Textbox - MVC3 How can I set focus on "Amount" textbox on page load for the following Razor code in MVC3? <tr> <th> <div class="editor-label"> @Html.LabelFor(model => model.Amount) </div> </th> <td> <div class="editor-field"> @Html.EditorFor(model => model.Amount) @Html.ValidationMessageFor(model => model.Amount) </div> </td> </tr> A: You could provide an additional class to the containing div: <div class="editor-field focus"> @Html.EditorFor(model => model.Amount) @Html.ValidationMessageFor(model => model.Amount) </div> and then you could use a jQuery class selector: $(function() { $('.focus :input').focus(); }); This being said you seem to have multiple Amount texboxes in a table and obviously only one can have the focus at a time. So assuming you want this to be the first, you could do this: $('.focus :input:first').focus(); A: with a html 5 compliant browser you set the autofocus <input type="text" autofocus="autofocus" /> if you need IE support you need to do it with javascript <input type="text" id=-"mytextbox"/> <script type="text/javascript">document.getElementById('mytextbox').focus();</script> in razor: @Html.EditorFor(model => model.Amount,new{@autofocus="autofocus"}) A: Open the /Views/Shared/Site.Master file and enter the following after the jquery script include this script: <script type="text/javascript"> $(function () { $("input[type=text]").first().focus(); }); </script> This will set the focus to first textbox on every form in the app without writing any additional code!
{ "pile_set_name": "StackExchange" }
Q: C++ reference & const pointers in C/C++ Recently while I was explaining the basic difference between pointers and references(in context of C++ programming) to someone, I told the usual explanations which talk about different function argument passing conventions - Call by value, Call by pointer, Call by reference, and all the associated theory about references. But then I thought whatever a C+ reference does in terms of argument passing,(Allows a memory efficient way of passing large structures/objects, at same time keeps it safe by not allowing the callee to modify any variables of the object passed as reference, if our design demands it) A const pointer in C would achieve the same thing , e.g. If one needs to pass a structure pointer say struct mystr *ptr, by casting the structure pointer as constant - func(int,int,(const struct mystr*)(ptr)); will ptr not be some kind of equivalent to a reference? Will it not work in the way which would be memory efficient by not replicating the structure(pass by pointer) but also be safe by disallowing any changes to the structure fields owing to the fact that it is passed as a const pointer. In C++ object context, we may pass const object pointer instead of object reference as achieve same functionality) If yes, then what use-case scenario in C++, needs references. Any specific benefits of references, and associated drawbacks? thank you. -AD A: You can bind a const reference to an rvalue: void foo(const std::string& s); foo(std::string("hello")); But it is impossible to pass the address of an rvalue: void bar(const std::string* s); bar(&std::string("hello")); // error: & operator requires lvalue References were introduced into the language to support operator overloading. You want to be able to say a - b, not &a - &b. (Note that the latter already has a meaning: pointer subtraction.) References primarily support pass by reference, pointers primarily support reference semantics. Yes I know, the distinction isn't always quite clear in C++. A: There are two typical use-case scenarios: First: Pointers denote optional arguments. Since, references cannot be NULL, but pointers can, document in the coding style that any argument that is notated as pointer, may be NULL, the function needs to handle that. Optional arguments can then be const or non-const, as can mandatory (reference) arguments. Second: References are only used in conjunction with the const keyword, because the calling syntax suggests to the reader pass-by-value semantics, which is by definition constant. Then pointers are only used for arguments that can be changed by the callee. I personally prefer the first option, because there each of the four cases "const reference", "non-const reference", "const pointer", "non-const pointer" has a different meaning. Option two only differentiates between two "things": "function may modify that value" vs. "function will not modify that value".
{ "pile_set_name": "StackExchange" }
Q: Indexing columns to make a MySQL query faster I have this query here that I am trying to make more efficient as it is taking an extremely long amount of time, about 40s on 3 million records. The query basically takes X amount of rows per company and turns them into columns for a given existing column. SQLFiddle SET @sql = NULL; SET @sql1 = NULL; SET @sql2 = NULL; SET @sql3 = NULL; SET @sql4 = NULL; SET @sql5 = NULL; SELECT GROUP_CONCAT(DISTINCT CONCAT( 'max(case when year = ', year, ' then experience_rate end) AS `', year, '-Pen`' ) ORDER BY year ) INTO @sql1 FROM spooner_pec; SELECT GROUP_CONCAT(DISTINCT CONCAT( 'max(case when year = ', year, ' then mco_name end) AS `', year, '-MCO`' ) ORDER BY year ) INTO @sql2 FROM spooner_pec; SELECT GROUP_CONCAT(DISTINCT CONCAT( 'max(case when year = ', year, ' then premium_range end) AS `', year, '-Prem`' ) ORDER BY year ) INTO @sql3 FROM spooner_pec; SELECT GROUP_CONCAT(DISTINCT CONCAT( 'max(case when year = ', year, ' then employer_rating_plan end) AS `', year, '-Rating`' ) ORDER BY year ) INTO @sql4 FROM spooner_pec; SELECT GROUP_CONCAT(DISTINCT CONCAT( 'max(case when year = ', year, ' then risk_group_number end) AS `', year, '-Gr Num`' ) ORDER BY year ) INTO @sql5 FROM spooner_pec; SET @sql = CONCAT( 'SELECT policy_number AS PolicyNumber, coverage_status_code As CoverageStatusCode, primary_name AS PrimaryName, primary_dba_name AS DBA, address1 AS Address1, address2 AS Address2, city AS CityName, state AS StateID, zipcode AS ZipCode, zip_plus_four AS ZipCode4, business_area_code AS PhoneAreaCode, business_phone AS PhoneNumber, business_extension AS PhoneExtension, business_contact_first_name AS FirstName, business_contact_last_name AS LastName, county_description AS County, ', @sql1, ', ', @sql2, ',', @sql3, ',', @sql4, ',', @sql5, ' FROM spooner_pec GROUP BY policy_number'); PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; One of my coworkers mentioned indexing but I think the columns that are taking the longest are the ones that I am creating to pivot the data. Is there any way to index those? A: Currently your code scans the spooner_pec table 6 times, once each for the year-based columns, and again for the final result. You can reduce this to just 2 times by caching the list of years in a temp table: CREATE TEMPORARY TABLE GotYears (year varchar(10)); INSERT INTO GotYears SELECT DISTINCT year FROM spooner_pec Now you have a small table with just a few years in it, instead of 3,000,000 records. You have scanned the table just once to do that too. Now use that table to build your SQL select clauses.... SELECT GROUP_CONCAT(CONCAT( 'max(case when year = ', year, ' then experience_rate end) AS `', year, '-Pen`' ) ORDER BY year ) INTO @sql1 FROM GotYears; Having made that recommendation, though, I also recommend having an index on the year column which will make the scan a whole lot faster too. The query is still really ugly ™ but that's a problem in your application and data storage. Additionally, your final query is horrible, horrible, and horrible. A group-by query with many columns, but only grouping by the policy_id is very messy, and is MySQL specific. The values returned in the other columns are unspecified in terms of behaviour. I hope all your values in all the columns are the same or otherwise your output values are unspecified. It is a problem with your database structure too, that the data is not normalized. Why do you record the same values for the same policies in multiple records? Your database may be a data warehouse, but even then it is a bit of a mess. You should audit your tables, and reconsider the design and normalization of your tables. Still, if you apply the changes I suggest (add the year index, and have a single temp table for the year values), then I imagine your query will execute in about 5 seconds instead of 30.
{ "pile_set_name": "StackExchange" }
Q: Add text to speak before announcing label's text I have a label in my app that the user should be able to tap on with VoiceOver enabled to have it speak the text of that label. However, I want it to always say something before it reads the label's text. I tried to set the accessibilityLabel via self.displayLabel.accessibilityLabel = "my text here" + self.displayLabel.text! but this results in it always being set to the label's original text value which is always changing in this app. How can I add text to announce just before the label's content, ensuring it will always speak the label's current text contents? A: Override the accessibilityLabel property in the UILabel subclass to return whatever you'd like. override var accessibilityLabel: String! { get { return "my text here" + "," + self.text! } set { } } You may want to post an announcement each time the text changes to inform VO users the value has changed.
{ "pile_set_name": "StackExchange" }
Q: cant use external js with angular2 Im trying to import the twitter-bootstrap-wizard javascript library to my angular 2 project but always getting this error: WEBPACK_IMPORTED_MODULE_1_jquery(...).bootstrapWizard is not a function I just create a new angualr app using the angular-cli 1.0.0 then add the scripts in the index.html like: <body> <app-root>Loading...</app-root> <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap-wizard/1.2/jquery.bootstrap.wizard.js"></script> </body> Then in my component: // declare var bootstrapWizard : any; import * as $ from 'jquery'; // ngAfterViewInit() { (<any>$('#wizard')).bootstrapWizard() } A: if you using cdn, just add declare declare const jQuery: any; or you can remove cdn, then install jquery from npm, then use your import npm i --save jquery import * as $ from 'jquery';
{ "pile_set_name": "StackExchange" }
Q: How can I run a gradle based Libgdx eclipse project in AIDE on Android? Before Gradle was used with libgdx I could just open my Eclipse project in AIDE and everything worked fine. As of libgdx version 1.0 I now use Gradle in Eclipse but I don't know how to get this to work with AIDE. It's not finding the jar libraries because I get compile errors about unknown libgdx classes. Do I have to add a local Maven repository or is there another way? Thanx! A: I had similar issues, and what worked for me is I started a libgdx project within AIDE (yes it has that function), let it set itself up properly with all the libraries etc in the lib folder, then copied my code into the respective core, android etc folders as appropriate. It's a bit fiddly, and I'm still not 100% there yet as I'm trying to work off two git branches, one for laptop (with gradle, your original project), and one for AIDE (with all the libraries already in it) It should at least help you get your project working.
{ "pile_set_name": "StackExchange" }
Q: Why did these plants wither? It's the middle of summer and I like to plant melons since they bring in some good money. For some reason, two of them withered even though they get watered everyday by my iridium sprinkler. Why did they wither? The season hasn't changed with them planted (it's day 14 in my current summer). The same thing happened earlier with my poppy flowers as well which are also watered by a sprinkler. A: Since you said that you think there was a thunderstorm recently, your plants may have died because lightning struck your crops. From this thread: Lightning storm could of struck the crop? It is most probably a lightning, because it has just happened to me. I still dont have rods and a day after a terrible two day storm one of my crops its just dead. In order to prevent this, you'll need to build a lightning rod somewhere on your farm. It's worth noting that this won't completely protect your crops (apparently prior to build 1.07, they did virtually nothing to help). The exact placement of the rod on The Farm has no bearing on the chance to intercept a lightning strike, rods do not protect a specific area. They have about a 50% chance to be struck. As of patch 1.07: Lightning is more likely to strike trees than crops, but a Lightning Rod now has a very good chance of intercepting lightning strikes (if they aren't already processing a lightning bolt) It is also not necessary to be on the farm while the lightning strike happens. As an aside, you can tell that it wasn't due to crows, as they will eat your crops, not leave a dead one.
{ "pile_set_name": "StackExchange" }
Q: Union order in Linq to Entities I have a problem with EDM model Union select. I have the records in db with uniqe Ids. For example id list: 1, 2, 3, 4, 5, 6, 7, 8, 9 I need to select, for example, record #6 and 2 records before #6 and 2 records past #6. In select result it should be 4,5,6,7,8 I made this next way: public IQueryable<photos> GetNextPrev(Int64 photoid, string userlogin) { var p1 = (from m in db.photos where m.id < photoid && m.userlogin == userlogin orderby m.id descending select m).Take(2).Skip(0); var p2 = (from m in db.photos where m.id >= photoid && m.userlogin == userlogin orderby m.id descending select m).Take(3).Skip(0); return (p1.Union(p2)); } But the ordering is not like in the example... Thanks for the help! A: It's because of the latter Union, you cannot guarantee order with it. You want to do this on your return: return (p1.Union(p2).OrderByDescending(m => m.id)); Update With further understanding of the issues, I think this will take care of it: public IQueryable<photos> GetNextPrev(Int64 photoid, string userlogin) { var p1 = (from m in db.photos where m.id < photoid && m.userlogin == userlogin orderby m.id descending select m).Take(2).Skip(0); var p2 = (from m in db.photos where m.id >= photoid && m.userlogin == userlogin orderby m.id select m).Take(3).Skip(0); return (p1.Union(p2).OrderBy(m => m.id)); } A: You can't assume any ordering. You always need an OrderBy if you want things ordered. return p1.Union(p2).OrderBy(p=> p.id);
{ "pile_set_name": "StackExchange" }
Q: caffe: what does BACKEND and SCALE mean in data layer definition? I'm a fresh guy to caffe. and was following mnsit handwritten digits recognize example. when seeing layer { name: "mnist" type: "Data" transform_param { scale: 0.00390625 } data_param { source: "mnist_train_lmdb" backend: LMDB batch_size: 64 } top: "data" top: "label" } I was confused by the parameters. Could somebody explain what does the backend and scale parameter means? and where can I find the definition of such params? Thank you! A: When facing confusing parameters in caffe's prototxt, you can always look at the $CAFFE_ROOT/src/caffe/caffe.proto file that defines the parameters. Most values have comments explaining them. As for the parameters in your question, Caffe supports two types of datasets for the "Data" layer: lmdb and leveldb. The backend paramter allows you to specify what type is your input dataset LEVELDB or LMDB. The scale parameter is part of the transform_param, the comment in caffe.proto reads: // For data pre-processing, we can do simple scaling and subtracting the // data mean, if provided. Note that the mean subtraction is always carried // out before scaling.
{ "pile_set_name": "StackExchange" }
Q: How to set both VM Params and Program args using exec-maven-plugin? I am using exec-maven-plugin to run java app. I need to pass both JVM params and program arguments. I am setting JVM params like this: <artifactId>exec-maven-plugin</artifactId> <version>1.6.0</version> <executions> <execution> <id>MyId</id> <goals> <goal>java</goal> </goals> <configuration> <mainClass>MyClass</mainClass> <arguments> <argument>-XX:+UseG1GC</argument> <argument>-Xms2G</argument> <argument>-Xmx2G</argument> </arguments> </configuration> </execution> ... and run the program: mvn exec:java@MyId -Dexec.args="my params" However it looks like arguments set in pom.xml are not used and overwritten by -Dexec.args, and section is used only as program arguments. Tried to add into arguments (as shown in this article), but ran into Unable to parse configuration of mojo org.codehaus.mojo:exec-maven-plugin:1.6.0:java for parameter arguments: Cannot store value into array: ArrayStoreException -> [Help 1] Found similar unresolved problem on jboss.org. Any suggestions? A: Found the answer for my question on the plugin page - at the very end of it. This goal helps you run a Java program within the same VM as Maven. The goal goes to great length to try to mimic the way the VM works, but there are some small subtle differences. Today all differences come from the way the goal deals with thread management. Note: The java goal doesn't spawn a new process. Any VM specific option that you want to pass to the executed class must be passed to the Maven VM using the MAVEN_OPTS environment variable. That doesn't work for me, so switching to mvn exec:exec mode. works for JVM params there. Found a solution here: Using Maven 'exec:exec' with Arguments
{ "pile_set_name": "StackExchange" }
Q: How to set set capability for chrome in selenium? How to use this method? What parameter should I pass to "capabilityName" and "value"? public void setCapability(java.lang.String capabilityName,java.lang.String value); A: For Chrome specifically, you can find the capabilities here: https://sites.google.com/a/chromium.org/chromedriver/capabilities-aka-chromeoptions There is a more general overview of capabilities on the selenium wiki: http://code.google.com/p/selenium/wiki/DesiredCapabilities
{ "pile_set_name": "StackExchange" }
Q: Man with saucer shaped machine that may or may not been a time travel machine What is name of (TV?) Movie (possibly british) from between 1970-1980's involving a man with saucer shaped machine that may or may not been a time travel machine? I am trying to remember a film I saw about 30 or 35 years ago on TV in Australia. I remember VERY little as I was around 10 years old or less at the time. Here is a list of what I DO remember: it was science fiction. there was an odd/possibly eccentric man. Could have been from the future or another planet. the man had some kind of craft that (I think) was shaped like a small, one man flying saucer. It may or may not have been able to travel in time. I believe there was some green colouring or lighting effect associated with the craft. the man may have worn a wide brim hat. Sorry, that is all I've got to go on :( I do not recall any plot. It might have been a TV movie or a failed series pilot. I do not believe any alien/creature was involved. I think all the protagonists were human or at least human-like. The whole thing could have been made on a BBC budget. A: As discussed in the comments this appears to be The Flipside of Dominick Hide, an episode in the BBC's Play for Today series: Dominick Hide, a time traveller from the year 2130, is studying the London transport system of 1980. Time travellers are supposed to be observers, and are strictly forbidden to land their flying saucers. One time traveller who broke this rule accidentally killed a dog, changing history and causing many future people to disappear. Inspired by his Great Aunt Mavis, Dominick decides to find his great great grandfather. He begins to land in 1980, where his strange clothes and speech make him seem an eccentric oddball. A sequel, Another Flip for Dominick, was broadcast a couple of years after the original episode.
{ "pile_set_name": "StackExchange" }
Q: initializing a typedef struct pointer to NULL #include<stdio.h> typedef struct student{ int id; int mark; }stud; typedef struct stud *s1; void main(){ s1 = NULL; printf("hi"); } Please help me how to initialize struct pointer to NULL. i get the following error during compilation. graph.c: In function ‘main’: graph.c:11:04: error: expected identifier or ‘(’ before ‘=’ token A: You meant to define the variable s1 as stud *s1; Live demo: http://ideone.com/9ThCDi The reason you got the error you did is that you were declaring s1 to be a type for "pointer to struct stud". This is wrong for two reasons: You didn't want s1 to be a type; you wanted it to be an object. Your struct was struct student. But you defined an actual type called stud.
{ "pile_set_name": "StackExchange" }
Q: Upload a large folder to Amazon S3 I know how to upload one single file to Amazon S3, I use this: <?php //include the S3 class if (!class_exists('S3')) require_once('S3.php'); //AWS access info $s3 = new S3(awsAccessKey, awsSecretKey); if ($s3->putObjectFile("movie.mp4", "mybucket", "movie-on-aws.mp4", S3::ACL_PUBLIC_READ)) { echo "<strong>We successfully uploaded your file.</strong>"; } else { echo "<strong>1 Something went wrong while uploading your file... sorry.</strong>"; }?> I have a large 1TB directory of videos I want to upload them on Amazon S3. I tried to loop recursively through each directory and upload each file alone, but it failed. Its just that too many bugs will occur due to file naming, server timeout issues, etc... I want the bucket to mirror my exact directory structure. The folder I want to copy is held on a dedicated server serving Apache. Is there a way I could just upload the folder through the API? It is also 1TB, so what's the best solution? A: Even better, use the official SDKs or CLI tools. https://aws.amazon.com/cli/ http://docs.aws.amazon.com/aws-sdk-php/guide/latest/service-s3.html#uploading-a-directory-to-a-bucket http://docs.aws.amazon.com/aws-sdk-php/guide/latest/feature-s3-stream-wrapper.html Also, if you're using PHP in 2014, but not using Composer, you're doing it wrong.
{ "pile_set_name": "StackExchange" }
Q: ContentValues put method At the db side, checkInTime and checkOutTime are of type TIMESTAMP In my java code also, checkInTime and checkOutTime are of type java.sql.Timestamp For inserting a record into db, i am using this piece of code: 1. ContentValues contentValues=new ContentValues(); 2. contentValues.put(USER_ID, userId); 3. contentValues.put(ROOM_ID, roomId); 4. contentValues.put(CHECK_IN, checkInTime); 5. contentValues.put(CHECK_OUT, checkOutTime); 6. return database.insert(MRM_BOOKING_DETAILS_TABLE, null, contentValues); But i am getting compilation errors at line 4 and 5 since they are not expecting something of type java.sql.Timestamp I can't see any put method of ContentValues which will accept type java.sql.Timestamp in its second parameter. Please suggest how to pass the java.sql.Timestamp in such a case so that i can remove the compilation errors as well. Thanks, A: I would suggest you to use DATETIME instead of TIMESTAMP. Its more general when handling dates and times. Moreover, you can use SimpleDateFormat to parse DATETIME values when inserting or reading from database. final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Updated: Try doing it as below: final SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-ddTHH:mm:ss.SSS"); contentValues.put(CHECK_IN, parser.format(checkInTime)); contentValues.put(CHECK_OUT, parser.format(checkOutTime));
{ "pile_set_name": "StackExchange" }
Q: Temporal distance matrix from dates From a very simple dataframe like time1 <- as.Date("2010/10/10") time2 <- as.Date("2010/10/11") time3 <- as.Date("2010/10/12") test <- data.frame(Sample=c("A","B", "C"), Date=c(time1, time2, time3)) how can i obtain a matrix with pairwise temporal distances (elapsed time in days between samples) between the Samples A, B, C? A B C A 0 1 2 B 1 0 1 C 2 1 0 /edit: changed the format of the dates. sorry for inconveniences A: To get actual days calculations, you can convert the days to a date since some pre-defined date and then use dist. Example below (converted your days, I doubt they were represented how you expected them to be): time1 <- as.Date("02/10/10","%m/%d/%y") time2 <- as.Date("02/10/11","%m/%d/%y") time3 <- as.Date("02/10/12","%m/%d/%y") test <- data.frame(Sample=c("A","B", "C"), Date=c(time1, time2, time3)) days_s2010 <- difftime(test$Date,as.Date("01/01/10","%m/%d/%y")) dist_days <- as.matrix(dist(days_s2010,diag=TRUE,upper=TRUE)) rownames(dist_days) <- test$Sample; colnames(dist_days) <- test$Sample dist_days then prints out: > dist_days A B C A 0 365 730 B 365 0 365 C 730 365 0 Actually dist doesn't need to convert the dates to days since some time, simply doing dist(test$Date) will work for days. A: Using outer() You don't need to work with a data frame. In your example, we can collect your dates in a single vector and use outer() x <- c(time1, time2, time3) abs(outer(x, x, "-")) [,1] [,2] [,3] [1,] 0 1 2 [2,] 1 0 1 [3,] 2 1 0 Note I have added an abs() outside, so that you will only get positive time difference, i.e, the time difference "today - yesterday" and "yesterday - today" are both 1. If your data are pre-stored in a data frame, you can extract that column as a vector and then proceed. Using dist() As Konrad mentioned, dist() is often used for computation of distance matrix. The greatest advantage is that it will only compute lower/upper triangular matrix (diagonal are 0), while copying the rest. On the other hand, outer() forces computing all matrix elements, not knowing the symmetry. However, dist() takes numerical vectors, and only computes some classes of distance. See ?dist Arguments: x: a numeric matrix, data frame or ‘"dist"’ object. method: the distance measure to be used. This must be one of ‘"euclidean"’, ‘"maximum"’, ‘"manhattan"’, ‘"canberra"’, ‘"binary"’ or ‘"minkowski"’. Any unambiguous substring can be given. But we can actually work around, to use it. Date object, can be coerced into integers, if you give it an origin. By x <- as.numeric(x - min(x)) we get number of days since the first day in record. Now we can use dist() with the default Euclidean distance: y <- as.matrix(dist(x, diag = TRUE, upper = TRUE)) rownames(y) <- colnames(y) <- c("A", "B", "C") A B C A 0 1 2 B 1 0 1 C 2 1 0 Why putting outer() as my first example In principle, time difference is not unsigned. In this case, outer(x, x, "-") is more appropriate. I added the abs() later, because it seems that you intentionally want positive result. Also, outer() has far broader use than dist(). Have a look at my answer here. That OP asks for computing Hamming distance, which is really a kind of bitwise distance. A: A really fast solution using a data.table approach in two steps # load library library(reshape) library(data.table) # 1. Get all possible combinations of pairs of dates in long format df <- expand.grid.df(test, test) colnames(df) <- c("Sample", "Date", "Sample2", "Date2") # 2. Calculate distances in days, weeks or hours, minutes etc setDT(df)[, datedist := difftime(Date2, Date, units ="days")] df #> Sample Date Sample2 Date2 datedist #> 1: A 2010-10-10 A 2010-10-10 0 days #> 2: B 2010-10-11 A 2010-10-10 -1 days #> 3: C 2010-10-12 A 2010-10-10 -2 days #> 4: A 2010-10-10 B 2010-10-11 1 days #> 5: B 2010-10-11 B 2010-10-11 0 days #> 6: C 2010-10-12 B 2010-10-11 -1 days #> 7: A 2010-10-10 C 2010-10-12 2 days #> 8: B 2010-10-11 C 2010-10-12 1 days #> 9: C 2010-10-12 C 2010-10-12 0 days
{ "pile_set_name": "StackExchange" }
Q: Trying to put partial in different header I have the following program working fine. But once I get rid of the forward declaration of the primary specialization in bar.h. I got compilation error saying the specialization is not a class template. Why? bar.h: template<typename T> struct Bar{ void bar() { std::cout<< "bar" << std::endl; }; }; //template<typename T> // Looks like I need to forward declare this in order to have it compile and work, why? //struct IsBar; template<typename T> struct IsBar<Bar<T>> { static const bool value = true; }; main.cpp: #include "bar.h" struct Raw{ }; template<typename T> struct IsBar{ static const bool value = false; }; template<typename Obj, bool> struct function{ static void callbar(Obj obj){ obj.bar(); }; }; template<typename Obj> struct function<Obj, false>{ static void callbar(Obj obj){ std::cout<< "no bar()" << std::endl; }; }; int main() { typedef Bar<Raw> Obj; Obj obj; function<Obj, IsBar<Obj>::value> f; f.callbar(obj); return 0; } A: This is because template<typename T> struct IsBar<Bar<T>> { static const bool value = true; }; is a template specialization of the template IsBar<U> for U=Bar<T>. In order to specialize a template, you must first declare the general un-specialized template. Moreover, for this to work properly (for example in SFINAE), you want the general version to contain the value=false: template<typename T> struct IsBar : std::integral_constant<bool,false> {}; template<typename T> struct IsBar<Bar<T>> : std::integral_constant<bool,true> {}; As this functionality is closely related to struct Bar<>, it should be defined within the same header file as struct Bar<>, i.e. bar.h in your case.
{ "pile_set_name": "StackExchange" }
Q: QChart диаграммы не имеет атрибута axisXx Сделал линейный график, по оси х - индексы, по у - значения линии. Сделал дополнительно ось QDateTimeAxis, так как по оси х мне нужны не индексы, а время("yyyy-MM-dd"). scrollbar прокручивает только ось с индексами, QDateTimeAxis нет. Если обратиться к оси QDateTimeAxis #self._chart.axisXx(self._line_tme).setRange(qt[value_min], qt[value_max]) то выходит ошибка: QChart диаграммы не имеет атрибута axisXx Файл с данными для отрисовки находится здесь файл from PyQt5 import QtCore, QtGui, QtWidgets, QtChart from PyQt5.QtCore import * from PyQt5.QtChart import * import math import datetime import time import numpy as np import pandas as pd df = pd.read_csv('file.txt', index_col='DATE', parse_dates=True, infer_datetime_format=True) date = df.iloc[:, 0].index.date z = df.iloc[:, 3].values x = len(z) x_ = x - 1 qt = [None] * x for i in range(0, x): qt[i] = QDateTime(date[i]).toMSecsSinceEpoch() class MainWindow(QtWidgets.QMainWindow): def __init__(self, parent=None): super().__init__(parent) self.step = 30 self._chart_view = QtChart.QChartView() self.scrollbar = QtWidgets.QScrollBar( QtCore.Qt.Horizontal, sliderMoved=self.onAxisSliderMoved, pageStep=self.step, ) self.scrollbar.setRange(0, x_) central_widget = QtWidgets.QWidget() self.setCentralWidget(central_widget) lay = QtWidgets.QVBoxLayout(central_widget) for w in (self._chart_view, self.scrollbar): lay.addWidget(w) self._chart = QtChart.QChart() self._line_serie = QtChart.QLineSeries() self._line_time = QtChart.QLineSeries() for i in range(0, len(z)): c_ = z[i] self._line_serie.append(QtCore.QPointF(i, c_)) self._line_time.append(qt[i], c_) min_x, max_x = 0, x_ self._chart.addSeries(self._line_serie) self._chart.addSeries(self._line_time) axisX = QValueAxis() axisX.setLabelFormat("%d") self._chart.addAxis(axisX, Qt.AlignBottom) self._line_serie.attachAxis(axisX) axisY = QValueAxis() #axisY.setLabelFormat("%f") self._chart.addAxis(axisY, Qt.AlignLeft) self._line_serie.attachAxis(axisY) axisXx = QDateTimeAxis() axisXx.setTickCount(5) axisXx.setFormat("yyyy-MM-dd") self._chart.addAxis(axisXx, Qt.AlignBottom) self._line_time.attachAxis(axisXx) self._chart.legend().hide() self._chart_view.setChart(self._chart) self.lims = np.array([min_x, max_x]) self.onAxisSliderMoved(self.scrollbar.value()) self.adjust_axes(1, 31) def adjust_axes(self, value_min, value_max): if value_min > 0 and value_max > 0 and value_max <= x_ and value_max > value_min: self._chart.axisX(self._line_serie).setRange(value_min, value_max) #self._chart.axisXx(self._line_tme).setRange(qt[value_min], qt[value_max]) @QtCore.pyqtSlot(int) def onAxisSliderMoved(self, value): value2 = value + self.step value1 = value if value2 >= x_: value2 = x_ value1 = value2 - self.step self.adjust_axes(math.floor(value1), math.ceil(value2)) if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) w = MainWindow() w.show() sys.exit(app.exec_()) A: Попробуйте заменить строку: self._chart.axisXx(self._line_tme).setRange(qt[value_min], qt[value_max]) на: self._chart.axisX(self._line_time).setRange( QDateTime(date[value_min]), QDateTime(date[value_max])) Обратите внимание: axisXx <---> axisX _line_tme <---> _line_time, qt[...] <---> QDateTime(date[...])
{ "pile_set_name": "StackExchange" }
Q: Error in Capistrano 3 when building task I am trying to deploy a crm application to digital ocean with Capistrano 3 and sunzi. (FWI Im a novice in rails ) My tasks templates are from this link: **https://github.com/TalkingQuickly/capistrano-3-rails-template I've tried lots of stuff to fix the error below, : I've changed the file extension, I've added code but nothings helping.. Anyone got any Ideas?** ** Invoke production (first_time) ** Execute production ** Invoke load:defaults (first_time) ** Execute load:defaults cap aborted! Don't know how to build task 'deploy:setup_config' (see --tasks) /usr/local/rvm/gems/ruby-2.2.1/gems/rake-10.5.0/lib/rake/task_manager.rb:62:in `[]' /usr/local/rvm/gems/ruby-2.2.1/gems/rake-10.5.0/lib/rake/task.rb:353:in `[]' /usr/local/rvm/gems/ruby-2.2.1/gems/capistrano-3.4.0/lib/capistrano/dsl/task_enhancements.rb:7:in `before' config/deploy.rb:81:in `block in <top (required)>' /usr/local/rvm/gems/ruby-2.2.1/gems/rake-10.5.0/lib/rake/task_manager.rb:209:in `in_namespace' /usr/local/rvm/gems/ruby-2.2.1/gems/rake-10.5.0/lib/rake/dsl_definition.rb:147:in `namespace' config/deploy.rb:71:in `<top (required)>' /usr/local/rvm/gems/ruby-2.2.1/gems/capistrano-3.4.0/lib/capistrano/setup.rb:14:in `load' /usr/local/rvm/gems/ruby-2.2.1/gems/capistrano-3.4.0/lib/capistrano/setup.rb:14:in `block (2 levels) in <top (required)>' /usr/local/rvm/gems/ruby-2.2.1/gems/rake-10.5.0/lib/rake/task.rb:240:in `call' /usr/local/rvm/gems/ruby-2.2.1/gems/rake-10.5.0/lib/rake/task.rb:240:in `block in execute' /usr/local/rvm/gems/ruby-2.2.1/gems/rake-10.5.0/lib/rake/task.rb:235:in `each' /usr/local/rvm/gems/ruby-2.2.1/gems/rake-10.5.0/lib/rake/task.rb:235:in `execute' /usr/local/rvm/gems/ruby-2.2.1/gems/rake-10.5.0/lib/rake/task.rb:179:in `block in invoke_with_call_chain' /usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/monitor.rb:211:in `mon_synchronize' /usr/local/rvm/gems/ruby-2.2.1/gems/rake-10.5.0/lib/rake/task.rb:172:in `invoke_with_call_chain' /usr/local/rvm/gems/ruby-2.2.1/gems/rake-10.5.0/lib/rake/task.rb:165:in `invoke' /home/ubuntu/workspace/tcrm/Capfile:27:in `<top (required)>' /usr/local/rvm/gems/ruby-2.2.1/gems/rake-10.5.0/lib/rake/rake_module.rb:28:in `load' /usr/local/rvm/gems/ruby-2.2.1/gems/rake-10.5.0/lib/rake/rake_module.rb:28:in `load_rakefile' /usr/local/rvm/gems/ruby-2.2.1/gems/rake-10.5.0/lib/rake/application.rb:689:in `raw_load_rakefile' /usr/local/rvm/gems/ruby-2.2.1/gems/rake-10.5.0/lib/rake/application.rb:94:in `block in load_rakefile' /usr/local/rvm/gems/ruby-2.2.1/gems/rake-10.5.0/lib/rake/application.rb:176:in `standard_exception_handling' /usr/local/rvm/gems/ruby-2.2.1/gems/rake-10.5.0/lib/rake/application.rb:93:in `load_rakefile' /usr/local/rvm/gems/ruby-2.2.1/gems/rake-10.5.0/lib/rake/application.rb:77:in `block in run' /usr/local/rvm/gems/ruby-2.2.1/gems/rake-10.5.0/lib/rake/application.rb:176:in `standard_exception_handling' /usr/local/rvm/gems/ruby-2.2.1/gems/rake-10.5.0/lib/rake/application.rb:75:in `run' /usr/local/rvm/gems/ruby-2.2.1/gems/capistrano-3.4.0/lib/capistrano/application.rb:15:in `run' /usr/local/rvm/gems/ruby-2.2.1/gems/capistrano-3.4.0/bin/cap:3:in `<top (required)>' /usr/local/rvm/gems/ruby-2.2.1/bin/cap:23:in `load' /usr/local/rvm/gems/ruby-2.2.1/bin/cap:23:in `<main>' /usr/local/rvm/gems/ruby-2.2.1/bin/ruby_executable_hooks:15:in `eval' /usr/local/rvm/gems/ruby-2.2.1/bin/ruby_executable_hooks:15:in `<main>' Tasks: TOP => production This is my capfile: # https://github.com/capistrano/rbenv # https://github.com/capistrano/chruby # https://github.com/capistrano/bundler # https://github.com/capistrano/rails # #require 'capistrano/rvm' require 'capistrano/rbenv' # require 'capistrano/chruby' require 'capistrano/bundler' require 'capistrano/rails/assets' require 'capistrano/rails/migrations' # Loads custom tasks from `lib/capistrano/tasks' if you have any defined. Dir.glob('/tcrm/lib/capistrano/tasks/*.rake').each { |r| import r } Dir.glob('lib/capistrano/**/*.rake').each { |r| import r } Rake::Task[:production].invoke This is My Deploy.rb file set :application, 'tcrm' set :deploy_user, 'deployer' set :assets_roles, [:app] # setup repo details set :scm, :git set :repo_url, 'https://github.com/mic50771/tcrm.git' # setup rbenv. set :rbenv_type, :system set :rbenv_ruby, '2.1.2' set :rbenv_prefix, "RBENV_ROOT=#{fetch(:rbenv_path)} RBENV_VERSION=#{fetch(:rbenv_ruby)} #{fetch(:rbenv_path)}/bin/rbenv exec" set :rbenv_map_bins, %w{rake gem bundle ruby rails} # how many old releases do we want to keep, not much set :keep_releases, 5 # files we want symlinking to specific entries in shared set :linked_files, %w{config/database.yml config/secrets.yml} # dirs we want symlinking to shared set :linked_dirs, %w{bin log tmp/pids tmp/cache tmp/sockets vendor/bundle public/system} # what specs should be run before deployment is allowed to # continue, see lib/capistrano/tasks/run_tests.cap #set :tests, [] # which config files should be copied by deploy:setup_config # see documentation in lib/capistrano/tasks/setup_config.cap # for details of operations set(:config_files, %w( nginx.conf database.example.yml secret.sample.yml log_rotation unicorn.rb unicorn_init.sh )) # which config files should be made executable after copying # by deploy:setup_config set(:executable_config_files, %w( unicorn_init.sh )) # files which need to be symlinked to other parts of the # filesystem. For example nginx virtualhosts, log rotation # init scripts etc. The full_app_name variable isn't # available at this point so we use a custom template {{}} # tag and then add it at run time. set(:symlinks, [ { source: "nginx.conf", link: "/etc/nginx/sites-enabled/{{full_app_name}}" }, { source: "unicorn_init.sh", link: "/etc/init.d/unicorn_{{full_app_name}}" }, { source: "log_rotation", link: "/etc/logrotate.d/{{full_app_name}}" } ]) # this: # http://www.capistranorb.com/documentation/getting-started/flow/ # is worth reading for a quick overview of what tasks are called # and when for `cap stage deploy` namespace :deploy do # make sure we're deploying what we think we're deploying before :deploy, "deploy:check_revision" # only allow a deploy with passing tests to deployed #before :deploy, "deploy:run_tests" # compile assets locally then rsync after :finishing, 'deploy:cleanup' # remove the default nginx configuration as it will tend # to conflict with our configs. before 'deploy:setup_config', 'nginx:remove_default_vhost' # reload nginx to it will pick up any modified vhosts from # setup_config after 'deploy:setup_config', 'nginx:reload' # Restart monit so it will pick up any monit configurations # we've added # after 'deploy:setup_config', 'monit:restart' # As of Capistrano 3.1, the `deploy:restart` task is not called # automatically. after 'deploy:publishing', 'deploy:restart' end UPDATE: I've updated my gems to 3.10 (they were 3.4.0 before) and I received a different error: /usr/local/rvm/gems/ruby-2.2.1/gems/capistrano-3.1.0/lib/capistrano/i18n.rb:4: warning: duplicated key at line 6 ignored: :starting ** Invoke production (first_time) ** Execute production ** Invoke load:defaults (first_time) ** Execute load:defaults cap aborted! Don't know how to build task 'deploy:setup_config' (see --tasks) /usr/local/rvm/gems/ruby-2.2.1/gems/rake-10.5.0/lib/rake/task_manager.rb:62:in `[]' /usr/local/rvm/gems/ruby-2.2.1/gems/rake-10.5.0/lib/rake/task.rb:353:in `[]' /usr/local/rvm/gems/ruby-2.2.1/gems/capistrano-3.1.0/lib/capistrano/dsl/task_enhancements.rb:5:in `before' config/deploy.rb:81:in `block in <top (required)>' /usr/local/rvm/gems/ruby-2.2.1/gems/rake-10.5.0/lib/rake/task_manager.rb:209:in `in_namespace' /usr/local/rvm/gems/ruby-2.2.1/gems/rake-10.5.0/lib/rake/dsl_definition.rb:147:in `namespace' config/deploy.rb:71:in `<top (required)>' /usr/local/rvm/gems/ruby-2.2.1/gems/capistrano-3.1.0/lib/capistrano/setup.rb:14:in `load' /usr/local/rvm/gems/ruby-2.2.1/gems/capistrano-3.1.0/lib/capistrano/setup.rb:14:in `block (2 levels) in <top (required)>' /usr/local/rvm/gems/ruby-2.2.1/gems/rake-10.5.0/lib/rake/task.rb:240:in `call' /usr/local/rvm/gems/ruby-2.2.1/gems/rake-10.5.0/lib/rake/task.rb:240:in `block in execute' /usr/local/rvm/gems/ruby-2.2.1/gems/rake-10.5.0/lib/rake/task.rb:235:in `each' /usr/local/rvm/gems/ruby-2.2.1/gems/rake-10.5.0/lib/rake/task.rb:235:in `execute' /usr/local/rvm/gems/ruby-2.2.1/gems/rake-10.5.0/lib/rake/task.rb:179:in `block in invoke_with_call_chain' /usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/monitor.rb:211:in `mon_synchronize' /usr/local/rvm/gems/ruby-2.2.1/gems/rake-10.5.0/lib/rake/task.rb:172:in `invoke_with_call_chain' /usr/local/rvm/gems/ruby-2.2.1/gems/rake-10.5.0/lib/rake/task.rb:165:in `invoke' /home/ubuntu/workspace/tcrm/Capfile:27:in `<top (required)>' /usr/local/rvm/gems/ruby-2.2.1/gems/rake-10.5.0/lib/rake/rake_module.rb:28:in `load' /usr/local/rvm/gems/ruby-2.2.1/gems/rake-10.5.0/lib/rake/rake_module.rb:28:in `load_rakefile' /usr/local/rvm/gems/ruby-2.2.1/gems/rake-10.5.0/lib/rake/application.rb:689:in `raw_load_rakefile' /usr/local/rvm/gems/ruby-2.2.1/gems/rake-10.5.0/lib/rake/application.rb:94:in `block in load_rakefile' /usr/local/rvm/gems/ruby-2.2.1/gems/rake-10.5.0/lib/rake/application.rb:176:in `standard_exception_handling' /usr/local/rvm/gems/ruby-2.2.1/gems/rake-10.5.0/lib/rake/application.rb:93:in `load_rakefile' /usr/local/rvm/gems/ruby-2.2.1/gems/capistrano-3.1.0/lib/capistrano/application.rb:24:in `load_rakefile' /usr/local/rvm/gems/ruby-2.2.1/gems/rake-10.5.0/lib/rake/application.rb:77:in `block in run' /usr/local/rvm/gems/ruby-2.2.1/gems/rake-10.5.0/lib/rake/application.rb:176:in `standard_exception_handling' /usr/local/rvm/gems/ruby-2.2.1/gems/rake-10.5.0/lib/rake/application.rb:75:in `run' /usr/local/rvm/gems/ruby-2.2.1/gems/capistrano-3.1.0/lib/capistrano/application.rb:15:in `run' /usr/local/rvm/gems/ruby-2.2.1/gems/capistrano-3.1.0/bin/cap:3:in `<top (required)>' /usr/local/rvm/gems/ruby-2.2.1/bin/cap:23:in `load' /usr/local/rvm/gems/ruby-2.2.1/bin/cap:23:in `<main>' /usr/local/rvm/gems/ruby-2.2.1@global/bin/ruby_executable_hooks:15:in `eval' /usr/local/rvm/gems/ruby-2.2.1@global/bin/ruby_executable_hooks:15:in `<main>' Tasks: TOP => production UPDATE 2: The cap production deploy went through though when I visit my Ip the nginx default page is still there? Any suggestions? A: The link you provided says that capistrano gem version should be 3.1 series but you are using capistrano 3.4.0. In terminal run: bundle clean --force Then in Gemfile paste the lines provided in the link you gave: gem 'capistrano', '~> 3.1.0' # rails specific capistrano funcitons gem 'capistrano-rails', '~> 1.1.0' # integrate bundler with capistrano gem 'capistrano-bundler' # if you are using RBENV gem 'capistrano-rbenv', "~> 2.0" # Use Unicorn as our app server gem 'unicorn' Then run bundle install If error still persists then check my link explaining Deploying Ruby on Rails with Puma and Capistrano to Digital Ocean the complete guide: http://sulmanbaig.com/blog/deploy-on-digitalocean-rails-puma-nginx For Your Second edit question the answer is: In Capfile put these lines: require 'capistrano/setup' require 'capistrano/deploy' require 'capistrano/rails' require 'capistrano/nginx' And in the end remove other two line and add following line: Dir.glob('lib/capistrano/tasks/*.rake').each { |r| import r } Actually you are callimg tasks of deploy and nginx but they are not require in Capfile.
{ "pile_set_name": "StackExchange" }
Q: Accessing the 3d model using c# script in Unity3d I am developing a software using c# (monodevelop) and unity3d. I am importing a 3d model as collada dae file. Scripts that I wrote must take into account geometry objects in dae file. I am writing some codes but I am new at coding stuff and I can not figure out how I can access geometric objects in dae file using c#. Any help would be very helpful A: Since you said you are new with coding, I will start from the very Unity basics. When you drag and drop your dae file from the project tab into the scene, you will have a GameObject inside the Hierarchy with the same name of dae file. That GameObject can be expanded like Windows Explorer with your all inner objects (they are all GameObjects as well). To access any unique GameObject of your Hierarchy from C#, you do this: GameObject.Find("desired-gameobject-name"); You can also specify the path of your GameObject if its name is not unique: GameObject.Find("GameObject1/GameObject2/Etc"); Most part of time when you want to do anything with a GameObject, you need to deal with Components. It's a very simple Unity concept. GameObject may have Components associated with them. The inspector tab shows all Components used by the selected GameObject. Let's say you want to make a door invisible from your house dae model. You can use something like this: GameObject.Find("HouseModel/Door").GetComponent<Renderer>().enabled = false; Now, if you want something more hardcore like getting vertices data, use the MeshFilter component: Vector3[] vertices = GameObject.Find("HouseModel/Door").GetComponent<MeshFilter>().mesh.vertices; It will return an array of all vertices from this door. I hope it gives you some direction.
{ "pile_set_name": "StackExchange" }
Q: Add new column based on sum of a column and grouped by 2 other columns in Pandas I have the dataframe: df = pd.DataFrame({'Continent':['North America','North America','North America','Europe','Europe','Europe','Europe'], 'Country': ['US','Canada','Mexico','France','Germany','Spain','Italy'], 'Status': ['Member','Non-Member','Non-Member','Member','Non-Member','Member','Non-Member'], 'Units': [27,5,4,10,15,8,8]}) print df Continent Country Status Units 0 North America US Member 27 1 North America Canada Non-Member 5 2 North America Mexico Non-Member 4 3 Europe France Member 10 4 Europe Germany Non-Member 15 5 Europe Spain Member 8 6 Europe Italy Non-Member 8 I need to add 2 columns which are summary statistics about the Continents. I need a column with the sum of Units for Member countries and Non Member countries. so that the final output would look like: Continent Member Units Non-Member Units Country Status Units 0 North America 27 9 US Member 27 1 North America 27 9 Canada Non-Member 5 2 North America 27 9 Mexico Non-Member 4 3 Europe 18 23 France Member 10 4 Europe 18 23 Germany Non-Member 15 5 Europe 18 23 Spain Member 8 6 Europe 18 23 Italy Non-Member 8 It seems like I need to use groupby but I can't figure out how to take the groupby values and re-insert them into the dataframe as new columns. summary_stats = df.groupby(['Continent','Status'])['Units'].sum() print summary_stats Continent Status Europe Member 18 Non-Member 23 North America Member 27 Non-Member 9 Name: Units, dtype: int64 I also tried not using groupby with these: df['Member Units'] = df['Units'][df['Status'] == 'Member'].sum() df['Non-Member Units'] = df['Units'][df['Status'] == 'Non-Member'].sum() but that doesn't differentiate by Continent so it just adds up all the Members and Non-Members Any help is greatly appreicated! A: Once you have summary_stats I think you can do something like: df['Member Units'] = summary_stats[zip(df['Continent'].values, df['Status'].values)] The reason you need to zip the Series values is that df['Continent'] returns a series with indices, but you don't want that to happen.
{ "pile_set_name": "StackExchange" }
Q: Opinions about authentication between application and database tiers I'm puzzling over a technical dilemma where two folks on our team a recommending two different security models each with pros and cons. The greenfield looks like this: We have a an asp.net web app, talking to a business layer, talking to a database. *One of the requirements is to be able to have higher level users delegate business layer rights to other users. One of the folks is lobbying for the capability of an internet user to pass their credentials all the way down into the database so the connection can use an actual sqlserver account for querying, etc. (Some aspects of this I like - auditing capabilities for instance) The alternate approach on hand is to simply go with suite of users,passwords,roles,resources tables in the database, and manage the security up in the business layer. It could be because I come from a java to oracle background where in most cases you use a connection pool that provides connections which were already authenticated using a service type account. Our internet clientele never had actual database accounts. Am I flawed in my thinking that managing delegatable security (by internet users) inside the builtin, internal credentials store that mssql server provides seems fraught with peril security wise? Any one have any recommendations? A: In most web applications, you the security model is defined at the business logic layer, not the data layer. For instance, my ability to edit a post on Stack Overflow is not controlled by my ability to read/write to the "posts" table - in fact, you could probably not even design a database schema that would allow you to implement database-level security at this level. Instead, there's a business logic layer which compares my privileges with the action I'm trying to take (I assume); security is implemented at the business logic layer. I frankly see almost no benefit to passing through credentials to the database layer - if somehow I'd bypassed the business logic for controlling who can edit SO posts, the database "read/write" controls wouldn't prevent it, and auditing wouldn't really help you. I see LOTS of drawbacks - not least the fact you'll be splitting your authorization logic into two (business logic and database), and introduce all kinds of entertaining failure modes with synchronizing accounts across your business logic layer and database layer (users changing their password, or leaving the web site). I can't begin to imagine how you'd sanely test and debug all this - what happens if an end user gets an error related to their database privileges?
{ "pile_set_name": "StackExchange" }
Q: djangorestframework browsable api: how to show all available endpoints urls? In djangorestframework, there is a browsable api. But how do I show a user an entire bird's eye view of all the possible API calls that he/she can make? I can only see one at a time right now and the user would have to already know the correct URL beforehand i.e., http://localhost:8000/users http://localhost:8000/books http://localhost:8000/book/1/author Thank you! A: The answer is as Klahnen said. Use this: https://django-rest-swagger.readthedocs.io/en/latest/ It works out of the box for me and it is exactly what I was hoping for. I still maintain, though, that the term browsable API implies that there is a table of contents available for consumers of your API to see. This app is a lifesaver and perhaps it should be included!
{ "pile_set_name": "StackExchange" }
Q: Manipulating binary C struct data off line I have a practical problem to solve. In an embedded system I'm working on, I have a pretty large structure holding system parameters, which includes int, float, and other structures. The structure can be saved to external storage. I'm thinking of writing a PC software to change certain values inside the binary structure without changing the overall layout of the file. The idea is that one can change 1 or 2 parameter and load it back into memory from external storage. So it's a special purpose hex editor. The way I figures it: if I can construct a table that contains: - parameter name - offset of the parameter in memory - type I should be able to change anything I want. My problem is that it doesn't look too easy to figure out offset of each parameter programmatically. One can always manually to printf their addresses but I'd like to avoid that. Anybody know a tool that can be of help? EDIT The system in question is 32 ARM based running in little endian mode. Compiler isn't asked to pack the structure so for my purpose it's the same as a x86 PC. The problem is the size of the structure: it contains no less than 1000 parameters in total, spreading across multiple level of nested structures. So it's not feasible (or rather i'm not willing to) to write a short piece of code to dump all the offsets. I guess the key problem is parsing the C headers and automatically generate offsets or code to dump their offsets. Please suggest such a parsing tool. Thanks A: The way this is normally done is by just sharing the header file that defines the struct with the other (PC) application as well. You should then be able to basically load the bytes and cast them to that kind of struct and edit away. Before doing this, you need to know about (and possibly handle): Type sizes. If the two platforms are very different (16bit vs 32 bit) etc, you might have differently sized ints/floats, etc. Field alignment. If the compiler/target are different, the packing rules for the fields won't be necessarily the same. You can generally force these to be the same with compiler-specific #pragmas. Endianness. This is something to be careful of in all cases. If your embedded device is a different endianness from the PC target, you'll have to byte swap each field when you load on the PC. If there are too many differences here to bother with, and you're building something quicker/dirtier, I don't know of tools to generate struct offsets automatically, but as another poster says, you could write some short C code that uses offsetof or equivalent (or does, as you suggest, pointer arithmetic) to dump out a table of fields and offsets.
{ "pile_set_name": "StackExchange" }
Q: Referencing AVCaptureSession won't build project in simulator I reference AVCaptureSession an consequently the project will only build for the device. However, I still want to test the rest my app on the simulator as I develop. Do I have to comment out all AVCaptureSession references or is there another way to build for the simulator successfully? A: You have to build it using a device with a camera which means you need either a 3GS or an iPhone 4 or you have to create conditionals to check for the existence of the framework/classes. Or you can comment everything out as you've supposed.
{ "pile_set_name": "StackExchange" }
Q: SLF4JLoggerContext cannot be cast to LoggerContext I get known error: Getting Exception org.apache.logging.slf4j.SLF4JLoggerContext cannot be cast to org.apache.logging.log4j.core.LoggerContext I know that the solution is to remove log4j-to-slf4j from the classpath, as described here: Getting Exception org.apache.logging.slf4j.SLF4JLoggerContext cannot be cast to org.apache.logging.log4j.core.LoggerContext But the project is build with maven and contains spring-boot-starter-web which imports the dependency. I can not get rid from spring-boot-starter-web, and I need log4j. Here is the pom: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>ru.beinteractive</groupId> <artifactId>newlps</artifactId> <packaging>war</packaging> <version>1.0</version> <name>newlps</name> <url>http://maven.apache.org</url> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.0.RELEASE</version> </parent> <dependencies> <dependency> <groupId>com.google.cloud</groupId> <artifactId>google-cloud-storage</artifactId> <version>1.14.0</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>com.jayway.jsonpath</groupId> <artifactId>json-path</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <type>jar</type> </dependency> <dependency> <groupId>com.google.code.externalsortinginjava</groupId> <artifactId>externalsortinginjava</artifactId> <version>0.1.9</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver</artifactId> </dependency> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <type>jar</type> <version>20171018</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-csv</artifactId> <version>1.5</version> <type>jar</type> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot</artifactId> <type>jar</type> </dependency> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> </dependency> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz-jobs</artifactId> <version>2.2.1</version> </dependency> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>com.opera</groupId> <artifactId>operadriver</artifactId> <scope>test</scope> <version>1.5</version> <exclusions> <exclusion> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-remote-driver</artifactId> </exclusion> </exclusions> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>9.4.8.v20171121</version> <configuration> <webAppConfig> <allowDuplicateFragmentNames> true </allowDuplicateFragmentNames> </webAppConfig> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <configuration> <warName>newlps</warName> </configuration> </plugin> </plugins> </build> <repositories> <repository> <id>spring-snapshots</id> <name>Spring Snapshots</name> <url>https://repo.spring.io/snapshot</url> <snapshots> <enabled>true</enabled> </snapshots> </repository> <repository> <id>spring-releases</id> <url>https://repo.spring.io/libs-release</url> <snapshots> <enabled>true</enabled> </snapshots> </repository> <repository> <id>spring-milestones</id> <name>Spring Milestones</name> <url>https://repo.spring.io/milestone</url> <snapshots> <enabled>false</enabled> </snapshots> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>repository.spring.release</id> <name>Spring GA Repository</name> <url>https://repo.spring.io/plugins-release/</url> </pluginRepository> </pluginRepositories> <properties> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> </project> A: In Maven, you can exclude a sub dependency from a dependency. Try this: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-to-slf4j</artifactId> </exclusion> </exclusions> </dependency>
{ "pile_set_name": "StackExchange" }
Q: How can I calculate desired selling price based on margin? I use the following formula to calculate profit margin: $$\text{profit_margin} = \frac{\text{selling_price} - (0.15\cdot \text{selling_price}) - \text{sourcing_cost}}{\text{sourcing_cost}}$$ What would the formula for $\text{selling_price}$ look like if the $\text{profit_margin}=0.3$ and the $\text{sourcing_cost}=16$? Thank you A: Combine selling prices to get $$\frac{\text{selling_price} - (0.15\cdot \text{selling_price}) - \text{sourcing_cost}}{\text{sourcing_cost}}=\frac{0.85\cdot\text{selling_price}- \text{sourcing_cost}}{\text{sourcing_cost}}$$ then multiply both sides of your equation by the denominator and rearrange for the selling price.
{ "pile_set_name": "StackExchange" }
Q: Cannot find RVM upon loading new Bash shell I'm really confused with this RVM Bash not being able to find my directory. This is really killing me. Whenever I load a new bash shell it keeps telling me: -bash: /Users/<username>/.rvm/scripts/rvm : No such file or directory I can't figure out what is wrong with my bash. The following is what my .bashrc looks like: 1 export PATH=/usr/local/bin:/usr/local/sbin:$PATH 2 3 4 export PATH=/usr/local/bin:/usr/local/sbin:/Library/Frameworks/Python.framework/Versions/2.7/bin:/opt/local/bin:/opt/local/sbin:/Users/<username>/.rvm/gems/ruby-1.9.2-p290/bin:/ Users/<username>/.rvm/gems/ruby-1.9.2-p290@global/bin:/Users/<username>/.rvm/rubies/ruby-1.9.2-p290/bin:/Users/<username>/.rvm/bin:/usr/local/bin:/usr/local/sbin:/usr/local/mysq l/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin:/usr/local/git/bin:/usr/local/MacGPG2/bin 5 6 7 # This line for ruby version manager has been commented out 8 PATH=$PATH:$HOME/.rvm/bin # Add RVM to PATH for scripting The following would be my .bash_profile: 6 [[ -s "$HOME/.rvm/scripts/rvm" ]] && . "$HOME/.rvm/scripts/rvm" # Load RVM function 7 8 ## 9 # Your previous /Users/<username>/.bash_profile file was backed up as /Users/<username>/.bash_profile.macports-saved_2011-11-01_at_20:41:30 10 ## 11 12 # MacPorts Installer addition on 2011-11-01_at_20:41:30: adding an appropriate PATH variable for use with MacPorts. 13 export PATH=/opt/local/bin:/opt/local/sbin:$PATH 14 # Finished adapting your PATH environment variable for use with MacPorts. 15 16 17 # Setting PATH for Python 2.7 18 # The orginal version is saved in .bash_profile.pysave 19 PATH="/Library/Frameworks/Python.framework/Versions/2.7/bin:${PATH}" 20 export PATH A: This usually happens with a broken RVM installation. Did you just try to remove RVM or remove ~/.rvm by accident? I would first try removing line 6 in your .bash_profile since the official way to load RVM now seems to be what you have on line 8 of your .bashrc. Also, make sure your .bashrc is actually being loaded. On OS X, .bashrc not loaded by default. Be sure to close all of your Terminal windows and reopen them so all your profile scripts are sourced again and none of them get missed. If it still doesn't work, I would recommend you just install it again with curl -L https://get.rvm.io | bash -s stable
{ "pile_set_name": "StackExchange" }