qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
1,061,785
So, this may sound stupid but I don't really get it. When I visited <http://www.themidnightcoders.com> and download WebOrb for .NET. After I finished product setup progress, I realize that the product that I just downloaded and setup in my machine was "Enterprise Edition in Development mode" Because when I go into the product web console page. It tell me that, it's in development mode and limit for on 5 IP Addresses. When I return to download-page of WebOrb site I only found one product for download and it's the one that I just downloaded. So I want to use WebOrb for .NET Community Edition but I have not found it yet. May you please tell me the solution of this problem? Thank you
2009/06/30
[ "https://Stackoverflow.com/questions/1061785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Here's Joel's article on Function Design documents. <http://www.joelonsoftware.com/articles/fog0000000036.html>
Joel Spolsky posted the functional spec to his CoPilot application along with a brief blog post about it. <http://www.joelonsoftware.com/articles/AardvarkSpec.html>
1,061,785
So, this may sound stupid but I don't really get it. When I visited <http://www.themidnightcoders.com> and download WebOrb for .NET. After I finished product setup progress, I realize that the product that I just downloaded and setup in my machine was "Enterprise Edition in Development mode" Because when I go into the product web console page. It tell me that, it's in development mode and limit for on 5 IP Addresses. When I return to download-page of WebOrb site I only found one product for download and it's the one that I just downloaded. So I want to use WebOrb for .NET Community Edition but I have not found it yet. May you please tell me the solution of this problem? Thank you
2009/06/30
[ "https://Stackoverflow.com/questions/1061785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Here's Joel's article on Function Design documents. <http://www.joelonsoftware.com/articles/fog0000000036.html>
If you are looking for books, I can recommend two right now, and in fact, I ordered a third because it looked good. The two I can recommend fully are: * [Software Requirements (2nd Edition)](https://rads.stackoverflow.com/amzn/click/com/0735618798) * [More about Software Requirements](https://rads.stackoverflow.com/amzn/click/com/0735622671) I also ordered a third book: * [Software Requirements Patterns](https://rads.stackoverflow.com/amzn/click/com/0735623988)
21,541,839
I am new bie to hibernate and i am facing one issue. I have fetched the record from database and displayed the values on Jsp form. I want to update some of the values i have displayed I made the ID of the entity hidden form field. When i click on submit the values which are not on form are set to be null. Everytime i have to update the record i have to manually set all the values again to the object and then save Example I have user entity having the following fields Id firstName lastName dateUpdated dateCreated In my jsp i have only two fields firstName lastName and on hidden form field Id In my controller i am creating new obj of User and setting these three values I am updating my record using merge method. on merging DateCreated and dateUpdated are getting null! How can i achieve it without fetching the record and setting the modified value and then saving it Regards Ramandeep S
2014/02/04
[ "https://Stackoverflow.com/questions/21541839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2613233/" ]
Strings in Java are *immutable*. Every time you use the concatenation operator (`+`) you're actually creating a new `String` object. Because you're starting with your `String` being `null` ... the conversion during the concatenation results in the word "null" in the result (this is specified in the JLS when using string concatenation). You *could* simply start with an empty `String` (e.g. `String webresponse = ""`) but that's still really inefficient due to the aforementioned immutability. You want to use a `StringBuilder`: ``` String line; StringBuilder sb = new StringBuilder(); while ((line = reader.readLine()) != null) { sb.append(line); } ``` **Edit:** I just noticed: *" that is generally a bad approach as I just initialized the var webresponse when it's not supposed to be (and can't check for null later)!"* `String` does provide a `.isEmpty()` method ... so I don't know what advantage `null` gives you, but you could simply check the length of the `StringBuilder` ``` String webresponse = null; if (sb.length() > 0) { webresponse = sb.toString(); } ```
In java you have to give default value to local variables. Local variables are those variables which are defined within methods. So you need to initialize your local variable with default value. You have defined with Null. So when you concatenate with this. It will add "Null" + your other values. To avoid this you can initalize your local variable with empty string e.q String ab=""; Second you are using String to concatenation is wrong. You are creating lots of String object. Instead you can use StringBuilder or StringBuffer. Right approach is to use StringBuilder if you are not worry about synchronization.
1,952,019
Say I have two process p1,p2 runnning as a part of my application. Say p1 is running initially executing function f1() and then f1() calls f2().With the invocation of f2() process p2 starts excuting What I want to confirm is it that :- 1)Do we have seperate stack for different process? 2)Do we have seperate heap for different process? or do different process share same heap? 3)As we know that for a 32 bit OS do for **every** process the size of virtual memory is 4GB .So is it that for every process which has 4GB as virtual memory this 4GB is partitioned into heap,stack,text,data Thanks.
2009/12/23
[ "https://Stackoverflow.com/questions/1952019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/232782/" ]
1) Yes, each process gets its own stack. 2) Yes, each process gets its own heap. 3) I don't think you get the whole 4GB. Some of it is reserved for kernel stuff.
* The virtual memory for a process will be different from other process. * Every process will get 4GB of virtual address space ( in 32 bit windows machine) and out of which you can use 2GB of user space ( remaining is for kernel). For stack, heap, static data storage and even loading the DLLs. (This is 3GB if you use large address space) * Every process will get separate heap, stack independent of other process.
1,952,019
Say I have two process p1,p2 runnning as a part of my application. Say p1 is running initially executing function f1() and then f1() calls f2().With the invocation of f2() process p2 starts excuting What I want to confirm is it that :- 1)Do we have seperate stack for different process? 2)Do we have seperate heap for different process? or do different process share same heap? 3)As we know that for a 32 bit OS do for **every** process the size of virtual memory is 4GB .So is it that for every process which has 4GB as virtual memory this 4GB is partitioned into heap,stack,text,data Thanks.
2009/12/23
[ "https://Stackoverflow.com/questions/1952019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/232782/" ]
* The virtual memory for a process will be different from other process. * Every process will get 4GB of virtual address space ( in 32 bit windows machine) and out of which you can use 2GB of user space ( remaining is for kernel). For stack, heap, static data storage and even loading the DLLs. (This is 3GB if you use large address space) * Every process will get separate heap, stack independent of other process.
There are other limitations to consider in Java too, such as only being able to address arrays using Integer.MAX\_VALUE at most. This limits you to about 2GB in a lot of areas relating to memory.
1,952,019
Say I have two process p1,p2 runnning as a part of my application. Say p1 is running initially executing function f1() and then f1() calls f2().With the invocation of f2() process p2 starts excuting What I want to confirm is it that :- 1)Do we have seperate stack for different process? 2)Do we have seperate heap for different process? or do different process share same heap? 3)As we know that for a 32 bit OS do for **every** process the size of virtual memory is 4GB .So is it that for every process which has 4GB as virtual memory this 4GB is partitioned into heap,stack,text,data Thanks.
2009/12/23
[ "https://Stackoverflow.com/questions/1952019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/232782/" ]
1) Yes, each process gets its own stack. 2) Yes, each process gets its own heap. 3) I don't think you get the whole 4GB. Some of it is reserved for kernel stuff.
There are other limitations to consider in Java too, such as only being able to address arrays using Integer.MAX\_VALUE at most. This limits you to about 2GB in a lot of areas relating to memory.
20,148,727
If I wanted to loop through a list of nested directories and run a set commands, how would I do that? My directory structure is like this: * videos + folder1 -> VTS\_01\_1.mp4 + folder2 -> VTS\_01\_1.mp4 + folder3 -> VTS\_01\_1.mp4 .... and so on I need to loop through each folder and run the script below.. All of the .mp4 files are named VTS\_01\_1.mp4, but I'd like to do it with a \*.mp4 wildcard condition just incase they aren't. The output file in each directory should be "VTS\_01\_h264.mp4". Ideas? I'm using CentOS 6.4. ``` ffmpeg -y -i "VTS_01_1.mp4" -an -pass 1 -threads 2 -vcodec libx264 -b 512k -flags +loop+mv4 -cmp 256 \ -partitions +parti4x4+parti8x8+partp4x4+partp8x8+partb8x8 \ -me_method hex -subq 7 -trellis 1 -refs 5 -bf 3 \ -flags2 +bpyramid+wpred+mixed_refs+dct8x8 -coder 1 -me_range 16 \ -g 250 -keyint_min 25 -sc_threshold 40 -i_qfactor 0.71 -qmin 10\ -qmax 51 -qdiff 4 "video_tmp.mp4" ffmpeg -y -i "VTS_01_1.mp4" -acodec libfaac -ar 44100 -ab 96k -pass 2 -threads 2 -vcodec libx264 -b 512k -flags +loop+mv4 -cmp 256 \ -partitions +parti4x4+parti8x8+partp4x4+partp8x8+partb8x8 \ -me_method hex -subq 7 -trellis 1 -refs 5 -bf 3 \ -flags2 +bpyramid+wpred+mixed_refs+dct8x8 -coder 1 -me_range 16 \ -g 250 -keyint_min 25 -sc_threshold 40 -i_qfactor 0.71 -qmin 10\ -qmax 51 -qdiff 4 "video_tmp.mp4" qt-faststart "video_tmp.mp4" "VTS_01_h264.mp4" ```
2013/11/22
[ "https://Stackoverflow.com/questions/20148727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1791709/" ]
You can't. If you lost your private key (part of the p12) you will need to create a profile certificate.
**You have to create new distribution certificates and provisioning profile** Go to developer portal, Revoke your current distribution certificate *(whose p12/private key lost)* It won't affect existing live app, Now wait a few seconds and refresh the page and you should see a button "Request Certificate". You'll have to follow the Certificate Signing Request instructions again and upload the .csr file. Create new certificate & download it and install in your Keychain Access app on your Mac. Export the .p12 from Keychain. Your Private key is ready. Now, delete the existing distribution provisioning profile with old certs, You'll have to create a new provisioning profile for the App, using the new certificate. Uplaod the **new p12 and distribution provisioning profile** to phonegap console. Create IPA and Submit to iTunesConnect. It worked for me, It will work for sure.
17,061,740
I have an actor which creates a child actor to perform some lengthy computations. The problem is that the initialization of the child actor takes a few seconds and all messages that the parent actor sends to the child between it is created and gets fully initialized are dropped. This is the logic of the code that I am using: ``` class ChildActor extends Actor { val tagger = IntializeTagger(...) // this takes a few seconds to complete def receive = { case Tag(text) => sender ! tagger.tag(text) case "hello" => println("Hello") case _ => println("Unknown message") } } class ParentActor extends Actor { val child = context.ActorOf(Props[ChildActor], name = "childactor") // the below two messages seem to get lost child ! "hello" child ! Tag("This is my sample text") def receive = { ... } } ``` How could I get around that problem? Is it possible to make the parent actor wait until the child is fully initialized? I will be using the child actor with routing and possibly on remote actor systems. **EDIT** Following drexin's advice I have change my code into: ``` class ChildActor extends Actor { var tagger: Tagger = _ override def preStart() = { tagger = IntializeTagger(...) // this takes a few seconds to complete } def receive = { case Tag(text) => sender ! tagger.tag(text) case "hello" => println("Hello") case _ => println("Unknown message") } } class ParentActor extends Actor { var child: ActorRef = _ override def preStart() = { child = context.ActorOf(Props[ChildActor], name = "childactor") // When I add // Thread.sleep(5000) // here messages are processed without problems // wihout hardcoding the 5 seconds waiting // the below two messages seem to get lost child ! "hello" child ! Tag("This is my sample text") } def receive = { ... } } ``` but the problem remains. What am I missing?
2013/06/12
[ "https://Stackoverflow.com/questions/17061740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/962628/" ]
Don't initialize the `tagger` in the constructor, but in the `preStart` hook, this way the messages will be collected in the message box and delivered, when the actor is ready. **edit**: You should do the same for the actor creation in your `ParentActor` class, because you would have the same problem, if the `ChildActor` would respond, before the `ParentActor` is initialized. **edit2**: I created a simple example, but I was not able to reproduce your problems. Following code works perfectly fine: ``` import akka.actor._ case class Tag(x: String) class ChildActor extends Actor { type Tagger = String => String var tagger: Tagger = _ override def preStart() = { tagger = (x: String) => x+"@tagged" // this takes a few seconds to complete Thread.sleep(2000) // simulate time taken to initialize Tagger } def receive = { case Tag(text) => sender ! tagger(text) case "hello" => println("Hello") case _ => println("Unknown message") } } class ParentActor extends Actor { var child: ActorRef = _ override def preStart() = { child = context.actorOf(Props[ChildActor], name = "childactor") // When I add // Thread.sleep(5000) // here messages are processed without problems // wihout hardcoding the 5 seconds waiting // the below two messages seem to get lost child ! "hello" child ! Tag("This is my sample text") } def receive = { case x => println(x) } } object Main extends App { val system = ActorSystem("MySystem") system.actorOf(Props[ParentActor]) } ``` Output is: ``` [info] Running Main Hello This is my sample text@tagged ```
I would suggest to send a "ready" message from the child actor to the parent and start sending messages to the child actor only after this message will be received. You can do it just in `receive()` method for simple use cases or you can use `become` or `FSM` to change parent actor behavior after the child will be initialized (for example, store the messages for the child in some intermediate storage and send them all when it will be ready).
17,061,740
I have an actor which creates a child actor to perform some lengthy computations. The problem is that the initialization of the child actor takes a few seconds and all messages that the parent actor sends to the child between it is created and gets fully initialized are dropped. This is the logic of the code that I am using: ``` class ChildActor extends Actor { val tagger = IntializeTagger(...) // this takes a few seconds to complete def receive = { case Tag(text) => sender ! tagger.tag(text) case "hello" => println("Hello") case _ => println("Unknown message") } } class ParentActor extends Actor { val child = context.ActorOf(Props[ChildActor], name = "childactor") // the below two messages seem to get lost child ! "hello" child ! Tag("This is my sample text") def receive = { ... } } ``` How could I get around that problem? Is it possible to make the parent actor wait until the child is fully initialized? I will be using the child actor with routing and possibly on remote actor systems. **EDIT** Following drexin's advice I have change my code into: ``` class ChildActor extends Actor { var tagger: Tagger = _ override def preStart() = { tagger = IntializeTagger(...) // this takes a few seconds to complete } def receive = { case Tag(text) => sender ! tagger.tag(text) case "hello" => println("Hello") case _ => println("Unknown message") } } class ParentActor extends Actor { var child: ActorRef = _ override def preStart() = { child = context.ActorOf(Props[ChildActor], name = "childactor") // When I add // Thread.sleep(5000) // here messages are processed without problems // wihout hardcoding the 5 seconds waiting // the below two messages seem to get lost child ! "hello" child ! Tag("This is my sample text") } def receive = { ... } } ``` but the problem remains. What am I missing?
2013/06/12
[ "https://Stackoverflow.com/questions/17061740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/962628/" ]
Don't initialize the `tagger` in the constructor, but in the `preStart` hook, this way the messages will be collected in the message box and delivered, when the actor is ready. **edit**: You should do the same for the actor creation in your `ParentActor` class, because you would have the same problem, if the `ChildActor` would respond, before the `ParentActor` is initialized. **edit2**: I created a simple example, but I was not able to reproduce your problems. Following code works perfectly fine: ``` import akka.actor._ case class Tag(x: String) class ChildActor extends Actor { type Tagger = String => String var tagger: Tagger = _ override def preStart() = { tagger = (x: String) => x+"@tagged" // this takes a few seconds to complete Thread.sleep(2000) // simulate time taken to initialize Tagger } def receive = { case Tag(text) => sender ! tagger(text) case "hello" => println("Hello") case _ => println("Unknown message") } } class ParentActor extends Actor { var child: ActorRef = _ override def preStart() = { child = context.actorOf(Props[ChildActor], name = "childactor") // When I add // Thread.sleep(5000) // here messages are processed without problems // wihout hardcoding the 5 seconds waiting // the below two messages seem to get lost child ! "hello" child ! Tag("This is my sample text") } def receive = { case x => println(x) } } object Main extends App { val system = ActorSystem("MySystem") system.actorOf(Props[ParentActor]) } ``` Output is: ``` [info] Running Main Hello This is my sample text@tagged ```
I think what you might be looking for is the combo of `Stash` and `become`. The idea will be that the child actor will set it's initial state to uninitialized, and while in this state, it will stash all incoming messages until it is fully initialized. When it's fully initialized, you can unstash all of the messages before swapping behavior over to the initialized state. A simple example is as follows: ``` class ChildActor2 extends Actor with Stash{ import context._ var dep:SlowDependency = _ override def preStart = { val me = context.self Future{ dep = new SlowDependency me ! "done" } } def uninitialized:Receive = { case "done" => unstashAll become(initialized) case other => stash() } def initialized:Receive = { case "a" => println("received the 'a' message") case "b" => println("received the 'b' message") } def receive = uninitialized } ``` Notice in the `preStart` that I'm doing my initialization asynchronously, so as to not halt the startup of the actor. Now this is a bit ugly, with closing over the mutable `dep` var. You could certainly handle it by instead sending a message to another actor that handles instantiation of the slow dependency and sends it back to this actor. Upon receiving the dependency, it will then call `become` for the `initialized` state. Now there is one caveat with `Stash` and I'll paste it in right from the Akka docs: ``` Please note that the Stash can only be used together with actors that have a deque-based mailbox. For this, configure the mailbox-type of the dispatcher to be a deque-based mailbox, such as akka.dispatch.UnboundedDequeBasedMailbox (see Dispatchers (Scala)). ``` Now if this does not suite you, you can try a more `DI` type approach and let the slow dependency be injected into the child actor via it's constructor. So you would define the child actor like so: ``` class ChildActor(dep:SlowDependency) extends Actor{ ... } ``` Then when starting up this actor, you would do it as follows: ``` context.actorOf(new Props().withCreator(new ChildActor(slowDep)), name = "child-actor") ```
17,061,740
I have an actor which creates a child actor to perform some lengthy computations. The problem is that the initialization of the child actor takes a few seconds and all messages that the parent actor sends to the child between it is created and gets fully initialized are dropped. This is the logic of the code that I am using: ``` class ChildActor extends Actor { val tagger = IntializeTagger(...) // this takes a few seconds to complete def receive = { case Tag(text) => sender ! tagger.tag(text) case "hello" => println("Hello") case _ => println("Unknown message") } } class ParentActor extends Actor { val child = context.ActorOf(Props[ChildActor], name = "childactor") // the below two messages seem to get lost child ! "hello" child ! Tag("This is my sample text") def receive = { ... } } ``` How could I get around that problem? Is it possible to make the parent actor wait until the child is fully initialized? I will be using the child actor with routing and possibly on remote actor systems. **EDIT** Following drexin's advice I have change my code into: ``` class ChildActor extends Actor { var tagger: Tagger = _ override def preStart() = { tagger = IntializeTagger(...) // this takes a few seconds to complete } def receive = { case Tag(text) => sender ! tagger.tag(text) case "hello" => println("Hello") case _ => println("Unknown message") } } class ParentActor extends Actor { var child: ActorRef = _ override def preStart() = { child = context.ActorOf(Props[ChildActor], name = "childactor") // When I add // Thread.sleep(5000) // here messages are processed without problems // wihout hardcoding the 5 seconds waiting // the below two messages seem to get lost child ! "hello" child ! Tag("This is my sample text") } def receive = { ... } } ``` but the problem remains. What am I missing?
2013/06/12
[ "https://Stackoverflow.com/questions/17061740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/962628/" ]
I think what you might be looking for is the combo of `Stash` and `become`. The idea will be that the child actor will set it's initial state to uninitialized, and while in this state, it will stash all incoming messages until it is fully initialized. When it's fully initialized, you can unstash all of the messages before swapping behavior over to the initialized state. A simple example is as follows: ``` class ChildActor2 extends Actor with Stash{ import context._ var dep:SlowDependency = _ override def preStart = { val me = context.self Future{ dep = new SlowDependency me ! "done" } } def uninitialized:Receive = { case "done" => unstashAll become(initialized) case other => stash() } def initialized:Receive = { case "a" => println("received the 'a' message") case "b" => println("received the 'b' message") } def receive = uninitialized } ``` Notice in the `preStart` that I'm doing my initialization asynchronously, so as to not halt the startup of the actor. Now this is a bit ugly, with closing over the mutable `dep` var. You could certainly handle it by instead sending a message to another actor that handles instantiation of the slow dependency and sends it back to this actor. Upon receiving the dependency, it will then call `become` for the `initialized` state. Now there is one caveat with `Stash` and I'll paste it in right from the Akka docs: ``` Please note that the Stash can only be used together with actors that have a deque-based mailbox. For this, configure the mailbox-type of the dispatcher to be a deque-based mailbox, such as akka.dispatch.UnboundedDequeBasedMailbox (see Dispatchers (Scala)). ``` Now if this does not suite you, you can try a more `DI` type approach and let the slow dependency be injected into the child actor via it's constructor. So you would define the child actor like so: ``` class ChildActor(dep:SlowDependency) extends Actor{ ... } ``` Then when starting up this actor, you would do it as follows: ``` context.actorOf(new Props().withCreator(new ChildActor(slowDep)), name = "child-actor") ```
I would suggest to send a "ready" message from the child actor to the parent and start sending messages to the child actor only after this message will be received. You can do it just in `receive()` method for simple use cases or you can use `become` or `FSM` to change parent actor behavior after the child will be initialized (for example, store the messages for the child in some intermediate storage and send them all when it will be ready).
30,398,511
I'd like to replace a cell's text in case a condition is fullfilled, but the data is in another file. How can I do it? I used something like this: ``` Sub test() Dim customerBook As Workbook Dim filter As String Dim caption As String Dim customerFilename As String Dim customerWorkbook As Workbook Dim targetWorkbook As Workbook Set targetWorkbook = Application.ActiveWorkbook filter = "Text files (*.xlsx),*.xlsx" caption = "Please Select an input file " customerFilename = Application.GetOpenFilename(filter, , caption) Set customerWorkbook = Application.Workbooks.Open(customerFilename) Dim targetSheet As Worksheet Set targetSheet = targetWorkbook.Worksheets(1) Dim sourceSheet As Worksheet Set sourceSheet = customerWorkbook.Worksheets(1) If targetSheet.Range("Q19", "BL23").Text = "OK" Then sourceSheet.Range("GB38", "GH38").Text = "Agreed" End If End Sub ```
2015/05/22
[ "https://Stackoverflow.com/questions/30398511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4929283/" ]
You need to: * test **Q19** and **BL23** separately * use **.Value** rather than **.Text** since **.Text** is read-only **EDIT#1:** Here is the reason I suggest testing the cells separately. Consider: ``` Sub qwerty() MsgBox Range("C3,A1") = "X" End Sub ``` On an empty worksheet, we get **False** If we set **C3** to an *X* we get **True** If we clear **C3** and set **A1** to an *X* we get **False**! It turns out that for a dis-joint range, only the **first** element is examined........the others are ignored!
Try adding ``` customerWorkbook.Close customerWorkbook.Saved = True ``` before your `End Sub` statement. That should fix it.
30,398,511
I'd like to replace a cell's text in case a condition is fullfilled, but the data is in another file. How can I do it? I used something like this: ``` Sub test() Dim customerBook As Workbook Dim filter As String Dim caption As String Dim customerFilename As String Dim customerWorkbook As Workbook Dim targetWorkbook As Workbook Set targetWorkbook = Application.ActiveWorkbook filter = "Text files (*.xlsx),*.xlsx" caption = "Please Select an input file " customerFilename = Application.GetOpenFilename(filter, , caption) Set customerWorkbook = Application.Workbooks.Open(customerFilename) Dim targetSheet As Worksheet Set targetSheet = targetWorkbook.Worksheets(1) Dim sourceSheet As Worksheet Set sourceSheet = customerWorkbook.Worksheets(1) If targetSheet.Range("Q19", "BL23").Text = "OK" Then sourceSheet.Range("GB38", "GH38").Text = "Agreed" End If End Sub ```
2015/05/22
[ "https://Stackoverflow.com/questions/30398511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4929283/" ]
You need to: * test **Q19** and **BL23** separately * use **.Value** rather than **.Text** since **.Text** is read-only **EDIT#1:** Here is the reason I suggest testing the cells separately. Consider: ``` Sub qwerty() MsgBox Range("C3,A1") = "X" End Sub ``` On an empty worksheet, we get **False** If we set **C3** to an *X* we get **True** If we clear **C3** and set **A1** to an *X* we get **False**! It turns out that for a dis-joint range, only the **first** element is examined........the others are ignored!
Got it! Thanks for the support ``` Sub test() Dim customerBook As Workbook Dim filter As String Dim caption As String Dim customerFilename As String Dim customerWorkbook As Workbook Dim targetWorkbook As Workbook Set targetWorkbook = Application.ActiveWorkbook filter = "Text files (*.xlsx),*.xlsx" caption = "Please Select an input file " customerFilename = Application.GetOpenFilename(filter, , caption) Set customerWorkbook = Application.Workbooks.Open(customerFilename) Dim targetSheet As Worksheet Set targetSheet = targetWorkbook.Worksheets(1) Dim sourceSheet As Worksheet Set sourceSheet = customerWorkbook.Worksheets(1) Dim x As String If sourceSheet.Range("Q19").Text = "OK" Then x = "Agreed" End If targetSheet.Range("GB38", "GH38") = x End Sub ```
30,398,511
I'd like to replace a cell's text in case a condition is fullfilled, but the data is in another file. How can I do it? I used something like this: ``` Sub test() Dim customerBook As Workbook Dim filter As String Dim caption As String Dim customerFilename As String Dim customerWorkbook As Workbook Dim targetWorkbook As Workbook Set targetWorkbook = Application.ActiveWorkbook filter = "Text files (*.xlsx),*.xlsx" caption = "Please Select an input file " customerFilename = Application.GetOpenFilename(filter, , caption) Set customerWorkbook = Application.Workbooks.Open(customerFilename) Dim targetSheet As Worksheet Set targetSheet = targetWorkbook.Worksheets(1) Dim sourceSheet As Worksheet Set sourceSheet = customerWorkbook.Worksheets(1) If targetSheet.Range("Q19", "BL23").Text = "OK" Then sourceSheet.Range("GB38", "GH38").Text = "Agreed" End If End Sub ```
2015/05/22
[ "https://Stackoverflow.com/questions/30398511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4929283/" ]
here an example how you can achieve replacement by condition ``` ''''' If targetSheet.[Q19, BL23].text= "ok" Then sourceSheet.Cells.Replace what:="Search string", replacement:="Replacement String" End If ''''' ``` > > the cell's content doesn't change to "Agreed" > > > here your updated code, but this is not replacement as written in title ``` '''''' If targetSheet.[Q19, BL23].text = "OK" Then sourceSheet.[GB38, GH38].Value = "Agreed" End If ''''' ``` for verification of the multiple range content use `.text`, but to insert value in multiple range you need to use `.value` test in screenshots below **wrong way of the multiple range verification using `.value`** ![enter image description here](https://i.stack.imgur.com/6gOfp.png) **wrong way of the multiple range verification without specified range property** ![enter image description here](https://i.stack.imgur.com/8pByU.png) **right way of the multiple range verification using `.text`** ![enter image description here](https://i.stack.imgur.com/wGnx6.png)
Try adding ``` customerWorkbook.Close customerWorkbook.Saved = True ``` before your `End Sub` statement. That should fix it.
30,398,511
I'd like to replace a cell's text in case a condition is fullfilled, but the data is in another file. How can I do it? I used something like this: ``` Sub test() Dim customerBook As Workbook Dim filter As String Dim caption As String Dim customerFilename As String Dim customerWorkbook As Workbook Dim targetWorkbook As Workbook Set targetWorkbook = Application.ActiveWorkbook filter = "Text files (*.xlsx),*.xlsx" caption = "Please Select an input file " customerFilename = Application.GetOpenFilename(filter, , caption) Set customerWorkbook = Application.Workbooks.Open(customerFilename) Dim targetSheet As Worksheet Set targetSheet = targetWorkbook.Worksheets(1) Dim sourceSheet As Worksheet Set sourceSheet = customerWorkbook.Worksheets(1) If targetSheet.Range("Q19", "BL23").Text = "OK" Then sourceSheet.Range("GB38", "GH38").Text = "Agreed" End If End Sub ```
2015/05/22
[ "https://Stackoverflow.com/questions/30398511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4929283/" ]
here an example how you can achieve replacement by condition ``` ''''' If targetSheet.[Q19, BL23].text= "ok" Then sourceSheet.Cells.Replace what:="Search string", replacement:="Replacement String" End If ''''' ``` > > the cell's content doesn't change to "Agreed" > > > here your updated code, but this is not replacement as written in title ``` '''''' If targetSheet.[Q19, BL23].text = "OK" Then sourceSheet.[GB38, GH38].Value = "Agreed" End If ''''' ``` for verification of the multiple range content use `.text`, but to insert value in multiple range you need to use `.value` test in screenshots below **wrong way of the multiple range verification using `.value`** ![enter image description here](https://i.stack.imgur.com/6gOfp.png) **wrong way of the multiple range verification without specified range property** ![enter image description here](https://i.stack.imgur.com/8pByU.png) **right way of the multiple range verification using `.text`** ![enter image description here](https://i.stack.imgur.com/wGnx6.png)
Got it! Thanks for the support ``` Sub test() Dim customerBook As Workbook Dim filter As String Dim caption As String Dim customerFilename As String Dim customerWorkbook As Workbook Dim targetWorkbook As Workbook Set targetWorkbook = Application.ActiveWorkbook filter = "Text files (*.xlsx),*.xlsx" caption = "Please Select an input file " customerFilename = Application.GetOpenFilename(filter, , caption) Set customerWorkbook = Application.Workbooks.Open(customerFilename) Dim targetSheet As Worksheet Set targetSheet = targetWorkbook.Worksheets(1) Dim sourceSheet As Worksheet Set sourceSheet = customerWorkbook.Worksheets(1) Dim x As String If sourceSheet.Range("Q19").Text = "OK" Then x = "Agreed" End If targetSheet.Range("GB38", "GH38") = x End Sub ```
19,985,610
I've got a String that I need to cycle through and create every possible substring. For example, if I had "HelloWorld", "rld" should be one of the possibilities. The String method, substring(int i, int k) is exclusive of k, so if ``` |H|e|l|l|o|W|o|r|l|d| 0 1 2 3 4 5 6 7 8 9 ``` then substring(7,9) returns "rl" How would I work around this and get it to work inclusively? I understand why a substring shouldn't be able to equal the String it was created from, but in this case it would be very helpful to me in this case. Example from Codingbat: <http://codingbat.com/prob/p137918> What I was able to come up with: ``` public String parenBit(String str) { String sub; if (str.charAt(0) == '(' && str.charAt(str.length() - 1) == ')') return str; for (int i = 0; i < str.length() - 1; i++) { for (int k = i + 1; k < str.length(); k++) { sub = str.substring(i,k); } } return null; } ```
2013/11/14
[ "https://Stackoverflow.com/questions/19985610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2853338/" ]
Try changing the display value of `.navbar-nav` to inline-block and then applying `text-align` on its parent to control alignment. If you need to change the mobile view alignment you can re-apply `text-align` at that breakpoint. ``` .navbar-nav { display: inline-block; } .navbar-default { text-align: center; } ``` Example: <http://jsfiddle.net/hwhS5/2/>
use bootstrap class="justify-content-center"
24,025,913
Mysql process is using up 100% cpu. show processlist shows that mysql seems to have a system lock because of "INTERNAL DDL LOG RECOVER IN PROGRESS". Searching for this doesn't return meaningful results so: what is this lock all about? How to fix this? Mysql version 5.6.14-log
2014/06/03
[ "https://Stackoverflow.com/questions/24025913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43671/" ]
It seems like you may have some in the tables MySQL uses to store database definitions. Your best option is to let MySQL try an recover. Check disk space and ensure you have enough free space for MySQL to work normally - this is a common cause of this problem. An unexpected shutdown may also have been the cause. Once it completes you may want to do a check and repair to make sure all is operational - be away that this may take some time as well. ``` mysqlcheck -u root -p --auto-repair --check --optimize --all-databases ``` Sometimes the repair may get stuck in a an internal lock, and never seems to stop, if your database is under 1GB and it's taken longer then 30 minutes, kill the mysql server process and try and restart it. If that still doesn't help, start the server in safe mode and try and take a backup, safe mode can be started with; ``` sudo mysqld_safe ```
See related: [Server stuck in INTERNAL DDL LOG RECOVERY IN PROGRESS](https://stackoverflow.com/questions/28476094/server-stuck-in-internal-ddl-log-recovery-in-progress) This is a known bug in MySQL: <http://bugs.mysql.com/bug.php?id=74517> The server does not clear this message when done, causing confusion. The bug was fixed, you need to upgrade the server: > > Noted in 5.6.25, 5.7.8, 5.8.0 changelogs. > > > In the Performance Schema threads table, the PROCESSLIST\_STATE and > PROCESSLIST\_INFO values did not change for the thread/sql/main main > thread instrument as the thread state changed. > > >
35,248,973
I'm trying to code a program where I can: 1. Load a file 2. Input a start and beginning offset addresses where to scan data from 3. Scan that offset range in search of specific sequence of bytes (such as "05805A6C") 4. Retrieve the offset of every match and write them to a .txt file i66.tinypic.com/2zelef5.png As the picture shows I need to search the file for "05805A6C" and then print to a .txt file the offset "0x21F0". I'm using Java Swing for this. So far I've been able to load the file as a Byte array[]. But I haven't found a way how to search for the specific sequence of bytes, nor setting that search between a range of offsets. This is my code that opens and reads the file into byte array[] ``` public class Read { static public byte[] readBytesFromFile () { try { JFileChooser chooser = new JFileChooser(); int returnVal = chooser.showOpenDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { FileInputStream input = new FileInputStream(chooser.getSelectedFile()); byte[] data = new byte[input.available()]; input.read(data); input.close(); return data; } return null; } catch (IOException e) { System.out.println("Unable to read bytes: " + e.getMessage()); return null; } } } ``` And my code where I try to search among the bytes. ``` byte[] model = Read.readBytesFromFile(); String x = new String(model); boolean found = false; for (int i = 0; i < model.length; i++) { if(x.contains("05805A6C")){ found = true; } } if(found == true){ System.out.println("Yes"); }else{ System.out.println("No"); } ```
2016/02/07
[ "https://Stackoverflow.com/questions/35248973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4980228/" ]
Here's a bomb-proof1 way to search for a sequence of bytes in a byte array: ``` public boolean find(byte[] buffer, byte[] key) { for (int i = 0; i <= buffer.length - key.length; i++) { int j = 0; while (j < key.length && buffer[i + j] == key[j]) { j++; } if (j == key.length) { return true; } } return false; } ``` There are more efficient ways to do this for large-scale searching; e.g. using the Boyer-Moore algorithm. However: * converting the byte array a String and using Java string search is NOT more efficient, and it is potentially fragile depending on what encoding you use when converting the bytes to a string. * converting the byte array to a hexadecimal encoded String is even less efficient ... and memory hungry ... though not fragile if you have enough memory. (You may need up to 5 times the memory as the file size while doing the conversion ...) --- 1 - bomb-proof, modulo any bugs :-)
**EDIT** It seems the charset from system to system is different so you may get different results so I approach it with another method: ``` String x = HexBin.encode(model); String b = new String("058a5a6c"); int index = 0; while((index = x.indexOf(b,index)) != -1 ) { System.out.println("0x"+Integer.toHexString(index/2)); index = index + 2; } ... ```
20,170,503
I have a header.php file that will redirect the user to the homepage on any page if they are not logged in. I'm running into an issue in that the homepage also includes the header and can't have a header to itself. What is the best way to prevent this? I'm thinking a flag I set before my include in the homepage but that seems kinda dirty and inelegant.
2013/11/24
[ "https://Stackoverflow.com/questions/20170503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1710704/" ]
Your code overflows the buffers for `old` and `new` because they do not contain enough space for a 1 character string. In C strings needs to be null terminated, so a `char` array must always be one element longer than the maximum number of characters it must contain. For example your `word` array can only hold a 49 character string, since the 50th element must be the null. So `old` and `new` must both be `char[2]` arrays.
Your loops are unnecessary and incorrect. You can print the values directly without specifying the index. In your post you're trying to loop through each index and print a character at a time. Here's what you should do: ``` int main (){ int i, j, k; char word[50], old[2], new[2]; printf("Enter a word: "); gets(word); printf("Enter desired letter to substitute: "); gets(old); printf("Enter the new letter: "); gets (new); printf("%s\n", word); printf("%s\n", old); printf("%s\n", new); ``` }
37,187,340
The first block is the input file that is used in this program (simply just a .txt file). In the 'SearchByTitle' function, it is correctly picking up on if the target is in the list, as well as printing it out successfully, however, it will only print out the actual target word. Is there a way to get it to print out the entire line? For example, if 'Sempiternal' was searched, could it return Sempiternal, Bring Me The Horizon, Metalcore, 14.50, rather than just the target word? Also, when SortingByPrice, it will only return the closest price less than the target, rather than all that are less. Any nudge in the right direction would be great, i've been messing with this for days. INPUT FILE: ``` Sempiternal,Bring Me The Horizon,Metalcore,14.50 Badlands,Halsey,Indie Pop,19.95 Wildlife,La Dispute,Post Hardcore,9.60 Move Along,The All American Rejects,Punk Rock,10.20 ``` FUNCTIONS: ``` def createDatabase(CD): aList = [] file = open(CD) for line in file: line = line.rstrip().split(",") #strip \n and split at , aList.append(line) #add lines into formerly empty aList for i in range(len(aList)): aList[i][3] = float(aList[i][3]) #override line for price to be float return aList def PrintList(aList): for line in aList: album = str(line[0]) artist = str(line[1]) genre = str(line[2]) price = str(line[3]) print("Album: " + album + " Artist: " + artist + " Genre: " + genre + " Price: $" + price) return def FindByTitle(aList): target = input("Enter Title to Search: ") title = [item[0] for item in aList] for item in title: if target in item: print("Title name found in database: " + target) return aList print("Title not found") return None def FindByPrice(aList): target = float(input("Enter Maximum Price: ")) price = [item[3] for item in aList] for item in price: if item <= target: print(item) return aList print("Artist not found") return None ```
2016/05/12
[ "https://Stackoverflow.com/questions/37187340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6265965/" ]
I would imagine your problem is cause by this line of code: ``` .run(["$rootScope", "$state", function($rootScope, $state) { $rootScope.$on("$stateChangeError", function(event, toState, toParams, fromState, fromParams, error) { // We can catch the error thrown when the $requireAuth promise is rejected // and redirect the user back to the home page if (error === "AUTH_REQUIRED") { $state.go("auth"); } }); }]); ``` You are closing it with semicolons and so the config and rest of the stuff is not going to run. You should remove the semicolon and have it like this: ``` .run(["$rootScope", "$state", function($rootScope, $state) { $rootScope.$on("$stateChangeError", function(event, toState, toParams, fromState, fromParams, error) { // We can catch the error thrown when the $requireAuth promise is rejected // and redirect the user back to the home page if (error === "AUTH_REQUIRED") { $state.go("auth"); } }); }]) ```
When you have a syntax error in a javascript file, the whole file isn't parsed so your module end up not exists for the other javascript file of your application. So the very 1st message is the true important one : the SyntaxError I counted roughly and end up there : ``` return auth.ref.$requireAuth(); ``` the word `ref` may cause trouble try `auth['ref'].$requireAuth()`
17,956,008
To turn on JPA logging as per the link [here](http://openjpa.apache.org/builds/1.0.3/apache-openjpa-1.0.3/docs/manual/ref_guide_logging_openjpa.html) This needs to be done where? in persistence.xml? ``` <property name="openjpa.Log" value="DefaultLevel=WARN, Runtime=INFO, Tool=INFO, SQL=TRACE"/> ```
2013/07/30
[ "https://Stackoverflow.com/questions/17956008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/454671/" ]
Your first issue which is masking the many other issues pointed out by other answers is this: ``` <script src="http://code.jquery.com/jquery-1.10.1.min.js"> // YOU HAVE CODE HERE </script> ``` If your script tag has a `src` attribute, then the contents of the tag (your code) will be ignored. Because of this, your actual code never executes. <http://jsfiddle.net/t9Z8F> It should be like this: ``` <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script> <script> // YOUR CODE GOES HERE </script> ``` One script tag to include jquery and another for your code. Once you fix this, you will see your syntax errors on the console and can begin to debug all of your issues.
by using a `setTimeout` function. this will delay your animations ``` $(function(){ // DOM ready shorthand setTimeout(function(){ $(".img-fade").animate({left:200, opacity:1}, 1500); }, 2000 ); // wait 2s before animating }); ``` Theremore you cannot have a **dot** in your `class` : `<div class=".img-fade">` use instead: ``` <div class="img-fade"> ``` Additionally if you plan to animate an element using it's `left` property (instead of `margin-left`) make sure to set a CSS `position:` (relative or absolute) for your element!
17,956,008
To turn on JPA logging as per the link [here](http://openjpa.apache.org/builds/1.0.3/apache-openjpa-1.0.3/docs/manual/ref_guide_logging_openjpa.html) This needs to be done where? in persistence.xml? ``` <property name="openjpa.Log" value="DefaultLevel=WARN, Runtime=INFO, Tool=INFO, SQL=TRACE"/> ```
2013/07/30
[ "https://Stackoverflow.com/questions/17956008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/454671/" ]
Your first issue which is masking the many other issues pointed out by other answers is this: ``` <script src="http://code.jquery.com/jquery-1.10.1.min.js"> // YOU HAVE CODE HERE </script> ``` If your script tag has a `src` attribute, then the contents of the tag (your code) will be ignored. Because of this, your actual code never executes. <http://jsfiddle.net/t9Z8F> It should be like this: ``` <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script> <script> // YOUR CODE GOES HERE </script> ``` One script tag to include jquery and another for your code. Once you fix this, you will see your syntax errors on the console and can begin to debug all of your issues.
Your `<div class=".img-fade">` div shouldn't have a "." at the beginning of the name. It should look like this: `<div class="img-fade">` - Everything else looks good. Your jQuery wasn't finding any elements matching "img-fade," because the actual name was ".img-fade".
17,956,008
To turn on JPA logging as per the link [here](http://openjpa.apache.org/builds/1.0.3/apache-openjpa-1.0.3/docs/manual/ref_guide_logging_openjpa.html) This needs to be done where? in persistence.xml? ``` <property name="openjpa.Log" value="DefaultLevel=WARN, Runtime=INFO, Tool=INFO, SQL=TRACE"/> ```
2013/07/30
[ "https://Stackoverflow.com/questions/17956008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/454671/" ]
Your first issue which is masking the many other issues pointed out by other answers is this: ``` <script src="http://code.jquery.com/jquery-1.10.1.min.js"> // YOU HAVE CODE HERE </script> ``` If your script tag has a `src` attribute, then the contents of the tag (your code) will be ignored. Because of this, your actual code never executes. <http://jsfiddle.net/t9Z8F> It should be like this: ``` <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script> <script> // YOUR CODE GOES HERE </script> ``` One script tag to include jquery and another for your code. Once you fix this, you will see your syntax errors on the console and can begin to debug all of your issues.
``` $(document).ready(function(2000,slow){ //syntax error ``` you can't pass parameter within function() it is a syntax error > > Uncaught SyntaxError: Unexpected number . > > > Try this ``` $(document).ready(function () { $(".img-fade").animate({ left: 200, opacity: "show" // wrong instead use 0 }, 1500); }); ``` `opacity: "show"` is wrong, instead use `opacity: 0` Check this [**JSFiddle**](http://jsfiddle.net/8mRyb/1/)
38,106
I want to know if "**she likes high school**" should be *elle aime lycée* or *elle aime **le** lycée*? As well as, I'd like to know about "**I listen to music**". Should that be *j’écoute **la** musique* or *j’écoute musique*?
2019/08/21
[ "https://french.stackexchange.com/questions/38106", "https://french.stackexchange.com", "https://french.stackexchange.com/users/21551/" ]
French nouns almost always require an article in French so that would be: > > *Elle aime **le** lycée.* > > > This sentence is perfectly idiomatic. *Le lycée* is likely here the high-school she studies in, work at, or just refer too but might also be high-school in general compared to something else. Note also that *j'écoute la musique* means "I listen to the music" so to properly translate "I listen to music", you would use: > > *J'écoute **de la** musique*. > > > Both *elle aime lycée* and *j'écoute musique* are always ungrammatical in French, a little like would be "I listen music". Note however that there are some cases, both in spoken and written French, where an abstract noun like *musique* might not take an article. e.g.: > > *Musique, maestro !* Very common expression used to tell an orchestra or a band to start playing. > > > > > *L’histoire des relations entre musique et littérature est tumultueuse.* [*Fabula*](https://www.fabula.org/lht/8/reibel.html), 2011 > > >
**I** You wouldn't say in French "Elle aime le lycée."; it is not idiomatic; what you'd say instead would be something like "Elle aime la vie de lycée.", or "Elle aime aller à l'école au lycée.". That is a generic use of "le". Here, you are taking "high school" as you do "school" meaning (uncountable, used without *the* or *a*) the process of learning in a school, the time during your life when you go to school. You say "She likes high school." as you say "She likes school.". In French you render "She likes school." by "Elle aime aller à l'école." or "Elle aime l'école."; the two possibilities do not exist for "lycée", though. Here are clues : [ngram1](https://books.google.com/ngrams/graph?content=aime+l%27%C3%A9cole%2Caime+le+lyc%C3%A9e&year_start=1800&year_end=2008&corpus=19&smoothing=3&share=&direct_url=t1%3B%2Caime%20l%27%20%C3%A9cole%3B%2Cc0), [ngram2](https://books.google.com/ngrams/graph?content=aime+le+coll%C3%A8ge%2Caime+la+fac&year_start=1800&year_end=2008&corpus=19&smoothing=3&share=&direct_url=) If you are talking about a particular place in which there is such a school besides other things such as a skating ring, a Church and a cinema for instance then you can use "le" according to the second way of using this definite article, that is in a specific mode, and say "Elle aime le lycée.", but then you do not translate "She likes high school." but "She likes **the** high school." **II** It can be both; if you take "I listen to music." as meaning "I listen to *some* music." you will translate as such: * "J'écoute **de** la musique.". If you take "music" as the noun "music" used generically, then you say "la musique"; * J'écoute la musique. --- *Explications supplémentaires* « Aimer l'école », comme je conçois cette expression, c'est aimer les études en général dans le cadre d'une institution d'enseignement collectif, et c'est un peu plus, c'est aussi aimer l'ambiance dans laquelle ces études se font. Cela ne s'applique peut-être pas trop au niveau universitaire, mais alors on peut se restreindre à un terme, qui même si plus général n'est plus associé à l'idée d'ambiance, laquelle devient comparativement beaucoup moins importante dans ce cadre-là ; ce terme est tout simplement « aimer les études ». Il me semble que c'est quelque chose de similaire pour à peu près tout le monde, les uns ayant possiblement moins d'enthousiasme pour les études que pour l'ambiance et vice versa pour les autres. Ceci dit, il reste le sens plus terre à terre dans lequel l'école n'est plus qu'un établissement particulier, le site sur lequel se trouve ses bâtiments, les bâtiments eux-mêmes, leur architecture, etc. Dans ce dernier sens l'expression se trouve beaucoup plus rarement. Il existe même d'autres sens de cette locution, et concernant ceux-là « école » peut avoir des sens divers, tels que « système de pensée » ; ils sont encore plus rares, et on se limite aux deux premiers. En dépit de la possibilité de ces deux sens, il n'existe pas de doute dans l'esprit de l'utilisateur du français qui est assez familier avec cette langue, lorsqu'il entend cette expression dans un contexte faiblement précisé ou même pas précisé du tout ; la raison de cela est assez claire : le premier sens est presque toujours celui dont il s'agit ; on a donc en cette expression virtuellement une expression figée. Il n'en est plus de même dès lors que l'on remplace « école » par « lycée » ou un terme semblable ; quand cela arrive, d'emblée, on n'est pas sûr de ce dont il s'agit. La raison de ce fait est encore assez évidente, et c'est qu'il nexiste pas un usage bien établi. Voilà donc ce que je reproche à cet usage naissant. Il existe une longue discussion qui donne des précisions supplémentaires qui pourraient intéresser les plus curieux ; on la trouve sur les pages « [2021/10/13](https://chat.stackexchange.com/transcript/1098/2021/10/13) », « [2021/10/14](https://chat.stackexchange.com/transcript/1098/2021/10/13) » et « [2021/10/15](https://chat.stackexchange.com/transcript/1098/2021/10/13) » du site « Chez Causette ».
38,106
I want to know if "**she likes high school**" should be *elle aime lycée* or *elle aime **le** lycée*? As well as, I'd like to know about "**I listen to music**". Should that be *j’écoute **la** musique* or *j’écoute musique*?
2019/08/21
[ "https://french.stackexchange.com/questions/38106", "https://french.stackexchange.com", "https://french.stackexchange.com/users/21551/" ]
French nouns almost always require an article in French so that would be: > > *Elle aime **le** lycée.* > > > This sentence is perfectly idiomatic. *Le lycée* is likely here the high-school she studies in, work at, or just refer too but might also be high-school in general compared to something else. Note also that *j'écoute la musique* means "I listen to the music" so to properly translate "I listen to music", you would use: > > *J'écoute **de la** musique*. > > > Both *elle aime lycée* and *j'écoute musique* are always ungrammatical in French, a little like would be "I listen music". Note however that there are some cases, both in spoken and written French, where an abstract noun like *musique* might not take an article. e.g.: > > *Musique, maestro !* Very common expression used to tell an orchestra or a band to start playing. > > > > > *L’histoire des relations entre musique et littérature est tumultueuse.* [*Fabula*](https://www.fabula.org/lht/8/reibel.html), 2011 > > >
I understand in English, the language learner may ask when to use an article, when to use "the", etc. When "the" is used, it answers the question "which one?". In French, the question is not so much when **to use** articles, rather when **not to use** them. As I would be tempted to say **always**. However, there are cases where you would not use them. Refer to the use of "article zéro" (Ø) in French to learn more. Here are examples I found in this [thread](https://www.etudes-litteraires.com/forum/topic24656-article-zero.html): > > * Pierre qui roule n'amasse pas mousse. (proverbes) > * tambour battant, chemin faisant (archaïsmes, locutions figées) > * Mère décédée. Enterrement demain. (télégrammes) > * Il viendra mardi. (ce mardi-là ) > * Maison à vendre. Sucre en poudre. (sur pancartes, étiquettes) > * Venez, jeune homme ! (apostrophe) > * Hommes, femmes, enfants, tout le monde était là. (énumération) > * Le métier de prof. Pierre est avocat. Le lion, roi des animaux. (appositions, attributs) > * Arbre est un nom masculin. (= "Le mot arbre" ) > * avoir faim, demander pardon, donner envie, faire fortune, perdre pied, > prendre feu, rendre service, etc. (locutions verbales). > * avec joie, sans crainte, sur place, etc. (locutions adverbiales) > > > Some examples: "faire cas" de qqch. Or "j'ai eu vent de ...". "Je vous souhaite bonheur et prospérité". Etc. As to the use of articles in English, they do map to something in French. For example: * Je mange **du** fromage\*\* => I eat **Ø** cheese. (Recall that we don't say de le, instead it becomes du. If the noun is feminin, use de la) * Je mange le fromage => I eat the piece of cheese (I don't think you'd say the cheese (?) ) * Je mange un fromage => I eat a piece of cheese * J'écoute de la musique => I'm listening to music * J'écoute la musique => I'm listening to the music (you brought me) But there are cases where it doesn't change: * Le chômage est de 16% et continue de croître. => Unemployment is 16% and keeps rising. So, just tell yourself that there are always articles. The rare cases where you don't use them, you'll learn them as you go. And retain that **j'écoute de la musique** is **I'm listening to music** and **j'écoute la musique** is **I'm listening to the music**. edit: By the way, I absolutely don't see what's wrong with saying "elle aime le lycée".
38,106
I want to know if "**she likes high school**" should be *elle aime lycée* or *elle aime **le** lycée*? As well as, I'd like to know about "**I listen to music**". Should that be *j’écoute **la** musique* or *j’écoute musique*?
2019/08/21
[ "https://french.stackexchange.com/questions/38106", "https://french.stackexchange.com", "https://french.stackexchange.com/users/21551/" ]
I understand in English, the language learner may ask when to use an article, when to use "the", etc. When "the" is used, it answers the question "which one?". In French, the question is not so much when **to use** articles, rather when **not to use** them. As I would be tempted to say **always**. However, there are cases where you would not use them. Refer to the use of "article zéro" (Ø) in French to learn more. Here are examples I found in this [thread](https://www.etudes-litteraires.com/forum/topic24656-article-zero.html): > > * Pierre qui roule n'amasse pas mousse. (proverbes) > * tambour battant, chemin faisant (archaïsmes, locutions figées) > * Mère décédée. Enterrement demain. (télégrammes) > * Il viendra mardi. (ce mardi-là ) > * Maison à vendre. Sucre en poudre. (sur pancartes, étiquettes) > * Venez, jeune homme ! (apostrophe) > * Hommes, femmes, enfants, tout le monde était là. (énumération) > * Le métier de prof. Pierre est avocat. Le lion, roi des animaux. (appositions, attributs) > * Arbre est un nom masculin. (= "Le mot arbre" ) > * avoir faim, demander pardon, donner envie, faire fortune, perdre pied, > prendre feu, rendre service, etc. (locutions verbales). > * avec joie, sans crainte, sur place, etc. (locutions adverbiales) > > > Some examples: "faire cas" de qqch. Or "j'ai eu vent de ...". "Je vous souhaite bonheur et prospérité". Etc. As to the use of articles in English, they do map to something in French. For example: * Je mange **du** fromage\*\* => I eat **Ø** cheese. (Recall that we don't say de le, instead it becomes du. If the noun is feminin, use de la) * Je mange le fromage => I eat the piece of cheese (I don't think you'd say the cheese (?) ) * Je mange un fromage => I eat a piece of cheese * J'écoute de la musique => I'm listening to music * J'écoute la musique => I'm listening to the music (you brought me) But there are cases where it doesn't change: * Le chômage est de 16% et continue de croître. => Unemployment is 16% and keeps rising. So, just tell yourself that there are always articles. The rare cases where you don't use them, you'll learn them as you go. And retain that **j'écoute de la musique** is **I'm listening to music** and **j'écoute la musique** is **I'm listening to the music**. edit: By the way, I absolutely don't see what's wrong with saying "elle aime le lycée".
**I** You wouldn't say in French "Elle aime le lycée."; it is not idiomatic; what you'd say instead would be something like "Elle aime la vie de lycée.", or "Elle aime aller à l'école au lycée.". That is a generic use of "le". Here, you are taking "high school" as you do "school" meaning (uncountable, used without *the* or *a*) the process of learning in a school, the time during your life when you go to school. You say "She likes high school." as you say "She likes school.". In French you render "She likes school." by "Elle aime aller à l'école." or "Elle aime l'école."; the two possibilities do not exist for "lycée", though. Here are clues : [ngram1](https://books.google.com/ngrams/graph?content=aime+l%27%C3%A9cole%2Caime+le+lyc%C3%A9e&year_start=1800&year_end=2008&corpus=19&smoothing=3&share=&direct_url=t1%3B%2Caime%20l%27%20%C3%A9cole%3B%2Cc0), [ngram2](https://books.google.com/ngrams/graph?content=aime+le+coll%C3%A8ge%2Caime+la+fac&year_start=1800&year_end=2008&corpus=19&smoothing=3&share=&direct_url=) If you are talking about a particular place in which there is such a school besides other things such as a skating ring, a Church and a cinema for instance then you can use "le" according to the second way of using this definite article, that is in a specific mode, and say "Elle aime le lycée.", but then you do not translate "She likes high school." but "She likes **the** high school." **II** It can be both; if you take "I listen to music." as meaning "I listen to *some* music." you will translate as such: * "J'écoute **de** la musique.". If you take "music" as the noun "music" used generically, then you say "la musique"; * J'écoute la musique. --- *Explications supplémentaires* « Aimer l'école », comme je conçois cette expression, c'est aimer les études en général dans le cadre d'une institution d'enseignement collectif, et c'est un peu plus, c'est aussi aimer l'ambiance dans laquelle ces études se font. Cela ne s'applique peut-être pas trop au niveau universitaire, mais alors on peut se restreindre à un terme, qui même si plus général n'est plus associé à l'idée d'ambiance, laquelle devient comparativement beaucoup moins importante dans ce cadre-là ; ce terme est tout simplement « aimer les études ». Il me semble que c'est quelque chose de similaire pour à peu près tout le monde, les uns ayant possiblement moins d'enthousiasme pour les études que pour l'ambiance et vice versa pour les autres. Ceci dit, il reste le sens plus terre à terre dans lequel l'école n'est plus qu'un établissement particulier, le site sur lequel se trouve ses bâtiments, les bâtiments eux-mêmes, leur architecture, etc. Dans ce dernier sens l'expression se trouve beaucoup plus rarement. Il existe même d'autres sens de cette locution, et concernant ceux-là « école » peut avoir des sens divers, tels que « système de pensée » ; ils sont encore plus rares, et on se limite aux deux premiers. En dépit de la possibilité de ces deux sens, il n'existe pas de doute dans l'esprit de l'utilisateur du français qui est assez familier avec cette langue, lorsqu'il entend cette expression dans un contexte faiblement précisé ou même pas précisé du tout ; la raison de cela est assez claire : le premier sens est presque toujours celui dont il s'agit ; on a donc en cette expression virtuellement une expression figée. Il n'en est plus de même dès lors que l'on remplace « école » par « lycée » ou un terme semblable ; quand cela arrive, d'emblée, on n'est pas sûr de ce dont il s'agit. La raison de ce fait est encore assez évidente, et c'est qu'il nexiste pas un usage bien établi. Voilà donc ce que je reproche à cet usage naissant. Il existe une longue discussion qui donne des précisions supplémentaires qui pourraient intéresser les plus curieux ; on la trouve sur les pages « [2021/10/13](https://chat.stackexchange.com/transcript/1098/2021/10/13) », « [2021/10/14](https://chat.stackexchange.com/transcript/1098/2021/10/13) » et « [2021/10/15](https://chat.stackexchange.com/transcript/1098/2021/10/13) » du site « Chez Causette ».
11,612,010
I'm inserting the event into Google calendar and I can't find the way I can specify that description is not a plain text but the HTML markup: ``` request = WebRequest.Create("https://www.googleapis.com/calendar/v3/calendars/" + calendarID + "/events?pp=1&key=" + ClientID) as HttpWebRequest; request.Headers.Add("Accept-Charset", "utf-8"); request.KeepAlive = true; request.ContentType = "application/json"; request.Method = "POST"; request.Headers.Add("Authorization", "OAuth " + googleToken.ToString()); var actEvent = new GoogleCalendarEvent { summary = eventCalendar.Title, description = eventCalendar.Description, start = new GoogleCalendarEventTime(eventCalendar.Date), end = new GoogleCalendarEventTime(eventCalendar.Date.AddHours(1)) }; var data = jsonSerializer.Serialize(actEvent); var postData = Encoding.UTF8.GetBytes(data); Stream ws = request.GetRequestStream(); ws.Write(postData, 0, postData.Length); ws.Close(); response = request.GetResponse(); stream = new StreamReader(response.GetResponseStream()); var result = stream.ReadToEnd().Trim(); return Json(new {Success = true}); ```
2012/07/23
[ "https://Stackoverflow.com/questions/11612010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/882162/" ]
There is only plain text available for Google Calendar Event description field. :-(
If you go to the [documentation here](https://developers.google.com/google-apps/calendar/v1/developers_guide_php#CreatingWebContent), it speaks of setting the type (MIME). This means you probably just have to set the type to HTML.
11,612,010
I'm inserting the event into Google calendar and I can't find the way I can specify that description is not a plain text but the HTML markup: ``` request = WebRequest.Create("https://www.googleapis.com/calendar/v3/calendars/" + calendarID + "/events?pp=1&key=" + ClientID) as HttpWebRequest; request.Headers.Add("Accept-Charset", "utf-8"); request.KeepAlive = true; request.ContentType = "application/json"; request.Method = "POST"; request.Headers.Add("Authorization", "OAuth " + googleToken.ToString()); var actEvent = new GoogleCalendarEvent { summary = eventCalendar.Title, description = eventCalendar.Description, start = new GoogleCalendarEventTime(eventCalendar.Date), end = new GoogleCalendarEventTime(eventCalendar.Date.AddHours(1)) }; var data = jsonSerializer.Serialize(actEvent); var postData = Encoding.UTF8.GetBytes(data); Stream ws = request.GetRequestStream(); ws.Write(postData, 0, postData.Length); ws.Close(); response = request.GetResponse(); stream = new StreamReader(response.GetResponseStream()); var result = stream.ReadToEnd().Trim(); return Json(new {Success = true}); ```
2012/07/23
[ "https://Stackoverflow.com/questions/11612010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/882162/" ]
put description in a variable like this: ``` $variable = [ "<span>Text here</span> <br/> <b>Text here</> ... " ]; ```
If you go to the [documentation here](https://developers.google.com/google-apps/calendar/v1/developers_guide_php#CreatingWebContent), it speaks of setting the type (MIME). This means you probably just have to set the type to HTML.
11,612,010
I'm inserting the event into Google calendar and I can't find the way I can specify that description is not a plain text but the HTML markup: ``` request = WebRequest.Create("https://www.googleapis.com/calendar/v3/calendars/" + calendarID + "/events?pp=1&key=" + ClientID) as HttpWebRequest; request.Headers.Add("Accept-Charset", "utf-8"); request.KeepAlive = true; request.ContentType = "application/json"; request.Method = "POST"; request.Headers.Add("Authorization", "OAuth " + googleToken.ToString()); var actEvent = new GoogleCalendarEvent { summary = eventCalendar.Title, description = eventCalendar.Description, start = new GoogleCalendarEventTime(eventCalendar.Date), end = new GoogleCalendarEventTime(eventCalendar.Date.AddHours(1)) }; var data = jsonSerializer.Serialize(actEvent); var postData = Encoding.UTF8.GetBytes(data); Stream ws = request.GetRequestStream(); ws.Write(postData, 0, postData.Length); ws.Close(); response = request.GetResponse(); stream = new StreamReader(response.GetResponseStream()); var result = stream.ReadToEnd().Trim(); return Json(new {Success = true}); ```
2012/07/23
[ "https://Stackoverflow.com/questions/11612010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/882162/" ]
There is only plain text available for Google Calendar Event description field. :-(
after fighting with this for 48 hours, Renato's answer worked for me, and to include a url link, I coded it like this ``` <a href=https://www.myweb.com/page.pdf>Page Description</a><br/> ```
11,612,010
I'm inserting the event into Google calendar and I can't find the way I can specify that description is not a plain text but the HTML markup: ``` request = WebRequest.Create("https://www.googleapis.com/calendar/v3/calendars/" + calendarID + "/events?pp=1&key=" + ClientID) as HttpWebRequest; request.Headers.Add("Accept-Charset", "utf-8"); request.KeepAlive = true; request.ContentType = "application/json"; request.Method = "POST"; request.Headers.Add("Authorization", "OAuth " + googleToken.ToString()); var actEvent = new GoogleCalendarEvent { summary = eventCalendar.Title, description = eventCalendar.Description, start = new GoogleCalendarEventTime(eventCalendar.Date), end = new GoogleCalendarEventTime(eventCalendar.Date.AddHours(1)) }; var data = jsonSerializer.Serialize(actEvent); var postData = Encoding.UTF8.GetBytes(data); Stream ws = request.GetRequestStream(); ws.Write(postData, 0, postData.Length); ws.Close(); response = request.GetResponse(); stream = new StreamReader(response.GetResponseStream()); var result = stream.ReadToEnd().Trim(); return Json(new {Success = true}); ```
2012/07/23
[ "https://Stackoverflow.com/questions/11612010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/882162/" ]
put description in a variable like this: ``` $variable = [ "<span>Text here</span> <br/> <b>Text here</> ... " ]; ```
after fighting with this for 48 hours, Renato's answer worked for me, and to include a url link, I coded it like this ``` <a href=https://www.myweb.com/page.pdf>Page Description</a><br/> ```
29,954,090
Here is the MySQL code I have tried: ``` "INSERT INTO wpcustom_productmeta.wpc_productmeta(brand,model,country,carrier) VALUES (SELECT meta_value FROM wordpress.wp_postmeta WHERE meta_key='brand'), (SELECT meta_value FROM wordpress.wp_postmeta WHERE meta_key='model'), (SELECT meta_value FROM wordpress.wp_postmeta WHERE meta_key='country'), (SELECT meta_value FROM wordpress.wp_postmeta WHERE meta_key='carrier')"; ``` I would like to insert data into `wpcustom_productmeta.wpc_productmeta` from the separate database and table `wordpress.wp_postmeta` but I want to choose only specific columns. Here is the structure of both tables:![wp_postmeta](https://i.stack.imgur.com/cCHhN.jpg) ![wpc_productmeta](https://i.stack.imgur.com/70EiO.jpg)
2015/04/29
[ "https://Stackoverflow.com/questions/29954090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3662518/" ]
> > Is there any reason inherent to the design of the VHDL language, why the following can not be done? > > > ``` process (clk) variable b : std_logic_vector(15 downto 0); -- This would be nice, but is not permitted: signal c : std_logic_vector(15 downto 0); begin ``` (Declare a signal in a process.) How would you resolve visibility? A process statement is a declarative region. All concurrent statements have equivalent processes or block statement equivalents and equivalent processes, elaborated for simulation. All those processes are separate declarative regions, albeit you're apparently only advocating allowing signal declarations as explicitly declared process declarative items. Function calls are expressions, procedure calls are statements, concurrent procedure calls have equivalent processes for simulation. A signal can only communicate between sequential statements in the same process by encountering a wait statement. A signal today would be declared in an enclosing declarative region (a block declarative item or a port declaration) or made visible by a use clause when declared as a package declarative item. Note you can use wait statements and variables to the same effect internally to a process. Where it get's interesting is using signals for their intended purpose - communicating between processes. Case 1 Two or more processes in the same declarative region which also has a signal of the same name declared as in one process. Which signal declaration do other processes use? Case 2 Three or more processes in the same declarative region with two of them declaring the same signal name. Which declaration does the third or other processes use? Signal declarations in a process don't seem resolvable from a visibility perspective. Consider how to extend the scope of a signal declaration to the enclosing declarative region by using a 'shared' signal declaration. That could resolve the second case if only one signal declaration were shared but not both and no declaration was visible in the enclosing declarative region. It doesn't address the first case at all, and selected names aren't allowed to use a process as a prefix (and would require an instantiation name if they were, incidentally requiring a process statement be labelled). How would this be useful? It's ambiguous. VHDL restricts where signals can be declared so that the visibility rules provide at most one possible declaration. The scope of a declaration doesn't extend into enclosing or adjacent declarative regions. And as a cure instead of using paebbel's block statement you could also declare signals as package declarative items made privately visible by use clauses in particular processes.
Yes you should be able to do it and no you cannot and I don't believe VHDL2008 is fixing it (but a lot of awesome things are being fixed/added in VHDL2008). You can use always true generate statements (as already mentioned in a comment). Although if your using always true generate statements your module is probably to big and you should break it up. I did just want to point out that you can still use/implement your pipeline register in a variable. if you swap the d and c assignments around. I know it's not as nice but I do use it occasionally and it synthesizes fine. Variables keep their values between consecutive runs of the process. ``` architecture does_not_compile of test is signal a, d : std_logic_vector(15 downto 0); begin process (clk) variable b : std_logic_vector(15 downto 0); variable c : std_logic_vector(15 downto 0); begin if (rising_edge(clk)) then b := foo_operation(a); -- could just be used to store an intermediary value d <= baz_operation(c); -- the "output register" of this process c := bar_operation(b); -- could e.g. be a pipeline end if; end process; -- somewhere else: a <= input_xyz; output_xyz <= d end architecture; ```
60,071,355
I am trying to select the values `LIKE '%Pro%'`, but ultimately I always want `'%PRO333%'` to be the last selected. This is my data: ``` userid: text: 1 PRO11 1 PRO23 1 PRO333 1 PRO2000 ``` This is my query: ``` select * from table1 where userid=1 and text LIKE '%PRO%' --now when I get that column I always need to return PRO333 as the last column ``` Expected output to be: ``` userid: text: 1 PRO11 1 PRO23 1 PRO2000 1 PRO333 --always the last ``` How can I do it, thank you all for your help
2020/02/05
[ "https://Stackoverflow.com/questions/60071355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9130240/" ]
You can include a comparison between the value of `text` and `PRO333` into your `ORDER BY` clause to sort that value last. For example: ``` SELECT * FROM table1 WHERE userid = 1 AND text LIKE '%PRO%' ORDER BY CASE WHEN text = 'PRO333' THEN 1 ELSE 0 END ``` Output: ``` userid text 1 PRO11 1 PRO23 1 PRO2000 1 PRO333 ``` [Demo on SQLFiddle](http://www.sqlfiddle.com/#!18/05395/1)
First way: ``` DECLARE @TABLE TABLE( userid int, [text] nvarchar(100) ) INSERT INTO @TABLE(userid,text) VALUES (1,'PRO11'), (1,'PRO23'), (1,'PRO333'), (1,'PRO2000') SELECT * FROM @TABLE WHERE text LIKE '%PRO%' ORDER BY IIF(text='PRO333',1,0) ``` Second way.I used ROW\_NUMBER. ``` DECLARE @TABLE TABLE( userid int, [text] nvarchar(100) ) INSERT INTO @TABLE(userid,text) VALUES (1,'PRO11'), (1,'PRO23'), (1,'PRO333'), (1,'PRO2000'), (1,'PRO1233'), (1,'PRO234234324') SELECT *,ROW_NUMBER() OVER(ORDER BY(IIF(text='PRO333',1,0))) FROM @TABLE ```
4,883,845
I Want iAd And AdMob In My Application Is it possible to provide Add By Both Of This way in My One application ? Or I Want Alternate Add From this Both Add Network what Are the Possibilities for to give the Add By BOth WAy ? Thank You In Advance
2011/02/03
[ "https://Stackoverflow.com/questions/4883845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/730776/" ]
Adwhirl is great for doing this. Check it out: <https://www.adwhirl.com/home/dev> Or when you want to do some crazy stuff you could even use a random number do decide which adview is shown, either iAd or AdMob ^^
You can use something like AdWhirl to control multiple ad networks. That way you can allocate percentage of fill to each network. Please note AdWhirl is not bad but we've had lots of problems/crashes when integrating it which we've had to sort out ourselves. There are other similar tools but I ve not tried them.
4,883,845
I Want iAd And AdMob In My Application Is it possible to provide Add By Both Of This way in My One application ? Or I Want Alternate Add From this Both Add Network what Are the Possibilities for to give the Add By BOth WAy ? Thank You In Advance
2011/02/03
[ "https://Stackoverflow.com/questions/4883845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/730776/" ]
Adwhirl is great for doing this. Check it out: <https://www.adwhirl.com/home/dev> Or when you want to do some crazy stuff you could even use a random number do decide which adview is shown, either iAd or AdMob ^^
Use these controls to add iAd as well as adMob both, ``` https://github.com/pjcook/iAdPlusAdMob https://github.com/chrisjp/CJPAdController ```
7,936,119
I have a jQuery Mobile webpage which currently has a `width=device-width` but my form elements (textfields and the submit button) stretch to the width of the browser when viewed on a desktop computer. Is there any way to set a maximum width so that these elements (or the whole content div) display properly on mobile devices but don't exceed a fixed maximum width when viewed on desktop computers?
2011/10/29
[ "https://Stackoverflow.com/questions/7936119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/343486/" ]
``` <style type='text/css'> <!-- html { background-color: #333; } @media only screen and (min-width: 600px){ .ui-page { width: 600px !important; margin: 0 auto !important; position: relative !important; border-right: 5px #666 outset !important; border-left: 5px #666 outset !important; } } --> </style> ``` The `@media only screen and (min-width: 600px)` restricts the CSS rule to desktop devices with a minimum window width of 600px. For these the `width` of the page container created by jQuery Mobile is fixed to 600px, `margin: 0 auto` centers the page. The rest improves the result aesthetically. However, ther is one drawback: this doesn't really play well with the sliding animation. I suggest to disable the animation (maybe also depending on the media type and screen size using `@media`), because it looks just weird on a big screen anyways.
You can use `document.getElementById("id").style.width="200px";` [jsFiddle Example](http://jsfiddle.net/Naning/VkyAv/7/)
7,936,119
I have a jQuery Mobile webpage which currently has a `width=device-width` but my form elements (textfields and the submit button) stretch to the width of the browser when viewed on a desktop computer. Is there any way to set a maximum width so that these elements (or the whole content div) display properly on mobile devices but don't exceed a fixed maximum width when viewed on desktop computers?
2011/10/29
[ "https://Stackoverflow.com/questions/7936119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/343486/" ]
``` @media only screen and (min-width: 800px){ body { background:transparent !important; overflow:hidden !important; } html { background: #fff; background-attachment: fixed; overflow:hidden !important; } .ui-page { width: 340px !important; border:60px solid #111 !important; margin: 50px auto !important; position: relative !important; border-right: 20px #222 outset !important; border-left: 20px #000 outset !important; border-radius:25px; -webkit-border-radius:25px; -moz-border-radius:25px; overflow-y:scroll !important; min-height:600px !important; height:600px !important; max-height:600px !important; padding-bottom:0px; } } ```
You can use `document.getElementById("id").style.width="200px";` [jsFiddle Example](http://jsfiddle.net/Naning/VkyAv/7/)
7,936,119
I have a jQuery Mobile webpage which currently has a `width=device-width` but my form elements (textfields and the submit button) stretch to the width of the browser when viewed on a desktop computer. Is there any way to set a maximum width so that these elements (or the whole content div) display properly on mobile devices but don't exceed a fixed maximum width when viewed on desktop computers?
2011/10/29
[ "https://Stackoverflow.com/questions/7936119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/343486/" ]
``` .ui-page { max-width: 320px !important;/*or 640 */ margin: 0 auto !important; position: relative !important; } ``` Design and test for 320 px or 640 px. in case of 640 px in desktop(bigger resolution) it will take a width of 640 px and on mobile it will be width of mobile. give border if needed ``` .ui-page { border-right: 2px #000 outset !important; border-left: 2px #000 outset !important; } ```
You can use `document.getElementById("id").style.width="200px";` [jsFiddle Example](http://jsfiddle.net/Naning/VkyAv/7/)
7,936,119
I have a jQuery Mobile webpage which currently has a `width=device-width` but my form elements (textfields and the submit button) stretch to the width of the browser when viewed on a desktop computer. Is there any way to set a maximum width so that these elements (or the whole content div) display properly on mobile devices but don't exceed a fixed maximum width when viewed on desktop computers?
2011/10/29
[ "https://Stackoverflow.com/questions/7936119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/343486/" ]
``` <style type='text/css'> <!-- html { background-color: #333; } @media only screen and (min-width: 600px){ .ui-page { width: 600px !important; margin: 0 auto !important; position: relative !important; border-right: 5px #666 outset !important; border-left: 5px #666 outset !important; } } --> </style> ``` The `@media only screen and (min-width: 600px)` restricts the CSS rule to desktop devices with a minimum window width of 600px. For these the `width` of the page container created by jQuery Mobile is fixed to 600px, `margin: 0 auto` centers the page. The rest improves the result aesthetically. However, ther is one drawback: this doesn't really play well with the sliding animation. I suggest to disable the animation (maybe also depending on the media type and screen size using `@media`), because it looks just weird on a big screen anyways.
``` @media only screen and (min-width: 800px){ body { background:transparent !important; overflow:hidden !important; } html { background: #fff; background-attachment: fixed; overflow:hidden !important; } .ui-page { width: 340px !important; border:60px solid #111 !important; margin: 50px auto !important; position: relative !important; border-right: 20px #222 outset !important; border-left: 20px #000 outset !important; border-radius:25px; -webkit-border-radius:25px; -moz-border-radius:25px; overflow-y:scroll !important; min-height:600px !important; height:600px !important; max-height:600px !important; padding-bottom:0px; } } ```
7,936,119
I have a jQuery Mobile webpage which currently has a `width=device-width` but my form elements (textfields and the submit button) stretch to the width of the browser when viewed on a desktop computer. Is there any way to set a maximum width so that these elements (or the whole content div) display properly on mobile devices but don't exceed a fixed maximum width when viewed on desktop computers?
2011/10/29
[ "https://Stackoverflow.com/questions/7936119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/343486/" ]
``` <style type='text/css'> <!-- html { background-color: #333; } @media only screen and (min-width: 600px){ .ui-page { width: 600px !important; margin: 0 auto !important; position: relative !important; border-right: 5px #666 outset !important; border-left: 5px #666 outset !important; } } --> </style> ``` The `@media only screen and (min-width: 600px)` restricts the CSS rule to desktop devices with a minimum window width of 600px. For these the `width` of the page container created by jQuery Mobile is fixed to 600px, `margin: 0 auto` centers the page. The rest improves the result aesthetically. However, ther is one drawback: this doesn't really play well with the sliding animation. I suggest to disable the animation (maybe also depending on the media type and screen size using `@media`), because it looks just weird on a big screen anyways.
``` .ui-page { max-width: 320px !important;/*or 640 */ margin: 0 auto !important; position: relative !important; } ``` Design and test for 320 px or 640 px. in case of 640 px in desktop(bigger resolution) it will take a width of 640 px and on mobile it will be width of mobile. give border if needed ``` .ui-page { border-right: 2px #000 outset !important; border-left: 2px #000 outset !important; } ```
7,936,119
I have a jQuery Mobile webpage which currently has a `width=device-width` but my form elements (textfields and the submit button) stretch to the width of the browser when viewed on a desktop computer. Is there any way to set a maximum width so that these elements (or the whole content div) display properly on mobile devices but don't exceed a fixed maximum width when viewed on desktop computers?
2011/10/29
[ "https://Stackoverflow.com/questions/7936119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/343486/" ]
``` @media only screen and (min-width: 800px){ body { background:transparent !important; overflow:hidden !important; } html { background: #fff; background-attachment: fixed; overflow:hidden !important; } .ui-page { width: 340px !important; border:60px solid #111 !important; margin: 50px auto !important; position: relative !important; border-right: 20px #222 outset !important; border-left: 20px #000 outset !important; border-radius:25px; -webkit-border-radius:25px; -moz-border-radius:25px; overflow-y:scroll !important; min-height:600px !important; height:600px !important; max-height:600px !important; padding-bottom:0px; } } ```
``` .ui-page { max-width: 320px !important;/*or 640 */ margin: 0 auto !important; position: relative !important; } ``` Design and test for 320 px or 640 px. in case of 640 px in desktop(bigger resolution) it will take a width of 640 px and on mobile it will be width of mobile. give border if needed ``` .ui-page { border-right: 2px #000 outset !important; border-left: 2px #000 outset !important; } ```
12,385,444
I'm using Vitamio plugin to play live streaming. It works well. But I cannot custom its VideoPlayer. Anybody can show me how to : 1/ auto play when streaming is loaded. I'm using this code but it is not efficient ``` mVideoView.setOnPreparedListener(new OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { mp.start(); if (mProgressDialog.isShowing()) mProgressDialog.dismiss(); } }); ``` 2/ hide the file name on control bar. I tried to use `mMediaController.setFileName("")` and `mMediaController.setInfoView(null)` but the file name is still shown.
2012/09/12
[ "https://Stackoverflow.com/questions/12385444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1244326/" ]
1) Their example uses ``` mVideoView.setOnPreparedListener(new OnPreparedListener() { @Override public void onPrepared(MediaPlayer arg0) { if (loadingDialog.isShowing()) { loadingDialog.dismiss(); mVideoView.start(); } } }); ``` 2) Are you using Vitamio Bundle as a library? If so, just open res/layout/mediacontroller.xml and edit the filename TextView to add visibility invisible (using gone breaks the ui) Here you can customize as much as you want ``` <TextView android:id="@+id/mediacontroller_file_name" style="@style/MediaController_Text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:ellipsize="marquee" android:singleLine="true" android:visibility="invisible" /> ```
``` mVideoView.setMediaController() ``` sets the MediaController widget to be displayed. Just create your own from scratch.
26,223,356
I have an MDI application where I'm trying to get a list of open windows for a `ComponentOne` Ribbon Menu. Using VB .NET. I have this sub for instantiating a new child form within the MDI container: ``` Private Sub newButton_Click(sender As Object, e As EventArgs) Handles newButton.Click ' Create a new instance of the child form. Dim ChildForm As New MyProject.MyForm 'Make it a child of this MDI form before showing it. ChildForm.MdiParent = Me m_ChildFormNumber += 1 ChildForm.Text = "Window " & m_ChildFormNumber ChildForm.Show() End Sub ``` Then in another Sub for the ribbon menu I try to get the list of windows. I tried this: ``` Dim frm As System.Windows.Window For Each frm In My.Application.Windows frmButton = New C1.Win.C1Ribbon.RibbonButton(frm.Title) ... ``` But I get a `NullReferenceException` on the `System.Windows.Window` collection. So then I tried this: ``` For Each Window In My.Application.Windows frmButton = New C1.Win.C1Ribbon.RibbonButton(Window.Title) ... ``` But with that, I get "overload resolution failed because no accessible 'new' can be called without a narrowing conversion" on the arguments for the new `RibbonButton`. If I turn `Option Strict` On, of course it says it disallows late binding. So I guess ultimately I'm wondering why my Windows collection is empty, even if I've opened child forms. Then even beyond that, why does the New RibbonButton accept frm.Title but not Window.Title. NOTE (in case you were wondering)...the frmButton is a class object: ``` Friend WithEvents frmButton As C1.Win.C1Ribbon.RibbonButton ``` Thank you!
2014/10/06
[ "https://Stackoverflow.com/questions/26223356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3830488/" ]
You want to look at a [while](https://wiki.python.org/moin/WhileLoop) loop eg: ``` # Set the target value target = 50 # Initialize the running total to 0 total = 0 run the indented code while target != total while total != target: # ask the user for a number choice = input("Number? ") # add choice to total total += choice ``` The above will keep running the `while` block while `total != 50` evaluates to `True`.
``` import random def amountGame(): coin=[25,5,1] target=random.randint(1,99) print(f'Your Amount is {target}') total=0 while target!=total: x=int(input('Enter pic of amount :')) if x in coin and (target-total)>=x: total+=x else: print('Envalid Entry') print('You Solve problam') opt='' while opt!='N': amountGame() opt=input('Do you want to continue press Y else N :).upper() ```
9,278,172
I have following ajax call: ``` $("#container").html("loading..."); $.ajax({ url: "somedoc.php", type: "POST", dataType: "html", success: function(response){ if(response != ''){ $("#container").html(response); } } }); ``` Response look like this: ``` <ul> <li><img src="big_size_image_1.jpg" alt="" /></li> <li><img src="big_size_image_2.jpg" alt="" /></li> <li><img src="big_size_image_3.jpg" alt="" /></li> </ul> ``` Ajax call finishes up before all images are downloaded to the user. So is it possible to use load function here and show loading text while not all images are loaded ? Your help would be appreaciated.
2012/02/14
[ "https://Stackoverflow.com/questions/9278172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/262460/" ]
[Large-Scale C++ Software Design](https://rads.stackoverflow.com/amzn/click/com/0201633620), by John Lakos.
Frankly, it doesn't matter much which language you're using in the end. Good software design is good software design. I don't think you'll ever learn it from a single book - and most books that talk about that kind of thing are referring to designing large frameworks which I doubt you're doing. Identify sub-components/functionalitities in your requirements that you can form into separate libaries (static or dynamic, read up on the difference). If you compartmentalize these components into libraries that can act independently of each other then you'll have loose coupling between libraries - and assuming you've correctly identified your sub-components, they should have high-cohesion (everything in a library is closely related). Try and keep dependencies out of your header files whenever possible regardless of where you're coding - you should read up (even on google) about separating declaration from definition). There's a number of design patterns for this purpose (including PIMPL which I seem to be mentioning alot today). Read the design patterns book by the Gang-of-Four, and do the above, and you'll be off to a good start. Also, assuming you're decent with C++, Effective C++ by Scott Meyers will talk about some of these topics in very helpful manners.
9,278,172
I have following ajax call: ``` $("#container").html("loading..."); $.ajax({ url: "somedoc.php", type: "POST", dataType: "html", success: function(response){ if(response != ''){ $("#container").html(response); } } }); ``` Response look like this: ``` <ul> <li><img src="big_size_image_1.jpg" alt="" /></li> <li><img src="big_size_image_2.jpg" alt="" /></li> <li><img src="big_size_image_3.jpg" alt="" /></li> </ul> ``` Ajax call finishes up before all images are downloaded to the user. So is it possible to use load function here and show loading text while not all images are loaded ? Your help would be appreaciated.
2012/02/14
[ "https://Stackoverflow.com/questions/9278172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/262460/" ]
[Large-Scale C++ Software Design](https://rads.stackoverflow.com/amzn/click/com/0201633620), by John Lakos.
Good design is a key on large projects and it is doesn't matter which language do you use if you follow the OO concept. But for some best practices in c++ you could read this book: <http://www.gotw.ca/publications/c++cs.htm>
9,278,172
I have following ajax call: ``` $("#container").html("loading..."); $.ajax({ url: "somedoc.php", type: "POST", dataType: "html", success: function(response){ if(response != ''){ $("#container").html(response); } } }); ``` Response look like this: ``` <ul> <li><img src="big_size_image_1.jpg" alt="" /></li> <li><img src="big_size_image_2.jpg" alt="" /></li> <li><img src="big_size_image_3.jpg" alt="" /></li> </ul> ``` Ajax call finishes up before all images are downloaded to the user. So is it possible to use load function here and show loading text while not all images are loaded ? Your help would be appreaciated.
2012/02/14
[ "https://Stackoverflow.com/questions/9278172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/262460/" ]
Frankly, it doesn't matter much which language you're using in the end. Good software design is good software design. I don't think you'll ever learn it from a single book - and most books that talk about that kind of thing are referring to designing large frameworks which I doubt you're doing. Identify sub-components/functionalitities in your requirements that you can form into separate libaries (static or dynamic, read up on the difference). If you compartmentalize these components into libraries that can act independently of each other then you'll have loose coupling between libraries - and assuming you've correctly identified your sub-components, they should have high-cohesion (everything in a library is closely related). Try and keep dependencies out of your header files whenever possible regardless of where you're coding - you should read up (even on google) about separating declaration from definition). There's a number of design patterns for this purpose (including PIMPL which I seem to be mentioning alot today). Read the design patterns book by the Gang-of-Four, and do the above, and you'll be off to a good start. Also, assuming you're decent with C++, Effective C++ by Scott Meyers will talk about some of these topics in very helpful manners.
Good design is a key on large projects and it is doesn't matter which language do you use if you follow the OO concept. But for some best practices in c++ you could read this book: <http://www.gotw.ca/publications/c++cs.htm>
9,757,261
I want to run a Ruby file in the context of a Rails environment. rails runner almost does what I want to do, but I'd like to just give it the file name and arguments. I'm pretty sure this is possible since I've done it before. Can someone remind me how to do this?
2012/03/18
[ "https://Stackoverflow.com/questions/9757261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/66702/" ]
The simplest way is with `rails runner` because you don't need to modify your script. `runner` runs Ruby code in the context of Rails non-interactively. <https://guides.rubyonrails.org/command_line.html#bin-rails-runner> Just say `rails runner script.rb`
Simply require `environment.rb` in your script. If your script is located in the `script` directory of your Rails app do ``` require File.expand_path('../../config/environment', __FILE__) ``` You can control the environment used (development/test/production) by setting the `RAILS_ENV` environment variable when running the script. ``` RAILS_ENV=production ruby script/test.rb ```
9,757,261
I want to run a Ruby file in the context of a Rails environment. rails runner almost does what I want to do, but I'd like to just give it the file name and arguments. I'm pretty sure this is possible since I've done it before. Can someone remind me how to do this?
2012/03/18
[ "https://Stackoverflow.com/questions/9757261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/66702/" ]
Simply require `environment.rb` in your script. If your script is located in the `script` directory of your Rails app do ``` require File.expand_path('../../config/environment', __FILE__) ``` You can control the environment used (development/test/production) by setting the `RAILS_ENV` environment variable when running the script. ``` RAILS_ENV=production ruby script/test.rb ```
This is an old question, but in my opinion I often find it helpful to create a rake task... and it's actually very easy. In `lib/tasks/example.rake`: ``` namespace :example do desc "Sample description you'd see if you ran: 'rake --tasks' in the terminal" task create_user: :environment do User.create! first_name: "Foo", last_name: "Bar" end ``` And then in the terminal run: ``` rake example:create_user ``` Locally this will be run in the context of your development database, and if run on Heroku it will be run while connected to your production database. I find this especially useful to assist with migrations, or modified tables.
9,757,261
I want to run a Ruby file in the context of a Rails environment. rails runner almost does what I want to do, but I'd like to just give it the file name and arguments. I'm pretty sure this is possible since I've done it before. Can someone remind me how to do this?
2012/03/18
[ "https://Stackoverflow.com/questions/9757261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/66702/" ]
Simply require `environment.rb` in your script. If your script is located in the `script` directory of your Rails app do ``` require File.expand_path('../../config/environment', __FILE__) ``` You can control the environment used (development/test/production) by setting the `RAILS_ENV` environment variable when running the script. ``` RAILS_ENV=production ruby script/test.rb ```
You just need: ``` bundle exec rails r ~/my_script.rb ```
9,757,261
I want to run a Ruby file in the context of a Rails environment. rails runner almost does what I want to do, but I'd like to just give it the file name and arguments. I'm pretty sure this is possible since I've done it before. Can someone remind me how to do this?
2012/03/18
[ "https://Stackoverflow.com/questions/9757261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/66702/" ]
The simplest way is with `rails runner` because you don't need to modify your script. `runner` runs Ruby code in the context of Rails non-interactively. <https://guides.rubyonrails.org/command_line.html#bin-rails-runner> Just say `rails runner script.rb`
[Runner](http://guides.rubyonrails.org/command_line.html#rails-runner) runs Ruby code in the context of Rails non-interactively. From `rails runner` command: ``` Usage: runner [options] ('Some.ruby(code)' or a filename) -e, --environment=name Specifies the environment for the runner to operate under (test/development/production). Default: development -h, --help Show this help message. ``` You can also use runner as a shebang line for your scripts like this: ``` ------------------------------------------------------------- #!/usr/bin/env /Users/me/rails_project/script/rails runner Product.all.each { |p| p.price *= 2 ; p.save! } ------------------------------------------------------------- ```
9,757,261
I want to run a Ruby file in the context of a Rails environment. rails runner almost does what I want to do, but I'd like to just give it the file name and arguments. I'm pretty sure this is possible since I've done it before. Can someone remind me how to do this?
2012/03/18
[ "https://Stackoverflow.com/questions/9757261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/66702/" ]
The simplest way is with `rails runner` because you don't need to modify your script. `runner` runs Ruby code in the context of Rails non-interactively. <https://guides.rubyonrails.org/command_line.html#bin-rails-runner> Just say `rails runner script.rb`
This is an old question, but in my opinion I often find it helpful to create a rake task... and it's actually very easy. In `lib/tasks/example.rake`: ``` namespace :example do desc "Sample description you'd see if you ran: 'rake --tasks' in the terminal" task create_user: :environment do User.create! first_name: "Foo", last_name: "Bar" end ``` And then in the terminal run: ``` rake example:create_user ``` Locally this will be run in the context of your development database, and if run on Heroku it will be run while connected to your production database. I find this especially useful to assist with migrations, or modified tables.
9,757,261
I want to run a Ruby file in the context of a Rails environment. rails runner almost does what I want to do, but I'd like to just give it the file name and arguments. I'm pretty sure this is possible since I've done it before. Can someone remind me how to do this?
2012/03/18
[ "https://Stackoverflow.com/questions/9757261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/66702/" ]
The simplest way is with `rails runner` because you don't need to modify your script. `runner` runs Ruby code in the context of Rails non-interactively. <https://guides.rubyonrails.org/command_line.html#bin-rails-runner> Just say `rails runner script.rb`
You just need: ``` bundle exec rails r ~/my_script.rb ```
9,757,261
I want to run a Ruby file in the context of a Rails environment. rails runner almost does what I want to do, but I'd like to just give it the file name and arguments. I'm pretty sure this is possible since I've done it before. Can someone remind me how to do this?
2012/03/18
[ "https://Stackoverflow.com/questions/9757261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/66702/" ]
[Runner](http://guides.rubyonrails.org/command_line.html#rails-runner) runs Ruby code in the context of Rails non-interactively. From `rails runner` command: ``` Usage: runner [options] ('Some.ruby(code)' or a filename) -e, --environment=name Specifies the environment for the runner to operate under (test/development/production). Default: development -h, --help Show this help message. ``` You can also use runner as a shebang line for your scripts like this: ``` ------------------------------------------------------------- #!/usr/bin/env /Users/me/rails_project/script/rails runner Product.all.each { |p| p.price *= 2 ; p.save! } ------------------------------------------------------------- ```
This is an old question, but in my opinion I often find it helpful to create a rake task... and it's actually very easy. In `lib/tasks/example.rake`: ``` namespace :example do desc "Sample description you'd see if you ran: 'rake --tasks' in the terminal" task create_user: :environment do User.create! first_name: "Foo", last_name: "Bar" end ``` And then in the terminal run: ``` rake example:create_user ``` Locally this will be run in the context of your development database, and if run on Heroku it will be run while connected to your production database. I find this especially useful to assist with migrations, or modified tables.
9,757,261
I want to run a Ruby file in the context of a Rails environment. rails runner almost does what I want to do, but I'd like to just give it the file name and arguments. I'm pretty sure this is possible since I've done it before. Can someone remind me how to do this?
2012/03/18
[ "https://Stackoverflow.com/questions/9757261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/66702/" ]
[Runner](http://guides.rubyonrails.org/command_line.html#rails-runner) runs Ruby code in the context of Rails non-interactively. From `rails runner` command: ``` Usage: runner [options] ('Some.ruby(code)' or a filename) -e, --environment=name Specifies the environment for the runner to operate under (test/development/production). Default: development -h, --help Show this help message. ``` You can also use runner as a shebang line for your scripts like this: ``` ------------------------------------------------------------- #!/usr/bin/env /Users/me/rails_project/script/rails runner Product.all.each { |p| p.price *= 2 ; p.save! } ------------------------------------------------------------- ```
You just need: ``` bundle exec rails r ~/my_script.rb ```
9,757,261
I want to run a Ruby file in the context of a Rails environment. rails runner almost does what I want to do, but I'd like to just give it the file name and arguments. I'm pretty sure this is possible since I've done it before. Can someone remind me how to do this?
2012/03/18
[ "https://Stackoverflow.com/questions/9757261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/66702/" ]
This is an old question, but in my opinion I often find it helpful to create a rake task... and it's actually very easy. In `lib/tasks/example.rake`: ``` namespace :example do desc "Sample description you'd see if you ran: 'rake --tasks' in the terminal" task create_user: :environment do User.create! first_name: "Foo", last_name: "Bar" end ``` And then in the terminal run: ``` rake example:create_user ``` Locally this will be run in the context of your development database, and if run on Heroku it will be run while connected to your production database. I find this especially useful to assist with migrations, or modified tables.
You just need: ``` bundle exec rails r ~/my_script.rb ```
21,663,570
Reading C11 Standard, when speaking about `main()` I read: > > 5.1.2.2.1 "...[main] shall be defined with a return type of int". > > 5.1.2.2.3 "...If the return type is not compatible with int,..." > > > The latter suggest that I can define `main()` to return a non integer value. How is it possible if main "shall" return int? And also, "The implementation declares no prototype for this function" gives freedom to use a non-integer return type? Why immediately after says: "[main] shall be defined with a return type of int"?
2014/02/09
[ "https://Stackoverflow.com/questions/21663570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2431763/" ]
The full quote says `If the return type is not compatible with int, the termination status returned to the host environment is unspecified.` That means it's undefined behavior. When `main()` exits, the program is essentially terminating, and the return value of main will be used as the exit status of the program. Since on most systems programs can only return an integer as their exit status, the return value of main is used as that exit code. Returning a string or pointer or whatever means you're returning something that the calling environment can't deal with.
> > The implementation declares no prototype for this function. > > > That is, there's no existing prototype; whether you define it as `int main(void)`, `int main (int argc, char *argv[])`, or in "some other implementation-defined manner", you won't be conflicting with some implicit prototype. > > or in some other implementation-defined manner. > > > If we read this as governing the return type as well, then there's no conflict with what comes later, because this basically says that the signature of `main` can be whatever you like, if it makes sense for the implementation — and later — but, if `main` returns `int` or something convertible to `int` then returning from `main` has to be equivalent to calling `exit` (since `exit` is declared `void exit(int)`). One possible point against my reading, though, is that if this was the intent I would expect it to say that the behavior when the return type is not `int` is *implementation-defined*, rather than undefined.
21,663,570
Reading C11 Standard, when speaking about `main()` I read: > > 5.1.2.2.1 "...[main] shall be defined with a return type of int". > > 5.1.2.2.3 "...If the return type is not compatible with int,..." > > > The latter suggest that I can define `main()` to return a non integer value. How is it possible if main "shall" return int? And also, "The implementation declares no prototype for this function" gives freedom to use a non-integer return type? Why immediately after says: "[main] shall be defined with a return type of int"?
2014/02/09
[ "https://Stackoverflow.com/questions/21663570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2431763/" ]
I have the impression that the sentence > > or in some other implementation-defined manner. > > > leads to confusion here. *implementation-defined* is the C standard jargon for *defined and documented* by the compiler provider. This doesn't mean that the programmer is free to chose an arbitrary prototype for `main`. It means that he *may* use a different prototype if his compiler documentation foresees it. The only other platform specific return type I know of is `void`, which is allowed on some oldish platforms. For the arguments to `main`, I know of platforms that allow for a third parameter that passes a pointer to the environment.
> > The implementation declares no prototype for this function. > > > That is, there's no existing prototype; whether you define it as `int main(void)`, `int main (int argc, char *argv[])`, or in "some other implementation-defined manner", you won't be conflicting with some implicit prototype. > > or in some other implementation-defined manner. > > > If we read this as governing the return type as well, then there's no conflict with what comes later, because this basically says that the signature of `main` can be whatever you like, if it makes sense for the implementation — and later — but, if `main` returns `int` or something convertible to `int` then returning from `main` has to be equivalent to calling `exit` (since `exit` is declared `void exit(int)`). One possible point against my reading, though, is that if this was the intent I would expect it to say that the behavior when the return type is not `int` is *implementation-defined*, rather than undefined.
6,707,062
I am trying to assign a delegate's method to a UIButton using `addTarget:action:forControlEvents:`. Everything compiles without warnings, the IBOutlet is connected to the button in Interface Bulder (XCode 4). If I moves the delegate's method to the controller, it works fine. (All code worked fine, but I refactored to use a delegate, it's my first try with delegates and protocols.) (added) The protocol declaration, placed before @interface in the .h: ``` @protocol MMGLVDelegate<NSObject> -(void)receiveQuitRequest:(id)sender; @end ``` In the controller interface, these properties: ``` @property (nonatomic, assign) id<TheDelegateProtocol> delegate; @property (nonatomic, retain) IBOutlet UIButton *quitBtn; ``` In the controller implementation: ``` -(void)setDelegate:(id<MMGLVDelegate>)delegate { DLog(@"MMGLVSegmented setDelegate: Entered"); _delegate = delegate; [self.quitBtn addTarget:self.delegate action:@selector(receiveQuitRequest:) forControlEvents:UIControlEventTouchUpInside]; } ``` Any help appreciated. Changing target to any of self.delegate, \_delegate, or delegate doesn't change app behavior. What I'm hoping to do is not have to declare a class receiveQuitRequest: that then passes off to the delegate, I'd rather go straight to the delegate from the control.
2011/07/15
[ "https://Stackoverflow.com/questions/6707062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/539662/" ]
I think you should write ``` [self.quitBtn addTarget:delegate action:@selector(receiveQuitRequest:) forControlEvents:UIControlEventTouchUpInside]; ``` I am not sure, but this may work in your case
I have a couple of minor suggestions: 1. Try disconnecting and re-connecting the delegate for the button in IB. I've noticed that sometimes this seems to reset it properly. 2. Clean and rebuild. Again, this helps to reset things that didn't get set properly.
6,707,062
I am trying to assign a delegate's method to a UIButton using `addTarget:action:forControlEvents:`. Everything compiles without warnings, the IBOutlet is connected to the button in Interface Bulder (XCode 4). If I moves the delegate's method to the controller, it works fine. (All code worked fine, but I refactored to use a delegate, it's my first try with delegates and protocols.) (added) The protocol declaration, placed before @interface in the .h: ``` @protocol MMGLVDelegate<NSObject> -(void)receiveQuitRequest:(id)sender; @end ``` In the controller interface, these properties: ``` @property (nonatomic, assign) id<TheDelegateProtocol> delegate; @property (nonatomic, retain) IBOutlet UIButton *quitBtn; ``` In the controller implementation: ``` -(void)setDelegate:(id<MMGLVDelegate>)delegate { DLog(@"MMGLVSegmented setDelegate: Entered"); _delegate = delegate; [self.quitBtn addTarget:self.delegate action:@selector(receiveQuitRequest:) forControlEvents:UIControlEventTouchUpInside]; } ``` Any help appreciated. Changing target to any of self.delegate, \_delegate, or delegate doesn't change app behavior. What I'm hoping to do is not have to declare a class receiveQuitRequest: that then passes off to the delegate, I'd rather go straight to the delegate from the control.
2011/07/15
[ "https://Stackoverflow.com/questions/6707062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/539662/" ]
I think you should write ``` [self.quitBtn addTarget:delegate action:@selector(receiveQuitRequest:) forControlEvents:UIControlEventTouchUpInside]; ``` I am not sure, but this may work in your case
If I've understood everything correctly, the UIButton does not include a `receiveQuitRequest:` selector, so there is nothing to be executed when the user touches the button.
46,547,137
I have a project in my C++ class - we're supposed to make a "simple student management system" comprised of a class for the student attribute variables, and a main function with a branch statement that lets the user input names and IDs for the students. I know that I need to use an array to make "slots" for the students, and that my branch statements need to let the user input values into those slots, but I'm not exactly sure how to do it. Here is the code that I have so far. ``` #include <string> #include <iostream> #include <utility> using std::string; using std::cin; using std::cout; using std::endl; struct Student { private: int id; string name; int birthday; public: Student() { id = 0; birthday = 0; } Student(int id, string name, int birthday) { //set your parameters to the class variables this->id = id; this->name = name; this->birthday = birthday; } void setID(int id) { this->id = id; } int getID() { return id; } void setName(string name) { this->name = name; } string getName() { return name; } void setBirthday(int birthday) { this->birthday = birthday; } int getBirthday() { return birthday; } void output() { cout << id << name << birthday << endl; } }; int main() { Student arr[50]; cout << "Student Management System" << endl; cout << "Press 'a' to add a student" << endl; char a = 1; int y = 1; while (a == 'a') { switch (y) { cout << "Input Student ID:"; cin >> id; } } } ``` What I'm focusing on most is the fourth line from the bottom. I was told that I need to use my setters, so I said that I want what my user inputs to be treated as the value of the ID variable that I set in the class. However, when I wrote this out, I was given an error. Could someone tell me what the issue is?
2017/10/03
[ "https://Stackoverflow.com/questions/46547137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8712278/" ]
Perhaps this will work for you ``` ans <- apply(M, 2, function(i) toString(unlist(i))) ans[1] # Genes # "PARP, BRCA1, BRCA2, PARP-1/2, BRCA" ```
using do.call,bind\_rows did the job!Thank you for your answers!
46,547,137
I have a project in my C++ class - we're supposed to make a "simple student management system" comprised of a class for the student attribute variables, and a main function with a branch statement that lets the user input names and IDs for the students. I know that I need to use an array to make "slots" for the students, and that my branch statements need to let the user input values into those slots, but I'm not exactly sure how to do it. Here is the code that I have so far. ``` #include <string> #include <iostream> #include <utility> using std::string; using std::cin; using std::cout; using std::endl; struct Student { private: int id; string name; int birthday; public: Student() { id = 0; birthday = 0; } Student(int id, string name, int birthday) { //set your parameters to the class variables this->id = id; this->name = name; this->birthday = birthday; } void setID(int id) { this->id = id; } int getID() { return id; } void setName(string name) { this->name = name; } string getName() { return name; } void setBirthday(int birthday) { this->birthday = birthday; } int getBirthday() { return birthday; } void output() { cout << id << name << birthday << endl; } }; int main() { Student arr[50]; cout << "Student Management System" << endl; cout << "Press 'a' to add a student" << endl; char a = 1; int y = 1; while (a == 'a') { switch (y) { cout << "Input Student ID:"; cin >> id; } } } ``` What I'm focusing on most is the fourth line from the bottom. I was told that I need to use my setters, so I said that I want what my user inputs to be treated as the value of the ID variable that I set in the class. However, when I wrote this out, I was given an error. Could someone tell me what the issue is?
2017/10/03
[ "https://Stackoverflow.com/questions/46547137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8712278/" ]
Your data is matrix. That is why you are seeing in form of a list. You can access it using matrix index or you can convert it into data frame then access using its column as below: ``` ##Your Data: M1 <- structure(list(c("PARP", "BRCA1", "BRCA2", "PARP-1/2", "BRCA" ), c("ovarian, fallopian tube", "peritoneal cancer", "tumor", "toxicity", "ovarian cancer", "thrombocytopenia", "fatigue", "nausea", "leukopenia", "neutropenia", "vomiting", "anemia"), NULL, c("veliparib", "Veliparib", "platinum"), "patients", 25818403), .Dim = c(1L, 6L), .Dimnames = list(NULL, c("Genes", "Diseases", "Mutations", "Chemicals", "Species", "PMID"))) class(M1) #[1] "matrix" ### It's matrix. So, to access it, you use row number and column number M1[1, 1] #$Genes #[1] "PARP" "BRCA1" "BRCA2" "PARP-1/2" "BRCA" M1[1, 2] #$Diseases #[1] "ovarian, fallopian tube" "peritoneal cancer" "tumor" #[4] "toxicity" "ovarian cancer" "thrombocytopenia" #[7] "fatigue" "nausea" "leukopenia" #[10] "neutropenia" "vomiting" "anemia" ## You can also convert to data frame then access it by column as below: # Converting your matrix M1 to data.frame df <- as.data.frame(M1) class(df) #[1] "data.frame" df$Genes $Genes #[1] "PARP" "BRCA1" "BRCA2" "PARP-1/2" "BRCA" ##You can do unlist your list unlist(df$Genes) #Genes1 Genes2 Genes3 Genes4 Genes5 #"PARP" "BRCA1" "BRCA2" "PARP-1/2" "BRCA" ## You can convert it into data frame after you unlist data.frame(unlist(df$Genes)) # unlist.df.Genes. # Genes1 PARP # Genes2 BRCA1 # Genes3 BRCA2 # Genes4 PARP-1/2 # Genes5 BRCA ``` I hope this helps you.
using do.call,bind\_rows did the job!Thank you for your answers!
19,707,674
I am trying to run the following code to access a DBF file in folder. the name of the file if RF10.dbf: ``` foxpro = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Documents and Settings\\xxxxxx\\xxxxx\\xxxxx\\;Extended Properties=dBASE IV;User ID=ADMIN;Password=;"); try { foxpro.Open(); label4.Text = "Connected"; } catch (OleDbException oex) { label4.Text = "Connection Failed"; // connection error } ``` And executing following query: ``` OleDbCommand fpcmd = new OleDbCommand(); fpcmd.Connection = foxpro; fpcmd.CommandText = "SELECT * FROM RF10.DBF WHERE SRNO='RDDFT000108'"; fpcmd.CommandType = CommandType.Text; fpcmd.CommandTimeout = 300; try { acompressor = (String)fpcmd.ExecuteScalar(); // SqlDataAdapter da = new SqlDataAdapter(cmd1); //DataSet ds = new DataSet(); // da.Fill(ds); if (acompressor == null) acompressor = ""; if (acompressor.Equals(compressor)) { MessageBox.Show("Serial number and compressor number is a correct match."); textBox1.Text = ""; textBox2.Text = ""; } else { MessageBox.Show("Serial number and compressor number DO NOT match."); textBox1.Text = ""; textBox2.Text = ""; } } catch (OleDbException oex) { Console.Write(fpcmd.CommandText); Console.Write(oex.Message); // command related or other exception } ``` The problem is when the query is executed it gives the following error: > > The Microsoft Jet database engine could not find the object > 'RF10.DBF'. Make sure the object exists and that you spell its name > and the path name correctly. > > > However, there exist a file named RF10.dbf. Where am I going wrong?
2013/10/31
[ "https://Stackoverflow.com/questions/19707674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1451836/" ]
IIRC you don't include the extension in the query: ``` fpcmd.CommandText = "SELECT * FROM RF10 WHERE SRNO='RDDFT000108'"; ```
It might be your access rights to the folder or file. Have you checked that?
19,707,674
I am trying to run the following code to access a DBF file in folder. the name of the file if RF10.dbf: ``` foxpro = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Documents and Settings\\xxxxxx\\xxxxx\\xxxxx\\;Extended Properties=dBASE IV;User ID=ADMIN;Password=;"); try { foxpro.Open(); label4.Text = "Connected"; } catch (OleDbException oex) { label4.Text = "Connection Failed"; // connection error } ``` And executing following query: ``` OleDbCommand fpcmd = new OleDbCommand(); fpcmd.Connection = foxpro; fpcmd.CommandText = "SELECT * FROM RF10.DBF WHERE SRNO='RDDFT000108'"; fpcmd.CommandType = CommandType.Text; fpcmd.CommandTimeout = 300; try { acompressor = (String)fpcmd.ExecuteScalar(); // SqlDataAdapter da = new SqlDataAdapter(cmd1); //DataSet ds = new DataSet(); // da.Fill(ds); if (acompressor == null) acompressor = ""; if (acompressor.Equals(compressor)) { MessageBox.Show("Serial number and compressor number is a correct match."); textBox1.Text = ""; textBox2.Text = ""; } else { MessageBox.Show("Serial number and compressor number DO NOT match."); textBox1.Text = ""; textBox2.Text = ""; } } catch (OleDbException oex) { Console.Write(fpcmd.CommandText); Console.Write(oex.Message); // command related or other exception } ``` The problem is when the query is executed it gives the following error: > > The Microsoft Jet database engine could not find the object > 'RF10.DBF'. Make sure the object exists and that you spell its name > and the path name correctly. > > > However, there exist a file named RF10.dbf. Where am I going wrong?
2013/10/31
[ "https://Stackoverflow.com/questions/19707674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1451836/" ]
IIRC you don't include the extension in the query: ``` fpcmd.CommandText = "SELECT * FROM RF10 WHERE SRNO='RDDFT000108'"; ```
Try to use the full file path: ``` fpcmd.CommandText = "SELECT * FROM 'D:\some_folder\RF10.DBF' WHERE SRNO='RDDFT000108'"; ```
58,014,868
I have a script that looks for duplicates. I want to know how now to delete those duplicates. ``` Select LastName, FirstName, DateOfBirth, Count (*) As Duplicates From PatientDemographics2 Group by FirstName, LastName, DateOfBirth Having count (*) >1 Order by LastName, FirstName Asc ```
2019/09/19
[ "https://Stackoverflow.com/questions/58014868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6391005/" ]
You can `ROW_NUMBER()` to detect duplicate ``` WITH cte AS ( SELECT LastName, FirstName, DateOfBirth , ROW_NUMBER() OVER(PARTITION BY LastName, FirstName, DateOfBirth ORDER BY LastName) AS rn FROM PatientDemographic2 ) DELETE FROM cte WHERE rn > 1 ```
Or simply: ``` DELETE FROM PatientDemographics2 WHERE id NOT IN ( SELECT MIN(id) i1 FROM PatientDemographics2 GROUP BY FirstName, LastName, DateOfBirth ) ``` demo: <https://rextester.com/KOZI16883>
31,445,899
a piece of code in an enum (deck of cards, they should have a 'status' either true or false) ``` enum Card:Int { case zero = 0, one, two, three, four, five, six, seven, eight, nine init() { self = .zero } init?(digit: Int) { switch digit { case 0: self = .zero case 1: self = .one case 2: self = .two case 3: self = .three case 4: self = .four case 5: self = .five case 6: self = .six case 7: self = .seven case 8: self = .eight case 9: self = .nine default: return nil } } var status { get { switch self { case .zero: return false case .one: return false case .two: return false case .three: return false case .four: return false case .five: return false case .six: return false case .seven: return false case .eight: return false case .nine: return false } } } ``` I'm trying to make a mutating function here that will change their value to true when function runs ``` mutating func swap() { switch status { case TRUE: self = false case false: self = TRUE } } } ``` code above doesnt work.
2015/07/16
[ "https://Stackoverflow.com/questions/31445899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5101499/" ]
**create a structure called Cards** which has **two stored properties** one of **Card enum** type and another of **Bool type to keep track of status** here you can declare a function swap() which changes the status value: ``` struct Cards { let card:Card? //This property stores an instance of Card enum var status = true mutating func swap() { self.status = !self.status } init(cardDigit: Int) { self.card = Card(digit: cardDigit) } init() { self.card = Card() } } var aCard :Cards = Cards(cardDigit: 2) aCard.status // returns true aCard.swap() aCard.status //returns false ``` You can remove the status computed property from enum, because we can access it from structure.
In case you do not want to use structs, another approach could be returning a new instance of the enum ``` func swap(status: Bool) -> Card { var card = Card() switch status { case true: card.status = false case false: card.status = true } return card } ```
61,526,378
This should be pretty simple, but after 3 hours of googling around, I apparently don't have the right wording to find the answer. I have and XML return that I need to format for a page. I have no control of the return as it is coming from UPS's databases. I have it formatted fine, but now I need to increase the returned rate by $4. This should be easy, but I'm very new to all of this and at a complete loss. Here is the relevant portion of the returned XML: ``` <Response> <ResponseStatusCode>1</ResponseStatusCode> <ResponseStatusDescription>Success</ResponseStatusDescription></Response> <RatedShipment> <Service><Code>03</Code></Service> <TotalCharges> <CurrencyCode>USD</CurrencyCode> <MonetaryValue>21.17</MonetaryValue></TotalCharges> </RatedShipment> </Response> ``` Here is the relevant portion of the XSL formatting: ``` <xsl:template match="/"> <select name="shipping_options" id="shipping_options"> <xsl:for-each select="/RatingServiceSelectionResponse/RatedShipment"> <xsl:choose> <xsl:when test="Service/Code = 01"> <xsl:element name="option"> <xsl:attribute name='value'> 1!!! <xsl:value-of select="TotalCharges/MonetaryValue"/> </xsl:attribute> UPS Next Day Air - $ <xsl:value-of select="format-number(TotalCharges/MonetaryValue, '###,###.00')"/> </xsl:element> </xsl:when> </xsl:choose> </xsl:for-each> </select> ``` Edit: The format for the XSL is correct for other needs later. The desired final output looks like this: ``` <select name="shipping_options" id="shipping_options"> <option value="">Enter Zip Code To Update</option> <option value="1!!!77.49">UPS Next Day Air - $77.49</option> <option value="2!!!51.20">UPS 2nd Day Air - $51.20</option> <option value="3!!!22.73">UPS Ground - $22.73</option> <option value="4!!!38.01">UPS 3 Day Select - $38.01</option> <option value="5!!!71.02">UPS Next Day Air Saver - $71.02</option> <option value="6!!!108.01">UPS Next Day Air Early - $108.01</option> <option value="8!!!0.00">Please call for freight pricing - $0.00</option> <option value="9!!!0.00">Please call for international pricing - $0.00</option> </select> ``` Edit #2: it was literally as easy as it should have been. Just had to change this one bit to add "+4": ``` select="format-number(TotalCharges/MonetaryValue + 4, '###,###.00')" ```
2020/04/30
[ "https://Stackoverflow.com/questions/61526378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6692956/" ]
you need to append the protocol at the start of the url or the browser will take it as a relative url to your document. ```html <form id="searchWikipedia" action="" onsubmit="searchWikipedia()"> <input id="search" name="search" type="text" /> <select id="lang" name="language"> <option value="en">English</option> <option value="fr">French</option> </select> </form> <script> function searchWikipedia() { var select = document.getElementById("lang"); var selectValue = select.options[select.selectedIndex].value; var searchValue = document.getElementById("search").value; // append https at the start document.getElementById("searchWikipedia").action = "https://" + selectValue + ".wikipedia.org/w/index.php?search=" + searchValue; document.getElementById("searchWikipedia").submit(); } </script> ```
Add Submit input tag, to perform action ```html <form id="searchWikipedia" action="" onsubmit="searchWikipedia(event)"> <input id="search" name="search" type="text" /> <select id="lang" name="language"> <option value="en">English</option> <option value="fr">French</option> </select> <input type="submit" value="Search"> </form> <script> function searchWikipedia(event) { event.preventDefault(); var select = document.getElementById("lang"); var selectValue = select.options[select.selectedIndex].value; var searchValue = document.getElementById("search").value; // it will open new tab window.open("https://" + selectValue + ".wikipedia.org/w/index.php?search=" + searchValue); // if you want to replace same url then use this // window.location.replace(`https://${selectValue}.wikipedia.org/w/index.php?search=${searchValue}`); } </script> ``` I think, it will be helpful for you.
28,626,064
I have an app where I want to execute a jQuery `equalize()` function on some `DIV` boxes every time my "pages" change. At the moment I have the code inside my main layout's `render()` function but it is executed only once the user reloads the whole page. I tried to use `autorun` but this didn't work out either. Meteor 1.0.3.1 + iron:router **EDIT:** I have different page views with routes (e.g. /home, /about-us, /terms, ...) and once the user navigates to a page (meaning follows a route to another view) the code should be executed.
2015/02/20
[ "https://Stackoverflow.com/questions/28626064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3481734/" ]
If you are using [iron-router](https://github.com/iron-meteor/iron-router/blob/devel/Guide.md), then try this: ``` Router.onAfterAction( function(){ // select divs and apply equalize }, { only: ['admin'] // or except: ['routeOne', 'routeTwo'] } ); ```
Take a look at [hooks](https://github.com/iron-meteor/iron-router/blob/devel/Guide.md#hooks) in IronRouter. Add an `onBeforeAction` hook to your router configuration to apply it to all routes. ``` Router.onBeforeAction(function () { //dostuff }) ```
6,833,511
I have a textbox that the user can input into. Right now the user can enter in anything, but I would like to limit the user. * I first need to only allow **numbers** from the user that are **negative or positive, and/or decimal (up to 3 digits)**. In the RichTextBox the data looks like this: ``` 227.905 227.905 242.210 -236.135 5.610 29.665 269.665 ``` ***SO***, what I am trying to do is add the string value from the TextBox to each one of these lines in the RichTextBox. **EXAMPLE:** If the user entered in ***"25.305"*** into the TextBox it would add that value to each one of the values in the RichTextBox and then replacing that value in the RichTextBox with the new value making the *updated* RichTextBox look like this: ``` 253.210 253.210 267.515 -210.830 30.915 54.970 294.970 ``` * Does anyone know how to do this?
2011/07/26
[ "https://Stackoverflow.com/questions/6833511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/864197/" ]
One is your basic division operation: ``` 10/5 => 2 10/4 => 2.5 ``` The other is the modulo operator, which will give you the integer remainder of the division operation. ``` 10%5 => 0 10%4 => 2 ```
10 / 5 is 10 divided by 5, or [basic division](https://en.wikipedia.org/wiki/Division_(mathematics)). 10 % 5 is 10 modulo 5, or [the remainder of a division operation](https://en.wikipedia.org/wiki/Modulo_operation).
6,833,511
I have a textbox that the user can input into. Right now the user can enter in anything, but I would like to limit the user. * I first need to only allow **numbers** from the user that are **negative or positive, and/or decimal (up to 3 digits)**. In the RichTextBox the data looks like this: ``` 227.905 227.905 242.210 -236.135 5.610 29.665 269.665 ``` ***SO***, what I am trying to do is add the string value from the TextBox to each one of these lines in the RichTextBox. **EXAMPLE:** If the user entered in ***"25.305"*** into the TextBox it would add that value to each one of the values in the RichTextBox and then replacing that value in the RichTextBox with the new value making the *updated* RichTextBox look like this: ``` 253.210 253.210 267.515 -210.830 30.915 54.970 294.970 ``` * Does anyone know how to do this?
2011/07/26
[ "https://Stackoverflow.com/questions/6833511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/864197/" ]
``` 10/5 = 2 10%5 = 0 ``` `%` is modulo
<http://www.w3schools.com/js/js_operators.asp> 10 / 5 is 2. 10 % 5 is 0.
6,833,511
I have a textbox that the user can input into. Right now the user can enter in anything, but I would like to limit the user. * I first need to only allow **numbers** from the user that are **negative or positive, and/or decimal (up to 3 digits)**. In the RichTextBox the data looks like this: ``` 227.905 227.905 242.210 -236.135 5.610 29.665 269.665 ``` ***SO***, what I am trying to do is add the string value from the TextBox to each one of these lines in the RichTextBox. **EXAMPLE:** If the user entered in ***"25.305"*** into the TextBox it would add that value to each one of the values in the RichTextBox and then replacing that value in the RichTextBox with the new value making the *updated* RichTextBox look like this: ``` 253.210 253.210 267.515 -210.830 30.915 54.970 294.970 ``` * Does anyone know how to do this?
2011/07/26
[ "https://Stackoverflow.com/questions/6833511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/864197/" ]
``` 10/5 = 2 10%5 = 0 ``` `%` is modulo
% is the modulus operator: it gives you the remainder of the division.
6,833,511
I have a textbox that the user can input into. Right now the user can enter in anything, but I would like to limit the user. * I first need to only allow **numbers** from the user that are **negative or positive, and/or decimal (up to 3 digits)**. In the RichTextBox the data looks like this: ``` 227.905 227.905 242.210 -236.135 5.610 29.665 269.665 ``` ***SO***, what I am trying to do is add the string value from the TextBox to each one of these lines in the RichTextBox. **EXAMPLE:** If the user entered in ***"25.305"*** into the TextBox it would add that value to each one of the values in the RichTextBox and then replacing that value in the RichTextBox with the new value making the *updated* RichTextBox look like this: ``` 253.210 253.210 267.515 -210.830 30.915 54.970 294.970 ``` * Does anyone know how to do this?
2011/07/26
[ "https://Stackoverflow.com/questions/6833511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/864197/" ]
``` 10/5 = 2 10%5 = 0 ``` `%` is modulo
In pretty much every language % is a modulus not a divide symbol. It does divide but it gives you just the remainder rather than the divided number.
6,833,511
I have a textbox that the user can input into. Right now the user can enter in anything, but I would like to limit the user. * I first need to only allow **numbers** from the user that are **negative or positive, and/or decimal (up to 3 digits)**. In the RichTextBox the data looks like this: ``` 227.905 227.905 242.210 -236.135 5.610 29.665 269.665 ``` ***SO***, what I am trying to do is add the string value from the TextBox to each one of these lines in the RichTextBox. **EXAMPLE:** If the user entered in ***"25.305"*** into the TextBox it would add that value to each one of the values in the RichTextBox and then replacing that value in the RichTextBox with the new value making the *updated* RichTextBox look like this: ``` 253.210 253.210 267.515 -210.830 30.915 54.970 294.970 ``` * Does anyone know how to do this?
2011/07/26
[ "https://Stackoverflow.com/questions/6833511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/864197/" ]
``` 10/5 = 2 10%5 = 0 ``` `%` is modulo
One is your basic division operation: ``` 10/5 => 2 10/4 => 2.5 ``` The other is the modulo operator, which will give you the integer remainder of the division operation. ``` 10%5 => 0 10%4 => 2 ```
6,833,511
I have a textbox that the user can input into. Right now the user can enter in anything, but I would like to limit the user. * I first need to only allow **numbers** from the user that are **negative or positive, and/or decimal (up to 3 digits)**. In the RichTextBox the data looks like this: ``` 227.905 227.905 242.210 -236.135 5.610 29.665 269.665 ``` ***SO***, what I am trying to do is add the string value from the TextBox to each one of these lines in the RichTextBox. **EXAMPLE:** If the user entered in ***"25.305"*** into the TextBox it would add that value to each one of the values in the RichTextBox and then replacing that value in the RichTextBox with the new value making the *updated* RichTextBox look like this: ``` 253.210 253.210 267.515 -210.830 30.915 54.970 294.970 ``` * Does anyone know how to do this?
2011/07/26
[ "https://Stackoverflow.com/questions/6833511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/864197/" ]
One is your basic division operation: ``` 10/5 => 2 10/4 => 2.5 ``` The other is the modulo operator, which will give you the integer remainder of the division operation. ``` 10%5 => 0 10%4 => 2 ```
% is the modulus operator: it gives you the remainder of the division.
6,833,511
I have a textbox that the user can input into. Right now the user can enter in anything, but I would like to limit the user. * I first need to only allow **numbers** from the user that are **negative or positive, and/or decimal (up to 3 digits)**. In the RichTextBox the data looks like this: ``` 227.905 227.905 242.210 -236.135 5.610 29.665 269.665 ``` ***SO***, what I am trying to do is add the string value from the TextBox to each one of these lines in the RichTextBox. **EXAMPLE:** If the user entered in ***"25.305"*** into the TextBox it would add that value to each one of the values in the RichTextBox and then replacing that value in the RichTextBox with the new value making the *updated* RichTextBox look like this: ``` 253.210 253.210 267.515 -210.830 30.915 54.970 294.970 ``` * Does anyone know how to do this?
2011/07/26
[ "https://Stackoverflow.com/questions/6833511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/864197/" ]
10/5 is division operation and depending on the data type storing the result in might not give you the result expected. if storing in a int you will loose the remainder. 10%2 is a modulus operation. it will return the remainder from the division and is commonly used to determine if a number is odd or even. take any given number mod 2 (N%2) and if the result is is 0 then you know the number is even.
10/5 divides 10/5 = 2 10%5 divides 5 and returns the remainder, 0, so 10%5 = 0
6,833,511
I have a textbox that the user can input into. Right now the user can enter in anything, but I would like to limit the user. * I first need to only allow **numbers** from the user that are **negative or positive, and/or decimal (up to 3 digits)**. In the RichTextBox the data looks like this: ``` 227.905 227.905 242.210 -236.135 5.610 29.665 269.665 ``` ***SO***, what I am trying to do is add the string value from the TextBox to each one of these lines in the RichTextBox. **EXAMPLE:** If the user entered in ***"25.305"*** into the TextBox it would add that value to each one of the values in the RichTextBox and then replacing that value in the RichTextBox with the new value making the *updated* RichTextBox look like this: ``` 253.210 253.210 267.515 -210.830 30.915 54.970 294.970 ``` * Does anyone know how to do this?
2011/07/26
[ "https://Stackoverflow.com/questions/6833511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/864197/" ]
``` 10/5 = 2 10%5 = 0 ``` `%` is modulo
10/5 divides 10/5 = 2 10%5 divides 5 and returns the remainder, 0, so 10%5 = 0
6,833,511
I have a textbox that the user can input into. Right now the user can enter in anything, but I would like to limit the user. * I first need to only allow **numbers** from the user that are **negative or positive, and/or decimal (up to 3 digits)**. In the RichTextBox the data looks like this: ``` 227.905 227.905 242.210 -236.135 5.610 29.665 269.665 ``` ***SO***, what I am trying to do is add the string value from the TextBox to each one of these lines in the RichTextBox. **EXAMPLE:** If the user entered in ***"25.305"*** into the TextBox it would add that value to each one of the values in the RichTextBox and then replacing that value in the RichTextBox with the new value making the *updated* RichTextBox look like this: ``` 253.210 253.210 267.515 -210.830 30.915 54.970 294.970 ``` * Does anyone know how to do this?
2011/07/26
[ "https://Stackoverflow.com/questions/6833511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/864197/" ]
10/5 divides 10/5 = 2 10%5 divides 5 and returns the remainder, 0, so 10%5 = 0
In pretty much every language % is a modulus not a divide symbol. It does divide but it gives you just the remainder rather than the divided number.
6,833,511
I have a textbox that the user can input into. Right now the user can enter in anything, but I would like to limit the user. * I first need to only allow **numbers** from the user that are **negative or positive, and/or decimal (up to 3 digits)**. In the RichTextBox the data looks like this: ``` 227.905 227.905 242.210 -236.135 5.610 29.665 269.665 ``` ***SO***, what I am trying to do is add the string value from the TextBox to each one of these lines in the RichTextBox. **EXAMPLE:** If the user entered in ***"25.305"*** into the TextBox it would add that value to each one of the values in the RichTextBox and then replacing that value in the RichTextBox with the new value making the *updated* RichTextBox look like this: ``` 253.210 253.210 267.515 -210.830 30.915 54.970 294.970 ``` * Does anyone know how to do this?
2011/07/26
[ "https://Stackoverflow.com/questions/6833511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/864197/" ]
``` 10/5 = 2 10%5 = 0 ``` `%` is modulo
10 / 5 is 10 divided by 5, or [basic division](https://en.wikipedia.org/wiki/Division_(mathematics)). 10 % 5 is 10 modulo 5, or [the remainder of a division operation](https://en.wikipedia.org/wiki/Modulo_operation).
48,191,584
I'm attempting to write a MVC/Web API page, and am stuck on the Web API post portion when doing more than just base types. I cannot seem to find an answer why the Roles object keeps getting set to null even though it's posting from the client side (and it's passing the ModelState.IsValid portion?) If I take all the code out that relates to the Roles portion, it works and the user gets created in the database. Edit: Changing [FromUri] to [FromBody] combined with adding Bracket around Roles data seemed to do it. Other errors popping up but able to take it from there. Thanks. The defined model: ``` public class ExpandedUser { [Key] [Display(Name = "User Name")] public string UserName { get; set; } public string Email { get; set; } public string Password { get; set; } [Display(Name = "Lockout End Date UTC")] public DateTime? LockoutEndDateUtc { get; set; } public int AccessFailedCount { get; set; } public IEnumerable<UserRoles> Roles { get; set; } } ``` The API: ``` [HttpPost] public IHttpActionResult CreateUser([FromUri] ExpandedUser user) { if (!ModelState.IsValid) { return BadRequest(); } else if (user.Roles == null) { return NotFound(); } var userStore = new UserStore<ApplicationUser>(_context); var userManager = new UserManager<ApplicationUser>(userStore); /*var roleId = user.Roles.ToList(); var role = _context.Roles.Select(c => new { Id = c.Id, Name = c.Name, Users = c.Users }).SingleOrDefault(c => c.Id == roleId.RoleName);*/ var newUser = new ApplicationUser { UserName = user.UserName, Email = user.Email, PasswordHash = userManager.PasswordHasher.HashPassword(user.Password) }; try { _context.Users.Add(newUser); /*userManager.AddToRole(newUser.Id, role.Name);*/ _context.SaveChanges(); } catch { return BadRequest(); } return Ok(); } ``` And the AJAX call: ``` var payload = { Id: 0, UserName: $('#username').val(), Email: $('#email').val(), Password: $('#password').val(), LockoutEndDateUtc: null, AccessFailedCount :0, Roles: { RoleName: $('#role').val() } }; payload = JSON.stringify(payload); console.log(payload); $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: "/api/CreateUser", data: payload, success: function (data) { redir(); }, error: function (jqXHR, textStatus, errorThrown) { }, dataType: "json", }); ```
2018/01/10
[ "https://Stackoverflow.com/questions/48191584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4714723/" ]
As rowNumber seems to be a field of your object I assume that it's also a column in your table. In that case you can just add "ORDER BY rowNumber" to your HQL query and don't use Collections.sort
You need a Comparator which can sort by your desired criteria: ``` Comparator<? super TestFlow> comparator = new Comparator<TestFlow>() { @Override public int compare(TestFlow o1, TestFlow o2) { return o1.getRowNumber().compareTo(o2.getRowNumber()); } }; testFlow.sort(comparator); ``` And if you're using Java 8 or 9, this can be reduced to: ``` testFlow.sort(Comparator.comparing(TestFlow::getRowNumber)); ```
20,842,630
I have a StackPanel that contains a TextBox and a Combobox. When I set the focus inside a textbox (not the first one), the Contents of the StackPanel "jumps" and goes to the top. Below is the code. I have researched this and post the one I found and tried (but did not worK). I want to prevent the "jumping". So run the code below. Scroll the vertical bar until you see: ``` Name Three <<Text Box (No Selection) ComboBox \/ Name Four <<Text Box (No Selection) ComboBox \/ ``` Now put your cursor in the "Name Four" text box.......and watch it "jump" to the top. (You don't see Three and Four now, you see Four and Five.) My stackpanel is much more complex than this in real life, and its driving my end-users nutty. Thanks. MainWindow.xaml ``` <Window x:Class="ListBoxControlSample.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="160" Width="250"> <Grid Margin="10"> <ListBox ItemsSource="{Binding Models}" SelectionMode="Single" RequestBringIntoView="FrameworkElement_OnRequestBringIntoView" SelectionChanged="Selector_OnSelectionChanged" > <ListBox.ItemTemplate> <DataTemplate> <StackPanel> <TextBox Text="{Binding Name}"/> <ComboBox VerticalContentAlignment="Top" VerticalAlignment="Top" Grid.Column="1" ItemsSource="{Binding Options}" > </ComboBox> <TextBlock Text="{Binding Title}"></TextBlock> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </Grid> </Window> ``` MainWindow.xaml.cs ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace ListBoxControlSample { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); DataContext = this; } private IList<Model> _models; public IList<Model> Models { get { return _models ?? (_models = new List<Model> { new Model{ Name = "Name One", Title = "Title One"}, new Model{ Name = "Name Two", Title = "Title Two"}, new Model{ Name = "Name Three", Title = "Title Three"}, new Model{ Name = "Name Four", Title = "Title Four"}, new Model{ Name = "Name Five", Title = "Title Five"}, new Model{ Name = "Name Six", Title = "Title Six"}, new Model{ Name = "Name Seven", Title = "Title Seven"} }); } } private void FrameworkElement_OnRequestBringIntoView(object sender, RequestBringIntoViewEventArgs e) { e.Handled = true; } private void Selector_OnSelectionChanged(object sender, SelectionChangedEventArgs e) { //throw new NotImplementedException(); } private void Selector_OnSelected(object sender, RoutedEventArgs e) { //throw new NotImplementedException(); } } public class Model { public string Name { get; set; } public string Title { get; set; } private IList<string> _options; public IList<string> Options { get { return _options ?? (_options = new List<string> { "left", "right", "both" }); } } } } ``` What I've found and tried (to prevent the jumping) ``` <DataTemplate> <StackPanel ScrollViewer.CanContentScroll="False"> ```
2013/12/30
[ "https://Stackoverflow.com/questions/20842630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/214977/" ]
I'm guessing it has something to do with the default scroll behavior of trying to show the full item whenever it gets selected. Try disabling the scrolling, and wrap it in another ScrollViewer: ``` <ScrollViewer VerticalScrollBarVisibility="Auto" CanContentScroll="True" Height="250"> <ListBox ScrollViewer.VerticalScrollBarVisibility="Disabled"> ... </ListBox> </ScrollViewer> ``` This way, instead of trying to scroll each individual `StackPanel` into view at a time, and ensuring the full item is visible, it will try to scroll the entire `ListBox` into view, which exceeds the height allotted to the `ScrollViewer`, so it will use the smoother content-based scrolling that you want. It should be noted that this will render the entire `ListBox` at once, without any virutalization, so it isn't advisable to use this method if you have a lot of rows and are depending on virtualization for performance. But based on your question, it doesn't sound like that is your case. I'm also not positive, but you may have to nest this in one more panel as well to allow the ListBox to grow to whatever height it wants. See [this answer](https://stackoverflow.com/a/8490640/302677) for more details if needed.
The effect is reproducible if you click into the TextBox of the last visible row. If that row isn't fully scrolled into the view the listbox automatically scrolls that line into view to be fully visible. That in turn means all rows scroll up one row which makes you feel the jumping effect. To my knowledge you cannot change that behaviour.
20,842,630
I have a StackPanel that contains a TextBox and a Combobox. When I set the focus inside a textbox (not the first one), the Contents of the StackPanel "jumps" and goes to the top. Below is the code. I have researched this and post the one I found and tried (but did not worK). I want to prevent the "jumping". So run the code below. Scroll the vertical bar until you see: ``` Name Three <<Text Box (No Selection) ComboBox \/ Name Four <<Text Box (No Selection) ComboBox \/ ``` Now put your cursor in the "Name Four" text box.......and watch it "jump" to the top. (You don't see Three and Four now, you see Four and Five.) My stackpanel is much more complex than this in real life, and its driving my end-users nutty. Thanks. MainWindow.xaml ``` <Window x:Class="ListBoxControlSample.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="160" Width="250"> <Grid Margin="10"> <ListBox ItemsSource="{Binding Models}" SelectionMode="Single" RequestBringIntoView="FrameworkElement_OnRequestBringIntoView" SelectionChanged="Selector_OnSelectionChanged" > <ListBox.ItemTemplate> <DataTemplate> <StackPanel> <TextBox Text="{Binding Name}"/> <ComboBox VerticalContentAlignment="Top" VerticalAlignment="Top" Grid.Column="1" ItemsSource="{Binding Options}" > </ComboBox> <TextBlock Text="{Binding Title}"></TextBlock> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </Grid> </Window> ``` MainWindow.xaml.cs ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace ListBoxControlSample { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); DataContext = this; } private IList<Model> _models; public IList<Model> Models { get { return _models ?? (_models = new List<Model> { new Model{ Name = "Name One", Title = "Title One"}, new Model{ Name = "Name Two", Title = "Title Two"}, new Model{ Name = "Name Three", Title = "Title Three"}, new Model{ Name = "Name Four", Title = "Title Four"}, new Model{ Name = "Name Five", Title = "Title Five"}, new Model{ Name = "Name Six", Title = "Title Six"}, new Model{ Name = "Name Seven", Title = "Title Seven"} }); } } private void FrameworkElement_OnRequestBringIntoView(object sender, RequestBringIntoViewEventArgs e) { e.Handled = true; } private void Selector_OnSelectionChanged(object sender, SelectionChangedEventArgs e) { //throw new NotImplementedException(); } private void Selector_OnSelected(object sender, RoutedEventArgs e) { //throw new NotImplementedException(); } } public class Model { public string Name { get; set; } public string Title { get; set; } private IList<string> _options; public IList<string> Options { get { return _options ?? (_options = new List<string> { "left", "right", "both" }); } } } } ``` What I've found and tried (to prevent the jumping) ``` <DataTemplate> <StackPanel ScrollViewer.CanContentScroll="False"> ```
2013/12/30
[ "https://Stackoverflow.com/questions/20842630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/214977/" ]
Here is another answer. It works with a simple WPF. However, my real situation had an Infragistics control and Rachel's answer worked. However, I want to post this for completeness. I'm pasting the code from this url: <http://social.msdn.microsoft.com/Forums/vstudio/en-US/a3532b1f-d76e-4955-b3da-84c98d6d435c/annoying-auto-scroll-of-partially-displayed-items-in-wpf-listbox?forum=wpf> Here is the code: ``` <ListBox.ItemContainerStyle> <Style TargetType="ListBoxItem"> <EventSetter Event="RequestBringIntoView" Handler="ListBoxItem_RequestBringIntoView"/> </Style> </ListBox.ItemContainerStyle> ``` and ``` void ListBoxItem_RequestBringIntoView(object sender, RequestBringIntoViewEventArgs e) { e.Handled = true; } ```
The effect is reproducible if you click into the TextBox of the last visible row. If that row isn't fully scrolled into the view the listbox automatically scrolls that line into view to be fully visible. That in turn means all rows scroll up one row which makes you feel the jumping effect. To my knowledge you cannot change that behaviour.
20,842,630
I have a StackPanel that contains a TextBox and a Combobox. When I set the focus inside a textbox (not the first one), the Contents of the StackPanel "jumps" and goes to the top. Below is the code. I have researched this and post the one I found and tried (but did not worK). I want to prevent the "jumping". So run the code below. Scroll the vertical bar until you see: ``` Name Three <<Text Box (No Selection) ComboBox \/ Name Four <<Text Box (No Selection) ComboBox \/ ``` Now put your cursor in the "Name Four" text box.......and watch it "jump" to the top. (You don't see Three and Four now, you see Four and Five.) My stackpanel is much more complex than this in real life, and its driving my end-users nutty. Thanks. MainWindow.xaml ``` <Window x:Class="ListBoxControlSample.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="160" Width="250"> <Grid Margin="10"> <ListBox ItemsSource="{Binding Models}" SelectionMode="Single" RequestBringIntoView="FrameworkElement_OnRequestBringIntoView" SelectionChanged="Selector_OnSelectionChanged" > <ListBox.ItemTemplate> <DataTemplate> <StackPanel> <TextBox Text="{Binding Name}"/> <ComboBox VerticalContentAlignment="Top" VerticalAlignment="Top" Grid.Column="1" ItemsSource="{Binding Options}" > </ComboBox> <TextBlock Text="{Binding Title}"></TextBlock> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </Grid> </Window> ``` MainWindow.xaml.cs ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace ListBoxControlSample { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); DataContext = this; } private IList<Model> _models; public IList<Model> Models { get { return _models ?? (_models = new List<Model> { new Model{ Name = "Name One", Title = "Title One"}, new Model{ Name = "Name Two", Title = "Title Two"}, new Model{ Name = "Name Three", Title = "Title Three"}, new Model{ Name = "Name Four", Title = "Title Four"}, new Model{ Name = "Name Five", Title = "Title Five"}, new Model{ Name = "Name Six", Title = "Title Six"}, new Model{ Name = "Name Seven", Title = "Title Seven"} }); } } private void FrameworkElement_OnRequestBringIntoView(object sender, RequestBringIntoViewEventArgs e) { e.Handled = true; } private void Selector_OnSelectionChanged(object sender, SelectionChangedEventArgs e) { //throw new NotImplementedException(); } private void Selector_OnSelected(object sender, RoutedEventArgs e) { //throw new NotImplementedException(); } } public class Model { public string Name { get; set; } public string Title { get; set; } private IList<string> _options; public IList<string> Options { get { return _options ?? (_options = new List<string> { "left", "right", "both" }); } } } } ``` What I've found and tried (to prevent the jumping) ``` <DataTemplate> <StackPanel ScrollViewer.CanContentScroll="False"> ```
2013/12/30
[ "https://Stackoverflow.com/questions/20842630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/214977/" ]
I'm guessing it has something to do with the default scroll behavior of trying to show the full item whenever it gets selected. Try disabling the scrolling, and wrap it in another ScrollViewer: ``` <ScrollViewer VerticalScrollBarVisibility="Auto" CanContentScroll="True" Height="250"> <ListBox ScrollViewer.VerticalScrollBarVisibility="Disabled"> ... </ListBox> </ScrollViewer> ``` This way, instead of trying to scroll each individual `StackPanel` into view at a time, and ensuring the full item is visible, it will try to scroll the entire `ListBox` into view, which exceeds the height allotted to the `ScrollViewer`, so it will use the smoother content-based scrolling that you want. It should be noted that this will render the entire `ListBox` at once, without any virutalization, so it isn't advisable to use this method if you have a lot of rows and are depending on virtualization for performance. But based on your question, it doesn't sound like that is your case. I'm also not positive, but you may have to nest this in one more panel as well to allow the ListBox to grow to whatever height it wants. See [this answer](https://stackoverflow.com/a/8490640/302677) for more details if needed.
When a command like SetFocus runs on a child of the scrollviewer, it triggers a ReqestBringInto view on the scrrollviewer but the act of scrolling to the child controls is implemented under the covers by the scrollviewer's ScrollInfo object. I think the key here is to create a class which implements IScrollInfo. I implemented one to override the amount the SV scrolls when using the mouse wheel. In my case, I cloned the default implementation from the [.NET source for ScrollContentProvider](http://www.dotnetframework.org/default.aspx/4@0/4@0/untmp/DEVDIV_TFS/Dev10/Releases/RTMRel/wpf/src/Framework/System/Windows/Controls/Primitives/ScrollContentPresenter@cs/1305600/ScrollContentPresenter@cs)) and changed some properties. Internally, ScrollViewer will call the IScrollInfo::MakeVisible() on the desired child control. You could just ignore that request. Create an instance of your own scroll provider to the scrollviewer using something like: ``` var myProvider = new MyScrollInfo(); myScrollViewer.ScrollInfo = myProvider; ```
20,842,630
I have a StackPanel that contains a TextBox and a Combobox. When I set the focus inside a textbox (not the first one), the Contents of the StackPanel "jumps" and goes to the top. Below is the code. I have researched this and post the one I found and tried (but did not worK). I want to prevent the "jumping". So run the code below. Scroll the vertical bar until you see: ``` Name Three <<Text Box (No Selection) ComboBox \/ Name Four <<Text Box (No Selection) ComboBox \/ ``` Now put your cursor in the "Name Four" text box.......and watch it "jump" to the top. (You don't see Three and Four now, you see Four and Five.) My stackpanel is much more complex than this in real life, and its driving my end-users nutty. Thanks. MainWindow.xaml ``` <Window x:Class="ListBoxControlSample.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="160" Width="250"> <Grid Margin="10"> <ListBox ItemsSource="{Binding Models}" SelectionMode="Single" RequestBringIntoView="FrameworkElement_OnRequestBringIntoView" SelectionChanged="Selector_OnSelectionChanged" > <ListBox.ItemTemplate> <DataTemplate> <StackPanel> <TextBox Text="{Binding Name}"/> <ComboBox VerticalContentAlignment="Top" VerticalAlignment="Top" Grid.Column="1" ItemsSource="{Binding Options}" > </ComboBox> <TextBlock Text="{Binding Title}"></TextBlock> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </Grid> </Window> ``` MainWindow.xaml.cs ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace ListBoxControlSample { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); DataContext = this; } private IList<Model> _models; public IList<Model> Models { get { return _models ?? (_models = new List<Model> { new Model{ Name = "Name One", Title = "Title One"}, new Model{ Name = "Name Two", Title = "Title Two"}, new Model{ Name = "Name Three", Title = "Title Three"}, new Model{ Name = "Name Four", Title = "Title Four"}, new Model{ Name = "Name Five", Title = "Title Five"}, new Model{ Name = "Name Six", Title = "Title Six"}, new Model{ Name = "Name Seven", Title = "Title Seven"} }); } } private void FrameworkElement_OnRequestBringIntoView(object sender, RequestBringIntoViewEventArgs e) { e.Handled = true; } private void Selector_OnSelectionChanged(object sender, SelectionChangedEventArgs e) { //throw new NotImplementedException(); } private void Selector_OnSelected(object sender, RoutedEventArgs e) { //throw new NotImplementedException(); } } public class Model { public string Name { get; set; } public string Title { get; set; } private IList<string> _options; public IList<string> Options { get { return _options ?? (_options = new List<string> { "left", "right", "both" }); } } } } ``` What I've found and tried (to prevent the jumping) ``` <DataTemplate> <StackPanel ScrollViewer.CanContentScroll="False"> ```
2013/12/30
[ "https://Stackoverflow.com/questions/20842630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/214977/" ]
I'm guessing it has something to do with the default scroll behavior of trying to show the full item whenever it gets selected. Try disabling the scrolling, and wrap it in another ScrollViewer: ``` <ScrollViewer VerticalScrollBarVisibility="Auto" CanContentScroll="True" Height="250"> <ListBox ScrollViewer.VerticalScrollBarVisibility="Disabled"> ... </ListBox> </ScrollViewer> ``` This way, instead of trying to scroll each individual `StackPanel` into view at a time, and ensuring the full item is visible, it will try to scroll the entire `ListBox` into view, which exceeds the height allotted to the `ScrollViewer`, so it will use the smoother content-based scrolling that you want. It should be noted that this will render the entire `ListBox` at once, without any virutalization, so it isn't advisable to use this method if you have a lot of rows and are depending on virtualization for performance. But based on your question, it doesn't sound like that is your case. I'm also not positive, but you may have to nest this in one more panel as well to allow the ListBox to grow to whatever height it wants. See [this answer](https://stackoverflow.com/a/8490640/302677) for more details if needed.
Here is another answer. It works with a simple WPF. However, my real situation had an Infragistics control and Rachel's answer worked. However, I want to post this for completeness. I'm pasting the code from this url: <http://social.msdn.microsoft.com/Forums/vstudio/en-US/a3532b1f-d76e-4955-b3da-84c98d6d435c/annoying-auto-scroll-of-partially-displayed-items-in-wpf-listbox?forum=wpf> Here is the code: ``` <ListBox.ItemContainerStyle> <Style TargetType="ListBoxItem"> <EventSetter Event="RequestBringIntoView" Handler="ListBoxItem_RequestBringIntoView"/> </Style> </ListBox.ItemContainerStyle> ``` and ``` void ListBoxItem_RequestBringIntoView(object sender, RequestBringIntoViewEventArgs e) { e.Handled = true; } ```
20,842,630
I have a StackPanel that contains a TextBox and a Combobox. When I set the focus inside a textbox (not the first one), the Contents of the StackPanel "jumps" and goes to the top. Below is the code. I have researched this and post the one I found and tried (but did not worK). I want to prevent the "jumping". So run the code below. Scroll the vertical bar until you see: ``` Name Three <<Text Box (No Selection) ComboBox \/ Name Four <<Text Box (No Selection) ComboBox \/ ``` Now put your cursor in the "Name Four" text box.......and watch it "jump" to the top. (You don't see Three and Four now, you see Four and Five.) My stackpanel is much more complex than this in real life, and its driving my end-users nutty. Thanks. MainWindow.xaml ``` <Window x:Class="ListBoxControlSample.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="160" Width="250"> <Grid Margin="10"> <ListBox ItemsSource="{Binding Models}" SelectionMode="Single" RequestBringIntoView="FrameworkElement_OnRequestBringIntoView" SelectionChanged="Selector_OnSelectionChanged" > <ListBox.ItemTemplate> <DataTemplate> <StackPanel> <TextBox Text="{Binding Name}"/> <ComboBox VerticalContentAlignment="Top" VerticalAlignment="Top" Grid.Column="1" ItemsSource="{Binding Options}" > </ComboBox> <TextBlock Text="{Binding Title}"></TextBlock> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </Grid> </Window> ``` MainWindow.xaml.cs ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace ListBoxControlSample { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); DataContext = this; } private IList<Model> _models; public IList<Model> Models { get { return _models ?? (_models = new List<Model> { new Model{ Name = "Name One", Title = "Title One"}, new Model{ Name = "Name Two", Title = "Title Two"}, new Model{ Name = "Name Three", Title = "Title Three"}, new Model{ Name = "Name Four", Title = "Title Four"}, new Model{ Name = "Name Five", Title = "Title Five"}, new Model{ Name = "Name Six", Title = "Title Six"}, new Model{ Name = "Name Seven", Title = "Title Seven"} }); } } private void FrameworkElement_OnRequestBringIntoView(object sender, RequestBringIntoViewEventArgs e) { e.Handled = true; } private void Selector_OnSelectionChanged(object sender, SelectionChangedEventArgs e) { //throw new NotImplementedException(); } private void Selector_OnSelected(object sender, RoutedEventArgs e) { //throw new NotImplementedException(); } } public class Model { public string Name { get; set; } public string Title { get; set; } private IList<string> _options; public IList<string> Options { get { return _options ?? (_options = new List<string> { "left", "right", "both" }); } } } } ``` What I've found and tried (to prevent the jumping) ``` <DataTemplate> <StackPanel ScrollViewer.CanContentScroll="False"> ```
2013/12/30
[ "https://Stackoverflow.com/questions/20842630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/214977/" ]
I'm guessing it has something to do with the default scroll behavior of trying to show the full item whenever it gets selected. Try disabling the scrolling, and wrap it in another ScrollViewer: ``` <ScrollViewer VerticalScrollBarVisibility="Auto" CanContentScroll="True" Height="250"> <ListBox ScrollViewer.VerticalScrollBarVisibility="Disabled"> ... </ListBox> </ScrollViewer> ``` This way, instead of trying to scroll each individual `StackPanel` into view at a time, and ensuring the full item is visible, it will try to scroll the entire `ListBox` into view, which exceeds the height allotted to the `ScrollViewer`, so it will use the smoother content-based scrolling that you want. It should be noted that this will render the entire `ListBox` at once, without any virutalization, so it isn't advisable to use this method if you have a lot of rows and are depending on virtualization for performance. But based on your question, it doesn't sound like that is your case. I'm also not positive, but you may have to nest this in one more panel as well to allow the ListBox to grow to whatever height it wants. See [this answer](https://stackoverflow.com/a/8490640/302677) for more details if needed.
Use this: ``` <ListBox ScrollViewer.PanningMode="None"> ```
20,842,630
I have a StackPanel that contains a TextBox and a Combobox. When I set the focus inside a textbox (not the first one), the Contents of the StackPanel "jumps" and goes to the top. Below is the code. I have researched this and post the one I found and tried (but did not worK). I want to prevent the "jumping". So run the code below. Scroll the vertical bar until you see: ``` Name Three <<Text Box (No Selection) ComboBox \/ Name Four <<Text Box (No Selection) ComboBox \/ ``` Now put your cursor in the "Name Four" text box.......and watch it "jump" to the top. (You don't see Three and Four now, you see Four and Five.) My stackpanel is much more complex than this in real life, and its driving my end-users nutty. Thanks. MainWindow.xaml ``` <Window x:Class="ListBoxControlSample.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="160" Width="250"> <Grid Margin="10"> <ListBox ItemsSource="{Binding Models}" SelectionMode="Single" RequestBringIntoView="FrameworkElement_OnRequestBringIntoView" SelectionChanged="Selector_OnSelectionChanged" > <ListBox.ItemTemplate> <DataTemplate> <StackPanel> <TextBox Text="{Binding Name}"/> <ComboBox VerticalContentAlignment="Top" VerticalAlignment="Top" Grid.Column="1" ItemsSource="{Binding Options}" > </ComboBox> <TextBlock Text="{Binding Title}"></TextBlock> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </Grid> </Window> ``` MainWindow.xaml.cs ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace ListBoxControlSample { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); DataContext = this; } private IList<Model> _models; public IList<Model> Models { get { return _models ?? (_models = new List<Model> { new Model{ Name = "Name One", Title = "Title One"}, new Model{ Name = "Name Two", Title = "Title Two"}, new Model{ Name = "Name Three", Title = "Title Three"}, new Model{ Name = "Name Four", Title = "Title Four"}, new Model{ Name = "Name Five", Title = "Title Five"}, new Model{ Name = "Name Six", Title = "Title Six"}, new Model{ Name = "Name Seven", Title = "Title Seven"} }); } } private void FrameworkElement_OnRequestBringIntoView(object sender, RequestBringIntoViewEventArgs e) { e.Handled = true; } private void Selector_OnSelectionChanged(object sender, SelectionChangedEventArgs e) { //throw new NotImplementedException(); } private void Selector_OnSelected(object sender, RoutedEventArgs e) { //throw new NotImplementedException(); } } public class Model { public string Name { get; set; } public string Title { get; set; } private IList<string> _options; public IList<string> Options { get { return _options ?? (_options = new List<string> { "left", "right", "both" }); } } } } ``` What I've found and tried (to prevent the jumping) ``` <DataTemplate> <StackPanel ScrollViewer.CanContentScroll="False"> ```
2013/12/30
[ "https://Stackoverflow.com/questions/20842630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/214977/" ]
I'm guessing it has something to do with the default scroll behavior of trying to show the full item whenever it gets selected. Try disabling the scrolling, and wrap it in another ScrollViewer: ``` <ScrollViewer VerticalScrollBarVisibility="Auto" CanContentScroll="True" Height="250"> <ListBox ScrollViewer.VerticalScrollBarVisibility="Disabled"> ... </ListBox> </ScrollViewer> ``` This way, instead of trying to scroll each individual `StackPanel` into view at a time, and ensuring the full item is visible, it will try to scroll the entire `ListBox` into view, which exceeds the height allotted to the `ScrollViewer`, so it will use the smoother content-based scrolling that you want. It should be noted that this will render the entire `ListBox` at once, without any virutalization, so it isn't advisable to use this method if you have a lot of rows and are depending on virtualization for performance. But based on your question, it doesn't sound like that is your case. I'm also not positive, but you may have to nest this in one more panel as well to allow the ListBox to grow to whatever height it wants. See [this answer](https://stackoverflow.com/a/8490640/302677) for more details if needed.
This issue is caused when a child item within the `ScrollVewier` receives focus and is subsequently scrolled into view (in this case the child element is the ListBoxItem). If the element receiving focus does not need to be navigaable via the tab key, then a simple solution is to make the element unfocusable via `Focusable=False`. If the element does not receive focus then the scroll viewer will also not try to scroll it into view. In this case this is likely an acceptable solution as I don't think the ListBoxItem is acting more as a container than as a control the user needs to be able to select.
20,842,630
I have a StackPanel that contains a TextBox and a Combobox. When I set the focus inside a textbox (not the first one), the Contents of the StackPanel "jumps" and goes to the top. Below is the code. I have researched this and post the one I found and tried (but did not worK). I want to prevent the "jumping". So run the code below. Scroll the vertical bar until you see: ``` Name Three <<Text Box (No Selection) ComboBox \/ Name Four <<Text Box (No Selection) ComboBox \/ ``` Now put your cursor in the "Name Four" text box.......and watch it "jump" to the top. (You don't see Three and Four now, you see Four and Five.) My stackpanel is much more complex than this in real life, and its driving my end-users nutty. Thanks. MainWindow.xaml ``` <Window x:Class="ListBoxControlSample.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="160" Width="250"> <Grid Margin="10"> <ListBox ItemsSource="{Binding Models}" SelectionMode="Single" RequestBringIntoView="FrameworkElement_OnRequestBringIntoView" SelectionChanged="Selector_OnSelectionChanged" > <ListBox.ItemTemplate> <DataTemplate> <StackPanel> <TextBox Text="{Binding Name}"/> <ComboBox VerticalContentAlignment="Top" VerticalAlignment="Top" Grid.Column="1" ItemsSource="{Binding Options}" > </ComboBox> <TextBlock Text="{Binding Title}"></TextBlock> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </Grid> </Window> ``` MainWindow.xaml.cs ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace ListBoxControlSample { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); DataContext = this; } private IList<Model> _models; public IList<Model> Models { get { return _models ?? (_models = new List<Model> { new Model{ Name = "Name One", Title = "Title One"}, new Model{ Name = "Name Two", Title = "Title Two"}, new Model{ Name = "Name Three", Title = "Title Three"}, new Model{ Name = "Name Four", Title = "Title Four"}, new Model{ Name = "Name Five", Title = "Title Five"}, new Model{ Name = "Name Six", Title = "Title Six"}, new Model{ Name = "Name Seven", Title = "Title Seven"} }); } } private void FrameworkElement_OnRequestBringIntoView(object sender, RequestBringIntoViewEventArgs e) { e.Handled = true; } private void Selector_OnSelectionChanged(object sender, SelectionChangedEventArgs e) { //throw new NotImplementedException(); } private void Selector_OnSelected(object sender, RoutedEventArgs e) { //throw new NotImplementedException(); } } public class Model { public string Name { get; set; } public string Title { get; set; } private IList<string> _options; public IList<string> Options { get { return _options ?? (_options = new List<string> { "left", "right", "both" }); } } } } ``` What I've found and tried (to prevent the jumping) ``` <DataTemplate> <StackPanel ScrollViewer.CanContentScroll="False"> ```
2013/12/30
[ "https://Stackoverflow.com/questions/20842630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/214977/" ]
Here is another answer. It works with a simple WPF. However, my real situation had an Infragistics control and Rachel's answer worked. However, I want to post this for completeness. I'm pasting the code from this url: <http://social.msdn.microsoft.com/Forums/vstudio/en-US/a3532b1f-d76e-4955-b3da-84c98d6d435c/annoying-auto-scroll-of-partially-displayed-items-in-wpf-listbox?forum=wpf> Here is the code: ``` <ListBox.ItemContainerStyle> <Style TargetType="ListBoxItem"> <EventSetter Event="RequestBringIntoView" Handler="ListBoxItem_RequestBringIntoView"/> </Style> </ListBox.ItemContainerStyle> ``` and ``` void ListBoxItem_RequestBringIntoView(object sender, RequestBringIntoViewEventArgs e) { e.Handled = true; } ```
When a command like SetFocus runs on a child of the scrollviewer, it triggers a ReqestBringInto view on the scrrollviewer but the act of scrolling to the child controls is implemented under the covers by the scrollviewer's ScrollInfo object. I think the key here is to create a class which implements IScrollInfo. I implemented one to override the amount the SV scrolls when using the mouse wheel. In my case, I cloned the default implementation from the [.NET source for ScrollContentProvider](http://www.dotnetframework.org/default.aspx/4@0/4@0/untmp/DEVDIV_TFS/Dev10/Releases/RTMRel/wpf/src/Framework/System/Windows/Controls/Primitives/ScrollContentPresenter@cs/1305600/ScrollContentPresenter@cs)) and changed some properties. Internally, ScrollViewer will call the IScrollInfo::MakeVisible() on the desired child control. You could just ignore that request. Create an instance of your own scroll provider to the scrollviewer using something like: ``` var myProvider = new MyScrollInfo(); myScrollViewer.ScrollInfo = myProvider; ```
20,842,630
I have a StackPanel that contains a TextBox and a Combobox. When I set the focus inside a textbox (not the first one), the Contents of the StackPanel "jumps" and goes to the top. Below is the code. I have researched this and post the one I found and tried (but did not worK). I want to prevent the "jumping". So run the code below. Scroll the vertical bar until you see: ``` Name Three <<Text Box (No Selection) ComboBox \/ Name Four <<Text Box (No Selection) ComboBox \/ ``` Now put your cursor in the "Name Four" text box.......and watch it "jump" to the top. (You don't see Three and Four now, you see Four and Five.) My stackpanel is much more complex than this in real life, and its driving my end-users nutty. Thanks. MainWindow.xaml ``` <Window x:Class="ListBoxControlSample.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="160" Width="250"> <Grid Margin="10"> <ListBox ItemsSource="{Binding Models}" SelectionMode="Single" RequestBringIntoView="FrameworkElement_OnRequestBringIntoView" SelectionChanged="Selector_OnSelectionChanged" > <ListBox.ItemTemplate> <DataTemplate> <StackPanel> <TextBox Text="{Binding Name}"/> <ComboBox VerticalContentAlignment="Top" VerticalAlignment="Top" Grid.Column="1" ItemsSource="{Binding Options}" > </ComboBox> <TextBlock Text="{Binding Title}"></TextBlock> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </Grid> </Window> ``` MainWindow.xaml.cs ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace ListBoxControlSample { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); DataContext = this; } private IList<Model> _models; public IList<Model> Models { get { return _models ?? (_models = new List<Model> { new Model{ Name = "Name One", Title = "Title One"}, new Model{ Name = "Name Two", Title = "Title Two"}, new Model{ Name = "Name Three", Title = "Title Three"}, new Model{ Name = "Name Four", Title = "Title Four"}, new Model{ Name = "Name Five", Title = "Title Five"}, new Model{ Name = "Name Six", Title = "Title Six"}, new Model{ Name = "Name Seven", Title = "Title Seven"} }); } } private void FrameworkElement_OnRequestBringIntoView(object sender, RequestBringIntoViewEventArgs e) { e.Handled = true; } private void Selector_OnSelectionChanged(object sender, SelectionChangedEventArgs e) { //throw new NotImplementedException(); } private void Selector_OnSelected(object sender, RoutedEventArgs e) { //throw new NotImplementedException(); } } public class Model { public string Name { get; set; } public string Title { get; set; } private IList<string> _options; public IList<string> Options { get { return _options ?? (_options = new List<string> { "left", "right", "both" }); } } } } ``` What I've found and tried (to prevent the jumping) ``` <DataTemplate> <StackPanel ScrollViewer.CanContentScroll="False"> ```
2013/12/30
[ "https://Stackoverflow.com/questions/20842630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/214977/" ]
Here is another answer. It works with a simple WPF. However, my real situation had an Infragistics control and Rachel's answer worked. However, I want to post this for completeness. I'm pasting the code from this url: <http://social.msdn.microsoft.com/Forums/vstudio/en-US/a3532b1f-d76e-4955-b3da-84c98d6d435c/annoying-auto-scroll-of-partially-displayed-items-in-wpf-listbox?forum=wpf> Here is the code: ``` <ListBox.ItemContainerStyle> <Style TargetType="ListBoxItem"> <EventSetter Event="RequestBringIntoView" Handler="ListBoxItem_RequestBringIntoView"/> </Style> </ListBox.ItemContainerStyle> ``` and ``` void ListBoxItem_RequestBringIntoView(object sender, RequestBringIntoViewEventArgs e) { e.Handled = true; } ```
Use this: ``` <ListBox ScrollViewer.PanningMode="None"> ```
20,842,630
I have a StackPanel that contains a TextBox and a Combobox. When I set the focus inside a textbox (not the first one), the Contents of the StackPanel "jumps" and goes to the top. Below is the code. I have researched this and post the one I found and tried (but did not worK). I want to prevent the "jumping". So run the code below. Scroll the vertical bar until you see: ``` Name Three <<Text Box (No Selection) ComboBox \/ Name Four <<Text Box (No Selection) ComboBox \/ ``` Now put your cursor in the "Name Four" text box.......and watch it "jump" to the top. (You don't see Three and Four now, you see Four and Five.) My stackpanel is much more complex than this in real life, and its driving my end-users nutty. Thanks. MainWindow.xaml ``` <Window x:Class="ListBoxControlSample.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="160" Width="250"> <Grid Margin="10"> <ListBox ItemsSource="{Binding Models}" SelectionMode="Single" RequestBringIntoView="FrameworkElement_OnRequestBringIntoView" SelectionChanged="Selector_OnSelectionChanged" > <ListBox.ItemTemplate> <DataTemplate> <StackPanel> <TextBox Text="{Binding Name}"/> <ComboBox VerticalContentAlignment="Top" VerticalAlignment="Top" Grid.Column="1" ItemsSource="{Binding Options}" > </ComboBox> <TextBlock Text="{Binding Title}"></TextBlock> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </Grid> </Window> ``` MainWindow.xaml.cs ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace ListBoxControlSample { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); DataContext = this; } private IList<Model> _models; public IList<Model> Models { get { return _models ?? (_models = new List<Model> { new Model{ Name = "Name One", Title = "Title One"}, new Model{ Name = "Name Two", Title = "Title Two"}, new Model{ Name = "Name Three", Title = "Title Three"}, new Model{ Name = "Name Four", Title = "Title Four"}, new Model{ Name = "Name Five", Title = "Title Five"}, new Model{ Name = "Name Six", Title = "Title Six"}, new Model{ Name = "Name Seven", Title = "Title Seven"} }); } } private void FrameworkElement_OnRequestBringIntoView(object sender, RequestBringIntoViewEventArgs e) { e.Handled = true; } private void Selector_OnSelectionChanged(object sender, SelectionChangedEventArgs e) { //throw new NotImplementedException(); } private void Selector_OnSelected(object sender, RoutedEventArgs e) { //throw new NotImplementedException(); } } public class Model { public string Name { get; set; } public string Title { get; set; } private IList<string> _options; public IList<string> Options { get { return _options ?? (_options = new List<string> { "left", "right", "both" }); } } } } ``` What I've found and tried (to prevent the jumping) ``` <DataTemplate> <StackPanel ScrollViewer.CanContentScroll="False"> ```
2013/12/30
[ "https://Stackoverflow.com/questions/20842630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/214977/" ]
Here is another answer. It works with a simple WPF. However, my real situation had an Infragistics control and Rachel's answer worked. However, I want to post this for completeness. I'm pasting the code from this url: <http://social.msdn.microsoft.com/Forums/vstudio/en-US/a3532b1f-d76e-4955-b3da-84c98d6d435c/annoying-auto-scroll-of-partially-displayed-items-in-wpf-listbox?forum=wpf> Here is the code: ``` <ListBox.ItemContainerStyle> <Style TargetType="ListBoxItem"> <EventSetter Event="RequestBringIntoView" Handler="ListBoxItem_RequestBringIntoView"/> </Style> </ListBox.ItemContainerStyle> ``` and ``` void ListBoxItem_RequestBringIntoView(object sender, RequestBringIntoViewEventArgs e) { e.Handled = true; } ```
This issue is caused when a child item within the `ScrollVewier` receives focus and is subsequently scrolled into view (in this case the child element is the ListBoxItem). If the element receiving focus does not need to be navigaable via the tab key, then a simple solution is to make the element unfocusable via `Focusable=False`. If the element does not receive focus then the scroll viewer will also not try to scroll it into view. In this case this is likely an acceptable solution as I don't think the ListBoxItem is acting more as a container than as a control the user needs to be able to select.
105,065
My paper was accepted for publication in a journal. I have also received an acceptance letter and even I have filled out the copyright form. The corresponding editor first told me "Your paper is published in one of the volumes of 2017" and next time said that my paper is "published in 2018", but now I have received an email that my paper is "rejected because the paper is not in the aim and scope of the journal"!!! Really I do not know, what should I do?
2018/03/07
[ "https://academia.stackexchange.com/questions/105065", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/88580/" ]
This is unacceptable. If this is a reputable journal, then you can make the point that they made you wait and the research results become stale, and that you have every right to expect them to honour their approval for publication. They simply cannot retroactively change whether the paper fits into aim/scope of the journal - that decision had been taken with acceptance. If they made a mistake in judgement, you cannot be expected to be the person to bear the cost of this. If the journal is not reputable, you probably dodged a bullet - and if it is "reputable", and they insist on not publishing your paper after this protest, you can be assured that they are on the way to becoming not reputable, fast (I would, however, not make this point in your protest email).
This is pretty disturbing. You should immediately contact the editorial board of the journal and explain the situation. I would also doubt the quality of the mentioned journal by looking at the series of events.
105,065
My paper was accepted for publication in a journal. I have also received an acceptance letter and even I have filled out the copyright form. The corresponding editor first told me "Your paper is published in one of the volumes of 2017" and next time said that my paper is "published in 2018", but now I have received an email that my paper is "rejected because the paper is not in the aim and scope of the journal"!!! Really I do not know, what should I do?
2018/03/07
[ "https://academia.stackexchange.com/questions/105065", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/88580/" ]
This is unacceptable. If this is a reputable journal, then you can make the point that they made you wait and the research results become stale, and that you have every right to expect them to honour their approval for publication. They simply cannot retroactively change whether the paper fits into aim/scope of the journal - that decision had been taken with acceptance. If they made a mistake in judgement, you cannot be expected to be the person to bear the cost of this. If the journal is not reputable, you probably dodged a bullet - and if it is "reputable", and they insist on not publishing your paper after this protest, you can be assured that they are on the way to becoming not reputable, fast (I would, however, not make this point in your protest email).
You should contact the editor in chief and make your complaints clear, that is awful behavior on behalf of the journal. If I were you I would do it as fast as I could and I would take it as far as I could. I wish you good luck and I hope it was a simple mix up.
105,065
My paper was accepted for publication in a journal. I have also received an acceptance letter and even I have filled out the copyright form. The corresponding editor first told me "Your paper is published in one of the volumes of 2017" and next time said that my paper is "published in 2018", but now I have received an email that my paper is "rejected because the paper is not in the aim and scope of the journal"!!! Really I do not know, what should I do?
2018/03/07
[ "https://academia.stackexchange.com/questions/105065", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/88580/" ]
This is unacceptable. If this is a reputable journal, then you can make the point that they made you wait and the research results become stale, and that you have every right to expect them to honour their approval for publication. They simply cannot retroactively change whether the paper fits into aim/scope of the journal - that decision had been taken with acceptance. If they made a mistake in judgement, you cannot be expected to be the person to bear the cost of this. If the journal is not reputable, you probably dodged a bullet - and if it is "reputable", and they insist on not publishing your paper after this protest, you can be assured that they are on the way to becoming not reputable, fast (I would, however, not make this point in your protest email).
Yes, of course you should complain, and the editor and chief does owe you an explanation. That being said, total devil's advocate (just because the other answers seemed to all have pitchforks ready)... If there has been a change in the editorial team it is somewhat their choice what direction they take the journal. The (hypothetical) outgoing editor is partially to blame for making a commitment they couldn't keep. Taking a moment for empathy, they were just trying to help the incoming editor out by having stuff in the pipeline. The content of journals, their standards, their quality, their requirements all drift with changing editors. Maybe you caught someone new to that side of publishing... they're learning on the job and might not have really thought of this from your point of view. Try to be kind. :)
105,065
My paper was accepted for publication in a journal. I have also received an acceptance letter and even I have filled out the copyright form. The corresponding editor first told me "Your paper is published in one of the volumes of 2017" and next time said that my paper is "published in 2018", but now I have received an email that my paper is "rejected because the paper is not in the aim and scope of the journal"!!! Really I do not know, what should I do?
2018/03/07
[ "https://academia.stackexchange.com/questions/105065", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/88580/" ]
**Check with the journal**. Especially do this if the rejection email you received looks like an auto-generated email. No rational journal would act in such a way, so my gut feeling says there was a mistake somewhere, most likely human error. It is possible that, e.g., the final status of your manuscript was accidentally set to 'reject' instead of 'accept'.
This is pretty disturbing. You should immediately contact the editorial board of the journal and explain the situation. I would also doubt the quality of the mentioned journal by looking at the series of events.
105,065
My paper was accepted for publication in a journal. I have also received an acceptance letter and even I have filled out the copyright form. The corresponding editor first told me "Your paper is published in one of the volumes of 2017" and next time said that my paper is "published in 2018", but now I have received an email that my paper is "rejected because the paper is not in the aim and scope of the journal"!!! Really I do not know, what should I do?
2018/03/07
[ "https://academia.stackexchange.com/questions/105065", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/88580/" ]
This is pretty disturbing. You should immediately contact the editorial board of the journal and explain the situation. I would also doubt the quality of the mentioned journal by looking at the series of events.
You should contact the editor in chief and make your complaints clear, that is awful behavior on behalf of the journal. If I were you I would do it as fast as I could and I would take it as far as I could. I wish you good luck and I hope it was a simple mix up.
105,065
My paper was accepted for publication in a journal. I have also received an acceptance letter and even I have filled out the copyright form. The corresponding editor first told me "Your paper is published in one of the volumes of 2017" and next time said that my paper is "published in 2018", but now I have received an email that my paper is "rejected because the paper is not in the aim and scope of the journal"!!! Really I do not know, what should I do?
2018/03/07
[ "https://academia.stackexchange.com/questions/105065", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/88580/" ]
This is pretty disturbing. You should immediately contact the editorial board of the journal and explain the situation. I would also doubt the quality of the mentioned journal by looking at the series of events.
Yes, of course you should complain, and the editor and chief does owe you an explanation. That being said, total devil's advocate (just because the other answers seemed to all have pitchforks ready)... If there has been a change in the editorial team it is somewhat their choice what direction they take the journal. The (hypothetical) outgoing editor is partially to blame for making a commitment they couldn't keep. Taking a moment for empathy, they were just trying to help the incoming editor out by having stuff in the pipeline. The content of journals, their standards, their quality, their requirements all drift with changing editors. Maybe you caught someone new to that side of publishing... they're learning on the job and might not have really thought of this from your point of view. Try to be kind. :)
105,065
My paper was accepted for publication in a journal. I have also received an acceptance letter and even I have filled out the copyright form. The corresponding editor first told me "Your paper is published in one of the volumes of 2017" and next time said that my paper is "published in 2018", but now I have received an email that my paper is "rejected because the paper is not in the aim and scope of the journal"!!! Really I do not know, what should I do?
2018/03/07
[ "https://academia.stackexchange.com/questions/105065", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/88580/" ]
**Check with the journal**. Especially do this if the rejection email you received looks like an auto-generated email. No rational journal would act in such a way, so my gut feeling says there was a mistake somewhere, most likely human error. It is possible that, e.g., the final status of your manuscript was accidentally set to 'reject' instead of 'accept'.
You should contact the editor in chief and make your complaints clear, that is awful behavior on behalf of the journal. If I were you I would do it as fast as I could and I would take it as far as I could. I wish you good luck and I hope it was a simple mix up.
105,065
My paper was accepted for publication in a journal. I have also received an acceptance letter and even I have filled out the copyright form. The corresponding editor first told me "Your paper is published in one of the volumes of 2017" and next time said that my paper is "published in 2018", but now I have received an email that my paper is "rejected because the paper is not in the aim and scope of the journal"!!! Really I do not know, what should I do?
2018/03/07
[ "https://academia.stackexchange.com/questions/105065", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/88580/" ]
**Check with the journal**. Especially do this if the rejection email you received looks like an auto-generated email. No rational journal would act in such a way, so my gut feeling says there was a mistake somewhere, most likely human error. It is possible that, e.g., the final status of your manuscript was accidentally set to 'reject' instead of 'accept'.
Yes, of course you should complain, and the editor and chief does owe you an explanation. That being said, total devil's advocate (just because the other answers seemed to all have pitchforks ready)... If there has been a change in the editorial team it is somewhat their choice what direction they take the journal. The (hypothetical) outgoing editor is partially to blame for making a commitment they couldn't keep. Taking a moment for empathy, they were just trying to help the incoming editor out by having stuff in the pipeline. The content of journals, their standards, their quality, their requirements all drift with changing editors. Maybe you caught someone new to that side of publishing... they're learning on the job and might not have really thought of this from your point of view. Try to be kind. :)
105,065
My paper was accepted for publication in a journal. I have also received an acceptance letter and even I have filled out the copyright form. The corresponding editor first told me "Your paper is published in one of the volumes of 2017" and next time said that my paper is "published in 2018", but now I have received an email that my paper is "rejected because the paper is not in the aim and scope of the journal"!!! Really I do not know, what should I do?
2018/03/07
[ "https://academia.stackexchange.com/questions/105065", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/88580/" ]
You should contact the editor in chief and make your complaints clear, that is awful behavior on behalf of the journal. If I were you I would do it as fast as I could and I would take it as far as I could. I wish you good luck and I hope it was a simple mix up.
Yes, of course you should complain, and the editor and chief does owe you an explanation. That being said, total devil's advocate (just because the other answers seemed to all have pitchforks ready)... If there has been a change in the editorial team it is somewhat their choice what direction they take the journal. The (hypothetical) outgoing editor is partially to blame for making a commitment they couldn't keep. Taking a moment for empathy, they were just trying to help the incoming editor out by having stuff in the pipeline. The content of journals, their standards, their quality, their requirements all drift with changing editors. Maybe you caught someone new to that side of publishing... they're learning on the job and might not have really thought of this from your point of view. Try to be kind. :)
732,283
I have a OpenVPN server ruining on Unbuntu 14.04 server. Everything works fine, the client connects to the server and can ping the VPN server. I want the client use my internet as it were his internet but I also want to block the client to access my Home LAN. Below is my setup: ``` Home LAN: 192.168.1.0/24 Router: 192.168.1.2 OpenVPN LAN ip: 192.168.139 VPN Network: 10.8.0.0/24 ``` --- ``` Server Configuration: proto udp dev tun ca ca.crt cert openvpn-server.crt key openvpn-server.key dh dh2048.pem server 10.8.0.0 255.255.255.0 ifconfig-pool-persist ipp.txt push "redirect-gateway def1" push "dhcp-option DNS 68.237.161.12" push "dhcp-option DNS 71.250.0.12" keepalive 10 120 comp-lzo persist-key persist-tun status openvpn-status.log verb 3 ``` --- ``` Client Configuration: client dev tun proto udp remote (ip removed) 1194 resolv-retry infinite nobind persist-key persist-tun ca ca.crt cert andres.crt key andres.key remote-cert-tls server comp-lzo verb 3 ``` What I have done is enable packet forwarding ``` # Uncomment the next line to enable packet forwarding for IPv4 net.ipv4.ip_forward=1 ``` It works but the client have access to my entire LAN. How can I block my LAN and allow internet traffic to a openvpn client? Thank you,
2015/10/28
[ "https://serverfault.com/questions/732283", "https://serverfault.com", "https://serverfault.com/users/242235/" ]
I'd do it with iptables. ``` iptables -A INPUT -s 10.8.0.0/24 -d 192.168.1.0/24 -j DROP ```
I think by default, there's no route to your Home LAN. You can ping the IP address on the OpenVPN server sitting on 192.168.1.0/24 but nothing else. Because when I set mine up, I had to push the route out on the server.conf file and also add a static route on my router for it to allow access to the 192.168.1.0/24 network.
39,449,770
I have a Table with Orders ``` +----+-------------+--------+ | ID | OrderNumber | CartId | +----+-------------+--------+ |1 | ABDE45677 | 1 | |2 | ABFRTG456 | 2 | +----+-------------+--------+ ``` One with cart items for each cart (which belongs to an order) ``` +----+--------+-----------+ | ID | CartId | ProductId | +----+--------+-----------+ |1 | 1 | 34577 | |2 | 1 | 26846 | |3 | 2 | 59055 | |4 | 3 | 43567 | +----+--------+-----------+ ``` And one with cart item events (such as 'sent', 'shipped', 'returned', etc) ``` +----+---------------------+------------+------+ | ID | EventDate | CartItemId | Type | +----+---------------------+------------+------+ |1 | 2016-07-12 11:54:12 | 1 |1 | |2 | 2016-07-12 12:01:12 | 1 |3 | |3 | 2016-07-12 10:10:00 | 2 |1 | |4 | 2016-07-12 11:00:00 | 2 |2 | |5 | 2016-07-13 13:00:00 | 2 |4 | |6 | 2016-07-12 12:00:00 | 3 |1 | |7 | 2016-07-14 12:30:12 | 3 |2 | +----+---------------------+------------+------| ``` The relationships are ``` Orders >hasmany> Carts >hasmany> CartItems >hasmany> CartItemEvents ``` I now want to get all Orders with a 'status' column at the end. This column should display the lowest 'type' value of all cart item events belonging to the order. I only want to get the latest event for each order Item. ``` SELECT o.ID, o.OrderNumber, (SELECT MIN(type) FROM CartItemEvents cie WHERE cie.CartItemId=ci.Id AND cie.EventDate= (SELECT MAX(EventDate) FROM CartItemEvents WHERE ci.id=CartItemId)) AS 'status' FROM Orders o LEFT JOIN CartItems ci on o.CartId=ci.CartId ``` Unfortunately, I get multiple types for each order (one type for each item) ``` +----+-------------+--------+ | ID | OrderNumber | Status | +----+-------------+--------+ |1 | ABDE45677 | 3 | |1 | ABDE45677 | 4 | |2 | ABFRTG456 | 2 | +----+-------------+--------+ ``` It seems like the function ``` SELECT MIN(type) ``` has no effect here, since removing MIN() brings the same result. How can I get only the minimum type for each order? Maybe I have too many nested subqueries here?
2016/09/12
[ "https://Stackoverflow.com/questions/39449770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4075164/" ]
You never want synchronous code when you can avoid it. In this case I would recommend to use Promises in order to manage the seven requests to redis. The [Bluebird promise library](http://bluebirdjs.com/docs/) can make most APIs promise-compatible in one line of code (read about [promisification](http://bluebirdjs.com/docs/api/promisification.html)), the API of redis is no exception. (The documentation of Bluebird even [uses redis as an example](http://bluebirdjs.com/docs/api/promise.promisifyall.html), and so does the [node-redis documentation](https://github.com/NodeRedis/node_redis#promises), so it's even "officially supported", if you care for that kind of thing.) So what you seem to want is a function that checks up to seven asynchronous calls to `sismember` and resolves to an overal positive result as soon as the first of them has a positive result - [Promise#any()](http://bluebirdjs.com/docs/api/promise.any.html) can do that. ``` var Promise = require('bluebird'); var _ = require('lodash'); var redis = require('redis'); Promise.promisifyAll(redis); function checkBlacklist(hashToken) { var blacklistChecks = _.range(7).map((day) => { return redis.sismemberAsync(`blacklist${day}`, hashToken); }); return Promise.any(blacklistChecks); } ``` usage ``` checkBlacklist('some_token').then((result) => { // do something with the result }).catch((err) => { // an error has occurred - handle it or rethrow it }); ```
If multiple redis ops are involved, generally I prefer to write lua script and then call it through my nodejs program. This is an unrelated example, but it shows how you can use lua through nodejs. example: get\_state.lua ``` local jobId = KEYS[1] local jobExists = redis.pcall('exists', jobId) if jobExists == 0 or jobExists == nil then return 404 -- not found. end -- check the job state local st = tonumber(redis.pcall('hmget', jobId, 'ctlState')[1]) if st == nil then st = 12002 -- job running, unless explicitly stated otherwise end return st ``` NodeJS code that uses lua: say index.js ``` ... // List of script files var scriptMap = { getState: {file:'./scripts/get_state.lua'} }; ... // A function to load the script file to Redis and cache the sha. function loadScript(script) { logger.trace("loadScript(): executing..."); if (scriptMap[script]['hash']) { logger.trace("Sript already loaded. Returning without loading again..."); return Promise.resolve(scriptMap[script]['hash']); } //load from file and send to redis logger.trace("Loading script from file %s...", scriptMap[script].file); return fs.readFileAsync(scriptMap[script].file).then(function(data) { return getConnection().then(function(conn) { logger.trace("Loading script to Redis..."); return conn.scriptAsync('load', data) }) }) } ``` And, finally, a function that uses the cached sha digest to execute the script: ``` getJobState: function(jobId) { return loadScript('getState').then(function(hash) { return getConnection().then(function (conn) { return conn.evalshaAsync(hash, 1, jobId) }) }) }, ```
10,813,592
> > **Possible Duplicate:** > > [What is the For attribute for in an HTML tag?](https://stackoverflow.com/questions/3681601/what-is-the-for-attribute-for-in-an-html-tag) > > > I have been trying to find this out. What is the reason for using the "for=" when you use a label in HTML? ``` <form> <label for="male">Male</label> <input type="radio" name="sex" id="male" /> <br /> <label for="female">Female</label> <input type="radio" name="sex" id="female" /> </form> ``` If it's needed then is there some equivalent in HTML 5 or is it the same?
2012/05/30
[ "https://Stackoverflow.com/questions/10813592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1422604/" ]
It makes a click on the label focus the input element it is `for`. In the example you posted, you simply click on the word `Male` *or* the radio button in order for it to get selected. Without this, you have a much smaller target to click... > > If it's needed then is there some equivalent in HTML 5 or is it the same? > > > It is not required, but is good practice for labels that have a direct form element to focus on (it wouldn't make much sense for a label that doesn't have a counterpart on a form). The syntax is the same for HTML 5.
For binds the `<label>` and the `<input>` field together. `for` should point to the `id` of the `<input>`. It is not actually needed, but it is useful for example on radio buttons, where the user can click the label to check the radio button, thus creating a larger click area and a better user experience. You use `for` the same in way HTML5 as you do in HTML4 or XHTML or whatever you used before.
10,813,592
> > **Possible Duplicate:** > > [What is the For attribute for in an HTML tag?](https://stackoverflow.com/questions/3681601/what-is-the-for-attribute-for-in-an-html-tag) > > > I have been trying to find this out. What is the reason for using the "for=" when you use a label in HTML? ``` <form> <label for="male">Male</label> <input type="radio" name="sex" id="male" /> <br /> <label for="female">Female</label> <input type="radio" name="sex" id="female" /> </form> ``` If it's needed then is there some equivalent in HTML 5 or is it the same?
2012/05/30
[ "https://Stackoverflow.com/questions/10813592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1422604/" ]
For binds the `<label>` and the `<input>` field together. `for` should point to the `id` of the `<input>`. It is not actually needed, but it is useful for example on radio buttons, where the user can click the label to check the radio button, thus creating a larger click area and a better user experience. You use `for` the same in way HTML5 as you do in HTML4 or XHTML or whatever you used before.
If you use the `for` attribute of the label, and set its value to the `id` of a related `input` element, most browsers will focus the input element when the label is clicked on. This is especially useful for small elements like checkboxes and radio buttons.
10,813,592
> > **Possible Duplicate:** > > [What is the For attribute for in an HTML tag?](https://stackoverflow.com/questions/3681601/what-is-the-for-attribute-for-in-an-html-tag) > > > I have been trying to find this out. What is the reason for using the "for=" when you use a label in HTML? ``` <form> <label for="male">Male</label> <input type="radio" name="sex" id="male" /> <br /> <label for="female">Female</label> <input type="radio" name="sex" id="female" /> </form> ``` If it's needed then is there some equivalent in HTML 5 or is it the same?
2012/05/30
[ "https://Stackoverflow.com/questions/10813592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1422604/" ]
It makes a click on the label focus the input element it is `for`. In the example you posted, you simply click on the word `Male` *or* the radio button in order for it to get selected. Without this, you have a much smaller target to click... > > If it's needed then is there some equivalent in HTML 5 or is it the same? > > > It is not required, but is good practice for labels that have a direct form element to focus on (it wouldn't make much sense for a label that doesn't have a counterpart on a form). The syntax is the same for HTML 5.
If you use the `for` attribute of the label, and set its value to the `id` of a related `input` element, most browsers will focus the input element when the label is clicked on. This is especially useful for small elements like checkboxes and radio buttons.
647,156
Can the following integral be computed? ![enter image description here](https://i.stack.imgur.com/M2UBx.jpg)
2014/01/22
[ "https://math.stackexchange.com/questions/647156", "https://math.stackexchange.com", "https://math.stackexchange.com/users/121418/" ]
Hint: consider $$A\_n=\int\_{1/(n+1)}^{1/n}\{1/x\}^{4}dx$$. This can be computed. Does the series $\sum\_{i=1}^\infty A\_i$ converges?
First, let's prove that it converges: $$\int\_0^1\bigg\{\frac1x\bigg\}^4dx=\int\_1^\infty\frac{\{t\}^4}{t^2}dt\color{red}<\int\_1^\infty\frac{1^4}{t^2}dt=\bigg[-\frac1t\bigg]\_1^\infty=1,\qquad\text{since }0\le\{t\}<1.$$ --- $$\int\_0^1\bigg\{\frac1x\bigg\}^4dx=\int\_1^\infty\frac{\{t\}^4}{t^2}dt=\sum\_1^\infty\int\_k^{k+1}\frac{(t-k)^4}{t^2}dt=\sum\_1^\infty\int\_0^1\frac{u^4}{(u+k)^2}du=$$ $$=\sum\_1^\infty\bigg(\frac43-2k+4k^2-\frac1{k+1}+4k^3\ln\frac k{k+1}\bigg)=\ldots<1$$