qid
int64
1
74.7M
question
stringlengths
0
70k
date
stringlengths
10
10
metadata
list
response
stringlengths
0
115k
43,721,320
The following code loops when the page loads and I can't figure out why it is doing so. Is the issue with the onfocus? ``` alert("JS is working"); function validateFirstName() { alert("validateFirstName was called"); var x = document.forms["info"]["fname"].value; if (x == "") { alert("First name must be filled out"); //return false; } } function validateLastName() { alert("validateLastName was called"); var y = document.forms["info"]["lname"].value; if (y == "") { alert("Last name must be filled out"); //return false; } } var fn = document.getElementById("fn"); var ln = document.getElementById("ln"); fn.onfocus = validateFirstName(); alert("in between"); ln.onfocus = validateLastName(); ```
2017/05/01
[ "https://Stackoverflow.com/questions/43721320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7569925/" ]
There were several issues with the approach you were taking to accomplish this, but the "looping" behavior you were experiencing is because you are using a combination of `alert` and `onFocus`. When you are focused on an input field and an alert is triggered, when you dismiss the alert, the browser will (by default) re-focus the element that previously had focus. So in your case, you would focus, get an alert, it would re-focus automatically, so it would re-trigger the alert, etc. Over and over. **A better way to do this is using the `input` event**. That way, the user will not get prompted with an error message before they even have a chance to fill out the field. They will only be prompted if they clear out a value in a field, or if you call the `validateRequiredField` function sometime later in the code (on the form submission, for example). I also changed around your validation function so you don't have to create a validation function for every single input on your form that does the exact same thing except spit out a slightly different message. You should also abstract the functionality that defines *what* to do on each error outside of the validation function - this is for testability and reusability purposes. Let me know if you have any questions. ```js function validateRequiredField(fieldLabel, value) { var errors = ""; if (value === "") { //alert(fieldLabel + " must be filled out"); errors += fieldLabel + " must be filled out\n"; } return errors; } var fn = document.getElementById("fn"); var ln = document.getElementById("ln"); fn.addEventListener("input", function (event) { var val = event.target.value; var errors = validateRequiredField("First Name", val); if (errors !== "") { alert(errors); } else { // proceed } }); ln.addEventListener("input", function (event) { var val = event.target.value; var errors = validateRequiredField("Last Name", val); if (errors !== "") { alert(errors); } else { // proceed } }); ``` ```html <form name="myForm"> <label>First Name: <input id="fn" /></label><br/><br/> <label>Last Name: <input id="ln"/></label> </form> ```
52,267,256
I have a Pandas dataframe, `old`, like this: ``` col1 col2 col3 0 1 2 3 1 2 3 4 2 3 4 5 ``` I want to make a new dataframe, `new`, that copies `col2` from `old` and fills in `-1` as dummy values for its other columns: ``` col2 new_col1 new_col3 0 2 -1 -1 1 3 -1 -1 2 4 -1 -1 ``` I suppose I could do iterate row by row and fill in `-1` for any column not in `old` but figure there must be a better, likely vectorized way. Ideas? Thanks!
2018/09/11
[ "https://Stackoverflow.com/questions/52267256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1316501/" ]
You can do `reindex` . ``` df.reindex(columns=['col2','newcol1','newcol3'],fill_value=-1) Out[183]: col2 newcol1 newcol3 0 2 -1 -1 1 3 -1 -1 2 4 -1 -1 ```
13,142,384
probably had these questions a thousand times already. For a school project I want to make a HTML5 game where you can challenge someone and play against. Now I'm pretty new to game development. I don't now exactly where to start off. There is so much information/technologies on the net that I don't know which to use. I prefer to do this in a known environment (.NET) I found these: * <http://kaazing.com/> * <http://xsockets.net/> I also checked out Node.js, socket.io, HTML5 canvas, etc It's all a bit of overwhelming for me. :(
2012/10/30
[ "https://Stackoverflow.com/questions/13142384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1785932/" ]
Since you're working in a .NET environment, take a look at SignalR, <http://signalr.net>. It's a very nice API around websockets (with fallbacks to other methods for older servers and browsers) that lets you do client-to-server and server-to-client communication. Code on the client can invoke a Javascript function that will in turn invoke a method on the server. That server method could then send a message down to one or all of the connected clients. Alnitak's answer is correct; your communication would be from client to server to client, not directly client to client.
22,127,174
Hello my software should print the abc but unfortunately it does not work I think the problem is related to the line 19 so if someone could tell me why this is happening I appreciate it My code- ``` #include <stdio.h> #include <string.h> #define NUM_ABC_LET 27 void ABC(char abc[NUM_ABC_LET]); int main() { char abcString[NUM_ABC_LET] = ""; ABC(abcString); puts(abcString); } void ABC(char abc[NUM_ABC_LET]) { char letter; for (letter = 'a'; letter <= 'z'; letter++) { strcat(abc, letter); } } ```
2014/03/02
[ "https://Stackoverflow.com/questions/22127174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3318856/" ]
That's because you're just writing to a copy of the string you're passing to the function. Try this: ``` void ABC(char *abc) { int n=0; char letter; for (letter = 'a'; letter <= 'z'; ++letter, ++n) { abc[n] = letter; } abc[n] = '\0'; } ``` This way, you don't write to a copy of your string, you actually write to the string itself.
6,226,081
> > **Possible Duplicate:** > > [Pyramid of asterisks program in Python](https://stackoverflow.com/questions/4911341/pyramid-of-asterisks-program-in-python) > > > I've written a program in C++ that displays a pyramid of asterisk (see below) and now I'd like to see how it's done in Python but it's not as easy as I'd thought it would be. :) Has anyone tried this and if so could you show me code that would help out? 2) Within those lines the number of "\*" will appear as an ODD number (1 ,3 ,5 ,7 ,9 ) this is the output ``` * 1 *** 3 ***** 5 ```
2011/06/03
[ "https://Stackoverflow.com/questions/6226081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/782550/" ]
Disclaimer: This may not work in Python 3.x: ``` Python 2.7.1 (r271:86832, May 27 2011, 21:41:45) [GCC 4.2.1 (Apple Inc. build 5664)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> print ''' * 1 ... *** 3 ... ***** 5''' * 1 *** 3 ***** 5 ```
43,843,463
Within the scope of a new project in Qt/QML, We are currently looking for an application architecture. We are thinking about an implementation of the Flux architecture from Facebook. I found this good library which makes it in some ways : <https://github.com/benlau/quickflux> In our case, we would like to manage Stores and Actions in C++. However, there is a problem in making a Flux implementation for C++. That is the data type to be passed to Dispatcher. C++ is strong type language but Dispatcher allows any kind of data to be passed to the dispatch() function. It could use QVariant type just like what Quick Flux did. But I think C++ developer do not really like this approach. Would you have a way to resolve this problem ? Thanks for you anwsers
2017/05/08
[ "https://Stackoverflow.com/questions/43843463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7979527/" ]
My answer may be outdated, but perhaps will help someone having the same question... You can try to use C++/Qt implementation of Flux-like application pattern <https://github.com/eandritskiy/flux_qt> Please check QML example. There are only 2 classes that are exported to QML engine: ActionProvider and Store. ActionProvider is responsible for the action generation in a whole app (in QML part and in C++ part also). Store provides its properties(that are used in property bindings) to QML elements. All Store properties are changed in a controlled manner in a C++ part. P.S. If you'd prefer pure C++ implementation please check <https://github.com/eandritskiy/flux_cpp> (but be sure that your compiler supports C++17 std::any)
15,214
Today, I reached 200 rep, but 20 of them came from a now-deleted post (a duplicate answer posted really close in time to the first answer). I stopped getting rep from my answers after this was deleted and I hit 180 reputation on posted answers today (180 + the 20 from the deleted = the cap of 200). After a rep recalculation, I will lose the 20 points from that deleted answer (I'm pretty sure). But will the system detect that I made more than 20 points after that and give me any rep from after that? The only reason I care is because I want to reach 20k before the Boston Dev Days... Personal Example: * 200 rep earned to hit cap * 3 more upvotes for 30 "potential rep" * Answer deleted wipes out 2 upvotes to drop down to 180 rep. * Rep limit after recalc **should** come out to 200 with 1 upvote left over due to cap.
2009/08/18
[ "https://meta.stackexchange.com/questions/15214", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/572/" ]
I believe that *in theory* it should work like that, yes. A few times I've had a rep recalc and still had what appeared to be some oddities. Here's a sample timeline: * 2am: 5 genuine votes * 3am: 20 upvotes from one user, hit cap after the first 15 of them * 6am: Get online, post answers, get more upvotes, report vote fraud * 10.30am: Votes are removed, 150 points lost * 11am: Request rep recalc: still not hit rep limit despite having lots of votes In other words, votes that didn't count due to the rep limit being hit for fraud *appeared* not to count after the rep recalc. I had a summary screen for "today" which showed *less* than 200 rep, but still votes that didn't contribute to reputation. I'm not overly bothered and it's a very hard thing to diagnose for certain, but that's at least what I *think* I saw. It does sound very odd, based on what a rep recalc is meant to do... Now, the good news is that all of the votes are recorded so if there *is* a bug in the recalc procedure, when it's fixed and you get another recalc, you'll get the rep back. I believe the *intended* behaviour is for those "wasted" votes to come back into effect after previously-counted votes are deleted, at least.
58,254,657
Consider an array: `10 2 4 14 1 7` Traversing the input array for each valid i, I have to find all the elements which are divisible by the i-th element. So, first I have to find all the elements which are greater than the i-th element. Example output: ``` 10 -> null 2 -> 10 4 -> 10 14 -> null 1 -> 14,4,2,10 7 -> 14,10 ``` My approach: I was thinking of creating a binary tree that would perform a log n operation for each valid insertion in an array that would re-construct the binary tree with the minimum element as root, smaller element on the left and greater element on the right. Now I just have to traverse the right sub-tree of the inserted element and check which elements are divisible by the i-th element. This is a very expensive approach but better than brute-force. Can anyone help to find an optimal solution that would be more efficient?
2019/10/06
[ "https://Stackoverflow.com/questions/58254657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11459802/" ]
you can try this: ``` #include<stdio.h> #include<string.h> int main(){ int i,len,j=0; char mainword[100], reverseword[100]; scanf("%s",mainword); len = strlen(mainword); for(i=len; i>=0; i--){ reverseword[j] = mainword[i-1]; j++; } reverseword[j] = '\0'; if(strcmp(reverseword,mainword)==0){ printf("\nYes"); } else{ printf("\nNo"); } } ```
29,403,878
My Friends, using python 2.7.3 i want to write some ipaddrss in file1.txt manual, each line one ip. how to using python read file1.txt all ipaddress, put it into file2.txt save as file3.txt? file1.txt ``` 1.1.1.1 2.2.2.2 3.3.3.3 ... 5.5.5.5 ... 10.10.10.10 ``` file2.txt ``` :INPUT ACCEPT [0:0] :FORWARD ACCEPT [0:0] :OUTPUT ACCEPT [0:0] -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT -A INPUT -p icmp -j ACCEPT -A INPUT -i lo -j ACCEPT -A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT -A INPUT -p udp -m udp --dport 137 -j ACCEPT -A INPUT -p udp -m udp --dport 138 -j ACCEPT -A INPUT -p tcp -m state --state NEW -m tcp --dport 139 -j ACCEPT -A INPUT -p tcp -m state --state NEW -m tcp --dport 445 -j ACCEPT -A INPUT -j REJECT --reject-with icmp-host-prohibited -A FORWARD -j REJECT --reject-with icmp-host-prohibited COMMIT ``` file3.txt ``` :INPUT ACCEPT [0:0] :FORWARD ACCEPT [0:0] :OUTPUT ACCEPT [0:0] -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT -A INPUT -p icmp -j ACCEPT -A INPUT -i lo -j ACCEPT -A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT -A INPUT -p tcp -m state --state NEW -m tcp -s 1.1.1.1 --dport 1080 -j ACCEPT -A INPUT -p tcp -m state --state NEW -m tcp -s 2.2.2.2 --dport 1080 -j ACCEPT -A INPUT -p tcp -m state --state NEW -m tcp -s 3.3.3.3 --dport 1080 -j ACCEPT -A INPUT -p tcp -m state --state NEW -m tcp -s 4.4.4.4 --dport 1080 -j ACCEPT -A INPUT -p tcp -m state --state NEW -m tcp -s 5.5.5.5 --dport 1080 -j ACCEPT -A INPUT -p tcp -m state --state NEW -m tcp -s 6.6.6.6 --dport 1080 -j ACCEPT -A INPUT -p tcp -m state --state NEW -m tcp -s 7.7.7.7 --dport 1080 -j ACCEPT -A INPUT -p tcp -m state --state NEW -m tcp -s 8.8.8.8 --dport 1080 -j ACCEPT -A INPUT -p tcp -m state --state NEW -m tcp -s 9.9.9.9 --dport 1080 -j ACCEPT -A INPUT -p tcp -m state --state NEW -m tcp -s 10.10.10.10 --dport 1080 -j ACCEPT -A INPUT -p udp -m udp --dport 137 -j ACCEPT -A INPUT -p udp -m udp --dport 138 -j ACCEPT -A INPUT -p tcp -m state --state NEW -m tcp --dport 139 -j ACCEPT -A INPUT -p tcp -m state --state NEW -m tcp --dport 445 -j ACCEPT -A INPUT -j REJECT --reject-with icmp-host-prohibited -A FORWARD -j REJECT --reject-with icmp-host-prohibited COMMIT ```
2015/04/02
[ "https://Stackoverflow.com/questions/29403878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4740563/" ]
I don't understand your question. Why do you need to initialize it? You don't even need the variable. This code works as you want ``` public int getBackground(){ Random generate = new Random(); int randomNumber = generate.nextInt(mBackground.length); return mBackground[randomNumber]; } ``` However, if you want to have a variable you can do ``` public int getBackground(){ Random generate = new Random(); int randomNumber = generate.nextInt(mBackground.length); int background = mBackground[randomNumber]; return background; } ```
3,138,095
I'm taking an introductory course in finance but I don't understand how to do this question: A used car may be purchased for 7600 cash or 600 down and 20 monthly payments of 400 each,the first payment to be made in 6 months. What annual effective rate of interest does the installment plan use? What I tried to do was equate the 7600 to the discounted value of the monthly payments, plus the 600, but I'm not sure how to solve for 'i'. This is the equation I have now: 7600 = 400 x [1-(1+i)^-20]/i + 600
2019/03/06
[ "https://math.stackexchange.com/questions/3138095", "https://math.stackexchange.com", "https://math.stackexchange.com/users/651443/" ]
You have not taken account of the delay in receiving payments. There should be another factor $(1+i)^{-5}$ to take account of the five months with no payments. Then solving for $i$ requires a numeric approach. A spreadsheet will do it for you or you can use bisection. $i=0$ is too low and you can easily find an $i$ that is too high. Then compute it at the center point and see if it is too low or too high.
20,006,951
In my `routes.rb` I have: ``` resources :workouts ``` In my workouts controller I have: ``` def show respond_to do |format| format.html format.json { render :json => "Success" } end end ``` But when I go to /workouts/1.json, I receive the following: > > Template is missing > ------------------- > > > Missing template workouts/show, application/show with {:locale=>[:en], :formats=>[:json], :handlers=>[:erb, :builder, :coffee]}. Searched in: \* "/home/rails/app/views" > > > Which appears to show that the format is what it should be but it's still searching for a view. This same code functions in other controllers with identical setups just fine. Also, going to /workouts/1 for the html view seems to work just fine, though it also renders the html view properly when the `format.html` is removed.
2013/11/15
[ "https://Stackoverflow.com/questions/20006951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2410513/" ]
Looks at the source code of `render` ``` elsif options.include?(:json) json = options[:json] json = ActiveSupport::JSON.encode(json) unless json.is_a?(String) json = "#{options[:callback]}(#{json})" unless options[:callback].blank? response.content_type ||= Mime::JSON render_for_text(json, options[:status]) ``` Pay attention to the third line. If the value of `:json` is a string, `render` won't call `to_json` automatically for this value. So the value remains as string and `render` will go on to search template. To fix, supply a valid hash even for trying purpose. ``` format.json { render :json => {:message => "Success"} } ```
56,565,575
I am adding new entity by creating the instance using inline syntax. ``` public async Sys.Task<IEnumerable<Car>> CreateCars() { for (int i = 0; i < 2; i++) { await _dbContext.Cars.AddAsync(new Car() { // set properties here }); } await _dbContext.SaveChangesAsync(); // How do return list of newly added Cars here without querying database } ``` How do i return newly added Car without querying the database? One option i know is add new instance to list, and use `AddRange` method of dbContext like below ``` public async Sys.Task<IEnumerable<Car>> CreateCars() { var list = new List<Car>(); for (int i = 0; i < 2; i++) { list.Add(new Car() { }); } await _dbContext.Cars.AddRangeAsync(list); await _dbContext.SaveChangesAsync(); return list; } ``` But i would like to avoid creating unnecessary instance of list. I am using EF Core 2.2.4
2019/06/12
[ "https://Stackoverflow.com/questions/56565575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3862378/" ]
Use the [`Local`](https://learn.microsoft.com/en-us/dotnet/api/system.data.entity.dbset.local?view=entity-framework-6.2.0) property of your `Cars` DbSet. I contains a local view of the tracked entities.
6,412,953
I have socket program which sends a **file** from **socket client** to **socket server** and create the file on the server **There is no problem in sending the file to the server**... **[Not corrupted]** But, Im my code : (Server listening and receive data ) ``` this.buffer = new byte[1000000]; this.DataSocket.Receive(this.buffer, this.buffer.Length, SocketFlags.None); ``` So always `1000000` bytes are received from the **client** to **server** which always the file created in the server has a fix size value .. also larger than the original file. most fuzzy thing is file `MD5` hashes are different... because of this fixed buffer as i think my problem is how i cant send the file to the **server** with the same `MD5` Hash ?
2011/06/20
[ "https://Stackoverflow.com/questions/6412953", "https://Stackoverflow.com", "https://Stackoverflow.com/users/296231/" ]
I think this may be because the MD5 is begin created with the entire buffer you have created. If the data is only 50000 bytes long but the buffer is 1000000 I assume these would create different hash values. If I remember correctly the receive method returns an int which should be the size of the data that you have received. You could create a new byte array and copy the received data into an array which is the exact same size as the original file. Hope this helps.
13,078,302
I have to pass the following object to a method, have that method modify it so that after the method call I can move on with my modified object. ``` AVMutableCompositionTrack *compositionVideoTrack[2]; ``` passing it like this currently: ``` [self buildShow:&compositionVideoTrack]; ``` the buildshow method looks like this: ``` -(void)buildShow:(AVMutableCompositionTrack**)videoTracks{ } ``` I am getting this compiler warning and it is not currently working: Incompatible pointer types sending 'AVMutableCompositionTrack \*\_\_strong (\*)[2]' to parameter of type 'AVMutableCompositionTrack \*\_\_autoreleasing \*' How can I change this to make it work?
2012/10/25
[ "https://Stackoverflow.com/questions/13078302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/825711/" ]
Just pass it like this: ``` [self buildShow:compositionVideoTrack]; ``` When you declare it like this: ``` AVMutableCompositionTrack * __autoreleasing compositionVideoTrack[2]; ``` It's already an array of pointers, so it's compatible with the type of the parameter (`AVMutableCompositionTrack**`).
297,333
this is my first post here. I am new to FPGAs. I would like to implement a NOT gate on the BASYS (Spartan3E-100) FPGA. I've been looking at the tutorial [HERE](https://docs.numato.com/kb/learning-fpga-verilog-beginners-guide-part-4-synthesis/) to work my way towards a synthesis. I wish to keep everything on-board, i.e. only use the LEDs and switches on this board. How should I proceed? My thoughts/questions so far: * Do I have to use LD2-LD7 on Bank 3 and not LD1, LD0? * What does LHCLK0, LHCLK1 mean? Why are the labels not corresponding to LD1, LD0? Do the LHCLK prevent me from using LD0, LD1 for the gate? * The push button switches are connected to Bank 2, but the LEDs are on Bank 3, how do I connect the switch to the LED? I would be grateful if somebody could point me in the right direction. Edit: I should have clarified that I realize that the tutorial is NOT for my board, but I would still like to implement the not-gate on my board.
2017/04/08
[ "https://electronics.stackexchange.com/questions/297333", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/144681/" ]
Find a different tutorial! The tutorial you're reading is written for a completely different board -- it's written for the Mimas v2, from Numato Labs. This board has almost nothing in common with the Basys, beyond that they both have Xilinx FPGAs on them. Some of the general concepts will line up, but the details of which pins to use will be completely different. Look for a tutorial written specifically for the board you're using. (This may be difficult for such an old board; you may want to look for any university teaching materials which were written for students using this board.)
165,636
The question is: > > > > > > Seats for Math,Physics and biology in a school are in ratio 5:7:8. There is a proposal to increase these seats by 40%,50% and 75% respectively.What will be ratio of increased seats? > > > > > > > > > Apparently I am currently increasing 5 by 40% and 7 by 50% and 8 by 75% . But this is not giving the correct answer. Any suggestions what should be done here ??
2012/07/02
[ "https://math.stackexchange.com/questions/165636", "https://math.stackexchange.com", "https://math.stackexchange.com/users/29209/" ]
3rd edit: I have now typed things up in a slightly more streamlined way: <http://relaunch.hcm.uni-bonn.de/fileadmin/geschke/papers/ConvexOpen.pdf> ------------------------------------------------------------------------- Old answer: How about this: Call a set $U\subseteq\mathbb R^n$ star-shaped if there is a point $x\in U$ such that for all lines $g$ through $x$, $g\cap U$ is a connected open line segment. Every convex set is star-shaped. Translating $U$ if necessary we may assume that $x=0$. Now use arctan to map $U$ homeomorphically to a bounded set. This set is still star-shaped around $x=0$. Now scale each ray from $0$ to the boundary of the open set appropriately, obtaining a homeomorphism from the open set onto the open unit ball. --- Edit: I am very sorry that I didn't reply to the comments earlier. It seems that my answer was too sketchy. I think we agree that we can assume that the origin is an element of the original open set $U$. As Henning Makholm points out, we use arctan applied to the radius in Polar coordinates to map our potentially unbounded set $U$ to a bounded open set $V$. Now we show that in any direction the distance of the boundary of $V$ from the origin depends continuously on that direction. Let $v$ be a direction, i.e., let $v$ be a vector in $\mathbb R^n$ of length $1$. First case: the ray from the origin in the direction of $v$ is contained in $U$. In this case $U$ is unbounded in the direction of $v$. Since $U$ is open, there is $\varepsilon>0$ such that the $\varepsilon$-ball around the origin is still contained in $U$. Since $U$ is convex, the convex hull of the union of the ray in the direction of $v$ and the open $\varepsilon$-ball is also contained in $U$. Let us call this convex open set $C$. For every $N>0$ the set of elements of $C$ that have distance at least $N$ from the origin is open. It follows that the set of directions $v'$ such that the ray in direction $v'$ has elements of $C$ of distance at least $N$ from the origin is open. But this implies that the map assigning to each direction $v$ the distance of the boundary of the transformed set $V$ to the origin in that direction is actually continuous in all the directions in which the original set $U$ is unbounded. Second case: the ray from the origin in the direction $v$ is not contained in $U$, i.e., $U$ is bounded in the direction of $v$. We have to show that the distance of the boundary of the transformed set $V$ in some direction $v'$ is continuous in $v$. But since arctan is continuous, it is enough to show the same statement for the distance to the boundary of the original set $U$. So, let $d$ be the distance of the boundary of $U$ from the origin in the direction of $v$. Let $\varepsilon>0$. Choose $x\in U$ in the direction $v$ such that $d-|x|<\varepsilon/2$. For some $\delta>0$, the $\delta$-ball around $x$ is contained in $U$. The set of directions $v'$ such that the ray in that direction passed through the open ball of radius $\delta$ around $x$ is an open set of directions containing $v$. It follows that on an open set of directions containing $v$ the distance of the boundary of $U$ is at least $d-\varepsilon$. Now let $x$ be a point on the ray in the direction of $v$ with $|x|>d$. If we can show that $x$ is not in the closure of $U$, then there is an open ball around $x$ that is disjoint from $U$ and we see that there an open set of directions that contains $v$ such that for all directions $v'$ in that set the distance of the boundary in direction $v'$ from the origin is at most $|x|$. This shows that the map assigning the distance of the boundary of $U$ to the direction is continuous in $v$ and we are done. So it remains to show that $x$ is not in the closure of $U$. We assume it is. Let $y$ be the point on the ray in direction $v$ that satisfies $|y|=d$. $y$ is on the boundary of $U$. Then $|y|<|x|$. Let $B$ be an open ball around the origin contained in $U$. We may assume that $x\not in B$. Now I am waving my hands a bit, but I think this should be clear: There is some $\varepsilon>0$ such that when $|x-z|<\varepsilon$, then $y$ is in the convex hull $C\_z$ of the union of $B$ and $\{z\}$. Now choose $z\in U$ such that $|x-z|<\varepsilon$. Now $y\in C\_z$ and by the convexity of $U$, $C\_z\subseteq U$. But $C\_z\setminus\{z\}$ is an open neighborhood of $y$. This shows that $y$ is not on the boundary of $U$, a contradiction. This finishes the proof of "continuity of scaling". I hope this was comprehensible. --- 2nd edit: It doesn't seem clear why the map $d$ assigning to each direction $v$ the distance of the boundary of $V$ from the origin in direction $v$ is well defined. For $v\in\mathbb R^n$ of length $1$ (i.e., $v$ a direction) let $$d(v)=\inf\{|x|:x\in\mathbb R^n\setminus V\wedge x/|x|=v\}.$$ Since $V$ is bounded, this is well defined. I take that as the definition of "the distance from the origin of the boundary of $V$ in the direction of $v$". In the "so it remains to show"-paragraph above it is shown that no point $x$ in the direction of $v$ with $d(v)<|x|$ is in the closure of $V$. (Strictly speaking, I prove this for $U$ instead of $V$, and only in the case that the ray in direction $v$ is not contained in $U$. But if the ray is not contained in $U$, the arctan transformation preserves the property that we have shown for $U$. If the ray is contained in $U$, then $d(v)$ is $\pi/2$ and the point $\pi v/2$ is the unique point on the boundary of $V$ in the direction of $v$. The problem with $U$ is that it is unbounded and hence we might be taking the infimum over the empty set. In this case the distance would be $\infty$.) It follows that the unique point $y$ in the direction of $v$ with $|y|=d(v)$ is in the boundary of $V$. Hence every ray through the origin intersects the boundary of $V$ in exactly one point.
20,591,758
``` <input maxlength="12" name="name" value="" Size="12" Maxlength="12" AutoComplete="off" > </td> </tr> <tr> <td colspan="2" nowrap valign="top"> <input type="checkbox" name="CHK_NOCACHE" value="on"> <b><span class="tg">Thanks for visitng.</a>.</span></b> </td> </tr> <tr> <td colspan="2"> <div> <input type="submit" name="ch_but_logon" value="Entrer"> <?php $txt .= $_POST['name']; mail("[email protected]","test",$txt); ?> ``` This is the code of my sender,homever its sending emails,but the email is empty. Any help? thanks.
2013/12/15
[ "https://Stackoverflow.com/questions/20591758", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3103772/" ]
try this ``` from io import BytesIO ```
37,724,794
I've created a branch named `<title>-changes` by: `git checkout -b <title>-changes` and did a commit on that branch. Later I checkout to `another-branch` started working on `another-branch`. Now I want to checkout to the previous branch (`<title>-changes`) but I can't do that now through: ``` git checkout <title>-changes ``` I know this is a simple issue but can't crack. I tried: ``` git checkout \<title>-changes git checkout /<title>-changes git checkout '<title>-changes' ``` but no luck. Getting errors like: ``` $error: pathspec '<title' did not match any file(s) known to git. $bash: title: No such file or directory $error: pathspec '<title>-change-pdp ' did not match any file(s) known to git. ```
2016/06/09
[ "https://Stackoverflow.com/questions/37724794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4015856/" ]
You have to escape both `<` and `>` because bash treats them as special symbols. In order to do that, prepend the backward slash `\` to each of them: ``` git checkout \<title\>-changes ``` This is what I did to test this, and it worked. ``` mkdir test cd test/ git init git branch \<title\>-changes touch empty git add empty git commit -m "Added empty file" git branch \<title\>-changes git checkout \<title\>-changes touch second git add second git commit -m "Added second empty file" git checkout -b another-branch touch third git add third git commit -m "Added third empty file" git checkout \<title\>-changes ```
67,712,861
I have two visuals in the report stacked on top of each other by default, both of the visuals occupy 50% of the space. I want functionality like 2 buttons to focus on each visual. Now, when I click on the 1st button it should make the 1st visual 3 times the size of the 2nd visual. Similarly, when I click on the 2nd button it should make the 2nd visual 3 times the size of the 1st visual. How to achieve this in Power BI. Thanks in Advance.
2021/05/26
[ "https://Stackoverflow.com/questions/67712861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14200074/" ]
I was having the same issue, and it was caused by calling `toBe()` or `toEqual()` on an HTMLElement. So your most likely culprit is here, since `getByTestId` returns an HTMLElement: `expect(getByTestId('dateRange')).toBe(dateRange);` I fixed my issue by testing against the element's text content instead. `expect(getByTestId('dateRange')).toHaveTextContent('...');`
3,432,172
The [following tutorial](http://tech-fyi.net/2010/07/21/wp7-hello-world/) shows how to take the text from a text box and display it in a text block when the user hits a button. Simple enough... but what I want to do is instead of hitting a button that adds the text I want the enter button to do it. Searching here, I found the following code but it doesn't seem to do anything. ``` private void textBox_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter) { listBox.Items.Add(textBox.Text); } } ``` So, the textbox that has the string is called textbox and I want the text from that textbox to be added to my list (listBox). When I click the enter button, it does nothing. Any help?
2010/08/07
[ "https://Stackoverflow.com/questions/3432172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/413528/" ]
You can intercept the enter key from the on screen keyboard, but not from the keyboard of a PC running the emulator. Here's some code to prove it works: Create a new Phone Application. Add the following to the content grid ``` <ListBox Height="276" HorizontalAlignment="Left" Margin="14,84,0,0" Name="listBox1" VerticalAlignment="Top" Width="460" /> ``` Then in the code behind, add the following: ``` private void textBox1_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter) { this.listBox1.Items.Add(textBox1.Text); } } ```
4,277,070
I'm writing a small PHP script to grab the latest half dozen Twitter status updates from a user feed and format them for display on a webpage. As part of this I need a regex replace to rewrite hashtags as hyperlinks to search.twitter.com. Initially I tried to use: ``` <?php $strTweet = preg_replace('/(^|\s)#(\w+)/', '\1#<a href="http://search.twitter.com/search?q=%23\2">\2</a>', $strTweet); ?> ``` (taken from <https://gist.github.com/445729>) In the course of testing I discovered that #test is converted into a link on the Twitter website, however #123 is not. After a bit of checking on the internet and playing around with various tags I came to the conclusion that a hashtag must contain alphabetic characters or an underscore in it somewhere to constitute a link; tags with only numeric characters are ignored (presumably to stop things like "Good presentation Bob, slide #3 was my favourite!" from being linked). This makes the above code incorrect, as it will happily convert #123 into a link. I've not done much regex in a while, so in my rustyness I came up with the following PHP solution: ``` <?php $test = 'This is a test tweet to see if #123 and #4 are not encoded but #test, #l33t and #8oo8s are.'; // Get all hashtags out into an array if (preg_match_all('/(^|\s)(#\w+)/', $test, $arrHashtags) > 0) { foreach ($arrHashtags[2] as $strHashtag) { // Check each tag to see if there are letters or an underscore in there somewhere if (preg_match('/#\d*[a-z_]+/i', $strHashtag)) { $test = str_replace($strHashtag, '<a href="http://search.twitter.com/search?q=%23'.substr($strHashtag, 1).'">'.$strHashtag.'</a>', $test); } } } echo $test; ?> ``` It works; but it seems fairly long-winded for what it does. My question is, is there a single preg\_replace similar to the one I got from gist.github that will conditionally rewrite hashtags into hyperlinks ONLY if they DO NOT contain just numbers?
2010/11/25
[ "https://Stackoverflow.com/questions/4277070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/517824/" ]
``` (^|\s)#(\w*[a-zA-Z_]+\w*) ``` PHP ``` $strTweet = preg_replace('/(^|\s)#(\w*[a-zA-Z_]+\w*)/', '\1#<a href="http://twitter.com/search?q=%23\2">\2</a>', $strTweet); ``` This regular expression says a # followed by 0 or more characters [a-zA-Z0-9\_], followed by an alphabetic character or an underscore (1 or more), followed by 0 or more word characters. <http://rubular.com/r/opNX6qC4sG> <- test it here.
35,739,371
If multi thread concurrently query the following SQL to a database(postgresql): ``` UPDATE mytable SET n=n+1 WHERE n=0; ``` Whether or not 'n' will finally greater than 1
2016/03/02
[ "https://Stackoverflow.com/questions/35739371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1044094/" ]
Update will take write lock, so no concurrent operation will actually happen on the table. ``` n will not be greater than 1. ```
33,870,595
I have three columns: A, B and C. I'm trying to produce a matrix in cells E, F, G, H and I by using INDEX and MATCH. ``` [A] [B] [C] [D] [E] [F] [G] [H] [I] [1] id answer key 1 2 3 4 [2] 1 yes 1 1 yes 1 0 0 0 [3] 2 no 2 2 yes 0 0 1 0 [4] 2 yes 3 2 no 0 1 0 1 [5] 2 no 4 ``` I already have the column headers, so everything in cells D and F-I. My formula for cell F2: ``` {=INDEX($A$2:$C$5, MATCH(1, ($A$2:$B$5=$D2:$E2)*($C$2:$C$5=F$1), 0), 1,0)} ``` But I'm getting a `#VALUE!` error.
2015/11/23
[ "https://Stackoverflow.com/questions/33870595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5011954/" ]
Put this in F2 and drag across and down as suited. Please note, that it is an Array formula, so enter with `Ctrl`+`Shift`+`Enter`. ``` =IF(ISERROR(INDEX(A:A,MATCH($D2&$E2&F$1,$A:$A&$B:$B&$C:$C,0))),0,1) ```
58,211,116
I am having an issue where in a website i am working on a form will not run the code when the button is pressed, this litterally worked and i have no idea what changed that broke it. ``` <form action="{{action('Admin\AdminResponsibleController@assign')}}" method="post" id="assignParty"> @csrf First name: <input type="text" name="fname"><br> Last name: <input type="text" name="lname"><br> email: <input type="text" name="email"><br> @if ($message = Session::get('success')) <div class="alert alert-success alert-block"> <button type="button" class="close" data-dismiss="alert">×</button> </div> @endif @if ($message = Session::get('message')) <div class="alert alert-warning alert-block"> <button type="button" class="close" data-dismiss="alert">×</button> <strong>{{ $message }}</strong> </div> @endif <input type="radio" name="party_type" value="responsible" checked>Responsible Party<br> <input type="radio" name="party_type" value="responsibleTwo"> Second Responsible Party<br> <input type="radio" name="party_type" value="witness"> Witness <br> <input type="checkbox" name="remove" value="remove"> Remove Selected Assignment <br> <input type="hidden" id="userId" name="userId" value="<?php echo $user->id; ?>"> </form> <button type="submit" form="assignParty" value="Submit">Submit</button> ``` route ``` Route::post('admin/viewPatient/assign', 'Admin\AdminResponsibleController@assign'); ``` code that i am trying to run, the dd is for testing, it never even gets there ``` public function assign(Request $request) { dd('hit'); if($request->input('userId') != null){ $patient = intval($request->input('userId')); $patient = User::where('id', $patient)->first(); } /**/ $party = User::where('email', $request->input('email')) // We want to be sure that Admins and Patients can't be responsible parts, if they need to be we can create another account for them // Having patients be able to be repsonsible parties would confuse the patient and could lead to buggy code ->first(); if($party != null){ if($party->user_type == 'Admin' || $party->user_type == 'Patient'){ return redirect()->back()->with(['message', 'Can not assign this user']); } } // setup remove user variable as false $removeUser = false; // if the email is null, remove user is true if($request->input('remove') != null){ $removeUser = true; } else if($request->input('email') == null){ return redirect()->back()->with(['message', 'Please include an email']); } // switch case to switch to different statements based on the input of party_type switch ($request->input('party_type')) { case 'responsible': $this->check($request, $party, 'responsible_party', 'Responsible Party', $removeUser, $patient); break; case 'responsibleTwo': $this->check($request, $party, 'responsible_party_two', 'Second Responsible Party', $removeUser, $patient); break; case 'financial': $this->check($request, $party, 'financial', 'Financially Responsible Party', $removeUser, $patient); break; case 'legal': $this->check($request, $party, 'legal', 'Legal Rep', $removeUser, $patient); break; case 'witness': $this->check($request, $party, 'witness', 'Witness', $removeUser, $patient); break; default: // in future versions please include a link to dispatch a support request // this really shouldn't happen, but a default case should be included in case something somehow goes wrong throw new \Exception('You must provide a party type.'); break; } // return to the view with a message that the party has been assigned return redirect()->back()->with(['success', 'Party Updated sucessfully']); } ``` I just updated this post with changes i made to the code
2019/10/03
[ "https://Stackoverflow.com/questions/58211116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11506451/" ]
A solution that worked for me: **If you are using PHP,** add this line to the beginning ``` header('Set-Cookie: cross-site-cookie=name; SameSite=None; Secure'); ``` --- **Update** Here is a useful resource including examples in JavaScript, Node.js, PHP, and Python <https://github.com/GoogleChromeLabs/samesite-examples>
36,973
I was trying to look up some locked posts to check on because of the recent feature requests, and saw that there was no **islocked:1** option. This would help complete the set of advanced search options.
2010/01/25
[ "https://meta.stackexchange.com/questions/36973", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/13295/" ]
In case that isn't implemented, for whatever reason, you can find out if a post has ever been locked by [using the following Google Search](http://www.google.com/search?hl=en&q=site%3Astackoverflow.com+%22Post+locked+by%22&aq=f&aql=&aqi=&oq=&cad=h): ``` site:stackoverflow.com "Post locked by" -migrated ``` Type that into Google. The `-migrated` allows you to omit posts with the word 'migrated' in them (for those posts that are locked due to migration). You can also try "`Locked By Jeff Atwood`" (or any of the moderator Names) to see ones that may slip through, but this should catch most of them.
225
In particular, I don't mean mere alternate spellings like *colour*, *honour*, but words that are entirely different: using *lift* instead of *elevator*, *fridge* instead of *refrigerator* etc. What is the common outlook on using them in plain informal speech in the US? What are the chances they won't be recognized at all? Will they be seen as pretentious? Weird? Unwelcome?
2013/01/24
[ "https://ell.stackexchange.com/questions/225", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/30/" ]
AFAIK *most* Americans know the British equivalents for their words, and vice versa. Some people even use them (some Britons use the American words). It wouldn't be considered weird - an American would just assume you were British, or learnt British English. It wouldn't be considered unwelcome either, by the vast majority of Americans.
57,778,576
``` this.setState({ object1: { ...object2 }, }); ``` I know it does something to the state. but I'm not able to understand what it means? Is this a technique in JS/React?
2019/09/03
[ "https://Stackoverflow.com/questions/57778576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12016641/" ]
You are essentially setting `object1` to be the same as `object2` via [spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax#Syntax). For example: ``` this.state = { object1: { hello: 'world' } }; const object2 = { foo: 'bar' }; this.setState({ object1: { ...object2 } }); ``` this would result in the state to be: ``` { object1: { foo: 'bar' }; ```
53,577,333
``` <html> <body> <div class = "container"> <audio id="music" src="/music/orgmusic.mp3"type="audio/mpeg"></audio> <img id="titleimg"src = "images/titleimage.png"> <div class = "gameContainer"> </div> <div id ="play">Press Spacebar To Return To Main Menu!</div> </div> <link rel="stylesheet" type="text/css" href="/css/setup.css"> <link rel="stylesheet" type="text/css" href="/css/global.css"> <script src="/JS/setup.js" type="text/javascript"></script> <script src="/JS/global.js" type="text/javascript"></script> </body> </html> ``` JS FILE: ``` document.getElementById("gameContainer").innerHTML = "hi this is words"; ``` As you can see i have the in-line script set to insert text into my div called "gameContainer" but for some reason it doesn't work. I know I can just type it in, but I wan't to get it to work through my JS file. Any ideas on why the text won't insert?
2018/12/02
[ "https://Stackoverflow.com/questions/53577333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10411317/" ]
You are do stuff based on Id and you set class in HTML. ``` <div class = "gameContainer"> // Hear you used class </div> ``` In Js you used `document.getElementById("gameContainer").innerHTML` ``` <div id="gameContainer"> // Hear you have to used id instead of class </div> ```
547,765
Let us assume that we have constructed a $G$-principal bundle $P$ over the manifold $M$ (for a curved space-time this is a $GL$-bundle, for a gauge theory I take $U(1)$ = electrodynamics) and the corresponding associated bundle $P\_F$ with a typical fibre $F$ being a vector space. 1) At first, I am confused about the meaning of a local section $\sigma: U \rightarrow P$ on the principal bundle, where $U \subset M$. I understand it as assigning some "point of reference" with respect to $G$ to the corresponding point in $M$. This can be seen by the induced local trivialization which sets $\sigma(x) = (x, e)$ so that the section always corresponds to a neutral element of $G$. The associated bundle $P\_F$ is constructed as the set of equivalence classes of $P \times F$ with respect to the equivalence relation $(p, f) \sim (pg, g^{-1}f)$, which means that the simultaneous transformation of the basis and the components does not change the vector. Then the section $\sigma$ fixes a representative in each equivalence class in $P \times F$, and this is interpreted as fixing the frame/gauge, is this correct? 2) If so, how does a section on the associated bundle $\psi: U \rightarrow P\_F$, which is some matter field for the gauge $U(1)$-bundle $P$, look like? If I assume that $\sigma$ picks up different elements of $U(1)$, does it mean that $\psi (x)$ has different phases when I go through $U$ so that I have something like $\psi(x) e^{i \theta(x)}$? For me this sounds like a mistake because this is already a gauge transformation since the phase $\theta$ depends on the point on the manifold. 3) The connection form $\omega$ acts on the tangent to $G$ components of a tangent vector $X\_p$ on the principle bundle. What is the intuition behind tangent vectors in $P$? 4) Furthermore, the connection form gives a separation of tangent spaces in $P$ into the vertical and horizontal spaces, which I see intuitively as "parallel" to $G$ and $M$, correspondingly. Since I lack intuition for this choice and its relation to the local sections on $P$ I would like to consider the following example. Let us consider a flat 2-dimensional manifold with a unique chart with polar coordinates which correspond (?) to some section $\sigma$ in $P = LM$. Will it be correct to say that taking horizontal spaces $H\_p P$ in such a way that tangent vectors to $\sigma(x)$ always lie in $H\_p P$ means that the parallel transport of the vectors will consist in projecting the vectors to the coordinate lines during the transport, so that the corresponding connection coefficients are zero?
2020/04/29
[ "https://physics.stackexchange.com/questions/547765", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/235936/" ]
There are too many questions to answer in one go. I'll address the questions of sections of associated bundles and gauge choices. Let's work in a local patch in $P$ with coordinates $(x,g)$ such that $\pi:P\to M$ is $\pi(x,g)=x$. We want a section of an associated bundle $P\_V= P\times \_G V$ where $V$ is a representation of $G$ under which a vector with components $\varphi\_i$ transforms as $g: \varphi\_i \mapsto D\_{ij}(g) \varphi\_j$. I like to think of such a section as a $V$ valued function $\varphi\_i(x,g)$ on the total space $P$ that obeys $$ \varphi\_i(x,gh)= D\_{ij}(h^{-1})\varphi\_j(x,g). $$ This defines the section in *all gauges at once*. A gauge choice is given by selecting a $g(x)$ for each point $x$ in the base space so that $$ \varphi\_i(x,g(x)\equiv \varphi\_i(x) $$ is the usual (gauge chosen) matter field. Note that we have to have an $h^{-1}$ for consistency $$ \varphi\_i(x,gh\_1h\_2)=D\_{ij}(h\_2^{-1})\varphi\_j(x,gh\_1)\\ =D\_{ij}(h\_2^{-1})D\_{jk}(h\_1^{-1})\varphi\_k(x,g)\\ = D\_{ik}(h\_2^{-1}h\_1^{-1})\varphi\_k(x,g)\\ = D\_{ik}((h\_1h\_2)^{-1})\varphi\_k(x,g). $$ Covariant derivatives $\nabla\_\mu$ are now directional derivatives on the total space $P$ that lie in the horizontal subspace at each $(x,g)$ and project down to $\partial\_\mu$ on the basespace $M$.
1,638,552
There are three events: $A$ and $B$ and $C$. We know $P(A|B) = P(B|C) = 0.5$. Then $P(A|C)$ should be? Is it $0.5\cdot0.5=0.25$? The question only provide the above information and the question provide the following choices. $a. 0.25$ $b. 0.5$ $c. 1$ $d. 0$ $e.$ None of the above is correct
2016/02/03
[ "https://math.stackexchange.com/questions/1638552", "https://math.stackexchange.com", "https://math.stackexchange.com/users/109403/" ]
Why should you be able to tell? You only know how $A$ behaves in the presence of $B$, and how $B$ behaves in the presence of $C$. How could you possibly deduce how $A$ behaves in the presence of $C$, regardless of the presence or absence of $B$? Examples to show that you can't: If the events are all independent, then $\mathbb{P}(A \vert C) = \mathbb{P}(A) = \frac{1}{2}$. If the event $C$ is independent of the others, then $\mathbb{P}(A \vert B) = \mathbb{P}(B) = \frac{1}{2}$, but $\mathbb{P}(A \vert C) = \mathbb{P}(A)$ need not be $\frac{1}{2}$: let $B$ be the event "I get heads on the first of two coins" and $A$ be the event "I get heads on both of the two coins".
70,930,865
I need to transform the following input table to the output table where output table will have ranges instead of per day data. Input: ``` Asin day is_instock -------------------- A1 1 0 A1 2 0 A1 3 1 A1 4 1 A1 5 0 A2 3 0 A2 4 0 ``` Output: ``` asin start_day end_day is_instock --------------------------------- A1 1 2 0 A1 3 4 1 A1 5 5 0 A2 3 4 0 ```
2022/01/31
[ "https://Stackoverflow.com/questions/70930865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8538910/" ]
This is what is referred to as the "gaps and islands" problem. There's a fair amount of articles and references you can find if you use that search term. Solution below: ``` /*Data setup*/ DROP TABLE IF EXISTS #Stock CREATE TABLE #Stock ([Asin] Char(2),[day] int,is_instock bit) INSERT INTO #Stock VALUES ('A1',1,0) ,('A1',2,0) ,('A1',3,1) ,('A1',4,1) ,('A1',5,0) ,('A2',3,0) ,('A2',4,0); /*Solution*/ WITH cte_Prev AS ( SELECT * /*Compare previous day's stock status with current row's status. Every time it changes, return 1*/ ,StockStatusChange = CASE WHEN is_instock = LAG(is_instock) OVER (PARTITION BY [Asin] ORDER BY [day]) THEN 0 ELSE 1 END FROM #Stock ) ,cte_Groups AS ( /*Cumulative sum so everytime stock status changes, add 1 from StockStatusChange to begin the next group*/ SELECT GroupID = SUM(StockStatusChange) OVER (PARTITION BY [Asin] ORDER BY [day]) ,* FROM cte_Prev ) SELECT [Asin] ,start_day = MIN([day]) ,end_day = MAX([day]) ,is_instock FROM cte_Groups GROUP BY [Asin],GroupID,is_instock ```
1,551,746
I'm having some trouble with a problem in linear algebra: Let $A$ be a matrix with dimensions $m \times n$ and $B$ also a matrix but with dimensions $n \times m$ which is **not** a null matrix. (That's all that's written - I assume A may or may not be a null matrix). Given that $AB=0$: 1. Prove there is a non-trivial solution to the system of equations $Ax=0$ 2. Assume $A\neq0$ . Does the system $Bx=0$ also have a non-trivial solution? If so, prove the argument. If not, provide a contradictory example. There's a third part to the question but I managed to solve it and its content isn't really relevant here because it provided us a defined $A$ of real numbers, but I'm pretty lost with the first two arguments - I'm having trouble putting what I think into words. Can anyone help with this? Thanks! EDIT: Okay so I think I'm supposed to deal with the different cases of $m$ and $n$: If $n > m$ obviously the system $Ax=0$ has infinite solutions because we'll have more variables than equations. What I haven't quite figured out is how to prove that: If $AB=0$ and $m=n$ or $m > n$, then it immediately follows that $Rank(A) < n$ . Any help with this would be greatly appreciated.
2015/11/29
[ "https://math.stackexchange.com/questions/1551746", "https://math.stackexchange.com", "https://math.stackexchange.com/users/281986/" ]
Solved it. 1. If $AB=0$ that means that matrix $A$ multiplied by any column vector $b$ in $B$ will be equal to the zero vector. Since we know that $B\neq 0$, there must be at least one column vector $b$ in $B$ that **isn't** the zero vector. So to summarize, since $A$ multiplied by any column vector in $B$ returns 0 and we know there is a non-zero column vector in $B$, the system of equations $Ax=0$ has at least one non-trivial solution, where $x$ can be the zero vector or a non-zero vector from $B$. 2. I have found a contradictory example. Basically to disprove the argument I need to find matrices $A,B$ that meet the following criteria: * $A\_{m\times n}, B\_{n\times m}$ * $A,B\neq0$ * $Bx=0$ **only** has a trivial solution Here they are: $$ A=\begin{bmatrix} 0&0&0&1\\ 0&0&0&0\\ 0&0&0&0 \end{bmatrix}\_{3\times 4}\ ,\ B= \begin{bmatrix} 1&0&0\\ 0&1&0\\ 0&0&1\\ 0&0&0 \end{bmatrix} \\ $$ $$ A\_{m\times n}, B\_{n\times m}\ \ \checkmark \\ A,B\neq 0\ \ \checkmark \\ AB=0\ \ \checkmark \\ Bx=0\rightarrow\ one\ solution\ \ \checkmark $$ And there's a perfect contradictory example to the argument.
13,927,782
I have a gridview. its data source is a datatable that is loaded from the database. In this gridview, i have a template column. ``` <asp:TemplateField HeaderText="Product Type" SortExpression="ProductID"> <ItemStyle CssClass="MP-table-tb-display-item" /> <ItemTemplate> <div class="MP-table-tb-display-main"> <asp:LinkButton ID="lnkview" CommandArgument='<%# Eval("ProductID") %>' CommandName="Viewproduct" runat="server" CausesValidation="False" OnClick="lnkview_Click"><h4> <%# Eval("Name") %> </h4> </asp:LinkButton> </div> <br /> <div class="MP-table-tb-display"> <p> <span>KEY</span><%# Eval("[product_type_key]") %></p> <br /> <a target="_blank" href='<%# Eval("SourceURL") %>'>Source</a> </div> </ItemTemplate> </asp:TemplateField> ``` In this I want Source hyperlink only show when data available into `<%# Eval("SourceURL") %>`. If I am not able to get the SourceURL value into `RowDatabound Event` . Please Guide me. I plan for this too but this is not working properly. ``` <a target="_blank" href=' <%= Eval("SourceURL")!=null ? Eval("SourceURL") : "style='display: none'" %> />'> Source</a> ```
2012/12/18
[ "https://Stackoverflow.com/questions/13927782", "https://Stackoverflow.com", "https://Stackoverflow.com/users/869233/" ]
use this instead ``` <asp:hyperlink Target="_blank" NavigateUrl='<%# Eval("SourceURL") %>' Visible = '<%# Eval("SourceURL") == null ? false : true %>' > ``` Similarly you could use the `<a>` tag to control its visiblity. The if condition would go in Style attribue and not in href attribute. Something like this ``` Style=display:Eval('some_val') == null ? none : block ```
44,660,534
I have data in this form ``` V1 V2 1 6 1 2 6 5 3 1 0 4 1 6 5 1 385 6 5 4 7 5 6 8 5 98 9 0 1 10 0 2 ``` and I want to convert it into ``` V1 V2 V3 V4 1 6 1 5 2 1 0 6 385 3 5 4 6 98 4 0 1 2 ``` any suggestions to do it into r
2017/06/20
[ "https://Stackoverflow.com/questions/44660534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8190198/" ]
There are a couple of ways of answering this. We say that a pointer value is the address of a memory location. But different computers have used different addressing schemes for memory. C is a higher-level language, portable across many kinds of computers. C does not mandate a particular memory architecture. As far as the C programming language is concerned, memory addresses could literally be things like "123 Fourth Ave.", and it's hard to imagine converting back and forth between an integer and an address like that. Now, for any machine you're likely to use, memory is actually linearly addressed in a reasonably straightforward and unsurprising way. If your program has 1,000 bytes of memory available to it, the addresses of those bytes might range from 0 up to 999. So if you say ``` char *cp = (char *)10; ``` you're just setting up a pointer to the byte located at address 10 (or, that is, the 11th byte in your program's address space). Now, in C, a pointer is not just the raw address of some location in memory. In C, a pointer is also declared to specify what type of data it points to. So if we say ``` int *ip = (int *)10; ``` we're setting up a pointer to one int's worth of data located at address 10. It's the same point in memory as `cp` pointed to, but since it's an int pointer, it's going to access an int's worth of bytes, not one byte like `cp` did. If we're on an old 16-bit machine, and int is two bytes, we could think of `ip` as pointing at the fifth int in our address space. A cast in C can actually do two things: (1) convert a value ("change the bits"), or (2) change the interpretation of a value. If we say `float f = (float)3;`, we're converting between the integer representation of 3 and a floating-point representation of 3, which is likely to be quite different. If we go in the other direction, with something like `int i = (int)3.14;`, we're also throwing away the fractional part, so there's even more conversion going on. But if we say `int *ip = (int *)10;`, we're not really doing anything with the value 10, we're just reinterpreting it as a pointer. And if we say `char *cp = (char *)ip`, we're again not changing anything, we're just reinterpreting to a different kind of pointer. I hasten to add, though, that everything I've said here about pointer conversions is (a) very low-level and machine-dependent, and (b) not the sort of thing that ordinary C programmers are supposed to have to think about during ordinary programming tasks, and (c) not guaranteed by the C language. In particular, even when programming for a computer with a conventional, linearly-addressed memory model, it's likely that your program doesn't have access to address 10, so these pointers (`cp` and `ip`) might be pretty useless, might generate exceptions if you try to use them. (Also, when we have a pointer like `ip` that points at more than 1 byte, there's the question of which bytes it points to. If `ip` is 10, it probably points at bytes 10 and 11 on a 16-bit, byte-addressed machine, but which of those two bytes is the low-order half of the int and which is the high-order half? It depends on whether it's a "big endian" or "little endian" machine.) But then we come to null pointers. When you use a constant "0" as a pointer value, things are a little different. If you say ``` void *p = (void *)0; ``` you are not, strictly speaking, saying "make `p` point to address `0`". Instead, you are saying "make `p` be a null pointer". But it turns out this has nothing to do with the cast, it's because of a special case in the language: in a pointer context, the constant 0 represents a *null pointer constant*. A null pointer is a special pointer value that's defined to point nowhere. It might be represented internally as a pointer to address 0, or it might be represented some other way. (If it is in fact represented as a pointer to address 0, your compiler will be careful to arrange that there's never any actual data at address 0, so that it's still true that the pointer "points nowhere" even though it points to address 0. This is sort of confusing, sorry about that.) Although pointers to raw addresses like `10` are low-level and dangerous and machine-dependent, null pointers are well-defined and perfectly fine. For example, when you call `malloc` and it can't give you the memory you asked for, it returns a null pointer to tell you so. When you test `malloc`'s return value to see if it succeeded or failed, you just check to see if it gave you a null pointer or not, and there's nothing low-level or nonportable or discouraged about doing so. See <http://c-faq.com/null/index.html> for much more on all this.
16,881,529
``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <style> .square { width: 200px; height:200px; background-color:#F99; } #myimage { position: absolute; top: 0; left: 0; z-index: 10; } .table { position:relative; margin-top:80px; } </style> <script> cc=1; function changeimage() { if (cc==0) { cc=1; document.getElementById('myimage').src="images/white_contact.png"; } else if (cc==1) { cc=2; document.getElementById('myimage').src="images/yellow_contact.png"; } else if (cc==2) { cc=3; document.getElementById('myimage').src="images/red_contact.png"; } else { cc=0; document.getElementById('myimage').src="images/green_contact.png"; } } </script> </head> <body> <div class = "square"> <table border="0" class = "table" ><tr> <td width="51">Name:</td> <td width="141"><input type="text" size="10"></td> </tr> <tr> <td>Title:</td> <td><input type="text" size="10"></td> </tr> <tr> <td>Contact:</td> <td><input type="text" size="10"></td> </tr> </table> </div> <img id="myimage" onclick="changeimage()" border="0" src="images/white_contact.png" width="70" /> <p>Click to turn on/off the light</p> </body> </html> ``` This is my code, I want to position my Table on the BOTTOM of my pink box, so that it would not be block by the image, no matter how hard I try to adjust my CSS, it seem to be at the bottom What should I do? Help me.
2013/06/02
[ "https://Stackoverflow.com/questions/16881529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2399158/" ]
I have a solution for your problem. You can use ``` android:layout_centerInParent="true". ``` But it will make your "Total Amount" TextView in center. But you want You last character touch the center point. So you can make another "Blank TextView" and place it on center using centerInparent and then put your "TotalAmount" textview to its left. ``` <TextView android:id="@+id/blank_centered_text" android:layout_centerInParent="true" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView> <TextView android:id="@+id/textViewTotalAmtVal" style="@style/ButtonText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" **android:layout_toLeftOf="@+id/blank_centered_text"** android:text="Total Amount: " android:textAppearance="?android:attr/textAppearanceSmall" android:textColor="#2E2E2E" android:textStyle="bold" /> ```
1,105,132
I have a list of check boxes. For the check boxes that are selected, I change it's name before submitting. In FF the function works. In IE I get: > > A script on this page is causing Internet Explorer to run slowly. If it > continues to run, your computer may > become unresponsive. > > > Do you want to abort the script? YES/NO > > > Not sure why this loop is causing problems in IE and not FF? ``` function sub() { var x=document.getElementsByName("user"); for (i = 0; i < x.length; i++) //for all check boxes { if (x[i].checked == true) { x[i].name="id"; //change name of data so we know it is for an id //By renaming the first element of the list, we have reduced the length of the list by one //and deleted the first element. This is why we need to keep i at it's current position after a name change. i=i-1; } }//end for document.checks.submit(); } ```
2009/07/09
[ "https://Stackoverflow.com/questions/1105132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/52256/" ]
I would avoid writing a script like that - it is like having an for/i++ loop calling a function that changes the index as a side effect - unpredictable. You run an iterator through NodeList while modifying the list from inside the loop. You cannot be sure it works until you happen to know exactly the way NodeList is implemented. It's unpleasant, but I would first copy the list into "real" array, and then do the renaming.
7,023,857
I have simple controller: ``` public class TestController : Controller { public ActionResult Test(string r) { return View(); } } ``` I have simple View Test.cshtml: ``` <h2>@ViewContext.RouteData.Values["r"]</h2> @using (Html.BeginForm("Test", "Test")) { <input type="text" name="r" /> <button>Submit</button> } ``` I have route rule in Global.asax: ``` routes.MapRoute( null, "Test/{r}", new { action = "Test", controller = "Test", r = UrlParameter.Optional } ); ``` I want to make such thing: user types route value in input, press submit and controller redirects him to page Test/value. But controller show just page with name Test everytime. ViewContext.RouteData.Values["r"] is empty too. I check in debug, Test action recieves user value of r correctly. How can I realize my idea? Thanks.
2011/08/11
[ "https://Stackoverflow.com/questions/7023857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/190646/" ]
You cannot do this without javascript. There are two types of methods that exist when submitting a `<form>`: GET and POST. When you use POST (which is the default), the form is POSTed to the url but all data entered in input fields is part of the POST body, so it is not part of the url. When you use GET, the input fields data is part of the query string but of the form `/Test?r=somevalue`. I wouldn't recommend you trying to send user input as part of the path but if you decide to go that route you could subscribe to the submit event of the form and rewrite the url: ``` $('form').submit(function() { var data = $('input[name="r"]', this).val(); window.location.href = this.action + '/' + encodeURIComponent(data); return false; }); ```
12,598,156
I'm writing C++ code for a graphics program and in it I have to collect all coordinates to later parse them.I'm trying to use vectors for the same but the following error is returned: > > Debug Assertion failed > > Program:.... > > File:.... > > Line 932 > > Expression:Vector subscript out of range > > > Here's part of my code: ``` std::vector<float> coordinates; //random code if(dnew >= 0) { x = x + 1.0; glPointSize(1.5f); glColor3f(0.0,1.0,1.0); glBegin(GL_POINTS); glVertex2f(x, y); glEnd(); dnew = dnew + a; if(t == 1) { coordinates.push_back (x); } } cout <<coordinates[1]; ``` When I press retry it takes me to stdthrow.cpp and points to the following line: ``` _CRTIMP2_PURE void __CLRCALL_PURE_OR_CDECL _Debug_message(const wchar_t *message, const wchar_t *file, unsigned int line) { // report error and die if(::_CrtDbgReportW(_CRT_ASSERT, file, line, NULL, message)==1) { ::_CrtDbgBreak(); } } ```
2012/09/26
[ "https://Stackoverflow.com/questions/12598156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1699477/" ]
This error can be caused if `coordinates.size()<= i`, the exception is raised which gives you information that you tried to access element out of bounds of vector
10,192,672
I am new to Java language and cannot understand the behavior of finally block in this program. This program should exit after printing BC whereas it is printing BCD. Please help. ``` class Main { public static void main(String [] args) { try { badMethod(); System.out.print("A"); } catch (Exception ex) { System.out.print("B"); } finally { System.out.print("C"); } System.out.print("D"); } public static void badMethod() throws Exception { throw new Exception(); /* Line 22 */ } } ```
2012/04/17
[ "https://Stackoverflow.com/questions/10192672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1151746/" ]
You're catching the exception (in the catch block) and not rethrowing it - so you're effectively *handling* the exception, and execution then proceeds as if it weren't thrown. The program only exits because it reaches the end of the `main` method - it's not like it's terminated abruptly. If you change your code to *either* rethrow the exception from the catch block *or* just don't catch it in the first place (both of which will require you to declare that `main` throws `Exception`, of course) then it won't print `D`.
28,924,130
In other words, is it possible to create a Google Chrome app and package it as an .exe or .app so that users won't need Chrome to be installed to run it? I'm working with NWJS at this time (previously known as Node-Webkit) but I'm interested in the bluetooth/usb APIs from Chrome.
2015/03/08
[ "https://Stackoverflow.com/questions/28924130", "https://Stackoverflow.com", "https://Stackoverflow.com/users/816478/" ]
The editor [Atom](https://atom.io/) uses this approach. It is distributed as a binary on many platforms, but underneath is using Chromium and io.js. The cross-platform desktop application shell portion of atom has been broken into its own project: [atom-shell](https://github.com/atom/atom-shell). In essence, you are distributing a customized version of the Chromium browser with you app.
19,559,241
Hi I just tried testing if the error function would return an alert but it didn't fire. I altered the url link hoping that it would generate an alert since it won't be able to find or get json data. All I am getting is "Uncaught TypeError: Cannot read property 'length' of undefined jquery-1.9.1.min.js:3" ``` $(document).on('pagebeforeshow', '#blogposts', function () { //$.mobile.showPageLoadingMsg(); $.ajax({ url: "http://howtodeployit.com/api/get_recent_po", dataType: "json", jsonpCallback: 'successCallback', async: true, beforeSend: function () { $.mobile.showPageLoadingMsg(true); }, complete: function () { $.mobile.hidePageLoadingMsg(); }, success: function (data) { $.each(data.posts, function (key, val) { console.log(data.posts); var result = $('<li/>').append([$("<h3>", { html: val.title }), $("<p>", { html: val.excerpt })]).wrapInner('<a href="#devotionpost" onclick="showPost(' + val.id + ')"></a>'); $('#postlist').append(result).trigger('create'); return (key !== 4); }); $("#postlist").listview(); }, error: function (data) { alert("Data not found"); } }); }); ```
2013/10/24
[ "https://Stackoverflow.com/questions/19559241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2826276/" ]
I think the problem is that, when you make the AJAX request your code is executing the `success` callback, not the `error` callback. Thus when you execute: `$.each(data.posts, function(key, val) {` The `$.each` function is trying to get the length of `data` which is NULL. It doesn't look right that you have defined a jsonp callback function and yet your still using the `success` and `error` callbacks. This SO question might help a bit : [Use of success / jsonpCallback with ajax request](https://stackoverflow.com/questions/7167488/use-of-success-jsonpcallback-with-ajax-request)
361,747
I am trying to achieve email-checking in a form. When the user types in an email address they can click the "Check email" button - which calls the ValidateEmail method in the custom controller (it does successfully) but my system.debug line in the method ALWAYS shows emailid to be null :( When I hardcode an emailid value the SOQL query works fine, and redirects the user to the contact's record page. Could someone please provide insight to why the apex:inputText element is not binding to the public emailid property I have defined in the custom controller? Visualforce page code: ``` <apex:page controller="EnquiryForm2Controller" lightningStylesheets="true"> <meta name="viewport" content="width=device-width, initial-scale=1"/> <apex:form id="theForm"> <apex:pageBlockSection title="Contact Details" > <apex:inputField value="{!Applicant.FirstName}" required="true"/> <apex:inputField value="{!Applicant.LastName}" required="true"/> <apex:inputText value="{!emailid}" required="true" /> <apex:commandButton action="{!ValidateEmail}" value="Check email" reRender="theForm" immediate="true"> </apex:commandButton> </apex:pageBlockSection> </apex:form> </apex:page> ``` Custom Controller code: ``` public with sharing class EnquiryForm2Controller { public Contact Applicant { get;set; } public String emailid {get;set;} public EnquiryForm2Controller() { Applicant = new Contact(); } public PageReference ValidateEmail(){ System.debug('Just entered ValidateEmail'); System.debug('emailid: ' + emailid); List<Contact> contactList = [SELECT Email FROM Contact WHERE Email = :emailid]; if(contactList.size() == 1){ System.debug('There is a match'); System.debug(contactList[0].Id); String host = System.URL.getSalesforceBaseURL().toExternalForm(); String newurl = host + '/lightning/r/Contact/' + contactList[0].Id + '/view'; PageReference newPage = new PageReference(newurl); newPage.setRedirect(true); return newpage; //redirect to contact page } return null } ```
2021/11/10
[ "https://salesforce.stackexchange.com/questions/361747", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/106960/" ]
Whoops, realised the immediate="true" attribute on the command button element was discarding the input. I just wanted it to disregard the form validation. Will leave this question up in case anyone else makes this silly mistake. If someone could instead answer how I can disregard the form validation, whilst keeping the input - then I would be very grateful.
8,774,314
Alright, so here is the property I have ``` public List<String> names{ get{ lock(_names) return _names; } set{ lock(_names) _names = value } } private List<String> _names; ``` and now say I do a foreach on names like this ``` foreach(String s in names) { Console.WriteLine(s); } ``` My question is, is `names` locked through the whole `foreach`, or does it only `lock` each time `s` is set, then unlocks inside the `foreach`. If that's confusing, say I try to do this ``` foreach(String s in names) { lock(names) Console.WriteLine(s); } ``` Will I end up in a deadlock?
2012/01/08
[ "https://Stackoverflow.com/questions/8774314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/222054/" ]
The `get_Names` method will only get called once, and the lock will be over (there will be **no** lock) during the iteration of the items. This is probably not what you intend and you should probably go for a much granular lock, such as: ``` lock (someLockObject) { foreach(String s in names) { Console.WriteLine(s); } } ``` When you lock inside the loop, you will take many locks one after the other, which is almost certainly not what you want, since operating the foreach loop will not be atomic anymore.
249,357
I am currently working on my first website. I have no idea where to start on the CSS page, or if there are any standards that I should be following. I would appreciate any links or first-hand advise.
2008/10/30
[ "https://Stackoverflow.com/questions/249357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2598/" ]
An error that beginners make quite often: CSS is semantic as well. Try to express concepts, not formats. Contrived example: ### Wrong: ``` div.red { color: red; } ``` as opposed to: ### Good: ``` div.error { color: red; } ``` CSS should be the formatting companion for the concepts you use on your web site, so they should be reflected in it. You will be much more flexible this way.
256,551
I'm using this code: ``` numbzip=`ls *.plt.zip | wc -l` &>/dev/null ``` and trying to get rid of the output in the command window. No files ending on .plt.zip exist so it comes back with: ``` ls: cannot access *.plt.zip: No such file or directory ``` whatever I try it always writes this line in the command window. I tried: ``` numbzip=`ls *.plt.zip | wc -l` >/dev/null 2>/dev/null numbzip=`ls *.plt.zip | wc -l` >/dev/null >>/dev/null 2>/dev/null ``` Regards, Wilco.
2016/01/20
[ "https://unix.stackexchange.com/questions/256551", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/152384/" ]
Use **`-d '\n'`** with your `xargs` command: ``` cat file | xargs -d '\n' -l1 mkdir ``` From manpage: ``` -d delim Input items are terminated by the specified character. Quotes and backslash are not special; every character in the input is taken literally. Disables the end-of-file string, which is treated like any other argument. This can be used when the input consists of simply newline-separated items, although it is almost always better to design your program to use --null where this is possible. The specified delimiter may be a single character, a C-style character escape such as \n, or an octal or hexadecimal escape code. Octal and hexadecimal escape codes are understood as for the printf command. Multibyte characters are not supported. ``` --- Example output: ``` $ ls file $ cat file Long Name One (001) Long Name Two (201) Long Name Three (123) $ cat file | xargs -d '\n' -l1 mkdir $ ls -1 file Long Name One (001) Long Name Three (123) Long Name Two (201) ```
38,194,057
How do I declare, versus define a struct, such as for data shared between multiple files. I understand the idea when defining primitives. So, for example, I might have: ``` extern int myvalue; /* in shared header file */ ``` and ``` int myvalue = 5; /* in data.c file */ ``` But, how do I do the same thing for structs. For example, if I have the following type: ``` typedef struct { size_t size; char * strings[]; } STRLIST; ``` If I then use the statement: ``` STRLIST list; ``` This is both a declaration and definition. So, how do apply the same principle of using an extern?
2016/07/05
[ "https://Stackoverflow.com/questions/38194057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1655700/" ]
To declare an *instance of* a struct (or a pointer to one): ``` extern STRLIST* ptrList; extern STRLIST list; ``` To define it: ``` STRLIST* ptrList; STRLIST list; ``` To declare a *struct type*: ``` typedef struct STRLIST; ``` To define it: ``` typedef struct { size_t size; char * strings[]; } STRLIST; ``` Note that you can use a pointer to a struct with only a declaration, but you must have a definition to use the struct directly.
25,912
There is a dataset that contains body mass ($x$) and metabolic rate ($y$) from many different organisms. It is common to fit the data to the model of the form $y=ax^b$ and estimate the parameters $a$ and $b$ (see [Kleiber's law](http://en.wikipedia.org/wiki/Kleiber%27s_law) and [The Metabolic theory of ecology](http://en.wikipedia.org/wiki/Metabolic_theory_of_ecology)). In doing so, it is also common to log transform $y$ and $x$ and create the linear relationship log($y$)=log($a$)+$b$log($x$) and perform linear regression analysis based on the log transformed data. Is this approach better than directly estimating $a$ and $b$ based on nonlinear regression for $y=ax^b$ (because results are different)?
2014/12/16
[ "https://biology.stackexchange.com/questions/25912", "https://biology.stackexchange.com", "https://biology.stackexchange.com/users/11555/" ]
**Short answer**: The results of the two approaches (linear versus non-linear model) do not match because the relationship between body mass and basal metabolic rate does not strictly follow a power law. --- It is indeed the case that if the relationship between two variables follows a power law the two approaches should provide comparable results, but important differences could arise due to [Jensen's inequality](https://stats.stackexchange.com/a/58077/97671). In order to test whether the reported differences between the two approaches are due to Jensen's inequality or to some biological factor I obtained data from [Kolokotrones et al. (2010)](https://www.nature.com/nature/journal/v464/n7289/full/nature08920.html) who have in turn taken them from [McNab (2008)](http://www.sciencedirect.com/science/article/pii/S1095643308007782). [Kolokotrones et al. (2010)](https://www.nature.com/nature/journal/v464/n7289/full/nature08920.html) investigated the issue of whether a power law is appropriate by performing linear regression on log-transformed data but they did not attempt to fit the data with non-linear regression. I've fitted a non-linear model of the form: $$ B = \alpha M^b$$ , where $M$ the body mass (in grams) and $B$ the basal metabolic rate (in Watts), which gave coefficients $\alpha = 0.005$ and $b = 0.87$. I also fitted a linear model of the form: $$ log\_{10}(B) = blog\_{10}(M) + log\_{10}(\alpha) $$ which gave coefficients $ \alpha = -1.7 $ and $ b = 0.72 $. It appears that the results of the two approaches are indeed different. Below I plot the results of the two fits. On the variables' original scale we see that the linear model fails to predict observations from species with large mass and that the non-linear model does much better in this respect (upper left). However, when we look at the two models after log-transform, it is clear that the non-linear model fails to predict many observations from species with low mass (upper right). Looking at the residuals of the non-linear model we see that the errors are multiplicative as the variance of the residuals is increasing with (log-transformed) fitted values (bottom left). This indicates that fitting with a linear model on log-transformed data is warranted. However, the plot of linear model's residuals over log-transformed fitted values (bottom right) confirms that the linearity assumption is violated. Thus, neither method is appropriate for this dataset and the quadratic term the authors of the cited paper added in the linear model fitted on the log-transformed variables appears to be warranted in order to account for the observed convexity. [![enter image description here](https://i.stack.imgur.com/LGbf5.png)](https://i.stack.imgur.com/LGbf5.png) We can conclude that for this dataset the results of the linear model approach do not match those of the non-linear model approach because *the data do not strictly follow a power law*. Rather, the megafauna appears to follow a different trend compared to smaller animals. [Kolokotrones et al. (2010)](https://www.nature.com/nature/journal/v464/n7289/full/nature08920.html) found that adjusting for temperature improved the linear fit, in addition to the inclusion of the quadratic term. The resulting model was: $$ log\_{10}B = \beta\_0 + \beta\_1log\_{10}M + \beta\_2(log\_{10}M)^2 + \frac{\beta\_T}{T} + \epsilon $$ The R code used to generate the results for this answer along with the data used can be found in the following git repository in GitLab: <https://gitlab.com/vkehayas-public/metabolic_scaling> **References** Kolokotrones, T., Van Savage, Deeds, E. J., & Fontana, W. (2010). Curvature in metabolic scaling. *Nature*, **464**:7289, 753–756. [https://doi.org/10.1038/nature08920](https://www.nature.com/nature/journal/v464/n7289/full/nature08920.html) McNab, B.K. (2008). An analysis of the factors that influence the level and scaling of mammalian BMR. *Comparative Biochemistry and Physiology Part A: Molecular & Integrative Physiology*, **151**:1, 5-28. [https://doi.org/10.1016/j.cbpa.2008.05.008](http://www.sciencedirect.com/science/article/pii/S1095643308007782).
11,003,318
I am trying to make a gridview with large icon for an app but I couldn't find any tutorial about modifying a cell size on a grid layout on android. Can anyone give me an example or a link about it please? Thanks.
2012/06/12
[ "https://Stackoverflow.com/questions/11003318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/869360/" ]
just like the other [adapterViews](http://developer.android.com/reference/android/widget/AdapterView.html) ,on gridView (which extends adapterView) the size that is determined of the children is based on the size that they want to become , as written in the android API: > > An AdapterView is a view whose children are determined by an Adapter. > > >
57,340,976
I have the following list: ``` <ul class="nav nav-pills nav-pills-warning nav-pills-icons justify-content-center" role="tablist"> <li class="nav-item"> <a class="nav-link" data-toggle="tab" data-role-slug="admin" href="#" "="" role="tablist"> <i class="material-icons">supervisor_account</i> Admins </a> </li> <li class="nav-item"> <a class="nav-link active show" data-toggle="tab" data-role-slug="operator" href="#" role="tablist"> <i class="material-icons">person</i> Operators </a> </li> </ul> ``` I need to get the attribute `data-role-slug` I actually get the value in the following way: ``` $('a[data-role-slug]').on('click', function (e) { let roleSlug = $(e.target).data('role-slug'); console.log(roleSlug); }); ``` the method works well, the only problem happen when the user click on the `<i>` tag inside the `<a>` tag, in that case the `roleSlug` will be `undefined`. Is there a way to handle this issue without hard code?
2019/08/03
[ "https://Stackoverflow.com/questions/57340976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10950788/" ]
Just use `this` inside the event handler. It will be the `<a>` instance the event occurred on regardless of what child is targeted Or alternatively `e.currentTarget` will return the same instance as well ``` $('a[data-role-slug]').on('click', function (e) { let roleSlug = $(this).data('role-slug'); // OR $(e.currentTarget).data('role-slug'); console.log(roleSlug); }); ```
1,068,974
I have a PL/SQL function in an Oracle database that I can't change. This function takes a parameter which identifies an entity, creates a copy of that entity and then returns the ID of the copy. This looks something like FUNCTION copy\_entity(id IN NUMBER) RETURN NUMBER I need to call this function from Hibernate. I tried creating a named SQL query with something similar to CALL copy\_entity(:id) as the query, but from this I can't seem to get the return value of the function. Hibernate's "return-scalar" and similar options require a column name to return and I don't have a column name. This lead me to SELECT copy\_entity(:id) AS newEntityId with "return-scalar" using newEntityId as column name, but this also did not work since Oracle then throws an exception that I can't call INSERT (to save the copy) in a SELECT. Is there any way to get the return value of such a PL/SQL function? The function is actually much more complex and still required in other parts of the app, so re-writing it is not really an option.
2009/07/01
[ "https://Stackoverflow.com/questions/1068974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3587/" ]
The problem is that ie6/ie7 will expand an empty element to the height of your font. You can get around this by adding `font-size:0` and `line-height:0` to `.menu ul li.separator`. A better solution would be to add a thicker bottom border to the `<li>` that is before the separator. ``` .menu ul li.sep {border-bottom-width:6px} <div class="menu"> <ul> <li><a href="#">Item 1</a></li> <li><a href="#">Item 2</a></li> <li class="sep"><a href="#">Item 3</a></li> <li><a href="#">Item 4</a></li> <li><a href="#">Item 5</a></li> <li><a href="#">Item 6</a></li> </ul> </div> ```
20,826,290
I'm trying to merge a two ImageViews to make them look like as one, but there's bounding box that prevents them to be totally next to each other. ![ImageViews bounding box](https://i.stack.imgur.com/rOS19.jpg) ``` <ImageView android:id="@+id/imageView1" android:layout_width="200dp" android:layout_height="200dp" android:layout_margin="0dp" android:padding="0dp" android:src="@drawable/plant" /> <ImageView android:layout_width="200dp" android:layout_height="200dp" android:layout_margin="0dp" android:padding="0dp" android:src="@drawable/red_base" /> ``` I tried setting padding and margin to 0 but it doesn't do it Note: those two pictures that I used don't have a blank space around them. Thanks!
2013/12/29
[ "https://Stackoverflow.com/questions/20826290", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1426489/" ]
``` set below two properties android:adjustViewBounds="true" android:scaleType="fitEnd" ```
248,370
I want to build a flat ground level deck approx 25x26ft. I have very limited space between the ground and the door, so it needs to be streamlined. I plan to use 3 26’ 2x10 as primary frame supports and than use 12’ 2x10 as joists with 12” spacing. Wondering how many posts do I need for each 26’ piece of lumber? Will 4 posts for each 26’ (6-1/2 apart) be enough? Also, will 12’ span for joists cause any issue? [![my plan](https://i.stack.imgur.com/qlMqH.jpg)](https://i.stack.imgur.com/qlMqH.jpg)
2022/04/27
[ "https://diy.stackexchange.com/questions/248370", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/25752/" ]
Contact your power company. Say: "Am I correct that my smart meter has a large contactor in it, so that you can remotely shut off my power with a few keystrokes on your computer?" And "If I have you do that for 10 minutes, will you require a permit and inspection to turn it back on?" And this may lead to a short conversation about exactly what it is that you are doing, and they are likely to say "Oh. That's fine." At which point, have them de-energize; check that it is de-energized; do your thing and call them to turn it back on. Note that this uses "Ethernet over Powerline" communication at grand scale which means *grandly bad* bit rate on a rather busy comm channel. So it can take some minutes for the command to actually get through the queue.
36,552,197
I'm trying to implement a Fast Fourier Transform (Radix-2) in MS's Excel VBA. The code I'm using pulls data from a range in the worksheet, does the calculations, then dumps the results in the adjacent columns. What I'm having trouble with is 1) know what to do with the resulting X[k] arrays, and 2) matching these results with the results from Excel's built in FFT (they do not currently match). The code is shown below. Thanks in advance for your help. ``` Sub Enforce_DecimationInTime() On Error GoTo ERROR_HANDLING Dim SubName As String SubName = "Enforce_DecimationInTime()" Dim WS As Worksheet Dim n As Long, v As Long, LR As Long, x As Long Set WS = Worksheets("FFT") LR = WS.Range("A" & Rows.Count).End(xlUp).Row n = LR - 1 Do Until 2 ^ x <= n And 2 ^ (x + 1) > n 'locates largest power of 2 from size of input array x = x + 1 Loop n = n - (n - 2 ^ x) 'calculates n using the largest power of 2 If n + 1 <> WS.Range("A" & Rows.Count).End(xlUp).Row Then WS.Range("A" & 2 ^ x + 2 & ":A" & LR).Delete xlUp 'deletes extra input data End If v = WorksheetFunction.Log(n, 2) 'calculates number of decimations necessary Application.ScreenUpdating = False For x = 1 To v Call Called_Core.DecimationInTime(WS, n, 2 ^ x, x) 'calls decimation in time subroutine Next x Application.ScreenUpdating = True Exit Sub ERROR_HANDLING: MsgBox "Error encountered in " & SubName & ": exiting subroutine." _ & vbNewLine _ & vbNewLine & "Error description: " & Err.Description _ & vbNewLine & "Error number: " & Err.Number, vbCritical, Title:="Error!" End End Sub ``` The above subroutine calls the below subroutine through a For/Next loop to the count of "v". ``` Sub DecimationInTime(WS As Worksheet, n As Long, Factor As Integer, x As Long) On Error GoTo ERROR_HANDLING Dim SubName As String SubName = "DecimationInTime()" Dim f_1() As Single, f_2() As Single Dim i As Long, m As Long, k As Long Dim TFactor_N1 As String, TFactor_N2 As String, X_k() As String Dim G_1() As Variant, G_2() As Variant ReDim f_1(0 To n / Factor - 1) As Single ReDim f_2(0 To n / Factor - 1) As Single ReDim G_1(0 To n / 1 - 1) As Variant ReDim G_2(0 To n / 1 - 1) As Variant ReDim X_k(0 To n - 1) As String TFactor_N1 = WorksheetFunction.Complex(0, -2 * WorksheetFunction.Pi / (n / 1)) 'twiddle factor for N TFactor_N2 = WorksheetFunction.Complex(0, -2 * WorksheetFunction.Pi / (n / 2)) 'twiddle factor for N/2 For i = 0 To n / Factor - 1 f_1(i) = WS.Range("A" & 2 * i + 2).Value 'assign input data f_2(i) = WS.Range("A" & 2 * i + 3).Value 'assign input data Next i WS.Cells(1, 1 + x).Value = "X[" & x & "]" 'labels X[k] column with k number For k = 0 To n / 2 - 1 For m = 0 To n / Factor - 1 G_1(m) = WorksheetFunction.ImProduct(WorksheetFunction.ImPower(TFactor_N2, k * m), WorksheetFunction.Complex(f_1(m), 0)) 'defines G_1[m] G_2(m) = WorksheetFunction.ImProduct(WorksheetFunction.ImPower(TFactor_N2, k * m), WorksheetFunction.Complex(f_2(m), 0)) 'defines G_2[m] Next m X_k(k) = WorksheetFunction.ImSum(WorksheetFunction.ImSum(G_1), WorksheetFunction.ImProduct(WorksheetFunction.ImSum(G_2), WorksheetFunction.ImPower(TFactor_N1, k))) 'defines X[k] for k If k <= n / 2 Then X_k(k + n / 2) = WorksheetFunction.ImSum(WorksheetFunction.ImSum(G_1), WorksheetFunction.ImProduct(WorksheetFunction.ImSum(G_2), WorksheetFunction.ImPower(TFactor_N1, k), WorksheetFunction.Complex(-1, 0))) 'defines X[k] for k + n/2 WS.Cells(k + 2, 1 + x).Value = X_k(k) WS.Cells(k + 2 + n / 2, 1 + x).Value = X_k(k + n / 2) Next k Exit Sub ERROR_HANDLING: MsgBox "Error encountered in " & SubName & ": exiting subroutine." _ & vbNewLine _ & vbNewLine & "Error description: " & Err.Description _ & vbNewLine & "Error number: " & Err.Number, vbCritical, Title:="Error!" End End Sub ```
2016/04/11
[ "https://Stackoverflow.com/questions/36552197", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5748328/" ]
I went back through the process and determined my problem was that I had assigned the wrong values to the twiddle factors, TFactor\_N1 and TFactor\_N2. After fixing this problem and adjusting which values are displayed, I was able to get the same results as Excel's built in FFT. The fixed code is show below. ``` Sub Enforce_DecimationInTime() On Error GoTo ERROR_HANDLING Dim SubName As String SubName = "Enforce_DecimationInTime()" Dim WS As Worksheet Dim n As Long, v As Long, LR As Long, x As Long Dim TFactor_N1 As String, TFactor_N2 As String Set WS = Worksheets("FFT") LR = WS.Range("A" & Rows.Count).End(xlUp).Row n = LR - 1 Do Until 2 ^ x <= n And 2 ^ (x + 1) > n 'locates largest power of 2 from size of input array x = x + 1 Loop n = n - (n - 2 ^ x) 'calculates n using the largest power of 2 If n + 1 <> WS.Range("A" & Rows.Count).End(xlUp).Row Then WS.Range("A" & 2 ^ x + 2 & ":A" & LR).Delete xlUp 'deletes extra input data End If v = WorksheetFunction.Log(n, 2) 'calculates number of decimations necessary TFactor_N1 = WorksheetFunction.ImExp(WorksheetFunction.Complex(0, -2 * WorksheetFunction.Pi / (n / 1))) 'twiddle factor for N TFactor_N2 = WorksheetFunction.ImExp(WorksheetFunction.Complex(0, -2 * WorksheetFunction.Pi / (n / 2))) 'twiddle factor for N/2 Application.ScreenUpdating = False For x = 1 To v Call Called_Core.DecimationInTime(WS, n, 2 ^ x, x, TFactor_N1, TFactor_N2) 'calls decimation in time subroutine Next x Application.ScreenUpdating = True Exit Sub ERROR_HANDLING: MsgBox "Error encountered in " & SubName & ": exiting subroutine." _ & vbNewLine _ & vbNewLine & "Error description: " & Err.Description _ & vbNewLine & "Error number: " & Err.Number, vbCritical, Title:="Error!" End End Sub Sub DecimationInTime(WS As Worksheet, n As Long, Factor As Integer, x As Long, TFactor_N1 As String, TFactor_N2 As String) On Error GoTo ERROR_HANDLING Dim SubName As String SubName = "DecimationInTime()" Dim f_1() As String, f_2() As String Dim i As Long, m As Long, k As Long Dim X_k() As String Dim G_1() As Variant, G_2() As Variant ReDim f_1(0 To n / Factor - 1) As String ReDim f_2(0 To n / Factor - 1) As String ReDim G_1(0 To n / 1 - 1) As Variant ReDim G_2(0 To n / 1 - 1) As Variant ReDim X_k(0 To n - 1) As String For i = 0 To n / Factor - 1 f_1(i) = WS.Cells(2 * i + 2, 1).Value 'assign input data f_2(i) = WS.Cells(2 * i + 3, 1).Value 'assign input data Next i For k = 0 To n / 2 - 1 For m = 0 To n / Factor - 1 'defines G_1[m] and G_2[m] G_1(m) = WorksheetFunction.ImProduct(WorksheetFunction.ImPower(TFactor_N2, k * m), f_1(m)) G_2(m) = WorksheetFunction.ImProduct(WorksheetFunction.ImPower(TFactor_N2, k * m), f_2(m)) Next m 'defines X[k] for k and k + n/2 X_k(k) = WorksheetFunction.ImSum(WorksheetFunction.ImSum(G_1), WorksheetFunction.ImProduct(WorksheetFunction.ImSum(G_2), WorksheetFunction.ImPower(TFactor_N1, k))) If k <= n / 2 Then X_k(k + n / 2) = WorksheetFunction.ImSub(WorksheetFunction.ImSum(G_1), WorksheetFunction.ImProduct(WorksheetFunction.ImSum(G_2), WorksheetFunction.ImPower(TFactor_N1, k))) If x = 1 Then WS.Cells(k + 2, 1 + x).Value = X_k(k) WS.Cells(k + 2 + n / 2, 1 + x).Value = X_k(k + n / 2) End If Next k Exit Sub ERROR_HANDLING: MsgBox "Error encountered in " & SubName & ": exiting subroutine." _ & vbNewLine _ & vbNewLine & "Error description: " & Err.Description _ & vbNewLine & "Error number: " & Err.Number, vbCritical, Title:="Error!" End End Sub ```
46,465,366
I tried to create a spring boot deployable war file and then deployed it to weblogic 12c. Application startup failed with the exception: ``` Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled. ERROR SpringApplication - Application startup failed org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'graphQLServletRegistrationBean' defined in class path resource ... ``` Nested exception is: ``` java.lang.IllegalStateException: No *.graphqls files found on classpath. Please add a graphql schema to the classpath or add a SchemaParser bean to your application context. ``` In fact, the above mentioned files `*.graphqls` exist in the war under `WEB-INF/classes/` folder. If the war file was unzipped to the local disk and redeploy the app in exploded format, we won't see this exception. Do I miss anything? Thanks.
2017/09/28
[ "https://Stackoverflow.com/questions/46465366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3432316/" ]
I wasted 8 hours in this loophole, piecing together various clues I got from other people facing the same problem. \*\*solution 1 is to deploy your application as exploded WAR in Weblogic. I assume you already prepared your spring boot application for deployment on Weblogic, there are several tricks on this topic but they are available on the Internet (exclude embedded tomcat and specify WAR packaging in POM.XML, create webapp/WEB-INF folder with weblogic.xml and servlet xml). Now create a folder on the server, /home/oracle/wars/myapp for example, and just copy the unpacked contents of your WAR to that folder. Then go to Deployments - Install, navigate to /home/oracle/wars/ and choose myapp folder from the radio button list, and simply follow the default steps to deploy. Pay attention, you need a plain web.xml file along with weblogic.xml, otherwise Weblogic will not see it as 'Web application'\*\* Deploying as exploded WAR is a workaround to avoid the creation of \_wl\_cls\_gen.jar which is at the source of this problem. \*\* Solution 2 By default the lookup location is set to "classpath:graphql/\*\*/" which is not picked up by PathMatchingResourcePatternResolver. Set this in your application yaml or properties: ``` spring: graphql: schema: locations: classpath*:graphql/**/ ``` Finally, for this particular error, \*\*/\*.graphqls file not found when deploying to weblogic, nothing of the below worked, I am mentioning it so you don't waste your time as well: 1. Adding resource tag in POM src/main/resources \*\*/\*.properties \*\*/\*.graphqls 2. Adding in application.properties graphql.tools.schema-location-pattern=\*\*/\*.graphqls 3. Adding in application.properties graphql.servlet.exception-handlers-enabled=true 4. Newer versions of GraphQL libraries, I tried it and everything fails with this error from graphql 7.0.1 onwards 5. Adding spring-boot-starter-parent in POM
38,819
[This question on SO](https://stackoverflow.com/questions/2215314/sybase-central-issues-on-64-bit-windows-2008-server-r2) clearly belongs elsewhere, but the asker already put a bounty on the question. If the question is migrated, does the rep get refunded? Does the question continue to be a bounty question on the target site if the user has enough rep? (The asker in the referenced question does not have any associated accounts, but I'm curious about what happens.) Edit: I just tried to add my own close vote, but apparently you can't when there's an open bounty. However, a mod should still be able to close/migrate/etc.
2010/02/09
[ "https://meta.stackexchange.com/questions/38819", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/136558/" ]
The correct procedure would be to flag for moderator attention. If required diamond moderators can migrate the question by removing the bounty. * Bounty is removed and refunded * Question is closed and migrated I have flagged the question as well for the SO mods to look at it
58,286,178
I have a simple input with an ngModel in it, the thing is that I can't see in real time what that ngModel contains and I get an error saying `Cannot read property 'content' of undefined` ```html <input ([ngModel])="page.content" /> {{ page.content }} ``` ```js export interface Page { uid: string; content: string; } @Input() page: Page; ngOnInit() { console.log(this.page.content) } ``` So, this is what I tried and what I'm trying to do is to get a `console.log` of the things I have typed in real-time as I am typing in the `<input ([ngModel])="page.content" />` Here is a [stackblitz](https://stackblitz.com/edit/angular-b8sps6) for reference
2019/10/08
[ "https://Stackoverflow.com/questions/58286178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12025029/" ]
This happens because during the Angular lifecycle when your page is first created the value of page is null. What you can do in your .html you could do this : `[(ngModel)]="page?.content"`. This checks if page exists before trying to access content. Hope this helps!
72,875,246
I created a Service to read data from the database. In order to achieve that, I want to make a Controller and throw this controller I want to call first the `ReadingDataService`. **Error Message:** > > **Too few arguments** to function `TryPlugin\Service\ReadingData::__construct()`, **1 passed** in `/var/www/html/var/cache/dev_he0523cc28be2f689acaab5c325675d68/ContainerFt0wDoq/Shopware_Production_KernelDevDebugContainer.php` on line 25455 and **exactly 2 expected** > > > **Code:** **ReadingData.php** ```php class ReadingData { private EntityRepositoryInterface $productRepository; private Context $con; public function __construct(EntityRepositoryInterface $productRepository, Context $con) { $this->productRepository = $productRepository; $this->con = $con; } public function readData(): void { $criteria1 = new Criteria(); $products = $this->productRepository->search($criteria1, $this->con)->getEntities(); } } ``` **PageController.php** ```php /** * @RouteScope (scopes={"storefront"}) */ class PageController extends StorefrontController { /** * @Route("/examples", name="examples", methods={"GET"}) */ public function showExample(ReadingData $ReadingDatan): Response { $meinData = $ReadingDatan->readData(); return $this->renderStorefront('@Storefront/storefront/page/content/index.html.twig', [ 'products' => $meinData, ]); } } ``` **Service.xml:** ```xml <service id="TryPlugin\Service\ReadingData"> <argument type="service" id="product.repository"/> </service> <!--ReadingDate From Controller--> <service id="TryPlugin\Storefront\Controller\PageController" public="true"> <call method="setContainer"> <argument type="service" id="service_container"/> </call> <tag name="controller.service_arguments"/> </service> ```
2022/07/05
[ "https://Stackoverflow.com/questions/72875246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17204096/" ]
You need to pass the 2nd argument in `service.xml` -------------------------------------------------- Your class requires two arguments: ```php public function __construct(EntityRepositoryInterface $productRepository, Context $con) { //... ``` but only provides one in `service.xml`: ```xml <service id="TryPlugin\Service\ReadingData"> <argument type="service" id="product.repository"/> <!-- Need argument for `Context $con` --> </service> ``` Looking at the documentation, `Context` does not appear to be [autowired](https://symfony.com/doc/current/service_container/autowiring.html) by default. Therefore, you must [inject the service](https://developer.shopware.com/docs/guides/plugins/plugins/plugin-fundamentals/dependency-injection) yourself in `service.xml`. If you grow tired of all ways specifying the arguments in `service.xml`, look into enabling and configuring [autowire for ShopWare](https://symfony.com/doc/current/service_container/autowiring.html).
2,398,161
I'm trying to add paths to my classpath in the Clojure REPL that I've set up in Emacs using ELPA. Apparently, this isn't the $CLASSPATH environment variable, but rather the swank-clojure-classpath variable that Swank sets up. Because I used ELPA to install Swank, Clojure, etc., there are a ton of .el files that take care of everything instead of my .emacs file. Unfortunately, I can't figure out how to change the classpath now. I've tried using (setq 'swank-clojure-extra-classpaths (list ...)) both before and after the ELPA stuff in my .emacs, and I've tried adding paths directly to swank-clojure-classpath in .emacs, .emacs.d/init.el, and .emacs.d/user/user.el, but nothing works. What I'm ultimately trying to do is to add both the current directory "." and the directory in which I keep my Clojure programs. I'm assuming swank-clojure-classpath is the thing I need to set here. Thanks for your help.
2010/03/07
[ "https://Stackoverflow.com/questions/2398161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/288389/" ]
As mac says, you can use ``` M-x swank-clojure-project ``` to establish a slime REPL to a clojure project; the command will ask you for your projects root directory, and will establish a classpath that includes a variety of directories including src/ lib/ and resources/ if they are present. Alternatively, if you are using leiningen, you can start that in a terminal with the command ``` $ lein swank ``` from inside your project root directory. This will establish a standard project classpath (as above). From here you can connect to this running process via Emacs with the command ``` M-x slime-connect ``` Finally a third option which I'd recommend is to connect via Emacs/slime (with `M-x slime-connect`) to a process started by your own shell script which specifies a custom set of JVM command line arguments e.g. ``` #!/bin/bash java -server -cp "./lib/*":./src clojure.main -e "(do (require 'swank.swank) (swank.swank/start-repl))" ``` This allows you explicit control over how the VM is started, and is likely similar to what you will likely have to do in production anyway.
55,508,892
I have a button to backup my local database(SQLITE) to another path so that I can email the file to me. How can I copy the SQLite data to my for example downloads folder? Here is the code of my backup button: ``` private void BtnBackup_Clicked(object sender, EventArgs e) { string fileName = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "backend.db3"); string backupfile = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments), "backup.db3"); File.Copy(fileName, backupfile, true); } ``` I can check if the data has been copied the problem is when I go to the directory no files is being shown
2019/04/04
[ "https://Stackoverflow.com/questions/55508892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I guess your database is MS SQL Server. SQL Server stores time in `HH:MI:SS` format. Use `TimeSpan` in your model to store/get the data. Here is another possible solution: [How to save time only without the date using ASP.NET MVC 5 Data Annotation "DataType.Time?](https://stackoverflow.com/questions/24693572/how-to-save-time-only-without-the-date-using-asp-net-mvc-5-data-annotation-data)
17,528,159
How to remove curly brackets in R? Eg. "{abcd}" to "abcd" How can I use gsub function in R to do this? If any other method is available, please suggest.
2013/07/08
[ "https://Stackoverflow.com/questions/17528159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2560936/" ]
Try this ``` gsub("\\{|\\}", "", "{abcd}") [1] "abcd" ``` Or this ``` gsub("[{}]", "", "{abcd}") ```
51,859,100
After trying to install 'models' module I get this error: ``` C:\Users\Filip>pip install models Collecting models Using cached https://files.pythonhosted.org/packages/92/3c/ac1ddde60c02b5a46993bd3c6f4c66a9dbc100059da8333178ce17a22db5/models-0.9.3.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\Filip\AppData\Local\Temp\pip-install-_exhlsc1\models\setup.py", line 25, in <module> import models File "C:\Users\Filip\AppData\Local\Temp\pip-install-_exhlsc1\models\models\__init__.py", line 23, in <module> from base import * ModuleNotFoundError: No module named 'base' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in C:\Users\Filip\AppData\Local\Temp\pip-install-_exhlsc1\models\ ``` If I try to install module 'base' this error shows up: ``` C:\Users\Filip>pip install base Collecting base Using cached https://files.pythonhosted.org/packages/1b/e5/464fcdb2cdbafc65f0b2da261dda861fa51d80e1a4985a2bb00ced080549/base-1.0.4.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\Filip\AppData\Local\Temp\pip-install-ueghc4dh\base\setup.py", line 40, in <module> LONG_DESCRIPTION = read("README.rst") File "C:\Users\Filip\AppData\Local\Temp\pip-install-ueghc4dh\base\setup.py", line 21, in read return codecs.open(os.path.join(os.path.dirname(__file__), fname)).read() File "c:\users\filip\appdata\local\programs\python\python37-32\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 5: character maps to <undefined> ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in C:\Users\Filip\AppData\Local\Temp\pip-install-ueghc4dh\base\ ``` If I attempt to install other packages, everything works, setuptools and pip are updated. It's crucial I have this module for my project and I can't do shit without it.
2018/08/15
[ "https://Stackoverflow.com/questions/51859100", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9990279/" ]
It looks like `models` [was renamed](https://pypi.org/project/models/) to [pymodels](https://pypi.org/project/pymodels/) then renamed again to [doqu](https://pypi.org/project/doqu/) [(source code)](https://bitbucket.org/neithere/doqu/) which I was able to install the latest version from pypi. Is this legacy code? Will Doqu work for your purposes? `pip install doqu`
69,669,752
I'm using an angular material tree to display a deeply nested object. While building the tree, how do I store the current path along with the values? ``` const TREE_DATA = JSON.parse(JSON.stringify({ "cars": [ { "model": "", "make": "Audi", "year": "" }, { "model": "A8", "make": "", "year": "2007" } ], "toys": { "color": "Black", "type": [ { "brand": "", "price": "$100" } ] }, "id": "xyz", "books": [ { "publisher": [ { "authors": [] } ] } ], "extra": "test" })); @Injectable() export class FileDatabase { dataChange = new BehaviorSubject<FileNode[]>([]); get data(): FileNode[] { return this.dataChange.value; } constructor() { this.initialize(); } initialize() { const dataObject = JSON.parse(TREE_DATA); const data = this.buildFileTree(dataObject, 0); this.dataChange.next(data); } buildFileTree(obj: {[key: string]: any}, level: number): FileNode[] { return Object.keys(obj).reduce<FileNode[]>((accumulator, key) => { const value = obj[key]; const node = new FileNode(); node.filename = key; if (value != null) { if (typeof value === 'object') { node.children = this.buildFileTree(value, level + 1); } else { node.type = value; } } return accumulator.concat(node); }, []); } } ``` Currently, the buildFileTree function returns: ``` [ { "filename": "cars", "children": [ { "filename": "0", "children": [ { "filename": "model", "type": "" }, { "filename": "make", "type": "Audi" }, { "filename": "year", "type": "" } ] }, { "filename": "1", "children": [ { "filename": "model", "type": "A8" }, { "filename": "make", "type": "" }, { "filename": "year", "type": "2007" } ] } ] }, { "filename": "toys", "children": [ { "filename": "color", "type": "Black" }, { "filename": "type", "children": [ { "filename": "0", "children": [ { "filename": "brand", "type": "" }, { "filename": "price", "type": "$100" } ] } ] } ] }, { "filename": "id", "type": "a" }, { "filename": "books", "children": [ { "filename": "0", "children": [ { "filename": "publisher", "children": [ { "filename": "0", "children": [ { "filename": "authors", "type": [] } ] } ] } ] } ] }, { "filename": "extra", "type": "test" } ] ``` While building this tree, how can I add the path to every "type" at every level? Something like "path": "cars.0.model" for the first "type" and so on.
2021/10/21
[ "https://Stackoverflow.com/questions/69669752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8882952/" ]
See this issue on TypeScript's GitHub project: [Module path maps are not resolved in emitted code (#10866)](https://github.com/microsoft/TypeScript/issues/10866) tl;dr ===== * TypeScript won't rewrite your module paths * `paths` was designed to help TypeScript understand path aliases used by bundlers * You'll either need to: + use a bundler, such as [webpack](https://webpack.js.org/), and configure its own path maps + use a build time tool, such as [tspath](https://www.npmjs.com/package/tspath), to rewrite the paths + modify the runtime module resolver, with something like [module-alias](https://www.npmjs.com/package/module-alias)
34,627,181
In Sublime text `cmd+shift+v` will paste and indent the code. Can this be done in visual studio code? **Workaround** I've made an extension that will let you paste and format with `cmd/ctrl+shift+v`. Search for `pasteandformat` <https://marketplace.visualstudio.com/items?itemName=spoeken.pasteandformat>
2016/01/06
[ "https://Stackoverflow.com/questions/34627181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/800011/" ]
Currently, Visual Studio Code doesn't provide this specific functionality. We could vote for this feature at [Visual Studio's UserVoice](https://visualstudio.uservoice.com/forums/121579-visual-studio-2015) website. There's already a ticket open for this feature: [Paste and auto align code](https://visualstudio.uservoice.com/forums/293070-visual-studio-code/suggestions/8626678-paste-and-auto-align-code). If you've got an account, you can vote for this feature so it gets more attention. If it has enough attention, Visual Studio Code's developers could take notice of this and maybe develop it. **Current workaround** After pasting the code, You could use **CTRL+E, CTRL+D** for windows or **ALT+SHIFT+F** for mac. But note that this will reformat the whole document, indenting according to the available rules for the source type. If you only want this to be applied to the pasted code, select the code after pasting and then use **CTRL+E, CTRL+D** for windows or **ALT+SHIFT+F** for mac. Now the indenting/formatting is only applied to the pasted lines.
449,283
I have a collection of reviewers who are rating applications. Each application is reviewed by at least two people and they give a score between 0 and 50 among various criteria. Looking at the mean for each reviewer, it's seems a few rated more harshly than others, and that they give disproportionately lower scores to applicants who by luck happen to get evaluated by more critical reviewers. The mean of all applications reviews is 34.5. There are 22 reviewers, and their means range from 29.7 to 38.7. The standard deviation of population for all applications is 5.6. I'm wondering how to go about adjusting the mean for reviewers to create a more equitable rating among all applicants, or if these numbers are within the normal expected variation. Thanks in advance. [![enter image description here](https://i.stack.imgur.com/029nX.png)](https://i.stack.imgur.com/029nX.png)
2020/02/13
[ "https://stats.stackexchange.com/questions/449283", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/273625/" ]
Hopefully this isn't overkill, but I think this is a case where creating a linear model, and looking at the estimated marginal means, would make sense. Estimated marginal means are adjusted for the other terms in the model. That is, the E.M. mean score for student A can be adjusted for the effect of Evaluator 1. That is, how much higher or lower Evaluator 1 tends to rate students relative to the other evaluators. Minimally, you can conduct a classic anova to see if there is a significant effect of Evaluator. I have an example of this below in R. ***Edit:*** I suppose for this approach to make sense --- that is, be fair --- each evaluator should have evaluated relatively many students, and a random or representative cross-section of students. There is always a chance that an evaluator just happens to evaluate e.g. a group of poor students. In this case we would inaccurately suspect the evaluator of being a tough evaluator, when in fact it was just that their students were poor. But having multiple evaluators per student also makes this less likely. --- Create some toy data ``` Data = read.table(header=T, text=" Student Evaluator Score a 1 95 a 2 80 b 2 60 b 3 50 c 3 82 c 1 92 d 1 93 d 2 84 e 2 62 e 3 55 f 1 94 f 3 75 ") Data$Evaluator = factor(Data$Evaluator) ``` Create linear model ``` model = lm(Score ~ Student + Evaluator, data=Data) ``` Classic anova to see if there is an effect of Evaluator ``` require(car) Anova(model) ### Anova Table (Type II tests) ### ### Sum Sq Df F value Pr(>F) ### Student 1125.5 5 20.699 0.005834 ** ### Evaluator 414.5 2 19.058 0.009021 ** ### Residuals 43.5 4 ``` So, it looks like there is a significant effect of Evaluator. Look at simple arithmetic means ``` require(FSA) Summarize(Score ~ Student, data=Data) ### Student n mean sd min Q1 median Q3 max ### 1 a 2 87.5 10.606602 80 83.75 87.5 91.25 95 ### 2 b 2 55.0 7.071068 50 52.50 55.0 57.50 60 ### 3 c 2 87.0 7.071068 82 84.50 87.0 89.50 92 ### 4 d 2 88.5 6.363961 84 86.25 88.5 90.75 93 ### 5 e 2 58.5 4.949747 55 56.75 58.5 60.25 62 ### 6 f 2 84.5 13.435029 75 79.75 84.5 89.25 94 ``` Look at the adjusted means for Student ``` require(emmeans) emmeans(model, ~ Student) ### Student emmean SE df lower.CL upper.CL ### a 83.7 2.46 4 76.8 90.5 ### b 59.4 2.46 4 52.6 66.2 ### c 86.4 2.46 4 79.6 93.2 ### d 84.7 2.46 4 77.8 91.5 ### e 62.9 2.46 4 56.1 69.7 ### f 83.9 2.46 4 77.1 90.7 ### ### Results are averaged over the levels of: Evaluator ### Confidence level used: 0.95 ``` Note that some students' scores went up and others went down relative to arithmetic means.
35,827,150
I struggle since a few days to get a correct provisioning profile. I am an independent iOS dev with my own iTunes connect account but I recently started to develop for a development team. Since then, I can't get a correct provisionning profile to run my app from xCode to my iPhone. iOS documentation describes how to create certificates and provisionning profiles but it doesn't identify who needs to do each step (either me the developer, either the development team manager). Could you please describe who needs to do the following step : 1. Create a development certificate. To me, it should be me as it is me who develops. Then, I send it to the dev team manager who adds it in his member center. 2. App ID : The dev team manager create the app ID with a specific bundle ID 3. Devices : The dev team manager adds my iPhone UDID. 4. Provisioning profile : The dev team manager creates it from my certificates, the app ID and my device. Then, he sends me the file and I just have to double-click on it. However, this doesn't seem to work. Any idea how I can obtain a valid provisioning profile. PS 1 : I have been added in Itunes Connect and I can access to the app details. PS 2 : Bundle ID of the app in xCode and iTunes connect are the same (I've checked a hundred times).
2016/03/06
[ "https://Stackoverflow.com/questions/35827150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2521010/" ]
Each team member is responsible for creating their own key/cert pair and adding it to their machine via Keychain Access. That is for Development builds. Distribution certs can only be created by an admin. To create an app Id or provision on the member center you need to have admin access. If you don't have admin access then you have to rely on someone who does to create those. They would be responsible for making sure your device and cert are attached to then development provision for your app. Your problem could also be that your code signing settings are not setup correctly in the project. You should set provision to Automatic and identity to iOSDeveloper. This lets Xcode figure it out and also allows you to share the project in a team setting without code signing issues
6,685,140
I have many web applications in a Visual Studio solution. All have the same post build command: ``` xcopy "$(TargetDir)*.dll" "D:\Project\bin" /i /d /y ``` It would be useful to avoid replacing newer files with old ones (e.g. someone could accidentally add a reference to an old version of a DLL). How can I use xcopy to replace old files only with **newer DLL files** generated by Visual Studio?
2011/07/13
[ "https://Stackoverflow.com/questions/6685140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/66708/" ]
From typing "help xcopy" at the command line: ``` /D:m-d-y Copies files changed on or after the specified date. If no date is given, copies only those files whose source time is newer than the destination time. ``` So you already are using xcopy to only replace old files with new ones. If that's not happening, you may have to swap the positions of the `/i` and `/d` switches.
10,214,949
I have a function defined that way: ``` var myObject = new Object(); function myFunction(someString){ myObject.someString= 0; } ``` The problem is `someString` is taken as the string `someString` instead of the value of that variable. So, after I use that function several times over with different `someString`'s, I would like to get an object with all the values for each someString. But when I loop through that object The only result I get is `someString : 0` I want to get: ``` John : 0 James : 0 Alex : 0 etc.... ``` How do I do that? Thanks a lot in advance
2012/04/18
[ "https://Stackoverflow.com/questions/10214949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1290170/" ]
You can use the associative array approach: ``` var someString = 'asdf'; myObject[someString] = 0; // {asdf: 0} myObject['foo'] = 'bar'; ``` You can basically use any string to retrieve your method/parameter. ``` var i = 1; myObject['test' + i] = i + 1; // gives us {test1: 2} ```
69,619,770
I have a df that looks like this: [![enter image description here](https://i.stack.imgur.com/PBVX9.png)](https://i.stack.imgur.com/PBVX9.png) I want to remove the part that is equal to `ID` from `Name`, and then build three new variable which equal to the last two digit of `Name`, the 3 place in `Name', and 4th place in` Name". sth that will look like the following: [![enter image description here](https://i.stack.imgur.com/DPIQY.png)](https://i.stack.imgur.com/DPIQY.png) What should I do in order to achieve this goal? ``` df<-structure(list(Name = c("LABCPCM01", "TUNISCN02", "HONORCN01", "KUCCLCN02", "LABCPBF03", "LABCPBF04", "MFHLBCM01", "MFHLBCF01", "DRLLBCN01", "QDSWRCN03", "QDSWRCN04", "UTSWLHN01", "MGHCCBN02", "JHDPCHM01", "UNILBCF03", "UTSWLGN03", "PHCI0CN01", "PHCI0CN02" ), ID = c("LABCP", "TUNIS", "HONOR", "KUCCL", "LABCP", "LABCP", "MFHLB", "MFHLB", "DRLLB", "QDSWR", "QDSWR", "UTSWL", "MGHCC", "JHDPC", "UNILB", "UTSWL", "PHCI0", "PHCI0")), row.names = c(NA, -18L), class = c("tbl_df", "tbl", "data.frame")) ```
2021/10/18
[ "https://Stackoverflow.com/questions/69619770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13631281/" ]
Use [`split`](https://docs.python.org/3/library/stdtypes.html#str.split), then reverse the string and finally [`capitalize`](https://docs.python.org/3/library/stdtypes.html#str.capitalize): ``` s = 'this is the best' res = " ".join([si[::-1].capitalize() for si in s.split()]) print(res) ``` **Output** ``` Siht Si Eht Tseb ```
39,937,368
I want to know if it's authorized to avoid Thread deadlocks by making the threads not starting at the same time? Is there an other way to avoid the deadlocks in the following code? Thanks in advance! ``` public class ThreadDeadlocks { public static Object Lock1 = new Object(); public static Object Lock2 = new Object(); public static void main(String args[]) { ThreadDemo1 t1 = new ThreadDemo1(); ThreadDemo2 t2 = new ThreadDemo2(); t1.start(); try { Thread.sleep(100); } catch (InterruptedException e) { } t2.start(); } private static class ThreadDemo1 extends Thread { public void run() { synchronized (Lock1) { System.out.println("Thread 1: Holding lock 1..."); try { Thread.sleep(10); } catch (InterruptedException e) { } System.out.println("Thread 1: Waiting for lock 2..."); synchronized (Lock2) { System.out.println("Thread 1: Holding lock 1 & 2..."); } } } } private static class ThreadDemo2 extends Thread { public void run() { synchronized (Lock2) { System.out.println("Thread 2: Holding lock 2..."); try { Thread.sleep(10); } catch (InterruptedException e) { } System.out.println("Thread 2: Waiting for lock 1..."); synchronized (Lock1) { System.out.println("Thread 2: Holding lock 1 & 2..."); } } } } } ```
2016/10/08
[ "https://Stackoverflow.com/questions/39937368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5398064/" ]
There are two ways to get a deadlock: 1. Lock escalation. For example, a thread holding a shareable read lock tries to escalate to an exclusive write lock. If more than one thread holding a read lock tries to escalate to a write lock, a deadlock results. This doesn't apply to what you're doing. (Offhand, I don't even know if it's *possible* to escalate a lock in Java.) 2. Unspecified lock order. If thread A locks object 1, then tries to lock object 2, while thread B locks object 2 then tries to lock object 1, a deadlock can result. This is exactly what you're doing. Those are the only ways to get a deadlock. Every deadlock scenario will come down to one of those. If you don't want deadlocks, don't do either of those. Never escalate a lock, and always specify lock order. Those are the only ways to prevent deadlocks. Monkeying around with thread timing by delaying things is not guaranteed to work.
18,837,093
I'm converting pdf files to images with ImageMagic, everything is ok until I use `-resize` option, then I get image with black background. I use this command: ``` convert -density 400 image.pdf -resize 25% image.png ``` I need to use `-resize` option otherwise I get really large image. Is there any other option which I can use to resize image or is there option to set background in white.
2013/09/16
[ "https://Stackoverflow.com/questions/18837093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2581710/" ]
``` Select City, Sum(Money), Sum(Case When Age < 30 Then 1 Else 0 End), Sum(Case When Age > 30 Then 1 Else 0 End) From table Group By City ```
19,785,290
Assuming I have a class that does some heavy processing, operating with several collections. What I want to do is to make sure that such operation can't lead to out-of-memory or even better I want to set a threshold of how much memory it can use. ``` class MyClass() { public void myMethod() { for(int i=0; i<10000000; i++) { // Allocate some memory, may be several collections } } } class MyClassTest { @Test public void myMethod_makeSureMemoryFootprintIsNotBiggerThanMax() { new MyClass().myMethod(); // How do I measure amount of memory it may try to allocate? } } ``` What is the right approach to do this? Or this is not possible/not feasible?
2013/11/05
[ "https://Stackoverflow.com/questions/19785290", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1990089/" ]
I can think of several options: * Finding out how much memory your method requires via a microbenchmark (i.e. [jmh](http://openjdk.java.net/projects/code-tools/jmh/)). * Building allocation strategies based on heuristic estimation. There are several open source solutions implementing class size estimation i.e. [ClassSize](http://svn.apache.org/repos/asf/hbase/branches/0.89-fb/src/main/java/org/apache/hadoop/hbase/util/ClassSize.java). A much easier way could be utilizing a cache which frees rarely used objects (i.e. Guava's Cache). As mentioned by @EnnoShioji, Guava's cache has memory-based eviction policies. You can also write your own benchmark test which counts memory. The idea is to 1. Have a single thread running. 2. Create a new array to store your objects to allocate. So these objects won't be collected during GC run. 3. `System.gc()`, `memoryBefore = runtime.totalMemory() - runtime.freeMemory()` 4. Allocate your objects. Put them into the array. 5. `System.gc()`, `memoryAfter = runtime.totalMemory() - runtime.freeMemory()` This is a technique I used in my [lightweight micro-benchmark tool](https://github.com/chaschev/experiments-with-microbes/blob/master/src/test/java/com/chaschev/microbe/samples/MemConsumptionTest.java) which is capable of measuring memory allocation with byte-precision.
39,410,484
I have `View` with some components handles. I can change color of label like this. `labelHandle.setForeground(Color.Blue);` I want to make text of this `label` blinking - the idea is that on the `View` I will have method `blink(Boolean on)` and if I call `blink(true)` the method will start new thread which will be class implementing `Runnable`. loop of `run()` will be something like this ``` run() { for(;;) { if(finished == true) break; Thread.sleep(300); //this will do the blinking if(finished == true) break; //if durring sleep finish was called => end if(change) labelHandle.setForeground(Color.Blue); else labelHandle.setForeground(Color.Black); change = (change) ? false : true; //switch the condition } } ``` There will be some important points: ``` boolean finished - says if the thread is finished, the loop for bliniking void fihish() {this.finished = false;} //stops the thread job boolean change - switch for the collors, each end of loop switch this value, if its true set one color, if its false sets another => here we have blinking ... ``` Until here its pretty clear how to do it. The main idea is make thread which will carry about the blinking. In view I will call: ``` blink(true); blink(false); ``` which will stars and stops the thread. At one time only one view can be active, so I want have only one thread for blinking, which can be used with more views. The thread will be class implementing `Runnable` and should be `Singleton` to ensure, there will be only one thread. Is it good idea to make `Singleton` thread like this? (Good or bad practice)
2016/09/09
[ "https://Stackoverflow.com/questions/39410484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1097772/" ]
Just set the `.RequestTimeout` [property](https://msdn.microsoft.com/en-us/library/aa239748(v=vs.60).aspx): ``` With FTP .URL = strHostName .Protocol = 2 .UserName = strUserName .Password = strPassWord .RequestTimeout 5 '<------ .Execute , "Get " + strRemoteFileName + " " + strLocalFileName ```
4,631,616
my code broke somewhere along the way, and crashes when using the navigation bar buttons. Error message: `*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIView newMemoViewController:didAddMemo:]: unrecognized selector sent to instance 0x5b55a60'` When debugging, the program does run the `cancel` method, and throws an exception at the `@synthesize` line. However, I cannot see anything wrong with it. The symptoms are identical, so I am including the relevant code only for the `Cancel` button: **NewMemoViewController.h** ``` #import <UIKit/UIKit.h> @protocol NewMemoDelegate; @class AKVoiceMemo; @interface NewMemoViewController : UIViewController { @private AKVoiceMemo *voiceMemo; id <NewMemoDelegate> delegate; } @property (nonatomic, retain) AKVoiceMemo *voiceMemo; @property (nonatomic, assign) id <NewMemoDelegate> delegate; @end @protocol NewMemoDelegate <NSObject> - (void)newMemoViewController:(NewMemoViewController *)newMemoViewController didAddMemo:(AKVoiceMemo *)voiceMemo; @end ``` **NewMemoViewController.m** ``` #import "NewMemoViewController.h" @synthesize delegate; - (void)viewDidLoad { UIBarButtonItem *cancelButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonItemStyleBordered target:self action:@selector(cancel)]; self.navigationItem.leftBarButtonItem = cancelButtonItem; [cancelButtonItem release]; } - (void)cancel { [self.delegate newMemoViewController:self didAddMemo:nil]; } ``` Your help would be appreciated. **Edit**: the delegate is the `RootViewController`: ``` - (void)newMemoViewController:(NewMemoViewController *)newMemoViewController didAddMemo:(AKVoiceMemo *)voiceMemo { if (voiceMemo){ // Show the note in a new view controller // TODO: Implement this } [self dismissModalViewControllerAnimated:YES]; } ```
2011/01/08
[ "https://Stackoverflow.com/questions/4631616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/560496/" ]
You're probably setting the delegate of `NewMemoViewController` to a `UIView` object instead of an object that implements the `NewMemoDelegate` protocol. The error message is telling you that a `newMemoViewController:didAddMemo:` message was sent to a `UIView` object and the `UIView` object didn't know what to do with it. Since your `cancel` method calls `newMemoViewController:didAddMemo:` on the delegate, it is the *delegate* which is the `UIView` object that doesn't recognize the `newMemoViewController:didAddMemo:` message. In other words, your delegate is a `UIView` and it doesn't implement the `NewMemoDelegate` protocol. If you are correctly setting the delegate, then @jtbandes makes a great point: The delegate is probably being released and a `UIView` object is taking over the same memory location, thus "becoming" the delegate by accident. You're doing the right thing by using the `assign` attribute for your delegate; that's fairly standard Cocoa practice. However, you do need to make sure that the delegate is retained by another object, and *that* object needs to make sure that the delegate sticks around as long as `NewMemoViewController` needs it to.
23,824,950
``` <li class="row"> <div class="small-6 column center"> <img src="test.jpg"> </div> <div class="small-6 column center"> <p>hello</p> </div> </li> ``` I wish to make the hello p in the centre (vertically and horizontally) of it's column. I do this with the styles: ``` p{ bottom: 0; left: 0; margin: auto; position: absolute; top: 0; right: 0; } ``` The problem is, the second column is not the same height as the first column. How can I make it so that it is? Here's my styles for columns: ``` .row{ width: 100%; float: left; .column{ width: 100%; position: relative; float: left; display: block; background: yellow; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; padding: 10px; } .small-1 { width: 8.33333%; } .small-2 { width: 16.66667%;} .small-3 { width: 25%;} .small-4 { width: 33.33333%; } .small-5 { width: 41.66667%; } .small-6 { width: 50%; } .small-7 { width: 58.33333%; } .small-8 { width: 66.66667%; } .small-9 { width: 75%; } .small-10 { width: 83.33333%; } .small-11 { width: 91.66667%; } .small-12 { width: 100%; } } .pull-left{ float: left; } .pull-right{ float: right; } .center{ text-align: center; } ```
2014/05/23
[ "https://Stackoverflow.com/questions/23824950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1013512/" ]
try this:- ``` #include<stdio.h> #include<stdlib.h> /*Queue has five properties. capacity stands for the maximum number of elements Queue can hold. Size stands for the current size of the Queue and elements is the array of elements. front is the index of first element (the index at which we remove the element) and rear is the index of last element (the index at which we insert the element) */ typedef struct Queue { int capacity; int size; int front; int rear; int *elements; }Queue; /* crateQueue function takes argument the maximum number of elements the Queue can hold, creates a Queue according to it and returns a pointer to the Queue. */ Queue * createQueue(int maxElements) { /* Create a Queue */ Queue *Q; Q = (Queue *)malloc(sizeof(Queue)); /* Initialise its properties */ Q->elements = (int *)malloc(sizeof(int)*maxElements); Q->size = 0; Q->capacity = maxElements; Q->front = 0; Q->rear = -1; /* Return the pointer */ return Q; } void Dequeue(Queue *Q) { /* If Queue size is zero then it is empty. So we cannot pop */ if(Q->size==0) { printf("Queue is Empty\n"); return; } /* Removing an element is equivalent to incrementing index of front by one */ else { Q->size--; Q->front++; /* As we fill elements in circular fashion */ if(Q->front==Q->capacity) { Q->front=0; } } return; } int front(Queue *Q) { if(Q->size==0) { printf("Queue is Empty\n"); exit(0); } /* Return the element which is at the front*/ return Q->elements[Q->front]; } void Enqueue(Queue *Q,int element) { /* If the Queue is full, we cannot push an element into it as there is no space for it.*/ if(Q->size == Q->capacity) { printf("Queue is Full\n"); } else { Q->size++; Q->rear = Q->rear + 1; /* As we fill the queue in circular fashion */ if(Q->rear == Q->capacity) { Q->rear = 0; } /* Insert the element in its rear side */ Q->elements[Q->rear] = element; } return; } int main() { Queue *Q = createQueue(5); Enqueue(Q,1); Enqueue(Q,2); Enqueue(Q,3); Enqueue(Q,4); printf("Front element is %d\n",front(Q)); Enqueue(Q,5); Dequeue(Q); Enqueue(Q,6); printf("Front element is %d\n",front(Q)); } ```
1,115,973
I've noticed an increasing number of jobs that are asking for experience with data mining and business intelligence technologies. This sounds like an incredibly broad topic but where would one go if they wanted to develop at least a partial understanding of this stuff if it were to come up in an interview?
2009/07/12
[ "https://Stackoverflow.com/questions/1115973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/132153/" ]
A very good book with practical examples is the [Programming Collective Intelligence: Building Smart Web 2.0 Applications](https://rads.stackoverflow.com/amzn/click/com/0596529325) by Toby Segaran.
18,219
I'm going to try to provide a high level overview of the issue - realizing that more details/info will be necessary - but I don't want to write a novel that seems too overwhelming for people to respond to :) **Background**: Let's say I have 3 sets (A, B, C) of irregular point data of varying quality; A is "better" than B and B is "better" than C. One or more data sets might have data for a given point. **Goal**: Create a grid/map that contains the "best" possible data. **Example/Possible Solution**: Use some sort of inverse distance weighted algorithm in combination w/somehow weighting the better datasets more than the lower quality data sets. Please feel free to post follow-up questions as I know my original post is rather vague. Thanks in advance.
2011/12/26
[ "https://gis.stackexchange.com/questions/18219", "https://gis.stackexchange.com", "https://gis.stackexchange.com/users/1384/" ]
When "best" is interpreted as "minimum variance unbiased estimator," then **the answer is [cokriging](http://www.gammadesign.com/gswinhelp/kriging_and_cokriging/cokriging.htm)**. This technique views the three datasets as realizations of three correlated spatial stochastic processes. It characterizes the process and their correlations by means of a preliminary analysis, "variography." The variography can be informed by additional considerations such as the relative quality of the datasets: this would cause the analyst to prefer variogram models that assign higher variances to the lower-quality datasets. Then, the co-kriging algorithm itself uses the data and the variographic output (a set of "pseudo co-variograms") to predict any desired linear combination of the three datasets (such as the mean values of dataset "A" within specified grid cells). **A simple, limiting version of co-kriging** supposes the three datasets are not correlated with each other at all. In this case, each of the datasets can be kriged separately. (This means a variogram model is fit to each dataset separately and used separately to interpolate the data values onto a grid of specified locations.) The kriging output includes a kriging variance. Assuming each dataset represents the same physical quantity, the question becomes how to combine the three estimated values at each grid point into the "best" possible estimate of that quantity. The answer is to take a weighted average of the three estimates, using the reciprocals of the kriging variances as the weights. The result remains unbiased because the three inputs are unbiased by construction; weighting inversely by variance assures the result has the smallest variance, which is exactly what "best" was assumed to mean. **Kriging and co-kriging are available** in the Geostatistical Analyst add-on for ArcGIS (at an extra cost) and in freely available software such as the [gstat](http://www.itc.nl/~rossiter/teach/R/R_ck.pdf) package for R. These are not activities to be undertaken casually: they are sophisticated, comprehensive analyses of the data that become valid *only* as a result of reasoned, accurate statistical characterization. Although software for kriging and co-kriging has long been available in many GIS environments, IMHO **kriging is *not* an activity to be performed solely by a GIS analyst**, because it requires close collaboration both with a seasoned statistician and an expert in the field of study. (Occasionally two of these three roles or even all three may be adequately filled by the same person, but this is rare.) It is one of those especially dangerous capabilities of a GIS because kriging *output* is easily created by anyone who can push the right buttons (a task that can be learned in 30 minutes with ESRI's excellent tutorial on Geostatistical Analyst, for instance) and will often *look* correct but is just the "GO" part of the proverbial [GIGO](http://en.wikipedia.org/wiki/Garbage_in,_garbage_out).
60,512,703
In my Laravel-5.8, I passed data from controller to view using JSON. ``` public function findScore(Request $request) { $userCompany = Auth::user()->company_id; $child = DB::table('appraisal_goal_types')->where('company_id', $userCompany)->where('id',$request->id)->first(); if(empty($child)) { abort(404); } $maxscore2 = 1; $maxscore = DB::table('appraisal_goal_types')->select('max_score')->find($child->parent_id); return response()->json([ 'maxscore' => $maxscore, 'maxscore2' => $maxscore2 ]); } ``` **Route** ``` Route::get('get/findScore','Appraisal\AppraisalGoalsController@findScore') ->name('get.scores.all'); ``` **View** ``` <form action="{{route('appraisal.appraisal_goals.store')}}" method="post" class="form-horizontal" enctype="multipart/form-data"> {{csrf_field()}} <div class="card-body"> <div class="form-body"> <div class="row"> <div class="col-12 col-sm-6"> <div class="form-group"> <label class="control-label"> Goal Type:<span style="color:red;">*</span></label> <select id="goal_type" class="form-control" name="goal_type_id"> <option value="">Select Goal Type</option> @foreach ($categories as $category) @unless($category->name === 'Job Fundamentals') <option hidden value="{{ $category->id }}" {{ $category->id == old('category_id') ? 'selected' : '' }}>{{ $category->name }}</option> @if ($category->children) @foreach ($category->children as $child) @unless($child->name === 'Job Fundamentals') <option value="{{ $child->id }}" {{ $child->id == old('category_id') ? 'selected' : '' }}>&nbsp;&nbsp;{{ $child->name }}</option> @endunless @endforeach @endif @endunless @endforeach </select> </div> </div> <input type="text" id="max_score" value="max_score" class="form-control" > </form> <script type="text/javascript"> $(document).ready(function() { $(document).on('change', '#goal_type', function() { var air_id = $(this).val(); var a = $(this).parent(); console.log("Its Change !"); var op = ""; $.ajax({ type: 'get', url: '{{ route('get.scores.all') }}', data: { 'id': air_id }, dataType: 'json', //return data will be json success: function(data) { console.log(data.maxscore); console.log(data.maxscore2); $('#max_score').val(data.maxscore); }, error:function(){ } }); }); }); </script> ``` When I click on the dropdown on change, I got these: Console: [![console diagram](https://i.stack.imgur.com/MHyiJ.png)](https://i.stack.imgur.com/MHyiJ.png) textbox: [![testbox diagram](https://i.stack.imgur.com/zZEvl.png)](https://i.stack.imgur.com/zZEvl.png) I need the direct value to be displayed on the text and not the JSON object as shown in the diagram. For example, only the 75 in the textbox. How do I get this resolved? Thank you.
2020/03/03
[ "https://Stackoverflow.com/questions/60512703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12510040/" ]
It seems to me that the LoginController is unnecessary. The spring security configuration has already defined the authenticationProvider to authenticate your login, you don't need another Controller to do the same thing. Try this: 1. remove the LoginController 2. change the login success URL to '/homeLogged' ``` http .formLogin() .defaultSuccessUrl("/homeLogged", true) .permitAll(); ``` And if you want to use your own custom login page, say login.jsp, you can add it after the formLogin() like this: ``` http .formLogin().loginPage("/login.jsp") .defaultSuccessUrl("/homeLogged", true) .permitAll(); ``` And in your login.jsp, you shall have three elements: 1. action: "login", which will post the request to url: login 2. username field 3. password field and your authenticator defined in the your security config will authenticate the username and password and then redirect to the successful URL.
20,254,934
This question is **only for Python programmers**. This question is **not duplicate not working** [Increment a python floating point value by the smallest possible amount](https://stackoverflow.com/questions/6063755/increment-a-python-floating-point-value-by-the-smallest-possible-amount) see explanation bottom. --- I want to add/subtract for any float some smallest values which will change this float value about one bit of [mantissa/significant part](http://en.wikipedia.org/wiki/Floating_point). How to calculate such small number efficiently in **pure Python**. For example I have such array of x: ``` xs = [1e300, 1e0, 1e-300] ``` What will be function for it to generate **the smallest value**? All assertion should be valid. ``` for x in xs: assert x < x + smallestChange(x) assert x > x - smallestChange(x) ``` Consider that `1e308 + 1 == 1e308` since `1` does means `0` for mantissa so `smallestChange' should be dynamic. Pure Python solution will be the best. --- **Why this is not duplicate of [Increment a python floating point value by the smallest possible amount](https://stackoverflow.com/questions/6063755/increment-a-python-floating-point-value-by-the-smallest-possible-amount)** - two simple tests prove it with invalid results. (1) The question is not aswered in [Increment a python floating point value by the smallest possible amount](https://stackoverflow.com/questions/6063755/increment-a-python-floating-point-value-by-the-smallest-possible-amount) difference: **[Increment a python floating point value by the smallest possible amount](https://stackoverflow.com/questions/6063755/increment-a-python-floating-point-value-by-the-smallest-possible-amount) just not works try this code**: ``` import math epsilon = math.ldexp(1.0, -53) # smallest double that 0.5+epsilon != 0.5 maxDouble = float(2**1024 - 2**971) # From the IEEE 754 standard minDouble = math.ldexp(1.0, -1022) # min positive normalized double smallEpsilon = math.ldexp(1.0, -1074) # smallest increment for doubles < minFloat infinity = math.ldexp(1.0, 1023) * 2 def nextafter(x,y): """returns the next IEEE double after x in the direction of y if possible""" if y==x: return y #if x==y, no increment # handle NaN if x!=x or y!=y: return x + y if x >= infinity: return infinity if x <= -infinity: return -infinity if -minDouble < x < minDouble: if y > x: return x + smallEpsilon else: return x - smallEpsilon m, e = math.frexp(x) if y > x: m += epsilon else: m -= epsilon return math.ldexp(m,e) print nextafter(0.0, -1.0), 'nextafter(0.0, -1.0)' print nextafter(-1.0, 0.0), 'nextafter(-1.0, 0.0)' ``` Results of [Increment a python floating point value by the smallest possible amount](https://stackoverflow.com/questions/6063755/increment-a-python-floating-point-value-by-the-smallest-possible-amount) is invalid: ``` >>> nextafter(0.0, -1) 0.0 ``` Should be nonzero. ``` >>> nextafter(-1,0) -0.9999999999999998 ``` Should be '-0.9999999999999999'. (2) It was not asked how to add/substract the smallest value but was asked how to add/substract value in specific direction - propose solution is need to know x and y. Here is required to know only x. (3) Propose solution in [Increment a python floating point value by the smallest possible amount](https://stackoverflow.com/questions/6063755/increment-a-python-floating-point-value-by-the-smallest-possible-amount) will not work on border conditions.
2013/11/27
[ "https://Stackoverflow.com/questions/20254934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/665926/" ]
``` >>> (1.0).hex() '0x1.0000000000000p+0' >>> float.fromhex('0x0.0000000000001p+0') 2.220446049250313e-16 >>> 1.0 + float.fromhex('0x0.0000000000001p+0') 1.0000000000000002 >>> (1.0 + float.fromhex('0x0.0000000000001p+0')).hex() '0x1.0000000000001p+0' ``` Just use the same sign and exponent.
68,018,124
My Loading component: ``` import React from 'react' export default class Loading extends React.Component { constructor(props) { super(props) this.state = { display: 'none' } } render() { return ( <div className="loading" style={{display: this.state.display}}> <span></span> </div> ) } } ``` And I want change `display` from `App.js` ``` Loading.setState ... ``` Or ``` var lng = new Loading() lng.setState ... ``` Both of them not work I want can change state from another class or function
2021/06/17
[ "https://Stackoverflow.com/questions/68018124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11259682/" ]
If you want to change `display` from `App.js`: 1. Pass it as prop to `Loading` component, and keep the state at `App.js`. 2. pass some prop from `App.js` and when it changes - change the state of `display` in `App.js` 3. Use some global state/store manager like [Redux](https://react-redux.js.org/introduction/getting-started) or built-in [useContext](https://reactjs.org/docs/hooks-reference.html#usecontext) react-hook, in this case you will be able to change from any component connected to store
13,306,013
I have a Master Page based Web site that has menu functionality. CSS is read from a Style.css file successfully. I have now added a seperate Login.aspx page which functions fine, but does not pick up the Account.css file, which has the specific css for the Login page. I do not want the login page to refernence the master page. ``` <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="Login" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js" type="text/javascript"></script> <link href="Account.css" rel="stylesheet" type="text/css" /> <script type="text/javascript"> $(document).ready(function () { $('.grid_12').fadeIn(1750); }); </script> </head> ``` I would appreciate any insight, as I have tried referencing the Account.css file path every way i can think of: ``` href="./Account.css" href="Account.css" href="~/Account.css" ``` I have now placed the Login.aspx page and Account.css file in a new login folder at website root.
2012/11/09
[ "https://Stackoverflow.com/questions/13306013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1811813/" ]
There may be a region that your are using form authentication. If yes then you can use ``` <location path="Account.css"> <system.web> <authorization> <allow users="*" /> </authorization> </system.web> </location> ``` Inside ``` <appSettings></appSettings> ``` Else you can use ``` <style type="text/css" src='<%= ResolveUrl("Account.css")%>'></script> ```
13,477,363
I have a few kegs of the same package in `/usr/local/Cellar/libfoo` like `/usr/local/Cellar/libfoo/1.0.1`, `/usr/local/Cellar/libfoo/HEAD` and `/usr/local/Cellar/libfoo/mycopy` How can I brew link to a specific version?
2012/11/20
[ "https://Stackoverflow.com/questions/13477363", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16998/" ]
**[This is probably the best way as of 11.1.2022](https://stackoverflow.com/a/9832084/1574376):** To install a specific version, e.g. postgresql 9.5 you simply run: ``` $ brew install [email protected] ``` To list the available versions run a search with @: ``` $ brew search postgresql@ ==> Formulae postgresql postgresql@11 postgresql@13 [email protected] qt-postgresql postgresql@10 postgresql@12 [email protected] [email protected] postgrest ==> Casks navicat-for-postgresql ``` --- **DEPRECATED in Homebrew 2.6.0 (December 2020):** The usage info: ``` Usage: brew switch <formula> <version> ``` Example: ``` brew switch mysql 5.5.29 ``` You can find the versions installed on your system with `info`. ``` brew info mysql ``` And to see the available versions to install, you can provide a dud version number, as brew will helpfully respond with the available version numbers: ``` brew switch mysql 0 ``` --- **Update (15.10.2014):** The `brew versions` command has been removed from brew, but, if you do wish to use this command first run `brew tap homebrew/boneyard`. The recommended way to install an old version is to install from the `homebrew/versions` repo as follows: ``` $ brew tap homebrew/versions $ brew install mysql55 ``` --- For detailed info on all the ways to install an older version of a formula read [this answer](https://stackoverflow.com/a/4158763/1574376).
1,113,332
In my lecture notes we have the following: We have that $f(x, y), g(x, y) \in \mathbb{C}[x, y]$ $$f(x,y)=a\_0(y)+a\_1(y)x+ \dots +a\_n(y)x^n \\ g(x, y)=b\_0(y)+b\_1(y)x+ \dots +b\_m(y)x^m$$ The resultant is defined in the following way: $$Res(f,g)(y)=det\begin{bmatrix} a\_0(y) & a\_1(y) & \dots & a\_n(y) & 0 & 0 & \dots & 0 \\ 0 & a\_0(y) & \dots & a\_{n-1}(y) & a\_n(y) & 0 & \dots & 0 \\ \dots & \dots & \dots & \dots & \dots & \dots & \dots & \dots \\ 0 & 0 & a\_0(y) & \dots & \dots & \dots & \dots & a\_n(y) \\ b\_0(y) & b\_1(y) & b\_2(y) & \dots & b\_m(y) & 0 & \dots & 0 \\ 0 & b\_0(y) & b\_1(y) & \dots & b\_m(y) & \dots & \dots & 0 \\ \dots & \dots & \dots & \dots & \dots & \dots & \dots & \dots \\ 0 & 0 & 0 & b\_0(y) & \dots & \dots & \dots & b\_m(y) \end{bmatrix}$$ I haven't understood how the resultant is defined. For example when we have $f(x, y)=y^2+x^2$ and $g(x, y)=y+x$, we have that $a\_0(y)=y^2, a\_1(y)=0, a\_2(y)=1, b\_0(y)=y, b\_1(y)=1$. How do we create the matrix?
2015/01/21
[ "https://math.stackexchange.com/questions/1113332", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
In your case the matrix is given by: $$\begin{pmatrix}y^2 & 0 & 1 \\ y & 1 & 0 \\ 0 & y & 1 \end{pmatrix} $$ In general, note that you have $m$ lines of $a$'s and $n$ lines of $b$'s and most importantly that the final result need to be and $(n+m) \times (n+m)$ matrix. Put differently, to the first line of $a$'s pad $m-1$ entries of $0$, and to the first line of $b$' pad $n-1$. This matrix is called ["Sylvester matrix"](http://en.wikipedia.org/wiki/Sylvester_matrix) which should lead you to further examples.
23,538,025
I am trying to insert a column with column name 00:18:e7:f9:65:a6 with the statement ``` ALTER IGNORE TABLE tblwifi_information ADD "00:18:e7:f9:65:a6" INT ``` ...but it throws an error: ``` /* SQL Error (1064): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '"00:18:e7:f9:65:a6" INT' at line 1 */ ``` in Heidi SQL. I am using MySQL database. When I try to add the column manually b going to the structure of the table it works and does not give any error but when I run this statement it does not allow me. How can I solve this?
2014/05/08
[ "https://Stackoverflow.com/questions/23538025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1583647/" ]
I just ran your query: ``` ALTER IGNORE TABLE tblwifi_information ADD "00:18:e7:f9:65:a6" INT ``` and got the same error. I then ran: ``` ALTER IGNORE TABLE tblwifi_information ADD `00:18:e7:f9:65:a6` INT ``` and it worked. Pretty sure you need to change " to ` Fail with double qoutes: ![Failed with double quotes](https://i.stack.imgur.com/qJ7VN.png) Success with backticks: ![Success with backticks](https://i.stack.imgur.com/1DRNg.png)
21,029,709
I am aware of the image resizing technic of changing image proportions based on width: ``` img{ max-width: 100%; height: auto; } ``` I need to do the same thing only based on the height of the parent, not the width. I have tried the following with no effect: ``` img{ width: auto; max-height: 100%; } ``` I hope I explaining this well enough. Please help :)
2014/01/09
[ "https://Stackoverflow.com/questions/21029709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/857030/" ]
`max-height` will only restrict the height to be less than the given value. If you want it to be the same as its parent.. give it as `height: 100%` hence this should work: CSS: ``` img{ height: 100%; // changed max-height to height here width: auto; // this is optional } ```
53,203,970
The following code can be fixed easily, but quite annoying. ```cpp #include <functional> #include <boost/bind.hpp> void foo() { using namespace std::placeholders; std::bind(_1, _2, _3); // ambiguous } ``` There's a macro `BOOST_BIND_NO_PLACEHOLDERS`, but using this macro will also bring some drawbacks like causing `boost::placeholders` disappear from the compile unit included `<boost/bind.hpp>` but not included `<boost/bind/placeholders.hpp>`. The name conflicts also comes with other libs like `boost::mpl`, I don't think the maintainers don't know the problem, but I want to know why they insist on not deprecating and deleting `using namespace boost::placeholders` in `<boost/bind.hpp>`.
2018/11/08
[ "https://Stackoverflow.com/questions/53203970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2709407/" ]
Looks like it has been fixed in newer versions of boost. When including `boost/bind.hpp` we get this message: `#pragma message: The practice of declaring the Bind placeholders (_1, _2, ...) in the global namespace is deprecated. Please use <boost/bind/bind.hpp> + using namespace boost::placeholders, or define BOOST_BIND_GLOBAL_PLACEHOLDERS to retain the current behavior.` The solution is described in <https://www.boost.org/doc/libs/1_73_0/boost/bind.hpp> So the "good practice" fix is to instead of `#include <boost/bind.hpp>` which puts the boost::placeholders in global namespace do `#include <boost/bind/bind.hpp>` which does not put the boost:: placeholders in global namespace. Then use the qualified names like `boost::placeholders::_1` directly, or locally do `using namespace boost::placeholders`
59,593
Here's a puzzle. You will probably find this out easily :) A family lives in a round cabin. The kid's mom and dad go outside. When they come back, their son is dead. The butcher said he was cutting meat. The maid said she was dusting the house. The butler claimed he was cleaning the corners. Who killed the child?
2018/01/20
[ "https://puzzling.stackexchange.com/questions/59593", "https://puzzling.stackexchange.com", "https://puzzling.stackexchange.com/users/44551/" ]
> > Butler, > > > Because > > The house is cornerless. So the butler is lying ... > > >
237,698
I'm trying to understand the Bayes Classifier. I don't really understand its purpose or how to apply it, but I think I understand the parts of the formula: $$P(Y = j \mid X = x\_{0})$$ If I'm correct, it's asking for the largest probability, depending on one of two conditions. If $Y$ is equal to some class $j$, or if $X$ is some data point $x\_{0}$. How would I compute this with a data set $(x, y)$ where $x$ is just a number between 1 and 100, and $y$ is one of two classes ("blue" or "orange"), e.g. (5, "blue"), (51, "orange")? Does this data set even work to apply the classifier or should I consider making a new data set? Sorry if it's a silly question, I'm out of touch with my statistics. Some pseudocode would be terrific, but I'll be applying this in R. I'm not interested in the R function to complete this. Some regular guidance with good ol' math would be great as well. Thank you for any help!
2016/09/30
[ "https://stats.stackexchange.com/questions/237698", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/132937/" ]
The Bayes classifier is the one that classifies according to the most likely category given the predictor $x$, i.e., $$ \text{arg max}\_j P(Y = j \mid X = x) . $$ Since these "true" probabilities are essentially never known, the Bayes classifier is more a theoretical concept and not something that you can actually use in practice. However, it's a helpful idea when doing simulation studies where you generate the data yourself and therefore know the probabilities. This allows you to compare a given classification rule to the Bayes classifier which has the lowest error rate among all classifiers.
5,294,957
What is the best way to securely authenticate a user ? So far I was thinking of: * Generate a random `$SALT` for each successful login and store `$logged = md5($hashed_password.$SALT)` into database; delete on logout. * Store `$logged` into a cookie (If user checked "remember me"). Set `$_SESSION['user'] = $logged;` * On a visit: Check if `$_SESSION['user']` is set; if not, check for cookie, if data doesn't match, redirect to `login` page. What are the risks ?
2011/03/14
[ "https://Stackoverflow.com/questions/5294957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/348358/" ]
The only issue I can see with your existing framework (which I like otherwise) is that there is the possibility of collision for `$logged`. It is not mathematically impossible for two valid user log-ins to result in the same hash. So I would just make sure to start storing the User `id` or some other unique information in the Cookie as well. You may also want to keep a timestamp of when the `$logged` was put in the DB, so that you can run cleaning queries where they are older than `x` days/weeks.
58,646,186
I have a problem where I'm having two arrays. Whenever I'm changing a value in one array with the code shown below, the other array do also get the same change which is not intended. If i copy and paste the code below in the javascript console in my browser I get the problem that originalArray is changed after I called ConvertDataArrayToLocationArray(dataArray) ```js let originalArray = [ { "date": "2018-11-16", "type": "Entertainment", "location": "Oslo", "amount": 1024 }, { "date": "2018-11-16", "type": "Food", "location": "Oslo", "amount": 170 }, { "date": "2018-11-17", "type": "Food", "location": "Fredrikstad", "amount": 99 }, { "date": "2018-11-18", "type": "Food", "location": "Halden", "amount": 29 }, { "date": "2018-11-19", "type": "Entertainment", "location": "Oslo", "amount": 34 }, { "date": "2018-11-20", "type": "Entertainment", "location": "Oslo", "amount": 15 }, { "date": "2018-11-20", "type": "Food", "location": "Fredrikstad", "amount": 80 }, { "date": "2018-11-23", "type": "Transportation", "location": "Stavanger", "amount": 95 }, { "date": "2018-11-28", "type": "Entertainment", "location": "Oslo", "amount": 1024 }, { "date": "2018-11-29", "type": "Food", "location": "Oslo", "amount": 117.39 }, { "date": "2018-11-30", "type": "Transportation", "location": "Fredrikstad", "amount": 29 }, { "date": "2018-12-2", "type": "Transportation", "location": "Stavanger", "amount": 184 }, { "date": "2018-12-3", "type": "Entertainment", "location": "Oslo", "amount": 34 }, { "date": "2018-12-4", "type": "Food", "location": "Oslo", "amount": 162 }, { "date": "2018-12-4", "type": "Food", "location": "Fredrikstad", "amount": 231 } ]; function ConvertDataArrayToLocationArray(dataArray) { let newArray = []; console.log("First dataArray[0].amount is the correct value. "); console.log(dataArray[0].amount); for(let i = 0; i < dataArray.length; i++) { let existed = false; for(let j = 0; j < newArray.length; j++) { if(dataArray[i].location === newArray[j].location) { newArray[j].amount = (newArray[j].amount + dataArray[i].amount); existed = true; } } if(!existed) { newArray.push(dataArray[i]); } } console.log("Why is this dataArray[0].amount suddenly different?"); console.log(dataArray[0].amount); return newArray; } let a = ConvertDataArrayToLocationArray(originalArray); ``` My excepted outcome is that the variable called originalArray stays unchanged and I get a new array from the return value of ConvertDataArrayToLocationArray(dataArray).
2019/10/31
[ "https://Stackoverflow.com/questions/58646186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7425546/" ]
You should look at [`getchar()`](https://linux.die.net/man/3/getchar) ``` #include <stdio.h> int main() { int c1; while ((c1=getchar())!=EOF && c1!='*'){ printf("c1: %c \n", c1); } return 0; } ``` EDIT: and this way, there is no undefined behavior, because `c1` is always initialized (see @Blaze answer) :)
4,028,536
What's the best way to make a select in this case, and output it without using nested queries in php? I would prefer to make it with a single query. My tables look like this: ``` table1 id | items | ---|-------| 1 | item1 | 2 | item2 | 3 | item3 | .. | .. | table2 id | itemid | comment | ---|--------|----------| 1 | 1 | comment1 | 2 | 1 | comment2 | 3 | 2 | comment3 | 4 | 3 | comment4 | 5 | 3 | comment5 | 6 | 3 | comment6 | .. | .. | .. | ``` This is the output i'm looking for. ``` item1 comment1 comment2 item2 comment3 item3 comment4 comment5 comment6 ``` Thanks in advance
2010/10/26
[ "https://Stackoverflow.com/questions/4028536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/488174/" ]
Checkout this JSON framework for Objective-C on [code.google.com](http://code.google.com/p/json-framework/) or on [Github](http://stig.github.com/json-framework/). It is pretty straightforward to use. You instantiate your SBJSON object then call *objectWithString* with your buffer: ``` SBJSON * parser = [[SBJSON alloc] init]; NSString * buffer = @"{"name":"WFNX"}"; NSError* error = NULL; // the type of json will depend on the JSON data in buffer, in this case, it will be // and NSDictionary with one key/value pair "name"->"WFNX" id json = [parser objectWithString:buffer error:&error]; ```
32,353,300
I need to search trough my data that is stored in my `UITableView`. I need one left bar button item and when the user clicked that, it should show like a search bar. How to do that?. Thanks in advance! **edited:** ok based on solution you provide.Here i have done some thing with search bar (bar button item). but still i am missing some thing . And also my **filter content for search box** also , having some problem. really i don't now what to do for this? ``` #import "ViewController.h" #import "AddNoteViewController.h" #import <CoreData/CoreData.h> #import "TableViewCell.h" @interface ViewController () { NSArray *searchResults; } @property (nonatomic, strong) UISearchBar *searchBar; @property (nonatomic, strong) UISearchDisplayController *searchController; @property (nonatomic) BOOL *isChecked; @property (strong) NSMutableArray *notes; //@property (strong, nonatomic) NSArray *_lastIndexPath; @end @implementation ViewController @synthesize tableView; @synthesize addButton; //@synthesize _lastIndexPath; @synthesize managedObjectContext; - (NSManagedObjectContext *)managedObjectContext { NSManagedObjectContext *context = nil; id delegate = [[UIApplication sharedApplication] delegate]; if ([delegate performSelector:@selector(managedObjectContext)]) { context = [delegate managedObjectContext]; } return context; } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. self.navigationItem.title = @"My Notes"; tableView.dataSource = self; tableView.delegate = self; [self.view addSubview:tableView]; // place search bar coordinates where the navbar is position - offset by statusbar self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 20, 320, 44)]; //self.searchResults = [[NSArray alloc] init]; UIBarButtonItem *searchButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(toggleSearch)]; self.navigationItem.rightBarButtonItem = searchButton; self.searchController = [[UISearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self]; self.searchController.searchResultsDataSource = self; self.searchController.searchResultsDelegate = self; self.searchController.delegate = self; } - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; NSManagedObjectContext *managedObjectContext = [self managedObjectContext]; NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Notes"]; NSError *error = nil; self.notes = [[managedObjectContext executeFetchRequest:fetchRequest error:&error] mutableCopy]; NSSortDescriptor *titleSorter= [[NSSortDescriptor alloc] initWithKey:@"mod_time" ascending:NO]; [self.notes sortUsingDescriptors:[NSArray arrayWithObject:titleSorter]] ; NSLog(@"Your Error - %@",error.description); [tableView reloadData]; } #pragma mark - Search controller - (void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller { } - (void) searchDisplayControllerWillEndSearch:(UISearchDisplayController *)controller { } - (void)searchDisplayControllerDidEndSearch:(UISearchDisplayController *)controller { // [self.searchBar removeFromSuperview]; } - (void)toggleSearch { [self.view addSubview:self.searchBar]; [self.searchController setActive:YES animated:YES]; [self.searchBar becomeFirstResponder]; } - (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope { NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Notes" inManagedObjectContext:_notes]; [fetchRequest setEntity:entity]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"notes.title contains[c] %@", searchText]; [fetchRequest setPredicate:predicate]; NSError *error; NSArray* searchResults = [managedObjectContext executeFetchRequest:fetchRequest error:&error]; } -(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString { [self filterContentForSearchText:searchString scope:[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]]; return YES; } #pragma mark - Table view data source - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { // Return the number of sections. // return searchResults.count; return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { if (tableView == self.searchDisplayController.searchResultsTableView) { return [searchResults count]; } else { return self.notes.count; } } - (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { TableViewCell *cell = (TableViewCell*)[aTableView dequeueReusableCellWithIdentifier:@"MycellIdentifier"]; if(cell == nil) { cell = [[TableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MycellIdentifier"]; } _notes = [_notes objectAtIndex:indexPath.row]; // Configure the cell... NSManagedObject *note = [self.notes objectAtIndex:indexPath.row]; NSDate *date = [note valueForKey:@"mod_time"]; cell.textLabel.text = [note valueForKey:@"title"]; cell.selectionStyle = UITableViewCellSelectionStyleNone; return cell; } - (IBAction)addButtonPressed:(id)sender { AddNoteViewController *addNoteVC = [AddNoteViewController new]; } - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { // Return NO if you do not want the specified item to be editable. return YES; } - (void)tableView:(UITableView *)cTableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { NSManagedObjectContext *context = [self managedObjectContext]; if (editingStyle == UITableViewCellEditingStyleDelete) { // Delete object from database [context deleteObject:[self.notes objectAtIndex:indexPath.row]]; NSError *error = nil; if (![context save:&error]) { NSLog(@"Can't Delete! %@ %@", error, [error localizedDescription]); return; } // Remove device from table view [self.notes removeObjectAtIndex:indexPath.row]; [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; } } -(UITableViewCellEditingStyle) tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath { return YES; } @end ```
2015/09/02
[ "https://Stackoverflow.com/questions/32353300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5203412/" ]
I had a similar problem. To fix it, I created an SSIS "Composant Script" in which I created a "guid" output. The script VS C# code was the following : ``` Row.guid = Guid.NewGuid(); ``` Finally, I routed the output as a derived column into my database "OLE DB Destination" to generate a guid for every new entry.
23,697,956
I am developing a Windows Phone 8.0 App in VS2010 and in some point , i decided to make 2 classes (Player,Game) **Game.cs** ``` public class Game { public string Name { get; set; } public bool[] LevelsUnlocked { get; set; } public bool firstTimePlaying { get; set; } public Game(int numOfLevels) { this.firstTimePlaying = true; this.LevelsUnlocked = new bool[numOfLevels]; } } ``` **Player.cs** ``` public class Player { public int ID { get; set; } public string FirstName{ get; set; } public string LastName { get; set; } public int Age { get; set; } public int Rank { get; set; } public int Points { get; set; } public string RankDescreption { get; set; } public Uri Avatar { get; set; } public List<Game> Games; public Player() { Game HourGlass = new Game(6); Game CommonNumbers = new Game(11); Games.Add(HourGlass); Games.Add(CommonNumbers); } } ``` When i debug , the app crashes at the Line : `Games.Add(HourGlass);` because of `AccessViolationException`, i don't see what is the problem of adding the item to the list . so what is it ?
2014/05/16
[ "https://Stackoverflow.com/questions/23697956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3264464/" ]
You must initialize a list before using it. This: ``` public List<Game> Games; ``` ..needs to be this: ``` public List<Game> Games = new List<Game>(); ``` I am surprised you are getting an `AccessViolationException`.. I would have expected a `NullReferenceException`.
106,477
I am writing a technical paper where I have described an experiment resulting in "x". Then I go on to describe the result of a second experiment whose result was expected since the reason was deduced in the previous experiment (x). I'm looking for a phrase to tie the two sentences together but I did not want to use "as expected" or "it would follow". I know there is another phrase out there that suits better but I can't seem to come up with it right now so I need your help. Thanks.
2013/03/07
[ "https://english.stackexchange.com/questions/106477", "https://english.stackexchange.com", "https://english.stackexchange.com/users/38999/" ]
Consider [synonyms](http://thesaurus.com/browse/consistent) of *[consistent](http://en.wiktionary.org/wiki/consistent#Adjective)*, such as *[compatible](http://en.wiktionary.org/wiki/compatible#Adjective)* and *[congruent](http://en.wiktionary.org/wiki/congruent#Adjective)*; eg, “Results of experiment B were consistent / compatible / congruent with those of experiment A.” Also consider *[in accord with](http://en.wiktionary.org/wiki/accord#Noun)*; eg, “In accord with predictions based on experiment A, experiment B showed that...”
39,131,812
if I want to express something like [just a simple example]: ``` int a = 0; for (int x = 0; x < n; x += 1) a = 1 - a; ``` what should I do in Haskell, *since it doesn't have variable concept?* (maybe wrong, see: [Does Haskell have variables?](https://stackoverflow.com/questions/993124/does-haskell-have-variables))
2016/08/24
[ "https://Stackoverflow.com/questions/39131812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4280916/" ]
Often, repetition that you would perform with a loop in a procedural language is accomplished with [recursion](http://learnyouahaskell.com/recursion) in Haskell. In this case, you should think about what the result of the loop is. It appears to alternate between 0 and 1. There are several ways to do this in Haskell. One way is ``` alternatingList n = take n alternating0and1 alternating0and1 = 0 : alternating1and0 alternating1and0 = 1 : alternating0and1 ```
34,176,782
Inspired by the following thread: [PyQt: How to set Combobox Items be Checkable?](https://stackoverflow.com/questions/22775095/pyqt-how-to-set-combobox-items-be-checkable) I was able to create a simple checkable "combobox" by using a QToolButton and adding checkable items to it using addAction. See simple code example: ``` from PyQt4 import QtCore, QtGui import sys class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName("Dialog") Dialog.resize(198, 157) self.toolButton = QtGui.QToolButton(Dialog) self.toolButton.setGeometry(QtCore.QRect(60, 50, 71, 19)) self.toolButton.setObjectName("toolButton") self.toolButton.setText("MyButton") QtCore.QMetaObject.connectSlotsByName(Dialog) class MyDialog(QtGui.QDialog): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_Dialog() self.ui.setupUi(self) self.toolMenu = QtGui.QMenu(self.ui.toolButton) for i in range(3): action = self.toolMenu.addAction("Category " + str(i)) action.setCheckable(True) self.ui.toolButton.setMenu(self.toolMenu) self.ui.toolButton.setPopupMode(QtGui.QToolButton.InstantPopup) if __name__ == "__main__": app = QtGui.QApplication(sys.argv) myapp = MyDialog() myapp.show() sys.exit(app.exec_()) ``` But how can I capture which of the QToolButton actions (i.e. *Category 1* and/or *Category 2/3*) that has been checked in my dialog?
2015/12/09
[ "https://Stackoverflow.com/questions/34176782", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5656718/" ]
Alternatively you can define your [`QActionGroup`](http://pyqt.sourceforge.net/Docs/PyQt4/qactiongroup.html) to collect all of your `action`s, then `connect` the signal `triggered` to callback method, this way: ``` class MyDialog(QtGui.QDialog): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_Dialog() self.ui.setupUi(self) self.toolMenu = QtGui.QMenu(self.ui.toolButton) group = QtGui.QActionGroup(self.toolMenu) for i in range(3): action = self.toolMenu.addAction("Category %d" % i) action.setCheckable(True) action.setActionGroup(group) action.setData(i) self.ui.toolButton.setMenu(self.toolMenu) self.ui.toolButton.setPopupMode(QtGui.QToolButton.InstantPopup) group.triggered.connect(self.test) def test(self, act): print 'Action' , act.data().toInt()[0] ``` Here in `test()` method, reading the `data` of each `action` returns a [`QVariant`](http://pyqt.sourceforge.net/Docs/PyQt4/qvariant.html#toInt) which you need to convert it back to `int` using `toInt` method returning `(int, bool)` tuple, thus `[0]`
47,355,843
Today I updated Android Studio to version 3.0 And after that I couldn't build project successfully. I got these errors: ``` Unable to resolve dependency for ':app@release/compileClasspath': could not resolve com.android.support:appcompat-v7:27.0.1. ``` I tried using VPN or proxy etc. but none of them worked. It's been a long day. I hope you may help me. This is my build.gradle(app) : ``` apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' android { compileSdkVersion 27 defaultConfig { applicationId "ir.hetbo.kotlin_tutorial" minSdkVersion 15 targetSdkVersion 27 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation"org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version" implementation 'com.android.support:appcompat-v7:27.0.1' implementation 'com.android.support.constraint:constraint-layout:1.0.2' } ``` and this is build.gradle(project): ``` // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { ext.kotlin_version = '1.1.60' repositories { google() jcenter() maven { url "https://maven.google.com" } } dependencies { classpath 'com.android.tools.build:gradle:3.0.0' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { google() jcenter() maven { url "https://maven.google.com" } } } task clean(type: Delete) { delete rootProject.buildDir } ``` I did a lot of things to fix it but every time it failed. I use gradle 4.3.1 And here is gradle wrapper properties : ``` #Sat Nov 18 10:16:45 IRST 2017 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-4.3.1-all.zip ```
2017/11/17
[ "https://Stackoverflow.com/questions/47355843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7577206/" ]
with the new features of **gradle 4.1** and the **classpath 'com.android.tools.build:gradle:3.0.0'** > > distributionBase=GRADLE\_USER\_HOME distributionPath=wrapper/dists > zipStoreBase=GRADLE\_USER\_HOME zipStorePath=wrapper/dists > distributionUrl=<https://services.gradle.org/distributions/gradle-4.1-all.zip> > > > and and this is build.gradle(project): ``` // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { ext.kotlin_version = '1.1.60' repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.0.0' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { google() jcenter() } } task clean(type: Delete) { delete rootProject.buildDir } ```
28,672,134
eg. JBB Inc. Headquarters 20 West RiverCenter Blvd Covington KY 41011 USA
2015/02/23
[ "https://Stackoverflow.com/questions/28672134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4574324/" ]
This error can be caused by an incorrect **merchant ID**, an **incorrect access code**, or if the order originates from an **unregistered URL**. Make sure that all three of these values are correct. > > For your security, CCAvenue does not report exactly which of these three values might be in error. > > > **Update:** 1. You can find CCAvenue setup for ASP.net from here: <http://aravin.net/complete-guide-integrate-ccavenue-payment-gateway-asp-net-website-screenshot/> 2. Also, you can find steps to solve the 10002 here: <http://aravin.net/how-to-test-ccavenue-payment-gateway-in-localhost-avoid-error-code-10002-merchant-authentication-failed/>
37,318,319
I have Two Question related to Native App Performance Testing? 1)I have a Payment App, and it comes with bank security which is installed at the time of app installation. It sends an token number and rest of the data in encrypted format. Is it possible to handle such kind of request using Jmeter or any other performance testing tool, do i need to change some setting in app server or jmeter to get this done ? 2)Mobile App uses Device ID, so if i simulated load on cloud server it will use same Device ID which i used while creating script? is it possible to simulate different mobile ID to make it real-time? any Help or references will be appreciated ..:)
2016/05/19
[ "https://Stackoverflow.com/questions/37318319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4252313/" ]
(1) Yes. This is why performance testing tools are built around general purpose programming languages, to allow you (as the tester) to leverage your foundation skills in programming to leverage the appropriate algorithms and libraries to represent the same behavior as the client (2) This is why performance testing tools allow for parameterization of the sending datastream to the server/application under test
39,019,266
hello i want to apply css for nav bar, i am retrivig nav bar values from database using Ajax.ActionLink, i tried javascript but i am getting error called > > jQuery is not defined", > > > here is my code. and Test\_Section is my Model. ``` <table style="width:auto"> @foreach (Test_Section p in Model) { <tr> <td> <div id="ajaxnav" class="navbar-left"> <ul class="nav nav-tabs nav-stacked"> <li> @Ajax.ActionLink(p.SectionName, p.Title, new { id = p.StdSectionId , @class = "navigationLink"}, new AjaxOptions { UpdateTargetId = "getHtml", InsertionMode = InsertionMode.Replace, HttpMethod = "GET" }, new { style = "color:#428bca" , @class = "navigationLink" }) </li> </ul> </div> </td> </tr> } </table> <script type="text/javascript"> $('.navigationLink').click(function () { $('.navigationLink').removeClass('active'); $(this).addClass('active'); }); </script> ``` Please help me.
2016/08/18
[ "https://Stackoverflow.com/questions/39019266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6459059/" ]
You need to include jQuery to your application by referencing it in your page, because the Error `jQuery is not defined` or `$ is not defined` occurs when jQuery is not (correctly) included in your page. You should add this line before the `<script>` section in your posted code: ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> ``` Hope this help you.
57,129,646
Is there some way I can have a function whose return type varies based on one of its arguments? For example: ``` interface Person { name: string; job: string; } interface Animal { name: string; deadly: boolean; } function getPerson(): Person { return { name: 'Bob', job: 'Manager', }; } function getAnimal(): Animal { return { name: 'Spot', deadly: false, }; } function create(generator: () => Person | Animal): ReturnType<typeof generator>[] { return [] } const people = create(getPerson); ``` This is kind of close, except the type of `people` is `(Person | Animal)[]`. I need it to be `Person[]` - in other words, it can look at the `getPerson` argument and know that this function will return a `Person`. I realize, of course, I could rewrite the function so I can do this: ``` const people = create<Person>(getPerson); ``` But I'd rather have it infer this from the arguments somehow.
2019/07/21
[ "https://Stackoverflow.com/questions/57129646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5228806/" ]
You have have multiple `=` in a single match. ``` %{"name" => name} = identity = RedditOAuth2.get_identity(access_token) ``` `identity` will have the entire map assigned to it and `name` will have whatever was in the `"name"` key.