qid
int64
1
74.7M
question
stringlengths
17
39.2k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
2
41.1k
response_k
stringlengths
2
47.9k
24,909
In general on piano do you play the melody of a song if you intend to sing? Is it the case that you play a much more basic version of a song if you intend to also sing? If I am looking at sheet music is this denoted in any fashion?
2014/11/10
[ "https://music.stackexchange.com/questions/24909", "https://music.stackexchange.com", "https://music.stackexchange.com/users/15263/" ]
There is a lot of sheet music available which has 3 lines of manuscript. The lower two are the standard treble and bass clef that most people know from piano music, and the top line is often treble clef, and has the melody line, usually with the lyrics. Looking at the middle line, you'll find that the top line is often duplicated, but there are also other right hand notes to play.When a singer is there, the top part of the middle line is optional, it doesn't need to play the melody, because it's being sung. However, it can be played if the vocals and piano player so wish. If you're working from real or fake books, all you'll get is the melody line and chord changes. You have the choice to play chords with the left hand, and melody with right, but if a singer is singing, it makes more sense to play chords and extensions, or fill in bits, with the right hand.
A melodic playalong is mostly working well for simple music and simple interpretations. If you have a singing style with melodic and rhythmic freedoms, an accompanist will do the performance no favor by trying to follow the line along, even when self-accompanying. You also get the problem on a piano that it is a percussive instrument and thus has problems in delivering an even texture when long and short syllables are alternating. In that case basically working on the chords, often arpeggiating them over both hands in order not to get a wham-wham-wham accentuation on the beats/changes tends to turn out nicer. Piano extracts of music for choir and orchestra are not really helpful here since they are intended as rehearsal aids and thus integrate the singers as well. You see similar effects in piano extracts for solo music: they tend to remain perfectly recognizable even if nobody sings along.
24,909
In general on piano do you play the melody of a song if you intend to sing? Is it the case that you play a much more basic version of a song if you intend to also sing? If I am looking at sheet music is this denoted in any fashion?
2014/11/10
[ "https://music.stackexchange.com/questions/24909", "https://music.stackexchange.com", "https://music.stackexchange.com/users/15263/" ]
I agree with everything everyone has said above. Just to add to what they've already said, sometimes its just better to play by ear. For example, if your wanting to sing and play an Adele song, like "No One Like You", you can replicate the same version if you just play what's on the recording. It is easier said than done, but you have a lot more flexibility if you develop that skill. Its better than being dependent solely on sheet music, because if you follow too adhesively to it, your at the mercy at some other musician's interpretation of the music. (Not to say that sheet music isn't great! Or a great place to start.)
A melodic playalong is mostly working well for simple music and simple interpretations. If you have a singing style with melodic and rhythmic freedoms, an accompanist will do the performance no favor by trying to follow the line along, even when self-accompanying. You also get the problem on a piano that it is a percussive instrument and thus has problems in delivering an even texture when long and short syllables are alternating. In that case basically working on the chords, often arpeggiating them over both hands in order not to get a wham-wham-wham accentuation on the beats/changes tends to turn out nicer. Piano extracts of music for choir and orchestra are not really helpful here since they are intended as rehearsal aids and thus integrate the singers as well. You see similar effects in piano extracts for solo music: they tend to remain perfectly recognizable even if nobody sings along.
44,939,833
Hi i need to get the leads from the salesforce through rest api for this i have done so far a successful oauth through rest api and i got a following response ``` stdClass Object ( [access_token] => 1111xxxxxxxx44444444444444 [instance_url] => https://eu7.salesforce.com [id] => https://login.salesforce.com/id/000000000 [token_type] => Bearer [issued_at] => xxxxxxxxxxxx [signature] => xxxxxxxxxxxx ) ``` after that for getting contact leads i am using the below code ``` $email = '[email protected]'; $query = 'SELECT Id, Email FROM Lead'; if($email != null){ $query .= sprintf("WHERE Email ='%s'", $email); } $url = $instance_url. '/services/data/v33.0/query?q=' . urlencode($query); $paramsnew = "access_token=$access_token"; $urlcurl = curl_init($url); curl_setopt($urlcurl, CURLOPT_HEADER, false); curl_setopt($urlcurl, CURLOPT_RETURNTRANSFER, true); curl_setopt($urlcurl, CURLOPT_POST, true); curl_setopt($urlcurl, CURLOPT_POSTFIELDS, $paramsnew); curl_setopt($urlcurl, CURLOPT_SSL_VERIFYPEER, false); $urljson_response = curl_exec($urlcurl); echo $urljson_response; curl_close($urlcurl); ``` but in response i am getting below ``` [{"message":"Session expired or invalid","errorCode":"INVALID_SESSION_ID"}] ``` Please suggest how can i fix this.
2017/07/06
[ "https://Stackoverflow.com/questions/44939833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1847459/" ]
Finally i fixed it by using the below code. ``` $firstname = 'rohit'; $query = 'SELECT FirstName , LastName ,Id, Email FROM Lead '; if($firstname != null){ $query .= sprintf("WHERE FirstName ='%s'", $firstname); } $url = $instance_url. '/services/data/v33.0/query?q=' . urlencode($query); $paramsnew = "access_token=$access_token"; $urlcurl = curl_init($url); curl_setopt($urlcurl, CURLOPT_HEADER, false); curl_setopt($urlcurl, CURLOPT_RETURNTRANSFER, true); curl_setopt($urlcurl, CURLOPT_HTTPGET, 1); curl_setopt($urlcurl, CURLOPT_HTTPHEADER, array("Authorization: OAuth $access_token")); curl_setopt($urlcurl, CURLOPT_SSL_VERIFYPEER, false); $urljson_response = curl_exec($urlcurl); print_r(json_decode($urljson_response)); curl_close($urlcurl); ``` we need to pass the access token like ``` curl_setopt($urlcurl, CURLOPT_HTTPHEADER, array("Authorization: OAuth $access_token")); ``` and we need to use get method of curl. ``` curl_setopt($urlcurl, CURLOPT_HTTPGET, 1); ```
1 more example of the rest client response for new API version. [![enter image description here](https://i.stack.imgur.com/4seeL.png)](https://i.stack.imgur.com/4seeL.png)
13,886,456
how would I go about checking to see if a triangular poly is present within a square area? (I.E. picture a grid of squares overlaying a group of 2d polys.) Or even better, how can I determine the percentage of one of these squares that is occupied by a given poly (if at all). I've used directx before but can't seem to find the right combination of functions in their documentation. - Though it feels like something with ray-tracing might be relevant. I use c++ and can use directx if helpful. Thanks for any suggestions or ideas. :)
2012/12/14
[ "https://Stackoverflow.com/questions/13886456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/980058/" ]
There are a few ways to do this and it's essentially a clipping problem. One way is to use the Cohen–Sutherland algorithm: <http://en.wikipedia.org/wiki/Cohen%E2%80%93Sutherland> You would run the algorithm 3 times (once for each triangle edge). You can then find the percentage of area occupied by calculating area(clipped\_triangle) / area(square\_region).
You might consider the clipper library for doing generic 2D polygon clipping, area computation, intersection testing, etc. It is fairly compact and easy to deal with, and has decent examples of how to use it. It is an implementation of the Vatti clipping algorithm and will handle many odd edge cases (which may be overkill for you) [Can ho celadon city](http://stda.vn/du-an/celadon-city-tan-phu/1396) - [vinhomes central park](http://vinhomescentralpark.info)
13,886,456
how would I go about checking to see if a triangular poly is present within a square area? (I.E. picture a grid of squares overlaying a group of 2d polys.) Or even better, how can I determine the percentage of one of these squares that is occupied by a given poly (if at all). I've used directx before but can't seem to find the right combination of functions in their documentation. - Though it feels like something with ray-tracing might be relevant. I use c++ and can use directx if helpful. Thanks for any suggestions or ideas. :)
2012/12/14
[ "https://Stackoverflow.com/questions/13886456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/980058/" ]
You might consider the [clipper](http://www.angusj.com/delphi/clipper.php) library for doing generic 2D polygon clipping, area computation, intersection testing, etc. It is fairly compact and easy to deal with, and has decent examples of how to use it. It is an implementation of the Vatti clipping algorithm and will handle many odd edge cases (which may be overkill for you)
You might consider the clipper library for doing generic 2D polygon clipping, area computation, intersection testing, etc. It is fairly compact and easy to deal with, and has decent examples of how to use it. It is an implementation of the Vatti clipping algorithm and will handle many odd edge cases (which may be overkill for you) [Can ho celadon city](http://stda.vn/du-an/celadon-city-tan-phu/1396) - [vinhomes central park](http://vinhomescentralpark.info)
30,898,336
I have a UIScrollView (with a clear background) and behind it I have a UIImage that takes up about 1/3 of the devices height. In order to initial display the image which is sitting being the scroll view I set the scrollviews contentInset to use the same height as the image. This does exactly what I want, initialing showing the image, but scrolling down will eventually cover the image with the scroll views content. The only issue is I added a button onto of the image. However it cannot be touched because the UIScrollView is actually over the top of it (even though the button can be seen due to the clear background). How can I get this to work. ![enter image description here](https://i.stack.imgur.com/3l7xH.png) ![enter image description here](https://i.stack.imgur.com/GY0n2.png) Edit: The following solved the problem: ``` //viewdidload self.scrollView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "onScrollViewTapped:")) ... func onScrollViewTapped(recognizer:UITapGestureRecognizer) { var point = recognizer.locationInView(self.view) if CGRectContainsPoint(self.closeButton.frame, point) { self.closeButton.sendActionsForControlEvents(UIControlEvents.TouchUpInside) } } ```
2015/06/17
[ "https://Stackoverflow.com/questions/30898336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1232048/" ]
Thanks for the screenshots and reference to Google maps doing what you're looking for, I can see what you're talking about now. I noticed that the image is clickable and is scrolled over but there is no button showing on the image itself. What you can do is put a clear button in your UIScrollView that covers the image in order to make it clickable when you're able to see it. You're not going to be able to click anything under a UIScrollView as far as I can tell. Please let me know if that works for you.
Two things to test: 1) Make sure the image that contains the button has its `userInteractionEnabled` set to `true` (the default is false). Although, since the button is a subview and added on top of the `ImageView` (I assume) then this might not help. 2) If that doesn't help, can you instead add the button as a `subview` of the `UIScrollView` and set its position to be where the image is? This way it should stay on the image and will be hidden as the user scrolls down, but clickable since it is a child of the `ScrollView`. Some code and/or images would help as well.
30,898,336
I have a UIScrollView (with a clear background) and behind it I have a UIImage that takes up about 1/3 of the devices height. In order to initial display the image which is sitting being the scroll view I set the scrollviews contentInset to use the same height as the image. This does exactly what I want, initialing showing the image, but scrolling down will eventually cover the image with the scroll views content. The only issue is I added a button onto of the image. However it cannot be touched because the UIScrollView is actually over the top of it (even though the button can be seen due to the clear background). How can I get this to work. ![enter image description here](https://i.stack.imgur.com/3l7xH.png) ![enter image description here](https://i.stack.imgur.com/GY0n2.png) Edit: The following solved the problem: ``` //viewdidload self.scrollView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "onScrollViewTapped:")) ... func onScrollViewTapped(recognizer:UITapGestureRecognizer) { var point = recognizer.locationInView(self.view) if CGRectContainsPoint(self.closeButton.frame, point) { self.closeButton.sendActionsForControlEvents(UIControlEvents.TouchUpInside) } } ```
2015/06/17
[ "https://Stackoverflow.com/questions/30898336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1232048/" ]
Thanks for the screenshots and reference to Google maps doing what you're looking for, I can see what you're talking about now. I noticed that the image is clickable and is scrolled over but there is no button showing on the image itself. What you can do is put a clear button in your UIScrollView that covers the image in order to make it clickable when you're able to see it. You're not going to be able to click anything under a UIScrollView as far as I can tell. Please let me know if that works for you.
I think the way to do this is to subclass whatever objects are in your UIScrollView and override `touches began` / `touches ended`. Then figure out which coordinates are being touched and whether they land within the bounds of your button e.g. in Swift this would be: ``` override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent?) { println("!!! touchesBegan") if var touch = touches.first { var touchObj:UITouch = touch as! UITouch println("touchesBegan \(touchObj.locationInView(self))") //this locationInView should probably target the main screen view and then test coordinates against your button bounds } super.touchesBegan(touches, withEvent:event!) } ``` See : <https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIResponder_Class/index.html#//apple_ref/occ/instm/UIResponder/touchesBegan:withEvent>: And: <https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITouch_Class/index.html#//apple_ref/occ/instm/UITouch/locationInView>:
30,898,336
I have a UIScrollView (with a clear background) and behind it I have a UIImage that takes up about 1/3 of the devices height. In order to initial display the image which is sitting being the scroll view I set the scrollviews contentInset to use the same height as the image. This does exactly what I want, initialing showing the image, but scrolling down will eventually cover the image with the scroll views content. The only issue is I added a button onto of the image. However it cannot be touched because the UIScrollView is actually over the top of it (even though the button can be seen due to the clear background). How can I get this to work. ![enter image description here](https://i.stack.imgur.com/3l7xH.png) ![enter image description here](https://i.stack.imgur.com/GY0n2.png) Edit: The following solved the problem: ``` //viewdidload self.scrollView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "onScrollViewTapped:")) ... func onScrollViewTapped(recognizer:UITapGestureRecognizer) { var point = recognizer.locationInView(self.view) if CGRectContainsPoint(self.closeButton.frame, point) { self.closeButton.sendActionsForControlEvents(UIControlEvents.TouchUpInside) } } ```
2015/06/17
[ "https://Stackoverflow.com/questions/30898336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1232048/" ]
Thanks for the screenshots and reference to Google maps doing what you're looking for, I can see what you're talking about now. I noticed that the image is clickable and is scrolled over but there is no button showing on the image itself. What you can do is put a clear button in your UIScrollView that covers the image in order to make it clickable when you're able to see it. You're not going to be able to click anything under a UIScrollView as far as I can tell. Please let me know if that works for you.
You should subclass `UIScrollView` and override `-hitTest:withEvent:` like so, to make sure it only eats touches it should. ``` - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event { UIView *const inherited = [super hitTest:point withEvent:event]; if (inherited == self) return nil; return inherited; } ``` Also make sure to set `userInteractionEnabled` to `YES` in your image view.
30,898,336
I have a UIScrollView (with a clear background) and behind it I have a UIImage that takes up about 1/3 of the devices height. In order to initial display the image which is sitting being the scroll view I set the scrollviews contentInset to use the same height as the image. This does exactly what I want, initialing showing the image, but scrolling down will eventually cover the image with the scroll views content. The only issue is I added a button onto of the image. However it cannot be touched because the UIScrollView is actually over the top of it (even though the button can be seen due to the clear background). How can I get this to work. ![enter image description here](https://i.stack.imgur.com/3l7xH.png) ![enter image description here](https://i.stack.imgur.com/GY0n2.png) Edit: The following solved the problem: ``` //viewdidload self.scrollView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "onScrollViewTapped:")) ... func onScrollViewTapped(recognizer:UITapGestureRecognizer) { var point = recognizer.locationInView(self.view) if CGRectContainsPoint(self.closeButton.frame, point) { self.closeButton.sendActionsForControlEvents(UIControlEvents.TouchUpInside) } } ```
2015/06/17
[ "https://Stackoverflow.com/questions/30898336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1232048/" ]
Thanks for the screenshots and reference to Google maps doing what you're looking for, I can see what you're talking about now. I noticed that the image is clickable and is scrolled over but there is no button showing on the image itself. What you can do is put a clear button in your UIScrollView that covers the image in order to make it clickable when you're able to see it. You're not going to be able to click anything under a UIScrollView as far as I can tell. Please let me know if that works for you.
There is 2 way you can checked that weather touch event is fire on UIButton or not? **Option 1** : You need to add `UITapGesture` on `UIScrollView`. while tapping on UIScrollView. Tap gesture return touch point with respect to UIScrollView. you need to convert that touch point with respect to main `UIView`(that is self.view) using following method. ``` CGPoint originInSuperview = [superview convertPoint:CGPointZero fromView:subview]; ``` after successfully conversation, you can checked that weather touch point is interact with `UIButton` frame or what. if it interact then you can perform you action that you are going to perform on `UIButton` selector. ``` CGRectContainsPoint(buttonView.frame, point) ``` **Option 2** : Received first touch event while user touch on iPhone screen. and redirect touch point to current `UIViewController`. where you can check interact as like in **option 1** describe. and perform your action. **Option 2** is already integrated in one of my project successfully but i have forgot the library that received first tap event and redirect to current controller. when i know its name i will remind you. May this help you.
30,898,336
I have a UIScrollView (with a clear background) and behind it I have a UIImage that takes up about 1/3 of the devices height. In order to initial display the image which is sitting being the scroll view I set the scrollviews contentInset to use the same height as the image. This does exactly what I want, initialing showing the image, but scrolling down will eventually cover the image with the scroll views content. The only issue is I added a button onto of the image. However it cannot be touched because the UIScrollView is actually over the top of it (even though the button can be seen due to the clear background). How can I get this to work. ![enter image description here](https://i.stack.imgur.com/3l7xH.png) ![enter image description here](https://i.stack.imgur.com/GY0n2.png) Edit: The following solved the problem: ``` //viewdidload self.scrollView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "onScrollViewTapped:")) ... func onScrollViewTapped(recognizer:UITapGestureRecognizer) { var point = recognizer.locationInView(self.view) if CGRectContainsPoint(self.closeButton.frame, point) { self.closeButton.sendActionsForControlEvents(UIControlEvents.TouchUpInside) } } ```
2015/06/17
[ "https://Stackoverflow.com/questions/30898336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1232048/" ]
a simple solution is to reorder the views in the document out line. The higher the view in the outline, the lower the view is as a layer ![enter image description here](https://i.stack.imgur.com/SG2hQ.png)
Two things to test: 1) Make sure the image that contains the button has its `userInteractionEnabled` set to `true` (the default is false). Although, since the button is a subview and added on top of the `ImageView` (I assume) then this might not help. 2) If that doesn't help, can you instead add the button as a `subview` of the `UIScrollView` and set its position to be where the image is? This way it should stay on the image and will be hidden as the user scrolls down, but clickable since it is a child of the `ScrollView`. Some code and/or images would help as well.
30,898,336
I have a UIScrollView (with a clear background) and behind it I have a UIImage that takes up about 1/3 of the devices height. In order to initial display the image which is sitting being the scroll view I set the scrollviews contentInset to use the same height as the image. This does exactly what I want, initialing showing the image, but scrolling down will eventually cover the image with the scroll views content. The only issue is I added a button onto of the image. However it cannot be touched because the UIScrollView is actually over the top of it (even though the button can be seen due to the clear background). How can I get this to work. ![enter image description here](https://i.stack.imgur.com/3l7xH.png) ![enter image description here](https://i.stack.imgur.com/GY0n2.png) Edit: The following solved the problem: ``` //viewdidload self.scrollView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "onScrollViewTapped:")) ... func onScrollViewTapped(recognizer:UITapGestureRecognizer) { var point = recognizer.locationInView(self.view) if CGRectContainsPoint(self.closeButton.frame, point) { self.closeButton.sendActionsForControlEvents(UIControlEvents.TouchUpInside) } } ```
2015/06/17
[ "https://Stackoverflow.com/questions/30898336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1232048/" ]
a simple solution is to reorder the views in the document out line. The higher the view in the outline, the lower the view is as a layer ![enter image description here](https://i.stack.imgur.com/SG2hQ.png)
I think the way to do this is to subclass whatever objects are in your UIScrollView and override `touches began` / `touches ended`. Then figure out which coordinates are being touched and whether they land within the bounds of your button e.g. in Swift this would be: ``` override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent?) { println("!!! touchesBegan") if var touch = touches.first { var touchObj:UITouch = touch as! UITouch println("touchesBegan \(touchObj.locationInView(self))") //this locationInView should probably target the main screen view and then test coordinates against your button bounds } super.touchesBegan(touches, withEvent:event!) } ``` See : <https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIResponder_Class/index.html#//apple_ref/occ/instm/UIResponder/touchesBegan:withEvent>: And: <https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITouch_Class/index.html#//apple_ref/occ/instm/UITouch/locationInView>:
30,898,336
I have a UIScrollView (with a clear background) and behind it I have a UIImage that takes up about 1/3 of the devices height. In order to initial display the image which is sitting being the scroll view I set the scrollviews contentInset to use the same height as the image. This does exactly what I want, initialing showing the image, but scrolling down will eventually cover the image with the scroll views content. The only issue is I added a button onto of the image. However it cannot be touched because the UIScrollView is actually over the top of it (even though the button can be seen due to the clear background). How can I get this to work. ![enter image description here](https://i.stack.imgur.com/3l7xH.png) ![enter image description here](https://i.stack.imgur.com/GY0n2.png) Edit: The following solved the problem: ``` //viewdidload self.scrollView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "onScrollViewTapped:")) ... func onScrollViewTapped(recognizer:UITapGestureRecognizer) { var point = recognizer.locationInView(self.view) if CGRectContainsPoint(self.closeButton.frame, point) { self.closeButton.sendActionsForControlEvents(UIControlEvents.TouchUpInside) } } ```
2015/06/17
[ "https://Stackoverflow.com/questions/30898336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1232048/" ]
a simple solution is to reorder the views in the document out line. The higher the view in the outline, the lower the view is as a layer ![enter image description here](https://i.stack.imgur.com/SG2hQ.png)
You should subclass `UIScrollView` and override `-hitTest:withEvent:` like so, to make sure it only eats touches it should. ``` - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event { UIView *const inherited = [super hitTest:point withEvent:event]; if (inherited == self) return nil; return inherited; } ``` Also make sure to set `userInteractionEnabled` to `YES` in your image view.
30,898,336
I have a UIScrollView (with a clear background) and behind it I have a UIImage that takes up about 1/3 of the devices height. In order to initial display the image which is sitting being the scroll view I set the scrollviews contentInset to use the same height as the image. This does exactly what I want, initialing showing the image, but scrolling down will eventually cover the image with the scroll views content. The only issue is I added a button onto of the image. However it cannot be touched because the UIScrollView is actually over the top of it (even though the button can be seen due to the clear background). How can I get this to work. ![enter image description here](https://i.stack.imgur.com/3l7xH.png) ![enter image description here](https://i.stack.imgur.com/GY0n2.png) Edit: The following solved the problem: ``` //viewdidload self.scrollView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "onScrollViewTapped:")) ... func onScrollViewTapped(recognizer:UITapGestureRecognizer) { var point = recognizer.locationInView(self.view) if CGRectContainsPoint(self.closeButton.frame, point) { self.closeButton.sendActionsForControlEvents(UIControlEvents.TouchUpInside) } } ```
2015/06/17
[ "https://Stackoverflow.com/questions/30898336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1232048/" ]
a simple solution is to reorder the views in the document out line. The higher the view in the outline, the lower the view is as a layer ![enter image description here](https://i.stack.imgur.com/SG2hQ.png)
There is 2 way you can checked that weather touch event is fire on UIButton or not? **Option 1** : You need to add `UITapGesture` on `UIScrollView`. while tapping on UIScrollView. Tap gesture return touch point with respect to UIScrollView. you need to convert that touch point with respect to main `UIView`(that is self.view) using following method. ``` CGPoint originInSuperview = [superview convertPoint:CGPointZero fromView:subview]; ``` after successfully conversation, you can checked that weather touch point is interact with `UIButton` frame or what. if it interact then you can perform you action that you are going to perform on `UIButton` selector. ``` CGRectContainsPoint(buttonView.frame, point) ``` **Option 2** : Received first touch event while user touch on iPhone screen. and redirect touch point to current `UIViewController`. where you can check interact as like in **option 1** describe. and perform your action. **Option 2** is already integrated in one of my project successfully but i have forgot the library that received first tap event and redirect to current controller. when i know its name i will remind you. May this help you.
73,402,521
In r, is there a solution to superpose two boxplots in only one graph with a different number of data? (With a different color for data1 and data2) Rather than doing this : ``` data1 <- data.frame(T1_A=rnorm(37),T2_A=rnorm(37),T3_A=rnorm(37)) data2 <- data.frame(T1_B=rnorm(25),T2_B=rnorm(25),T3_B=rnorm(25)) par(mfrow = c(2,1) boxplot(data1) boxplot(data2) ``` Thanks !
2022/08/18
[ "https://Stackoverflow.com/questions/73402521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can use `&&` operator to multiple values with `some` method. ``` var users = [ {id: 1, firstName: 'Max', lastname: 'Muster', birthdate: '10.10.1990', number: '123'}, {id: 2, firstName: 'Mia', lastname: 'Gruber', birthdate: '11.03.2001', number: '254'} ]; function addUser (user) { const isExist = users.some(u => u.firstName === user.firstName && u.lastName === user.lastName && u.birthDate === user.birthDate) !isExist && users.push(user) } ```
You can use a lambda function as a parameter with `array.some()` in order to create custom validation like checking multiple values. As a working example with the code you added to the question: ```js const users = [ {id: 1, firstName: 'Max', lastname: 'Muster', birthdate: '10.10.1990', number: '123'}, {id: 2, firstName: 'Mia', lastname: 'Gruber', birthdate: '11.03.2001', number: '254'} ]; const userToAdd = {id: 3, firstName: 'Mia', lastname: 'Gruber', birthdate: '11.03.2001', number: '284'}; // Use some with a custom validation an saves the boolean result in "userAlreadyExists" const userAlreadyExists = users.some(u => u.firstName == userToAdd.firstName && u.lastname == userToAdd.lastname && u.birthdate == userToAdd.birthdate ); // logs "true", as expected :) console.log(userAlreadyExists); ```
73,402,521
In r, is there a solution to superpose two boxplots in only one graph with a different number of data? (With a different color for data1 and data2) Rather than doing this : ``` data1 <- data.frame(T1_A=rnorm(37),T2_A=rnorm(37),T3_A=rnorm(37)) data2 <- data.frame(T1_B=rnorm(25),T2_B=rnorm(25),T3_B=rnorm(25)) par(mfrow = c(2,1) boxplot(data1) boxplot(data2) ``` Thanks !
2022/08/18
[ "https://Stackoverflow.com/questions/73402521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can use a lambda function as a parameter with `array.some()` in order to create custom validation like checking multiple values. As a working example with the code you added to the question: ```js const users = [ {id: 1, firstName: 'Max', lastname: 'Muster', birthdate: '10.10.1990', number: '123'}, {id: 2, firstName: 'Mia', lastname: 'Gruber', birthdate: '11.03.2001', number: '254'} ]; const userToAdd = {id: 3, firstName: 'Mia', lastname: 'Gruber', birthdate: '11.03.2001', number: '284'}; // Use some with a custom validation an saves the boolean result in "userAlreadyExists" const userAlreadyExists = users.some(u => u.firstName == userToAdd.firstName && u.lastname == userToAdd.lastname && u.birthdate == userToAdd.birthdate ); // logs "true", as expected :) console.log(userAlreadyExists); ```
One method of comparing objects in JavaScript is to compare their strings. Use `JSON.stringify()` to convert the objects into strings and just compare them after. **Sample code:** ``` function checkIfPresent() { var users = [ { id: 1, firstName: "Max", lastname: "Muster", birthdate: "10.10.1990", number: "123", }, { id: 2, firstName: "Mia", lastname: "Gruber", birthdate: "11.03.2001", number: "254", }, ]; var obj = { id: 1, firstName: "Max", lastname: "Muster", birthdate: "10.10.1990", number: "123", }; for (var i = 0; i < users.length; ++i) { if (JSON.stringify(users[i]) === JSON.stringify(obj)) { return true; } } return false; } console.log(checkIfPresent()); ```
73,402,521
In r, is there a solution to superpose two boxplots in only one graph with a different number of data? (With a different color for data1 and data2) Rather than doing this : ``` data1 <- data.frame(T1_A=rnorm(37),T2_A=rnorm(37),T3_A=rnorm(37)) data2 <- data.frame(T1_B=rnorm(25),T2_B=rnorm(25),T3_B=rnorm(25)) par(mfrow = c(2,1) boxplot(data1) boxplot(data2) ``` Thanks !
2022/08/18
[ "https://Stackoverflow.com/questions/73402521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can use `&&` operator to multiple values with `some` method. ``` var users = [ {id: 1, firstName: 'Max', lastname: 'Muster', birthdate: '10.10.1990', number: '123'}, {id: 2, firstName: 'Mia', lastname: 'Gruber', birthdate: '11.03.2001', number: '254'} ]; function addUser (user) { const isExist = users.some(u => u.firstName === user.firstName && u.lastName === user.lastName && u.birthDate === user.birthDate) !isExist && users.push(user) } ```
One method of comparing objects in JavaScript is to compare their strings. Use `JSON.stringify()` to convert the objects into strings and just compare them after. **Sample code:** ``` function checkIfPresent() { var users = [ { id: 1, firstName: "Max", lastname: "Muster", birthdate: "10.10.1990", number: "123", }, { id: 2, firstName: "Mia", lastname: "Gruber", birthdate: "11.03.2001", number: "254", }, ]; var obj = { id: 1, firstName: "Max", lastname: "Muster", birthdate: "10.10.1990", number: "123", }; for (var i = 0; i < users.length; ++i) { if (JSON.stringify(users[i]) === JSON.stringify(obj)) { return true; } } return false; } console.log(checkIfPresent()); ```
73,402,521
In r, is there a solution to superpose two boxplots in only one graph with a different number of data? (With a different color for data1 and data2) Rather than doing this : ``` data1 <- data.frame(T1_A=rnorm(37),T2_A=rnorm(37),T3_A=rnorm(37)) data2 <- data.frame(T1_B=rnorm(25),T2_B=rnorm(25),T3_B=rnorm(25)) par(mfrow = c(2,1) boxplot(data1) boxplot(data2) ``` Thanks !
2022/08/18
[ "https://Stackoverflow.com/questions/73402521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can use `&&` operator to multiple values with `some` method. ``` var users = [ {id: 1, firstName: 'Max', lastname: 'Muster', birthdate: '10.10.1990', number: '123'}, {id: 2, firstName: 'Mia', lastname: 'Gruber', birthdate: '11.03.2001', number: '254'} ]; function addUser (user) { const isExist = users.some(u => u.firstName === user.firstName && u.lastName === user.lastName && u.birthDate === user.birthDate) !isExist && users.push(user) } ```
Another approach to check the existence of an object in the array ```js const users = [ {id: 1, firstName: 'Max', lastname: 'Muster', birthdate: '10.10.1990', number: '123'}, {id: 2, firstName: 'Mia', lastname: 'Gruber', birthdate: '11.03.2001', number: '254'} ]; const userToAdd = {id: 3, firstName: 'Mia', lastname: 'Gruber', birthdate: '11.03.2001', number: '284'}; const isUserinStore = (users, userToAdd) => { const getHash = ({ firstName, lastname, birthdate }) => [firstName, lastname, birthdate].join('|||'); return users.some((user) => getHash(user) === getHash(userToAdd)); }; console.log(isUserinStore(users, userToAdd)); ``` ```css .as-console-wrapper { max-height: 100% !important; top: 0 } ```
73,402,521
In r, is there a solution to superpose two boxplots in only one graph with a different number of data? (With a different color for data1 and data2) Rather than doing this : ``` data1 <- data.frame(T1_A=rnorm(37),T2_A=rnorm(37),T3_A=rnorm(37)) data2 <- data.frame(T1_B=rnorm(25),T2_B=rnorm(25),T3_B=rnorm(25)) par(mfrow = c(2,1) boxplot(data1) boxplot(data2) ``` Thanks !
2022/08/18
[ "https://Stackoverflow.com/questions/73402521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Another approach to check the existence of an object in the array ```js const users = [ {id: 1, firstName: 'Max', lastname: 'Muster', birthdate: '10.10.1990', number: '123'}, {id: 2, firstName: 'Mia', lastname: 'Gruber', birthdate: '11.03.2001', number: '254'} ]; const userToAdd = {id: 3, firstName: 'Mia', lastname: 'Gruber', birthdate: '11.03.2001', number: '284'}; const isUserinStore = (users, userToAdd) => { const getHash = ({ firstName, lastname, birthdate }) => [firstName, lastname, birthdate].join('|||'); return users.some((user) => getHash(user) === getHash(userToAdd)); }; console.log(isUserinStore(users, userToAdd)); ``` ```css .as-console-wrapper { max-height: 100% !important; top: 0 } ```
One method of comparing objects in JavaScript is to compare their strings. Use `JSON.stringify()` to convert the objects into strings and just compare them after. **Sample code:** ``` function checkIfPresent() { var users = [ { id: 1, firstName: "Max", lastname: "Muster", birthdate: "10.10.1990", number: "123", }, { id: 2, firstName: "Mia", lastname: "Gruber", birthdate: "11.03.2001", number: "254", }, ]; var obj = { id: 1, firstName: "Max", lastname: "Muster", birthdate: "10.10.1990", number: "123", }; for (var i = 0; i < users.length; ++i) { if (JSON.stringify(users[i]) === JSON.stringify(obj)) { return true; } } return false; } console.log(checkIfPresent()); ```
56,252,963
I'm trying to condense non-sequential numbers to subset haplotype data. I could do it manually, but given that I've got hundreds to do, I'd rather not if there's an alternative ``` class(haplotype1[[1]]) #[1] "integer" haplotype1[[1]] #[1] 1 2 3 4 5 7 8 9 10 11 ``` I want to get `[1:5, 7:11]`, which seems simple, but I haven't found a solution exactly matching my problem Thanks!
2019/05/22
[ "https://Stackoverflow.com/questions/56252963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9396277/" ]
```cs List<MyKnownType> rows; using (var conn = new SqlConnection(connectionString)) { DateTime when = ... /// 2019-05-20 - typed **as a DateTime**, not a string rows = conn.Query<MyKnownType>("return_records", new { ParamNameHere = when, AnotherParamName = "ABC" }, // this is the parameters commandType: CommandType.StoredProcedure ).AsList(); } ``` Important points here: * `DataTable` is almost never a preferred choice, unless you're writing a dynamic reporting app, or something similar to SSMS * in this case, I'm using a `class MyKnownType { ... }` which would have properties that match your expected columns in both name and type * parameters; always parameters * ADO.NET has an unfriendly API; tools like "Dapper", shown above, make it easy * I removed the `sp_` prefix; [you aren't meant to do that](https://stackoverflow.com/questions/42640852/using-sp-as-prefix-for-user-stored-procedures-in-sql-server-causing-performance)
``` using System.Collections.Generic; using System.Text; using System.Web.Mvc; using System.Data.Entity; public class Car { public string Model{ get; set; } public string Color{ get; set; } public int Year { get; set; } } var sql = new StringBuilder(); sql.Append(" SELECT Model, Color, Year "); sql.Append(" FROM TableCar "); var list = someDBCONTEXT.Database.SqlQuery<Car>(sql.ToString()).ToList(); ``` Important points here: I'm using Entity Framework 6
184,429
Is it possible to avoid hardcoding the `\node` position in the below MWE and apply horisontal offset of the Forest node to the TikZ node it links to? The goal is to put the green nodes as close as possible to right above the linked Forest node, but at the same time try not to overlap other Forest nodes. The vertical position will have to be hardcoded. ``` \documentclass{standalone} \usepackage{forest} \begin{document} \begin{forest} for tree={ draw=black, align=center, l sep=4ex, parent anchor=south, child anchor=north, node options={font=\footnotesize, minimum width=14em, minimum height=10ex}, edge path={ \noexpand\path[\forestoption{edge}] (!u.parent anchor) -- +(0,-2ex) -| (.child anchor)\forestoption{edge label}; } } [Parent [SubParent [Child1 [Child11] [Child12,name=Child12] ] [Child2 [Child21] [Child22] [Child23,name=Child23] ] [Child3 [Child31] [Child32] ] ] ] % \tikzset{every node/.style={font=\footnotesize, draw=green, minimum width=14em, minimum height=10ex}} % \node[anchor=south,draw=green](Second1) at (-30em, -15ex) {Second Parent 1}[]; \node[anchor=south,draw=green](Second2) at (15em, -15ex) {Second Parent 2}[]; % \draw[->,dotted] (Child12) to[out=north east,in=south] (Second1); \draw[->,dotted] (Child23) to[out=north east,in=south] (Second2); \end{forest} \end{document} ```
2014/06/11
[ "https://tex.stackexchange.com/questions/184429", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/37570/" ]
You don't actually need the `positioning` library for this although that is one option. At least, if I've understood what you want to do correctly: ``` \documentclass{standalone} \usepackage{forest} \begin{document} \begin{forest} for tree={ draw=black, align=center, l sep=4ex, parent anchor=south, child anchor=north, node options={font=\footnotesize, minimum width=14em, minimum height=10ex}, edge path={ \noexpand\path[\forestoption{edge}] (!u.parent anchor) -- +(0,-2ex) -| (.child anchor)\forestoption{edge label}; } } [Parent [SubParent [Child1 [Child11] [Child12,name=Child12] ] [Child2 [Child21] [Child22] [Child23,name=Child23] ] [Child3 [Child31] [Child32] ] ] ] % \tikzset{every node/.style={font=\footnotesize, draw=green, minimum width=14em, minimum height=10ex}} % \node[anchor=south,draw=green](Second1) at (Child12 |- 0,-15ex) {Second Parent 1}[]; \node[anchor=south,draw=green](Second2) at (Child23 |- 0,-15ex) {Second Parent 2}[]; % \draw[->,dotted] (Child12) to[out=north east,in=south] (Second1); \draw[->,dotted] (Child23) to[out=north east,in=south] (Second2); \end{forest} \end{document} ``` ![Non-hardcoded second parents](https://i.stack.imgur.com/UZpO2.png)
Another way is to use the `yshift` key in setting coordinates. Since your green box `Second1` is directly above the `Child12` node, you can use ``` \draw(Child12) to ([yshift=25ex]Child12) node{Second Parent 1}; ``` to draw a line from `Child12` to a coordinate `25ex` units above it. Including the `node` operation in the same path allows you to place a node at the latter coordinate. Setting the appropriate styles for `draw` and `node` is easy from here on. Code ==== ``` \documentclass{standalone} \usepackage{forest} \begin{document} \begin{forest} for tree={ draw=black, align=center, l sep=4ex, parent anchor=south, child anchor=north, node options={font=\footnotesize, minimum width=14em, minimum height=10ex}, edge path={ \noexpand\path[\forestoption{edge}] (!u.parent anchor) -- +(0,-2ex) -| (.child anchor)\forestoption{edge label}; } } [Parent [SubParent [Child1 [Child11] [Child12,name=Child12] ] [Child2 [Child21] [Child22] [Child23,name=Child23] ] [Child3 [Child31] [Child32] ] ] ] % \tikzset{every node/.style={font=\footnotesize, draw=green, solid, minimum width=14em, minimum height=10ex}} \draw[->,dotted] (Child12) to[out=north east,in=south] ([yshift=25ex]Child12) node[anchor=south]{Second Parent 1}; \draw[->,dotted] (Child23) to[out=north east,in=south] ([yshift=25ex]Child23) node[anchor=south]{Second Parent 2}; \end{forest} \end{document} ``` Output ====== ![enter image description here](https://i.stack.imgur.com/DIXBs.png)
35,199,349
in flask-socketio, is it possible to force the transport to be only web socket? According to the original protocol: ``` https://github.com/socketio/engine.io transports (<Array> String): transports to allow connections to (['polling', 'websocket']) ``` My goal would be to get rid of the original HTTP call. Best,
2016/02/04
[ "https://Stackoverflow.com/questions/35199349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4541683/" ]
See this post - [Socket.io 1.x: use WebSockets only?](https://stackoverflow.com/q/28238628/2404152) It looks like you can't get rid of the original HTTP call, but you can tell the client not to use long-polling. ``` var socket = io({transports: ['websocket']}); ``` I can't find a way to disable it from the server-side with Flask-SocketIO.
According to the documentation of Flask-SoskcetIO you can use async\_mode to set async\_mode. if you installed eventlet or gevent with gevent-websocket the websocket would be used first. ``` async_mode: The asynchronous model to use. See the Deployment section in the documentation for a description of the available options. Valid async modes are ``threading``, ``eventlet``, ``gevent`` and ``gevent_uwsgi``. If this argument is not given, ``eventlet`` is tried first, then ``gevent_uwsgi``, then ``gevent``, and finally ``threading``. The first async mode that has all its dependencies installed is then one that is chosen. ```
13,730,365
I'm creating a registration form. The user enters the username and password, and presses submit, and the form is submitted using POST. HTML : ``` <link href="Styles/RegisterStyles.css" rel="stylesheet" type="text/css" /> <form id="frmRegister" method="post" action="register.php"> <h1>Register</h1> <table width="100%"> <tr> <td width="16%"><label class="alignRight"> Username: </label></td> <td width="84%"><input name="txtUsername" type="text" maxlength="40" /></td> </tr> <tr> <td width="16%"><label class="alignRight"> Password: </label></td> <td width="84%"><input name="txtPassword" type="text" maxlength="40" /></td> </tr> <tr> <td width="16%">&nbsp;</td> <td width="84%"><input name="Submit" class="submitButton" type="submit" /></td> </tr> </table> </form> </html> ``` PHP: ``` $username = $_POST["txtUsername"]; $password = $_POST["txtPassword"]; //Code to connect to database function doesUsernameExist($username) { //return true if username exists or false otherwise } ``` Now, in PHP, I run a query to check if the username exists in the database. If the username already exists, how can I notify the user without navigating to another page and causing the "username" and "password" fields to be reset to blank? Some registration forms have a really neat Javascript that checks if the username exists each time you press a key on the keyboard. Any ideas on how this could be implemented? It's difficult ( and bad practice ) to connect to a database using JavaScript from what I can gather.
2012/12/05
[ "https://Stackoverflow.com/questions/13730365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/656963/" ]
My solution to this would be to utilize AJAX. On submission of your form, make an AJAX call to a page that will evaluate the data that has been input into the form, and return information regarding whether or not it was validated. After you get back some information from that AJAX call, determine whether or not to submit the form again, but this time to a page that will absorb the data into the database. It's one solution; and as an AJAX newbie I'd say there are probably better ones, but it might work for you.
A great option is to use jQuery/AJAX. [Look at these examples](https://stackoverflow.com/questions/13499559/make-div-text-change-on-click-based-on-php-data-using-ajax/13501242#13501242) and try them out on your server. In this example, in FILE1.php, note that it is passing a blank value. You don't want to pass a blank value, this is where you would put your username and password to deliver to FILE2.php. In your case, the line would look like this: ``` data: 'username='+username+'&password='+password, ``` In the FILE2.php example, you would retrieve those values like this: ``` $uname = $_POST['username']; $pword = $_POST['password']; ``` Then do your MySQL lookup and return the values thus: ``` echo 1; ``` This would deliver a `1` to the success function in FILE1.php, and it would be stored in the variable called "data". Therefore, the `alert(data)` line in the success function would alert the number one. [Here is another good example](https://stackoverflow.com/questions/13502638/submit-form-and-pass-values-with-ajax/13502872#13502872) to review. The approach is to create your form, and then use jQuery to detect the button press and submit the data to a secondary PHP file via AJAX. The above examples show how to do that. The secondary PHP file returns a response (whatever you choose to send) and that appears in the Success: section of your AJAX call. The jQuery/AJAX is JavaScript, so you have two options: you can place it within `<script type="text/javascript"></script>` tags within your main PHP document, or you can `<?php include "my_javascript_stuff.js"; ?>` at the bottom of your PHP document.
13,730,365
I'm creating a registration form. The user enters the username and password, and presses submit, and the form is submitted using POST. HTML : ``` <link href="Styles/RegisterStyles.css" rel="stylesheet" type="text/css" /> <form id="frmRegister" method="post" action="register.php"> <h1>Register</h1> <table width="100%"> <tr> <td width="16%"><label class="alignRight"> Username: </label></td> <td width="84%"><input name="txtUsername" type="text" maxlength="40" /></td> </tr> <tr> <td width="16%"><label class="alignRight"> Password: </label></td> <td width="84%"><input name="txtPassword" type="text" maxlength="40" /></td> </tr> <tr> <td width="16%">&nbsp;</td> <td width="84%"><input name="Submit" class="submitButton" type="submit" /></td> </tr> </table> </form> </html> ``` PHP: ``` $username = $_POST["txtUsername"]; $password = $_POST["txtPassword"]; //Code to connect to database function doesUsernameExist($username) { //return true if username exists or false otherwise } ``` Now, in PHP, I run a query to check if the username exists in the database. If the username already exists, how can I notify the user without navigating to another page and causing the "username" and "password" fields to be reset to blank? Some registration forms have a really neat Javascript that checks if the username exists each time you press a key on the keyboard. Any ideas on how this could be implemented? It's difficult ( and bad practice ) to connect to a database using JavaScript from what I can gather.
2012/12/05
[ "https://Stackoverflow.com/questions/13730365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/656963/" ]
I use jQuery to do something like this. in the html ``` <input type="text" name="username" onBlur="checkUsername(this)"> ``` in the javascript something like this ``` function checkUsername(v){ $.post("phppage.php",{ valToBeChecked:v },function(d){ if($.trim(d)==true){ // php page returned true }else{ // php page returned false } }); } ``` do note this is only an example, I think I got the syntax right tho.
A great option is to use jQuery/AJAX. [Look at these examples](https://stackoverflow.com/questions/13499559/make-div-text-change-on-click-based-on-php-data-using-ajax/13501242#13501242) and try them out on your server. In this example, in FILE1.php, note that it is passing a blank value. You don't want to pass a blank value, this is where you would put your username and password to deliver to FILE2.php. In your case, the line would look like this: ``` data: 'username='+username+'&password='+password, ``` In the FILE2.php example, you would retrieve those values like this: ``` $uname = $_POST['username']; $pword = $_POST['password']; ``` Then do your MySQL lookup and return the values thus: ``` echo 1; ``` This would deliver a `1` to the success function in FILE1.php, and it would be stored in the variable called "data". Therefore, the `alert(data)` line in the success function would alert the number one. [Here is another good example](https://stackoverflow.com/questions/13502638/submit-form-and-pass-values-with-ajax/13502872#13502872) to review. The approach is to create your form, and then use jQuery to detect the button press and submit the data to a secondary PHP file via AJAX. The above examples show how to do that. The secondary PHP file returns a response (whatever you choose to send) and that appears in the Success: section of your AJAX call. The jQuery/AJAX is JavaScript, so you have two options: you can place it within `<script type="text/javascript"></script>` tags within your main PHP document, or you can `<?php include "my_javascript_stuff.js"; ?>` at the bottom of your PHP document.
13,730,365
I'm creating a registration form. The user enters the username and password, and presses submit, and the form is submitted using POST. HTML : ``` <link href="Styles/RegisterStyles.css" rel="stylesheet" type="text/css" /> <form id="frmRegister" method="post" action="register.php"> <h1>Register</h1> <table width="100%"> <tr> <td width="16%"><label class="alignRight"> Username: </label></td> <td width="84%"><input name="txtUsername" type="text" maxlength="40" /></td> </tr> <tr> <td width="16%"><label class="alignRight"> Password: </label></td> <td width="84%"><input name="txtPassword" type="text" maxlength="40" /></td> </tr> <tr> <td width="16%">&nbsp;</td> <td width="84%"><input name="Submit" class="submitButton" type="submit" /></td> </tr> </table> </form> </html> ``` PHP: ``` $username = $_POST["txtUsername"]; $password = $_POST["txtPassword"]; //Code to connect to database function doesUsernameExist($username) { //return true if username exists or false otherwise } ``` Now, in PHP, I run a query to check if the username exists in the database. If the username already exists, how can I notify the user without navigating to another page and causing the "username" and "password" fields to be reset to blank? Some registration forms have a really neat Javascript that checks if the username exists each time you press a key on the keyboard. Any ideas on how this could be implemented? It's difficult ( and bad practice ) to connect to a database using JavaScript from what I can gather.
2012/12/05
[ "https://Stackoverflow.com/questions/13730365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/656963/" ]
This will do an AJAX check on blur of the input without jQuery. Edit: I want to clarify that I don't suggest this approach, and much prefer the use of jQuery (or other similar JS framework) for AJAX. However, I understand that not everyone has the luxury of specifying the technologies they use, and so here's the answer to your request! :) ``` <input id="txtUsername" name="txtUsername" /> <script type="text/javascript"> window.onload = function() { document.getElementById('txtUsername').onblur = function(e) { // Get the username entered var el = e.target; var username = el.value; // Create an XHR var xhr = null; if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } // AJAX call to the server request.open('GET', '/check_username.php?username=' + username, false); xhr.onload = function(e) { var json = eval(xhr.responseText); if (json.exists) { window.alert('That username exists already.'); } } xhr.send(); } } </script> ``` **user\_exists.php** ``` $username = isset($_GET['username']) ? $_GET['username'] : ''; $username = mysqli_real_escape_string($username); $sql = "SELECT COUNT(*) > 0 AS user_found FROM users WHERE username = '{$username}'"; $result = mysqli_query($sql); $exists = false; if ($row = mysqli_fetch_assoc($result)) { $exists = $row['user_found'] ? true : false; } echo json_encode(array('exists' => $exists)); ```
A great option is to use jQuery/AJAX. [Look at these examples](https://stackoverflow.com/questions/13499559/make-div-text-change-on-click-based-on-php-data-using-ajax/13501242#13501242) and try them out on your server. In this example, in FILE1.php, note that it is passing a blank value. You don't want to pass a blank value, this is where you would put your username and password to deliver to FILE2.php. In your case, the line would look like this: ``` data: 'username='+username+'&password='+password, ``` In the FILE2.php example, you would retrieve those values like this: ``` $uname = $_POST['username']; $pword = $_POST['password']; ``` Then do your MySQL lookup and return the values thus: ``` echo 1; ``` This would deliver a `1` to the success function in FILE1.php, and it would be stored in the variable called "data". Therefore, the `alert(data)` line in the success function would alert the number one. [Here is another good example](https://stackoverflow.com/questions/13502638/submit-form-and-pass-values-with-ajax/13502872#13502872) to review. The approach is to create your form, and then use jQuery to detect the button press and submit the data to a secondary PHP file via AJAX. The above examples show how to do that. The secondary PHP file returns a response (whatever you choose to send) and that appears in the Success: section of your AJAX call. The jQuery/AJAX is JavaScript, so you have two options: you can place it within `<script type="text/javascript"></script>` tags within your main PHP document, or you can `<?php include "my_javascript_stuff.js"; ?>` at the bottom of your PHP document.
13,730,365
I'm creating a registration form. The user enters the username and password, and presses submit, and the form is submitted using POST. HTML : ``` <link href="Styles/RegisterStyles.css" rel="stylesheet" type="text/css" /> <form id="frmRegister" method="post" action="register.php"> <h1>Register</h1> <table width="100%"> <tr> <td width="16%"><label class="alignRight"> Username: </label></td> <td width="84%"><input name="txtUsername" type="text" maxlength="40" /></td> </tr> <tr> <td width="16%"><label class="alignRight"> Password: </label></td> <td width="84%"><input name="txtPassword" type="text" maxlength="40" /></td> </tr> <tr> <td width="16%">&nbsp;</td> <td width="84%"><input name="Submit" class="submitButton" type="submit" /></td> </tr> </table> </form> </html> ``` PHP: ``` $username = $_POST["txtUsername"]; $password = $_POST["txtPassword"]; //Code to connect to database function doesUsernameExist($username) { //return true if username exists or false otherwise } ``` Now, in PHP, I run a query to check if the username exists in the database. If the username already exists, how can I notify the user without navigating to another page and causing the "username" and "password" fields to be reset to blank? Some registration forms have a really neat Javascript that checks if the username exists each time you press a key on the keyboard. Any ideas on how this could be implemented? It's difficult ( and bad practice ) to connect to a database using JavaScript from what I can gather.
2012/12/05
[ "https://Stackoverflow.com/questions/13730365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/656963/" ]
I use jQuery to do something like this. in the html ``` <input type="text" name="username" onBlur="checkUsername(this)"> ``` in the javascript something like this ``` function checkUsername(v){ $.post("phppage.php",{ valToBeChecked:v },function(d){ if($.trim(d)==true){ // php page returned true }else{ // php page returned false } }); } ``` do note this is only an example, I think I got the syntax right tho.
My solution to this would be to utilize AJAX. On submission of your form, make an AJAX call to a page that will evaluate the data that has been input into the form, and return information regarding whether or not it was validated. After you get back some information from that AJAX call, determine whether or not to submit the form again, but this time to a page that will absorb the data into the database. It's one solution; and as an AJAX newbie I'd say there are probably better ones, but it might work for you.
13,730,365
I'm creating a registration form. The user enters the username and password, and presses submit, and the form is submitted using POST. HTML : ``` <link href="Styles/RegisterStyles.css" rel="stylesheet" type="text/css" /> <form id="frmRegister" method="post" action="register.php"> <h1>Register</h1> <table width="100%"> <tr> <td width="16%"><label class="alignRight"> Username: </label></td> <td width="84%"><input name="txtUsername" type="text" maxlength="40" /></td> </tr> <tr> <td width="16%"><label class="alignRight"> Password: </label></td> <td width="84%"><input name="txtPassword" type="text" maxlength="40" /></td> </tr> <tr> <td width="16%">&nbsp;</td> <td width="84%"><input name="Submit" class="submitButton" type="submit" /></td> </tr> </table> </form> </html> ``` PHP: ``` $username = $_POST["txtUsername"]; $password = $_POST["txtPassword"]; //Code to connect to database function doesUsernameExist($username) { //return true if username exists or false otherwise } ``` Now, in PHP, I run a query to check if the username exists in the database. If the username already exists, how can I notify the user without navigating to another page and causing the "username" and "password" fields to be reset to blank? Some registration forms have a really neat Javascript that checks if the username exists each time you press a key on the keyboard. Any ideas on how this could be implemented? It's difficult ( and bad practice ) to connect to a database using JavaScript from what I can gather.
2012/12/05
[ "https://Stackoverflow.com/questions/13730365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/656963/" ]
This will do an AJAX check on blur of the input without jQuery. Edit: I want to clarify that I don't suggest this approach, and much prefer the use of jQuery (or other similar JS framework) for AJAX. However, I understand that not everyone has the luxury of specifying the technologies they use, and so here's the answer to your request! :) ``` <input id="txtUsername" name="txtUsername" /> <script type="text/javascript"> window.onload = function() { document.getElementById('txtUsername').onblur = function(e) { // Get the username entered var el = e.target; var username = el.value; // Create an XHR var xhr = null; if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } // AJAX call to the server request.open('GET', '/check_username.php?username=' + username, false); xhr.onload = function(e) { var json = eval(xhr.responseText); if (json.exists) { window.alert('That username exists already.'); } } xhr.send(); } } </script> ``` **user\_exists.php** ``` $username = isset($_GET['username']) ? $_GET['username'] : ''; $username = mysqli_real_escape_string($username); $sql = "SELECT COUNT(*) > 0 AS user_found FROM users WHERE username = '{$username}'"; $result = mysqli_query($sql); $exists = false; if ($row = mysqli_fetch_assoc($result)) { $exists = $row['user_found'] ? true : false; } echo json_encode(array('exists' => $exists)); ```
My solution to this would be to utilize AJAX. On submission of your form, make an AJAX call to a page that will evaluate the data that has been input into the form, and return information regarding whether or not it was validated. After you get back some information from that AJAX call, determine whether or not to submit the form again, but this time to a page that will absorb the data into the database. It's one solution; and as an AJAX newbie I'd say there are probably better ones, but it might work for you.
11,218,612
I have the following model: ``` public class Contact { public Contact() { Name = "Your Name"; Email = "Your Email"; Message = "Your Message"; } [Required] [StringLength(60,MinimumLength = 3)] public string Name { get; set; } [Required] [DataType(DataType.EmailAddress)] [RegularExpression(@"\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b")] public string Email { get; set; } [Required] [StringLength(2200, MinimumLength = 10)] [DataType(DataType.MultilineText)] public string Message { get; set; } } ``` For Message and Name, their default values (in the constructor) actually pass validation, obviously that is bad. I know I could check for this and throw an error in the Controller, but I'm trying to find a way to do these in the model (as I assume that is the correct place to do it).
2012/06/27
[ "https://Stackoverflow.com/questions/11218612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/451075/" ]
I wouldn't do this at all server side. Use a textbox watermark ala one of the many methods for ex. <http://code.google.com/p/jquery-watermark/>
Those look like hints, not default values. You should implement these with javascript, instead of setting them as input values.
94,305
Lets say I have the option of identifying a code path to take on the basis of a string comparison or else iffing the type: Which is quicker and why? ``` switch(childNode.Name) { case "Bob": break; case "Jill": break; case "Marko": break; } if(childNode is Bob) { } elseif(childNode is Jill) { } else if(childNode is Marko) { } ``` **Update:** The main reason I ask this is because the switch statement is perculiar about what counts as a case. For example it wont allow you to use variables, only constants which get moved to the main assembly. I assumed it had this restriction due to some funky stuff it was doing. If it is only translating to elseifs (as one poster commented) then why are we not allowed variables in case statements? **Caveat:** I am post-optimising. This method is called *many* times in a slow part of the app.
2008/09/18
[ "https://Stackoverflow.com/questions/94305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1143/" ]
If you've got the classes made, I'd suggest using a Strategy design pattern instead of switch or elseif.
A SWITCH construct was originally intended for integer data; it's intent was to use the argument directly as a index into a "dispatch table", a table of pointers. As such, there would be a single test, then launch directly to the relevant code, rather than a series of tests. The difficulty here is that it's use has been generalized to "string" types, which obviously cannot be used as an index, and all advantage of the SWITCH construct is lost. If speed is your intended goal, the problem is NOT your code, but your data structure. If the "name" space is as simple as you show it, better to code it into an integer value (when data is created, for example), and use this integer in the "many times in a slow part of the app".
94,305
Lets say I have the option of identifying a code path to take on the basis of a string comparison or else iffing the type: Which is quicker and why? ``` switch(childNode.Name) { case "Bob": break; case "Jill": break; case "Marko": break; } if(childNode is Bob) { } elseif(childNode is Jill) { } else if(childNode is Marko) { } ``` **Update:** The main reason I ask this is because the switch statement is perculiar about what counts as a case. For example it wont allow you to use variables, only constants which get moved to the main assembly. I assumed it had this restriction due to some funky stuff it was doing. If it is only translating to elseifs (as one poster commented) then why are we not allowed variables in case statements? **Caveat:** I am post-optimising. This method is called *many* times in a slow part of the app.
2008/09/18
[ "https://Stackoverflow.com/questions/94305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1143/" ]
Firstly, you're comparing apples and oranges. You'd first need to compare switch on type vs switch on string, and then if on type vs if on string, and then compare the winners. Secondly, this is the kind of thing OO was designed for. In languages that support OO, switching on type (of any kind) is a code smell that points to poor design. The solution is to derive from a common base with an abstract or virtual method (or a similar construct, depending on your language) eg. ``` class Node { public virtual void Action() { // Perform default action } } class Bob : Node { public override void Action() { // Perform action for Bill } } class Jill : Node { public override void Action() { // Perform action for Jill } } ``` Then, instead of doing the switch statement, you just call childNode.Action()
I kind of do it a bit different, The strings you're switching on are going to be constants, so you can predict the values at compile time. in your case i'd use the hash values, this is an int switch, you have 2 options, use compile time constants or calculate at run-time. ``` //somewhere in your code static long _bob = "Bob".GetUniqueHashCode(); static long _jill = "Jill".GetUniqueHashCode(); static long _marko = "Marko".GeUniquetHashCode(); void MyMethod() { ... if(childNode.Tag==0) childNode.Tag= childNode.Name.GetUniquetHashCode() switch(childNode.Tag) { case _bob : break; case _jill : break; case _marko : break; } } ``` The extension method for GetUniquetHashCode can be something like this: ``` public static class StringExtentions { /// <summary> /// Return unique Int64 value for input string /// </summary> /// <param name="strText"></param> /// <returns></returns> public static Int64 GetUniquetHashCode(this string strText) { Int64 hashCode = 0; if (!string.IsNullOrEmpty(strText)) { //Unicode Encode Covering all character-set byte[] byteContents = Encoding.Unicode.GetBytes(strText); System.Security.Cryptography.SHA256 hash = new System.Security.Cryptography.SHA256CryptoServiceProvider(); byte[] hashText = hash.ComputeHash(byteContents); //32Byte hashText separate //hashCodeStart = 0~7 8Byte //hashCodeMedium = 8~23 8Byte //hashCodeEnd = 24~31 8Byte //and Fold Int64 hashCodeStart = BitConverter.ToInt64(hashText, 0); Int64 hashCodeMedium = BitConverter.ToInt64(hashText, 8); Int64 hashCodeEnd = BitConverter.ToInt64(hashText, 24); hashCode = hashCodeStart ^ hashCodeMedium ^ hashCodeEnd; } return (hashCode); } } ``` The source of this code was published [here](https://www.codeproject.com/Articles/34309/Convert-String-to-bit-Integer) Please note that using Cryptography is slow, you would typically warm-up the supported string on application start, i do this my saving them at static fields as will not change and are not instance relevant. please note that I set the tag value of the node object, I could use any property or add one, just make sure that these are in sync with the actual text. I work on low latency systems and all my codes come as a string of command:value,command:value.... now the command are all known as 64 bit integer values so switching like this saves some CPU time.
94,305
Lets say I have the option of identifying a code path to take on the basis of a string comparison or else iffing the type: Which is quicker and why? ``` switch(childNode.Name) { case "Bob": break; case "Jill": break; case "Marko": break; } if(childNode is Bob) { } elseif(childNode is Jill) { } else if(childNode is Marko) { } ``` **Update:** The main reason I ask this is because the switch statement is perculiar about what counts as a case. For example it wont allow you to use variables, only constants which get moved to the main assembly. I assumed it had this restriction due to some funky stuff it was doing. If it is only translating to elseifs (as one poster commented) then why are we not allowed variables in case statements? **Caveat:** I am post-optimising. This method is called *many* times in a slow part of the app.
2008/09/18
[ "https://Stackoverflow.com/questions/94305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1143/" ]
I think the main performance issue here is, that in the switch block, you compare strings, and that in the if-else block, you check for types... Those two are not the same, and therefore, I'd say you're "comparing potatoes to bananas". I'd start by comparing this: ``` switch(childNode.Name) { case "Bob": break; case "Jill": break; case "Marko": break; } if(childNode.Name == "Bob") {} else if(childNode.Name == "Jill") {} else if(childNode.Name == "Marko") {} ```
Switch on string basically gets compiled into a if-else-if ladder. Try decompiling a simple one. In any case, testing string equailty should be cheaper since they are interned and all that would be needed is a reference check. Do what makes sense in terms of maintainability; if you are compring strings, do the string switch. If you are selecting based on type, a type ladder is the more appropriate.
94,305
Lets say I have the option of identifying a code path to take on the basis of a string comparison or else iffing the type: Which is quicker and why? ``` switch(childNode.Name) { case "Bob": break; case "Jill": break; case "Marko": break; } if(childNode is Bob) { } elseif(childNode is Jill) { } else if(childNode is Marko) { } ``` **Update:** The main reason I ask this is because the switch statement is perculiar about what counts as a case. For example it wont allow you to use variables, only constants which get moved to the main assembly. I assumed it had this restriction due to some funky stuff it was doing. If it is only translating to elseifs (as one poster commented) then why are we not allowed variables in case statements? **Caveat:** I am post-optimising. This method is called *many* times in a slow part of the app.
2008/09/18
[ "https://Stackoverflow.com/questions/94305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1143/" ]
Greg's profile results are great for the exact scenario he covered, but interestingly, the relative costs of the different methods change dramatically when considering a number of different factors including the number of types being compared, and the relative frequency and any patterns in the underlying data. The simple answer is that nobody can tell you what the performance difference is going to be in your specific scenario, you will need to measure the performance in different ways yourself in your own system to get an accurate answer. The If/Else chain is an effective approach for a small number of type comparisons, or if you can reliably predict which few types are going to make up the majority of the ones that you see. The potential problem with the approach is that as the number of types increases, the number of comparisons that must be executed increases as well. if I execute the following: ```cs int value = 25124; if(value == 0) ... else if (value == 1) ... else if (value == 2) ... ... else if (value == 25124) ... ``` each of the previous if conditions must be evaluated before the correct block is entered. On the other hand ```cs switch(value) { case 0:...break; case 1:...break; case 2:...break; ... case 25124:...break; } ``` will perform one simple jump to the correct bit of code. Where it gets more complicated in your example is that your other method uses a switch on strings rather than integers which gets a little more complicated. At a low level, strings can't be switched on in the same way that integer values can so the C# compiler does some magic to make this work for you. If the switch statement is "small enough" (where the compiler does what it thinks is best automatically) switching on strings generates code that is the same as an if/else chain. ```cs switch(someString) { case "Foo": DoFoo(); break; case "Bar": DoBar(); break; default: DoOther; break; } ``` is the same as: ```cs if(someString == "Foo") { DoFoo(); } else if(someString == "Bar") { DoBar(); } else { DoOther(); } ``` Once the list of items in the dictionary gets "big enough" the compiler will automatically create an internal dictionary that maps from the strings in the switch to an integer index and then a switch based on that index. It looks something like this (Just imagine more entries than I am going to bother to type) A static field is defined in a "hidden" location that is associated with the class containing the switch statement of type `Dictionary<string, int>` and given a mangled name ```cs //Make sure the dictionary is loaded if(theDictionary == null) { //This is simplified for clarity, the actual implementation is more complex // in order to ensure thread safety theDictionary = new Dictionary<string,int>(); theDictionary["Foo"] = 0; theDictionary["Bar"] = 1; } int switchIndex; if(theDictionary.TryGetValue(someString, out switchIndex)) { switch(switchIndex) { case 0: DoFoo(); break; case 1: DoBar(); break; } } else { DoOther(); } ``` In some quick tests that I just ran, the If/Else method is about 3x as fast as the switch for 3 different types (where the types are randomly distributed). At 25 types the switch is faster by a small margin (16%) at 50 types the switch is more than twice as fast. If you are going to be switching on a large number of types, I would suggest a 3rd method: ```cs private delegate void NodeHandler(ChildNode node); static Dictionary<RuntimeTypeHandle, NodeHandler> TypeHandleSwitcher = CreateSwitcher(); private static Dictionary<RuntimeTypeHandle, NodeHandler> CreateSwitcher() { var ret = new Dictionary<RuntimeTypeHandle, NodeHandler>(); ret[typeof(Bob).TypeHandle] = HandleBob; ret[typeof(Jill).TypeHandle] = HandleJill; ret[typeof(Marko).TypeHandle] = HandleMarko; return ret; } void HandleChildNode(ChildNode node) { NodeHandler handler; if (TaskHandleSwitcher.TryGetValue(Type.GetRuntimeType(node), out handler)) { handler(node); } else { //Unexpected type... } } ``` This is similar to what Ted Elliot suggested, but the usage of runtime type handles instead of full type objects avoids the overhead of loading the type object through reflection. Here are some quick timings on my machine: ``` Testing 3 iterations with 5,000,000 data elements (mode=Random) and 5 types Method Time % of optimal If/Else 179.67 100.00 TypeHandleDictionary 321.33 178.85 TypeDictionary 377.67 210.20 Switch 492.67 274.21 Testing 3 iterations with 5,000,000 data elements (mode=Random) and 10 types Method Time % of optimal If/Else 271.33 100.00 TypeHandleDictionary 312.00 114.99 TypeDictionary 374.33 137.96 Switch 490.33 180.71 Testing 3 iterations with 5,000,000 data elements (mode=Random) and 15 types Method Time % of optimal TypeHandleDictionary 312.00 100.00 If/Else 369.00 118.27 TypeDictionary 371.67 119.12 Switch 491.67 157.59 Testing 3 iterations with 5,000,000 data elements (mode=Random) and 20 types Method Time % of optimal TypeHandleDictionary 335.33 100.00 TypeDictionary 373.00 111.23 If/Else 462.67 137.97 Switch 490.33 146.22 Testing 3 iterations with 5,000,000 data elements (mode=Random) and 25 types Method Time % of optimal TypeHandleDictionary 319.33 100.00 TypeDictionary 371.00 116.18 Switch 483.00 151.25 If/Else 562.00 175.99 Testing 3 iterations with 5,000,000 data elements (mode=Random) and 50 types Method Time % of optimal TypeHandleDictionary 319.67 100.00 TypeDictionary 376.67 117.83 Switch 453.33 141.81 If/Else 1,032.67 323.04 ``` On my machine at least, the type handle dictionary approach beats all of the others for anything over 15 different types when the distribution of the types used as input to the method is random. If on the other hand, the input is composed entirely of the type that is checked first in the if/else chain that method is *much* faster: ``` Testing 3 iterations with 5,000,000 data elements (mode=UniformFirst) and 50 types Method Time % of optimal If/Else 39.00 100.00 TypeHandleDictionary 317.33 813.68 TypeDictionary 396.00 1,015.38 Switch 403.00 1,033.33 ``` Conversely, if the input is always the last thing in the if/else chain, it has the opposite effect: ``` Testing 3 iterations with 5,000,000 data elements (mode=UniformLast) and 50 types Method Time % of optimal TypeHandleDictionary 317.67 100.00 Switch 354.33 111.54 TypeDictionary 377.67 118.89 If/Else 1,907.67 600.52 ``` If you can make some assumptions about your input, you might get the best performance from a hybrid approach where you perform if/else checks for the few types that are most common, and then fall back to a dictionary-driven approach if those fail.
Surely the switch on String would compile down to a String comparison (one per case) which is slower than a type comparison (and far slower than the typical integer compare that is used for switch/case)?
94,305
Lets say I have the option of identifying a code path to take on the basis of a string comparison or else iffing the type: Which is quicker and why? ``` switch(childNode.Name) { case "Bob": break; case "Jill": break; case "Marko": break; } if(childNode is Bob) { } elseif(childNode is Jill) { } else if(childNode is Marko) { } ``` **Update:** The main reason I ask this is because the switch statement is perculiar about what counts as a case. For example it wont allow you to use variables, only constants which get moved to the main assembly. I assumed it had this restriction due to some funky stuff it was doing. If it is only translating to elseifs (as one poster commented) then why are we not allowed variables in case statements? **Caveat:** I am post-optimising. This method is called *many* times in a slow part of the app.
2008/09/18
[ "https://Stackoverflow.com/questions/94305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1143/" ]
Greg's profile results are great for the exact scenario he covered, but interestingly, the relative costs of the different methods change dramatically when considering a number of different factors including the number of types being compared, and the relative frequency and any patterns in the underlying data. The simple answer is that nobody can tell you what the performance difference is going to be in your specific scenario, you will need to measure the performance in different ways yourself in your own system to get an accurate answer. The If/Else chain is an effective approach for a small number of type comparisons, or if you can reliably predict which few types are going to make up the majority of the ones that you see. The potential problem with the approach is that as the number of types increases, the number of comparisons that must be executed increases as well. if I execute the following: ```cs int value = 25124; if(value == 0) ... else if (value == 1) ... else if (value == 2) ... ... else if (value == 25124) ... ``` each of the previous if conditions must be evaluated before the correct block is entered. On the other hand ```cs switch(value) { case 0:...break; case 1:...break; case 2:...break; ... case 25124:...break; } ``` will perform one simple jump to the correct bit of code. Where it gets more complicated in your example is that your other method uses a switch on strings rather than integers which gets a little more complicated. At a low level, strings can't be switched on in the same way that integer values can so the C# compiler does some magic to make this work for you. If the switch statement is "small enough" (where the compiler does what it thinks is best automatically) switching on strings generates code that is the same as an if/else chain. ```cs switch(someString) { case "Foo": DoFoo(); break; case "Bar": DoBar(); break; default: DoOther; break; } ``` is the same as: ```cs if(someString == "Foo") { DoFoo(); } else if(someString == "Bar") { DoBar(); } else { DoOther(); } ``` Once the list of items in the dictionary gets "big enough" the compiler will automatically create an internal dictionary that maps from the strings in the switch to an integer index and then a switch based on that index. It looks something like this (Just imagine more entries than I am going to bother to type) A static field is defined in a "hidden" location that is associated with the class containing the switch statement of type `Dictionary<string, int>` and given a mangled name ```cs //Make sure the dictionary is loaded if(theDictionary == null) { //This is simplified for clarity, the actual implementation is more complex // in order to ensure thread safety theDictionary = new Dictionary<string,int>(); theDictionary["Foo"] = 0; theDictionary["Bar"] = 1; } int switchIndex; if(theDictionary.TryGetValue(someString, out switchIndex)) { switch(switchIndex) { case 0: DoFoo(); break; case 1: DoBar(); break; } } else { DoOther(); } ``` In some quick tests that I just ran, the If/Else method is about 3x as fast as the switch for 3 different types (where the types are randomly distributed). At 25 types the switch is faster by a small margin (16%) at 50 types the switch is more than twice as fast. If you are going to be switching on a large number of types, I would suggest a 3rd method: ```cs private delegate void NodeHandler(ChildNode node); static Dictionary<RuntimeTypeHandle, NodeHandler> TypeHandleSwitcher = CreateSwitcher(); private static Dictionary<RuntimeTypeHandle, NodeHandler> CreateSwitcher() { var ret = new Dictionary<RuntimeTypeHandle, NodeHandler>(); ret[typeof(Bob).TypeHandle] = HandleBob; ret[typeof(Jill).TypeHandle] = HandleJill; ret[typeof(Marko).TypeHandle] = HandleMarko; return ret; } void HandleChildNode(ChildNode node) { NodeHandler handler; if (TaskHandleSwitcher.TryGetValue(Type.GetRuntimeType(node), out handler)) { handler(node); } else { //Unexpected type... } } ``` This is similar to what Ted Elliot suggested, but the usage of runtime type handles instead of full type objects avoids the overhead of loading the type object through reflection. Here are some quick timings on my machine: ``` Testing 3 iterations with 5,000,000 data elements (mode=Random) and 5 types Method Time % of optimal If/Else 179.67 100.00 TypeHandleDictionary 321.33 178.85 TypeDictionary 377.67 210.20 Switch 492.67 274.21 Testing 3 iterations with 5,000,000 data elements (mode=Random) and 10 types Method Time % of optimal If/Else 271.33 100.00 TypeHandleDictionary 312.00 114.99 TypeDictionary 374.33 137.96 Switch 490.33 180.71 Testing 3 iterations with 5,000,000 data elements (mode=Random) and 15 types Method Time % of optimal TypeHandleDictionary 312.00 100.00 If/Else 369.00 118.27 TypeDictionary 371.67 119.12 Switch 491.67 157.59 Testing 3 iterations with 5,000,000 data elements (mode=Random) and 20 types Method Time % of optimal TypeHandleDictionary 335.33 100.00 TypeDictionary 373.00 111.23 If/Else 462.67 137.97 Switch 490.33 146.22 Testing 3 iterations with 5,000,000 data elements (mode=Random) and 25 types Method Time % of optimal TypeHandleDictionary 319.33 100.00 TypeDictionary 371.00 116.18 Switch 483.00 151.25 If/Else 562.00 175.99 Testing 3 iterations with 5,000,000 data elements (mode=Random) and 50 types Method Time % of optimal TypeHandleDictionary 319.67 100.00 TypeDictionary 376.67 117.83 Switch 453.33 141.81 If/Else 1,032.67 323.04 ``` On my machine at least, the type handle dictionary approach beats all of the others for anything over 15 different types when the distribution of the types used as input to the method is random. If on the other hand, the input is composed entirely of the type that is checked first in the if/else chain that method is *much* faster: ``` Testing 3 iterations with 5,000,000 data elements (mode=UniformFirst) and 50 types Method Time % of optimal If/Else 39.00 100.00 TypeHandleDictionary 317.33 813.68 TypeDictionary 396.00 1,015.38 Switch 403.00 1,033.33 ``` Conversely, if the input is always the last thing in the if/else chain, it has the opposite effect: ``` Testing 3 iterations with 5,000,000 data elements (mode=UniformLast) and 50 types Method Time % of optimal TypeHandleDictionary 317.67 100.00 Switch 354.33 111.54 TypeDictionary 377.67 118.89 If/Else 1,907.67 600.52 ``` If you can make some assumptions about your input, you might get the best performance from a hybrid approach where you perform if/else checks for the few types that are most common, and then fall back to a dictionary-driven approach if those fail.
If the types you're switching on are primitive .NET types you can use Type.GetTypeCode(Type), but if they're custom types they will all come back as TypeCode.Object. A dictionary with delegates or handler classes might work as well. ``` Dictionary<Type, HandlerDelegate> handlers = new Dictionary<Type, HandlerDelegate>(); handlers[typeof(Bob)] = this.HandleBob; handlers[typeof(Jill)] = this.HandleJill; handlers[typeof(Marko)] = this.HandleMarko; handlers[childNode.GetType()](childNode); /// ... private void HandleBob(Node childNode) { // code to handle Bob } ```
94,305
Lets say I have the option of identifying a code path to take on the basis of a string comparison or else iffing the type: Which is quicker and why? ``` switch(childNode.Name) { case "Bob": break; case "Jill": break; case "Marko": break; } if(childNode is Bob) { } elseif(childNode is Jill) { } else if(childNode is Marko) { } ``` **Update:** The main reason I ask this is because the switch statement is perculiar about what counts as a case. For example it wont allow you to use variables, only constants which get moved to the main assembly. I assumed it had this restriction due to some funky stuff it was doing. If it is only translating to elseifs (as one poster commented) then why are we not allowed variables in case statements? **Caveat:** I am post-optimising. This method is called *many* times in a slow part of the app.
2008/09/18
[ "https://Stackoverflow.com/questions/94305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1143/" ]
Try using enumerations for each object, you can switch on enums quickly and easily.
well it depend on language you need to test yourself to see timing that which one is fast. like in **php** web language `if / else if` is fast compare to `switch` so you need to find it out by running some bench basic code in your desire language. personally i prefer `if / else if` for code reading as switch statements can be nightmare to read where there is big code blocks in each condition as you will have to look for break keywords it each end point manually while with `if / else if` due to the start and end braces its easy to trace code blocks. **php** [![enter image description here](https://i.stack.imgur.com/r9kYB.png)](https://i.stack.imgur.com/r9kYB.png)
94,305
Lets say I have the option of identifying a code path to take on the basis of a string comparison or else iffing the type: Which is quicker and why? ``` switch(childNode.Name) { case "Bob": break; case "Jill": break; case "Marko": break; } if(childNode is Bob) { } elseif(childNode is Jill) { } else if(childNode is Marko) { } ``` **Update:** The main reason I ask this is because the switch statement is perculiar about what counts as a case. For example it wont allow you to use variables, only constants which get moved to the main assembly. I assumed it had this restriction due to some funky stuff it was doing. If it is only translating to elseifs (as one poster commented) then why are we not allowed variables in case statements? **Caveat:** I am post-optimising. This method is called *many* times in a slow part of the app.
2008/09/18
[ "https://Stackoverflow.com/questions/94305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1143/" ]
Greg's profile results are great for the exact scenario he covered, but interestingly, the relative costs of the different methods change dramatically when considering a number of different factors including the number of types being compared, and the relative frequency and any patterns in the underlying data. The simple answer is that nobody can tell you what the performance difference is going to be in your specific scenario, you will need to measure the performance in different ways yourself in your own system to get an accurate answer. The If/Else chain is an effective approach for a small number of type comparisons, or if you can reliably predict which few types are going to make up the majority of the ones that you see. The potential problem with the approach is that as the number of types increases, the number of comparisons that must be executed increases as well. if I execute the following: ```cs int value = 25124; if(value == 0) ... else if (value == 1) ... else if (value == 2) ... ... else if (value == 25124) ... ``` each of the previous if conditions must be evaluated before the correct block is entered. On the other hand ```cs switch(value) { case 0:...break; case 1:...break; case 2:...break; ... case 25124:...break; } ``` will perform one simple jump to the correct bit of code. Where it gets more complicated in your example is that your other method uses a switch on strings rather than integers which gets a little more complicated. At a low level, strings can't be switched on in the same way that integer values can so the C# compiler does some magic to make this work for you. If the switch statement is "small enough" (where the compiler does what it thinks is best automatically) switching on strings generates code that is the same as an if/else chain. ```cs switch(someString) { case "Foo": DoFoo(); break; case "Bar": DoBar(); break; default: DoOther; break; } ``` is the same as: ```cs if(someString == "Foo") { DoFoo(); } else if(someString == "Bar") { DoBar(); } else { DoOther(); } ``` Once the list of items in the dictionary gets "big enough" the compiler will automatically create an internal dictionary that maps from the strings in the switch to an integer index and then a switch based on that index. It looks something like this (Just imagine more entries than I am going to bother to type) A static field is defined in a "hidden" location that is associated with the class containing the switch statement of type `Dictionary<string, int>` and given a mangled name ```cs //Make sure the dictionary is loaded if(theDictionary == null) { //This is simplified for clarity, the actual implementation is more complex // in order to ensure thread safety theDictionary = new Dictionary<string,int>(); theDictionary["Foo"] = 0; theDictionary["Bar"] = 1; } int switchIndex; if(theDictionary.TryGetValue(someString, out switchIndex)) { switch(switchIndex) { case 0: DoFoo(); break; case 1: DoBar(); break; } } else { DoOther(); } ``` In some quick tests that I just ran, the If/Else method is about 3x as fast as the switch for 3 different types (where the types are randomly distributed). At 25 types the switch is faster by a small margin (16%) at 50 types the switch is more than twice as fast. If you are going to be switching on a large number of types, I would suggest a 3rd method: ```cs private delegate void NodeHandler(ChildNode node); static Dictionary<RuntimeTypeHandle, NodeHandler> TypeHandleSwitcher = CreateSwitcher(); private static Dictionary<RuntimeTypeHandle, NodeHandler> CreateSwitcher() { var ret = new Dictionary<RuntimeTypeHandle, NodeHandler>(); ret[typeof(Bob).TypeHandle] = HandleBob; ret[typeof(Jill).TypeHandle] = HandleJill; ret[typeof(Marko).TypeHandle] = HandleMarko; return ret; } void HandleChildNode(ChildNode node) { NodeHandler handler; if (TaskHandleSwitcher.TryGetValue(Type.GetRuntimeType(node), out handler)) { handler(node); } else { //Unexpected type... } } ``` This is similar to what Ted Elliot suggested, but the usage of runtime type handles instead of full type objects avoids the overhead of loading the type object through reflection. Here are some quick timings on my machine: ``` Testing 3 iterations with 5,000,000 data elements (mode=Random) and 5 types Method Time % of optimal If/Else 179.67 100.00 TypeHandleDictionary 321.33 178.85 TypeDictionary 377.67 210.20 Switch 492.67 274.21 Testing 3 iterations with 5,000,000 data elements (mode=Random) and 10 types Method Time % of optimal If/Else 271.33 100.00 TypeHandleDictionary 312.00 114.99 TypeDictionary 374.33 137.96 Switch 490.33 180.71 Testing 3 iterations with 5,000,000 data elements (mode=Random) and 15 types Method Time % of optimal TypeHandleDictionary 312.00 100.00 If/Else 369.00 118.27 TypeDictionary 371.67 119.12 Switch 491.67 157.59 Testing 3 iterations with 5,000,000 data elements (mode=Random) and 20 types Method Time % of optimal TypeHandleDictionary 335.33 100.00 TypeDictionary 373.00 111.23 If/Else 462.67 137.97 Switch 490.33 146.22 Testing 3 iterations with 5,000,000 data elements (mode=Random) and 25 types Method Time % of optimal TypeHandleDictionary 319.33 100.00 TypeDictionary 371.00 116.18 Switch 483.00 151.25 If/Else 562.00 175.99 Testing 3 iterations with 5,000,000 data elements (mode=Random) and 50 types Method Time % of optimal TypeHandleDictionary 319.67 100.00 TypeDictionary 376.67 117.83 Switch 453.33 141.81 If/Else 1,032.67 323.04 ``` On my machine at least, the type handle dictionary approach beats all of the others for anything over 15 different types when the distribution of the types used as input to the method is random. If on the other hand, the input is composed entirely of the type that is checked first in the if/else chain that method is *much* faster: ``` Testing 3 iterations with 5,000,000 data elements (mode=UniformFirst) and 50 types Method Time % of optimal If/Else 39.00 100.00 TypeHandleDictionary 317.33 813.68 TypeDictionary 396.00 1,015.38 Switch 403.00 1,033.33 ``` Conversely, if the input is always the last thing in the if/else chain, it has the opposite effect: ``` Testing 3 iterations with 5,000,000 data elements (mode=UniformLast) and 50 types Method Time % of optimal TypeHandleDictionary 317.67 100.00 Switch 354.33 111.54 TypeDictionary 377.67 118.89 If/Else 1,907.67 600.52 ``` If you can make some assumptions about your input, you might get the best performance from a hybrid approach where you perform if/else checks for the few types that are most common, and then fall back to a dictionary-driven approach if those fail.
A SWITCH construct was originally intended for integer data; it's intent was to use the argument directly as a index into a "dispatch table", a table of pointers. As such, there would be a single test, then launch directly to the relevant code, rather than a series of tests. The difficulty here is that it's use has been generalized to "string" types, which obviously cannot be used as an index, and all advantage of the SWITCH construct is lost. If speed is your intended goal, the problem is NOT your code, but your data structure. If the "name" space is as simple as you show it, better to code it into an integer value (when data is created, for example), and use this integer in the "many times in a slow part of the app".
94,305
Lets say I have the option of identifying a code path to take on the basis of a string comparison or else iffing the type: Which is quicker and why? ``` switch(childNode.Name) { case "Bob": break; case "Jill": break; case "Marko": break; } if(childNode is Bob) { } elseif(childNode is Jill) { } else if(childNode is Marko) { } ``` **Update:** The main reason I ask this is because the switch statement is perculiar about what counts as a case. For example it wont allow you to use variables, only constants which get moved to the main assembly. I assumed it had this restriction due to some funky stuff it was doing. If it is only translating to elseifs (as one poster commented) then why are we not allowed variables in case statements? **Caveat:** I am post-optimising. This method is called *many* times in a slow part of the app.
2008/09/18
[ "https://Stackoverflow.com/questions/94305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1143/" ]
Greg's profile results are great for the exact scenario he covered, but interestingly, the relative costs of the different methods change dramatically when considering a number of different factors including the number of types being compared, and the relative frequency and any patterns in the underlying data. The simple answer is that nobody can tell you what the performance difference is going to be in your specific scenario, you will need to measure the performance in different ways yourself in your own system to get an accurate answer. The If/Else chain is an effective approach for a small number of type comparisons, or if you can reliably predict which few types are going to make up the majority of the ones that you see. The potential problem with the approach is that as the number of types increases, the number of comparisons that must be executed increases as well. if I execute the following: ```cs int value = 25124; if(value == 0) ... else if (value == 1) ... else if (value == 2) ... ... else if (value == 25124) ... ``` each of the previous if conditions must be evaluated before the correct block is entered. On the other hand ```cs switch(value) { case 0:...break; case 1:...break; case 2:...break; ... case 25124:...break; } ``` will perform one simple jump to the correct bit of code. Where it gets more complicated in your example is that your other method uses a switch on strings rather than integers which gets a little more complicated. At a low level, strings can't be switched on in the same way that integer values can so the C# compiler does some magic to make this work for you. If the switch statement is "small enough" (where the compiler does what it thinks is best automatically) switching on strings generates code that is the same as an if/else chain. ```cs switch(someString) { case "Foo": DoFoo(); break; case "Bar": DoBar(); break; default: DoOther; break; } ``` is the same as: ```cs if(someString == "Foo") { DoFoo(); } else if(someString == "Bar") { DoBar(); } else { DoOther(); } ``` Once the list of items in the dictionary gets "big enough" the compiler will automatically create an internal dictionary that maps from the strings in the switch to an integer index and then a switch based on that index. It looks something like this (Just imagine more entries than I am going to bother to type) A static field is defined in a "hidden" location that is associated with the class containing the switch statement of type `Dictionary<string, int>` and given a mangled name ```cs //Make sure the dictionary is loaded if(theDictionary == null) { //This is simplified for clarity, the actual implementation is more complex // in order to ensure thread safety theDictionary = new Dictionary<string,int>(); theDictionary["Foo"] = 0; theDictionary["Bar"] = 1; } int switchIndex; if(theDictionary.TryGetValue(someString, out switchIndex)) { switch(switchIndex) { case 0: DoFoo(); break; case 1: DoBar(); break; } } else { DoOther(); } ``` In some quick tests that I just ran, the If/Else method is about 3x as fast as the switch for 3 different types (where the types are randomly distributed). At 25 types the switch is faster by a small margin (16%) at 50 types the switch is more than twice as fast. If you are going to be switching on a large number of types, I would suggest a 3rd method: ```cs private delegate void NodeHandler(ChildNode node); static Dictionary<RuntimeTypeHandle, NodeHandler> TypeHandleSwitcher = CreateSwitcher(); private static Dictionary<RuntimeTypeHandle, NodeHandler> CreateSwitcher() { var ret = new Dictionary<RuntimeTypeHandle, NodeHandler>(); ret[typeof(Bob).TypeHandle] = HandleBob; ret[typeof(Jill).TypeHandle] = HandleJill; ret[typeof(Marko).TypeHandle] = HandleMarko; return ret; } void HandleChildNode(ChildNode node) { NodeHandler handler; if (TaskHandleSwitcher.TryGetValue(Type.GetRuntimeType(node), out handler)) { handler(node); } else { //Unexpected type... } } ``` This is similar to what Ted Elliot suggested, but the usage of runtime type handles instead of full type objects avoids the overhead of loading the type object through reflection. Here are some quick timings on my machine: ``` Testing 3 iterations with 5,000,000 data elements (mode=Random) and 5 types Method Time % of optimal If/Else 179.67 100.00 TypeHandleDictionary 321.33 178.85 TypeDictionary 377.67 210.20 Switch 492.67 274.21 Testing 3 iterations with 5,000,000 data elements (mode=Random) and 10 types Method Time % of optimal If/Else 271.33 100.00 TypeHandleDictionary 312.00 114.99 TypeDictionary 374.33 137.96 Switch 490.33 180.71 Testing 3 iterations with 5,000,000 data elements (mode=Random) and 15 types Method Time % of optimal TypeHandleDictionary 312.00 100.00 If/Else 369.00 118.27 TypeDictionary 371.67 119.12 Switch 491.67 157.59 Testing 3 iterations with 5,000,000 data elements (mode=Random) and 20 types Method Time % of optimal TypeHandleDictionary 335.33 100.00 TypeDictionary 373.00 111.23 If/Else 462.67 137.97 Switch 490.33 146.22 Testing 3 iterations with 5,000,000 data elements (mode=Random) and 25 types Method Time % of optimal TypeHandleDictionary 319.33 100.00 TypeDictionary 371.00 116.18 Switch 483.00 151.25 If/Else 562.00 175.99 Testing 3 iterations with 5,000,000 data elements (mode=Random) and 50 types Method Time % of optimal TypeHandleDictionary 319.67 100.00 TypeDictionary 376.67 117.83 Switch 453.33 141.81 If/Else 1,032.67 323.04 ``` On my machine at least, the type handle dictionary approach beats all of the others for anything over 15 different types when the distribution of the types used as input to the method is random. If on the other hand, the input is composed entirely of the type that is checked first in the if/else chain that method is *much* faster: ``` Testing 3 iterations with 5,000,000 data elements (mode=UniformFirst) and 50 types Method Time % of optimal If/Else 39.00 100.00 TypeHandleDictionary 317.33 813.68 TypeDictionary 396.00 1,015.38 Switch 403.00 1,033.33 ``` Conversely, if the input is always the last thing in the if/else chain, it has the opposite effect: ``` Testing 3 iterations with 5,000,000 data elements (mode=UniformLast) and 50 types Method Time % of optimal TypeHandleDictionary 317.67 100.00 Switch 354.33 111.54 TypeDictionary 377.67 118.89 If/Else 1,907.67 600.52 ``` If you can make some assumptions about your input, you might get the best performance from a hybrid approach where you perform if/else checks for the few types that are most common, and then fall back to a dictionary-driven approach if those fail.
I think the main performance issue here is, that in the switch block, you compare strings, and that in the if-else block, you check for types... Those two are not the same, and therefore, I'd say you're "comparing potatoes to bananas". I'd start by comparing this: ``` switch(childNode.Name) { case "Bob": break; case "Jill": break; case "Marko": break; } if(childNode.Name == "Bob") {} else if(childNode.Name == "Jill") {} else if(childNode.Name == "Marko") {} ```
94,305
Lets say I have the option of identifying a code path to take on the basis of a string comparison or else iffing the type: Which is quicker and why? ``` switch(childNode.Name) { case "Bob": break; case "Jill": break; case "Marko": break; } if(childNode is Bob) { } elseif(childNode is Jill) { } else if(childNode is Marko) { } ``` **Update:** The main reason I ask this is because the switch statement is perculiar about what counts as a case. For example it wont allow you to use variables, only constants which get moved to the main assembly. I assumed it had this restriction due to some funky stuff it was doing. If it is only translating to elseifs (as one poster commented) then why are we not allowed variables in case statements? **Caveat:** I am post-optimising. This method is called *many* times in a slow part of the app.
2008/09/18
[ "https://Stackoverflow.com/questions/94305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1143/" ]
I just implemented a quick test application and profiled it with ANTS 4. Spec: .Net 3.5 sp1 in 32bit Windows XP, code built in release mode. 3 million tests: * Switch: 1.842 seconds * If: 0.344 seconds. Furthermore, the switch statement results reveal (unsurprisingly) that longer names take longer. 1 million tests * Bob: 0.612 seconds. * Jill: 0.835 seconds. * Marko: 1.093 seconds. I looks like the "If Else" is faster, at least the the scenario I created. ``` class Program { static void Main( string[] args ) { Bob bob = new Bob(); Jill jill = new Jill(); Marko marko = new Marko(); for( int i = 0; i < 1000000; i++ ) { Test( bob ); Test( jill ); Test( marko ); } } public static void Test( ChildNode childNode ) { TestSwitch( childNode ); TestIfElse( childNode ); } private static void TestIfElse( ChildNode childNode ) { if( childNode is Bob ){} else if( childNode is Jill ){} else if( childNode is Marko ){} } private static void TestSwitch( ChildNode childNode ) { switch( childNode.Name ) { case "Bob": break; case "Jill": break; case "Marko": break; } } } class ChildNode { public string Name { get; set; } } class Bob : ChildNode { public Bob(){ this.Name = "Bob"; }} class Jill : ChildNode{public Jill(){this.Name = "Jill";}} class Marko : ChildNode{public Marko(){this.Name = "Marko";}} ```
Try using enumerations for each object, you can switch on enums quickly and easily.
94,305
Lets say I have the option of identifying a code path to take on the basis of a string comparison or else iffing the type: Which is quicker and why? ``` switch(childNode.Name) { case "Bob": break; case "Jill": break; case "Marko": break; } if(childNode is Bob) { } elseif(childNode is Jill) { } else if(childNode is Marko) { } ``` **Update:** The main reason I ask this is because the switch statement is perculiar about what counts as a case. For example it wont allow you to use variables, only constants which get moved to the main assembly. I assumed it had this restriction due to some funky stuff it was doing. If it is only translating to elseifs (as one poster commented) then why are we not allowed variables in case statements? **Caveat:** I am post-optimising. This method is called *many* times in a slow part of the app.
2008/09/18
[ "https://Stackoverflow.com/questions/94305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1143/" ]
I think the main performance issue here is, that in the switch block, you compare strings, and that in the if-else block, you check for types... Those two are not the same, and therefore, I'd say you're "comparing potatoes to bananas". I'd start by comparing this: ``` switch(childNode.Name) { case "Bob": break; case "Jill": break; case "Marko": break; } if(childNode.Name == "Bob") {} else if(childNode.Name == "Jill") {} else if(childNode.Name == "Marko") {} ```
Surely the switch on String would compile down to a String comparison (one per case) which is slower than a type comparison (and far slower than the typical integer compare that is used for switch/case)?
124,029
My main character lives in a world of magic. Nothing seems off about the people around them, but some of them are Philosophical Zombies, automatons without any inner life, for reasons important to the plot. What non-contrived ways could the character discover this fact without any doubt? Feel free to conjure any magic you want. It's more of a sequence of events that lead to the discovery I need.
2018/09/03
[ "https://worldbuilding.stackexchange.com/questions/124029", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/53296/" ]
The whole philosophical point of zombies is that there is no way to distinguish them from outside. Which obviously means that you need to distinguish them from inside. You need some kind of magic that lets you get inside the minds of other people—whether it's telepathy, or possession, or whatever. At which point it becomes trivial: you get inside their mind, and there is no "inside" there. It's hard to imagine how to stretch that out into "a sequence of events", short of by developing that magic over time. For example: * At first, you can just borrow the sense perceptions of other people (and animals?), and the zombies are the same as everyone else. * Then you learn to feel the effects of… not emotions, but the hormonal and other physiological changes that go with them, and still the zombies are the same. * Then you learn to read their memories, and even use their minds to figure things out for you, and still the zombies are the same. * Then you learn to access their thoughts, and… some people are just different in some way you can't explain. * Then you learn to access their second-order thoughts, their self-reflective stream of consciousness, and now you get it: the zombies don't have one. --- If you can also control people, the way you control regular people and zombies will be very different. With regular people, you essentially insert yourself into the arguments happening inside their conscious mind all the time and sway the "vote" the way you want, and the decisions and first-order thoughts and actions all follow from there. But this is more complicated than it sounds, because people are making decisions without conscious deciding all the time, and you have to sway them indirectly. But with zombies, you just directly produce an order and it's followed. At first, you'd think this makes things easier—but in fact, because the orders have to be at a much lower level than the kind of things we determine consciously, it's actually a lot more effort to control a zombie in any useful way. Maybe this leads you to realize that whatever's using the zombies must be either a pack of people or a superhuman force (a computer-god or something?), because otherwise they'd be useless. --- If you've read Julian Jaynes and find his Bicameral Mind hypothesis interesting, you can put a twist on this—which doesn't really fit the use of zombies in philosophy, but might be more interesting for your story anyway. Conscious people, whose left and right hemispheres are integrated, are just like the above, and you have to get involved in the discussions inside their brain to do anything useful. Zombies are people whose hemispheres are independent. Their right brain issues verbal commands; their left brain follows them, using its intelligence to do so as well as possible, but unable to even think of disobeying. Zombies believe these commands come from the gods. This makes them different from non-zombies, and philosophical zombies, because they actually describe their motivation completely differently. Why did you build the house there? Marduk told me to build the house there and so I did. Anyway, this means you can read and control the left brain of a Jaynes-zombie quite easily, putting yourself in the place of their internalized gods. But it also means that if you want to understand, or control, their deeper motivations, you have to talk to the right brain, which is like a cacophony of gods fighting over who gets to give the next command to the left brain. These gods are, of course, not superhuman, but in fact less than human, but that doesn't make them much less interesting than squabbling Olympians. And you've got a whole pantheon of them for each zombie—similar to, but independent of, each other.
Challenge the P-Zombies to any kind of activity that involves self-reflection or (mental) self-improvement. Free will means more than just that we can decide to do what we want; it also means we can decide *not* to do what we want (I can decide *not* to have that piece of cake, despite the fact that I want it) and moreover, I can (with effort) decide not to *want* what I want. We can in fact train our mental virtues -- self control, patience, courage, etc. -- the same way we train muscles, heart, and lungs. I would suggest that philosophical zombies would be incapable of self-reflection. They could tell you why they're doing what they're doing -- "I did X because I want X. I want X because I'm a Y kind of person and I value Z" because they're sort of programmed with this motivation, and may be programmed to give that explanation for it. But the zombies wouldn't be able to change their motivations. If you asked them what they like or dislike about their motivations (or personalities) I think they'd be dumbfounded by the question, incapable of reflecting on an interior life that doesn't really exist. Your main character might discover/realize this while attending a meeting of a self-help group like AA, or perhaps even by hearing how others pray. If your main character is a priest, he may notice that p-zombies confess their sins in a different way than normal humans.
8,246,717
I am invoking VSDBCMD.EXE in my build process template, there is a custom setvar parameter that requires a reference to the current source directory, passing this path has become an unexpected challenge. I've tried using relative paths and `$(SourceDirectory)` to no avail (it remains as the literal string `"$(SourceDirectory)"` when I see the debug output), the parameter needs an absolute path. Is there any way to get the absolute path for the current source directory when the script runs?
2011/11/23
[ "https://Stackoverflow.com/questions/8246717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/632722/" ]
In the DefaultTemplate build workflow there is a variable called SourcesDirectory that contains the absolute path. If you pass it to an InvokeProcess you just type the variable name in the activity property, no $() around it.
It might be worth checking out [this](http://www.codewrecks.com/blog/index.php/2010/01/04/deploy-a-database-project-with-tfs-build-2010/) resource, where author makes use of `ConvertWorkspaceItem` within his build in order to pass in a string the disk location of a know target in source control
17,187,392
I am working on an app where i am using custom gridview with images & checkboxes. Displaying of gridview with images & checkboxes is working good. But here my issue is after make one checkbox checked if i scroll the gridview another checkbox is checked & again if i scroll down again it is displaying. Here checkbox checked state was maintaing. My Adapterclass Code is.. MyGrid.java ``` public class ImageAdapter extends BaseAdapter { private LayoutInflater mInflater; public ImageAdapter() { mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public int getCount() { return count; } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { final ViewHolder holder; if (convertView == null) { holder = new ViewHolder(); convertView = mInflater.inflate(R.layout.galleryitem, null); holder.imageview = (ImageView) convertView.findViewById(R.id.thumbImage); holder.checkbox = (CheckBox) convertView.findViewById(R.id.itemCheckBox); holder.textview = (TextView) convertView.findViewById(R.id.saved_image_name); Drawable background = holder.textview.getBackground(); background.setAlpha(150); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.checkbox.setId(position); holder.imageview.setId(position); holder.textview.setId(position); holder.checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton arg0, boolean arg1) { // TODO Auto-generated method stub CheckBox cb = (CheckBox) holder.checkbox; int id = cb.getId(); if (thumbnailsselection[id]) { cb.setChecked(false); thumbnailsselection[id] = false; selected_images.remove(String.valueOf(id)); } else { cb.setChecked(true); thumbnailsselection[id] = true; if (selected_images.contains(String.valueOf(id))) { }else{ selected_images.add(String.valueOf(id)); } } } }); holder.imageview.setOnClickListener(new OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub int id = v.getId(); Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.setDataAndType(Uri.parse("file://" + arrPath[id]), "image/*"); startActivity(intent); } }); if (arrPath[position] == null || arrPath[position].equals(null)) { }else{ image_name=extractString(arrPath[position]); String[] splited_name = image_name.split("\\."); for (int i = 0; i < selected_images.size(); i++) { if (selected_images.get(i).equals(String.valueOf(position)) || selected_images.get(i) == String.valueOf(position)) { holder.checkbox.setChecked(true); } } holder.textview.setText(splited_name[0]); holder.imageview.setImageBitmap(thumbnails[position]); holder.checkbox.setChecked(thumbnailsselection[position]); holder.id = position; holder.imageview.setScaleType(ImageView.ScaleType.FIT_XY); } return convertView; } } class ViewHolder { ImageView imageview; CheckBox checkbox,checkbox1; TextView textview; int id; } ``` Can anyone help me how to maintain the persistence state of checkbox (selected checkbox).
2013/06/19
[ "https://Stackoverflow.com/questions/17187392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2384424/" ]
<https://groups.google.com/forum/?fromgroups#!topic/android-developers/No0LrgJ6q2M> Drawing from romain guy's solution of listview in the above link. Your Custom Adapter must implement `CompoundButton.OnCheckedChangeListener` and use a `SparseBooleanArray` Then ``` cb.setChecked(mCheckStates.get(position, false)); cb.setOnCheckedChangeListener(this); ``` Then ``` public boolean isChecked(int position) { return mCheckStates.get(position, false); } public void setChecked(int position, boolean isChecked) { mCheckStates.put(position, isChecked); } public void toggle(int position) { setChecked(position, !isChecked(position)); } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { mCheckStates.put((Integer) buttonView.getTag(), isChecked); } ``` Example ``` public class MainActivity extends Activity implements AdapterView.OnItemClickListener { int count; private CheckBoxAdapter mCheckBoxAdapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final GridView gridView = (GridView) findViewById(R.id.lv); gridView.setTextFilterEnabled(true); gridView.setOnItemClickListener(this); mCheckBoxAdapter = new CheckBoxAdapter(this); gridView.setAdapter(mCheckBoxAdapter); } public void onItemClick(AdapterView parent, View view, int position, long id) { mCheckBoxAdapter.toggle(position); } class CheckBoxAdapter extends ArrayAdapter implements CompoundButton.OnCheckedChangeListener { private SparseBooleanArray mCheckStates; LayoutInflater mInflater; ImageView imageview1,imageview; CheckBox cb; CheckBoxAdapter(MainActivity context) { super(context,0); mCheckStates = new SparseBooleanArray(10); mInflater = (LayoutInflater)MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { // TODO Auto-generated method stub return 10; } @Override public Object getItem(int position) { // TODO Auto-generated method stub return position; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return 0; } @Override public View getView(final int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub View vi=convertView; if(convertView==null) vi = mInflater.inflate(R.layout.checkbox, null); imageview= (ImageView) vi.findViewById(R.id.textView1); cb = (CheckBox) vi.findViewById(R.id.checkBox1); cb.setTag(position); cb.setChecked(mCheckStates.get(position, false)); cb.setOnCheckedChangeListener(this); return vi; } public boolean isChecked(int position) { return mCheckStates.get(position, false); } public void setChecked(int position, boolean isChecked) { mCheckStates.put(position, isChecked); } public void toggle(int position) { setChecked(position, !isChecked(position)); } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TODO Auto-generated method stub mCheckStates.put((Integer) buttonView.getTag(), isChecked); } } } ``` activity\_main.xml ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <GridView android:id="@+id/lv" android:layout_width="wrap_content" android:numColumns="2" android:layout_height="wrap_content" /> </RelativeLayout> ``` checkbox.xml ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <ImageView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginLeft="15dp" android:layout_marginTop="34dp" android:src="@drawable/ic_launcher"/> <CheckBox android:id="@+id/checkBox1" android:focusable="false" android:focusableInTouchMode="false" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_below="@+id/textView1" android:layout_marginRight="22dp" android:layout_marginTop="23dp" /> </RelativeLayout> ``` Similar to the one answered here. Instead of listview use gridview and instead of textview use imageview. [How to change the text of a CheckBox in listview?](https://stackoverflow.com/questions/17168814/how-to-change-the-text-of-a-checkbox-in-listview/17169411#17169411)
The cells are reused. In `getView()` where you are setting the id's, you should also set the state of the checkbox `holder.checkbox..setChecked(thumbnailsselection[position]);`. Also it isn't recommended to change the id's, if you want to save the position use `setTag()` and put the position there, the views already have id's in the layout.
30,578,975
Hi there I'm trying to play around with my code and can't really seem to figure out how to make part of my code into a grayscale. This is my code: ``` def grayScale(picture): xstop=getWidth(picture)/2 ystop=getHeight(picture)/2 for x in range(0,xstop): for y in range(0,ystop): oldpixel= getPixel(picture,x,y) colour=getColor(oldpixel) newColor=(getRed(oldpixel),getGreen(oldpixel),getBlue(oldpixel))/3 setColor(picture,(newColor,newColor,newColor)) repaint(picture) nP=makePicture(pickAFile()) show(nP) ``` Any help is appreciated, really trying hard to understand this. Thanks again for your help! Error shown: > > grayScale(nP) > The error was: 'tuple' and 'int' > > > Inappropriate argument type. > An attempt was made to call a function with a parameter of an invalid type. This means that you did something such as trying to pass a string to a method that is expecting an integer. > Please check line 8 of /Users/enochphan/Desktop/test > > >
2015/06/01
[ "https://Stackoverflow.com/questions/30578975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4937036/" ]
There are a few things giving you trouble here: * Indenting of your code after the y for loop (I'm guessing you want all of the height to traversed). * The new colour is just the average of your current pixels, so you need to use addition to add them before dividing by three. * setColor() takes a pixel and a color object. The pixel you want to change is oldpixel, and the color object is created using makeColor(). Here is code with all the fixes implemented: ``` def grayScale(picture): xstop=getWidth(picture)/2 ystop=getHeight(picture)/2 for x in range(0,xstop): for y in range(0,ystop): oldpixel= getPixel(picture,x,y) colour=getColor(oldpixel) newColor = (getRed(oldpixel)+getGreen(oldpixel)+getBlue(oldpixel))/3 setColor(oldpixel,makeColor(newColor,newColor,newColor)) repaint(picture) ```
**I did this instead:** ``` def greyTone(): #pict:Picture pict=makePicture(pickAFile()) for p in getPixels(pict): intensity=(getRed(p)+getGreen(p)+getBlue(p))*0.1 greyTone=makeColor(intensity+intensity+intensity) setColor(p,greyTone) show(pict) ``` My professor used the r+g+b/3 variant but when I ran the code the picture was really bright, so I found this variation and it works really nice, I hope this helps :)
718,394
Duplicate of [Asp.Net Button Event on refresh fires again??? GUID?](https://stackoverflow.com/questions/716187/asp-net-button-event-on-refresh-fires-again-guid/716252#716252) hello, ive a website and when a user click a button and the page postback, if the user refresh the Page or hit F5 the button method is called again. any one know some method to prevent page refresh with out redirect the page to the same page again ? something like if (page.isRefresh) or something... or if exist any javascript solution is better. this seen to works.... but when i refresh it does not postback but show the before value in the textbox <http://www.dotnetspider.com/resources/4040-IsPageRefresh-ASP-NET.aspx> ``` private Boolean IsPageRefresh = false; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { ViewState["postids"] = System.Guid.NewGuid().ToString(); Session["postid"] = ViewState["postids"].ToString(); TextBox1.Text = "Hi"; } else { if (ViewState["postids"].ToString() != Session["postid"].ToString()) { IsPageRefresh = true; } Session["postid"] = System.Guid.NewGuid().ToString(); ViewState["postids"] = Session["postid"]; } } protected void Button1_Click(object sender, EventArgs e) { if (!IsPageRefresh) // check that page is not refreshed by browser. { TextBox2.Text = TextBox1.Text + "@"; } } ```
2009/04/05
[ "https://Stackoverflow.com/questions/718394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/87221/" ]
Thanks for comments and sorry for my mistake, I found this code in: <http://www.codeproject.com/KB/aspnet/Detecting_Refresh.aspx> And this time tested ;) ``` private bool _refreshState; private bool _isRefresh; protected override void LoadViewState(object savedState) { object[] AllStates = (object[])savedState; base.LoadViewState(AllStates[0]); _refreshState = bool.Parse(AllStates[1].ToString()); _isRefresh = _refreshState == bool.Parse(Session["__ISREFRESH"].ToString()); } protected override object SaveViewState() { Session["__ISREFRESH"] = _refreshState; object[] AllStates = new object[2]; AllStates[0] = base.SaveViewState(); AllStates[1] = !(_refreshState); return AllStates; } protected void btn_Click(object sender, EventArgs e) { if (!_isRefresh) Response.Write(DateTime.Now.Millisecond.ToString()); } ```
You can test for the Page.IsPostBack property to see if the page is responding to an initial request or if it's handling a PostBack such as your button click event. Here's a bit more information: [w3schools on IsPostBack](http://www.w3schools.com/aspnet/aspnet_events.asp) Unfortunately that's not going to solve your problem since IsPostBack will be true when the user clicks the button as well as when they refresh the page after the button action has taken place. If you're doing a task like performing CRUD on some data, you can Response.Redirect the user back to the same page when you're done processing and get around this problem. It has the side benefit of reloading your content (assuming you added a record to the DB it would now show in the page...) and prevents the refresh problem behavior. The only caveat is they still resubmit the form by going back in their history. Postbacks were a bad implementation choice for the Asp.net and generally are what ruin the Webforms platform for me.
718,394
Duplicate of [Asp.Net Button Event on refresh fires again??? GUID?](https://stackoverflow.com/questions/716187/asp-net-button-event-on-refresh-fires-again-guid/716252#716252) hello, ive a website and when a user click a button and the page postback, if the user refresh the Page or hit F5 the button method is called again. any one know some method to prevent page refresh with out redirect the page to the same page again ? something like if (page.isRefresh) or something... or if exist any javascript solution is better. this seen to works.... but when i refresh it does not postback but show the before value in the textbox <http://www.dotnetspider.com/resources/4040-IsPageRefresh-ASP-NET.aspx> ``` private Boolean IsPageRefresh = false; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { ViewState["postids"] = System.Guid.NewGuid().ToString(); Session["postid"] = ViewState["postids"].ToString(); TextBox1.Text = "Hi"; } else { if (ViewState["postids"].ToString() != Session["postid"].ToString()) { IsPageRefresh = true; } Session["postid"] = System.Guid.NewGuid().ToString(); ViewState["postids"] = Session["postid"]; } } protected void Button1_Click(object sender, EventArgs e) { if (!IsPageRefresh) // check that page is not refreshed by browser. { TextBox2.Text = TextBox1.Text + "@"; } } ```
2009/04/05
[ "https://Stackoverflow.com/questions/718394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/87221/" ]
You can test for the Page.IsPostBack property to see if the page is responding to an initial request or if it's handling a PostBack such as your button click event. Here's a bit more information: [w3schools on IsPostBack](http://www.w3schools.com/aspnet/aspnet_events.asp) Unfortunately that's not going to solve your problem since IsPostBack will be true when the user clicks the button as well as when they refresh the page after the button action has taken place. If you're doing a task like performing CRUD on some data, you can Response.Redirect the user back to the same page when you're done processing and get around this problem. It has the side benefit of reloading your content (assuming you added a record to the DB it would now show in the page...) and prevents the refresh problem behavior. The only caveat is they still resubmit the form by going back in their history. Postbacks were a bad implementation choice for the Asp.net and generally are what ruin the Webforms platform for me.
This doesn't solve the problem. First of all, storing a token in the view state is not a good idea, since it can be disabled. Use control state instead. Although, a HttpModule is a better solution. All in all, this will not work anyway. If you open another tab/window the session will be invalid for the previous tab/window. Therefore braking it. You must somehow store a unique value each time a page is first loaded. Use that to determine where the request came from and then check the "refresh ticket". As you may see, the object for one user might get pretty big depending on the amount of requests made, where and how long you store this information. I haven't seen any solution to this I'm afraid, as it is pretty complex.
718,394
Duplicate of [Asp.Net Button Event on refresh fires again??? GUID?](https://stackoverflow.com/questions/716187/asp-net-button-event-on-refresh-fires-again-guid/716252#716252) hello, ive a website and when a user click a button and the page postback, if the user refresh the Page or hit F5 the button method is called again. any one know some method to prevent page refresh with out redirect the page to the same page again ? something like if (page.isRefresh) or something... or if exist any javascript solution is better. this seen to works.... but when i refresh it does not postback but show the before value in the textbox <http://www.dotnetspider.com/resources/4040-IsPageRefresh-ASP-NET.aspx> ``` private Boolean IsPageRefresh = false; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { ViewState["postids"] = System.Guid.NewGuid().ToString(); Session["postid"] = ViewState["postids"].ToString(); TextBox1.Text = "Hi"; } else { if (ViewState["postids"].ToString() != Session["postid"].ToString()) { IsPageRefresh = true; } Session["postid"] = System.Guid.NewGuid().ToString(); ViewState["postids"] = Session["postid"]; } } protected void Button1_Click(object sender, EventArgs e) { if (!IsPageRefresh) // check that page is not refreshed by browser. { TextBox2.Text = TextBox1.Text + "@"; } } ```
2009/04/05
[ "https://Stackoverflow.com/questions/718394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/87221/" ]
You can test for the Page.IsPostBack property to see if the page is responding to an initial request or if it's handling a PostBack such as your button click event. Here's a bit more information: [w3schools on IsPostBack](http://www.w3schools.com/aspnet/aspnet_events.asp) Unfortunately that's not going to solve your problem since IsPostBack will be true when the user clicks the button as well as when they refresh the page after the button action has taken place. If you're doing a task like performing CRUD on some data, you can Response.Redirect the user back to the same page when you're done processing and get around this problem. It has the side benefit of reloading your content (assuming you added a record to the DB it would now show in the page...) and prevents the refresh problem behavior. The only caveat is they still resubmit the form by going back in their history. Postbacks were a bad implementation choice for the Asp.net and generally are what ruin the Webforms platform for me.
``` bool IsPageRefresh ; if (Page.IsPostBack) { if (ViewState["postid"].ToString() != Session["postid"].ToString()) IsPageRefresh = true; } Session["postid"] = System.Guid.NewGuid().ToString(); ViewState["postid"] = Session["postid"]; ```
718,394
Duplicate of [Asp.Net Button Event on refresh fires again??? GUID?](https://stackoverflow.com/questions/716187/asp-net-button-event-on-refresh-fires-again-guid/716252#716252) hello, ive a website and when a user click a button and the page postback, if the user refresh the Page or hit F5 the button method is called again. any one know some method to prevent page refresh with out redirect the page to the same page again ? something like if (page.isRefresh) or something... or if exist any javascript solution is better. this seen to works.... but when i refresh it does not postback but show the before value in the textbox <http://www.dotnetspider.com/resources/4040-IsPageRefresh-ASP-NET.aspx> ``` private Boolean IsPageRefresh = false; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { ViewState["postids"] = System.Guid.NewGuid().ToString(); Session["postid"] = ViewState["postids"].ToString(); TextBox1.Text = "Hi"; } else { if (ViewState["postids"].ToString() != Session["postid"].ToString()) { IsPageRefresh = true; } Session["postid"] = System.Guid.NewGuid().ToString(); ViewState["postids"] = Session["postid"]; } } protected void Button1_Click(object sender, EventArgs e) { if (!IsPageRefresh) // check that page is not refreshed by browser. { TextBox2.Text = TextBox1.Text + "@"; } } ```
2009/04/05
[ "https://Stackoverflow.com/questions/718394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/87221/" ]
You can test for the Page.IsPostBack property to see if the page is responding to an initial request or if it's handling a PostBack such as your button click event. Here's a bit more information: [w3schools on IsPostBack](http://www.w3schools.com/aspnet/aspnet_events.asp) Unfortunately that's not going to solve your problem since IsPostBack will be true when the user clicks the button as well as when they refresh the page after the button action has taken place. If you're doing a task like performing CRUD on some data, you can Response.Redirect the user back to the same page when you're done processing and get around this problem. It has the side benefit of reloading your content (assuming you added a record to the DB it would now show in the page...) and prevents the refresh problem behavior. The only caveat is they still resubmit the form by going back in their history. Postbacks were a bad implementation choice for the Asp.net and generally are what ruin the Webforms platform for me.
I tried many ways and I ended up looking for the form data sent when the postback / refresh is triggered... I found that there is a Key for any VIEWSTATE created and you can just compare those Keys like... I put that on my custom basepage to reuse it like an Property > > > ``` > public bool IsPageRefresh = false; > protected void Page_Init(object sender, EventArgs e) > { > if (IsPostBack) > { > var rForm = Request.Form; > var vw = rForm["__EVENTVALIDATION"].ToString(); > var svw = Session["__EVENTVALIDATION"] ?? ""; > if (vw.Equals(svw)) IsPageRefresh = true; > Session["__EVENTVALIDATION"] = vw; > } > } > > ``` > >
718,394
Duplicate of [Asp.Net Button Event on refresh fires again??? GUID?](https://stackoverflow.com/questions/716187/asp-net-button-event-on-refresh-fires-again-guid/716252#716252) hello, ive a website and when a user click a button and the page postback, if the user refresh the Page or hit F5 the button method is called again. any one know some method to prevent page refresh with out redirect the page to the same page again ? something like if (page.isRefresh) or something... or if exist any javascript solution is better. this seen to works.... but when i refresh it does not postback but show the before value in the textbox <http://www.dotnetspider.com/resources/4040-IsPageRefresh-ASP-NET.aspx> ``` private Boolean IsPageRefresh = false; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { ViewState["postids"] = System.Guid.NewGuid().ToString(); Session["postid"] = ViewState["postids"].ToString(); TextBox1.Text = "Hi"; } else { if (ViewState["postids"].ToString() != Session["postid"].ToString()) { IsPageRefresh = true; } Session["postid"] = System.Guid.NewGuid().ToString(); ViewState["postids"] = Session["postid"]; } } protected void Button1_Click(object sender, EventArgs e) { if (!IsPageRefresh) // check that page is not refreshed by browser. { TextBox2.Text = TextBox1.Text + "@"; } } ```
2009/04/05
[ "https://Stackoverflow.com/questions/718394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/87221/" ]
Thanks for comments and sorry for my mistake, I found this code in: <http://www.codeproject.com/KB/aspnet/Detecting_Refresh.aspx> And this time tested ;) ``` private bool _refreshState; private bool _isRefresh; protected override void LoadViewState(object savedState) { object[] AllStates = (object[])savedState; base.LoadViewState(AllStates[0]); _refreshState = bool.Parse(AllStates[1].ToString()); _isRefresh = _refreshState == bool.Parse(Session["__ISREFRESH"].ToString()); } protected override object SaveViewState() { Session["__ISREFRESH"] = _refreshState; object[] AllStates = new object[2]; AllStates[0] = base.SaveViewState(); AllStates[1] = !(_refreshState); return AllStates; } protected void btn_Click(object sender, EventArgs e) { if (!_isRefresh) Response.Write(DateTime.Now.Millisecond.ToString()); } ```
This doesn't solve the problem. First of all, storing a token in the view state is not a good idea, since it can be disabled. Use control state instead. Although, a HttpModule is a better solution. All in all, this will not work anyway. If you open another tab/window the session will be invalid for the previous tab/window. Therefore braking it. You must somehow store a unique value each time a page is first loaded. Use that to determine where the request came from and then check the "refresh ticket". As you may see, the object for one user might get pretty big depending on the amount of requests made, where and how long you store this information. I haven't seen any solution to this I'm afraid, as it is pretty complex.
718,394
Duplicate of [Asp.Net Button Event on refresh fires again??? GUID?](https://stackoverflow.com/questions/716187/asp-net-button-event-on-refresh-fires-again-guid/716252#716252) hello, ive a website and when a user click a button and the page postback, if the user refresh the Page or hit F5 the button method is called again. any one know some method to prevent page refresh with out redirect the page to the same page again ? something like if (page.isRefresh) or something... or if exist any javascript solution is better. this seen to works.... but when i refresh it does not postback but show the before value in the textbox <http://www.dotnetspider.com/resources/4040-IsPageRefresh-ASP-NET.aspx> ``` private Boolean IsPageRefresh = false; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { ViewState["postids"] = System.Guid.NewGuid().ToString(); Session["postid"] = ViewState["postids"].ToString(); TextBox1.Text = "Hi"; } else { if (ViewState["postids"].ToString() != Session["postid"].ToString()) { IsPageRefresh = true; } Session["postid"] = System.Guid.NewGuid().ToString(); ViewState["postids"] = Session["postid"]; } } protected void Button1_Click(object sender, EventArgs e) { if (!IsPageRefresh) // check that page is not refreshed by browser. { TextBox2.Text = TextBox1.Text + "@"; } } ```
2009/04/05
[ "https://Stackoverflow.com/questions/718394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/87221/" ]
Thanks for comments and sorry for my mistake, I found this code in: <http://www.codeproject.com/KB/aspnet/Detecting_Refresh.aspx> And this time tested ;) ``` private bool _refreshState; private bool _isRefresh; protected override void LoadViewState(object savedState) { object[] AllStates = (object[])savedState; base.LoadViewState(AllStates[0]); _refreshState = bool.Parse(AllStates[1].ToString()); _isRefresh = _refreshState == bool.Parse(Session["__ISREFRESH"].ToString()); } protected override object SaveViewState() { Session["__ISREFRESH"] = _refreshState; object[] AllStates = new object[2]; AllStates[0] = base.SaveViewState(); AllStates[1] = !(_refreshState); return AllStates; } protected void btn_Click(object sender, EventArgs e) { if (!_isRefresh) Response.Write(DateTime.Now.Millisecond.ToString()); } ```
``` bool IsPageRefresh ; if (Page.IsPostBack) { if (ViewState["postid"].ToString() != Session["postid"].ToString()) IsPageRefresh = true; } Session["postid"] = System.Guid.NewGuid().ToString(); ViewState["postid"] = Session["postid"]; ```
718,394
Duplicate of [Asp.Net Button Event on refresh fires again??? GUID?](https://stackoverflow.com/questions/716187/asp-net-button-event-on-refresh-fires-again-guid/716252#716252) hello, ive a website and when a user click a button and the page postback, if the user refresh the Page or hit F5 the button method is called again. any one know some method to prevent page refresh with out redirect the page to the same page again ? something like if (page.isRefresh) or something... or if exist any javascript solution is better. this seen to works.... but when i refresh it does not postback but show the before value in the textbox <http://www.dotnetspider.com/resources/4040-IsPageRefresh-ASP-NET.aspx> ``` private Boolean IsPageRefresh = false; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { ViewState["postids"] = System.Guid.NewGuid().ToString(); Session["postid"] = ViewState["postids"].ToString(); TextBox1.Text = "Hi"; } else { if (ViewState["postids"].ToString() != Session["postid"].ToString()) { IsPageRefresh = true; } Session["postid"] = System.Guid.NewGuid().ToString(); ViewState["postids"] = Session["postid"]; } } protected void Button1_Click(object sender, EventArgs e) { if (!IsPageRefresh) // check that page is not refreshed by browser. { TextBox2.Text = TextBox1.Text + "@"; } } ```
2009/04/05
[ "https://Stackoverflow.com/questions/718394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/87221/" ]
Thanks for comments and sorry for my mistake, I found this code in: <http://www.codeproject.com/KB/aspnet/Detecting_Refresh.aspx> And this time tested ;) ``` private bool _refreshState; private bool _isRefresh; protected override void LoadViewState(object savedState) { object[] AllStates = (object[])savedState; base.LoadViewState(AllStates[0]); _refreshState = bool.Parse(AllStates[1].ToString()); _isRefresh = _refreshState == bool.Parse(Session["__ISREFRESH"].ToString()); } protected override object SaveViewState() { Session["__ISREFRESH"] = _refreshState; object[] AllStates = new object[2]; AllStates[0] = base.SaveViewState(); AllStates[1] = !(_refreshState); return AllStates; } protected void btn_Click(object sender, EventArgs e) { if (!_isRefresh) Response.Write(DateTime.Now.Millisecond.ToString()); } ```
I tried many ways and I ended up looking for the form data sent when the postback / refresh is triggered... I found that there is a Key for any VIEWSTATE created and you can just compare those Keys like... I put that on my custom basepage to reuse it like an Property > > > ``` > public bool IsPageRefresh = false; > protected void Page_Init(object sender, EventArgs e) > { > if (IsPostBack) > { > var rForm = Request.Form; > var vw = rForm["__EVENTVALIDATION"].ToString(); > var svw = Session["__EVENTVALIDATION"] ?? ""; > if (vw.Equals(svw)) IsPageRefresh = true; > Session["__EVENTVALIDATION"] = vw; > } > } > > ``` > >
61,820,329
I have a data-frame that has text in the first column named 'original\_column'. I have successfully been able to pick specific words out of the text column 'original\_column' with a list and have them appended to another column and deleted from the original column with the following code: ``` list1 = {’text’ , ‘and’ , ‘example’} finder = lambda x: next(iter([y for y in x.split() if y in list1]), None) df['list1'] = df.original_column.apply(finder) df['original column']=df['original column'].replace(regex=r'(?i)'+ df['list1'],value="") ``` I would now like to build on this code by being able to delete ONLY THE FIRST instance of the the specific words in the list from the 'original\_column' after appending the listed word to a new column. The data-frame currently looks like this: ``` | original column | __________________________ | text text word | -------------------------- | and other and | ``` My current code outputs this: ``` | original column | list1 ______________________________ | word | text ------------------------------ | other | and ``` My desired to output this: ``` | original column | list1 _______________________________ | text word | text ------------------------------- | other and | and ```
2020/05/15
[ "https://Stackoverflow.com/questions/61820329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13517743/" ]
Let us do `replace` ``` df['original column']=df['original column'].replace(regex=r'(?i)'+ df['list1'],value="") df Out[101]: original column list1 0 text text word 1 text text and ```
Assuming the given dataframe as: ``` df = pd.DataFrame({"original_column": ["text text word", "text and text"]}) ``` Use: ``` import re pattern = '|'.join(f"\s*{item}\s*" for item in list1) regex = re.compile(pattern) def extract_words(s): s['list1'] = ' '.join(map(str.strip, regex.findall(s['original_column']))) s['original_column'] = regex.sub(' ', s['original_column']).strip() return s df = df.apply(extract_words, axis=1) print(df) ``` This results the dataframe `df` as: ``` original_column list1 0 text text word 1 text text and ```
15,039,905
``` alias cgrep='current_dir_grep' function current_dir_grep_exact { grep -w $1 . } alias cgrepe='current_dir_grep_exact' ``` `grep -w 'label for' .` works but doing `cgrepe 'label for'` only searches for the occurrences of `label` while I would like to find the occurences `label for` in the current directory.
2013/02/23
[ "https://Stackoverflow.com/questions/15039905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1305724/" ]
Put the argument in quotes: ``` grep -w "$1" . ```
In `bash(1)`, aliases *do not take arguments*. It sometimes looks like they do, but they don't. Use a function.
249,493
Can we construct a function **Iceberg**, which maps a given expression X to Iceberg[X] **satisfying 1. and 2. and 3.** ? **1**. From Iceberg[X], it is not possible to inspect/extract a part of X *with usual method*. It would be better if there is no part of Iceberg[X]. Applying Iceberg to X is like putting X into an iceberg. ex) It is not difficult to extract 3rd part of {101,102,103,104,105}, from Hold[{101,102,103,104,105}]. ``` In[1] Hold[{101,102,103,104,105}][[1]][[3]] Out[1] 103 ``` So Hold is *not* like Iceberg. Likewise, for HoldComplete, Unevaluate, Defer, Inactivate, ... and combinations of these commands, similar method can extract any part of X. So they are not like Iceberg. **2**. From Iceberg[X], there is a unique way to comeback to X. ``` In[2] Icemelt[Iceberg[{101,102,103,104,105}]] Out[2] {101,102,103,104,105} ``` No function other than 'Icemelt', can do it. **3**. In fact there is a function satisfying 1. and 2. : Iceberg = ToString Icemelt = ToExpression But I ask you to find another solution. I believe ToString/ToExpression is the only solution.
2021/06/11
[ "https://mathematica.stackexchange.com/questions/249493", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/34532/" ]
``` ClearAll@Iceberg; expr : HoldPattern[Iceberg[x_]] /; ! AtomQ[Unevaluated[expr]] := System`Private`SetNoEntry[Unevaluated[expr]]; Iceberg /: MakeBoxes[v_Iceberg?AtomQ, fmt_] := InterpretationBox[ RowBox[{"Iceberg", "[", "\[LeftAngleBracket]", "\[RightAngleBracket]", "]"}], v]; Icemelt[HoldPattern[Iceberg[x_]]] := x ``` Now you can do ``` Iceberg[{1,2,3}] ``` [![enter image description here](https://i.stack.imgur.com/LKeTp.png)](https://i.stack.imgur.com/LKeTp.png) I believe it satisfies the other requirements ``` In[80]:= Iceberg[{101, 102, 103, 104, 105}][[1]][[3]] During evaluation of In[80]:= Part::partd: Part specification Iceberg[\[LeftAngleBracket]\[RightAngleBracket]][[1]] is longer than depth of object. During evaluation of In[80]:= Part::partw: Part 3 of Iceberg[\[LeftAngleBracket]\[RightAngleBracket]][[1]] does not exist. Out[80]= Iceberg[{101, 102, 103, 104, 105}][[1]][[3]] In[81]:= Icemelt[Iceberg[{101, 102, 103, 104, 105}]] Out[81]= {101, 102, 103, 104, 105} ```
Silly, but fun ``` X = {101, 102, 103, 104, 105}; img = Rasterize[X]; ToExpression[TextRecognize[img]] === X (* True *) ```
249,493
Can we construct a function **Iceberg**, which maps a given expression X to Iceberg[X] **satisfying 1. and 2. and 3.** ? **1**. From Iceberg[X], it is not possible to inspect/extract a part of X *with usual method*. It would be better if there is no part of Iceberg[X]. Applying Iceberg to X is like putting X into an iceberg. ex) It is not difficult to extract 3rd part of {101,102,103,104,105}, from Hold[{101,102,103,104,105}]. ``` In[1] Hold[{101,102,103,104,105}][[1]][[3]] Out[1] 103 ``` So Hold is *not* like Iceberg. Likewise, for HoldComplete, Unevaluate, Defer, Inactivate, ... and combinations of these commands, similar method can extract any part of X. So they are not like Iceberg. **2**. From Iceberg[X], there is a unique way to comeback to X. ``` In[2] Icemelt[Iceberg[{101,102,103,104,105}]] Out[2] {101,102,103,104,105} ``` No function other than 'Icemelt', can do it. **3**. In fact there is a function satisfying 1. and 2. : Iceberg = ToString Icemelt = ToExpression But I ask you to find another solution. I believe ToString/ToExpression is the only solution.
2021/06/11
[ "https://mathematica.stackexchange.com/questions/249493", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/34532/" ]
Silly, but fun ``` X = {101, 102, 103, 104, 105}; img = Rasterize[X]; ToExpression[TextRecognize[img]] === X (* True *) ```
So this seems to come close to satisfying all the properties, including Icemelt uniqueness. I don't know any method to hack this `Iceberg` at this point, but I'll think about it more. If someone knows a hack please let me know: ``` (* hold attribute helpers *) HoldPosition[sym_Symbol[args___]] := With[{attrs = Attributes[sym], len = Length @ Unevaluated @ {args}}, Which[ MemberQ[attrs, HoldFirst], {1}, MemberQ[attrs, HoldRest], Range[2, len], MemberQ[attrs, HoldAll | HoldAllComplete], Range @ len, True, {} ] ] HoldPosition[_] := Missing["Position"] HoldPositionQ[expr_, i_] := With[{pos = HoldPosition[Unevaluated[expr]]}, MissingQ[pos] || MemberQ[pos, i]] SequenceHoldQ[sym_Symbol[___]] := MemberQ[Attributes[sym], SequenceHold] SequenceHoldQ[_] := False (* Icemelt *) (* always melt with StackComplete *) Icemelt[Verbatim[Iceberg][data_]] /; MemberQ[Stack[], StackComplete] := data Icemelt[iceberg_Iceberg] := StackComplete[Icemelt[iceberg]] Icemelt[expr___] := $Failed (* Iceberg *) Iceberg::unbrk = "is unbreakable with ``"; Iceberg::symbol = "attempt at reading iceberg symbol is detected"; (* run this if anything except Icemelt is executed with Iceberg in it *) Iceberg /: expr : (f : Except[Icemelt])[left___, iceberg_Iceberg, right___] /; ! SequenceHoldQ[Unevaluated[expr]] := With[{ i = Length[HoldComplete[left]] + 1 }, ( Message[Iceberg::unbrk, HoldForm[DisableFormatting[f[left, Iceberg["\[Ellipsis]"], right]]]]; $Failed ) /; ! HoldPositionQ[Unevaluated[expr], i] ] (* formatting *) Iceberg /: MakeBoxes[iceberg_Iceberg, fmt___] := With[{data = StackComplete @ Icemelt[iceberg]}, BoxForm`ArrangeSummaryBox["Iceberg", "Iceberg"["\[Ellipsis]"], Style["", 48], {{}}, {{data}}, fmt] ] (* make Iceberg atomic *) Iceberg /: iceberg_Iceberg /; System`Private`HoldEntryQ[iceberg] := System`Private`HoldSetNoEntry[iceberg] (* make an Iceberg with protected symbol that only returns its data inside Icemelt *) iceberg : Iceberg[data_] /; System`Private`HoldNotValidQ[iceberg] := Module[{var}, var := If[MemberQ[Stack[], Icemelt], data, Message[Iceberg::"symbol"]; $Failed]; SetAttributes[var, {Protected, ReadProtected, Locked}]; System`Private`HoldSetValid[Iceberg[var]] ] (* protect and lock it *) SetAttributes[Iceberg, {ReadProtected, Protected, Locked, HoldAllComplete}] ``` Here is notebook with an example: <https://www.wolframcloud.com/obj/nikm/Published/Iceberg.nb>
249,493
Can we construct a function **Iceberg**, which maps a given expression X to Iceberg[X] **satisfying 1. and 2. and 3.** ? **1**. From Iceberg[X], it is not possible to inspect/extract a part of X *with usual method*. It would be better if there is no part of Iceberg[X]. Applying Iceberg to X is like putting X into an iceberg. ex) It is not difficult to extract 3rd part of {101,102,103,104,105}, from Hold[{101,102,103,104,105}]. ``` In[1] Hold[{101,102,103,104,105}][[1]][[3]] Out[1] 103 ``` So Hold is *not* like Iceberg. Likewise, for HoldComplete, Unevaluate, Defer, Inactivate, ... and combinations of these commands, similar method can extract any part of X. So they are not like Iceberg. **2**. From Iceberg[X], there is a unique way to comeback to X. ``` In[2] Icemelt[Iceberg[{101,102,103,104,105}]] Out[2] {101,102,103,104,105} ``` No function other than 'Icemelt', can do it. **3**. In fact there is a function satisfying 1. and 2. : Iceberg = ToString Icemelt = ToExpression But I ask you to find another solution. I believe ToString/ToExpression is the only solution.
2021/06/11
[ "https://mathematica.stackexchange.com/questions/249493", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/34532/" ]
``` ClearAll@Iceberg; expr : HoldPattern[Iceberg[x_]] /; ! AtomQ[Unevaluated[expr]] := System`Private`SetNoEntry[Unevaluated[expr]]; Iceberg /: MakeBoxes[v_Iceberg?AtomQ, fmt_] := InterpretationBox[ RowBox[{"Iceberg", "[", "\[LeftAngleBracket]", "\[RightAngleBracket]", "]"}], v]; Icemelt[HoldPattern[Iceberg[x_]]] := x ``` Now you can do ``` Iceberg[{1,2,3}] ``` [![enter image description here](https://i.stack.imgur.com/LKeTp.png)](https://i.stack.imgur.com/LKeTp.png) I believe it satisfies the other requirements ``` In[80]:= Iceberg[{101, 102, 103, 104, 105}][[1]][[3]] During evaluation of In[80]:= Part::partd: Part specification Iceberg[\[LeftAngleBracket]\[RightAngleBracket]][[1]] is longer than depth of object. During evaluation of In[80]:= Part::partw: Part 3 of Iceberg[\[LeftAngleBracket]\[RightAngleBracket]][[1]] does not exist. Out[80]= Iceberg[{101, 102, 103, 104, 105}][[1]][[3]] In[81]:= Icemelt[Iceberg[{101, 102, 103, 104, 105}]] Out[81]= {101, 102, 103, 104, 105} ```
So this seems to come close to satisfying all the properties, including Icemelt uniqueness. I don't know any method to hack this `Iceberg` at this point, but I'll think about it more. If someone knows a hack please let me know: ``` (* hold attribute helpers *) HoldPosition[sym_Symbol[args___]] := With[{attrs = Attributes[sym], len = Length @ Unevaluated @ {args}}, Which[ MemberQ[attrs, HoldFirst], {1}, MemberQ[attrs, HoldRest], Range[2, len], MemberQ[attrs, HoldAll | HoldAllComplete], Range @ len, True, {} ] ] HoldPosition[_] := Missing["Position"] HoldPositionQ[expr_, i_] := With[{pos = HoldPosition[Unevaluated[expr]]}, MissingQ[pos] || MemberQ[pos, i]] SequenceHoldQ[sym_Symbol[___]] := MemberQ[Attributes[sym], SequenceHold] SequenceHoldQ[_] := False (* Icemelt *) (* always melt with StackComplete *) Icemelt[Verbatim[Iceberg][data_]] /; MemberQ[Stack[], StackComplete] := data Icemelt[iceberg_Iceberg] := StackComplete[Icemelt[iceberg]] Icemelt[expr___] := $Failed (* Iceberg *) Iceberg::unbrk = "is unbreakable with ``"; Iceberg::symbol = "attempt at reading iceberg symbol is detected"; (* run this if anything except Icemelt is executed with Iceberg in it *) Iceberg /: expr : (f : Except[Icemelt])[left___, iceberg_Iceberg, right___] /; ! SequenceHoldQ[Unevaluated[expr]] := With[{ i = Length[HoldComplete[left]] + 1 }, ( Message[Iceberg::unbrk, HoldForm[DisableFormatting[f[left, Iceberg["\[Ellipsis]"], right]]]]; $Failed ) /; ! HoldPositionQ[Unevaluated[expr], i] ] (* formatting *) Iceberg /: MakeBoxes[iceberg_Iceberg, fmt___] := With[{data = StackComplete @ Icemelt[iceberg]}, BoxForm`ArrangeSummaryBox["Iceberg", "Iceberg"["\[Ellipsis]"], Style["", 48], {{}}, {{data}}, fmt] ] (* make Iceberg atomic *) Iceberg /: iceberg_Iceberg /; System`Private`HoldEntryQ[iceberg] := System`Private`HoldSetNoEntry[iceberg] (* make an Iceberg with protected symbol that only returns its data inside Icemelt *) iceberg : Iceberg[data_] /; System`Private`HoldNotValidQ[iceberg] := Module[{var}, var := If[MemberQ[Stack[], Icemelt], data, Message[Iceberg::"symbol"]; $Failed]; SetAttributes[var, {Protected, ReadProtected, Locked}]; System`Private`HoldSetValid[Iceberg[var]] ] (* protect and lock it *) SetAttributes[Iceberg, {ReadProtected, Protected, Locked, HoldAllComplete}] ``` Here is notebook with an example: <https://www.wolframcloud.com/obj/nikm/Published/Iceberg.nb>
13,093,236
Since MVC3 WebGrid sorting default is ascending via query string, &sortdir=ASC.. I would like to know how to sort initially by descending. I've tried below, using Request.QueryString, but in the case were there is absolutely no query string "?..", this doesn't see, to be working: ``` // Force a descending sort on page load when query string is empty if(Request.QueryString[grid.SortDirectionFieldName].IsEmpty()){ grid.SortDirection = SortDirection.Descending; } ``` Since I have a path like ..Admin/Review initially, and not ../Admin/Review?sort=Question6&sortdir=ASC, how can I test this case? Would the above condition still return true if there isn't even a query parameter? I believe I need to extract a query from the raw url and if it doesn't exist, set my sort direction to descending.
2012/10/26
[ "https://Stackoverflow.com/questions/13093236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1148619/" ]
You may need to change your if statement to this: ``` if( string.IsNullOrEmpty(Request.QueryString[grid.SortDirectionFieldName]) ){ //sort desc } ```
Would this work? It will default to Descending unless the querystring variable is explicitly "ASC". ``` if (Request.QueryString[grid.SortDirectionFieldName] == "ASC") { grid.SortDirection = SortDirection.Ascending; } else { grid.SortDirection = SortDirection.Descending; } ```
13,093,236
Since MVC3 WebGrid sorting default is ascending via query string, &sortdir=ASC.. I would like to know how to sort initially by descending. I've tried below, using Request.QueryString, but in the case were there is absolutely no query string "?..", this doesn't see, to be working: ``` // Force a descending sort on page load when query string is empty if(Request.QueryString[grid.SortDirectionFieldName].IsEmpty()){ grid.SortDirection = SortDirection.Descending; } ``` Since I have a path like ..Admin/Review initially, and not ../Admin/Review?sort=Question6&sortdir=ASC, how can I test this case? Would the above condition still return true if there isn't even a query parameter? I believe I need to extract a query from the raw url and if it doesn't exist, set my sort direction to descending.
2012/10/26
[ "https://Stackoverflow.com/questions/13093236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1148619/" ]
You may need to change your if statement to this: ``` if( string.IsNullOrEmpty(Request.QueryString[grid.SortDirectionFieldName]) ){ //sort desc } ```
ended up using JS: ``` $(document).ready(function () { var ignoreURL = window.location.href.replace('DESC', 'ASC'); $('#grid th a').each(function () { if (this.href.indexOf('ASC') > -1 && this.href != ignoreURL) { this.href = this.href.replace('ASC', 'DESC'); } }); }); ```
42,875,770
I am trying to use a fine-tuning approach to retrain a model. As a sanity check I tried to retrain it while first freezing all of its the layers. I expected that the model will not change; I was surprised to see this: ``` Epoch 1/50 16/16 [==============================] - 25s - loss: 4.0006 - acc: 0.5000 - val_loss: 1.3748e-04 - val_acc: 1.0000 Epoch 2/50 16/16 [==============================] - 24s - loss: 3.8861 - acc: 0.5000 - val_loss: 1.7333e-04 - val_acc: 1.0000 Epoch 3/50 16/16 [==============================] - 25s - loss: 3.9560 - acc: 0.5000 - val_loss: 3.0870e-04 - val_acc: 1.0000 Epoch 4/50 16/16 [==============================] - 26s - loss: 3.9730 - acc: 0.5000 - val_loss: 7.5931e-04 - val_acc: 1.0000 Epoch 5/50 16/16 [==============================] - 26s - loss: 3.7195 - acc: 0.5000 - val_loss: 0.0021 - val_acc: 1.0000 Epoch 6/50 16/16 [==============================] - 25s - loss: 3.9514 - acc: 0.5000 - val_loss: 0.0058 - val_acc: 1.0000 Epoch 7/50 16/16 [==============================] - 26s - loss: 3.9459 - acc: 0.5000 - val_loss: 0.0180 - val_acc: 1.0000 Epoch 8/50 16/16 [==============================] - 26s - loss: 3.8744 - acc: 0.5000 - val_loss: 0.0489 - val_acc: 1.0000 Epoch 9/50 16/16 [==============================] - 27s - loss: 3.8914 - acc: 0.5000 - val_loss: 0.1100 - val_acc: 1.0000 Epoch 10/50 16/16 [==============================] - 26s - loss: 4.0585 - acc: 0.5000 - val_loss: 0.2092 - val_acc: 0.7500 Epoch 11/50 16/16 [==============================] - 27s - loss: 4.0232 - acc: 0.5000 - val_loss: 0.3425 - val_acc: 0.7500 Epoch 12/50 16/16 [==============================] - 25s - loss: 3.9073 - acc: 0.5000 - val_loss: 0.4566 - val_acc: 0.7500 Epoch 13/50 16/16 [==============================] - 27s - loss: 4.1036 - acc: 0.5000 - val_loss: 0.5454 - val_acc: 0.7500 Epoch 14/50 16/16 [==============================] - 26s - loss: 3.7854 - acc: 0.5000 - val_loss: 0.6213 - val_acc: 0.7500 Epoch 15/50 16/16 [==============================] - 27s - loss: 3.7907 - acc: 0.5000 - val_loss: 0.7120 - val_acc: 0.7500 Epoch 16/50 16/16 [==============================] - 27s - loss: 4.0540 - acc: 0.5000 - val_loss: 0.7226 - val_acc: 0.7500 Epoch 17/50 16/16 [==============================] - 26s - loss: 3.8669 - acc: 0.5000 - val_loss: 0.8032 - val_acc: 0.7500 Epoch 18/50 16/16 [==============================] - 28s - loss: 3.9834 - acc: 0.5000 - val_loss: 0.9523 - val_acc: 0.7500 Epoch 19/50 16/16 [==============================] - 27s - loss: 3.9495 - acc: 0.5000 - val_loss: 2.5764 - val_acc: 0.6250 Epoch 20/50 16/16 [==============================] - 25s - loss: 3.7534 - acc: 0.5000 - val_loss: 3.0939 - val_acc: 0.6250 Epoch 21/50 16/16 [==============================] - 29s - loss: 3.8447 - acc: 0.5000 - val_loss: 3.0467 - val_acc: 0.6250 Epoch 22/50 16/16 [==============================] - 28s - loss: 4.0613 - acc: 0.5000 - val_loss: 3.2160 - val_acc: 0.6250 Epoch 23/50 16/16 [==============================] - 28s - loss: 4.1428 - acc: 0.5000 - val_loss: 3.8793 - val_acc: 0.6250 Epoch 24/50 16/16 [==============================] - 27s - loss: 3.7868 - acc: 0.5000 - val_loss: 4.1935 - val_acc: 0.6250 Epoch 25/50 16/16 [==============================] - 28s - loss: 3.8437 - acc: 0.5000 - val_loss: 4.5031 - val_acc: 0.6250 Epoch 26/50 16/16 [==============================] - 28s - loss: 3.9798 - acc: 0.5000 - val_loss: 4.5121 - val_acc: 0.6250 Epoch 27/50 16/16 [==============================] - 28s - loss: 3.8727 - acc: 0.5000 - val_loss: 4.5341 - val_acc: 0.6250 Epoch 28/50 16/16 [==============================] - 28s - loss: 3.8343 - acc: 0.5000 - val_loss: 4.5198 - val_acc: 0.6250 Epoch 29/50 16/16 [==============================] - 28s - loss: 4.2144 - acc: 0.5000 - val_loss: 4.5341 - val_acc: 0.6250 Epoch 30/50 16/16 [==============================] - 28s - loss: 3.8348 - acc: 0.5000 - val_loss: 4.5684 - val_acc: 0.6250 ``` This is the code I used: ``` from keras import backend as K import inception_v4 import numpy as np import cv2 import os import re from keras import optimizers from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequential from keras.layers import Convolution2D, MaxPooling2D, ZeroPadding2D from keras.layers import Activation, Dropout, Flatten, Dense, Input from keras.models import Model os.environ['CUDA_VISIBLE_DEVICES'] = '' v4 = inception_v4.create_model(weights='imagenet') #v4.summary() my_batch_size=1 train_data_dir ='//shared_directory/projects/try_CDFxx/data/train/' validation_data_dir ='//shared_directory/projects/try_CDFxx/data/validation/' top_model_weights_path= 'bottleneck_fc_model.h5' class_num=2 img_width, img_height = 299, 299 nbr_train_samples=16 nbr_validation_samples=8 num_classes=2 nb_epoch=50 main_input= v4.layers[1].input main_output=v4.layers[-1].output flatten_output= v4.layers[-2].output BN_model = Model(input=[main_input], output=[main_output, flatten_output]) ### DEF train_datagen = ImageDataGenerator( rescale=1./255, shear_range=0.1, zoom_range=0.1, rotation_range=10., width_shift_range=0.1, height_shift_range=0.1, horizontal_flip=True) val_datagen = ImageDataGenerator(rescale=1./255) train_generator = train_datagen.flow_from_directory( train_data_dir, target_size = (img_width, img_height), batch_size = my_batch_size, shuffle = True, class_mode = 'categorical') validation_generator = val_datagen.flow_from_directory( validation_data_dir, target_size=(img_width, img_height), batch_size=my_batch_size, shuffle = True, class_mode = 'categorical') # sparse ### def save_BN(BN_model): # but we will need to get the get_processed_image into it!!!! # datagen = ImageDataGenerator(rescale=1./255) # here! # generator = datagen.flow_from_directory( train_data_dir, target_size=(img_width, img_height), batch_size=my_batch_size, class_mode='categorical', shuffle=False) nb_train_samples = generator.classes.size bottleneck_features_train = BN_model.predict_generator(generator, nb_train_samples) # np.save(open('bottleneck_flat_features_train.npy', 'wb'), bottleneck_features_train[1]) np.save(open('bottleneck_train_labels.npy', 'wb'), generator.classes) # generator is probably a tuple - and the second thing in it is a label! OKAY, its not :( generator = datagen.flow_from_directory( validation_data_dir, target_size=(img_width, img_height), batch_size=my_batch_size, class_mode='categorical', shuffle=False) nb_validation_samples = generator.classes.size bottleneck_features_validation = BN_model.predict_generator(generator, nb_validation_samples) #bottleneck_features_validation = model.train_generator(generator, nb_validation_samples) # np.save(open('bottleneck_flat_features_validation.npy', 'wb'), bottleneck_features_validation[1]) np.save(open('bottleneck_validation_labels.npy', 'wb'), generator.classes) def train_top_model (): train_data = np.load(open('bottleneck_flat_features_train.npy')) train_labels = np.load(open('bottleneck_train_labels.npy')) # validation_data = np.load(open('bottleneck_flat_features_validation.npy')) validation_labels = np.load(open('bottleneck_validation_labels.npy')) # top_m = Sequential() top_m.add(Dense(class_num,input_shape=train_data.shape[1:], activation='softmax', name='top_dense1')) top_m.compile(optimizer='rmsprop', loss='sparse_categorical_crossentropy', metrics=['accuracy']) # top_m.fit(train_data, train_labels, nb_epoch=nb_epoch, batch_size=my_batch_size, validation_data=(validation_data, validation_labels)) # # #top_m.save_weights (top_model_weights_path) # validation_data[0] # train_data[0] Dense_layer=top_m.layers[-1] top_layer_weights=Dense_layer.get_weights() np.save(open('retrained_top_layer_weight.npy', 'wb'), top_layer_weights) def fine_tune_model (): predictions = Flatten()(v4.layers[-3].output) predictions = Dense(output_dim=num_classes, activation='softmax', name="newDense")(predictions) main_input= v4.layers[1].input main_output=predictions FT_model = Model(input=[main_input], output=[main_output]) top_layer_weights = np.load(open('retrained_top_layer_weight.npy')) Dense_layer=FT_model.layers[-1] Dense_layer.set_weights(top_layer_weights) for layer in FT_model.layers: layer.trainable = False # FT_model.layers[-1].trainable=True FT_model.compile(optimizer=optimizers.SGD(lr=1e-4, momentum=0.9), loss='categorical_crossentropy', metrics=['accuracy']) FT_model.fit_generator( train_generator, samples_per_epoch = nbr_train_samples, nb_epoch = nb_epoch, validation_data = validation_generator, nb_val_samples = nbr_validation_samples) ######################################################## ########### save_BN(BN_model) train_top_model() fine_tune_model() ``` Thanks. P.S. I'm using keras 1.
2017/03/18
[ "https://Stackoverflow.com/questions/42875770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2182857/" ]
You are using `dropout` so metrics may vary across different runs as different units are turned off.
The training changes are normal because you are using image data augmentation, so every dataset per epoch will be different. For freezing all the layers try to change to False the trainable argument of the model directly: ``` FT_model.trainable = False print('This is the number of trainable weights ''after freezing the conv base:', len(FT_model.trainable_weights)) ```
24,975,629
I have this `void` ``` -(void)MoveMissile:(UIImageView *)Missile mtimer:(NSTimer *)MissileTimer{ // lines of code here } ``` and this NSTimer: ``` [NSTimer scheduledTimerWithTimeInterval:0.025 target:self selector:@selector(MoveMissile:mtimer:) userInfo:nil repeats:YES]; ``` I want to pass the `NSTimer` as the second parameter, and a `UIImageView` called `Missile1` as the first parameter. How do I pass these two parameters?
2014/07/26
[ "https://Stackoverflow.com/questions/24975629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3496038/" ]
From the [NSTimer documentation](https://developer.apple.com/library/ios/documentation/cocoa/reference/foundation/classes/NSTimer_Class/Reference/NSTimer.html#//apple_ref/occ/clm/NSTimer/scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:): > > aSelector > > > The message to send to target when the timer fires. The > selector should have the following signature: timerFireMethod: > (including a colon to indicate that the method takes an argument). The > timer passes itself as the argument, thus the method would adopt the > following pattern: > > > > ``` > - (void)timerFireMethod:(NSTimer *)timer > > ``` > > So, you have to work with a method that takes a single parameter, and pass a reference to the image view in via the timers userInfo, like so. ``` [NSTimer scheduledTimerWithTimeInterval:0.025 target:self selector:@selector(missileTimerMethod:) userInfo:anImageViewReference repeats:YES]; - (void)missileTimerMethod:(NSTimer *)missileTimer { UIImageView *theImageView = (UIImageView *)missileTimer.userInfo; } ```
You can't do it the way you're trying. The selector for the timer hast to have zero or one parameters, and if it has one, that has to be the timer (the signature for the method is clearly spelled out in the NSTimer class reference). However, you can pass any object you want in the userInfo parameter. So pass your image view as the userInfo.
66,489,732
I have a class like this ``` public class KReport : IReport { private readonly EDevContext _context; private readonly IMapper _mapper; public KReport(EDevContext context, IMapper mapper = null) { _context = context; _mapper = mapper; } public void GetKReport(int reportId,int page=1) { string s; //some logic here if(reportId==1){ GetKReport(452,2) } } } ``` Also in startup I have added a singleton service ``` services.AddSingleton<IKReport, KReport>(); ``` But when I execute the application I am getting this error > > System.AggregateException: 'Some services are not able to be > constructed (Error while validating the service descriptor > 'ServiceType: common.IKReport Lifetime: Singleton ImplementationType: > common.KReport': Cannot consume scoped service > 'Models.EPMO\_DevContext' from singleton 'common.IKnReport'.)' > > > This error wont occur when that recursive call gets commented Really sorry my understanding of this dependency injection or singleton services are almost 0. So I didnt understand what happens here
2021/03/05
[ "https://Stackoverflow.com/questions/66489732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/954093/" ]
It is because you are injecting scoped service in KReport. Use following code in "Startup.cs" file. ``` services.AddScoped<IKReport,KReport>(); ```
You must add EDevContext service before `services.AddSingleton<IKReport, KReport>();` --- Edit: From the trace stack, that show your class EDevContext is addScopeService ,you need make the EDevContext and KReport as the same lifetimes
46,491,871
Currently facing a problem, long story short: I'm trying to combine 2 formulas into one, by making use of the OR-function, but if one of the 2 conditions does not exist, it gives me an #N/A back. There's 3 conditions that can happen: "MTI", "MTI Z" and "MTO". What I would like is that the formula searches for any combination in column L with either "MTI" or "MTI Z" (might also be both) and if that combination exists, give back a 1. If not (so only MTO exists) then return a 0 (in this case it will be an #N/A, but I can fix that with either ISNA or IFERROR). Formula 1 is: ``` =IF(CONCATENATE(A2,B2,"MTI")=INDEX(L:L,MATCH(CONCATENATE(A2,B2,"MTI"),L:L,0),0),1,0) ``` Formula 2 is ``` =IF(CONCATENATE(A2,B2,"MTI Z")=INDEX(L:L,MATCH(CONCATENATE(A2,B2,"MTI Z"),L:L,0),0),1,0) ``` Both formulas work, giving back a "1" when there is respectively a "MTI" or "MTI Z" However, when I try to combine them, if 1 of the 2 does not exist in the list, it gives me an #N/A, even though I'm using OR (which would state if at least 1 of the 2 exists, go ahead). ``` =IF(OR(CONCATENATE(A2,B2,"MTI Z")=INDEX(L:L,MATCH(CONCATENATE(A2,B2,"MTI Z"),L:L,0),0) ,CONCATENATE(A2,B2,"MTI")=INDEX(L:L,MATCH(CONCATENATE(A2,B2,"MTI"),L:L,0),0)),1,0) ``` How can I adjust my formula so that it does work?
2017/09/29
[ "https://Stackoverflow.com/questions/46491871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4887991/" ]
Wrap each of these formulas in an `IFERROR([formula],0)`
Try adding two IFERROR 'wrappers' so you return FALSE when no match, not #N/A. ``` =IF(OR(IFERROR(CONCATENATE(A2,B2,"MTI Z")=INDEX(L:L, MATCH(CONCATENATE(A2,B2, "MTI Z"), L:L, 0)), FALSE), IFERROR(CONCATENATE(A2,B2,"MTI")=INDEX(L:L, MATCH(CONCATENATE(A2,B2,"MTI"), L:L, 0)), FALSE)), 1, 0) ```
46,491,871
Currently facing a problem, long story short: I'm trying to combine 2 formulas into one, by making use of the OR-function, but if one of the 2 conditions does not exist, it gives me an #N/A back. There's 3 conditions that can happen: "MTI", "MTI Z" and "MTO". What I would like is that the formula searches for any combination in column L with either "MTI" or "MTI Z" (might also be both) and if that combination exists, give back a 1. If not (so only MTO exists) then return a 0 (in this case it will be an #N/A, but I can fix that with either ISNA or IFERROR). Formula 1 is: ``` =IF(CONCATENATE(A2,B2,"MTI")=INDEX(L:L,MATCH(CONCATENATE(A2,B2,"MTI"),L:L,0),0),1,0) ``` Formula 2 is ``` =IF(CONCATENATE(A2,B2,"MTI Z")=INDEX(L:L,MATCH(CONCATENATE(A2,B2,"MTI Z"),L:L,0),0),1,0) ``` Both formulas work, giving back a "1" when there is respectively a "MTI" or "MTI Z" However, when I try to combine them, if 1 of the 2 does not exist in the list, it gives me an #N/A, even though I'm using OR (which would state if at least 1 of the 2 exists, go ahead). ``` =IF(OR(CONCATENATE(A2,B2,"MTI Z")=INDEX(L:L,MATCH(CONCATENATE(A2,B2,"MTI Z"),L:L,0),0) ,CONCATENATE(A2,B2,"MTI")=INDEX(L:L,MATCH(CONCATENATE(A2,B2,"MTI"),L:L,0),0)),1,0) ``` How can I adjust my formula so that it does work?
2017/09/29
[ "https://Stackoverflow.com/questions/46491871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4887991/" ]
This is a bit more straight forward: ``` =SIGN(COUNTIF(L:L,CONCATENATE(A2,B2,"MTI*"))) ```
Try adding two IFERROR 'wrappers' so you return FALSE when no match, not #N/A. ``` =IF(OR(IFERROR(CONCATENATE(A2,B2,"MTI Z")=INDEX(L:L, MATCH(CONCATENATE(A2,B2, "MTI Z"), L:L, 0)), FALSE), IFERROR(CONCATENATE(A2,B2,"MTI")=INDEX(L:L, MATCH(CONCATENATE(A2,B2,"MTI"), L:L, 0)), FALSE)), 1, 0) ```
46,491,871
Currently facing a problem, long story short: I'm trying to combine 2 formulas into one, by making use of the OR-function, but if one of the 2 conditions does not exist, it gives me an #N/A back. There's 3 conditions that can happen: "MTI", "MTI Z" and "MTO". What I would like is that the formula searches for any combination in column L with either "MTI" or "MTI Z" (might also be both) and if that combination exists, give back a 1. If not (so only MTO exists) then return a 0 (in this case it will be an #N/A, but I can fix that with either ISNA or IFERROR). Formula 1 is: ``` =IF(CONCATENATE(A2,B2,"MTI")=INDEX(L:L,MATCH(CONCATENATE(A2,B2,"MTI"),L:L,0),0),1,0) ``` Formula 2 is ``` =IF(CONCATENATE(A2,B2,"MTI Z")=INDEX(L:L,MATCH(CONCATENATE(A2,B2,"MTI Z"),L:L,0),0),1,0) ``` Both formulas work, giving back a "1" when there is respectively a "MTI" or "MTI Z" However, when I try to combine them, if 1 of the 2 does not exist in the list, it gives me an #N/A, even though I'm using OR (which would state if at least 1 of the 2 exists, go ahead). ``` =IF(OR(CONCATENATE(A2,B2,"MTI Z")=INDEX(L:L,MATCH(CONCATENATE(A2,B2,"MTI Z"),L:L,0),0) ,CONCATENATE(A2,B2,"MTI")=INDEX(L:L,MATCH(CONCATENATE(A2,B2,"MTI"),L:L,0),0)),1,0) ``` How can I adjust my formula so that it does work?
2017/09/29
[ "https://Stackoverflow.com/questions/46491871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4887991/" ]
Wrap each of these formulas in an `IFERROR([formula],0)`
You can re-write your formula as ``` =IF(OR(ISNUMBER(MATCH(CONCATENATE(A2,B2,"MTI"),L:L,0)), ISNUMBER(MATCH(CONCATENATE(A2,B2,"MTI Z"),L:L,0))),1,0) ```
46,491,871
Currently facing a problem, long story short: I'm trying to combine 2 formulas into one, by making use of the OR-function, but if one of the 2 conditions does not exist, it gives me an #N/A back. There's 3 conditions that can happen: "MTI", "MTI Z" and "MTO". What I would like is that the formula searches for any combination in column L with either "MTI" or "MTI Z" (might also be both) and if that combination exists, give back a 1. If not (so only MTO exists) then return a 0 (in this case it will be an #N/A, but I can fix that with either ISNA or IFERROR). Formula 1 is: ``` =IF(CONCATENATE(A2,B2,"MTI")=INDEX(L:L,MATCH(CONCATENATE(A2,B2,"MTI"),L:L,0),0),1,0) ``` Formula 2 is ``` =IF(CONCATENATE(A2,B2,"MTI Z")=INDEX(L:L,MATCH(CONCATENATE(A2,B2,"MTI Z"),L:L,0),0),1,0) ``` Both formulas work, giving back a "1" when there is respectively a "MTI" or "MTI Z" However, when I try to combine them, if 1 of the 2 does not exist in the list, it gives me an #N/A, even though I'm using OR (which would state if at least 1 of the 2 exists, go ahead). ``` =IF(OR(CONCATENATE(A2,B2,"MTI Z")=INDEX(L:L,MATCH(CONCATENATE(A2,B2,"MTI Z"),L:L,0),0) ,CONCATENATE(A2,B2,"MTI")=INDEX(L:L,MATCH(CONCATENATE(A2,B2,"MTI"),L:L,0),0)),1,0) ``` How can I adjust my formula so that it does work?
2017/09/29
[ "https://Stackoverflow.com/questions/46491871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4887991/" ]
This is a bit more straight forward: ``` =SIGN(COUNTIF(L:L,CONCATENATE(A2,B2,"MTI*"))) ```
Wrap each of these formulas in an `IFERROR([formula],0)`
46,491,871
Currently facing a problem, long story short: I'm trying to combine 2 formulas into one, by making use of the OR-function, but if one of the 2 conditions does not exist, it gives me an #N/A back. There's 3 conditions that can happen: "MTI", "MTI Z" and "MTO". What I would like is that the formula searches for any combination in column L with either "MTI" or "MTI Z" (might also be both) and if that combination exists, give back a 1. If not (so only MTO exists) then return a 0 (in this case it will be an #N/A, but I can fix that with either ISNA or IFERROR). Formula 1 is: ``` =IF(CONCATENATE(A2,B2,"MTI")=INDEX(L:L,MATCH(CONCATENATE(A2,B2,"MTI"),L:L,0),0),1,0) ``` Formula 2 is ``` =IF(CONCATENATE(A2,B2,"MTI Z")=INDEX(L:L,MATCH(CONCATENATE(A2,B2,"MTI Z"),L:L,0),0),1,0) ``` Both formulas work, giving back a "1" when there is respectively a "MTI" or "MTI Z" However, when I try to combine them, if 1 of the 2 does not exist in the list, it gives me an #N/A, even though I'm using OR (which would state if at least 1 of the 2 exists, go ahead). ``` =IF(OR(CONCATENATE(A2,B2,"MTI Z")=INDEX(L:L,MATCH(CONCATENATE(A2,B2,"MTI Z"),L:L,0),0) ,CONCATENATE(A2,B2,"MTI")=INDEX(L:L,MATCH(CONCATENATE(A2,B2,"MTI"),L:L,0),0)),1,0) ``` How can I adjust my formula so that it does work?
2017/09/29
[ "https://Stackoverflow.com/questions/46491871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4887991/" ]
This is a bit more straight forward: ``` =SIGN(COUNTIF(L:L,CONCATENATE(A2,B2,"MTI*"))) ```
You can re-write your formula as ``` =IF(OR(ISNUMBER(MATCH(CONCATENATE(A2,B2,"MTI"),L:L,0)), ISNUMBER(MATCH(CONCATENATE(A2,B2,"MTI Z"),L:L,0))),1,0) ```
502,345
The question could be subjective, so the syntax of ``` std::ostream& operator << (std::ostream & o, const SomeClass &a) { return o << a.accessor().. ; } ``` When do you normally define this for the classes that you write, when do you avoid writing this friend function for your class.
2009/02/02
[ "https://Stackoverflow.com/questions/502345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43756/" ]
IF I want to stream a class I normally write this: ``` std::ostream& operator << (std::ostream& o, const SomeClass& a) { a.print(o); return o; } ``` Then make print a const method on SomeClass that knows how to serialize the class to a stream.
A benefit of Martin's answer above is that you also get polymorphism for free. If you make `print(ostream&)` a **virtual** function, then the << operator acts like a virtual function as well! As to when to overload the operator, do so anytime you think the class should be able to be written to a stream (file, socket, etc...). This might even be only for debug purposes. It is often useful to be able to output the internals of a class, so there is no real downside to overloading this operator.
502,345
The question could be subjective, so the syntax of ``` std::ostream& operator << (std::ostream & o, const SomeClass &a) { return o << a.accessor().. ; } ``` When do you normally define this for the classes that you write, when do you avoid writing this friend function for your class.
2009/02/02
[ "https://Stackoverflow.com/questions/502345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43756/" ]
IF I want to stream a class I normally write this: ``` std::ostream& operator << (std::ostream& o, const SomeClass& a) { a.print(o); return o; } ``` Then make print a const method on SomeClass that knows how to serialize the class to a stream.
I had never ever overloaded this one in production code. Although you might want do this if you log a lot, it'll be useful.
502,345
The question could be subjective, so the syntax of ``` std::ostream& operator << (std::ostream & o, const SomeClass &a) { return o << a.accessor().. ; } ``` When do you normally define this for the classes that you write, when do you avoid writing this friend function for your class.
2009/02/02
[ "https://Stackoverflow.com/questions/502345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43756/" ]
A benefit of Martin's answer above is that you also get polymorphism for free. If you make `print(ostream&)` a **virtual** function, then the << operator acts like a virtual function as well! As to when to overload the operator, do so anytime you think the class should be able to be written to a stream (file, socket, etc...). This might even be only for debug purposes. It is often useful to be able to output the internals of a class, so there is no real downside to overloading this operator.
I had never ever overloaded this one in production code. Although you might want do this if you log a lot, it'll be useful.
502,345
The question could be subjective, so the syntax of ``` std::ostream& operator << (std::ostream & o, const SomeClass &a) { return o << a.accessor().. ; } ``` When do you normally define this for the classes that you write, when do you avoid writing this friend function for your class.
2009/02/02
[ "https://Stackoverflow.com/questions/502345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43756/" ]
I had never ever overloaded this one in production code. Although you might want do this if you log a lot, it'll be useful.
I implement this if, and only if, I intend to make use of that operator. This is pretty much never... my reasons for not implementing it are therefore not using it. If its for public use then include it for completeness, but certainly I wouldn't include this in every class in a project of your own, since for the most part you will not need to output a class to a stream. e.g. If you wrap your entry point in a class, providing this operator will be pointless.
502,345
The question could be subjective, so the syntax of ``` std::ostream& operator << (std::ostream & o, const SomeClass &a) { return o << a.accessor().. ; } ``` When do you normally define this for the classes that you write, when do you avoid writing this friend function for your class.
2009/02/02
[ "https://Stackoverflow.com/questions/502345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43756/" ]
I would only overload operator<< when that has anything to do with streaming, or with shifting and the class is purely numeral. For writing something into an ostream, as in your code, i think it's fine. Anything else, i think, will cause confusion and i would better use member functions for those other purposes. One other application, which i think i would still do as an exception to the rule, is doing something like this: ``` StringList list; list << "foo" << "bar" << "baz"; ``` It is how Qt does it with its string list, and which i find quite nice.
I do it very frequently since it makes dumping the object to a log for debugging really convenient.
502,345
The question could be subjective, so the syntax of ``` std::ostream& operator << (std::ostream & o, const SomeClass &a) { return o << a.accessor().. ; } ``` When do you normally define this for the classes that you write, when do you avoid writing this friend function for your class.
2009/02/02
[ "https://Stackoverflow.com/questions/502345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43756/" ]
IF I want to stream a class I normally write this: ``` std::ostream& operator << (std::ostream& o, const SomeClass& a) { a.print(o); return o; } ``` Then make print a const method on SomeClass that knows how to serialize the class to a stream.
I would consider using it for something like logging. So you can do: ``` SystemLog systemLog; systemLog << "Processing Item #15"; systemLog << "Error 0014: Bad things happened."; systemLog << system.executeCommand(cmd); // returns a result string ``` Or maybe for networking as in: ``` NetworkInterface networkInterface; string message("Hello World! I'm a server."); networkInterface << message; ``` Of course implementing these things as regular function is also possible and might just be preferable. Generally, you should beware of operator overloading. Only use it when it really fits.
502,345
The question could be subjective, so the syntax of ``` std::ostream& operator << (std::ostream & o, const SomeClass &a) { return o << a.accessor().. ; } ``` When do you normally define this for the classes that you write, when do you avoid writing this friend function for your class.
2009/02/02
[ "https://Stackoverflow.com/questions/502345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43756/" ]
I would consider using it for something like logging. So you can do: ``` SystemLog systemLog; systemLog << "Processing Item #15"; systemLog << "Error 0014: Bad things happened."; systemLog << system.executeCommand(cmd); // returns a result string ``` Or maybe for networking as in: ``` NetworkInterface networkInterface; string message("Hello World! I'm a server."); networkInterface << message; ``` Of course implementing these things as regular function is also possible and might just be preferable. Generally, you should beware of operator overloading. Only use it when it really fits.
I implement this if, and only if, I intend to make use of that operator. This is pretty much never... my reasons for not implementing it are therefore not using it. If its for public use then include it for completeness, but certainly I wouldn't include this in every class in a project of your own, since for the most part you will not need to output a class to a stream. e.g. If you wrap your entry point in a class, providing this operator will be pointless.
502,345
The question could be subjective, so the syntax of ``` std::ostream& operator << (std::ostream & o, const SomeClass &a) { return o << a.accessor().. ; } ``` When do you normally define this for the classes that you write, when do you avoid writing this friend function for your class.
2009/02/02
[ "https://Stackoverflow.com/questions/502345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43756/" ]
IF I want to stream a class I normally write this: ``` std::ostream& operator << (std::ostream& o, const SomeClass& a) { a.print(o); return o; } ``` Then make print a const method on SomeClass that knows how to serialize the class to a stream.
I do it very frequently since it makes dumping the object to a log for debugging really convenient.
502,345
The question could be subjective, so the syntax of ``` std::ostream& operator << (std::ostream & o, const SomeClass &a) { return o << a.accessor().. ; } ``` When do you normally define this for the classes that you write, when do you avoid writing this friend function for your class.
2009/02/02
[ "https://Stackoverflow.com/questions/502345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43756/" ]
IF I want to stream a class I normally write this: ``` std::ostream& operator << (std::ostream& o, const SomeClass& a) { a.print(o); return o; } ``` Then make print a const method on SomeClass that knows how to serialize the class to a stream.
I would only overload operator<< when that has anything to do with streaming, or with shifting and the class is purely numeral. For writing something into an ostream, as in your code, i think it's fine. Anything else, i think, will cause confusion and i would better use member functions for those other purposes. One other application, which i think i would still do as an exception to the rule, is doing something like this: ``` StringList list; list << "foo" << "bar" << "baz"; ``` It is how Qt does it with its string list, and which i find quite nice.
502,345
The question could be subjective, so the syntax of ``` std::ostream& operator << (std::ostream & o, const SomeClass &a) { return o << a.accessor().. ; } ``` When do you normally define this for the classes that you write, when do you avoid writing this friend function for your class.
2009/02/02
[ "https://Stackoverflow.com/questions/502345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43756/" ]
I would only overload operator<< when that has anything to do with streaming, or with shifting and the class is purely numeral. For writing something into an ostream, as in your code, i think it's fine. Anything else, i think, will cause confusion and i would better use member functions for those other purposes. One other application, which i think i would still do as an exception to the rule, is doing something like this: ``` StringList list; list << "foo" << "bar" << "baz"; ``` It is how Qt does it with its string list, and which i find quite nice.
I implement this if, and only if, I intend to make use of that operator. This is pretty much never... my reasons for not implementing it are therefore not using it. If its for public use then include it for completeness, but certainly I wouldn't include this in every class in a project of your own, since for the most part you will not need to output a class to a stream. e.g. If you wrap your entry point in a class, providing this operator will be pointless.
26,833,587
I have the next little code, it has to read a file and when it finds an `\n` or an `\r` it substitutes it with a `$`. The file is this: ``` for A27y= + 1643.2 - 642 : b end F017 = 3.5 ``` and here is the code: ``` public static void main(String[] args){ int car; String l = ""; try { File file = new File("openFile.txt"); RandomAccessFile af = new RandomAccessFile(file,"r"); while((car = af.read()) != -1) l += (char)car; l = l.replace('\n', '$').replace('\r', '$'); System.out.println(""+l); af.close(); } catch(IOException ex) { System.out.println("Cannot open file"); } } ``` The problem that I have is that every time it finds an '\n' or an '\r' in the file, instead of printing a single `$` it prints it double `$$`, and I don't understand why. It prints something like this: > > for A27y= + 1643.2 - 642 : b$$end$$$$F017 = 3.5$$ > > > when it should be like this: > > for A27y= + 1643.2 - 642 : b$end$$F017 = 3.5$ > > >
2014/11/09
[ "https://Stackoverflow.com/questions/26833587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3105533/" ]
Since some systems (Windows for example) use `\r\n` to represent end of line, you will sometimes get this behaviour for the code you are showing. You can fix this by first replacing these: ``` l = l.replace("\r\n", "$").replace('\n', '$').replace('\r', '$'); ```
you can check what Keppil said by looking at the values of car in the debugger
26,833,587
I have the next little code, it has to read a file and when it finds an `\n` or an `\r` it substitutes it with a `$`. The file is this: ``` for A27y= + 1643.2 - 642 : b end F017 = 3.5 ``` and here is the code: ``` public static void main(String[] args){ int car; String l = ""; try { File file = new File("openFile.txt"); RandomAccessFile af = new RandomAccessFile(file,"r"); while((car = af.read()) != -1) l += (char)car; l = l.replace('\n', '$').replace('\r', '$'); System.out.println(""+l); af.close(); } catch(IOException ex) { System.out.println("Cannot open file"); } } ``` The problem that I have is that every time it finds an '\n' or an '\r' in the file, instead of printing a single `$` it prints it double `$$`, and I don't understand why. It prints something like this: > > for A27y= + 1643.2 - 642 : b$$end$$$$F017 = 3.5$$ > > > when it should be like this: > > for A27y= + 1643.2 - 642 : b$end$$F017 = 3.5$ > > >
2014/11/09
[ "https://Stackoverflow.com/questions/26833587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3105533/" ]
Since some systems (Windows for example) use `\r\n` to represent end of line, you will sometimes get this behaviour for the code you are showing. You can fix this by first replacing these: ``` l = l.replace("\r\n", "$").replace('\n', '$').replace('\r', '$'); ```
You can try as @Keppil suggested (probadly the "\r\n" is a line feed at your system). I'd suggest making things more efficient and short by not iterating through each character in the file: ``` String text = readFileAsString("textfile.txt").replace("\n", "$").replace("\r", ""); ```
26,833,587
I have the next little code, it has to read a file and when it finds an `\n` or an `\r` it substitutes it with a `$`. The file is this: ``` for A27y= + 1643.2 - 642 : b end F017 = 3.5 ``` and here is the code: ``` public static void main(String[] args){ int car; String l = ""; try { File file = new File("openFile.txt"); RandomAccessFile af = new RandomAccessFile(file,"r"); while((car = af.read()) != -1) l += (char)car; l = l.replace('\n', '$').replace('\r', '$'); System.out.println(""+l); af.close(); } catch(IOException ex) { System.out.println("Cannot open file"); } } ``` The problem that I have is that every time it finds an '\n' or an '\r' in the file, instead of printing a single `$` it prints it double `$$`, and I don't understand why. It prints something like this: > > for A27y= + 1643.2 - 642 : b$$end$$$$F017 = 3.5$$ > > > when it should be like this: > > for A27y= + 1643.2 - 642 : b$end$$F017 = 3.5$ > > >
2014/11/09
[ "https://Stackoverflow.com/questions/26833587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3105533/" ]
Since some systems (Windows for example) use `\r\n` to represent end of line, you will sometimes get this behaviour for the code you are showing. You can fix this by first replacing these: ``` l = l.replace("\r\n", "$").replace('\n', '$').replace('\r', '$'); ```
The question is what the task actually is. If it's about finding actual `CR` and `LF` characters in the text and replacing each with a dollar sign, then you are getting the correct output. As others have already explained - on Windows each newline is composed of `CR``LF` together. If it's about finding newlines, and replacing each newline with a dollar sign, then you first need to ask yourself how you define a newline. What if you have a file where there are some separate `CR`s, some separate `LF`s and some together? If you want individual `CR` and `LF` characters to be replaced with `$` but also `CR``LF` to be replaced by a single `$`, you could try: ``` char lastChar = `\0`; while((car = af.read()) != -1) { char currChar = (char)car; if ( currChar == `\n` && lastChar != `\r` || currChar == `\r` ) { l += '$'; } else { l += currChar; } lastChar = currChar; } ``` If, however, you want to replace only what Windows considers a newline (that is, if the file is on Windows, only `CR``LF` are newlines so only they should be replaced with `$`), then you might change that to: ``` char lastChar = `\0`; while((car = af.read()) != -1) { char currChar = (char)car; if ( currChar == `\n` && lastChar == `\r` ) { l += '$' } else { l += currChar; } lastChar = currChar; } ``` This will keep individual `CR` and `LF` characters as they were, and only replace "real newline" combinations. So choose your definition, and you have your implementation.
14,193,607
I am working on a client-server application in which server sends the indication and client receives those indication.The Map is declared as ``` private static Map<key,value> obj=new HashMap<key,value>(); ``` The Map is getting the values through `synchronised(obj)` in constructor of the value Class ``` obj.put(this,this); ``` I am trying to retrieve the all the keys for this Map. I used `Set<key> t=Map.KeySet();` but this throws a compile error saying can not found symbol :KeySet() in interface `java.util.Map.` Note:key is interface and value is the class in which Map is Declared.
2013/01/07
[ "https://Stackoverflow.com/questions/14193607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1838314/" ]
As you have written ``` private static Map<key,value> obj=new HashMap<key,value>(); ``` You should write ``` Set<key> t=obj.keySet(); ``` instead of `Set<key> t=Map.KeySet();`
There is no KeySet method on Map, keySet is the correct method for getting the keys
14,193,607
I am working on a client-server application in which server sends the indication and client receives those indication.The Map is declared as ``` private static Map<key,value> obj=new HashMap<key,value>(); ``` The Map is getting the values through `synchronised(obj)` in constructor of the value Class ``` obj.put(this,this); ``` I am trying to retrieve the all the keys for this Map. I used `Set<key> t=Map.KeySet();` but this throws a compile error saying can not found symbol :KeySet() in interface `java.util.Map.` Note:key is interface and value is the class in which Map is Declared.
2013/01/07
[ "https://Stackoverflow.com/questions/14193607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1838314/" ]
Check the Map API once. Map is interface and you are trying to use the keySet() like you call a static method. You should call the methods on the object created. you should use `obj.keySet()` [Map Api](http://docs.oracle.com/javase/6/docs/api/java/util/Map.html#keySet%28%29)
There is no KeySet method on Map, keySet is the correct method for getting the keys
36,954,889
My application have several components and I want that each component will write logs to a separate file. I wanted to use the "Text multi-file backend" but according to the documentation it does not support file rotation. So my idea was to implement a log class and make an instant for each of the components and store them in a map, that way I can use the map to get the correct logger instance (according to the name) and log to the correct file. I have done this but this is not working for me, I can see the same messages in all of the files (it seems that this is a global logger). This is a draft of my code: logger.h ``` struct LogInfo{ std::string log_path; LogLevel log_level; long log_file_size; int log_file_amount; }; LogLevel stringToLogLevel(const std::string &fileType); class Logger { public: Logger(const LogInfo &log_info, const std::string &component_name); void writeToLog(LogLevel log_level, const std::string &scope, const std::string &message); private: void scanForFiles(const std::string &path, const std::string &component_name); std::string pid; std::string log_file_name; boost::log::sources::severity_logger<boost::log::trivial::severity_level> boost_severity_logger; }; ``` logger.cpp ``` using namespace boost::log; using namespace std; namespace fs = boost::filesystem; LogLevel stringToLogLevel(const string &fileType) { if (fileType == "TRACE") return LOGLEVEL_TRACE; if (fileType == "DEBUG") return LOGLEVEL_DEBUG; if (fileType == "INFO") return LOGLEVEL_INFO; if (fileType == "WARNING") return LOGLEVEL_WARNING; if (fileType == "ERROR") return LOGLEVEL_ERROR; throw invalid_argument("Unknown file type"); } trivial::severity_level logLevelToBoostLogLevel(const LogLevel log_level) { if (log_level == LOGLEVEL_TRACE) return trivial::trace; if (log_level == LOGLEVEL_DEBUG) return trivial::debug; if (log_level == LOGLEVEL_INFO) return trivial::info; if (log_level == LOGLEVEL_WARNING) return trivial::warning; if (log_level == LOGLEVEL_ERROR) return trivial::error; throw invalid_argument("Unknown log type"); } Logger::Logger(const LogInfo &log_info, const string &component_name) { scanForFiles(log_info.log_path, component_name); stringstream s; s << log_info.log_path << component_name << "_%N.log"; add_file_log( keywords::file_name = s.str(), keywords::rotation_size = log_info.log_file_size, keywords::max_size = log_info.log_file_amount * log_info.log_file_size, keywords::target = log_info.log_path, keywords::open_mode = std::ios::out | std::ios::app, keywords::auto_flush = true, keywords::format = expressions::format("[%1%] [%2%] [%3%] [%4%] %5%") % expressions::format_date_time< boost::posix_time::ptime >("TimeStamp", "%Y-%m-%d %H:%M:%S.%f") % expressions::attr<unsigned int>("ThreadID") % expressions::attr<string>("Scope") % trivial::severity % expressions::smessage ); trivial::severity_level requested_level = logLevelToBoostLogLevel(log_info.log_level); core::get()->set_filter( trivial::severity >= requested_level ); add_common_attributes(); } void Logger::writeToLog(LogLevel log_level, const std::string &scope, const std::string &message) { BOOST_LOG_SCOPED_THREAD_ATTR("ThreadID", attributes::constant<unsigned int>(OS::getTid())); BOOST_LOG_SCOPED_THREAD_ATTR("Scope", attributes::constant<string>(scope)); BOOST_LOG_SEV(this->boost_severity_logger, logLevelToBoostLogLevel(log_level))<< message.c_str(); } ``` Is it possible to achieve what I want?
2016/04/30
[ "https://Stackoverflow.com/questions/36954889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4914961/" ]
See [this](https://stackoverflow.com/questions/34362871/use-channel-hiearchy-of-boost-log-for-severity-and-sink-filtering/34372526#34372526) reply. Among other things, it describes how to use channels and filters to achieve what you want.
To separate log files you can add filter to the added log file, in that way file rotation will work fine and each of your components will have their own log file: ``` logging::add_file_log( keywords::file_name = s.str(), keywords::rotation_size = log_info.log_file_size, keywords::max_size = log_info.log_file_amount * log_info.log_file_size, keywords::filter = expr::attr< std::string >([ATTRIBUTE/TAG]) == [ex. COMPONENT_NAME], keywords::target = log_info.log_path, keywords::open_mode = std::ios::out | std::ios::app, keywords::auto_flush = true, keywords::format = expressions::format("[%1%] [%2%] [%3%] [%4%] %5%") % expressions::format_date_time< boost::posix_time::ptime >("TimeStamp", "%Y-%m-%d %H:%M:%S.%f") % expressions::attr<unsigned int>("ThreadID") % expressions::attr<string>("Scope") % trivial::severity % expressions::smessage ); ``` While logging the attribute should be set and so the message will be written on corresponding log file, for instance: ``` void Logger::writeToLog(LogLevel log_level, const std::string &scope, const std::string &message) { ... BOOST_LOG_SCOPED_THREAD_TAG([ATT/TAG], [VALUE]); // Add Component name here BOOST_LOG_SEV(this->boost_severity_logger, logLevelToBoostLogLevel(log_level))<< message.c_str(); } ```
64,913,270
I'm having hard time figuring out how to make the pipeline use the restored cache of npm modules. Here's the manifest file: ``` jobs: setup-build-push-deploy: name: Setup, Build, Push, and Deploy runs-on: ubuntu-latest steps: # Checkout the repo - name: Checkout uses: actions/checkout@v2 - name: Setup NodeJS uses: actions/setup-node@v1 with: node-version: '12.14' # Cache the npm node modules - name: Cache node modules uses: actions/cache@v1 id: cache-node-modules env: CACHE_NAME: cache-node-modules with: # npm cache files are stored in `~/.npm` on Linux/macOS path: ~/.npm key: ${{ env.CACHE_NAME }}-${{ hashFiles('app/package-lock.json') }} restore-keys: | ${{ env.CACHE_NAME }}- # Install NPM dependencies - name: Install Dependencies if: steps.cache-node-modules.outputs.cache-hit != 'true' run: | cd app/ npm install # Compile Typescript to Javascript - name: Compile Typescript run: | cd app/ npm run make ``` The "cache" step does make a successful cache hit, and therefore the "install dependencies" step is skipped. But then the "compile" step fails, because it cannot find any installed npm modules. [![enter image description here](https://i.stack.imgur.com/bpUTN.png)](https://i.stack.imgur.com/bpUTN.png) The docs [here](https://github.com/actions/cache/blob/main/examples.md#node---npm) and [here](https://docs.github.com/en/free-pro-team@latest/actions/guides/caching-dependencies-to-speed-up-workflows#using-the-cache-action) and the SO question, eg. [here](https://stackoverflow.com/questions/64226272/caching-npm-dependency-with-github-action), do not specify any *certain* step or configuration that points towards *where to pick up the cached modules from*. Seems like they should be picked up automatically from `~/.npm`, but that's not the case.
2020/11/19
[ "https://Stackoverflow.com/questions/64913270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1430394/" ]
`**kwargs` are just dicts of `str: object`, so you can have the wrapper take a *key name*, create a dict out of that, and using that to call the wrapped function: ```py def wrapperfunc(key): val = [10, 20, 30] for v in val: load_data(**{key: v}) wrapperfunc('remove_smallest') wrapperfunc('remove_largest') ```
No, keyword arguments are purely *syntactic*, though the name and value are collected in a `dict` if the name does not correspond to a named parameter. The closest you can do is pass a `str` value, then pass an unpacked `dict` to `load_data`. ``` def wrapper(arg): val = [10, 20, 30] for v in val: load_data(**{arg: v}) wrapper('remove_smallest') ```
33,062,016
I have this vector `myvec`. I want to remove everything after second ':' and get the result. How do I remove the string after nth ':'? ``` myvec<- c("chr2:213403244:213403244:G:T:snp","chr7:55240586:55240586:T:G:snp" ,"chr7:55241607:55241607:C:G:snp") result chr2:213403244 chr7:55240586 chr7:55241607 ```
2015/10/11
[ "https://Stackoverflow.com/questions/33062016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4701887/" ]
We can use `sub`. We match one or more characters that are not `:` from the start of the string (`^([^:]+`) followed by a `:`, followed by one more characters not a `:` (`[^:]+`), place it in a capture group i.e. within the parentheses. We replace by the capture group (`\\1`) in the replacement. ``` sub('^([^:]+:[^:]+).*', '\\1', myvec) #[1] "chr2:213403244" "chr7:55240586" "chr7:55241607" ``` The above works for the example posted. For general cases to remove after the nth delimiter, ``` n <- 2 pat <- paste0('^([^:]+(?::[^:]+){',n-1,'}).*') sub(pat, '\\1', myvec) #[1] "chr2:213403244" "chr7:55240586" "chr7:55241607" ``` Checking with a different 'n' ``` n <- 3 ``` and repeating the same steps ``` sub(pat, '\\1', myvec) #[1] "chr2:213403244:213403244" "chr7:55240586:55240586" #[3] "chr7:55241607:55241607" ``` --- Or another option would be to split by `:` and then `paste` the n number of components together. ``` n <- 2 vapply(strsplit(myvec, ':'), function(x) paste(x[seq.int(n)], collapse=':'), character(1L)) #[1] "chr2:213403244" "chr7:55240586" "chr7:55241607" ```
Here are a few alternatives. We delete the kth colon and everything after it. The example in the question would correspond to k = 2. In the examples below we use k = 3. **1) read.table** Read the data into a data.frame, pick out the columns desired and paste it back together again: ``` k <- 3 # keep first 3 fields only do.call(paste, c(read.table(text = myvec, sep = ":")[1:k], sep = ":")) ``` giving: ``` [1] "chr2:213403244:213403244" "chr7:55240586:55240586" [3] "chr7:55241607:55241607" ``` **2) sprintf/sub** Construct the appropriate regular expression (in the case below of k equal to 3 it would be `^((.*?:){2}.*?):.*` ) and use it with `sub`: ``` k <- 3 sub(sprintf("^((.*?:){%d}.*?):.*", k-1), "\\1", myvec) ``` giving: ``` [1] "chr2:213403244:213403244" "chr7:55240586:55240586" [3] "chr7:55241607:55241607" ``` **Note 1:** For k=1 this can be further simplified to `sub(":.*", "", myvec)` and for k=n-1 it can be further simplified to `sub(":[^:]*$", "", myvec)` **Note 2:** Here is a visualization of the regular regular expression for `k` equal to 3: ``` ^((.*?:){2}.*?):.* ``` ![Regular expression visualization](https://www.debuggex.com/i/C8MSTUM9sPxE1-hj.png) [Debuggex Demo](https://www.debuggex.com/r/C8MSTUM9sPxE1-hj) **3) iteratively delete last field** We could remove the last field `n-k` times using the last regular expression in Note 1 above like this: ``` n <- 6 # number of fields k < - 3 # number of fields to retain out <- myvec for(i in seq_len(n-k)) out <- sub(":[^:]*$", "", out) ``` If we wanted to set n automatically we could optionally replace the hard coded line setting n above with this: ``` n <- count.fields(textConnection(myvec[1]), sep = ":") ``` **4) locate position of kth colon** Locate the positions of the colons using `gregexpr` and then extract the location of the kth subtracting one from it since we don't want the trailing colon. Use `substr` to extract that many characters from the respective strings. ``` k <- 3 substr(myvec, 1, sapply(gregexpr(":", myvec), "[", k) - 1) ``` giving: ``` [1] "chr2:213403244:213403244" "chr7:55240586:55240586" [3] "chr7:55241607:55241607" ``` **Note 3:** Suppose there are n fields. The question asked to delete everything after the kth delimiter so the solution should work for k = 1, 2, ..., n-1. It need not work for k = n since there are not n delimiters; however, if instead we define k as the number of fields to return then k = n makes sense and, in fact, (1) and (3) work in that case too. (2) and (4) do not work for this extension but we can easily get them to work by using `paste0(myvec, ":")` as the input instead of `myvec`. **Note 4:** We compare performance: ``` library(rbenchmark) benchmark( .read.table = do.call(paste, c(read.table(text = myvec, sep = ":")[1:k], sep = ":")), .sprintf.sub = sub(sprintf("^((.*?:){%d}.*?):.*", k-1), "\\1", myvec), .for = { out <- myvec; for(i in seq_len(n-k)) out <- sub(":[^:]*$", "", out)}, .gregexpr = substr(myvec, 1, sapply(gregexpr(":", myvec), "[", k) - 1), order = "elapsed", replications = 1000)[1:4] ``` giving: ``` test replications elapsed relative 2 .sprintf.sub 1000 0.11 1.000 4 .gregexpr 1000 0.14 1.273 3 .for 1000 0.15 1.364 1 .read.table 1000 2.16 19.636 ``` The solution using sprintf and sub is the fastest although it does use a complex regular expression whereas the others use simpler or no regular expressions and might be preferred on grounds of simplicity. **ADDED** Added additional solutions and additional notes.
996,795
What are the odds of 7 straight spins on a roulette wheel rendering a number within the same group of 12 numbers? (i.e. 7 numbers within 1-12, 7 within 13-24 or 7 within 25-36). This would be a natural streak of 7 straight within the same group and no spins hitting 0 or 00. Thank you for your help! Mike
2014/10/29
[ "https://math.stackexchange.com/questions/996795", "https://math.stackexchange.com", "https://math.stackexchange.com/users/188298/" ]
If you literally mean "all the time", then the probability is $1$. Prime factorization is a necessarily finite process. You end up with **some** answer at the end, even if it's that the only prime factor of the number is the number itself. If you **don't** literally mean "all the time", but perhaps only "a few hours every day for a year", then the probability directly depends on how fast your laptop searches through possible factors.
It's highly unlikely. Looking at the page Dietrich linked, you will see that a factorization for $m = 12, k = 7$ discovered by Pervushin and Lucas in 1877 is still "known to be incomplete"! After more than a century! I've been alive almost a century but already three laptops have died on me, and I didn't even subject them to such intense number crunching. If you're serious about this, you're going to need a good, strong, sturdy desktop computer devoted to running the most efficient algorithm you can get your hands on. And also some kind of back-up system. Good luck with that.
996,795
What are the odds of 7 straight spins on a roulette wheel rendering a number within the same group of 12 numbers? (i.e. 7 numbers within 1-12, 7 within 13-24 or 7 within 25-36). This would be a natural streak of 7 straight within the same group and no spins hitting 0 or 00. Thank you for your help! Mike
2014/10/29
[ "https://math.stackexchange.com/questions/996795", "https://math.stackexchange.com", "https://math.stackexchange.com/users/188298/" ]
There is no fixed probability of finding a factor and depends on the number you select and the processing speed of your computer. It also depends on how long you are going to run it. You can see [this link](http://en.wikipedia.org/wiki/Fermat_number#Factorization_of_Fermat_numbers) for known factors and how much computational power it actually takes o find them.
It's highly unlikely. Looking at the page Dietrich linked, you will see that a factorization for $m = 12, k = 7$ discovered by Pervushin and Lucas in 1877 is still "known to be incomplete"! After more than a century! I've been alive almost a century but already three laptops have died on me, and I didn't even subject them to such intense number crunching. If you're serious about this, you're going to need a good, strong, sturdy desktop computer devoted to running the most efficient algorithm you can get your hands on. And also some kind of back-up system. Good luck with that.
443,991
I'd like to parse rss feeds and download [podcasts](https://blog.stackoverflow.com/category/podcasts/) on my ReadyNas which is running 24/7 anyway. So I'm thinking about having a shell script checking periodically the feeds and spawning wget to download the files. What is the best way to do the parsing? Thanks!
2009/01/14
[ "https://Stackoverflow.com/questions/443991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15296/" ]
Do you have access to awk? Maybe you could use [XMLGawk](http://home.vrweb.de/~juergen.kahrs/gawk/XML/)
I read about [XMLStartlet](http://xmlstar.sourceforge.net/) [here](http://codesnippets.joyent.com/posts/show/1909) and [there](http://bashcurescancer.com/the-best-in-command-line-xml-xmlstarlet.html) But is there a port to ReadyNas NV+ available?
443,991
I'd like to parse rss feeds and download [podcasts](https://blog.stackoverflow.com/category/podcasts/) on my ReadyNas which is running 24/7 anyway. So I'm thinking about having a shell script checking periodically the feeds and spawning wget to download the files. What is the best way to do the parsing? Thanks!
2009/01/14
[ "https://Stackoverflow.com/questions/443991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15296/" ]
I read about [XMLStartlet](http://xmlstar.sourceforge.net/) [here](http://codesnippets.joyent.com/posts/show/1909) and [there](http://bashcurescancer.com/the-best-in-command-line-xml-xmlstarlet.html) But is there a port to ReadyNas NV+ available?
You can use xsltproc from [libxml2](http://xmlsoft.org/) and write a simple xsl stylesheet that parses the rss and outputs a list of links.
443,991
I'd like to parse rss feeds and download [podcasts](https://blog.stackoverflow.com/category/podcasts/) on my ReadyNas which is running 24/7 anyway. So I'm thinking about having a shell script checking periodically the feeds and spawning wget to download the files. What is the best way to do the parsing? Thanks!
2009/01/14
[ "https://Stackoverflow.com/questions/443991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15296/" ]
Sometimes a simple one liner with shell standard commands can be enough for this: ``` wget -q -O- "http://www.rss-specifications.com/rss-podcast.xml" | grep -o '<enclosure url="[^"]*' | grep -o '[^"]*$' | xargs wget -c ``` Sure this does not work in every case, but it's often good enough.
I read about [XMLStartlet](http://xmlstar.sourceforge.net/) [here](http://codesnippets.joyent.com/posts/show/1909) and [there](http://bashcurescancer.com/the-best-in-command-line-xml-xmlstarlet.html) But is there a port to ReadyNas NV+ available?
443,991
I'd like to parse rss feeds and download [podcasts](https://blog.stackoverflow.com/category/podcasts/) on my ReadyNas which is running 24/7 anyway. So I'm thinking about having a shell script checking periodically the feeds and spawning wget to download the files. What is the best way to do the parsing? Thanks!
2009/01/14
[ "https://Stackoverflow.com/questions/443991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15296/" ]
Do you have access to awk? Maybe you could use [XMLGawk](http://home.vrweb.de/~juergen.kahrs/gawk/XML/)
You can use xsltproc from [libxml2](http://xmlsoft.org/) and write a simple xsl stylesheet that parses the rss and outputs a list of links.
443,991
I'd like to parse rss feeds and download [podcasts](https://blog.stackoverflow.com/category/podcasts/) on my ReadyNas which is running 24/7 anyway. So I'm thinking about having a shell script checking periodically the feeds and spawning wget to download the files. What is the best way to do the parsing? Thanks!
2009/01/14
[ "https://Stackoverflow.com/questions/443991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15296/" ]
Sometimes a simple one liner with shell standard commands can be enough for this: ``` wget -q -O- "http://www.rss-specifications.com/rss-podcast.xml" | grep -o '<enclosure url="[^"]*' | grep -o '[^"]*$' | xargs wget -c ``` Sure this does not work in every case, but it's often good enough.
Do you have access to awk? Maybe you could use [XMLGawk](http://home.vrweb.de/~juergen.kahrs/gawk/XML/)
443,991
I'd like to parse rss feeds and download [podcasts](https://blog.stackoverflow.com/category/podcasts/) on my ReadyNas which is running 24/7 anyway. So I'm thinking about having a shell script checking periodically the feeds and spawning wget to download the files. What is the best way to do the parsing? Thanks!
2009/01/14
[ "https://Stackoverflow.com/questions/443991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15296/" ]
Do you have access to awk? Maybe you could use [XMLGawk](http://home.vrweb.de/~juergen.kahrs/gawk/XML/)
I've wrote the following simple script for downloading XML from Amazon S3, so it would be useful for parsing different kind of XML files: ``` #!/bin/bash # # Download all files from the Amazon feed # # Usage: # ./dl_amazon_feed_files.sh http://example.s3.amazonaws.com/ # Note: Don't forget about slash at the end # wget -qO- "$1" | grep -o '<Key>[^<]*' | grep -o "[^>]*$" | xargs -I% -L1 wget -c "$1%" ``` This is similar approach to [@leo answer](https://stackoverflow.com/a/446217/55075).
443,991
I'd like to parse rss feeds and download [podcasts](https://blog.stackoverflow.com/category/podcasts/) on my ReadyNas which is running 24/7 anyway. So I'm thinking about having a shell script checking periodically the feeds and spawning wget to download the files. What is the best way to do the parsing? Thanks!
2009/01/14
[ "https://Stackoverflow.com/questions/443991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15296/" ]
Sometimes a simple one liner with shell standard commands can be enough for this: ``` wget -q -O- "http://www.rss-specifications.com/rss-podcast.xml" | grep -o '<enclosure url="[^"]*' | grep -o '[^"]*$' | xargs wget -c ``` Sure this does not work in every case, but it's often good enough.
You can use xsltproc from [libxml2](http://xmlsoft.org/) and write a simple xsl stylesheet that parses the rss and outputs a list of links.
443,991
I'd like to parse rss feeds and download [podcasts](https://blog.stackoverflow.com/category/podcasts/) on my ReadyNas which is running 24/7 anyway. So I'm thinking about having a shell script checking periodically the feeds and spawning wget to download the files. What is the best way to do the parsing? Thanks!
2009/01/14
[ "https://Stackoverflow.com/questions/443991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15296/" ]
I've wrote the following simple script for downloading XML from Amazon S3, so it would be useful for parsing different kind of XML files: ``` #!/bin/bash # # Download all files from the Amazon feed # # Usage: # ./dl_amazon_feed_files.sh http://example.s3.amazonaws.com/ # Note: Don't forget about slash at the end # wget -qO- "$1" | grep -o '<Key>[^<]*' | grep -o "[^>]*$" | xargs -I% -L1 wget -c "$1%" ``` This is similar approach to [@leo answer](https://stackoverflow.com/a/446217/55075).
You can use xsltproc from [libxml2](http://xmlsoft.org/) and write a simple xsl stylesheet that parses the rss and outputs a list of links.
443,991
I'd like to parse rss feeds and download [podcasts](https://blog.stackoverflow.com/category/podcasts/) on my ReadyNas which is running 24/7 anyway. So I'm thinking about having a shell script checking periodically the feeds and spawning wget to download the files. What is the best way to do the parsing? Thanks!
2009/01/14
[ "https://Stackoverflow.com/questions/443991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15296/" ]
Sometimes a simple one liner with shell standard commands can be enough for this: ``` wget -q -O- "http://www.rss-specifications.com/rss-podcast.xml" | grep -o '<enclosure url="[^"]*' | grep -o '[^"]*$' | xargs wget -c ``` Sure this does not work in every case, but it's often good enough.
I've wrote the following simple script for downloading XML from Amazon S3, so it would be useful for parsing different kind of XML files: ``` #!/bin/bash # # Download all files from the Amazon feed # # Usage: # ./dl_amazon_feed_files.sh http://example.s3.amazonaws.com/ # Note: Don't forget about slash at the end # wget -qO- "$1" | grep -o '<Key>[^<]*' | grep -o "[^>]*$" | xargs -I% -L1 wget -c "$1%" ``` This is similar approach to [@leo answer](https://stackoverflow.com/a/446217/55075).
478,095
I use a 60GB SSD for the `C:` partition where Windows and other essential programs are installed, using a larger mechanical HDD for `D:`, and I repeatedly find myself short of disk space on `C:`, with the main culprits being folders within `%LocalAppData%` [Picasa & Outlook files]. How can I move these folders to `D:`, recovering space on `C:`?
2012/09/21
[ "https://superuser.com/questions/478095", "https://superuser.com", "https://superuser.com/users/9814/" ]
1. Open the `%LocalAppData%` Properties dialog 2. Location tab → Enter desired new location 3. Move
How about using `mklink` to create a symbolic link: 1. ``` MkLink /d C:\Users\Nikhil\AppData\Local D:\AppData\Local ``` * *I haven't tried this, so maybe give it a test drive in a VM first; you may also have to create separate symbolic links for each subfolder* 2. Move all the files/folders from the `%LocalAppData%` to `D:\AppData\Local` 3. Delete `%UserProfile\AppData\Local`
478,095
I use a 60GB SSD for the `C:` partition where Windows and other essential programs are installed, using a larger mechanical HDD for `D:`, and I repeatedly find myself short of disk space on `C:`, with the main culprits being folders within `%LocalAppData%` [Picasa & Outlook files]. How can I move these folders to `D:`, recovering space on `C:`?
2012/09/21
[ "https://superuser.com/questions/478095", "https://superuser.com", "https://superuser.com/users/9814/" ]
It's possible to move Outlook `.pst` files to a different location, changing your profile to point to the new location: * [How to manage `.pst` files in Microsoft Outlook](http://support.microsoft.com/kb/291636)
While it's not recommended to move the entire `%AppData%` folder, if you have folders that are taking up a lot of space (`Pictures`, `Documents`, etc.), these can be easily moved to another partition: 1. File Explorer → Right-click on `%UserProfile%\Pictures` → *Properties* ![Pictures Properties Image Example](https://i.stack.imgur.com/jS3nB.png) 2. Tab: *Location* → Change directory to the desired location (e.g. `D:\Pictures`) → OK * If you have OneDrive set up, you may run into an issue here; in this case, you need to make a change to the Registry: 1. Open OneDrive → Settings → Backup 2. Deselect the desired folder (e.g. `Pictures`) → Save 3. `[![WinKey](https://i.stack.imgur.com/dHzy6.png)](https://i.stack.imgur.com/dHzy6.png)`+`R` → `regedit` → OK 4. Navigate to: ``` HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders ``` ![Registry Entry Image Example](https://i.stack.imgur.com/mydp7.png) 5. Change the value of `My Pictures` to the desired folder (e.g. `D:\Pictures`). You can also change all of the `%UserProfile%` data folders (`Documents`, `Downloads`, etc.) 6. You should be able to move the directories you specified in the Registry via the directory's *Properties* → *Location* tab If you want to continue backing up these folders in OneDrive, go back into your OneDrive settings and select the new location to sync.
478,095
I use a 60GB SSD for the `C:` partition where Windows and other essential programs are installed, using a larger mechanical HDD for `D:`, and I repeatedly find myself short of disk space on `C:`, with the main culprits being folders within `%LocalAppData%` [Picasa & Outlook files]. How can I move these folders to `D:`, recovering space on `C:`?
2012/09/21
[ "https://superuser.com/questions/478095", "https://superuser.com", "https://superuser.com/users/9814/" ]
This isn't an answer to your question but probably a solution to your problem, as I'm thinking: * Generally, `C:\Hiberfil.sys` is huge and since you don't need hibernation with an SSD as it lowers boot time, disable hibernation via an Admin terminal: ``` PowerCfg –h Off ``` On my system, this freed 12GB since `hiberfil.sys` is no longer needed, and, for me, this would be a much better solution than moving the `%LocalAppData%` since moving it to a mechanical HDD would slow down drive-access for every affected program, thus defeating the purpose of the SSD.
It's possible to move Outlook `.pst` files to a different location, changing your profile to point to the new location: * [How to manage `.pst` files in Microsoft Outlook](http://support.microsoft.com/kb/291636)
478,095
I use a 60GB SSD for the `C:` partition where Windows and other essential programs are installed, using a larger mechanical HDD for `D:`, and I repeatedly find myself short of disk space on `C:`, with the main culprits being folders within `%LocalAppData%` [Picasa & Outlook files]. How can I move these folders to `D:`, recovering space on `C:`?
2012/09/21
[ "https://superuser.com/questions/478095", "https://superuser.com", "https://superuser.com/users/9814/" ]
How about using `mklink` to create a symbolic link: 1. ``` MkLink /d C:\Users\Nikhil\AppData\Local D:\AppData\Local ``` * *I haven't tried this, so maybe give it a test drive in a VM first; you may also have to create separate symbolic links for each subfolder* 2. Move all the files/folders from the `%LocalAppData%` to `D:\AppData\Local` 3. Delete `%UserProfile\AppData\Local`
Using the registry method within [Shell Folder/User Shell Folder](http://www.tweaklibrary.com/System/Application-Path/71/Change-default-location-of-the-%E2%80%9CApplication-Data%E2%80%9D-folder/10471/), folder redirection for all subsequent data will be saved at the new location by default: * Microsoft's [Deploy Folder Redirection with Offline Files](http://support.microsoft.com/kb/242557) article shows how to change the location of the `Desktop` folder by using folder redirection. *(replace `Desktop` with `AppData`, `Start Menu`, etc.)*
478,095
I use a 60GB SSD for the `C:` partition where Windows and other essential programs are installed, using a larger mechanical HDD for `D:`, and I repeatedly find myself short of disk space on `C:`, with the main culprits being folders within `%LocalAppData%` [Picasa & Outlook files]. How can I move these folders to `D:`, recovering space on `C:`?
2012/09/21
[ "https://superuser.com/questions/478095", "https://superuser.com", "https://superuser.com/users/9814/" ]
Microsoft [does not](https://support.microsoft.com/kb/949977?wa=wsignin1.0) recommend moving `%AppData%` off the system partition. * Use [TreeSize Free](http://www.jam-software.com/treesize_free/) to see if there other ways to remove files, as sometimes `C:\hiberfile.sys` and `C:\pagefile.sys` are candidates * `%LocalAppData%\Temp` could be redirected to a mechanical HDD You should really consider getting a bigger SSD, as you want to run with at least 30% free so the SSD has vacant blocks to write to; running at 99% full on an SSD increases wear level, with the performance you come to expect from SSD being greatly diminished.
Over a period of time, I mysteriously lost 100gb HD space within Win 7 Home Premium, with *Space Monger* reporting it was from subfolders within `%UserProfile%\AppData`, which I think are hidden files. * Research online suggested that since these are temporary user files, I could delete them, which I did via Space Monger, recovering 100GB with no noticeable ill effects.
478,095
I use a 60GB SSD for the `C:` partition where Windows and other essential programs are installed, using a larger mechanical HDD for `D:`, and I repeatedly find myself short of disk space on `C:`, with the main culprits being folders within `%LocalAppData%` [Picasa & Outlook files]. How can I move these folders to `D:`, recovering space on `C:`?
2012/09/21
[ "https://superuser.com/questions/478095", "https://superuser.com", "https://superuser.com/users/9814/" ]
1. Open the `%LocalAppData%` Properties dialog 2. Location tab → Enter desired new location 3. Move
Login using *Safe mode*: 1. Press `F8` at boot and select *Safe Mode* from the menu 2. Navigate to `%AppData%` → Right-click `LocalLow` and/or `Roaming` → *Properties* * *You can't safely move `%LocalAppData%` since it's also being used in Safe Mode, but the `Roaming` and `LocalLow` folders hold great potential for space recovery.* 3. Tab: *Location* → Move
478,095
I use a 60GB SSD for the `C:` partition where Windows and other essential programs are installed, using a larger mechanical HDD for `D:`, and I repeatedly find myself short of disk space on `C:`, with the main culprits being folders within `%LocalAppData%` [Picasa & Outlook files]. How can I move these folders to `D:`, recovering space on `C:`?
2012/09/21
[ "https://superuser.com/questions/478095", "https://superuser.com", "https://superuser.com/users/9814/" ]
This isn't an answer to your question but probably a solution to your problem, as I'm thinking: * Generally, `C:\Hiberfil.sys` is huge and since you don't need hibernation with an SSD as it lowers boot time, disable hibernation via an Admin terminal: ``` PowerCfg –h Off ``` On my system, this freed 12GB since `hiberfil.sys` is no longer needed, and, for me, this would be a much better solution than moving the `%LocalAppData%` since moving it to a mechanical HDD would slow down drive-access for every affected program, thus defeating the purpose of the SSD.
Over a period of time, I mysteriously lost 100gb HD space within Win 7 Home Premium, with *Space Monger* reporting it was from subfolders within `%UserProfile%\AppData`, which I think are hidden files. * Research online suggested that since these are temporary user files, I could delete them, which I did via Space Monger, recovering 100GB with no noticeable ill effects.
478,095
I use a 60GB SSD for the `C:` partition where Windows and other essential programs are installed, using a larger mechanical HDD for `D:`, and I repeatedly find myself short of disk space on `C:`, with the main culprits being folders within `%LocalAppData%` [Picasa & Outlook files]. How can I move these folders to `D:`, recovering space on `C:`?
2012/09/21
[ "https://superuser.com/questions/478095", "https://superuser.com", "https://superuser.com/users/9814/" ]
This isn't an answer to your question but probably a solution to your problem, as I'm thinking: * Generally, `C:\Hiberfil.sys` is huge and since you don't need hibernation with an SSD as it lowers boot time, disable hibernation via an Admin terminal: ``` PowerCfg –h Off ``` On my system, this freed 12GB since `hiberfil.sys` is no longer needed, and, for me, this would be a much better solution than moving the `%LocalAppData%` since moving it to a mechanical HDD would slow down drive-access for every affected program, thus defeating the purpose of the SSD.
I just recently did something about this to move 100gb of data. First of all, I did not try to move the whole appdata. Instead, I search in appdata to find where It consumes the most space. Turns out, the adobe folder was getting about 70 gb. So I did a joint folder with a mklink. First, I created the folder D:\mklinks\appdata\adobe. The name here is purely organizational. Second, I copied the contents of C:\users\user\appdata\roaming\adobe to the folder in D. Third, I ran command prompt in administrator mode. There I entered the command MkLink /J "C:\Users\User\AppData\roaming\adobe\linkadobe" "D:\mklinks\AppData\adobe" The /J will create a joint connection named linkadobe, which will look like a shortcut. But all the adobe programs kept running smoothly (the only complain is the icon on the taskbar changed to a blank icon). The name "linkadobe" is just my own chosen pattern. The citations are necessary in case any folder is not single word named. I repeated the process for a few more big folder and did not see any problems so far. I just checked the adobe folder as I was writting these. It seems that adobe recreated all the folders there were on the original directory, but the folder is 19mb so far.