question_id int64 4 6.31M | answer_id int64 7 6.31M | title stringlengths 9 150 | question_body stringlengths 0 28.8k | answer_body stringlengths 60 27.2k | question_text stringlengths 40 28.9k | combined_text stringlengths 124 39.6k | tags listlengths 1 6 | question_score int64 0 26.3k | answer_score int64 0 28.8k | view_count int64 15 14M | answer_count int64 0 182 | favorite_count int64 0 32 | question_creation_date stringdate 2008-07-31 21:42:52 2011-06-10 18:12:18 | answer_creation_date stringdate 2008-07-31 22:17:57 2011-06-10 18:14:17 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6,308,369 | 6,308,515 | CSS form buttons | I'm looking for a good way to implement reusable buttons in CSS on my forms. The requirements: - Separate image and text (text is in many languages) - Rollover effects - Plays nicely cross browser - No javascript (if possible) - Rounded corners Whats the best way to do this? Years ago I was using the sliding doors technique, but this seems out of date now. Would you use CSS3 with a fallback for older browsers? Any particularly well thought of techniques out there? | I would use css sprites for this. You can find out about them here: http://css-tricks.com/css-sprites/ It is basically a way to make one large image that has all states of buttons(normal, hover, selected). The benefit is it is one http request and you don't see a flicker the first time a hover occurs. If you use this route, the css background property will be the image. You can then use text-align and line-height to center the text that you want to place over the image. | CSS form buttons I'm looking for a good way to implement reusable buttons in CSS on my forms. The requirements: - Separate image and text (text is in many languages) - Rollover effects - Plays nicely cross browser - No javascript (if possible) - Rounded corners Whats the best way to do this? Years ago I was using the sliding doors technique, but this seems out of date now. Would you use CSS3 with a fallback for older browsers? Any particularly well thought of techniques out there? | TITLE:
CSS form buttons
QUESTION:
I'm looking for a good way to implement reusable buttons in CSS on my forms. The requirements: - Separate image and text (text is in many languages) - Rollover effects - Plays nicely cross browser - No javascript (if possible) - Rounded corners Whats the best way to do this? Years ago I was using the sliding doors technique, but this seems out of date now. Would you use CSS3 with a fallback for older browsers? Any particularly well thought of techniques out there?
ANSWER:
I would use css sprites for this. You can find out about them here: http://css-tricks.com/css-sprites/ It is basically a way to make one large image that has all states of buttons(normal, hover, selected). The benefit is it is one http request and you don't see a flicker the first time a hover occurs. If you use this route, the css background property will be the image. You can then use text-align and line-height to center the text that you want to place over the image. | [
"button",
"css"
] | 0 | 1 | 639 | 5 | 0 | 2011-06-10T15:14:53.590000 | 2011-06-10T15:25:25.670000 |
6,308,373 | 6,310,348 | How do I invoke the '!=' method on an object? | I just started playing with scala and have been using the "Scala By Example" by Michel Schinz ( http://www.scala-lang.org/node/198 ) as a starting point. In the segment on traits, I've attempted to use reflection/method invocation to test traits and wanted to test all the comparison operator. I hit the issue with name mangling and found the solution in NameTransformer for the operators. However, the!= operator, appears to me that it does not translate into an equivalent function like <, <=, >, >=, equals. I wonder if there is a way to invoke!= much like the other operators that I have not found out? From the pdf: trait ord { def < (that:Any):Boolean def <= (that:Any):Boolean = (this < that) || (this == that) def > (that:Any):Boolean =!(this <= that) def >= (that:Any):Boolean =!(this < that) }
class Date(y:Int, m:Int, d:Int) extends ord{ def year = y def month = m def day = d
override def toString():String = year + "-" + month + "-" + day
override def equals(that:Any): Boolean = that.isInstanceOf[Date] && { val o = that.asInstanceOf[Date] o.day == this.day && o.month == this.month && o.year == this.year }
override def <(that:Any):Boolean = { if (!that.isInstanceOf[Date]) error("Cannot compare " + that + " and date") val o = that.asInstanceOf[Date] (year < o.year) || (year == o.year && (month < o.month || (month == o.month && day < o.day ))) } } My code: def Classes_Traits(){ val (d1, d2, d3) = (new Date(2001, 10, 1), new Date(2001, 10, 1), new Date(2000, 1, 10)) println("d1: " + d1) println("d2: " + d2) println("d3: " + d3)
Array((d1,d2), (d2,d3), (d3,d1)).foreach { (comp:(Date, Date)) => println("comparing " + comp._1 + " and " + comp._2) val d = comp._1.getClass() Map( "equals " -> "equals", "not equals " -> "!=", "less than " -> "<", "less than or equal" -> "<=", "more than " -> ">", "more than or equal" -> ">=").foreach { (a) => println(a._1 + ": " + d.getMethod(scala.reflect.NameTransformer.encode(a._2), classOf[Object]).invoke(comp._1, comp._2)) } /*println("equals: " + m.invoke(comp._1, comp._2) ) // Same as above println(comp._1 + " == " + comp._2 + " is " + (comp._1 == comp._2)) println(comp._1 + "!= " + comp._2 + " is " + (comp._1!= comp._2)) println(comp._1 + " > " + comp._2 + " is " + (comp._1 > comp._2)) println(comp._1 + " >= " + comp._2 + " is " + (comp._1 >= comp._2)) println(comp._1 + " < " + comp._2 + " is " + (comp._1 < comp._2)) println(comp._1 + " <= " + comp._2 + " is " + (comp._1 <= comp._2)) */ } } exception: comparing 2001-10-1 and 2001-10-1 more than or equal: true more than: false Exception in thread "main" java.lang.NoSuchMethodException: proj2.Main$Date.$bang$eq(java.lang.Object) at java.lang.Class.getMethod(Class.java:1605) at proj2.Main$$anonfun$Classes_Traits$1$$anonfun$apply$1.apply(Main.scala:180) at proj2.Main$$anonfun$Classes_Traits$1$$anonfun$apply$1.apply(Main.scala:178) at scala.collection.immutable.HashMap$HashMap1.foreach(HashMap.scala:125) at scala.collection.immutable.HashMap$HashTrieMap.foreach(HashMap.scala:344) at proj2.Main$$anonfun$Classes_Traits$1.apply(Main.scala:177) at proj2.Main$$anonfun$Classes_Traits$1.apply(Main.scala:168) at scala.collection.IndexedSeqOptimized$class.foreach(IndexedSeqOptimized.scala:34) at scala.collection.mutable.ArrayOps.foreach(ArrayOps.scala:35) at proj2.Main$.Classes_Traits(Main.scala:167) at proj2.Main$.main(Main.scala:26) at proj2.Main.main(Main.scala) | Try calling equals and negating the result. == and!= benefit from a little compiler magic in Scala (e.g., you can call null.==(4) without getting a NullPointerException ). | How do I invoke the '!=' method on an object? I just started playing with scala and have been using the "Scala By Example" by Michel Schinz ( http://www.scala-lang.org/node/198 ) as a starting point. In the segment on traits, I've attempted to use reflection/method invocation to test traits and wanted to test all the comparison operator. I hit the issue with name mangling and found the solution in NameTransformer for the operators. However, the!= operator, appears to me that it does not translate into an equivalent function like <, <=, >, >=, equals. I wonder if there is a way to invoke!= much like the other operators that I have not found out? From the pdf: trait ord { def < (that:Any):Boolean def <= (that:Any):Boolean = (this < that) || (this == that) def > (that:Any):Boolean =!(this <= that) def >= (that:Any):Boolean =!(this < that) }
class Date(y:Int, m:Int, d:Int) extends ord{ def year = y def month = m def day = d
override def toString():String = year + "-" + month + "-" + day
override def equals(that:Any): Boolean = that.isInstanceOf[Date] && { val o = that.asInstanceOf[Date] o.day == this.day && o.month == this.month && o.year == this.year }
override def <(that:Any):Boolean = { if (!that.isInstanceOf[Date]) error("Cannot compare " + that + " and date") val o = that.asInstanceOf[Date] (year < o.year) || (year == o.year && (month < o.month || (month == o.month && day < o.day ))) } } My code: def Classes_Traits(){ val (d1, d2, d3) = (new Date(2001, 10, 1), new Date(2001, 10, 1), new Date(2000, 1, 10)) println("d1: " + d1) println("d2: " + d2) println("d3: " + d3)
Array((d1,d2), (d2,d3), (d3,d1)).foreach { (comp:(Date, Date)) => println("comparing " + comp._1 + " and " + comp._2) val d = comp._1.getClass() Map( "equals " -> "equals", "not equals " -> "!=", "less than " -> "<", "less than or equal" -> "<=", "more than " -> ">", "more than or equal" -> ">=").foreach { (a) => println(a._1 + ": " + d.getMethod(scala.reflect.NameTransformer.encode(a._2), classOf[Object]).invoke(comp._1, comp._2)) } /*println("equals: " + m.invoke(comp._1, comp._2) ) // Same as above println(comp._1 + " == " + comp._2 + " is " + (comp._1 == comp._2)) println(comp._1 + "!= " + comp._2 + " is " + (comp._1!= comp._2)) println(comp._1 + " > " + comp._2 + " is " + (comp._1 > comp._2)) println(comp._1 + " >= " + comp._2 + " is " + (comp._1 >= comp._2)) println(comp._1 + " < " + comp._2 + " is " + (comp._1 < comp._2)) println(comp._1 + " <= " + comp._2 + " is " + (comp._1 <= comp._2)) */ } } exception: comparing 2001-10-1 and 2001-10-1 more than or equal: true more than: false Exception in thread "main" java.lang.NoSuchMethodException: proj2.Main$Date.$bang$eq(java.lang.Object) at java.lang.Class.getMethod(Class.java:1605) at proj2.Main$$anonfun$Classes_Traits$1$$anonfun$apply$1.apply(Main.scala:180) at proj2.Main$$anonfun$Classes_Traits$1$$anonfun$apply$1.apply(Main.scala:178) at scala.collection.immutable.HashMap$HashMap1.foreach(HashMap.scala:125) at scala.collection.immutable.HashMap$HashTrieMap.foreach(HashMap.scala:344) at proj2.Main$$anonfun$Classes_Traits$1.apply(Main.scala:177) at proj2.Main$$anonfun$Classes_Traits$1.apply(Main.scala:168) at scala.collection.IndexedSeqOptimized$class.foreach(IndexedSeqOptimized.scala:34) at scala.collection.mutable.ArrayOps.foreach(ArrayOps.scala:35) at proj2.Main$.Classes_Traits(Main.scala:167) at proj2.Main$.main(Main.scala:26) at proj2.Main.main(Main.scala) | TITLE:
How do I invoke the '!=' method on an object?
QUESTION:
I just started playing with scala and have been using the "Scala By Example" by Michel Schinz ( http://www.scala-lang.org/node/198 ) as a starting point. In the segment on traits, I've attempted to use reflection/method invocation to test traits and wanted to test all the comparison operator. I hit the issue with name mangling and found the solution in NameTransformer for the operators. However, the!= operator, appears to me that it does not translate into an equivalent function like <, <=, >, >=, equals. I wonder if there is a way to invoke!= much like the other operators that I have not found out? From the pdf: trait ord { def < (that:Any):Boolean def <= (that:Any):Boolean = (this < that) || (this == that) def > (that:Any):Boolean =!(this <= that) def >= (that:Any):Boolean =!(this < that) }
class Date(y:Int, m:Int, d:Int) extends ord{ def year = y def month = m def day = d
override def toString():String = year + "-" + month + "-" + day
override def equals(that:Any): Boolean = that.isInstanceOf[Date] && { val o = that.asInstanceOf[Date] o.day == this.day && o.month == this.month && o.year == this.year }
override def <(that:Any):Boolean = { if (!that.isInstanceOf[Date]) error("Cannot compare " + that + " and date") val o = that.asInstanceOf[Date] (year < o.year) || (year == o.year && (month < o.month || (month == o.month && day < o.day ))) } } My code: def Classes_Traits(){ val (d1, d2, d3) = (new Date(2001, 10, 1), new Date(2001, 10, 1), new Date(2000, 1, 10)) println("d1: " + d1) println("d2: " + d2) println("d3: " + d3)
Array((d1,d2), (d2,d3), (d3,d1)).foreach { (comp:(Date, Date)) => println("comparing " + comp._1 + " and " + comp._2) val d = comp._1.getClass() Map( "equals " -> "equals", "not equals " -> "!=", "less than " -> "<", "less than or equal" -> "<=", "more than " -> ">", "more than or equal" -> ">=").foreach { (a) => println(a._1 + ": " + d.getMethod(scala.reflect.NameTransformer.encode(a._2), classOf[Object]).invoke(comp._1, comp._2)) } /*println("equals: " + m.invoke(comp._1, comp._2) ) // Same as above println(comp._1 + " == " + comp._2 + " is " + (comp._1 == comp._2)) println(comp._1 + "!= " + comp._2 + " is " + (comp._1!= comp._2)) println(comp._1 + " > " + comp._2 + " is " + (comp._1 > comp._2)) println(comp._1 + " >= " + comp._2 + " is " + (comp._1 >= comp._2)) println(comp._1 + " < " + comp._2 + " is " + (comp._1 < comp._2)) println(comp._1 + " <= " + comp._2 + " is " + (comp._1 <= comp._2)) */ } } exception: comparing 2001-10-1 and 2001-10-1 more than or equal: true more than: false Exception in thread "main" java.lang.NoSuchMethodException: proj2.Main$Date.$bang$eq(java.lang.Object) at java.lang.Class.getMethod(Class.java:1605) at proj2.Main$$anonfun$Classes_Traits$1$$anonfun$apply$1.apply(Main.scala:180) at proj2.Main$$anonfun$Classes_Traits$1$$anonfun$apply$1.apply(Main.scala:178) at scala.collection.immutable.HashMap$HashMap1.foreach(HashMap.scala:125) at scala.collection.immutable.HashMap$HashTrieMap.foreach(HashMap.scala:344) at proj2.Main$$anonfun$Classes_Traits$1.apply(Main.scala:177) at proj2.Main$$anonfun$Classes_Traits$1.apply(Main.scala:168) at scala.collection.IndexedSeqOptimized$class.foreach(IndexedSeqOptimized.scala:34) at scala.collection.mutable.ArrayOps.foreach(ArrayOps.scala:35) at proj2.Main$.Classes_Traits(Main.scala:167) at proj2.Main$.main(Main.scala:26) at proj2.Main.main(Main.scala)
ANSWER:
Try calling equals and negating the result. == and!= benefit from a little compiler magic in Scala (e.g., you can call null.==(4) without getting a NullPointerException ). | [
"scala",
"scala-2.8"
] | 3 | 5 | 213 | 1 | 0 | 2011-06-10T15:15:18.903000 | 2011-06-10T18:03:30.680000 |
6,308,376 | 6,308,509 | PHP Navigation + jQuery animation - Page Reload | i have a site with a simple PHP-Navigation (using $_GET-Variables). HTML-code for navigation links (they are floated right): Test 1 Test 2 Test 3 Simple PHP-codeblock to include pages: if(!isset($_GET['main'])) { $page = "home"; } else { $page = $_GET['main']; } include($page.".php"); Both codeblocs are on index.php. The menu-elements are animated with jQuerys.animate() like this (the code is between $(document).ready): $('.menuelement').hover(function () { if ($(this).hasClass('clicked') == false) { $(this).stop(true, false).animate({ 'padding-right': '80px' }, 900, 'easeOutBounce'); } }, function () { if ($(this).hasClass('clicked') == false) { $(this).stop(true, false).animate({ 'padding-right': '0px' }, 900, 'easeOutBounce'); } } ).click(function() { if ($(this).hasClass('clicked') == true) { //Don't do anything. } else { $('a.clicked').animate({ 'padding-right': '0px' }, 900, 'easeOutBounce'); $('a.clicked').removeClass('clicked');
$(this).addClass('clicked'); $(this).stop(true, false).animate({ 'padding-right': '80px' }, 900, 'easeOutBounce'); } }); What happens is that the hovered menuelement slides to the left (remember: it's floated right), on mouseout it slides back. On click, it stays where it is and gets a class to mark that it's clicked. If you click on another menuelement, the one which was clicked before slides back and the new one stays slided out. All this is done with addClass, removeClass and some if-else-statements... quite simple. If the a-Tags of the links doesn't have any linktargets, e. g. only the hash sign () everything works fine. But as soon as the links have a target (e. g. ), the jQuery-animation starts again when a menuelement is clicked, because index.php is kind of reloaded. The result is that the clicked menuelement won't stay slided out. I know I could (and I already did) load some content with e. g..load() into a div. But I don't want to do that concerning SEO and some other aspects. Is ther any way to use the PHP-navigation and jQuerys fantastic.animate(), without "reloading" the animation each time a link is clicked? Maybe there are some PHP or jQuery hints that I don't know. Thank you for any help! | You can use event.preventDefault() to stop the browser from following the link and use a complete callback function in animate to load the linked-to page after the animation is done. | PHP Navigation + jQuery animation - Page Reload i have a site with a simple PHP-Navigation (using $_GET-Variables). HTML-code for navigation links (they are floated right): Test 1 Test 2 Test 3 Simple PHP-codeblock to include pages: if(!isset($_GET['main'])) { $page = "home"; } else { $page = $_GET['main']; } include($page.".php"); Both codeblocs are on index.php. The menu-elements are animated with jQuerys.animate() like this (the code is between $(document).ready): $('.menuelement').hover(function () { if ($(this).hasClass('clicked') == false) { $(this).stop(true, false).animate({ 'padding-right': '80px' }, 900, 'easeOutBounce'); } }, function () { if ($(this).hasClass('clicked') == false) { $(this).stop(true, false).animate({ 'padding-right': '0px' }, 900, 'easeOutBounce'); } } ).click(function() { if ($(this).hasClass('clicked') == true) { //Don't do anything. } else { $('a.clicked').animate({ 'padding-right': '0px' }, 900, 'easeOutBounce'); $('a.clicked').removeClass('clicked');
$(this).addClass('clicked'); $(this).stop(true, false).animate({ 'padding-right': '80px' }, 900, 'easeOutBounce'); } }); What happens is that the hovered menuelement slides to the left (remember: it's floated right), on mouseout it slides back. On click, it stays where it is and gets a class to mark that it's clicked. If you click on another menuelement, the one which was clicked before slides back and the new one stays slided out. All this is done with addClass, removeClass and some if-else-statements... quite simple. If the a-Tags of the links doesn't have any linktargets, e. g. only the hash sign () everything works fine. But as soon as the links have a target (e. g. ), the jQuery-animation starts again when a menuelement is clicked, because index.php is kind of reloaded. The result is that the clicked menuelement won't stay slided out. I know I could (and I already did) load some content with e. g..load() into a div. But I don't want to do that concerning SEO and some other aspects. Is ther any way to use the PHP-navigation and jQuerys fantastic.animate(), without "reloading" the animation each time a link is clicked? Maybe there are some PHP or jQuery hints that I don't know. Thank you for any help! | TITLE:
PHP Navigation + jQuery animation - Page Reload
QUESTION:
i have a site with a simple PHP-Navigation (using $_GET-Variables). HTML-code for navigation links (they are floated right): Test 1 Test 2 Test 3 Simple PHP-codeblock to include pages: if(!isset($_GET['main'])) { $page = "home"; } else { $page = $_GET['main']; } include($page.".php"); Both codeblocs are on index.php. The menu-elements are animated with jQuerys.animate() like this (the code is between $(document).ready): $('.menuelement').hover(function () { if ($(this).hasClass('clicked') == false) { $(this).stop(true, false).animate({ 'padding-right': '80px' }, 900, 'easeOutBounce'); } }, function () { if ($(this).hasClass('clicked') == false) { $(this).stop(true, false).animate({ 'padding-right': '0px' }, 900, 'easeOutBounce'); } } ).click(function() { if ($(this).hasClass('clicked') == true) { //Don't do anything. } else { $('a.clicked').animate({ 'padding-right': '0px' }, 900, 'easeOutBounce'); $('a.clicked').removeClass('clicked');
$(this).addClass('clicked'); $(this).stop(true, false).animate({ 'padding-right': '80px' }, 900, 'easeOutBounce'); } }); What happens is that the hovered menuelement slides to the left (remember: it's floated right), on mouseout it slides back. On click, it stays where it is and gets a class to mark that it's clicked. If you click on another menuelement, the one which was clicked before slides back and the new one stays slided out. All this is done with addClass, removeClass and some if-else-statements... quite simple. If the a-Tags of the links doesn't have any linktargets, e. g. only the hash sign () everything works fine. But as soon as the links have a target (e. g. ), the jQuery-animation starts again when a menuelement is clicked, because index.php is kind of reloaded. The result is that the clicked menuelement won't stay slided out. I know I could (and I already did) load some content with e. g..load() into a div. But I don't want to do that concerning SEO and some other aspects. Is ther any way to use the PHP-navigation and jQuerys fantastic.animate(), without "reloading" the animation each time a link is clicked? Maybe there are some PHP or jQuery hints that I don't know. Thank you for any help!
ANSWER:
You can use event.preventDefault() to stop the browser from following the link and use a complete callback function in animate to load the linked-to page after the animation is done. | [
"php",
"jquery",
"navigation",
"reload"
] | 0 | 0 | 1,282 | 1 | 0 | 2011-06-10T15:15:32.583000 | 2011-06-10T15:24:56.933000 |
6,308,382 | 6,309,148 | Start a new line (paragraph) on a Label or TextView | I'd like to start a new line paragraph on a label and on a TextView but I can't find a way to do it via Interface Builder. Can you help me please? Thanks in advance | Two steps: In Interface Builder you have to set the "number of lines" option to 0 Use Cmd+Return (or Alt-Return) to make a carriage return | Start a new line (paragraph) on a Label or TextView I'd like to start a new line paragraph on a label and on a TextView but I can't find a way to do it via Interface Builder. Can you help me please? Thanks in advance | TITLE:
Start a new line (paragraph) on a Label or TextView
QUESTION:
I'd like to start a new line paragraph on a label and on a TextView but I can't find a way to do it via Interface Builder. Can you help me please? Thanks in advance
ANSWER:
Two steps: In Interface Builder you have to set the "number of lines" option to 0 Use Cmd+Return (or Alt-Return) to make a carriage return | [
"iphone",
"ios",
"ipad",
"xcode4"
] | 15 | 24 | 11,715 | 1 | 0 | 2011-06-10T15:15:52.400000 | 2011-06-10T16:12:53.640000 |
6,308,383 | 6,308,456 | Sql Server With Scope | I was wondering if there was any way to make the scope of a with statement more than just for the first statement after the with, for example WITH cr AS (SELECT TOP 1 * FROM @rq ORDER BY h, f) SELECT * FROM cr DELETE cr FROM @rq by the time the line DELETE cr FROM @rq is reached SQL SERVER no longer remembers what cr is and gives the error Invalid object name 'cr'., I have tried adding begin and end blocks so it looked like WITH cr AS (SELECT TOP 1 * FROM @rq ORDER BY h, f) BEGIN SELECT * FROM cr DELETE cr FROM @rq END but that is invalid and gives the error Incorrect syntax near the keyword 'BEGIN'. Can the scope of a with statement be expanded or was it always created to be used instantly and then no longer be accessible? NOTE: WITH cr AS (SELECT TOP 1 * FROM @rq ORDER BY h, f) DELETE cr FROM @rq works as does WITH cr AS (SELECT TOP 1 * FROM @rq ORDER BY h, f) SELECT * FROM cr so both statements are allowed when the with statement is used | For now, you'd need to store the results of the CTE query in a table variable or temp table. There is an open Microsoft Connect item requesting such functionality if you'd like to vote it up. | Sql Server With Scope I was wondering if there was any way to make the scope of a with statement more than just for the first statement after the with, for example WITH cr AS (SELECT TOP 1 * FROM @rq ORDER BY h, f) SELECT * FROM cr DELETE cr FROM @rq by the time the line DELETE cr FROM @rq is reached SQL SERVER no longer remembers what cr is and gives the error Invalid object name 'cr'., I have tried adding begin and end blocks so it looked like WITH cr AS (SELECT TOP 1 * FROM @rq ORDER BY h, f) BEGIN SELECT * FROM cr DELETE cr FROM @rq END but that is invalid and gives the error Incorrect syntax near the keyword 'BEGIN'. Can the scope of a with statement be expanded or was it always created to be used instantly and then no longer be accessible? NOTE: WITH cr AS (SELECT TOP 1 * FROM @rq ORDER BY h, f) DELETE cr FROM @rq works as does WITH cr AS (SELECT TOP 1 * FROM @rq ORDER BY h, f) SELECT * FROM cr so both statements are allowed when the with statement is used | TITLE:
Sql Server With Scope
QUESTION:
I was wondering if there was any way to make the scope of a with statement more than just for the first statement after the with, for example WITH cr AS (SELECT TOP 1 * FROM @rq ORDER BY h, f) SELECT * FROM cr DELETE cr FROM @rq by the time the line DELETE cr FROM @rq is reached SQL SERVER no longer remembers what cr is and gives the error Invalid object name 'cr'., I have tried adding begin and end blocks so it looked like WITH cr AS (SELECT TOP 1 * FROM @rq ORDER BY h, f) BEGIN SELECT * FROM cr DELETE cr FROM @rq END but that is invalid and gives the error Incorrect syntax near the keyword 'BEGIN'. Can the scope of a with statement be expanded or was it always created to be used instantly and then no longer be accessible? NOTE: WITH cr AS (SELECT TOP 1 * FROM @rq ORDER BY h, f) DELETE cr FROM @rq works as does WITH cr AS (SELECT TOP 1 * FROM @rq ORDER BY h, f) SELECT * FROM cr so both statements are allowed when the with statement is used
ANSWER:
For now, you'd need to store the results of the CTE query in a table variable or temp table. There is an open Microsoft Connect item requesting such functionality if you'd like to vote it up. | [
"sql",
"t-sql",
"sql-server-2008"
] | 0 | 1 | 111 | 2 | 0 | 2011-06-10T15:15:55.337000 | 2011-06-10T15:21:26.070000 |
6,308,386 | 6,309,320 | Has anyone secured a .net wcf RESTful service using basic/digest authentication? | I have to secure a WCF RESTful service i'm thinking of doing it in one of two following ways... 1: By implementing the feature suggested in this article 2: By simply passing a username and password in either the url or the post variables What im wondering is has anyone done this? Is this the way to do it? If I use the second option can this be accused of being insecure (given that asp.net forms are sent clear text anyway)? | Passing PII information on the querystring is a definite no-no. WCF supports basic authentication out of the box. You would need to combine this with transport security (SSL) to ensure the data is safely encrypted over the wire. This is absolutely the lowest common denominator form of authentication on the web and will be supported most widely. To configure your WCF REST service with this kind of security you simply need to configure your service's binding like so: WCF supports digest authenticatoin out of the box as well, but only if validated against the AD of the server which pretty much makes it useless in internet scenarios. So to do Digest Authentication you would need to write your own implementation which hooks into the WCF security runtime. There are some examples of how to do this out there on the web. That said, if you have SSL, there's no real benefit to doing digest authentication over basic authentication. | Has anyone secured a .net wcf RESTful service using basic/digest authentication? I have to secure a WCF RESTful service i'm thinking of doing it in one of two following ways... 1: By implementing the feature suggested in this article 2: By simply passing a username and password in either the url or the post variables What im wondering is has anyone done this? Is this the way to do it? If I use the second option can this be accused of being insecure (given that asp.net forms are sent clear text anyway)? | TITLE:
Has anyone secured a .net wcf RESTful service using basic/digest authentication?
QUESTION:
I have to secure a WCF RESTful service i'm thinking of doing it in one of two following ways... 1: By implementing the feature suggested in this article 2: By simply passing a username and password in either the url or the post variables What im wondering is has anyone done this? Is this the way to do it? If I use the second option can this be accused of being insecure (given that asp.net forms are sent clear text anyway)?
ANSWER:
Passing PII information on the querystring is a definite no-no. WCF supports basic authentication out of the box. You would need to combine this with transport security (SSL) to ensure the data is safely encrypted over the wire. This is absolutely the lowest common denominator form of authentication on the web and will be supported most widely. To configure your WCF REST service with this kind of security you simply need to configure your service's binding like so: WCF supports digest authenticatoin out of the box as well, but only if validated against the AD of the server which pretty much makes it useless in internet scenarios. So to do Digest Authentication you would need to write your own implementation which hooks into the WCF security runtime. There are some examples of how to do this out there on the web. That said, if you have SSL, there's no real benefit to doing digest authentication over basic authentication. | [
"asp.net",
"wcf"
] | 0 | 0 | 507 | 1 | 0 | 2011-06-10T15:16:06.913000 | 2011-06-10T16:25:38.420000 |
6,308,392 | 6,309,149 | Oracle: Inconsistent Datatype Issue | I am getting inconsistent datatype error message and I am not sure why. I need some guidance to figure this out. I am creating two types as: My universe table have following columns with column type: Column Name Data Type
PON VARCHAR2(25 BYTE) RPON VARCHAR2(25 BYTE) SUPPLIER_NAME VARCHAR2(255 BYTE) SUB_SUPPLIER_NAME VARCHAR2(255 BYTE) SOURCE_NO VARCHAR2(40 BYTE) CKR VARCHAR2(200 BYTE) LEC_ID VARCHAR2(200 BYTE) ICSC VARCHAR2(10 BYTE) ACTL_ST VARCHAR2(10 BYTE) ADW_ST VARCHAR2(10 BYTE) PROJ_ID VARCHAR2(100 BYTE) MOVE_TO_INV_DT DATE IE_DT DATE DDD_DT DATE EFF_BILL_DT DATE ACTION VARCHAR2(10 BYTE) SERVICE VARCHAR2(10 BYTE) AFP VARCHAR2(10 BYTE) ACNA VARCHAR2(10 BYTE) SERVICE_NAME VARCHAR2(255 BYTE) UPLOAD_DT DATE PROGRAM VARCHAR2(50 BYTE) INITIATIVE_ID NUMBER ACOST NUMBER ACOST_IND VARCHAR2(25 BYTE) MAPFILE VARCHAR2(100 BYTE) Row Type create or replace TYPE test_COMP_REPORT_ROW_TYPE AS OBJECT ( PON VARCHAR2(25 BYTE), RPON VARCHAR2(25 BYTE), VENDOR VARCHAR2(255 BYTE), SUB_SUPPLIER VARCHAR2(255 BYTE), SOURCE_NO VARCHAR2(40 BYTE), ATT_CKT_ID VARCHAR2(200 BYTE), LEC_ID VARCHAR2(200 BYTE), ICSC VARCHAR2(10 BYTE), STATE VARCHAR2(10 BYTE), PROJECT_ID VARCHAR2(100 BYTE), ACTION VARCHAR2(10 BYTE), SERVICE_SPEED VARCHAR2(10 BYTE), SERVICE_NAME VARCHAR(255 BYTE), INEFFECT_DATE DATE, EVENT_DATE DATE, DUE_DATE DATE, ACOST NUMBER ) Tab Type create or replace type test_COMP_REPORT_TAB_TYPE AS TABLE OF test_COMP_REPORT_ROW_TYPE Here is the Function which is using this type: create or replace FUNCTION test_comp_report_func ( start_dt_h IN VARCHAR2 DEFAULT NULL, end_dt_h IN VARCHAR2 DEFAULT NULL, year_h IN VARCHAR2 DEFAULT NULL ) RETURN test_comp_report_tab_type pipelined IS e_sql LONG; program_v VARCHAR2(10);
v_row test_comp_report_row_type:= test_comp_report_row_type(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL );
TYPE rectyp IS REF CURSOR; rrc_rectyp rectyp; TYPE recordvar IS RECORD ( PON VARCHAR2(25 BYTE), RPON VARCHAR2(25 BYTE), VENDOR VARCHAR2(255 BYTE), SUB_SUPPLIER VARCHAR2(255 BYTE), SOURCE_NO VARCHAR2(40 BYTE), ATT_CKT_ID VARCHAR2(200 BYTE), LEC_ID VARCHAR2(200 BYTE), ICSC VARCHAR2(10 BYTE), STATE VARCHAR2(10 BYTE), PROJECT_ID VARCHAR2(100 BYTE), ACTION VARCHAR2(10 BYTE), SERVICE_SPEED VARCHAR2(10 BYTE), SERVICE_NAME VARCHAR(255 BYTE), INEFFECT_DATE DATE, EVENT_DATE DATE, DUE_DATE DATE, ACOST NUMBER ); res_rec recordvar;
BEGIN
e_sql:= e_sql || 'SELECT PON, RPON, SUPPLIER_NAME VENDOR, SUB_SUPPLIER_NAME SUB_SUPPLIER, SOURCE_NO, CKR, LEC_ID, ICSC, ACTL_ST, ADW_ST STATE, PROJ_ID, ACTION, SERVICE SPEED, AFP, ACNA, SERVICE_NAME, IE_DT, MOVE_TO_INV_DT EVENTDAT, DDD_DT DUEDATE, EFF_BILL_DT, ACOST FROM UNIVERSE WHERE to_date(IE_DT) between to_date(nvl(''01/01/2000'', ''01/01/2000''), ''MM/DD/YYYY'') and to_date(nvl(''12/31/2009'', to_char(trunc(add_months(sysdate, 12),''year'')-1,''MM/DD/YYYY'')), ''MM/DD/YYYY'') AND PROGRAM = ''T45sONNET'' AND nvl(trim(ACOST_IND), ''NULL'') not in (''INVALID-2005'') ORDER BY ACTION';
dbms_output.put_line(e_sql); OPEN rrc_rectyp FOR e_sql; LOOP FETCH rrc_rectyp INTO res_rec; EXIT WHEN rrc_rectyp%NOTFOUND; v_row.PON:= res_rec.PON; v_row.RPON:= res_rec.RPON; v_row.VENDOR:= res_rec.VENDOR; v_row.SUB_SUPPLIER:= res_rec.SUB_SUPPLIER; v_row.SOURCE_NO:= res_rec.SOURCE_NO; v_row.ATT_CKT_ID:= res_rec.ATT_CKT_ID; v_row.LEC_ID:= res_rec.LEC_ID; v_row.ICSC:= res_rec.ICSC; v_row.STATE:= res_rec.STATE; v_row.PROJECT_ID:= res_rec.PROJECT_ID; v_row.ACTION:= res_rec.ACTION; v_row.SERVICE_SPEED:= res_rec.SERVICE_SPEED; v_row.SERVICE_NAME:= res_rec.SERVICE_NAME; v_row.INEFFECT_DATE:= res_rec.INEFFECT_DATE; v_row.EVENT_DATE:= res_rec.EVENT_DATE; v_row.DUE_DATE:= res_rec.DUE_DATE; v_row.ACOST:= res_rec.ACOST; pipe ROW(v_row); END LOOP; return;
end test_comp_report_func; I have tried to debug issue but still am not able to find my way out and would appreciate if SO Community can guide. | I first wrote an answer trying to reproduce your error but you've changed your question quite a bit so I'm starting again from scratch. First a few remarks: By your own account you're quite new to PL/SQL yet you're using pretty advanced features: dynamic SQL, pipelined functions, SQL Objects. Let's try to begin with something simpler at first (I'll show you how you can work with static SQL, this would be sufficient 99.9% of the time). When you hit a problem you need to decompose your code to see what is working and what is not. That usually means simplifying your code until it is so simple it starts to work, then bring back the complex elements of your code one by one until you hit the problem again. When you provide a test case, try to make it as simple as possible:) It'll be easier for people to help you, but more importantly in most of the cases, building the test case will help you find the solution yourself since this will force you to decompose your complex code (see previous point). My rule of thumb (FWIW) is that code that is displayed with a scroll bar (either horizontal or vertical) in SO is too big for a test case and needs to be trimmed if possible. I ran your code and got the ORA-00932 on the fetch line. When I replace the SQL with static SQL the error is more explicit: SQL> CREATE OR REPLACE FUNCTION test_comp_report_func 2 RETURN test_comp_report_tab_type 3 PIPELINED IS 4 TYPE recordvar IS RECORD( 5 PON VARCHAR2(25 BYTE), (...snip...) 21 ACOST NUMBER); 22 res_rec recordvar; 23 v_row test_COMP_REPORT_ROW_TYPE; 24 CURSOR rrc_rectyp IS 25 SELECT PON, (...snip...) 45 ACOST 46 FROM UNIVERSE; 48 BEGIN 49 OPEN rrc_rectyp; 50 LOOP 51 FETCH rrc_rectyp 52 INTO res_rec; 54 EXIT WHEN rrc_rectyp%NOTFOUND; 55 /*...*/ 56 PIPE ROW(v_row); 57 END LOOP; 58 RETURN; 59 END test_comp_report_func; 60 /
Warning: Function created with compilation errors. LINE/COL ERROR -------- ----------------------------------------------------------------- 51/7 PL/SQL: SQL Statement ignored 52/15 PLS-00386: type mismatch found at 'RES_REC' between FETCH cursor and INTO variables Here the problem comes from the fact that your select statement doesn't have the same number of columns as the number of fields in your record. You can use %rowcount to prevent this: CREATE OR REPLACE FUNCTION test_comp_report_func RETURN test_comp_report_tab_type PIPELINED IS v_row test_COMP_REPORT_ROW_TYPE; CURSOR rrc_rectyp IS SELECT PON, RPON, SUPPLIER_NAME VENDOR, SUB_SUPPLIER_NAME SUB_SUPPLIER, SOURCE_NO, CKR, LEC_ID, ICSC, ACTL_ST, ADW_ST STATE, PROJ_ID, ACTION, SERVICE SPEED, AFP, ACNA, SERVICE_NAME, IE_DT, MOVE_TO_INV_DT EVENTDAT, DDD_DT DUEDATE, EFF_BILL_DT, ACOST FROM UNIVERSE; res_rec rrc_rectyp%ROWTYPE; BEGIN OPEN rrc_rectyp; LOOP FETCH rrc_rectyp INTO res_rec; EXIT WHEN rrc_rectyp%NOTFOUND; v_row.pon:= res_rec.pon; /*...*/ PIPE ROW(v_row); END LOOP; RETURN; END test_comp_report_func; You can even fetch the SQL object directly (with an implicit cursor): CREATE OR REPLACE FUNCTION test_comp_report_func RETURN test_comp_report_tab_type PIPELINED IS BEGIN FOR res_rec IN (SELECT test_comp_report_row_type(PON, RPON, SUPPLIER_NAME, SUB_SUPPLIER_NAME,SOURCE_NO, CKR, LEC_ID, ICSC, ACTL_ST, PROJ_ID, ACTION, SERVICE, SERVICE_NAME, IE_DT, DDD_DT, EFF_BILL_DT, ACOST)my_object FROM UNIVERSE) LOOP PIPE ROW(res_rec.my_object); END LOOP; RETURN; END test_comp_report_func; | Oracle: Inconsistent Datatype Issue I am getting inconsistent datatype error message and I am not sure why. I need some guidance to figure this out. I am creating two types as: My universe table have following columns with column type: Column Name Data Type
PON VARCHAR2(25 BYTE) RPON VARCHAR2(25 BYTE) SUPPLIER_NAME VARCHAR2(255 BYTE) SUB_SUPPLIER_NAME VARCHAR2(255 BYTE) SOURCE_NO VARCHAR2(40 BYTE) CKR VARCHAR2(200 BYTE) LEC_ID VARCHAR2(200 BYTE) ICSC VARCHAR2(10 BYTE) ACTL_ST VARCHAR2(10 BYTE) ADW_ST VARCHAR2(10 BYTE) PROJ_ID VARCHAR2(100 BYTE) MOVE_TO_INV_DT DATE IE_DT DATE DDD_DT DATE EFF_BILL_DT DATE ACTION VARCHAR2(10 BYTE) SERVICE VARCHAR2(10 BYTE) AFP VARCHAR2(10 BYTE) ACNA VARCHAR2(10 BYTE) SERVICE_NAME VARCHAR2(255 BYTE) UPLOAD_DT DATE PROGRAM VARCHAR2(50 BYTE) INITIATIVE_ID NUMBER ACOST NUMBER ACOST_IND VARCHAR2(25 BYTE) MAPFILE VARCHAR2(100 BYTE) Row Type create or replace TYPE test_COMP_REPORT_ROW_TYPE AS OBJECT ( PON VARCHAR2(25 BYTE), RPON VARCHAR2(25 BYTE), VENDOR VARCHAR2(255 BYTE), SUB_SUPPLIER VARCHAR2(255 BYTE), SOURCE_NO VARCHAR2(40 BYTE), ATT_CKT_ID VARCHAR2(200 BYTE), LEC_ID VARCHAR2(200 BYTE), ICSC VARCHAR2(10 BYTE), STATE VARCHAR2(10 BYTE), PROJECT_ID VARCHAR2(100 BYTE), ACTION VARCHAR2(10 BYTE), SERVICE_SPEED VARCHAR2(10 BYTE), SERVICE_NAME VARCHAR(255 BYTE), INEFFECT_DATE DATE, EVENT_DATE DATE, DUE_DATE DATE, ACOST NUMBER ) Tab Type create or replace type test_COMP_REPORT_TAB_TYPE AS TABLE OF test_COMP_REPORT_ROW_TYPE Here is the Function which is using this type: create or replace FUNCTION test_comp_report_func ( start_dt_h IN VARCHAR2 DEFAULT NULL, end_dt_h IN VARCHAR2 DEFAULT NULL, year_h IN VARCHAR2 DEFAULT NULL ) RETURN test_comp_report_tab_type pipelined IS e_sql LONG; program_v VARCHAR2(10);
v_row test_comp_report_row_type:= test_comp_report_row_type(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL );
TYPE rectyp IS REF CURSOR; rrc_rectyp rectyp; TYPE recordvar IS RECORD ( PON VARCHAR2(25 BYTE), RPON VARCHAR2(25 BYTE), VENDOR VARCHAR2(255 BYTE), SUB_SUPPLIER VARCHAR2(255 BYTE), SOURCE_NO VARCHAR2(40 BYTE), ATT_CKT_ID VARCHAR2(200 BYTE), LEC_ID VARCHAR2(200 BYTE), ICSC VARCHAR2(10 BYTE), STATE VARCHAR2(10 BYTE), PROJECT_ID VARCHAR2(100 BYTE), ACTION VARCHAR2(10 BYTE), SERVICE_SPEED VARCHAR2(10 BYTE), SERVICE_NAME VARCHAR(255 BYTE), INEFFECT_DATE DATE, EVENT_DATE DATE, DUE_DATE DATE, ACOST NUMBER ); res_rec recordvar;
BEGIN
e_sql:= e_sql || 'SELECT PON, RPON, SUPPLIER_NAME VENDOR, SUB_SUPPLIER_NAME SUB_SUPPLIER, SOURCE_NO, CKR, LEC_ID, ICSC, ACTL_ST, ADW_ST STATE, PROJ_ID, ACTION, SERVICE SPEED, AFP, ACNA, SERVICE_NAME, IE_DT, MOVE_TO_INV_DT EVENTDAT, DDD_DT DUEDATE, EFF_BILL_DT, ACOST FROM UNIVERSE WHERE to_date(IE_DT) between to_date(nvl(''01/01/2000'', ''01/01/2000''), ''MM/DD/YYYY'') and to_date(nvl(''12/31/2009'', to_char(trunc(add_months(sysdate, 12),''year'')-1,''MM/DD/YYYY'')), ''MM/DD/YYYY'') AND PROGRAM = ''T45sONNET'' AND nvl(trim(ACOST_IND), ''NULL'') not in (''INVALID-2005'') ORDER BY ACTION';
dbms_output.put_line(e_sql); OPEN rrc_rectyp FOR e_sql; LOOP FETCH rrc_rectyp INTO res_rec; EXIT WHEN rrc_rectyp%NOTFOUND; v_row.PON:= res_rec.PON; v_row.RPON:= res_rec.RPON; v_row.VENDOR:= res_rec.VENDOR; v_row.SUB_SUPPLIER:= res_rec.SUB_SUPPLIER; v_row.SOURCE_NO:= res_rec.SOURCE_NO; v_row.ATT_CKT_ID:= res_rec.ATT_CKT_ID; v_row.LEC_ID:= res_rec.LEC_ID; v_row.ICSC:= res_rec.ICSC; v_row.STATE:= res_rec.STATE; v_row.PROJECT_ID:= res_rec.PROJECT_ID; v_row.ACTION:= res_rec.ACTION; v_row.SERVICE_SPEED:= res_rec.SERVICE_SPEED; v_row.SERVICE_NAME:= res_rec.SERVICE_NAME; v_row.INEFFECT_DATE:= res_rec.INEFFECT_DATE; v_row.EVENT_DATE:= res_rec.EVENT_DATE; v_row.DUE_DATE:= res_rec.DUE_DATE; v_row.ACOST:= res_rec.ACOST; pipe ROW(v_row); END LOOP; return;
end test_comp_report_func; I have tried to debug issue but still am not able to find my way out and would appreciate if SO Community can guide. | TITLE:
Oracle: Inconsistent Datatype Issue
QUESTION:
I am getting inconsistent datatype error message and I am not sure why. I need some guidance to figure this out. I am creating two types as: My universe table have following columns with column type: Column Name Data Type
PON VARCHAR2(25 BYTE) RPON VARCHAR2(25 BYTE) SUPPLIER_NAME VARCHAR2(255 BYTE) SUB_SUPPLIER_NAME VARCHAR2(255 BYTE) SOURCE_NO VARCHAR2(40 BYTE) CKR VARCHAR2(200 BYTE) LEC_ID VARCHAR2(200 BYTE) ICSC VARCHAR2(10 BYTE) ACTL_ST VARCHAR2(10 BYTE) ADW_ST VARCHAR2(10 BYTE) PROJ_ID VARCHAR2(100 BYTE) MOVE_TO_INV_DT DATE IE_DT DATE DDD_DT DATE EFF_BILL_DT DATE ACTION VARCHAR2(10 BYTE) SERVICE VARCHAR2(10 BYTE) AFP VARCHAR2(10 BYTE) ACNA VARCHAR2(10 BYTE) SERVICE_NAME VARCHAR2(255 BYTE) UPLOAD_DT DATE PROGRAM VARCHAR2(50 BYTE) INITIATIVE_ID NUMBER ACOST NUMBER ACOST_IND VARCHAR2(25 BYTE) MAPFILE VARCHAR2(100 BYTE) Row Type create or replace TYPE test_COMP_REPORT_ROW_TYPE AS OBJECT ( PON VARCHAR2(25 BYTE), RPON VARCHAR2(25 BYTE), VENDOR VARCHAR2(255 BYTE), SUB_SUPPLIER VARCHAR2(255 BYTE), SOURCE_NO VARCHAR2(40 BYTE), ATT_CKT_ID VARCHAR2(200 BYTE), LEC_ID VARCHAR2(200 BYTE), ICSC VARCHAR2(10 BYTE), STATE VARCHAR2(10 BYTE), PROJECT_ID VARCHAR2(100 BYTE), ACTION VARCHAR2(10 BYTE), SERVICE_SPEED VARCHAR2(10 BYTE), SERVICE_NAME VARCHAR(255 BYTE), INEFFECT_DATE DATE, EVENT_DATE DATE, DUE_DATE DATE, ACOST NUMBER ) Tab Type create or replace type test_COMP_REPORT_TAB_TYPE AS TABLE OF test_COMP_REPORT_ROW_TYPE Here is the Function which is using this type: create or replace FUNCTION test_comp_report_func ( start_dt_h IN VARCHAR2 DEFAULT NULL, end_dt_h IN VARCHAR2 DEFAULT NULL, year_h IN VARCHAR2 DEFAULT NULL ) RETURN test_comp_report_tab_type pipelined IS e_sql LONG; program_v VARCHAR2(10);
v_row test_comp_report_row_type:= test_comp_report_row_type(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL );
TYPE rectyp IS REF CURSOR; rrc_rectyp rectyp; TYPE recordvar IS RECORD ( PON VARCHAR2(25 BYTE), RPON VARCHAR2(25 BYTE), VENDOR VARCHAR2(255 BYTE), SUB_SUPPLIER VARCHAR2(255 BYTE), SOURCE_NO VARCHAR2(40 BYTE), ATT_CKT_ID VARCHAR2(200 BYTE), LEC_ID VARCHAR2(200 BYTE), ICSC VARCHAR2(10 BYTE), STATE VARCHAR2(10 BYTE), PROJECT_ID VARCHAR2(100 BYTE), ACTION VARCHAR2(10 BYTE), SERVICE_SPEED VARCHAR2(10 BYTE), SERVICE_NAME VARCHAR(255 BYTE), INEFFECT_DATE DATE, EVENT_DATE DATE, DUE_DATE DATE, ACOST NUMBER ); res_rec recordvar;
BEGIN
e_sql:= e_sql || 'SELECT PON, RPON, SUPPLIER_NAME VENDOR, SUB_SUPPLIER_NAME SUB_SUPPLIER, SOURCE_NO, CKR, LEC_ID, ICSC, ACTL_ST, ADW_ST STATE, PROJ_ID, ACTION, SERVICE SPEED, AFP, ACNA, SERVICE_NAME, IE_DT, MOVE_TO_INV_DT EVENTDAT, DDD_DT DUEDATE, EFF_BILL_DT, ACOST FROM UNIVERSE WHERE to_date(IE_DT) between to_date(nvl(''01/01/2000'', ''01/01/2000''), ''MM/DD/YYYY'') and to_date(nvl(''12/31/2009'', to_char(trunc(add_months(sysdate, 12),''year'')-1,''MM/DD/YYYY'')), ''MM/DD/YYYY'') AND PROGRAM = ''T45sONNET'' AND nvl(trim(ACOST_IND), ''NULL'') not in (''INVALID-2005'') ORDER BY ACTION';
dbms_output.put_line(e_sql); OPEN rrc_rectyp FOR e_sql; LOOP FETCH rrc_rectyp INTO res_rec; EXIT WHEN rrc_rectyp%NOTFOUND; v_row.PON:= res_rec.PON; v_row.RPON:= res_rec.RPON; v_row.VENDOR:= res_rec.VENDOR; v_row.SUB_SUPPLIER:= res_rec.SUB_SUPPLIER; v_row.SOURCE_NO:= res_rec.SOURCE_NO; v_row.ATT_CKT_ID:= res_rec.ATT_CKT_ID; v_row.LEC_ID:= res_rec.LEC_ID; v_row.ICSC:= res_rec.ICSC; v_row.STATE:= res_rec.STATE; v_row.PROJECT_ID:= res_rec.PROJECT_ID; v_row.ACTION:= res_rec.ACTION; v_row.SERVICE_SPEED:= res_rec.SERVICE_SPEED; v_row.SERVICE_NAME:= res_rec.SERVICE_NAME; v_row.INEFFECT_DATE:= res_rec.INEFFECT_DATE; v_row.EVENT_DATE:= res_rec.EVENT_DATE; v_row.DUE_DATE:= res_rec.DUE_DATE; v_row.ACOST:= res_rec.ACOST; pipe ROW(v_row); END LOOP; return;
end test_comp_report_func; I have tried to debug issue but still am not able to find my way out and would appreciate if SO Community can guide.
ANSWER:
I first wrote an answer trying to reproduce your error but you've changed your question quite a bit so I'm starting again from scratch. First a few remarks: By your own account you're quite new to PL/SQL yet you're using pretty advanced features: dynamic SQL, pipelined functions, SQL Objects. Let's try to begin with something simpler at first (I'll show you how you can work with static SQL, this would be sufficient 99.9% of the time). When you hit a problem you need to decompose your code to see what is working and what is not. That usually means simplifying your code until it is so simple it starts to work, then bring back the complex elements of your code one by one until you hit the problem again. When you provide a test case, try to make it as simple as possible:) It'll be easier for people to help you, but more importantly in most of the cases, building the test case will help you find the solution yourself since this will force you to decompose your complex code (see previous point). My rule of thumb (FWIW) is that code that is displayed with a scroll bar (either horizontal or vertical) in SO is too big for a test case and needs to be trimmed if possible. I ran your code and got the ORA-00932 on the fetch line. When I replace the SQL with static SQL the error is more explicit: SQL> CREATE OR REPLACE FUNCTION test_comp_report_func 2 RETURN test_comp_report_tab_type 3 PIPELINED IS 4 TYPE recordvar IS RECORD( 5 PON VARCHAR2(25 BYTE), (...snip...) 21 ACOST NUMBER); 22 res_rec recordvar; 23 v_row test_COMP_REPORT_ROW_TYPE; 24 CURSOR rrc_rectyp IS 25 SELECT PON, (...snip...) 45 ACOST 46 FROM UNIVERSE; 48 BEGIN 49 OPEN rrc_rectyp; 50 LOOP 51 FETCH rrc_rectyp 52 INTO res_rec; 54 EXIT WHEN rrc_rectyp%NOTFOUND; 55 /*...*/ 56 PIPE ROW(v_row); 57 END LOOP; 58 RETURN; 59 END test_comp_report_func; 60 /
Warning: Function created with compilation errors. LINE/COL ERROR -------- ----------------------------------------------------------------- 51/7 PL/SQL: SQL Statement ignored 52/15 PLS-00386: type mismatch found at 'RES_REC' between FETCH cursor and INTO variables Here the problem comes from the fact that your select statement doesn't have the same number of columns as the number of fields in your record. You can use %rowcount to prevent this: CREATE OR REPLACE FUNCTION test_comp_report_func RETURN test_comp_report_tab_type PIPELINED IS v_row test_COMP_REPORT_ROW_TYPE; CURSOR rrc_rectyp IS SELECT PON, RPON, SUPPLIER_NAME VENDOR, SUB_SUPPLIER_NAME SUB_SUPPLIER, SOURCE_NO, CKR, LEC_ID, ICSC, ACTL_ST, ADW_ST STATE, PROJ_ID, ACTION, SERVICE SPEED, AFP, ACNA, SERVICE_NAME, IE_DT, MOVE_TO_INV_DT EVENTDAT, DDD_DT DUEDATE, EFF_BILL_DT, ACOST FROM UNIVERSE; res_rec rrc_rectyp%ROWTYPE; BEGIN OPEN rrc_rectyp; LOOP FETCH rrc_rectyp INTO res_rec; EXIT WHEN rrc_rectyp%NOTFOUND; v_row.pon:= res_rec.pon; /*...*/ PIPE ROW(v_row); END LOOP; RETURN; END test_comp_report_func; You can even fetch the SQL object directly (with an implicit cursor): CREATE OR REPLACE FUNCTION test_comp_report_func RETURN test_comp_report_tab_type PIPELINED IS BEGIN FOR res_rec IN (SELECT test_comp_report_row_type(PON, RPON, SUPPLIER_NAME, SUB_SUPPLIER_NAME,SOURCE_NO, CKR, LEC_ID, ICSC, ACTL_ST, PROJ_ID, ACTION, SERVICE, SERVICE_NAME, IE_DT, DDD_DT, EFF_BILL_DT, ACOST)my_object FROM UNIVERSE) LOOP PIPE ROW(res_rec.my_object); END LOOP; RETURN; END test_comp_report_func; | [
"oracle",
"plsql",
"ora-00932",
"ora-06512"
] | 1 | 4 | 4,201 | 2 | 0 | 2011-06-10T15:16:35.890000 | 2011-06-10T16:13:01.957000 |
6,308,393 | 6,308,418 | How do I prefix a String to each element in an array of Strings? | I would like to know if there is, in Java, a function that can prefix a defined String to the beginning of every String of an array of Strings. For example, my_function({"apple", "orange", "ant"}, "eat an ") would return {"eat an apple", "eat an orange", "eat an ant"} Currently, I coded this function, but I wonder if it already exists. | Nope. Since it should be about a three-line function, you're probably better of just sticking with the one you coded. Update With Java 8, the syntax is simple enough I'm not even sure if it's worth creating a function for: List eatFoods = foodNames.stream().map(s -> "eat an " + s).collect(Collectors.toList()); | How do I prefix a String to each element in an array of Strings? I would like to know if there is, in Java, a function that can prefix a defined String to the beginning of every String of an array of Strings. For example, my_function({"apple", "orange", "ant"}, "eat an ") would return {"eat an apple", "eat an orange", "eat an ant"} Currently, I coded this function, but I wonder if it already exists. | TITLE:
How do I prefix a String to each element in an array of Strings?
QUESTION:
I would like to know if there is, in Java, a function that can prefix a defined String to the beginning of every String of an array of Strings. For example, my_function({"apple", "orange", "ant"}, "eat an ") would return {"eat an apple", "eat an orange", "eat an ant"} Currently, I coded this function, but I wonder if it already exists.
ANSWER:
Nope. Since it should be about a three-line function, you're probably better of just sticking with the one you coded. Update With Java 8, the syntax is simple enough I'm not even sure if it's worth creating a function for: List eatFoods = foodNames.stream().map(s -> "eat an " + s).collect(Collectors.toList()); | [
"java",
"arrays",
"string",
"append"
] | 5 | 14 | 23,468 | 4 | 0 | 2011-06-10T15:16:39.403000 | 2011-06-10T15:18:53.073000 |
6,308,404 | 6,308,648 | Can't make a 301 redirect to home when parameters | Hi guys I need to redirect all addresses that have the promoG601.aspx in the url to the home page so I created the following rule RewriteRule promoG601.aspx(.*) http://% {HTTP_HOST}/ [L,R=301] If I send promoG601.aspx it takes me to www.domain.com correctly but if I do promoG601.aspx?tid=b then it takes me to www.domain.com/?tid=b Can you please tell me what am I missing here, thanks a lot! | The only thing I found that worked was to add a? to the end: RewriteRule promoG601.aspx(.*) http://%{HTTP_HOST}/? [L,R=301] Worked for me but I would have thought there would be a better way of doing it. Just found that the querystring is added by default: use the? to discard the querystring which is otherwise preserved by default | Can't make a 301 redirect to home when parameters Hi guys I need to redirect all addresses that have the promoG601.aspx in the url to the home page so I created the following rule RewriteRule promoG601.aspx(.*) http://% {HTTP_HOST}/ [L,R=301] If I send promoG601.aspx it takes me to www.domain.com correctly but if I do promoG601.aspx?tid=b then it takes me to www.domain.com/?tid=b Can you please tell me what am I missing here, thanks a lot! | TITLE:
Can't make a 301 redirect to home when parameters
QUESTION:
Hi guys I need to redirect all addresses that have the promoG601.aspx in the url to the home page so I created the following rule RewriteRule promoG601.aspx(.*) http://% {HTTP_HOST}/ [L,R=301] If I send promoG601.aspx it takes me to www.domain.com correctly but if I do promoG601.aspx?tid=b then it takes me to www.domain.com/?tid=b Can you please tell me what am I missing here, thanks a lot!
ANSWER:
The only thing I found that worked was to add a? to the end: RewriteRule promoG601.aspx(.*) http://%{HTTP_HOST}/? [L,R=301] Worked for me but I would have thought there would be a better way of doing it. Just found that the querystring is added by default: use the? to discard the querystring which is otherwise preserved by default | [
".htaccess"
] | 0 | 1 | 106 | 1 | 0 | 2011-06-10T15:17:29.253000 | 2011-06-10T15:33:52.807000 |
6,308,408 | 6,308,610 | Why does delayed_jobs loop when it errors? | I have had several occassions where delayed_jobs will be taking care of delivering 4 thousand emails, and if something errors in those emails ( for instance, if there's a nil a call ), then it will restart the entire process and attempt to send yet another 4000 emails. This will go on indefinately until I manually kill -9 the entire process. It's happened so many times to me over the past few years in different applications, I'm curious if it has happened to anyone else. And what they did to overcome it. | A delayed job is usually just a method that gets executed by a worker in a background process as opposed to during the main thread of your application (request lifecycle for a Rails app). If you read the documentation for delayed_job under "Gory Details" it states: On failure, the job is scheduled again in 5 seconds + N ** 4, where N is the number of retries. The default Worker.max_attempts is 25. After this, the job either deleted (default), or left in the database with “failed_at” set. With the default of 25 attempts, the last retry will be 20 days later, with the last interval being almost 100 hours. It sounds like what you are describing is the way delayed_jobs was intended to function - if a job to send 4,000 emails fails after sending 3,000 of them, it just starts over again. You will probably need to keep track of what has and hasn't been sent, so your job can loop over "unsent" emails (or whatever information is appropriate for your background process). That way when you send 3,000 emails, they get marked as "sent" and if your job fails, it will start over by loading the remaining 1,000 "unsent" emails and attempting to send them. If you really don't want jobs to retry themselves on failure, you can add the following code to your project: # config/initializers/delayed_job_config.rb Delayed::Worker.max_attempts = 1 | Why does delayed_jobs loop when it errors? I have had several occassions where delayed_jobs will be taking care of delivering 4 thousand emails, and if something errors in those emails ( for instance, if there's a nil a call ), then it will restart the entire process and attempt to send yet another 4000 emails. This will go on indefinately until I manually kill -9 the entire process. It's happened so many times to me over the past few years in different applications, I'm curious if it has happened to anyone else. And what they did to overcome it. | TITLE:
Why does delayed_jobs loop when it errors?
QUESTION:
I have had several occassions where delayed_jobs will be taking care of delivering 4 thousand emails, and if something errors in those emails ( for instance, if there's a nil a call ), then it will restart the entire process and attempt to send yet another 4000 emails. This will go on indefinately until I manually kill -9 the entire process. It's happened so many times to me over the past few years in different applications, I'm curious if it has happened to anyone else. And what they did to overcome it.
ANSWER:
A delayed job is usually just a method that gets executed by a worker in a background process as opposed to during the main thread of your application (request lifecycle for a Rails app). If you read the documentation for delayed_job under "Gory Details" it states: On failure, the job is scheduled again in 5 seconds + N ** 4, where N is the number of retries. The default Worker.max_attempts is 25. After this, the job either deleted (default), or left in the database with “failed_at” set. With the default of 25 attempts, the last retry will be 20 days later, with the last interval being almost 100 hours. It sounds like what you are describing is the way delayed_jobs was intended to function - if a job to send 4,000 emails fails after sending 3,000 of them, it just starts over again. You will probably need to keep track of what has and hasn't been sent, so your job can loop over "unsent" emails (or whatever information is appropriate for your background process). That way when you send 3,000 emails, they get marked as "sent" and if your job fails, it will start over by loading the remaining 1,000 "unsent" emails and attempting to send them. If you really don't want jobs to retry themselves on failure, you can add the following code to your project: # config/initializers/delayed_job_config.rb Delayed::Worker.max_attempts = 1 | [
"ruby-on-rails",
"delayed-job"
] | 5 | 11 | 1,850 | 2 | 0 | 2011-06-10T15:17:54.207000 | 2011-06-10T15:31:33.300000 |
6,308,413 | 6,309,208 | Create TableRows dynamically | I'm trying to create "cells" dynamically, they need an image and 3 TextViews. I chose to use the TableLayout and my cells are TableRows. I've tried this: http://www.warriorpoint.com/blog/2009/07/01/android-creating-tablerow-rows-inside-a-tablelayout-programatically/ But cells do not appear (yes, I changed the color of the text:-)) Does anyone have any idea what might be happening? And, someone suggests something better than TableRow? | You can use a WebView and then your table can be created/manipulated using HTML/js (there are excellent jQuery plugins). I've tried a couple of times using TableLayout and then I've switched to the WebView/HTML solution. It really depends on the design of your app. | Create TableRows dynamically I'm trying to create "cells" dynamically, they need an image and 3 TextViews. I chose to use the TableLayout and my cells are TableRows. I've tried this: http://www.warriorpoint.com/blog/2009/07/01/android-creating-tablerow-rows-inside-a-tablelayout-programatically/ But cells do not appear (yes, I changed the color of the text:-)) Does anyone have any idea what might be happening? And, someone suggests something better than TableRow? | TITLE:
Create TableRows dynamically
QUESTION:
I'm trying to create "cells" dynamically, they need an image and 3 TextViews. I chose to use the TableLayout and my cells are TableRows. I've tried this: http://www.warriorpoint.com/blog/2009/07/01/android-creating-tablerow-rows-inside-a-tablelayout-programatically/ But cells do not appear (yes, I changed the color of the text:-)) Does anyone have any idea what might be happening? And, someone suggests something better than TableRow?
ANSWER:
You can use a WebView and then your table can be created/manipulated using HTML/js (there are excellent jQuery plugins). I've tried a couple of times using TableLayout and then I've switched to the WebView/HTML solution. It really depends on the design of your app. | [
"android",
"layout",
"dynamic",
"mobile",
"tablerow"
] | 0 | 0 | 334 | 1 | 0 | 2011-06-10T15:18:16.410000 | 2011-06-10T16:17:43.160000 |
6,308,414 | 6,308,752 | Can't change property value in IE using JS | I've a little snippet code that doesn't work in IE only, tested in FF, Safari, Chrome, Rockmelt and all working. JS: document.forma.score.value = 12; html: | You may have encountered a well known name/id mixup problem. Make sure that you have unique id's and that no id attribute value in your document is equal to name attribute values in that document. On the other hand, I've jsfiddled a small test. That worked in IE7-9. If it's IE6: that in this day and age should be an obsolete browser. If it's about another IE version, then look for other elements with name or id 'score' in your document. | Can't change property value in IE using JS I've a little snippet code that doesn't work in IE only, tested in FF, Safari, Chrome, Rockmelt and all working. JS: document.forma.score.value = 12; html: | TITLE:
Can't change property value in IE using JS
QUESTION:
I've a little snippet code that doesn't work in IE only, tested in FF, Safari, Chrome, Rockmelt and all working. JS: document.forma.score.value = 12; html:
ANSWER:
You may have encountered a well known name/id mixup problem. Make sure that you have unique id's and that no id attribute value in your document is equal to name attribute values in that document. On the other hand, I've jsfiddled a small test. That worked in IE7-9. If it's IE6: that in this day and age should be an obsolete browser. If it's about another IE version, then look for other elements with name or id 'score' in your document. | [
"javascript",
"html",
"internet-explorer"
] | 0 | 1 | 291 | 2 | 0 | 2011-06-10T15:18:20.870000 | 2011-06-10T15:41:45.763000 |
6,308,419 | 6,308,656 | How can I commit from diff machines? | Let's imagine this scenario Running Dropbox in my Windows Work PC, my Windows Home PC and my Mac laptop, and all have different local folders and Git 1.7.4 is installed in all enumerating them: Machine 1: Windows Work PC Machine 2: Windows Home PC Machine 3: Mac Laptop I create a new folder in Dropbox and let's assume I took Machine 1 and the ending path is D:\DropBox\Projects\My AspNet Mvc WebApp\ so I do git init git add. git commit -m "initial commit" and also run git remote to hook up with the cloud repository and do my git push. My question is simple How can I now commit changes made in other machines? Can I do git add. git commit -m "My changes" git push could master from other machines? Note: I'm using AppHarbour as my cloud service Note 2: Dropbox don't replicate.git folders:( | You said: git add. git push could master You'll need a commit in between those (and I'm assuming your remote is named "could"), but yeah, in principle, what you've got there is a git repository that's kept in sync via dropbox on all the machines that share that dropbox directory. In principle you could go from one machine to the other and have the "same" repository on both of them. Now, I've heard a few things about dropbox hosing.git directories--something about permissions, I think. Also if you're making and committing different changes at the same time from different machines, obviously dropbox is going to end up with conflicting versions that it may or may not resolve nicely. But those caviats aside, yes this should work, and from what I'm reading people are having some success sharing git repos with working directories inside shared dropboxes. | How can I commit from diff machines? Let's imagine this scenario Running Dropbox in my Windows Work PC, my Windows Home PC and my Mac laptop, and all have different local folders and Git 1.7.4 is installed in all enumerating them: Machine 1: Windows Work PC Machine 2: Windows Home PC Machine 3: Mac Laptop I create a new folder in Dropbox and let's assume I took Machine 1 and the ending path is D:\DropBox\Projects\My AspNet Mvc WebApp\ so I do git init git add. git commit -m "initial commit" and also run git remote to hook up with the cloud repository and do my git push. My question is simple How can I now commit changes made in other machines? Can I do git add. git commit -m "My changes" git push could master from other machines? Note: I'm using AppHarbour as my cloud service Note 2: Dropbox don't replicate.git folders:( | TITLE:
How can I commit from diff machines?
QUESTION:
Let's imagine this scenario Running Dropbox in my Windows Work PC, my Windows Home PC and my Mac laptop, and all have different local folders and Git 1.7.4 is installed in all enumerating them: Machine 1: Windows Work PC Machine 2: Windows Home PC Machine 3: Mac Laptop I create a new folder in Dropbox and let's assume I took Machine 1 and the ending path is D:\DropBox\Projects\My AspNet Mvc WebApp\ so I do git init git add. git commit -m "initial commit" and also run git remote to hook up with the cloud repository and do my git push. My question is simple How can I now commit changes made in other machines? Can I do git add. git commit -m "My changes" git push could master from other machines? Note: I'm using AppHarbour as my cloud service Note 2: Dropbox don't replicate.git folders:(
ANSWER:
You said: git add. git push could master You'll need a commit in between those (and I'm assuming your remote is named "could"), but yeah, in principle, what you've got there is a git repository that's kept in sync via dropbox on all the machines that share that dropbox directory. In principle you could go from one machine to the other and have the "same" repository on both of them. Now, I've heard a few things about dropbox hosing.git directories--something about permissions, I think. Also if you're making and committing different changes at the same time from different machines, obviously dropbox is going to end up with conflicting versions that it may or may not resolve nicely. But those caviats aside, yes this should work, and from what I'm reading people are having some success sharing git repos with working directories inside shared dropboxes. | [
"git",
"dropbox"
] | 2 | 1 | 88 | 2 | 0 | 2011-06-10T15:19:05.750000 | 2011-06-10T15:34:10.617000 |
6,308,425 | 6,308,556 | iOS 5 Best Practice (Release/retain?) | As a beginning iPhone programmer, what is the best practice for writing apps to be used either with iOS 5 or older versions? Specifically, should I continue using the release/retain of data, or should I ignore that? Does it matter? | It's up to you. You can write apps using ARC (Automatic Reference Counting), and Xcode will write "glue code" to allow your ARC enabled apps to run on iOS 4, no modifications required. However, certain things wont work, and most noticeably many libraries you might wish to use will (sometimes) throw up innumerable errors and you will be unable to use them until the developers release an update which is compatible with ARC. Edit: I recently discovered that you can turn off ARC on a per-file basis. See pixelfreak 's answer. So, my advice still stands, but now the 3rd-party libraries shouldn't need to be updated to work with ARC. Here's what Apple says about opting out of ARC for specific files: When you migrate a project to use ARC, the -fobjc-arc compiler flag is set as the default for all Objective-C source files. You can disable ARC for a specific class using the -fno-objc-arc compiler flag for that class. In Xcode, in the target Build Phases tab, open the Compile Sources group to reveal the source file list. Double-click the file for which you want to set the flag, enter -fno-objc-arc in the pop-up panel, then click Done. See the full transition guide here. | iOS 5 Best Practice (Release/retain?) As a beginning iPhone programmer, what is the best practice for writing apps to be used either with iOS 5 or older versions? Specifically, should I continue using the release/retain of data, or should I ignore that? Does it matter? | TITLE:
iOS 5 Best Practice (Release/retain?)
QUESTION:
As a beginning iPhone programmer, what is the best practice for writing apps to be used either with iOS 5 or older versions? Specifically, should I continue using the release/retain of data, or should I ignore that? Does it matter?
ANSWER:
It's up to you. You can write apps using ARC (Automatic Reference Counting), and Xcode will write "glue code" to allow your ARC enabled apps to run on iOS 4, no modifications required. However, certain things wont work, and most noticeably many libraries you might wish to use will (sometimes) throw up innumerable errors and you will be unable to use them until the developers release an update which is compatible with ARC. Edit: I recently discovered that you can turn off ARC on a per-file basis. See pixelfreak 's answer. So, my advice still stands, but now the 3rd-party libraries shouldn't need to be updated to work with ARC. Here's what Apple says about opting out of ARC for specific files: When you migrate a project to use ARC, the -fobjc-arc compiler flag is set as the default for all Objective-C source files. You can disable ARC for a specific class using the -fno-objc-arc compiler flag for that class. In Xcode, in the target Build Phases tab, open the Compile Sources group to reveal the source file list. Double-click the file for which you want to set the flag, enter -fno-objc-arc in the pop-up panel, then click Done. See the full transition guide here. | [
"iphone",
"ios",
"ios5",
"memory-management",
"automatic-ref-counting"
] | 109 | 98 | 57,641 | 7 | 0 | 2011-06-10T15:19:16.380000 | 2011-06-10T15:28:14.693000 |
6,308,428 | 6,309,125 | Routing Error No route matches "/users/new" | My name is Juan I'm from Spain and this is my first post. Thank you. I following the Ruby on Rails tutorial of Michael Hartl in the chapter 8. My problem is that to create the form for signup users in this chapter. He say that action go to "action=/users" but my code I can see it with the firebug the action go to: action="/users/new". Then when I go click to sign up button the action go to action="/users/new" and the next error: Routing Error No route matches "/users/new" I have not errors in rspec spec/ or autotest its all OK!!. Can you help me for this problem? The helper used its "form_for" Thank you very much! | Updated Ok. I've checked the code of the tutorial. The source of the problem is the object you pass to form_for. Please, check if your users_controller's new action has this line: @user = User.new This line creates a new AR object, but doesn't save it to the DB. So when you pass it to form_for, Rails knows it should generate a form for create action (POST /users). https://github.com/railstutorial/sample_app Here is the full source code of the tutorial application. You might find it useful. It gets updated sometimes to fix bugs and typos. And one last thing. Have you tried restarting your web-server? | Routing Error No route matches "/users/new" My name is Juan I'm from Spain and this is my first post. Thank you. I following the Ruby on Rails tutorial of Michael Hartl in the chapter 8. My problem is that to create the form for signup users in this chapter. He say that action go to "action=/users" but my code I can see it with the firebug the action go to: action="/users/new". Then when I go click to sign up button the action go to action="/users/new" and the next error: Routing Error No route matches "/users/new" I have not errors in rspec spec/ or autotest its all OK!!. Can you help me for this problem? The helper used its "form_for" Thank you very much! | TITLE:
Routing Error No route matches "/users/new"
QUESTION:
My name is Juan I'm from Spain and this is my first post. Thank you. I following the Ruby on Rails tutorial of Michael Hartl in the chapter 8. My problem is that to create the form for signup users in this chapter. He say that action go to "action=/users" but my code I can see it with the firebug the action go to: action="/users/new". Then when I go click to sign up button the action go to action="/users/new" and the next error: Routing Error No route matches "/users/new" I have not errors in rspec spec/ or autotest its all OK!!. Can you help me for this problem? The helper used its "form_for" Thank you very much!
ANSWER:
Updated Ok. I've checked the code of the tutorial. The source of the problem is the object you pass to form_for. Please, check if your users_controller's new action has this line: @user = User.new This line creates a new AR object, but doesn't save it to the DB. So when you pass it to form_for, Rails knows it should generate a form for create action (POST /users). https://github.com/railstutorial/sample_app Here is the full source code of the tutorial application. You might find it useful. It gets updated sometimes to fix bugs and typos. And one last thing. Have you tried restarting your web-server? | [
"ruby-on-rails"
] | 1 | 3 | 3,855 | 2 | 0 | 2011-06-10T15:19:30.077000 | 2011-06-10T16:11:07.917000 |
6,308,431 | 6,308,601 | Problem with two NSDate | I have a problem with this code: NSDate *today = [[NSDate alloc] init]; if (dateOne == today) { dataLabel.textColor = [UIColor redColor]; NSLog(@"inside if");} NSLog(@"today:%@", oggi); NSLog(@"dateOne:%@", dateOne); the result of console is 2011-06-10 17:19:00.170 Project[678:707] today:2011-06-10 15:19:00 +0000 2011-06-10 17:19:00.174 Project[678:707] dateOne:2011-06-10 15:19:00 +0000 I also try "isEqualToDate" but the code don't entry inside "if" | I understand you are trying to determine if a given NSDate is today. To do this you don't have to take in consideration hours, minutes, etc. in your comparison. How about this: NSCalendar *calendar = [NSCalendar currentCalendar]; NSDateComponents *components = [calendar components:(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:[NSDate date]]; NSDate *today = [calendar dateFromComponents:components]; components = [calendar components:(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:otherDate]; NSDate *dateOne = [calendar dateFromComponents:components];
if([today isEqualToDate:dateOne]) {... } The method isEqualToDate: won't do this job because it checks whether a given date is exactly equal the receiver (with sub-second precision). The == operator is not appropriate for this either because it compares the pointers to the objects, it checks whether the pointers point to the same memory location. | Problem with two NSDate I have a problem with this code: NSDate *today = [[NSDate alloc] init]; if (dateOne == today) { dataLabel.textColor = [UIColor redColor]; NSLog(@"inside if");} NSLog(@"today:%@", oggi); NSLog(@"dateOne:%@", dateOne); the result of console is 2011-06-10 17:19:00.170 Project[678:707] today:2011-06-10 15:19:00 +0000 2011-06-10 17:19:00.174 Project[678:707] dateOne:2011-06-10 15:19:00 +0000 I also try "isEqualToDate" but the code don't entry inside "if" | TITLE:
Problem with two NSDate
QUESTION:
I have a problem with this code: NSDate *today = [[NSDate alloc] init]; if (dateOne == today) { dataLabel.textColor = [UIColor redColor]; NSLog(@"inside if");} NSLog(@"today:%@", oggi); NSLog(@"dateOne:%@", dateOne); the result of console is 2011-06-10 17:19:00.170 Project[678:707] today:2011-06-10 15:19:00 +0000 2011-06-10 17:19:00.174 Project[678:707] dateOne:2011-06-10 15:19:00 +0000 I also try "isEqualToDate" but the code don't entry inside "if"
ANSWER:
I understand you are trying to determine if a given NSDate is today. To do this you don't have to take in consideration hours, minutes, etc. in your comparison. How about this: NSCalendar *calendar = [NSCalendar currentCalendar]; NSDateComponents *components = [calendar components:(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:[NSDate date]]; NSDate *today = [calendar dateFromComponents:components]; components = [calendar components:(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:otherDate]; NSDate *dateOne = [calendar dateFromComponents:components];
if([today isEqualToDate:dateOne]) {... } The method isEqualToDate: won't do this job because it checks whether a given date is exactly equal the receiver (with sub-second precision). The == operator is not appropriate for this either because it compares the pointers to the objects, it checks whether the pointers point to the same memory location. | [
"objective-c",
"xcode",
"if-statement",
"io",
"nsdate"
] | 2 | 9 | 900 | 2 | 0 | 2011-06-10T15:19:41.420000 | 2011-06-10T15:31:03.567000 |
6,308,435 | 6,308,703 | Enclosing external jQuery script | I have an external JavaScript file that will be used on pages with lots of other scripts. My script involves a lot of jQuery that listens for events, and by design, I have many global vars declared. I've been reading best practice articles, and a lot is said about 'polluting the global namespace' and inadvertent script interaction. What's the best way to enclose (encapsulate?) my JavaScript file so that: I can still access some of the variables outside of the enclosure The jQuery event listeners will function properly I'm not at liberty to disclose the code, so even general responses are appreciated. Additionally, any other tips on making scripts less vulnerable to other scripts on the page are welcome. I've found enclosure styles for regular JavaScript, but does the use of jQuery complicate this? | Generally what this boils down to is encapsulating your objects into a "namespace". I use quotes there because the term is not an official semantic in JavaScript, but rather one that is achieved through basic object encapsulation. There are several ways to do this, and it ultimately comes down to personal preference. One approach is to just use a basic JS object, and keep everything in it. The name of the object should be semantic and give the object some meaning, but otherwise it's purpose is to just wrap your own code and keep it out of the global namespace. var SomeName = { alpha: 1, beta: {a: 1, b: 2}, gamma: function(){ SomeName.alpha += 1; } } In this case, only SomeName is in the global namespace. The one downside to this approach is that everything inside the namespace is public, and you have to use the full namespace to reference an object, instead of using 'this' - e.g. in SomeName.gamma we have to use SomeName.alpha to reference the contents of alpha. Another approach is to make your namespace a function with properties. The nice feature of this approach is you can create 'private' variable through closures. It also gives you access to closured functions and variables without full namespace referencing. var SomeName = (function(){ var self = this; var privateVar = 1; var privateFunc = function() { };
this.publicVar = 2; this.publicFunc = function(){ console.log(privateVar); console.log(this.publicVar); // if called via SomeName.publicFunc
setTimeout(function(){ console.log(self.publicVar); console.log(privateVar); }, 1000); }; }(); The other bonus of this approach is it lets you protect the global variables you want to use. For example, if you use jQuery, AND another library that creates a $ variable, you can always insure you are referencing jQuery when using $ by this approach: var SomeName = (function($){ console.log($('div')); })(jQuery); | Enclosing external jQuery script I have an external JavaScript file that will be used on pages with lots of other scripts. My script involves a lot of jQuery that listens for events, and by design, I have many global vars declared. I've been reading best practice articles, and a lot is said about 'polluting the global namespace' and inadvertent script interaction. What's the best way to enclose (encapsulate?) my JavaScript file so that: I can still access some of the variables outside of the enclosure The jQuery event listeners will function properly I'm not at liberty to disclose the code, so even general responses are appreciated. Additionally, any other tips on making scripts less vulnerable to other scripts on the page are welcome. I've found enclosure styles for regular JavaScript, but does the use of jQuery complicate this? | TITLE:
Enclosing external jQuery script
QUESTION:
I have an external JavaScript file that will be used on pages with lots of other scripts. My script involves a lot of jQuery that listens for events, and by design, I have many global vars declared. I've been reading best practice articles, and a lot is said about 'polluting the global namespace' and inadvertent script interaction. What's the best way to enclose (encapsulate?) my JavaScript file so that: I can still access some of the variables outside of the enclosure The jQuery event listeners will function properly I'm not at liberty to disclose the code, so even general responses are appreciated. Additionally, any other tips on making scripts less vulnerable to other scripts on the page are welcome. I've found enclosure styles for regular JavaScript, but does the use of jQuery complicate this?
ANSWER:
Generally what this boils down to is encapsulating your objects into a "namespace". I use quotes there because the term is not an official semantic in JavaScript, but rather one that is achieved through basic object encapsulation. There are several ways to do this, and it ultimately comes down to personal preference. One approach is to just use a basic JS object, and keep everything in it. The name of the object should be semantic and give the object some meaning, but otherwise it's purpose is to just wrap your own code and keep it out of the global namespace. var SomeName = { alpha: 1, beta: {a: 1, b: 2}, gamma: function(){ SomeName.alpha += 1; } } In this case, only SomeName is in the global namespace. The one downside to this approach is that everything inside the namespace is public, and you have to use the full namespace to reference an object, instead of using 'this' - e.g. in SomeName.gamma we have to use SomeName.alpha to reference the contents of alpha. Another approach is to make your namespace a function with properties. The nice feature of this approach is you can create 'private' variable through closures. It also gives you access to closured functions and variables without full namespace referencing. var SomeName = (function(){ var self = this; var privateVar = 1; var privateFunc = function() { };
this.publicVar = 2; this.publicFunc = function(){ console.log(privateVar); console.log(this.publicVar); // if called via SomeName.publicFunc
setTimeout(function(){ console.log(self.publicVar); console.log(privateVar); }, 1000); }; }(); The other bonus of this approach is it lets you protect the global variables you want to use. For example, if you use jQuery, AND another library that creates a $ variable, you can always insure you are referencing jQuery when using $ by this approach: var SomeName = (function($){ console.log($('div')); })(jQuery); | [
"javascript",
"jquery",
"reliability",
"side-effects"
] | 3 | 1 | 3,232 | 6 | 0 | 2011-06-10T15:19:50.617000 | 2011-06-10T15:37:30.403000 |
6,308,438 | 6,309,461 | comments amongst parameters in BASH | I want to include command-parameters-inline comments, e.g.: sed -i.bak -r \ # comment 1 -e 'sed_commands' \ # comment 2 -e 'sed_commands' \ # comment 3 -e 'sed_commands' \ /path/to/file The above code doesn't work. Is there a different way for embedding comments in the parameters line? | If you really want comment arguments, can try this: ls $( echo '-l' #for the long list echo '-F' #show file types too echo '-t' #sort by time ) This will be equivalent to: ls -l -F -t echo is an shell built-in, so does not execute external commands, so it is fast enough. But, it is crazy anyway. or makeargs() { while read line; do echo ${line//#*/}; done } ls $(makeargs < | comments amongst parameters in BASH I want to include command-parameters-inline comments, e.g.: sed -i.bak -r \ # comment 1 -e 'sed_commands' \ # comment 2 -e 'sed_commands' \ # comment 3 -e 'sed_commands' \ /path/to/file The above code doesn't work. Is there a different way for embedding comments in the parameters line? | TITLE:
comments amongst parameters in BASH
QUESTION:
I want to include command-parameters-inline comments, e.g.: sed -i.bak -r \ # comment 1 -e 'sed_commands' \ # comment 2 -e 'sed_commands' \ # comment 3 -e 'sed_commands' \ /path/to/file The above code doesn't work. Is there a different way for embedding comments in the parameters line?
ANSWER:
If you really want comment arguments, can try this: ls $( echo '-l' #for the long list echo '-F' #show file types too echo '-t' #sort by time ) This will be equivalent to: ls -l -F -t echo is an shell built-in, so does not execute external commands, so it is fast enough. But, it is crazy anyway. or makeargs() { while read line; do echo ${line//#*/}; done } ls $(makeargs < | [
"bash",
"comments"
] | 7 | 11 | 3,288 | 7 | 0 | 2011-06-10T15:19:58.893000 | 2011-06-10T16:37:39.447000 |
6,308,441 | 6,308,630 | Javascript onbeforeunload close browser window | I have this tiny script for now that checks if any change is made on the form. If there is a change then I set a flag to 'Y'. I call this function on onBeforeunload="changeConfirm()" places in the body tag. I know I can't stop the user from closing down the window, but how do I make this scenario work where he made a change -> decide to close the window -> Script alerted him -> User clicks cancel (Now I need to bring him back to the screen instead of closing browser. | Try this: function confirmChanges() { if(Flag == 'Y') { if(confirm('Changes made. Dont want to save?')){ return false; }else{ return true; } } else { alert("No changes were made " + Flag); } } | Javascript onbeforeunload close browser window I have this tiny script for now that checks if any change is made on the form. If there is a change then I set a flag to 'Y'. I call this function on onBeforeunload="changeConfirm()" places in the body tag. I know I can't stop the user from closing down the window, but how do I make this scenario work where he made a change -> decide to close the window -> Script alerted him -> User clicks cancel (Now I need to bring him back to the screen instead of closing browser. | TITLE:
Javascript onbeforeunload close browser window
QUESTION:
I have this tiny script for now that checks if any change is made on the form. If there is a change then I set a flag to 'Y'. I call this function on onBeforeunload="changeConfirm()" places in the body tag. I know I can't stop the user from closing down the window, but how do I make this scenario work where he made a change -> decide to close the window -> Script alerted him -> User clicks cancel (Now I need to bring him back to the screen instead of closing browser.
ANSWER:
Try this: function confirmChanges() { if(Flag == 'Y') { if(confirm('Changes made. Dont want to save?')){ return false; }else{ return true; } } else { alert("No changes were made " + Flag); } } | [
"javascript",
"jsp"
] | 0 | 1 | 2,315 | 2 | 0 | 2011-06-10T15:20:13.613000 | 2011-06-10T15:32:42.877000 |
6,308,443 | 6,309,474 | Parsing HTML - is regex the only option in this case? | A user will supply HTML, it may be valid or invalid (malformed). I need to be able to determine such things as: Is there a style tag in the body Is there a div that has a style attribute that makes use of width or background-image. I have tried using the DOMDocument class but it can only do 1 and not 2 with xPath. I have also tried simple_html_dom and that can only do 1 but not 2. Do you think its a good idea that I just use regular expressions or is there something that I haven't thought of? | XPath can do both (1) and (2): To test if there's a style tag in the body: //body//style To test if there's a div with a style attribute using width or background-image: //div[contains(@style,'width:') or contains(@style,'background-image:')] And, as you were curious about in your comments, seeing if a style tag contains a:hover or font-size: //style[contains(text(),'a:hover') or contains(text(),'font-size:')] | Parsing HTML - is regex the only option in this case? A user will supply HTML, it may be valid or invalid (malformed). I need to be able to determine such things as: Is there a style tag in the body Is there a div that has a style attribute that makes use of width or background-image. I have tried using the DOMDocument class but it can only do 1 and not 2 with xPath. I have also tried simple_html_dom and that can only do 1 but not 2. Do you think its a good idea that I just use regular expressions or is there something that I haven't thought of? | TITLE:
Parsing HTML - is regex the only option in this case?
QUESTION:
A user will supply HTML, it may be valid or invalid (malformed). I need to be able to determine such things as: Is there a style tag in the body Is there a div that has a style attribute that makes use of width or background-image. I have tried using the DOMDocument class but it can only do 1 and not 2 with xPath. I have also tried simple_html_dom and that can only do 1 but not 2. Do you think its a good idea that I just use regular expressions or is there something that I haven't thought of?
ANSWER:
XPath can do both (1) and (2): To test if there's a style tag in the body: //body//style To test if there's a div with a style attribute using width or background-image: //div[contains(@style,'width:') or contains(@style,'background-image:')] And, as you were curious about in your comments, seeing if a style tag contains a:hover or font-size: //style[contains(text(),'a:hover') or contains(text(),'font-size:')] | [
"php",
"html",
"regex",
"parsing"
] | 0 | 2 | 239 | 4 | 0 | 2011-06-10T15:20:15.150000 | 2011-06-10T16:38:46.313000 |
6,308,457 | 6,308,731 | shadowed parameter | why is the second constructor shadowing the first? class RC2{ private; bool keyset; public: RC2(uint32_t t1 = 64){ keyset = false; }
RC2(const std::string KEY, uint32_t t1 = 64){ RC2(t1); //setkey(KEY); } }; is giving me: error: declaration of 'RC2 t1' shadows a parameter i would think that there is no way for the compiler to mess up distinguishing between these im using codeblocks gcc with C++0x | Because RC2(t1); is a local variable declaration shadowing argument t1, not a call to the other constructor. The following code is also valid: int main(int argc,char* args[]) { int(a); a = 2; return a; } Note! Before C++11, there was no way to call another constructor on the same class from an constructor in C++. If you are using an old C++ version make an Init() -method which both constructors invoke. | shadowed parameter why is the second constructor shadowing the first? class RC2{ private; bool keyset; public: RC2(uint32_t t1 = 64){ keyset = false; }
RC2(const std::string KEY, uint32_t t1 = 64){ RC2(t1); //setkey(KEY); } }; is giving me: error: declaration of 'RC2 t1' shadows a parameter i would think that there is no way for the compiler to mess up distinguishing between these im using codeblocks gcc with C++0x | TITLE:
shadowed parameter
QUESTION:
why is the second constructor shadowing the first? class RC2{ private; bool keyset; public: RC2(uint32_t t1 = 64){ keyset = false; }
RC2(const std::string KEY, uint32_t t1 = 64){ RC2(t1); //setkey(KEY); } }; is giving me: error: declaration of 'RC2 t1' shadows a parameter i would think that there is no way for the compiler to mess up distinguishing between these im using codeblocks gcc with C++0x
ANSWER:
Because RC2(t1); is a local variable declaration shadowing argument t1, not a call to the other constructor. The following code is also valid: int main(int argc,char* args[]) { int(a); a = 2; return a; } Note! Before C++11, there was no way to call another constructor on the same class from an constructor in C++. If you are using an old C++ version make an Init() -method which both constructors invoke. | [
"c++",
"class",
"parameters",
"shadow"
] | 5 | 9 | 14,950 | 2 | 0 | 2011-06-10T15:21:26.263000 | 2011-06-10T15:39:53.947000 |
6,308,459 | 6,308,481 | Lifetime of static variable on windows service | I am wondering what would be the life time of a static variable in windows service. I have a windows service and static variable to save the messages flowing inside the service. will I get the messages saved on the static variable after the service is restarted? | No, static variables will revert to their original values upon application restart, and a service restart is an application restart. | Lifetime of static variable on windows service I am wondering what would be the life time of a static variable in windows service. I have a windows service and static variable to save the messages flowing inside the service. will I get the messages saved on the static variable after the service is restarted? | TITLE:
Lifetime of static variable on windows service
QUESTION:
I am wondering what would be the life time of a static variable in windows service. I have a windows service and static variable to save the messages flowing inside the service. will I get the messages saved on the static variable after the service is restarted?
ANSWER:
No, static variables will revert to their original values upon application restart, and a service restart is an application restart. | [
"wcf"
] | 1 | 1 | 1,759 | 2 | 0 | 2011-06-10T15:21:31.590000 | 2011-06-10T15:23:16.467000 |
6,308,486 | 6,308,590 | Having trouble using jQuery to toggle a slide down nav element | I have a nav bar that when I over over an element the next list displays. But when my mouse leaves the original nav the list dissappears. I want the list to stay when it is overed upon. Can you please help? http://jsfiddle.net/GxshD/ | Because your event handler is attached to your li.drop element, you need to encapsulate your child menu in that element like so... Recruiter Tools Featured Tools All Tools | Having trouble using jQuery to toggle a slide down nav element I have a nav bar that when I over over an element the next list displays. But when my mouse leaves the original nav the list dissappears. I want the list to stay when it is overed upon. Can you please help? http://jsfiddle.net/GxshD/ | TITLE:
Having trouble using jQuery to toggle a slide down nav element
QUESTION:
I have a nav bar that when I over over an element the next list displays. But when my mouse leaves the original nav the list dissappears. I want the list to stay when it is overed upon. Can you please help? http://jsfiddle.net/GxshD/
ANSWER:
Because your event handler is attached to your li.drop element, you need to encapsulate your child menu in that element like so... Recruiter Tools Featured Tools All Tools | [
"jquery"
] | 0 | 1 | 128 | 4 | 0 | 2011-06-10T15:23:36.207000 | 2011-06-10T15:30:45.610000 |
6,308,493 | 6,308,581 | using html forms in jsp file | I have a very simple question....I have multiple jsp files like login.jsp, Registration.jsp, forgetpassword.jsp each having their owm forms to take input from user. So, my question is.....Is it OK to have these many files or should I include all my html forms in a single file like user_auth.jsp and use javascript [Which i have no idea how to do] to display them individually...... All these files process the inputs taken by user against mysql database. I am using Struts 1.3.8 framework... | I don't think that anybody would argue that you should have all of those forms in a single file. Most web pages will have some sort of form on them, it's just how it goes. I would stick with your current model. | using html forms in jsp file I have a very simple question....I have multiple jsp files like login.jsp, Registration.jsp, forgetpassword.jsp each having their owm forms to take input from user. So, my question is.....Is it OK to have these many files or should I include all my html forms in a single file like user_auth.jsp and use javascript [Which i have no idea how to do] to display them individually...... All these files process the inputs taken by user against mysql database. I am using Struts 1.3.8 framework... | TITLE:
using html forms in jsp file
QUESTION:
I have a very simple question....I have multiple jsp files like login.jsp, Registration.jsp, forgetpassword.jsp each having their owm forms to take input from user. So, my question is.....Is it OK to have these many files or should I include all my html forms in a single file like user_auth.jsp and use javascript [Which i have no idea how to do] to display them individually...... All these files process the inputs taken by user against mysql database. I am using Struts 1.3.8 framework...
ANSWER:
I don't think that anybody would argue that you should have all of those forms in a single file. Most web pages will have some sort of form on them, it's just how it goes. I would stick with your current model. | [
"html",
"jsp",
"struts"
] | 0 | 1 | 291 | 1 | 0 | 2011-06-10T15:23:48.220000 | 2011-06-10T15:29:55.920000 |
6,308,497 | 6,308,539 | perl if line matches regex, ignore line and move onto next line in file | How would you do the following in perl: for $line (@lines) { if ($line =~ m/ImportantLineNotToBeChanged/){ #break out of the for loop, move onto the next line of the file being processed #start the loop again } if ($line =~ s/SUMMER/WINTER/g){ print "."; } } Updated to show more code, this is what I'm trying to do: sub ChangeSeason(){
if (-f and /.log?/) { $file = $_; open FILE, $file; @lines =; close FILE;
for $line (@lines) { if ($line =~ m/'?Don't touch this line'?/) { last; } if ($line =~ m/'?Or this line'?/){ last; } if ($line =~ m/'?Or this line too'?/){ last; } if ($line +~ m/'?Or this line as well'?/){ last; } if ($line =~ s/(WINTER)/{$1 eq 'winter'? 'summer': 'SUMMER'}/gie){ print "."; } }
print "\nSeason changed in file $_"; open FILE, ">$file"; print FILE @lines; close FILE; } } | Just use next for my $line (@lines) { next if ($line =~ m/ImportantLineNotToBeChanged/); if ($line =~ s/SUMMER/WINTER/g){ print "."; } } | perl if line matches regex, ignore line and move onto next line in file How would you do the following in perl: for $line (@lines) { if ($line =~ m/ImportantLineNotToBeChanged/){ #break out of the for loop, move onto the next line of the file being processed #start the loop again } if ($line =~ s/SUMMER/WINTER/g){ print "."; } } Updated to show more code, this is what I'm trying to do: sub ChangeSeason(){
if (-f and /.log?/) { $file = $_; open FILE, $file; @lines =; close FILE;
for $line (@lines) { if ($line =~ m/'?Don't touch this line'?/) { last; } if ($line =~ m/'?Or this line'?/){ last; } if ($line =~ m/'?Or this line too'?/){ last; } if ($line +~ m/'?Or this line as well'?/){ last; } if ($line =~ s/(WINTER)/{$1 eq 'winter'? 'summer': 'SUMMER'}/gie){ print "."; } }
print "\nSeason changed in file $_"; open FILE, ">$file"; print FILE @lines; close FILE; } } | TITLE:
perl if line matches regex, ignore line and move onto next line in file
QUESTION:
How would you do the following in perl: for $line (@lines) { if ($line =~ m/ImportantLineNotToBeChanged/){ #break out of the for loop, move onto the next line of the file being processed #start the loop again } if ($line =~ s/SUMMER/WINTER/g){ print "."; } } Updated to show more code, this is what I'm trying to do: sub ChangeSeason(){
if (-f and /.log?/) { $file = $_; open FILE, $file; @lines =; close FILE;
for $line (@lines) { if ($line =~ m/'?Don't touch this line'?/) { last; } if ($line =~ m/'?Or this line'?/){ last; } if ($line =~ m/'?Or this line too'?/){ last; } if ($line +~ m/'?Or this line as well'?/){ last; } if ($line =~ s/(WINTER)/{$1 eq 'winter'? 'summer': 'SUMMER'}/gie){ print "."; } }
print "\nSeason changed in file $_"; open FILE, ">$file"; print FILE @lines; close FILE; } }
ANSWER:
Just use next for my $line (@lines) { next if ($line =~ m/ImportantLineNotToBeChanged/); if ($line =~ s/SUMMER/WINTER/g){ print "."; } } | [
"perl",
"line"
] | 7 | 16 | 59,028 | 4 | 0 | 2011-06-10T15:23:55.687000 | 2011-06-10T15:27:23.580000 |
6,308,502 | 6,308,607 | Problem with cleaning up a thread pool | I have a server in Java which is multithreading, and I've created a thread pool for it. Now everything goes well and my server accepts and reads data from the clients that connect to it, but I don't know really how to clean up the sockets after the connections are closed. So here is my code: public static void main(String[] args) throws Exception { // TODO Auto-generated method stub
ThreadPooledServer server = new ThreadPooledServer(queue,7001); new Thread(server).start(); } ThreadPooledServer class: public class ThreadPooledServer implements Runnable { protected ExecutorService threadPool = Executors.newFixedThreadPool(5);
public ThreadPooledServer(BlockingQueue queue,int port) { this.serverPort = port; this.queue=queue; }
public void run() { openServerSocket();
while (!isStopped()) { Socket clientSocket = null; try { clientSocket = serverSocket.accept(); clientconnection++; } catch (IOException e) { if (isStopped()) { System.out.println("Server Stopped."); return; }
throw new RuntimeException("Error accepting client connection", e); }
WorkerRunnable workerRunnable = new WorkerRunnable(queue,clientSocket);
this.threadPool.execute(workerRunnable);
} this.threadPool.shutdown();
System.out.println("Server Stopped."); }
private synchronized boolean isStopped() { return this.isStopped; }
public synchronized void stop() { this.isStopped = true;
try { this.serverSocket.close(); }
catch (IOException e) { throw new RuntimeException("Error closing server", e); } } Here's what I don't understand: My while() loop that accepts for clients works as loong as isStopped is false. When isStopped is set to true, my loop ends and then I shut down my thread pool, which is correct. isStopped is set to true in onstop(){..............}.... Where should I call onstop()...? Because in this moment I'm not using this method,I'm not calling it and that means that I'm not cleaning correctly my threads. WorkerRunnable class: public class WorkerRunnable implements Runnable { public WorkerRunnable(BlockingQueue queue2, Socket clientSocket2) { // TODO Auto-generated constructor stub
this.clientSocket2 = clientSocket2;
this.queue2 = queue2; }
public void run() { try { is = new ObjectInputStream(this.clientSocket2.getInputStream());
try { while (!stop) { System.out.println("Suntem in interiorul buclei while:!");
v = (Coordinate) is.readObject();
queue2.put(v); } } catch (Exception e) { e.printStackTrace(); is.close();
clientSocket2.close(); }
is.close(); clientSocket2.close(); } catch (IOException e) { e.printStackTrace(); } }
public void stop() { this.stop = true; } } } Here I have the same issue. How should I clean and close up my sockets correctly? | Once you call shutdown() the thread pool will close off each thread once all the tasks are complete. You should call onstop() from whatever code knows the pool should be shutdown. This depends on what the rest of your application does and why you would stop the pool before the application has finished. | Problem with cleaning up a thread pool I have a server in Java which is multithreading, and I've created a thread pool for it. Now everything goes well and my server accepts and reads data from the clients that connect to it, but I don't know really how to clean up the sockets after the connections are closed. So here is my code: public static void main(String[] args) throws Exception { // TODO Auto-generated method stub
ThreadPooledServer server = new ThreadPooledServer(queue,7001); new Thread(server).start(); } ThreadPooledServer class: public class ThreadPooledServer implements Runnable { protected ExecutorService threadPool = Executors.newFixedThreadPool(5);
public ThreadPooledServer(BlockingQueue queue,int port) { this.serverPort = port; this.queue=queue; }
public void run() { openServerSocket();
while (!isStopped()) { Socket clientSocket = null; try { clientSocket = serverSocket.accept(); clientconnection++; } catch (IOException e) { if (isStopped()) { System.out.println("Server Stopped."); return; }
throw new RuntimeException("Error accepting client connection", e); }
WorkerRunnable workerRunnable = new WorkerRunnable(queue,clientSocket);
this.threadPool.execute(workerRunnable);
} this.threadPool.shutdown();
System.out.println("Server Stopped."); }
private synchronized boolean isStopped() { return this.isStopped; }
public synchronized void stop() { this.isStopped = true;
try { this.serverSocket.close(); }
catch (IOException e) { throw new RuntimeException("Error closing server", e); } } Here's what I don't understand: My while() loop that accepts for clients works as loong as isStopped is false. When isStopped is set to true, my loop ends and then I shut down my thread pool, which is correct. isStopped is set to true in onstop(){..............}.... Where should I call onstop()...? Because in this moment I'm not using this method,I'm not calling it and that means that I'm not cleaning correctly my threads. WorkerRunnable class: public class WorkerRunnable implements Runnable { public WorkerRunnable(BlockingQueue queue2, Socket clientSocket2) { // TODO Auto-generated constructor stub
this.clientSocket2 = clientSocket2;
this.queue2 = queue2; }
public void run() { try { is = new ObjectInputStream(this.clientSocket2.getInputStream());
try { while (!stop) { System.out.println("Suntem in interiorul buclei while:!");
v = (Coordinate) is.readObject();
queue2.put(v); } } catch (Exception e) { e.printStackTrace(); is.close();
clientSocket2.close(); }
is.close(); clientSocket2.close(); } catch (IOException e) { e.printStackTrace(); } }
public void stop() { this.stop = true; } } } Here I have the same issue. How should I clean and close up my sockets correctly? | TITLE:
Problem with cleaning up a thread pool
QUESTION:
I have a server in Java which is multithreading, and I've created a thread pool for it. Now everything goes well and my server accepts and reads data from the clients that connect to it, but I don't know really how to clean up the sockets after the connections are closed. So here is my code: public static void main(String[] args) throws Exception { // TODO Auto-generated method stub
ThreadPooledServer server = new ThreadPooledServer(queue,7001); new Thread(server).start(); } ThreadPooledServer class: public class ThreadPooledServer implements Runnable { protected ExecutorService threadPool = Executors.newFixedThreadPool(5);
public ThreadPooledServer(BlockingQueue queue,int port) { this.serverPort = port; this.queue=queue; }
public void run() { openServerSocket();
while (!isStopped()) { Socket clientSocket = null; try { clientSocket = serverSocket.accept(); clientconnection++; } catch (IOException e) { if (isStopped()) { System.out.println("Server Stopped."); return; }
throw new RuntimeException("Error accepting client connection", e); }
WorkerRunnable workerRunnable = new WorkerRunnable(queue,clientSocket);
this.threadPool.execute(workerRunnable);
} this.threadPool.shutdown();
System.out.println("Server Stopped."); }
private synchronized boolean isStopped() { return this.isStopped; }
public synchronized void stop() { this.isStopped = true;
try { this.serverSocket.close(); }
catch (IOException e) { throw new RuntimeException("Error closing server", e); } } Here's what I don't understand: My while() loop that accepts for clients works as loong as isStopped is false. When isStopped is set to true, my loop ends and then I shut down my thread pool, which is correct. isStopped is set to true in onstop(){..............}.... Where should I call onstop()...? Because in this moment I'm not using this method,I'm not calling it and that means that I'm not cleaning correctly my threads. WorkerRunnable class: public class WorkerRunnable implements Runnable { public WorkerRunnable(BlockingQueue queue2, Socket clientSocket2) { // TODO Auto-generated constructor stub
this.clientSocket2 = clientSocket2;
this.queue2 = queue2; }
public void run() { try { is = new ObjectInputStream(this.clientSocket2.getInputStream());
try { while (!stop) { System.out.println("Suntem in interiorul buclei while:!");
v = (Coordinate) is.readObject();
queue2.put(v); } } catch (Exception e) { e.printStackTrace(); is.close();
clientSocket2.close(); }
is.close(); clientSocket2.close(); } catch (IOException e) { e.printStackTrace(); } }
public void stop() { this.stop = true; } } } Here I have the same issue. How should I clean and close up my sockets correctly?
ANSWER:
Once you call shutdown() the thread pool will close off each thread once all the tasks are complete. You should call onstop() from whatever code knows the pool should be shutdown. This depends on what the rest of your application does and why you would stop the pool before the application has finished. | [
"java",
"multithreading",
"sockets"
] | 2 | 0 | 4,640 | 1 | 0 | 2011-06-10T15:24:08.043000 | 2011-06-10T15:31:26.483000 |
6,308,504 | 6,308,560 | Send ssh commands with a script | I want to to check a Nortel Router by running./script: #!/bin/ksh print "IP:" read ip; ping ${ip}; ssh -l default ${ip} "sho mod; en; sho int; sho node-e; sho node-a"; I can ssh normaly with ssh -l [user] [ip]. But not with ssh -l [user] [ip] '[cmd1], [cmd2]' it says automatically "Conection to [ip] closed." | There's application called expect which can do that kind of interaction / terminal simulation for you. Otherwise, you could write a script using fabric or even straight in python using paramiko Running commands this way would be better of course, but if your router doesn't accept commands this way, you'll need to simulate the standard connection. | Send ssh commands with a script I want to to check a Nortel Router by running./script: #!/bin/ksh print "IP:" read ip; ping ${ip}; ssh -l default ${ip} "sho mod; en; sho int; sho node-e; sho node-a"; I can ssh normaly with ssh -l [user] [ip]. But not with ssh -l [user] [ip] '[cmd1], [cmd2]' it says automatically "Conection to [ip] closed." | TITLE:
Send ssh commands with a script
QUESTION:
I want to to check a Nortel Router by running./script: #!/bin/ksh print "IP:" read ip; ping ${ip}; ssh -l default ${ip} "sho mod; en; sho int; sho node-e; sho node-a"; I can ssh normaly with ssh -l [user] [ip]. But not with ssh -l [user] [ip] '[cmd1], [cmd2]' it says automatically "Conection to [ip] closed."
ANSWER:
There's application called expect which can do that kind of interaction / terminal simulation for you. Otherwise, you could write a script using fabric or even straight in python using paramiko Running commands this way would be better of course, but if your router doesn't accept commands this way, you'll need to simulate the standard connection. | [
"networking",
"scripting",
"ssh",
"ksh"
] | 1 | 1 | 537 | 1 | 0 | 2011-06-10T15:24:37.323000 | 2011-06-10T15:28:21.233000 |
6,308,508 | 6,308,629 | Entity Framework 4.1, Table Per Type Inheritance and Lookup Tables | Using table per type inheritance is it possible to have the same data with the same key in more than one of the derived types? e.g. Base Type: [Table("BaseType")] public abstract class BaseType { public int Id { get; set; } public string Description { get; set; } } Derived Type A: [Table("DerivedTypeA")] public class DerivedTypeA: BaseType {} Derived Type B: [Table("DerivedTypeB")] public class DerivedTypeB: BaseType {} Along with a number of types that are either DerivedTypeA or DerivedTypeB I have one particular type that is both DerivedTypeA and DerivedTypeB When I seed the database by creating a new DerivedTypeA and DerivedTypeB for this type it gets added twice, with different Id s. While not the end of the world, I'd like it to have the same Id in the two derived tables. Is this possible? Thanks in advance. | If I understand you correctly, you're describing a multiple-inheritance situation, which isn't supported in C#. DerivedA cannot be DerivedB or vice-versa because they are siblings. This article helps define the issue and presents a pattern which might help you: http://www.codeproject.com/KB/architecture/smip.aspx | Entity Framework 4.1, Table Per Type Inheritance and Lookup Tables Using table per type inheritance is it possible to have the same data with the same key in more than one of the derived types? e.g. Base Type: [Table("BaseType")] public abstract class BaseType { public int Id { get; set; } public string Description { get; set; } } Derived Type A: [Table("DerivedTypeA")] public class DerivedTypeA: BaseType {} Derived Type B: [Table("DerivedTypeB")] public class DerivedTypeB: BaseType {} Along with a number of types that are either DerivedTypeA or DerivedTypeB I have one particular type that is both DerivedTypeA and DerivedTypeB When I seed the database by creating a new DerivedTypeA and DerivedTypeB for this type it gets added twice, with different Id s. While not the end of the world, I'd like it to have the same Id in the two derived tables. Is this possible? Thanks in advance. | TITLE:
Entity Framework 4.1, Table Per Type Inheritance and Lookup Tables
QUESTION:
Using table per type inheritance is it possible to have the same data with the same key in more than one of the derived types? e.g. Base Type: [Table("BaseType")] public abstract class BaseType { public int Id { get; set; } public string Description { get; set; } } Derived Type A: [Table("DerivedTypeA")] public class DerivedTypeA: BaseType {} Derived Type B: [Table("DerivedTypeB")] public class DerivedTypeB: BaseType {} Along with a number of types that are either DerivedTypeA or DerivedTypeB I have one particular type that is both DerivedTypeA and DerivedTypeB When I seed the database by creating a new DerivedTypeA and DerivedTypeB for this type it gets added twice, with different Id s. While not the end of the world, I'd like it to have the same Id in the two derived tables. Is this possible? Thanks in advance.
ANSWER:
If I understand you correctly, you're describing a multiple-inheritance situation, which isn't supported in C#. DerivedA cannot be DerivedB or vice-versa because they are siblings. This article helps define the issue and presents a pattern which might help you: http://www.codeproject.com/KB/architecture/smip.aspx | [
"entity-framework",
"ef-code-first",
"table-per-type"
] | 0 | 0 | 560 | 1 | 0 | 2011-06-10T15:24:52.053000 | 2011-06-10T15:32:42.483000 |
6,308,524 | 6,308,591 | Mysql - return all results from table A and selectively join with table B | I have two tables: default: +----+--------+ | id | colour | +----+--------+ | 1 | red | | 2 | green | | 3 | yellow | +----+--------+ custom: +--------+--------------+---------+ | linkId | customcolour | ownerId | +--------+--------------+---------+ | 1 | bright red | 1 | | 2 | garden green | 2 | +--------+--------------+---------+ I want to return everything from the default table and then get any associated customcolours (via the linkId). The query I am using is: SELECT a.colour, b.customcolour FROM default a LEFT JOIN custom b ON a.id = b.linkId WHERE (b.ownerId IS NULL OR b.ownerId = 1) GROUP BY a.id ORDER BY a.colur However when I join to the custom table it will not select custom linkId 2 because the ownerId is not 1 nor NULL. Is there a way to return the row default.id = 2 and just set customercolour as NULL, without adding it to the table? | You need to move your WHERE criteria into the join SELECT a.colour, b.customcolour FROM default a LEFT JOIN custom b ON a.id = b.linkId AND (b.ownerId IS NULL OR b.ownerId = 1) GROUP BY a.id ORDER BY a.colur | Mysql - return all results from table A and selectively join with table B I have two tables: default: +----+--------+ | id | colour | +----+--------+ | 1 | red | | 2 | green | | 3 | yellow | +----+--------+ custom: +--------+--------------+---------+ | linkId | customcolour | ownerId | +--------+--------------+---------+ | 1 | bright red | 1 | | 2 | garden green | 2 | +--------+--------------+---------+ I want to return everything from the default table and then get any associated customcolours (via the linkId). The query I am using is: SELECT a.colour, b.customcolour FROM default a LEFT JOIN custom b ON a.id = b.linkId WHERE (b.ownerId IS NULL OR b.ownerId = 1) GROUP BY a.id ORDER BY a.colur However when I join to the custom table it will not select custom linkId 2 because the ownerId is not 1 nor NULL. Is there a way to return the row default.id = 2 and just set customercolour as NULL, without adding it to the table? | TITLE:
Mysql - return all results from table A and selectively join with table B
QUESTION:
I have two tables: default: +----+--------+ | id | colour | +----+--------+ | 1 | red | | 2 | green | | 3 | yellow | +----+--------+ custom: +--------+--------------+---------+ | linkId | customcolour | ownerId | +--------+--------------+---------+ | 1 | bright red | 1 | | 2 | garden green | 2 | +--------+--------------+---------+ I want to return everything from the default table and then get any associated customcolours (via the linkId). The query I am using is: SELECT a.colour, b.customcolour FROM default a LEFT JOIN custom b ON a.id = b.linkId WHERE (b.ownerId IS NULL OR b.ownerId = 1) GROUP BY a.id ORDER BY a.colur However when I join to the custom table it will not select custom linkId 2 because the ownerId is not 1 nor NULL. Is there a way to return the row default.id = 2 and just set customercolour as NULL, without adding it to the table?
ANSWER:
You need to move your WHERE criteria into the join SELECT a.colour, b.customcolour FROM default a LEFT JOIN custom b ON a.id = b.linkId AND (b.ownerId IS NULL OR b.ownerId = 1) GROUP BY a.id ORDER BY a.colur | [
"mysql",
"join"
] | 0 | 1 | 253 | 1 | 0 | 2011-06-10T15:26:26.560000 | 2011-06-10T15:30:46.167000 |
6,308,530 | 6,308,643 | PHP code works until I make it a function | I have this code here which gives me the result I'm looking for, a nicely formatted tree of values. $todos = $this->db->get('todos'); //store the resulting records $tree = array(); //empty array for storage $result = $todos->result_array(); //store results as arrays
foreach ($result as $item){ $id = $item['recordId']; $parent = $item['actionParent']; $tree[$id] = isset($tree[$id])? $item + $tree[$id]: $item; $tree[$parent]['_children'][] = &$tree[]; }
echo ' '; print_r($tree); echo ' '; When I put the code from the foreach into a function like so, I get an empty array. What am I missing? function adj_tree($tree, $item){ $id = $item['recordId']; $parent = $item['actionParent']; $tree[$id] = isset($tree[$id])? $item + $tree[$id]: $item; $tree[$parent]['_children'][] = &$tree[]; }
$todos = $this->db->get('todos'); //store the resulting records $tree = array(); //empty array for storage $result = $todos->result_array(); //store results as arrays
foreach ($result as $item){ adj_tree($tree, $item); }
echo ' '; print_r($tree); echo ' '; | Right now the function is making a local copy of {$tree}, editing it and then discarding that copy when the function closes. You have two options: 1) return the local copy of {$tree} and assign it to the global copy. function adj_tree($tree, $item){ $id = $item['recordId']; $parent = $item['actionParent']; $tree[$id] = isset($tree[$id])? $item + $tree[$id]: $item; $tree[$parent]['_children'][] = &$tree[]; return $tree; } //... foreach ($result as $item){ $tree = adj_tree($tree, $item); } 2) pass the array by reference and edit the global version within the function. function adj_tree(&$tree, $item){ $id = $item['recordId']; $parent = $item['actionParent']; $tree[$id] = isset($tree[$id])? $item + $tree[$id]: $item; $tree[$parent]['_children'][] = &$tree[]; } | PHP code works until I make it a function I have this code here which gives me the result I'm looking for, a nicely formatted tree of values. $todos = $this->db->get('todos'); //store the resulting records $tree = array(); //empty array for storage $result = $todos->result_array(); //store results as arrays
foreach ($result as $item){ $id = $item['recordId']; $parent = $item['actionParent']; $tree[$id] = isset($tree[$id])? $item + $tree[$id]: $item; $tree[$parent]['_children'][] = &$tree[]; }
echo ' '; print_r($tree); echo ' '; When I put the code from the foreach into a function like so, I get an empty array. What am I missing? function adj_tree($tree, $item){ $id = $item['recordId']; $parent = $item['actionParent']; $tree[$id] = isset($tree[$id])? $item + $tree[$id]: $item; $tree[$parent]['_children'][] = &$tree[]; }
$todos = $this->db->get('todos'); //store the resulting records $tree = array(); //empty array for storage $result = $todos->result_array(); //store results as arrays
foreach ($result as $item){ adj_tree($tree, $item); }
echo ' '; print_r($tree); echo ' '; | TITLE:
PHP code works until I make it a function
QUESTION:
I have this code here which gives me the result I'm looking for, a nicely formatted tree of values. $todos = $this->db->get('todos'); //store the resulting records $tree = array(); //empty array for storage $result = $todos->result_array(); //store results as arrays
foreach ($result as $item){ $id = $item['recordId']; $parent = $item['actionParent']; $tree[$id] = isset($tree[$id])? $item + $tree[$id]: $item; $tree[$parent]['_children'][] = &$tree[]; }
echo ' '; print_r($tree); echo ' '; When I put the code from the foreach into a function like so, I get an empty array. What am I missing? function adj_tree($tree, $item){ $id = $item['recordId']; $parent = $item['actionParent']; $tree[$id] = isset($tree[$id])? $item + $tree[$id]: $item; $tree[$parent]['_children'][] = &$tree[]; }
$todos = $this->db->get('todos'); //store the resulting records $tree = array(); //empty array for storage $result = $todos->result_array(); //store results as arrays
foreach ($result as $item){ adj_tree($tree, $item); }
echo ' '; print_r($tree); echo ' ';
ANSWER:
Right now the function is making a local copy of {$tree}, editing it and then discarding that copy when the function closes. You have two options: 1) return the local copy of {$tree} and assign it to the global copy. function adj_tree($tree, $item){ $id = $item['recordId']; $parent = $item['actionParent']; $tree[$id] = isset($tree[$id])? $item + $tree[$id]: $item; $tree[$parent]['_children'][] = &$tree[]; return $tree; } //... foreach ($result as $item){ $tree = adj_tree($tree, $item); } 2) pass the array by reference and edit the global version within the function. function adj_tree(&$tree, $item){ $id = $item['recordId']; $parent = $item['actionParent']; $tree[$id] = isset($tree[$id])? $item + $tree[$id]: $item; $tree[$parent]['_children'][] = &$tree[]; } | [
"php",
"arrays",
"function"
] | 3 | 2 | 143 | 3 | 0 | 2011-06-10T15:26:51.823000 | 2011-06-10T15:33:40.520000 |
6,308,567 | 6,308,579 | Is jQuery considered to be outdated? | This may be an open and close case but may open some debate. I was speaking with my friend recently who said to me "jQuery is so 2008" Now while I don't pretend to know a whole lot about this language (Or JavaScript for that matter), I have used both for projects that I have done in the past. So my question is, is this framework still widely used? Are there newer more "2011" frameworks? I see that this may be a daft question, as different frameworks have different uses but I have seen a lot of large companies have used jQuery on their site which leads me to believe that of course it has its uses (as does any other language). What's the general consensus among designers/developers? Is it outdated? Is it still widely used in industry? EDIT: The reason I ask this is because all the time I've searched for things jQuery related the articles that come up first seem to be dated back a few years... Another EDIT: Thanks for your points, I think his reason for thinking it was outdated was maybe because the company he worked for didn't use it. Maybe THEY were outdated?! | Your friend is speaking out of total ignorance, and probably just uses whatever was invented within the past 6 months in order to feel "hip" and "cool". jQuery is still widely used. jQuery is still frequently updated (in fact there was a major release just last month). jQuery is not "outdated". (In 2008, jQuery was on 1.2.x, which is outdated.) | Is jQuery considered to be outdated? This may be an open and close case but may open some debate. I was speaking with my friend recently who said to me "jQuery is so 2008" Now while I don't pretend to know a whole lot about this language (Or JavaScript for that matter), I have used both for projects that I have done in the past. So my question is, is this framework still widely used? Are there newer more "2011" frameworks? I see that this may be a daft question, as different frameworks have different uses but I have seen a lot of large companies have used jQuery on their site which leads me to believe that of course it has its uses (as does any other language). What's the general consensus among designers/developers? Is it outdated? Is it still widely used in industry? EDIT: The reason I ask this is because all the time I've searched for things jQuery related the articles that come up first seem to be dated back a few years... Another EDIT: Thanks for your points, I think his reason for thinking it was outdated was maybe because the company he worked for didn't use it. Maybe THEY were outdated?! | TITLE:
Is jQuery considered to be outdated?
QUESTION:
This may be an open and close case but may open some debate. I was speaking with my friend recently who said to me "jQuery is so 2008" Now while I don't pretend to know a whole lot about this language (Or JavaScript for that matter), I have used both for projects that I have done in the past. So my question is, is this framework still widely used? Are there newer more "2011" frameworks? I see that this may be a daft question, as different frameworks have different uses but I have seen a lot of large companies have used jQuery on their site which leads me to believe that of course it has its uses (as does any other language). What's the general consensus among designers/developers? Is it outdated? Is it still widely used in industry? EDIT: The reason I ask this is because all the time I've searched for things jQuery related the articles that come up first seem to be dated back a few years... Another EDIT: Thanks for your points, I think his reason for thinking it was outdated was maybe because the company he worked for didn't use it. Maybe THEY were outdated?!
ANSWER:
Your friend is speaking out of total ignorance, and probably just uses whatever was invented within the past 6 months in order to feel "hip" and "cool". jQuery is still widely used. jQuery is still frequently updated (in fact there was a major release just last month). jQuery is not "outdated". (In 2008, jQuery was on 1.2.x, which is outdated.) | [
"jquery"
] | 1 | 8 | 1,523 | 2 | 0 | 2011-06-10T15:28:34.583000 | 2011-06-10T15:29:42.883000 |
6,308,569 | 6,308,596 | How do you skip over a list comprehension in Python's debugger (pdb)? | In pdb the next instruction does not step over list comprehensions, instead it steps through each iteration. Is there a way to step over them so debugging will continue at the next line after the list comprehension? I've had to resort to listing the code, setting a breakpoint at the next line, and then continuing execution to the next breakpoint. This is annoying and I figured there must be a better way. | You can use the until command. Output of help until in pdb: unt(il) Continue execution until the line with a number greater than the current one is reached or until the current frame returns | How do you skip over a list comprehension in Python's debugger (pdb)? In pdb the next instruction does not step over list comprehensions, instead it steps through each iteration. Is there a way to step over them so debugging will continue at the next line after the list comprehension? I've had to resort to listing the code, setting a breakpoint at the next line, and then continuing execution to the next breakpoint. This is annoying and I figured there must be a better way. | TITLE:
How do you skip over a list comprehension in Python's debugger (pdb)?
QUESTION:
In pdb the next instruction does not step over list comprehensions, instead it steps through each iteration. Is there a way to step over them so debugging will continue at the next line after the list comprehension? I've had to resort to listing the code, setting a breakpoint at the next line, and then continuing execution to the next breakpoint. This is annoying and I figured there must be a better way.
ANSWER:
You can use the until command. Output of help until in pdb: unt(il) Continue execution until the line with a number greater than the current one is reached or until the current frame returns | [
"python",
"list-comprehension",
"pdb"
] | 53 | 70 | 6,310 | 2 | 0 | 2011-06-10T15:28:42.783000 | 2011-06-10T15:30:52.523000 |
6,308,570 | 6,308,632 | Javascript If statement to run some html code | I've got a little bit of javascript embedded in my html (using a.aspx file). I want to perform some sort of if statement which then determines whether or not some sort of chart is displayed. This chart is displayed using html, and I'm assuming the if statement should be written in javascript. However, I don't really know how to "run" this html code from within java. It is basically just drawing a table. Any suggestions? I've seen document.write, but I've only seen that being used with single lines. | You don't really "run" an HTML code. HTML is a markup language and it is mostly used to format and arrange elements that are displayed in the web browser. The problem you are probably trying to solve is: Display or hide an element based on some condition. A JavaScript code like this is what you want. if (condition) { document.getElementById('chart').style.display = "none" } else { document.getElementById('chart').style.display = "" } Of course whatever element is responsible for displaying the chart should have an id="chart" attribute. e.g.. The JavaScript code I have given alters the display CSS property of this element to hide it or make it visible. In case this is not what you want but you want to dynamically modify the HTML responsible for the chart, then you need to use the innerHTML property of the element. Example: if (condition) { document.getElementById('chart').innerHTML = " " } else { document.getElementById('chart').innerHTML = "" } | Javascript If statement to run some html code I've got a little bit of javascript embedded in my html (using a.aspx file). I want to perform some sort of if statement which then determines whether or not some sort of chart is displayed. This chart is displayed using html, and I'm assuming the if statement should be written in javascript. However, I don't really know how to "run" this html code from within java. It is basically just drawing a table. Any suggestions? I've seen document.write, but I've only seen that being used with single lines. | TITLE:
Javascript If statement to run some html code
QUESTION:
I've got a little bit of javascript embedded in my html (using a.aspx file). I want to perform some sort of if statement which then determines whether or not some sort of chart is displayed. This chart is displayed using html, and I'm assuming the if statement should be written in javascript. However, I don't really know how to "run" this html code from within java. It is basically just drawing a table. Any suggestions? I've seen document.write, but I've only seen that being used with single lines.
ANSWER:
You don't really "run" an HTML code. HTML is a markup language and it is mostly used to format and arrange elements that are displayed in the web browser. The problem you are probably trying to solve is: Display or hide an element based on some condition. A JavaScript code like this is what you want. if (condition) { document.getElementById('chart').style.display = "none" } else { document.getElementById('chart').style.display = "" } Of course whatever element is responsible for displaying the chart should have an id="chart" attribute. e.g.. The JavaScript code I have given alters the display CSS property of this element to hide it or make it visible. In case this is not what you want but you want to dynamically modify the HTML responsible for the chart, then you need to use the innerHTML property of the element. Example: if (condition) { document.getElementById('chart').innerHTML = " " } else { document.getElementById('chart').innerHTML = "" } | [
"javascript",
".net",
"asp.net",
"html",
"if-statement"
] | 5 | 4 | 23,967 | 3 | 0 | 2011-06-10T15:28:53.337000 | 2011-06-10T15:32:46.030000 |
6,308,582 | 6,309,171 | MVC Deserialization Error | Okay. This is my company's customer portal, it's an MVC 2 project. We have a back end SAP system that the portal draws data from. But it does not directly hit SAP, it sends an xml request to a VB app that gets the data and sends it back in an xml response. There is an interface IRequest that all the various requests implement examples would be CustomerNumberRequest, CompanyNameRequest, etc. These all implement the method ToXml which as the name suggests simply builds xml to send. All of the existing requests work fine. (Let me preface this by saying that I inherited this project and the guy who wrote it is no longer with us) I am now trying to send a request to get the Rep Groups from SAP. I basically copied one of the other requests verbatim, making the necessary tweaks to send the appropriate request. But it keeps failing with error messages that I don't understand: The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://tempuri.org/:request. The InnerException message was 'The deserializer cannot load the type to deserialize because type 'XXXXX.CustomerPortal.Domain.RepGroupRequest' could not be found in assembly 'XXXXX.CustomerPortal.Domain, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. Check that the type being serialized has the same contract as the type being deserialized and the same assembly is used.'. Please see InnerException for more details. This error happens right at _communicationService.ProcessRequest(request); (shown below) It does not enter the ProcessRequest method it just tries to create a NetDataContractSerializer here: public override XmlObjectSerializer CreateSerializer(Type type, XmlDictionaryString name, XmlDictionaryString ns, IList knownTypes) { return new NetDataContractSerializer(); } and then it dies. These are the methods being called: private void PopulateRepGroups() { List repGroups = new List (); RepGroupRequest request = new RepGroupRequest(); foreach (RepGroup repGroup in _repService.GetRepGroups(request)) repGroups.Add(repGroup.RepGroupName); ViewData["RepGroups"] = new SelectList(repGroups); }
public List GetRepGroups(RepGroupRequest request) { string response = _communicationService.ProcessRequest(request); return RepGroupResponseFactory.GetRepGroupResponse(response); } Can anybody tell me what this error message is telling me? It says the type cannot be found but the type should be IRequest (that's what it says when the CreateSerializer is hit) which is used all over this. I'm clearly lost, please help! | Quoting your exception Check that the type being serialized has the same contract as the type being deserialized and the same assembly is used Check the version of the library on both ends that CustomerPortal.Domain.RepGroupRequest resides in to make sure they are the same version exactly. | MVC Deserialization Error Okay. This is my company's customer portal, it's an MVC 2 project. We have a back end SAP system that the portal draws data from. But it does not directly hit SAP, it sends an xml request to a VB app that gets the data and sends it back in an xml response. There is an interface IRequest that all the various requests implement examples would be CustomerNumberRequest, CompanyNameRequest, etc. These all implement the method ToXml which as the name suggests simply builds xml to send. All of the existing requests work fine. (Let me preface this by saying that I inherited this project and the guy who wrote it is no longer with us) I am now trying to send a request to get the Rep Groups from SAP. I basically copied one of the other requests verbatim, making the necessary tweaks to send the appropriate request. But it keeps failing with error messages that I don't understand: The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://tempuri.org/:request. The InnerException message was 'The deserializer cannot load the type to deserialize because type 'XXXXX.CustomerPortal.Domain.RepGroupRequest' could not be found in assembly 'XXXXX.CustomerPortal.Domain, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. Check that the type being serialized has the same contract as the type being deserialized and the same assembly is used.'. Please see InnerException for more details. This error happens right at _communicationService.ProcessRequest(request); (shown below) It does not enter the ProcessRequest method it just tries to create a NetDataContractSerializer here: public override XmlObjectSerializer CreateSerializer(Type type, XmlDictionaryString name, XmlDictionaryString ns, IList knownTypes) { return new NetDataContractSerializer(); } and then it dies. These are the methods being called: private void PopulateRepGroups() { List repGroups = new List (); RepGroupRequest request = new RepGroupRequest(); foreach (RepGroup repGroup in _repService.GetRepGroups(request)) repGroups.Add(repGroup.RepGroupName); ViewData["RepGroups"] = new SelectList(repGroups); }
public List GetRepGroups(RepGroupRequest request) { string response = _communicationService.ProcessRequest(request); return RepGroupResponseFactory.GetRepGroupResponse(response); } Can anybody tell me what this error message is telling me? It says the type cannot be found but the type should be IRequest (that's what it says when the CreateSerializer is hit) which is used all over this. I'm clearly lost, please help! | TITLE:
MVC Deserialization Error
QUESTION:
Okay. This is my company's customer portal, it's an MVC 2 project. We have a back end SAP system that the portal draws data from. But it does not directly hit SAP, it sends an xml request to a VB app that gets the data and sends it back in an xml response. There is an interface IRequest that all the various requests implement examples would be CustomerNumberRequest, CompanyNameRequest, etc. These all implement the method ToXml which as the name suggests simply builds xml to send. All of the existing requests work fine. (Let me preface this by saying that I inherited this project and the guy who wrote it is no longer with us) I am now trying to send a request to get the Rep Groups from SAP. I basically copied one of the other requests verbatim, making the necessary tweaks to send the appropriate request. But it keeps failing with error messages that I don't understand: The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://tempuri.org/:request. The InnerException message was 'The deserializer cannot load the type to deserialize because type 'XXXXX.CustomerPortal.Domain.RepGroupRequest' could not be found in assembly 'XXXXX.CustomerPortal.Domain, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. Check that the type being serialized has the same contract as the type being deserialized and the same assembly is used.'. Please see InnerException for more details. This error happens right at _communicationService.ProcessRequest(request); (shown below) It does not enter the ProcessRequest method it just tries to create a NetDataContractSerializer here: public override XmlObjectSerializer CreateSerializer(Type type, XmlDictionaryString name, XmlDictionaryString ns, IList knownTypes) { return new NetDataContractSerializer(); } and then it dies. These are the methods being called: private void PopulateRepGroups() { List repGroups = new List (); RepGroupRequest request = new RepGroupRequest(); foreach (RepGroup repGroup in _repService.GetRepGroups(request)) repGroups.Add(repGroup.RepGroupName); ViewData["RepGroups"] = new SelectList(repGroups); }
public List GetRepGroups(RepGroupRequest request) { string response = _communicationService.ProcessRequest(request); return RepGroupResponseFactory.GetRepGroupResponse(response); } Can anybody tell me what this error message is telling me? It says the type cannot be found but the type should be IRequest (that's what it says when the CreateSerializer is hit) which is used all over this. I'm clearly lost, please help!
ANSWER:
Quoting your exception Check that the type being serialized has the same contract as the type being deserialized and the same assembly is used Check the version of the library on both ends that CustomerPortal.Domain.RepGroupRequest resides in to make sure they are the same version exactly. | [
"c#",
"asp.net-mvc-2",
"netdatacontractserializer"
] | 1 | 1 | 1,216 | 1 | 0 | 2011-06-10T15:29:57.640000 | 2011-06-10T16:14:39.987000 |
6,308,583 | 6,308,659 | Count set bits in float in Java | This is an interview question: how to count set bits in float in Java? I guess I should not know the bit representation of float to answer this question. Can I just convert a float to a byte array somehow? I can use the Java serialization but it looks like overkill. | The Float class has an: public static int floatToIntBits(float value) method that returns a representation of the specified floating-point value according to the IEEE 754 floating-point "single format" bit layout. So you can get the bits with this method, then count which ones are set. http://download.oracle.com/javase/7/docs/api/ | Count set bits in float in Java This is an interview question: how to count set bits in float in Java? I guess I should not know the bit representation of float to answer this question. Can I just convert a float to a byte array somehow? I can use the Java serialization but it looks like overkill. | TITLE:
Count set bits in float in Java
QUESTION:
This is an interview question: how to count set bits in float in Java? I guess I should not know the bit representation of float to answer this question. Can I just convert a float to a byte array somehow? I can use the Java serialization but it looks like overkill.
ANSWER:
The Float class has an: public static int floatToIntBits(float value) method that returns a representation of the specified floating-point value according to the IEEE 754 floating-point "single format" bit layout. So you can get the bits with this method, then count which ones are set. http://download.oracle.com/javase/7/docs/api/ | [
"java",
"floating-point",
"bit-manipulation"
] | 3 | 5 | 892 | 3 | 0 | 2011-06-10T15:30:00.733000 | 2011-06-10T15:34:14.627000 |
6,308,594 | 6,308,620 | How can I copy data from one column to another in the same table? | Is it possible to copy data from column A to column B for all records in a table in SQL? | How about this UPDATE table SET columnB = columnA; This will update every row. | How can I copy data from one column to another in the same table? Is it possible to copy data from column A to column B for all records in a table in SQL? | TITLE:
How can I copy data from one column to another in the same table?
QUESTION:
Is it possible to copy data from column A to column B for all records in a table in SQL?
ANSWER:
How about this UPDATE table SET columnB = columnA; This will update every row. | [
"sql"
] | 416 | 754 | 489,164 | 4 | 0 | 2011-06-10T15:30:50.290000 | 2011-06-10T15:32:13.613000 |
6,308,600 | 6,308,959 | Simple DataGrid Binding to Remote SQL Server 2005/8 Database | How can we Use a DataGrid in WPF to show/update/add/delete records in a Table? I have watched/read and tried many tutorials, but I can't find a single, easy to understand tutorial on how to bind data with a remote database. I can't seem to find anything like this. | Well, if you want to use Linq2Sql (less difficult to learn than EntityFramework) try a tutorial like this one: http://www.codeproject.com/KB/WPF/WPFDataGrid.aspx or http://www.codeproject.com/KB/WPF/WPFDataGridExamples.aspx And you will do fine. | Simple DataGrid Binding to Remote SQL Server 2005/8 Database How can we Use a DataGrid in WPF to show/update/add/delete records in a Table? I have watched/read and tried many tutorials, but I can't find a single, easy to understand tutorial on how to bind data with a remote database. I can't seem to find anything like this. | TITLE:
Simple DataGrid Binding to Remote SQL Server 2005/8 Database
QUESTION:
How can we Use a DataGrid in WPF to show/update/add/delete records in a Table? I have watched/read and tried many tutorials, but I can't find a single, easy to understand tutorial on how to bind data with a remote database. I can't seem to find anything like this.
ANSWER:
Well, if you want to use Linq2Sql (less difficult to learn than EntityFramework) try a tutorial like this one: http://www.codeproject.com/KB/WPF/WPFDataGrid.aspx or http://www.codeproject.com/KB/WPF/WPFDataGridExamples.aspx And you will do fine. | [
"c#",
".net",
"sql",
"wpf",
"data-binding"
] | 0 | 1 | 1,214 | 2 | 0 | 2011-06-10T15:31:03.207000 | 2011-06-10T15:57:29.117000 |
6,308,605 | 6,308,682 | more than one database per model | class Service < ActiveRecord::Base
establish_connection(:adapter => "mysql",:host => "myip",:username => "myusername",:password => "mypassword",:database => "mydatabase" )
end This works Service.all #connects to mydatabase But i need something like that. Service.use(mydatabase1).all #connects to mydatabase1 Service.use(mydatabase2).all #connects to mydatabase2 How can i achieve this? Update Database names are dynamic. I want Service model to connect database dynamically. When i type Service.use(weeweweaszxc).all it has to use weeweweaszxc database. | Try taking a look as this question over here. How to best handle per-Model database connections with ActiveRecord? They define the databases in the database.yml file like normal and call this in the model: class AnotherDatabase < ActiveRecord::Base self.abstract_class = true establish_connection "anotherbase_#{RAILS_ENV}" end Used info from Priit's answer | more than one database per model class Service < ActiveRecord::Base
establish_connection(:adapter => "mysql",:host => "myip",:username => "myusername",:password => "mypassword",:database => "mydatabase" )
end This works Service.all #connects to mydatabase But i need something like that. Service.use(mydatabase1).all #connects to mydatabase1 Service.use(mydatabase2).all #connects to mydatabase2 How can i achieve this? Update Database names are dynamic. I want Service model to connect database dynamically. When i type Service.use(weeweweaszxc).all it has to use weeweweaszxc database. | TITLE:
more than one database per model
QUESTION:
class Service < ActiveRecord::Base
establish_connection(:adapter => "mysql",:host => "myip",:username => "myusername",:password => "mypassword",:database => "mydatabase" )
end This works Service.all #connects to mydatabase But i need something like that. Service.use(mydatabase1).all #connects to mydatabase1 Service.use(mydatabase2).all #connects to mydatabase2 How can i achieve this? Update Database names are dynamic. I want Service model to connect database dynamically. When i type Service.use(weeweweaszxc).all it has to use weeweweaszxc database.
ANSWER:
Try taking a look as this question over here. How to best handle per-Model database connections with ActiveRecord? They define the databases in the database.yml file like normal and call this in the model: class AnotherDatabase < ActiveRecord::Base self.abstract_class = true establish_connection "anotherbase_#{RAILS_ENV}" end Used info from Priit's answer | [
"ruby-on-rails"
] | 2 | 4 | 528 | 1 | 0 | 2011-06-10T15:31:20.930000 | 2011-06-10T15:35:58.557000 |
6,308,612 | 6,308,685 | Reasoning behind not using non-implemented Interfaces to hold constants? | In his book Effective Java, Joshua Bloch recommends against using Interfaces to hold constants, The constant interface pattern is a poor use of interfaces. That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class’s exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them. Worse, it represents a commitment: if in a future release the class is modified so that it no longer needs to use the con-stants, it still must implement the interface to ensure binary compatibility. If a nonfinal class implements a constant interface, all of its subclasses will have their namespaces polluted by the constants in the interface. His reasoning makes sense to me and it seems to be the prevailing logic whenever the question is brought up but it overlooks storing constants in interfaces and then NOT implementing them. For instance, public interface SomeInterface { public static final String FOO = "example"; }
public class SomeOtherClass { //notice that this class does not implement anything public void foo() { thisIsJustAnExample("Designed to be short", SomeInteface.FOO); } } I work with someone who uses this method all the time. I tend to use class with private constructors to hold my constants, but I've started using interfaces in this manner to keep our code a consistent style. Are there any reasons to not use interfaces in the way I've outlined above? Essentially it's a short hand that prevents you from having to make a class private, since an interface can not be initialized. | I don't think a class with a private constructor is any better than using an interface. What the quote says is that using implements ConstantInterface is not best pratice because this interface becomes part of the API. However, you can use static import or qualified names like SomeInteface.FOO of the values from the interface instead to avoid this issue. | Reasoning behind not using non-implemented Interfaces to hold constants? In his book Effective Java, Joshua Bloch recommends against using Interfaces to hold constants, The constant interface pattern is a poor use of interfaces. That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class’s exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them. Worse, it represents a commitment: if in a future release the class is modified so that it no longer needs to use the con-stants, it still must implement the interface to ensure binary compatibility. If a nonfinal class implements a constant interface, all of its subclasses will have their namespaces polluted by the constants in the interface. His reasoning makes sense to me and it seems to be the prevailing logic whenever the question is brought up but it overlooks storing constants in interfaces and then NOT implementing them. For instance, public interface SomeInterface { public static final String FOO = "example"; }
public class SomeOtherClass { //notice that this class does not implement anything public void foo() { thisIsJustAnExample("Designed to be short", SomeInteface.FOO); } } I work with someone who uses this method all the time. I tend to use class with private constructors to hold my constants, but I've started using interfaces in this manner to keep our code a consistent style. Are there any reasons to not use interfaces in the way I've outlined above? Essentially it's a short hand that prevents you from having to make a class private, since an interface can not be initialized. | TITLE:
Reasoning behind not using non-implemented Interfaces to hold constants?
QUESTION:
In his book Effective Java, Joshua Bloch recommends against using Interfaces to hold constants, The constant interface pattern is a poor use of interfaces. That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class’s exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them. Worse, it represents a commitment: if in a future release the class is modified so that it no longer needs to use the con-stants, it still must implement the interface to ensure binary compatibility. If a nonfinal class implements a constant interface, all of its subclasses will have their namespaces polluted by the constants in the interface. His reasoning makes sense to me and it seems to be the prevailing logic whenever the question is brought up but it overlooks storing constants in interfaces and then NOT implementing them. For instance, public interface SomeInterface { public static final String FOO = "example"; }
public class SomeOtherClass { //notice that this class does not implement anything public void foo() { thisIsJustAnExample("Designed to be short", SomeInteface.FOO); } } I work with someone who uses this method all the time. I tend to use class with private constructors to hold my constants, but I've started using interfaces in this manner to keep our code a consistent style. Are there any reasons to not use interfaces in the way I've outlined above? Essentially it's a short hand that prevents you from having to make a class private, since an interface can not be initialized.
ANSWER:
I don't think a class with a private constructor is any better than using an interface. What the quote says is that using implements ConstantInterface is not best pratice because this interface becomes part of the API. However, you can use static import or qualified names like SomeInteface.FOO of the values from the interface instead to avoid this issue. | [
"java",
"interface",
"constants"
] | 5 | 3 | 571 | 4 | 0 | 2011-06-10T15:31:34.453000 | 2011-06-10T15:36:05.750000 |
6,308,616 | 6,308,640 | C# return a string from another void | I'm pretty sure this is an easy one. I simply want to return a string from another void. public static void LinkWorker(string baseURLString) { // do some stuff here HTMLWork(baseURLStringCycle) --> this is where i need xstring returned foreach(string xyString in xstring.split('\n')) { } }
public static void HTMLWork(string baseURLStringCycle) { //do HTML work here // create x string string xString =; //the result of the htmlwork } | You do not want a void method, you want a method returning type string. public static string HTMLWork(string baseURLStringCycle) { //... return xString; } | C# return a string from another void I'm pretty sure this is an easy one. I simply want to return a string from another void. public static void LinkWorker(string baseURLString) { // do some stuff here HTMLWork(baseURLStringCycle) --> this is where i need xstring returned foreach(string xyString in xstring.split('\n')) { } }
public static void HTMLWork(string baseURLStringCycle) { //do HTML work here // create x string string xString =; //the result of the htmlwork } | TITLE:
C# return a string from another void
QUESTION:
I'm pretty sure this is an easy one. I simply want to return a string from another void. public static void LinkWorker(string baseURLString) { // do some stuff here HTMLWork(baseURLStringCycle) --> this is where i need xstring returned foreach(string xyString in xstring.split('\n')) { } }
public static void HTMLWork(string baseURLStringCycle) { //do HTML work here // create x string string xString =; //the result of the htmlwork }
ANSWER:
You do not want a void method, you want a method returning type string. public static string HTMLWork(string baseURLStringCycle) { //... return xString; } | [
"c#"
] | 0 | 9 | 24,658 | 8 | 0 | 2011-06-10T15:31:45.607000 | 2011-06-10T15:33:26.107000 |
6,308,633 | 6,308,684 | Is there a way to do two different functions? | For an example, if I want the user to do both click and keypress that will give the same output. I would not like to have two of the same codes. If I had something like $('#next').click(function(){ // code goes here }); I would like to also implement this $(document).keydown(function(e){ if (e.keyCode == 37) { alert( "left pressed" ); return false; } }); that will be part of the click. Any suggests? Thank you!! | function myFunc() { alert("left pressed"); }
$("#next").click(myFunc);
$(document).keypress(function(e) { if(e.keyCode == 37) myFunc(); }); You could also have myFunc() handle both events like so.. function myFunc(e) { // First we check to see if this event has a keyCode property // If so, then we need to check the value of that keyCode. // If it doesn't match the value we're trying to capture, // then we just "exit" the function by returning false. if(e.keyCode && e.keyCode!= 37) { return false; }
alert("left pressed"); }
// Since myFunc() handles both scenarios, we can // bind it to both objects. $("#next").click(myFunc); $(document).keypress(myFunc); | Is there a way to do two different functions? For an example, if I want the user to do both click and keypress that will give the same output. I would not like to have two of the same codes. If I had something like $('#next').click(function(){ // code goes here }); I would like to also implement this $(document).keydown(function(e){ if (e.keyCode == 37) { alert( "left pressed" ); return false; } }); that will be part of the click. Any suggests? Thank you!! | TITLE:
Is there a way to do two different functions?
QUESTION:
For an example, if I want the user to do both click and keypress that will give the same output. I would not like to have two of the same codes. If I had something like $('#next').click(function(){ // code goes here }); I would like to also implement this $(document).keydown(function(e){ if (e.keyCode == 37) { alert( "left pressed" ); return false; } }); that will be part of the click. Any suggests? Thank you!!
ANSWER:
function myFunc() { alert("left pressed"); }
$("#next").click(myFunc);
$(document).keypress(function(e) { if(e.keyCode == 37) myFunc(); }); You could also have myFunc() handle both events like so.. function myFunc(e) { // First we check to see if this event has a keyCode property // If so, then we need to check the value of that keyCode. // If it doesn't match the value we're trying to capture, // then we just "exit" the function by returning false. if(e.keyCode && e.keyCode!= 37) { return false; }
alert("left pressed"); }
// Since myFunc() handles both scenarios, we can // bind it to both objects. $("#next").click(myFunc); $(document).keypress(myFunc); | [
"jquery",
"javascript"
] | 4 | 5 | 96 | 4 | 0 | 2011-06-10T15:32:55.610000 | 2011-06-10T15:36:04.220000 |
6,308,653 | 6,308,695 | Why is the base class method called if the derived class overrides the method? | consider the following program: class Base { public: virtual void foo() const { cout << "Base::foo()" << endl; } };
class Derived: public Base { public: virtual void foo() { cout << "Derived::foo()" << endl; } };
void func(Base& obj) { obj.foo(); }
void main() { Derived d; func(d); // Base::foo() is printed } If I remove the const from the Base class foo method then Derived::foo() is called. I can't seem to understand this behavior. 1) What is the reason for this behavior? 2) Is this decided at compile time or runtime? Thanks | In the derived class, the function signature is this: virtual void foo(); //Derived::foo which doesn't mention const. Its a non-const member function, while the Base::foo is a const member function. They're two different functions, because const is a part of the function signature. virtual void foo() const; //Base::foo Derived class does NOT override this function, instead it adds another function. So the fix is this: class Derived: public Base { public: virtual void foo() const { cout << "Derived::foo()" << endl; } }; As const is a part of the function signature. So you must mention it when you intend to override base's foo. @davka's asked: so why the const version is selected over the non-const? Is there any rule or it just happened to be the first option? Its because the static type of obj is Base, and function name is resolved based on the static type of object. Base doesn't even have non-const version. So there is no question of it being selected or rejected. It doesn't exist in Base to begin with. void func(Base& obj) { obj.foo(); //calls Base::foo } However, if you change the above code to the following: void func(Derived & obj) { obj.foo(); //calls Derived:foo } Now non-const version will be selected, because Base::foo is hidden in Derived class. Since Derived::foo hides the Base::foo, so you cannot call the latter using an instance of Derived. Now, lets unhide Base::foo and do some more experiments. class Derived: public Base { public: using Base::foo; //<----------------this unhides Base::foo virtual void foo() { cout << "Derived::foo()" << endl; } }; Now in Derived, both functions (const as well as non-const version) are available, unhidden. Now few interesting questions. Since now Derived has both functions unhidden, which function will be called in each function below? void f(Derived& obj) { obj.foo(); //Which function? Base::foo or Derived::foo? } void g(const Derived & obj) { obj.foo(); //Which function? Base::foo or Derived::foo? } First one will call Derived::foo which is non-const version, and second one will call Base::foo which is const version. The reason is simple, with const object, only const functions can be invoked, but with non-const objects, both can be invoked, however non-const version is selected if its available. See online demo: http://www.ideone.com/955aY | Why is the base class method called if the derived class overrides the method? consider the following program: class Base { public: virtual void foo() const { cout << "Base::foo()" << endl; } };
class Derived: public Base { public: virtual void foo() { cout << "Derived::foo()" << endl; } };
void func(Base& obj) { obj.foo(); }
void main() { Derived d; func(d); // Base::foo() is printed } If I remove the const from the Base class foo method then Derived::foo() is called. I can't seem to understand this behavior. 1) What is the reason for this behavior? 2) Is this decided at compile time or runtime? Thanks | TITLE:
Why is the base class method called if the derived class overrides the method?
QUESTION:
consider the following program: class Base { public: virtual void foo() const { cout << "Base::foo()" << endl; } };
class Derived: public Base { public: virtual void foo() { cout << "Derived::foo()" << endl; } };
void func(Base& obj) { obj.foo(); }
void main() { Derived d; func(d); // Base::foo() is printed } If I remove the const from the Base class foo method then Derived::foo() is called. I can't seem to understand this behavior. 1) What is the reason for this behavior? 2) Is this decided at compile time or runtime? Thanks
ANSWER:
In the derived class, the function signature is this: virtual void foo(); //Derived::foo which doesn't mention const. Its a non-const member function, while the Base::foo is a const member function. They're two different functions, because const is a part of the function signature. virtual void foo() const; //Base::foo Derived class does NOT override this function, instead it adds another function. So the fix is this: class Derived: public Base { public: virtual void foo() const { cout << "Derived::foo()" << endl; } }; As const is a part of the function signature. So you must mention it when you intend to override base's foo. @davka's asked: so why the const version is selected over the non-const? Is there any rule or it just happened to be the first option? Its because the static type of obj is Base, and function name is resolved based on the static type of object. Base doesn't even have non-const version. So there is no question of it being selected or rejected. It doesn't exist in Base to begin with. void func(Base& obj) { obj.foo(); //calls Base::foo } However, if you change the above code to the following: void func(Derived & obj) { obj.foo(); //calls Derived:foo } Now non-const version will be selected, because Base::foo is hidden in Derived class. Since Derived::foo hides the Base::foo, so you cannot call the latter using an instance of Derived. Now, lets unhide Base::foo and do some more experiments. class Derived: public Base { public: using Base::foo; //<----------------this unhides Base::foo virtual void foo() { cout << "Derived::foo()" << endl; } }; Now in Derived, both functions (const as well as non-const version) are available, unhidden. Now few interesting questions. Since now Derived has both functions unhidden, which function will be called in each function below? void f(Derived& obj) { obj.foo(); //Which function? Base::foo or Derived::foo? } void g(const Derived & obj) { obj.foo(); //Which function? Base::foo or Derived::foo? } First one will call Derived::foo which is non-const version, and second one will call Base::foo which is const version. The reason is simple, with const object, only const functions can be invoked, but with non-const objects, both can be invoked, however non-const version is selected if its available. See online demo: http://www.ideone.com/955aY | [
"c++",
"inheritance"
] | 6 | 7 | 4,193 | 5 | 0 | 2011-06-10T15:34:01.190000 | 2011-06-10T15:36:49.273000 |
6,308,657 | 6,309,489 | NSNotification does not reach all Observers | I use NSNotification for a particular set of events. I have three views such that I have an "ADD" button on view 1 and clicking that makes me navigate from view 1 to view 2 to view 3 and again back to view 1. 1->2->3->1 I use NSNotification s to push a view controller if the ADD button on view 1 is clicked, and I update the other views respectively, based on the notification posted by View 1. When the notification is sent from view 1, only view 2 receives it. View 3 does not. How is this possible? The code for observers is EXACTLY the same on view 2 and view 3. This is the code for adding observers in view 2 and view 3: [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didPressAdd:) name:@"DidAddNotification" object:nil]; I also remove them in the dealloc() function properly. | Navigating back to 1 using navigation controller will remove 2 and 3. So in dealloc, add a log saying that the particular controller has stopped listening. You shall see that the listener is being deallocated after which it won't listen to notifications. Updated the sample to send a notification on return. | NSNotification does not reach all Observers I use NSNotification for a particular set of events. I have three views such that I have an "ADD" button on view 1 and clicking that makes me navigate from view 1 to view 2 to view 3 and again back to view 1. 1->2->3->1 I use NSNotification s to push a view controller if the ADD button on view 1 is clicked, and I update the other views respectively, based on the notification posted by View 1. When the notification is sent from view 1, only view 2 receives it. View 3 does not. How is this possible? The code for observers is EXACTLY the same on view 2 and view 3. This is the code for adding observers in view 2 and view 3: [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didPressAdd:) name:@"DidAddNotification" object:nil]; I also remove them in the dealloc() function properly. | TITLE:
NSNotification does not reach all Observers
QUESTION:
I use NSNotification for a particular set of events. I have three views such that I have an "ADD" button on view 1 and clicking that makes me navigate from view 1 to view 2 to view 3 and again back to view 1. 1->2->3->1 I use NSNotification s to push a view controller if the ADD button on view 1 is clicked, and I update the other views respectively, based on the notification posted by View 1. When the notification is sent from view 1, only view 2 receives it. View 3 does not. How is this possible? The code for observers is EXACTLY the same on view 2 and view 3. This is the code for adding observers in view 2 and view 3: [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didPressAdd:) name:@"DidAddNotification" object:nil]; I also remove them in the dealloc() function properly.
ANSWER:
Navigating back to 1 using navigation controller will remove 2 and 3. So in dealloc, add a log saying that the particular controller has stopped listening. You shall see that the listener is being deallocated after which it won't listen to notifications. Updated the sample to send a notification on return. | [
"objective-c",
"ios",
"cocoa-touch",
"uiviewcontroller",
"nsnotifications"
] | 3 | 3 | 1,157 | 2 | 0 | 2011-06-10T15:34:10.747000 | 2011-06-10T16:39:52.207000 |
6,308,667 | 6,308,716 | iPhone web-app parse html with PHP or JavaScript? | I'm making a web-app for iPhone/iPod touch. And need to load in a external HTML file and parse some data out of that HTML file. I can do this on the server (on a separate page) and echo the data with json. Then I load that page with AJAX after the web-app is loaded. But I can also load the complete HTML file with AJAX and parse the HTML to data with JavaScript. Which option would be faster? PS: There's no option to load the html file and parse it while you "load" the web-app. The web-app must be dynamically changing itself while already loaded. So having a possibility to refresh the data without restarting the web-app. | Loading the JSON from an AJAX call would be faster than parsing an HTML file in JavaScript (Since JSON is "near-native" in JS). NOTE: To qualify this answer, it would be faster for the client (iPhone/iPod). | iPhone web-app parse html with PHP or JavaScript? I'm making a web-app for iPhone/iPod touch. And need to load in a external HTML file and parse some data out of that HTML file. I can do this on the server (on a separate page) and echo the data with json. Then I load that page with AJAX after the web-app is loaded. But I can also load the complete HTML file with AJAX and parse the HTML to data with JavaScript. Which option would be faster? PS: There's no option to load the html file and parse it while you "load" the web-app. The web-app must be dynamically changing itself while already loaded. So having a possibility to refresh the data without restarting the web-app. | TITLE:
iPhone web-app parse html with PHP or JavaScript?
QUESTION:
I'm making a web-app for iPhone/iPod touch. And need to load in a external HTML file and parse some data out of that HTML file. I can do this on the server (on a separate page) and echo the data with json. Then I load that page with AJAX after the web-app is loaded. But I can also load the complete HTML file with AJAX and parse the HTML to data with JavaScript. Which option would be faster? PS: There's no option to load the html file and parse it while you "load" the web-app. The web-app must be dynamically changing itself while already loaded. So having a possibility to refresh the data without restarting the web-app.
ANSWER:
Loading the JSON from an AJAX call would be faster than parsing an HTML file in JavaScript (Since JSON is "near-native" in JS). NOTE: To qualify this answer, it would be faster for the client (iPhone/iPod). | [
"php",
"javascript",
"ajax",
"html-parsing",
"iphone-web-app"
] | 0 | 1 | 343 | 1 | 0 | 2011-06-10T15:34:51.090000 | 2011-06-10T15:38:50.580000 |
6,308,668 | 6,309,126 | Writing to a remote MSMQ | Okay, here is a very simple and fundamental question. If I have an application on windows machine A that wants to write to a queue on windows machine B, do I need to have MSMQ installed on machine A (even though there is no queue there)? I am just beginning to use queues for my applications and trying to figure some fundamentals out. Thanks | Yes, you need MSMQ installed locally to write to a remote queue. If you're writing to a private queue, take a look at this page which has useful information on how to format the queue name. If you're writing to a remote Transactional queue, then you need to make sure you specify that correctly (point 5) This is the article text: 1. When working with remote queues, the queue name in the format machinename\private$\queuename doesn't work. This results in an "invalid queue path" error. 2. The queue name has to be mentioned as FormatName:Direct=OS:machinename\\private$\\queuename. This is necessary since the queue access is internally done using the format name syntax only. The other friendly representation is converted to the FormatName and then used. When working with remote queues, unless there is an AD to resolve the queue name, the friendly name won't work. Check out documentation for details. For Eg. MessageQueue rmQ = new MessageQueue ("FormatName:Direct=OS:machinename\\private$\\queue"); rmQ.Send("sent to regular queue - Atul"); 3. Further to previous point, note that FormatName is case sensitive. If you mention the earlier string as FORMATNAME:Direct=OS:machinename\\private$\\queuename, it won't work. Surprisingly, there is no error thrown in this case. "FormatName" part of the string seems to be the only case sensitive part. Others can appear in different case. For eg. You can write "DIRECT". 4. In case you want to use the machine's IP address the syntax will be FormatName:Direct=TCP:ipaddress\\private$\\queuename. For Eg. MessageQueue rmQ = new MessageQueue ("FormatName:Direct=TCP:121.0.0.1\\private$\\queue"); rmQ.Send("sent to regular queue - Atul"); 5. The transactional properties of the queue instance you create in code should match with that of the queue you are trying to send the message to. So in the earlier examples, I was sending message to a non-transactional queue. To send to a transactional queue, the code would be MessageQueue rmTxnQ = new MessageQueue ("FormatName:Direct=OS:machinename\\private$\\queue"); rmTxnQ.Send("sent to Txn queue - Atul", MessageQueueTransactionType.Single); If the transactional properties don't match, the message will not be delivered. The surprising part is again, I didn't get any error, and the message just disappeared 6. Finally, when you send messages to remote queue, a temporary outgoing queue is created on your own machine. This is used in case the remote queue is unavailable. If you go to the computer Management console (compmgmt.msc), and expand the Services and Applications / Message Queuing / Outgoing Queues, you would see these queues. The right side of the console should show the details including the state (connected or not) and the IP address(es) for the next hop(s). | Writing to a remote MSMQ Okay, here is a very simple and fundamental question. If I have an application on windows machine A that wants to write to a queue on windows machine B, do I need to have MSMQ installed on machine A (even though there is no queue there)? I am just beginning to use queues for my applications and trying to figure some fundamentals out. Thanks | TITLE:
Writing to a remote MSMQ
QUESTION:
Okay, here is a very simple and fundamental question. If I have an application on windows machine A that wants to write to a queue on windows machine B, do I need to have MSMQ installed on machine A (even though there is no queue there)? I am just beginning to use queues for my applications and trying to figure some fundamentals out. Thanks
ANSWER:
Yes, you need MSMQ installed locally to write to a remote queue. If you're writing to a private queue, take a look at this page which has useful information on how to format the queue name. If you're writing to a remote Transactional queue, then you need to make sure you specify that correctly (point 5) This is the article text: 1. When working with remote queues, the queue name in the format machinename\private$\queuename doesn't work. This results in an "invalid queue path" error. 2. The queue name has to be mentioned as FormatName:Direct=OS:machinename\\private$\\queuename. This is necessary since the queue access is internally done using the format name syntax only. The other friendly representation is converted to the FormatName and then used. When working with remote queues, unless there is an AD to resolve the queue name, the friendly name won't work. Check out documentation for details. For Eg. MessageQueue rmQ = new MessageQueue ("FormatName:Direct=OS:machinename\\private$\\queue"); rmQ.Send("sent to regular queue - Atul"); 3. Further to previous point, note that FormatName is case sensitive. If you mention the earlier string as FORMATNAME:Direct=OS:machinename\\private$\\queuename, it won't work. Surprisingly, there is no error thrown in this case. "FormatName" part of the string seems to be the only case sensitive part. Others can appear in different case. For eg. You can write "DIRECT". 4. In case you want to use the machine's IP address the syntax will be FormatName:Direct=TCP:ipaddress\\private$\\queuename. For Eg. MessageQueue rmQ = new MessageQueue ("FormatName:Direct=TCP:121.0.0.1\\private$\\queue"); rmQ.Send("sent to regular queue - Atul"); 5. The transactional properties of the queue instance you create in code should match with that of the queue you are trying to send the message to. So in the earlier examples, I was sending message to a non-transactional queue. To send to a transactional queue, the code would be MessageQueue rmTxnQ = new MessageQueue ("FormatName:Direct=OS:machinename\\private$\\queue"); rmTxnQ.Send("sent to Txn queue - Atul", MessageQueueTransactionType.Single); If the transactional properties don't match, the message will not be delivered. The surprising part is again, I didn't get any error, and the message just disappeared 6. Finally, when you send messages to remote queue, a temporary outgoing queue is created on your own machine. This is used in case the remote queue is unavailable. If you go to the computer Management console (compmgmt.msc), and expand the Services and Applications / Message Queuing / Outgoing Queues, you would see these queues. The right side of the console should show the details including the state (connected or not) and the IP address(es) for the next hop(s). | [
".net",
"windows",
"msmq"
] | 26 | 49 | 31,846 | 4 | 0 | 2011-06-10T15:34:56.503000 | 2011-06-10T16:11:13.890000 |
6,308,675 | 6,308,879 | How to track which network ports any program is trying to use? | I want to see what kind of connections any program is doing, which port and see the program exe path etc. I'm trying to achieve some sort of firewall notification system, it would pop up a window for me to tell that this and that port needs to be opened in order the program could work properly. How do i get started on this? | You'll need to hook the socket API for each process you're willing to provide this functionality, or write a filter using WFP and a client application that receive the informations from your filter and shows a notification window. | How to track which network ports any program is trying to use? I want to see what kind of connections any program is doing, which port and see the program exe path etc. I'm trying to achieve some sort of firewall notification system, it would pop up a window for me to tell that this and that port needs to be opened in order the program could work properly. How do i get started on this? | TITLE:
How to track which network ports any program is trying to use?
QUESTION:
I want to see what kind of connections any program is doing, which port and see the program exe path etc. I'm trying to achieve some sort of firewall notification system, it would pop up a window for me to tell that this and that port needs to be opened in order the program could work properly. How do i get started on this?
ANSWER:
You'll need to hook the socket API for each process you're willing to provide this functionality, or write a filter using WFP and a client application that receive the informations from your filter and shows a notification window. | [
"c++",
"windows",
"winapi",
"networking",
"network-programming"
] | 1 | 1 | 349 | 3 | 0 | 2011-06-10T15:35:22.753000 | 2011-06-10T15:51:22.580000 |
6,308,687 | 6,308,702 | PHP number format | I have this string: 000000000000100 and need to convert it to: 1,00 So, the rules are: Divide the number by 100 and use a comma as decimal separator Strip leading zeros Keep two decimals | From the PHP Manual page on number_format: string number_format ( float $number, int $decimals = 0, string $dec_point = '.', string $thousands_sep = ',' ) If you want numbers like 123456 be formatted as 1234,45, use: echo number_format($number / 100, 2, ",", ""); If you need a dot as thousands separator ( 1.234,56 ): echo number_format($number / 100, 2, ",", "."); The zeros are automatically removed by PHP when converting the string to a number. | PHP number format I have this string: 000000000000100 and need to convert it to: 1,00 So, the rules are: Divide the number by 100 and use a comma as decimal separator Strip leading zeros Keep two decimals | TITLE:
PHP number format
QUESTION:
I have this string: 000000000000100 and need to convert it to: 1,00 So, the rules are: Divide the number by 100 and use a comma as decimal separator Strip leading zeros Keep two decimals
ANSWER:
From the PHP Manual page on number_format: string number_format ( float $number, int $decimals = 0, string $dec_point = '.', string $thousands_sep = ',' ) If you want numbers like 123456 be formatted as 1234,45, use: echo number_format($number / 100, 2, ",", ""); If you need a dot as thousands separator ( 1.234,56 ): echo number_format($number / 100, 2, ",", "."); The zeros are automatically removed by PHP when converting the string to a number. | [
"php",
"number-formatting"
] | 6 | 21 | 21,721 | 2 | 0 | 2011-06-10T15:36:10.443000 | 2011-06-10T15:37:29.937000 |
6,308,708 | 6,308,799 | Making only portion of screen modal with jQuery UI | Is there any way to create a modal 'scope' for jQuery dialogs? As a somewhat contrived example, I've got a page: Console I want to create some modal dialogs for the mainContent area. When the dialog is open, I want to not allow interaction with the mainContent area, but still allow interaction with the toolbar and footer. Or if a page has multiple mainContent-like divs, each one has there own independent set of modal dialogs that still allow interaction with the other divs. I know how to create modal dialogs with the jQuery UI library; my question is specifically about applying modality to a section of the page rather than the entire page, either using this library, or in a way that easily complements this library. | Simple solution would be to have a hidden div that would act as an overlay. It would always have the same dimensions and positioning as your "mainContent" div. Then show that div over the top of your content by using the z-index. Then place your modal on top of the overlay. Net effect, everything will be covered in main content area by the overlay but your modal will rest on top of the overlay and thus the user can only interact with it. Edits: Z-index management: I would just set the overlay z-index to a high base number to avoid conflicts with other z-indices. Then whenever showing the modal, just have jquery selectors that look for shown overlays and increment the modal z-index by one of that number..Overlay { z-index: 200; }.Modal { //... }
function ShowModal(modalId) { var maxZIndex = 200; $('.Overlay:visible').each(function() //find all visible overlays { var currZIndex = $(this).attr('z-index'); maxZIndex = currZIndex > maxZIndex? currZIndex: maxZIndex; //max, min alg. } $('#' + modalId).attr('z-index', maxZIndex + 1); //... do some positioning of modal here $('#' + modalId).show(); } Positioning: You will need to write javascript to position your overlay over the desired area. I would think using absolute positioning will make this easy. Then obviously you should position the modal div in the center of the overlay div. The calculations aren't really that hard to position something in a centered fashion. Let me know if you want my take on doing that piece. | Making only portion of screen modal with jQuery UI Is there any way to create a modal 'scope' for jQuery dialogs? As a somewhat contrived example, I've got a page: Console I want to create some modal dialogs for the mainContent area. When the dialog is open, I want to not allow interaction with the mainContent area, but still allow interaction with the toolbar and footer. Or if a page has multiple mainContent-like divs, each one has there own independent set of modal dialogs that still allow interaction with the other divs. I know how to create modal dialogs with the jQuery UI library; my question is specifically about applying modality to a section of the page rather than the entire page, either using this library, or in a way that easily complements this library. | TITLE:
Making only portion of screen modal with jQuery UI
QUESTION:
Is there any way to create a modal 'scope' for jQuery dialogs? As a somewhat contrived example, I've got a page: Console I want to create some modal dialogs for the mainContent area. When the dialog is open, I want to not allow interaction with the mainContent area, but still allow interaction with the toolbar and footer. Or if a page has multiple mainContent-like divs, each one has there own independent set of modal dialogs that still allow interaction with the other divs. I know how to create modal dialogs with the jQuery UI library; my question is specifically about applying modality to a section of the page rather than the entire page, either using this library, or in a way that easily complements this library.
ANSWER:
Simple solution would be to have a hidden div that would act as an overlay. It would always have the same dimensions and positioning as your "mainContent" div. Then show that div over the top of your content by using the z-index. Then place your modal on top of the overlay. Net effect, everything will be covered in main content area by the overlay but your modal will rest on top of the overlay and thus the user can only interact with it. Edits: Z-index management: I would just set the overlay z-index to a high base number to avoid conflicts with other z-indices. Then whenever showing the modal, just have jquery selectors that look for shown overlays and increment the modal z-index by one of that number..Overlay { z-index: 200; }.Modal { //... }
function ShowModal(modalId) { var maxZIndex = 200; $('.Overlay:visible').each(function() //find all visible overlays { var currZIndex = $(this).attr('z-index'); maxZIndex = currZIndex > maxZIndex? currZIndex: maxZIndex; //max, min alg. } $('#' + modalId).attr('z-index', maxZIndex + 1); //... do some positioning of modal here $('#' + modalId).show(); } Positioning: You will need to write javascript to position your overlay over the desired area. I would think using absolute positioning will make this easy. Then obviously you should position the modal div in the center of the overlay div. The calculations aren't really that hard to position something in a centered fashion. Let me know if you want my take on doing that piece. | [
"javascript",
"jquery-ui",
"modal-dialog"
] | 7 | 3 | 2,045 | 1 | 0 | 2011-06-10T15:38:11.693000 | 2011-06-10T15:45:45.720000 |
6,308,710 | 6,308,743 | Setting properties with {} braces when instantiating | Anyone knows why the following will not compile? The setter for ID is supposed to be private for both classes, so why can we instantiate ClassA but not ClassB? public class ClassA { public string ID { get; private set; }
public void test() { var instanceA = new ClassA() { ID = "42" }; var instanceB = new ClassB() { ID = "43" }; }
public class ClassB { public string ID { get; private set; } } } Thanks | test() is a member of ClassA, so it has access to the private members (and the setter) of A. It does not have access to the private members or setters of ClassB, hence the error on instanceB but not instanceA. For more on accessibility of private members, I encourage you to see this answer on a related question. | Setting properties with {} braces when instantiating Anyone knows why the following will not compile? The setter for ID is supposed to be private for both classes, so why can we instantiate ClassA but not ClassB? public class ClassA { public string ID { get; private set; }
public void test() { var instanceA = new ClassA() { ID = "42" }; var instanceB = new ClassB() { ID = "43" }; }
public class ClassB { public string ID { get; private set; } } } Thanks | TITLE:
Setting properties with {} braces when instantiating
QUESTION:
Anyone knows why the following will not compile? The setter for ID is supposed to be private for both classes, so why can we instantiate ClassA but not ClassB? public class ClassA { public string ID { get; private set; }
public void test() { var instanceA = new ClassA() { ID = "42" }; var instanceB = new ClassB() { ID = "43" }; }
public class ClassB { public string ID { get; private set; } } } Thanks
ANSWER:
test() is a member of ClassA, so it has access to the private members (and the setter) of A. It does not have access to the private members or setters of ClassB, hence the error on instanceB but not instanceA. For more on accessibility of private members, I encourage you to see this answer on a related question. | [
"c#",
"instantiation"
] | 4 | 10 | 4,787 | 3 | 0 | 2011-06-10T15:38:24.437000 | 2011-06-10T15:41:00.083000 |
6,308,714 | 6,309,042 | Windows LoadMenu error: "The specified resource name cannot be found in the image file." | I'm writing a program that, among other things, needs to display a context menu on right-click. I'm trapping WM_NOTIFY, the identifier of the control being clicked on, and NM_RCLICK. That all works great. The problem comes in when I'm processing that right-click: case NM_RCLICK: { HMENU Popup = LoadMenu(0, MAKEINTRESOURCE(IDR_NED_MENU)); if (!Popup ) { DWORD err = GetLastError(); char* buf; FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_ALLOCATE_BUFFER, 0, err, 0, buf, 1<<19, 0); _ERROR("LoadMenu(0, MAKEINTRESOURCE(IDR_NED_MENU)); Error '%s' thrown; no menu loaded.", buf); delete [] buf; } Popup = GetSubMenu(Popup, 0); CheckMenuItem(Popup, 1, MF_CHECKED|MF_BYPOSITION);
POINT Point; GetCursorPos(&Point);
switch (TrackPopupMenu(Popup, TPM_LEFTALIGN | TPM_LEFTBUTTON | TPM_RETURNCMD, Point.x, Point.y, 0, GetActiveWindow(), NULL)) { //... Primarily, LoadMenu(0, MAKEINTRESOURCE(IDR_NED_MENU)); is returning NULL, and I'm getting an error message that states that "The specified resource name cannot be found in the image file." Now, IDR_NED_MENU is the ID of a menu I have in the.rc file, and I've included the corresponding.rc.h file in this.cpp file. The actual dialog window IDs contained in the same.rc file work perfectly. This code is further copied and pasted from another project where the LoadMenu call worked perfectly: I did recreate the IDR_NED_MENU from scratch, though, and the IDs are somewhat different (but they do match between the.rc file and the.cpp file that has the code snippet I've pasted here); originally I'd accidentally created the menu in a separate.rc file so I sought to rectify that here. I noticed that in Visual Studio's Resource View, the dialogs are contained in the Dialog folder, while this is contained in the Menu folder (sensible), but I'm not sure what, if any, difference that makes. Why would I be getting this error? Why can't it find IDR_NED_MENU? I'm using Visual Studio 2010, and this is not an MFC project. I'm not sure what, if any, other relevant details I should include; let me know in comments and I'll edit-update. Thanks. | The first parameter to LoadMenu must be a handle to your executable image where the resource resides. The handle is the first HINSTANCE that you get in WinMain. Alternatively you can obtain it by a call to GetModuleHandle(0). | Windows LoadMenu error: "The specified resource name cannot be found in the image file." I'm writing a program that, among other things, needs to display a context menu on right-click. I'm trapping WM_NOTIFY, the identifier of the control being clicked on, and NM_RCLICK. That all works great. The problem comes in when I'm processing that right-click: case NM_RCLICK: { HMENU Popup = LoadMenu(0, MAKEINTRESOURCE(IDR_NED_MENU)); if (!Popup ) { DWORD err = GetLastError(); char* buf; FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_ALLOCATE_BUFFER, 0, err, 0, buf, 1<<19, 0); _ERROR("LoadMenu(0, MAKEINTRESOURCE(IDR_NED_MENU)); Error '%s' thrown; no menu loaded.", buf); delete [] buf; } Popup = GetSubMenu(Popup, 0); CheckMenuItem(Popup, 1, MF_CHECKED|MF_BYPOSITION);
POINT Point; GetCursorPos(&Point);
switch (TrackPopupMenu(Popup, TPM_LEFTALIGN | TPM_LEFTBUTTON | TPM_RETURNCMD, Point.x, Point.y, 0, GetActiveWindow(), NULL)) { //... Primarily, LoadMenu(0, MAKEINTRESOURCE(IDR_NED_MENU)); is returning NULL, and I'm getting an error message that states that "The specified resource name cannot be found in the image file." Now, IDR_NED_MENU is the ID of a menu I have in the.rc file, and I've included the corresponding.rc.h file in this.cpp file. The actual dialog window IDs contained in the same.rc file work perfectly. This code is further copied and pasted from another project where the LoadMenu call worked perfectly: I did recreate the IDR_NED_MENU from scratch, though, and the IDs are somewhat different (but they do match between the.rc file and the.cpp file that has the code snippet I've pasted here); originally I'd accidentally created the menu in a separate.rc file so I sought to rectify that here. I noticed that in Visual Studio's Resource View, the dialogs are contained in the Dialog folder, while this is contained in the Menu folder (sensible), but I'm not sure what, if any, difference that makes. Why would I be getting this error? Why can't it find IDR_NED_MENU? I'm using Visual Studio 2010, and this is not an MFC project. I'm not sure what, if any, other relevant details I should include; let me know in comments and I'll edit-update. Thanks. | TITLE:
Windows LoadMenu error: "The specified resource name cannot be found in the image file."
QUESTION:
I'm writing a program that, among other things, needs to display a context menu on right-click. I'm trapping WM_NOTIFY, the identifier of the control being clicked on, and NM_RCLICK. That all works great. The problem comes in when I'm processing that right-click: case NM_RCLICK: { HMENU Popup = LoadMenu(0, MAKEINTRESOURCE(IDR_NED_MENU)); if (!Popup ) { DWORD err = GetLastError(); char* buf; FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_ALLOCATE_BUFFER, 0, err, 0, buf, 1<<19, 0); _ERROR("LoadMenu(0, MAKEINTRESOURCE(IDR_NED_MENU)); Error '%s' thrown; no menu loaded.", buf); delete [] buf; } Popup = GetSubMenu(Popup, 0); CheckMenuItem(Popup, 1, MF_CHECKED|MF_BYPOSITION);
POINT Point; GetCursorPos(&Point);
switch (TrackPopupMenu(Popup, TPM_LEFTALIGN | TPM_LEFTBUTTON | TPM_RETURNCMD, Point.x, Point.y, 0, GetActiveWindow(), NULL)) { //... Primarily, LoadMenu(0, MAKEINTRESOURCE(IDR_NED_MENU)); is returning NULL, and I'm getting an error message that states that "The specified resource name cannot be found in the image file." Now, IDR_NED_MENU is the ID of a menu I have in the.rc file, and I've included the corresponding.rc.h file in this.cpp file. The actual dialog window IDs contained in the same.rc file work perfectly. This code is further copied and pasted from another project where the LoadMenu call worked perfectly: I did recreate the IDR_NED_MENU from scratch, though, and the IDs are somewhat different (but they do match between the.rc file and the.cpp file that has the code snippet I've pasted here); originally I'd accidentally created the menu in a separate.rc file so I sought to rectify that here. I noticed that in Visual Studio's Resource View, the dialogs are contained in the Dialog folder, while this is contained in the Menu folder (sensible), but I'm not sure what, if any, difference that makes. Why would I be getting this error? Why can't it find IDR_NED_MENU? I'm using Visual Studio 2010, and this is not an MFC project. I'm not sure what, if any, other relevant details I should include; let me know in comments and I'll edit-update. Thanks.
ANSWER:
The first parameter to LoadMenu must be a handle to your executable image where the resource resides. The handle is the first HINSTANCE that you get in WinMain. Alternatively you can obtain it by a call to GetModuleHandle(0). | [
"c++",
"windows",
"resources",
"contextmenu"
] | 1 | 1 | 4,756 | 1 | 0 | 2011-06-10T15:38:39.603000 | 2011-06-10T16:04:35.143000 |
6,308,738 | 6,308,790 | iOS SDK: Conjoined Text Fields | I don't know if I'm completely missing the boat here or what, but I can't figure out how to achieve conjoined email/password text fields like on the flow login screen. Any help is appreciated! FYI: I'm using XCode 3.2.5 | It's a custom table view cell with a label and a text field in a grouped table view probably with a single section and two rows one of which is for username and other for password. The logo could be the table view's header. | iOS SDK: Conjoined Text Fields I don't know if I'm completely missing the boat here or what, but I can't figure out how to achieve conjoined email/password text fields like on the flow login screen. Any help is appreciated! FYI: I'm using XCode 3.2.5 | TITLE:
iOS SDK: Conjoined Text Fields
QUESTION:
I don't know if I'm completely missing the boat here or what, but I can't figure out how to achieve conjoined email/password text fields like on the flow login screen. Any help is appreciated! FYI: I'm using XCode 3.2.5
ANSWER:
It's a custom table view cell with a label and a text field in a grouped table view probably with a single section and two rows one of which is for username and other for password. The logo could be the table view's header. | [
"iphone",
"ios",
"xcode",
"interface-builder"
] | 5 | 4 | 1,764 | 3 | 0 | 2011-06-10T15:40:25.083000 | 2011-06-10T15:44:50.590000 |
6,308,744 | 6,309,372 | How do I deploy a VBA Excel Add-In (foo.xlam) using an msi installer? | I am a C# developer who is bundling a colleague's VBA Excel Add-In (.xlam file) with my msi installer (built using a VS Deployment project if that matters). The.xlam is placed in the application folder (C:\Program Files (x86)\MyCompany\TheProduct) directory. Users are forced to navigate to Excel Options > Add-Ins > Manage Excel Add-Ins Go... > Browse and are then forced to navigate to the install directory listed above. The Browse screen default directory is %APPDATA%\Microsoft\AddIns. Is there a way for me to automatically enable this VBA Add-In without all of the clicking? Thanks in advance, Frank | Windows Installer doesn't have direct support for this. So either you use some custom actions or you buy a tool which offers direct support for installing Office add-ins. | How do I deploy a VBA Excel Add-In (foo.xlam) using an msi installer? I am a C# developer who is bundling a colleague's VBA Excel Add-In (.xlam file) with my msi installer (built using a VS Deployment project if that matters). The.xlam is placed in the application folder (C:\Program Files (x86)\MyCompany\TheProduct) directory. Users are forced to navigate to Excel Options > Add-Ins > Manage Excel Add-Ins Go... > Browse and are then forced to navigate to the install directory listed above. The Browse screen default directory is %APPDATA%\Microsoft\AddIns. Is there a way for me to automatically enable this VBA Add-In without all of the clicking? Thanks in advance, Frank | TITLE:
How do I deploy a VBA Excel Add-In (foo.xlam) using an msi installer?
QUESTION:
I am a C# developer who is bundling a colleague's VBA Excel Add-In (.xlam file) with my msi installer (built using a VS Deployment project if that matters). The.xlam is placed in the application folder (C:\Program Files (x86)\MyCompany\TheProduct) directory. Users are forced to navigate to Excel Options > Add-Ins > Manage Excel Add-Ins Go... > Browse and are then forced to navigate to the install directory listed above. The Browse screen default directory is %APPDATA%\Microsoft\AddIns. Is there a way for me to automatically enable this VBA Add-In without all of the clicking? Thanks in advance, Frank
ANSWER:
Windows Installer doesn't have direct support for this. So either you use some custom actions or you buy a tool which offers direct support for installing Office add-ins. | [
"excel",
"windows-installer",
"vba"
] | 5 | 1 | 8,592 | 4 | 0 | 2011-06-10T15:41:03.893000 | 2011-06-10T16:31:00.673000 |
6,308,757 | 6,309,152 | What happens during a display mode change? | What happens during a display mode change (resolution, depth) on an ordinary computer? (classical stationarys and laptops) It might not be so trivial since video cards are so different, but one thing is common to all of them: The screen goes black (understandable since the signal is turned off) It takes many seconds for the signal to return with the new mode and if it is under D3D or GL: The graphics device is lost and all VRAM objects must be reloaded, making the mode change take even longer Can someone explain the underlying nature of this, and specifically why a display mode change is not a trivial reallocation of the backbuffer(s) and takes such a "long" time? | The only thing that actually changes are the settings of the so called RAMDAC (a Digital Analog Converter directly attached to the video RAM), well today with digital connections it's more like a RAMTX (a DVI/HDMI/DisplayPort Transmitter attached to the video RAM). DOS graphics programmer veterans probably remember the fights between the RAMDAC, the specification and the woes of one's own code. It actually doesn't take seconds until the signal returns. This is a rather quick process, but most display devices take their time to synchronize with the new signal parameters. Actually with well written drivers the change happens almost immediately, between vertical blanks. A few years ago, when the displays were, errr, stupider and analogue, after changing the video mode settings, one could see the picture going berserk for a short moment, until the display resynchronized (maybe I should take a video of this, while I still own equipment capable of this). Since what actually is going on is just a change of RAMDAC settings there's also not neccesary data lost as long as the basic parameters stays the same: Number of Bits per Pixel, number of components per pixel and pixel stride. And in fact OpenGL contexts usually don't loose their data with an video mode change. Of course visible framebuffer layouts change, but that happens also when moving the window around. DirectX Graphics is a bit of different story, though. There is device exclusive access and whenever switching between Direct3D fullscreen mode and regular desktop mode all graphics objects are swapped, so that's the reason for DirectX Graphics being so laggy when switching from/to a game to the Windows desktop. If the pixel data format changes it usually requires a full reinitialization of the visible framebuffer, but today GPUs are exceptionally good in maping heterogenous pixel formats into a target framebuffer, so no delays neccesary there, too. | What happens during a display mode change? What happens during a display mode change (resolution, depth) on an ordinary computer? (classical stationarys and laptops) It might not be so trivial since video cards are so different, but one thing is common to all of them: The screen goes black (understandable since the signal is turned off) It takes many seconds for the signal to return with the new mode and if it is under D3D or GL: The graphics device is lost and all VRAM objects must be reloaded, making the mode change take even longer Can someone explain the underlying nature of this, and specifically why a display mode change is not a trivial reallocation of the backbuffer(s) and takes such a "long" time? | TITLE:
What happens during a display mode change?
QUESTION:
What happens during a display mode change (resolution, depth) on an ordinary computer? (classical stationarys and laptops) It might not be so trivial since video cards are so different, but one thing is common to all of them: The screen goes black (understandable since the signal is turned off) It takes many seconds for the signal to return with the new mode and if it is under D3D or GL: The graphics device is lost and all VRAM objects must be reloaded, making the mode change take even longer Can someone explain the underlying nature of this, and specifically why a display mode change is not a trivial reallocation of the backbuffer(s) and takes such a "long" time?
ANSWER:
The only thing that actually changes are the settings of the so called RAMDAC (a Digital Analog Converter directly attached to the video RAM), well today with digital connections it's more like a RAMTX (a DVI/HDMI/DisplayPort Transmitter attached to the video RAM). DOS graphics programmer veterans probably remember the fights between the RAMDAC, the specification and the woes of one's own code. It actually doesn't take seconds until the signal returns. This is a rather quick process, but most display devices take their time to synchronize with the new signal parameters. Actually with well written drivers the change happens almost immediately, between vertical blanks. A few years ago, when the displays were, errr, stupider and analogue, after changing the video mode settings, one could see the picture going berserk for a short moment, until the display resynchronized (maybe I should take a video of this, while I still own equipment capable of this). Since what actually is going on is just a change of RAMDAC settings there's also not neccesary data lost as long as the basic parameters stays the same: Number of Bits per Pixel, number of components per pixel and pixel stride. And in fact OpenGL contexts usually don't loose their data with an video mode change. Of course visible framebuffer layouts change, but that happens also when moving the window around. DirectX Graphics is a bit of different story, though. There is device exclusive access and whenever switching between Direct3D fullscreen mode and regular desktop mode all graphics objects are swapped, so that's the reason for DirectX Graphics being so laggy when switching from/to a game to the Windows desktop. If the pixel data format changes it usually requires a full reinitialization of the visible framebuffer, but today GPUs are exceptionally good in maping heterogenous pixel formats into a target framebuffer, so no delays neccesary there, too. | [
"windows",
"opengl",
"graphics",
"direct3d"
] | 14 | 13 | 574 | 1 | 0 | 2011-06-10T15:42:16.957000 | 2011-06-10T16:13:22.533000 |
6,308,772 | 6,309,130 | How to center align a view? | I need to lay a variable number of views (may just be one) next to each other like in LinearLayout. But I want the whole arrangement to be center aligned. The views should be next to each other. But the whole arrangement should be equidistant from the left and right edge of the screen or the containing parent. How can I accomplish this? | You will have to wrap your views inside a LinearLayout and your linear layout inside something else: etc... Make sure all your views use android:layout_width="wrap_content". If you are working with RelativeLayout, it will be: | How to center align a view? I need to lay a variable number of views (may just be one) next to each other like in LinearLayout. But I want the whole arrangement to be center aligned. The views should be next to each other. But the whole arrangement should be equidistant from the left and right edge of the screen or the containing parent. How can I accomplish this? | TITLE:
How to center align a view?
QUESTION:
I need to lay a variable number of views (may just be one) next to each other like in LinearLayout. But I want the whole arrangement to be center aligned. The views should be next to each other. But the whole arrangement should be equidistant from the left and right edge of the screen or the containing parent. How can I accomplish this?
ANSWER:
You will have to wrap your views inside a LinearLayout and your linear layout inside something else: etc... Make sure all your views use android:layout_width="wrap_content". If you are working with RelativeLayout, it will be: | [
"android",
"android-layout"
] | 10 | 23 | 32,245 | 3 | 0 | 2011-06-10T15:43:23.557000 | 2011-06-10T16:11:15.757000 |
6,308,778 | 6,308,822 | MS Access query - select most recent date | I have a query I'm designing which grabs data from multiple different tables. In MS Access 2010, how would I create one of the query columns so that it returns the most recent date out of a series of dates, for each user in the table: Sample data from table: userid: | appointment: 000001 | 05/10/2009 000001 | 05/10/2010 000001 | 05/11/2010 000002 | 05/12/2009 000002 | 30/12/2010 expected output for field query: userid: | appointment: 000001 | 05/11/2010 000002 | 30/12/2010 | SELECT userid, Max(appointment) AS most_recent FROM YourTable GROUP BY userid; | MS Access query - select most recent date I have a query I'm designing which grabs data from multiple different tables. In MS Access 2010, how would I create one of the query columns so that it returns the most recent date out of a series of dates, for each user in the table: Sample data from table: userid: | appointment: 000001 | 05/10/2009 000001 | 05/10/2010 000001 | 05/11/2010 000002 | 05/12/2009 000002 | 30/12/2010 expected output for field query: userid: | appointment: 000001 | 05/11/2010 000002 | 30/12/2010 | TITLE:
MS Access query - select most recent date
QUESTION:
I have a query I'm designing which grabs data from multiple different tables. In MS Access 2010, how would I create one of the query columns so that it returns the most recent date out of a series of dates, for each user in the table: Sample data from table: userid: | appointment: 000001 | 05/10/2009 000001 | 05/10/2010 000001 | 05/11/2010 000002 | 05/12/2009 000002 | 30/12/2010 expected output for field query: userid: | appointment: 000001 | 05/11/2010 000002 | 30/12/2010
ANSWER:
SELECT userid, Max(appointment) AS most_recent FROM YourTable GROUP BY userid; | [
"date",
"ms-access"
] | 4 | 5 | 16,602 | 2 | 0 | 2011-06-10T15:43:50.817000 | 2011-06-10T15:47:23.993000 |
6,308,782 | 6,308,793 | Convert JNI types to Native types | While there is documentation regarding turning a jstring to a native string ( string nativeString = env->GetStringUTFChars(jStringVariable, NULL); ) I can't find an example which will convert a jboolean to a bool or a jint to an int. Can anyone suggest how this is achieved? | You just need to cast jint to int using C style casts. Same for jboolean to bool (if you're using C99 bool type) or to uint8_t (if you're using std int types) or to unsigned char. Open $NDK_ROOT/platforms/android-8/arch-arm/usr/include/jni.h and you'll see jint, jboolean etc are just typedef s. | Convert JNI types to Native types While there is documentation regarding turning a jstring to a native string ( string nativeString = env->GetStringUTFChars(jStringVariable, NULL); ) I can't find an example which will convert a jboolean to a bool or a jint to an int. Can anyone suggest how this is achieved? | TITLE:
Convert JNI types to Native types
QUESTION:
While there is documentation regarding turning a jstring to a native string ( string nativeString = env->GetStringUTFChars(jStringVariable, NULL); ) I can't find an example which will convert a jboolean to a bool or a jint to an int. Can anyone suggest how this is achieved?
ANSWER:
You just need to cast jint to int using C style casts. Same for jboolean to bool (if you're using C99 bool type) or to uint8_t (if you're using std int types) or to unsigned char. Open $NDK_ROOT/platforms/android-8/arch-arm/usr/include/jni.h and you'll see jint, jboolean etc are just typedef s. | [
"java-native-interface",
"android-ndk"
] | 55 | 66 | 66,429 | 6 | 0 | 2011-06-10T15:44:09.507000 | 2011-06-10T15:45:18.100000 |
6,308,794 | 6,308,904 | @Html.ValidationMessageFor() custom validationMessage always shown | I am trying to use a different message for @Html.ValidationMessageFor() in ASP.NET MVC3. This works fine but it seems to make the message be always displayed, e.g. if I do this: @Html.ValidationMessageFor(model => model.TimesheetEntry.Product) then the error is only shown when I submit the form and it is invalid. However if I do this: @Html.ValidationMessageFor(model => model.TimesheetEntry.Product, "custom error") then that message is displayed as soon as I initially load the page. I'm probably doing something stupid here and any help would be appreciated. | Have you tried the CSS from this question?.field-validation-valid { display: none; }.validation-summary-valid { display: none; } | @Html.ValidationMessageFor() custom validationMessage always shown I am trying to use a different message for @Html.ValidationMessageFor() in ASP.NET MVC3. This works fine but it seems to make the message be always displayed, e.g. if I do this: @Html.ValidationMessageFor(model => model.TimesheetEntry.Product) then the error is only shown when I submit the form and it is invalid. However if I do this: @Html.ValidationMessageFor(model => model.TimesheetEntry.Product, "custom error") then that message is displayed as soon as I initially load the page. I'm probably doing something stupid here and any help would be appreciated. | TITLE:
@Html.ValidationMessageFor() custom validationMessage always shown
QUESTION:
I am trying to use a different message for @Html.ValidationMessageFor() in ASP.NET MVC3. This works fine but it seems to make the message be always displayed, e.g. if I do this: @Html.ValidationMessageFor(model => model.TimesheetEntry.Product) then the error is only shown when I submit the form and it is invalid. However if I do this: @Html.ValidationMessageFor(model => model.TimesheetEntry.Product, "custom error") then that message is displayed as soon as I initially load the page. I'm probably doing something stupid here and any help would be appreciated.
ANSWER:
Have you tried the CSS from this question?.field-validation-valid { display: none; }.validation-summary-valid { display: none; } | [
"forms",
"asp.net-mvc-3"
] | 31 | 50 | 29,725 | 4 | 0 | 2011-06-10T15:45:20.420000 | 2011-06-10T15:53:07.100000 |
6,308,801 | 6,308,923 | Replace DOM element with a DOM element and children, of which exists in an eternal .html(?) file | Rewriting an html element's content, or itself is easy via jquery, but is it possible to replace an element with an element that exists on another page/file? My point is that i don't want this info that i'm trying to retrieve to be on the page by default as it would clog up the file and bloat the file size... To provide context: I have an unordered list in my html. Say it's a grocery list. I have some option that changes the list to a bill of materials instead. So it replaces the ul with the ul (and it's li children) with this new set, of which is located in an external html file. (that file being just an ul and li's.) I want this external/retrieval because these lists could be quite long, and i need the lists to be DOM elements because i need to work with them via other scripts, etc. Regex on a text file that's been prepared for this operation isn't a perfect solution either, since these li's will have a/> tags within, and there's a variety of classes across the li's as well... I pretty much want to append an html file to the DOM, i suppose. | Try this: jQuery.get('myFile.html', function(data) { jQuery('#myElement').html(data); }); Or to replace the element itselft: jQuery.get('myFile.html', function(data) { jQuery('#myElement').replaceWith(data); }); | Replace DOM element with a DOM element and children, of which exists in an eternal .html(?) file Rewriting an html element's content, or itself is easy via jquery, but is it possible to replace an element with an element that exists on another page/file? My point is that i don't want this info that i'm trying to retrieve to be on the page by default as it would clog up the file and bloat the file size... To provide context: I have an unordered list in my html. Say it's a grocery list. I have some option that changes the list to a bill of materials instead. So it replaces the ul with the ul (and it's li children) with this new set, of which is located in an external html file. (that file being just an ul and li's.) I want this external/retrieval because these lists could be quite long, and i need the lists to be DOM elements because i need to work with them via other scripts, etc. Regex on a text file that's been prepared for this operation isn't a perfect solution either, since these li's will have a/> tags within, and there's a variety of classes across the li's as well... I pretty much want to append an html file to the DOM, i suppose. | TITLE:
Replace DOM element with a DOM element and children, of which exists in an eternal .html(?) file
QUESTION:
Rewriting an html element's content, or itself is easy via jquery, but is it possible to replace an element with an element that exists on another page/file? My point is that i don't want this info that i'm trying to retrieve to be on the page by default as it would clog up the file and bloat the file size... To provide context: I have an unordered list in my html. Say it's a grocery list. I have some option that changes the list to a bill of materials instead. So it replaces the ul with the ul (and it's li children) with this new set, of which is located in an external html file. (that file being just an ul and li's.) I want this external/retrieval because these lists could be quite long, and i need the lists to be DOM elements because i need to work with them via other scripts, etc. Regex on a text file that's been prepared for this operation isn't a perfect solution either, since these li's will have a/> tags within, and there's a variety of classes across the li's as well... I pretty much want to append an html file to the DOM, i suppose.
ANSWER:
Try this: jQuery.get('myFile.html', function(data) { jQuery('#myElement').html(data); }); Or to replace the element itselft: jQuery.get('myFile.html', function(data) { jQuery('#myElement').replaceWith(data); }); | [
"jquery",
"append"
] | 0 | 1 | 1,427 | 1 | 0 | 2011-06-10T15:45:54.617000 | 2011-06-10T15:54:50.287000 |
6,308,803 | 6,308,837 | Sending $(this) in a callback | I have this jQuery click event $('#sidebar.nav a span').click(function () { var sidebar_nav = $(this); $("#main").load("type_change.php?id="+id, successCallback); And then i have the callback to do the binding var successCallback = function(responseText, textStatus, XMLHttpRequest) { //doing all the binding in here } Is there a way to pass $(this) or sidebar_nav or to the successCallback function so I can do something with it | You could use $.proxy: $("#main").load("type_change.php?id="+id, $.proxy(successCallback, $(this))); This will set this inside successCallback to whatever you pass as second parameter. If you want this still to refer to $("#main"), then you could change the callback to accept one more parameter: var successCallback = function(responseText, textStatus, XMLHttpRequest, target) { //doing all the binding in here } and call it like so: var sidebar_nav = $(this); $("#main").load("type_change.php?id="+id, function() { var args = $.makeArray(arguments); args.push(sidebar_nav); successCallback.apply(this, args); }); target will refer to sidebar_nav. | Sending $(this) in a callback I have this jQuery click event $('#sidebar.nav a span').click(function () { var sidebar_nav = $(this); $("#main").load("type_change.php?id="+id, successCallback); And then i have the callback to do the binding var successCallback = function(responseText, textStatus, XMLHttpRequest) { //doing all the binding in here } Is there a way to pass $(this) or sidebar_nav or to the successCallback function so I can do something with it | TITLE:
Sending $(this) in a callback
QUESTION:
I have this jQuery click event $('#sidebar.nav a span').click(function () { var sidebar_nav = $(this); $("#main").load("type_change.php?id="+id, successCallback); And then i have the callback to do the binding var successCallback = function(responseText, textStatus, XMLHttpRequest) { //doing all the binding in here } Is there a way to pass $(this) or sidebar_nav or to the successCallback function so I can do something with it
ANSWER:
You could use $.proxy: $("#main").load("type_change.php?id="+id, $.proxy(successCallback, $(this))); This will set this inside successCallback to whatever you pass as second parameter. If you want this still to refer to $("#main"), then you could change the callback to accept one more parameter: var successCallback = function(responseText, textStatus, XMLHttpRequest, target) { //doing all the binding in here } and call it like so: var sidebar_nav = $(this); $("#main").load("type_change.php?id="+id, function() { var args = $.makeArray(arguments); args.push(sidebar_nav); successCallback.apply(this, args); }); target will refer to sidebar_nav. | [
"jquery"
] | 7 | 7 | 244 | 4 | 0 | 2011-06-10T15:45:55.613000 | 2011-06-10T15:48:24.327000 |
6,308,807 | 6,309,426 | Rendering different templates for the same XML element, at same level | XML: el1 el2 el1 el2 Trying to generate to apply two different templates for the same element. Main template: At root level Render something more render something here render something else here If I add mode to the first template, both don't render. Also tried: with the different template to apply as: Only one of the two(the first one which has the mode specified is rendered). i.e doesn't render or renders twice. How should I fix this? Everywhere I researched, it suggests to put a priority on the mode. Must be something simple since so many programmers use it? | At root level After first template First template Second template | Rendering different templates for the same XML element, at same level XML: el1 el2 el1 el2 Trying to generate to apply two different templates for the same element. Main template: At root level Render something more render something here render something else here If I add mode to the first template, both don't render. Also tried: with the different template to apply as: Only one of the two(the first one which has the mode specified is rendered). i.e doesn't render or renders twice. How should I fix this? Everywhere I researched, it suggests to put a priority on the mode. Must be something simple since so many programmers use it? | TITLE:
Rendering different templates for the same XML element, at same level
QUESTION:
XML: el1 el2 el1 el2 Trying to generate to apply two different templates for the same element. Main template: At root level Render something more render something here render something else here If I add mode to the first template, both don't render. Also tried: with the different template to apply as: Only one of the two(the first one which has the mode specified is rendered). i.e doesn't render or renders twice. How should I fix this? Everywhere I researched, it suggests to put a priority on the mode. Must be something simple since so many programmers use it?
ANSWER:
At root level After first template First template Second template | [
"xml",
"templates",
"xslt",
"apply-templates"
] | 2 | 5 | 4,262 | 2 | 0 | 2011-06-10T15:46:05.397000 | 2011-06-10T16:34:35.660000 |
6,308,808 | 6,308,866 | Force show soft keyboard from within an AlertDialog | I have the following code which I think should work to force the keyboard to be shown when the Alert Dialog is shown. public void showTypeBox(){ edit = new EditText(this); edit.setPadding(10, 0, 0, 10);
AlertDialog dialog = new AlertDialog.Builder(this).setTitle("Type word to search for:").setPositiveButton("Search", Main.this).setNegativeButton("Cancel", null).setView(edit).setIcon(R.drawable.menu_icon).create(); dialog.show();
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); mgr.showSoftInput(edit, InputMethodManager.SHOW_IMPLICIT); } I can't see what i'm doing wrong here. | You're trying to show the keyboard before the EditText is laid out and visible. Try this: Handler delayedRun = new Handler(); delayedRun.post(new Runnable() { @Override public void run() { edit.requestFocus(); InputMethodManager mgr = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE); mgr.showSoftInput(addressBox, InputMethodManager.SHOW_IMPLICIT); } }); | Force show soft keyboard from within an AlertDialog I have the following code which I think should work to force the keyboard to be shown when the Alert Dialog is shown. public void showTypeBox(){ edit = new EditText(this); edit.setPadding(10, 0, 0, 10);
AlertDialog dialog = new AlertDialog.Builder(this).setTitle("Type word to search for:").setPositiveButton("Search", Main.this).setNegativeButton("Cancel", null).setView(edit).setIcon(R.drawable.menu_icon).create(); dialog.show();
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); mgr.showSoftInput(edit, InputMethodManager.SHOW_IMPLICIT); } I can't see what i'm doing wrong here. | TITLE:
Force show soft keyboard from within an AlertDialog
QUESTION:
I have the following code which I think should work to force the keyboard to be shown when the Alert Dialog is shown. public void showTypeBox(){ edit = new EditText(this); edit.setPadding(10, 0, 0, 10);
AlertDialog dialog = new AlertDialog.Builder(this).setTitle("Type word to search for:").setPositiveButton("Search", Main.this).setNegativeButton("Cancel", null).setView(edit).setIcon(R.drawable.menu_icon).create(); dialog.show();
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); mgr.showSoftInput(edit, InputMethodManager.SHOW_IMPLICIT); } I can't see what i'm doing wrong here.
ANSWER:
You're trying to show the keyboard before the EditText is laid out and visible. Try this: Handler delayedRun = new Handler(); delayedRun.post(new Runnable() { @Override public void run() { edit.requestFocus(); InputMethodManager mgr = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE); mgr.showSoftInput(addressBox, InputMethodManager.SHOW_IMPLICIT); } }); | [
"java",
"android",
"keyboard"
] | 2 | 5 | 1,250 | 1 | 0 | 2011-06-10T15:46:06.410000 | 2011-06-10T15:50:42.943000 |
6,308,809 | 6,308,981 | Why Java SHA1 does not Initial Vector? | I am trying to use java in built method (MessageDigest) to implement SHA1. However, in examples I have not find any method parameters to declare Initial Vector. Can anybody help me about this???? Thanks in advance...... | I am in no way an expert in cryptography, but logically thinking, what woud IV be needed for in digest? The point of digest is to produce seemingly random result for each input message but, as with any other hash, it must be the same for the same input. IV on the other hand are used to modify encryption algorithm to have different results for the same input. So, I don't think there would be any IV. | Why Java SHA1 does not Initial Vector? I am trying to use java in built method (MessageDigest) to implement SHA1. However, in examples I have not find any method parameters to declare Initial Vector. Can anybody help me about this???? Thanks in advance...... | TITLE:
Why Java SHA1 does not Initial Vector?
QUESTION:
I am trying to use java in built method (MessageDigest) to implement SHA1. However, in examples I have not find any method parameters to declare Initial Vector. Can anybody help me about this???? Thanks in advance......
ANSWER:
I am in no way an expert in cryptography, but logically thinking, what woud IV be needed for in digest? The point of digest is to produce seemingly random result for each input message but, as with any other hash, it must be the same for the same input. IV on the other hand are used to modify encryption algorithm to have different results for the same input. So, I don't think there would be any IV. | [
"java",
"security"
] | 0 | 5 | 927 | 1 | 0 | 2011-06-10T15:46:10.877000 | 2011-06-10T15:59:05.310000 |
6,308,817 | 6,309,303 | Wpf treeview selectedItem databinding | I have a view where I've got an object bound to a treeview. The object has a number of collections (of different types) so I'm using hiearchical templates with a CompositeCollection to display them in the treeview. I've then got a textbox that is bound to the treeview's selectedItem. Here I'm serialising the selectedItem to XML and displaying it in the textbox for editing. All good so far. However, the big problem I have is that I can't use 2-way databinding with the SelectedItem property of the treeview as it is read only. How can I cleanly keep the textbox edits in sync with my object that is bound to the treeview? | I do not think you need to do two-way databinding on the SelectedItem itself, you should expose a property in the class of your bound object which returns the serialized string and upon set modifies the object appropriately. This should be easier than dealing with the object as a whole. | Wpf treeview selectedItem databinding I have a view where I've got an object bound to a treeview. The object has a number of collections (of different types) so I'm using hiearchical templates with a CompositeCollection to display them in the treeview. I've then got a textbox that is bound to the treeview's selectedItem. Here I'm serialising the selectedItem to XML and displaying it in the textbox for editing. All good so far. However, the big problem I have is that I can't use 2-way databinding with the SelectedItem property of the treeview as it is read only. How can I cleanly keep the textbox edits in sync with my object that is bound to the treeview? | TITLE:
Wpf treeview selectedItem databinding
QUESTION:
I have a view where I've got an object bound to a treeview. The object has a number of collections (of different types) so I'm using hiearchical templates with a CompositeCollection to display them in the treeview. I've then got a textbox that is bound to the treeview's selectedItem. Here I'm serialising the selectedItem to XML and displaying it in the textbox for editing. All good so far. However, the big problem I have is that I can't use 2-way databinding with the SelectedItem property of the treeview as it is read only. How can I cleanly keep the textbox edits in sync with my object that is bound to the treeview?
ANSWER:
I do not think you need to do two-way databinding on the SelectedItem itself, you should expose a property in the class of your bound object which returns the serialized string and upon set modifies the object appropriately. This should be easier than dealing with the object as a whole. | [
"wpf",
"treeview",
"2-way-object-databinding"
] | 0 | 0 | 885 | 2 | 0 | 2011-06-10T15:46:33.400000 | 2011-06-10T16:24:39.847000 |
6,308,819 | 6,308,861 | How to ignore numbers when doing string.startswith() in python? | I have a directory with a large number of files. The file names are similar to the following: the(number)one(number), where (number) can be any number. There are also files with the name: the(number), where (number) can be any number. I was wondering how I can count the number of files with the additional "one(number)" at the end of their file name. Let's say I have the list of file names, I was thinking of doing for n in list: if n.startswith(the(number)one): add one to a counter Is there anyway for it to accept any number in the (number) space when doing a startswith? Example: the34one5 the37one2 the444one3 the87one8 the34 the32 This should return 4. | Use a regex matching 'one\d+' using the re module. import re for n in list: if re.search(r"one\d+", n): add one to a counter If you want to make it very accurate, you can even do: for n in list: if re.search(r"^the\d+one\d+$", n): add one to a counter Which will even take care of any possible non digit chars between "the" and "one" and won't allow anything else before 'the' and after the last digit'. You should start learning regexp now: they let you make some complex text analysis in a blink that would be hard to code manually they work almost the same from one language to another, making you more flexible if you encounter some code using them, you will be puzzled if you didn't cause it's not something you can guess the sooner you know them, the sooner you'll learn when NOT ( hint ) to use them. Which is eventually as important as knowing them. | How to ignore numbers when doing string.startswith() in python? I have a directory with a large number of files. The file names are similar to the following: the(number)one(number), where (number) can be any number. There are also files with the name: the(number), where (number) can be any number. I was wondering how I can count the number of files with the additional "one(number)" at the end of their file name. Let's say I have the list of file names, I was thinking of doing for n in list: if n.startswith(the(number)one): add one to a counter Is there anyway for it to accept any number in the (number) space when doing a startswith? Example: the34one5 the37one2 the444one3 the87one8 the34 the32 This should return 4. | TITLE:
How to ignore numbers when doing string.startswith() in python?
QUESTION:
I have a directory with a large number of files. The file names are similar to the following: the(number)one(number), where (number) can be any number. There are also files with the name: the(number), where (number) can be any number. I was wondering how I can count the number of files with the additional "one(number)" at the end of their file name. Let's say I have the list of file names, I was thinking of doing for n in list: if n.startswith(the(number)one): add one to a counter Is there anyway for it to accept any number in the (number) space when doing a startswith? Example: the34one5 the37one2 the444one3 the87one8 the34 the32 This should return 4.
ANSWER:
Use a regex matching 'one\d+' using the re module. import re for n in list: if re.search(r"one\d+", n): add one to a counter If you want to make it very accurate, you can even do: for n in list: if re.search(r"^the\d+one\d+$", n): add one to a counter Which will even take care of any possible non digit chars between "the" and "one" and won't allow anything else before 'the' and after the last digit'. You should start learning regexp now: they let you make some complex text analysis in a blink that would be hard to code manually they work almost the same from one language to another, making you more flexible if you encounter some code using them, you will be puzzled if you didn't cause it's not something you can guess the sooner you know them, the sooner you'll learn when NOT ( hint ) to use them. Which is eventually as important as knowing them. | [
"python"
] | 0 | 8 | 542 | 3 | 0 | 2011-06-10T15:46:46.470000 | 2011-06-10T15:50:07.590000 |
6,308,824 | 6,308,912 | Should node.js changes be instantaneous? | Seeing how node.js is ultimately javascript, shouldn't changes to any files be seen when trying to run the app command? I've forked the yuidocjs repo on github and am trying to work my way through my local build, but for some reason my minor changes do not get picked up. I'm new to node.js so I'm not really sure what the exact conventions are. | In node.js when you require a file the source code gets interpreted. It's considered good practice to require all code when you start the server so all the code gets interpreted once. The code does not get re-interpreted whenever you run it though. So changes are not instantaneous. To help you out, try supervisor which does hot reloading of the server on code changes. It is possible to make instant changes happen by re-interpreting source code but that is not the default action. Generally you should just re-start the server. | Should node.js changes be instantaneous? Seeing how node.js is ultimately javascript, shouldn't changes to any files be seen when trying to run the app command? I've forked the yuidocjs repo on github and am trying to work my way through my local build, but for some reason my minor changes do not get picked up. I'm new to node.js so I'm not really sure what the exact conventions are. | TITLE:
Should node.js changes be instantaneous?
QUESTION:
Seeing how node.js is ultimately javascript, shouldn't changes to any files be seen when trying to run the app command? I've forked the yuidocjs repo on github and am trying to work my way through my local build, but for some reason my minor changes do not get picked up. I'm new to node.js so I'm not really sure what the exact conventions are.
ANSWER:
In node.js when you require a file the source code gets interpreted. It's considered good practice to require all code when you start the server so all the code gets interpreted once. The code does not get re-interpreted whenever you run it though. So changes are not instantaneous. To help you out, try supervisor which does hot reloading of the server on code changes. It is possible to make instant changes happen by re-interpreting source code but that is not the default action. Generally you should just re-start the server. | [
"node.js"
] | 2 | 3 | 542 | 2 | 0 | 2011-06-10T15:47:38.633000 | 2011-06-10T15:53:46.953000 |
6,308,827 | 6,309,196 | merging two stored procedures | So this is what i thought of doing but now the error i am getting is: Cannot use an aggregate or a subquery in an expression used for the group by list of a GROUP BY clause and not sure which part it means - the overall code i am trying to get open cases based on two different levels one is to return cases based on date range passed in and the other is to return cases based on just the begin date and before it. Help will be great!:) CODE: SELECT C.CaseNumber, O.OfficeName, CT.Description AS CaseType, DATEADD(dd, 0, DATEDIFF(dd, 0, C.DateOpened)) AS DateOpened, CR.Description AS Court, CaseOfficeAppointment.OpenCases, CaseOfficeAppointment.CloseCases FROM ( SELECT C.CaseId, O.OfficeId, CRT.CourtId, ( SELECT COUNT(DISTINCT CD.CaseId) FROM [Case] CD INNER JOIN CaseOffice COD ON CD.CaseId = COD.CaseId --INNER JOIN Court CR ON CD.CourtId = CR.CourtId INNER JOIN Office OD ON COD.OfficeId = OD.OfficeId LEFT OUTER JOIN CaseStatusChange CSC ON CD.CaseId = CSC.CaseId --WHERE CR.CourtId = CRT.CourtId WHERE OD.OfficeId = O.OfficeId AND ( CD.DateOpened BETWEEN @BeginDate AND @EndDate OR CSC.DateReopened BETWEEN @BeginDate AND @EndDate ) )AS OpenCases, ( SELECT COUNT(DISTINCT CD.CaseId) FROM [Case] CD INNER JOIN CaseOffice COD ON CD.CaseId = COD.CaseId --INNER JOIN Court CR ON CD.CourtId = CR.CourtId INNER JOIN Office OD ON COD.OfficeId = OD.OfficeId LEFT OUTER JOIN CaseStatusChange CSC ON CD.CaseId = CSC.CaseId --WHERE CR.CourtId = CRT.CourtId WHERE OD.OfficeId = O.OfficeId AND ( CSC.DateClosed BETWEEN @BeginDate AND @EndDate ) )AS CloseCases FROM [Case] C INNER JOIN [Appointment] A ON C.CaseId = A.CaseId INNER JOIN [Office] O ON A.OfficeId = O.OfficeId INNER JOIN [Court] CRT ON C.CourtId = CRT.CourtId
WHERE -- Case was open (or reopened) during the date range C.DateOpened BETWEEN @beginDate AND @endDate OR C.CaseId IN (SELECT CaseId FROM CaseStatusChange WHERE DateReopened BETWEEN @beginDate AND @endDate) AND -- Office had an appointment sometime during the date range A.DateOn < @endDate AND (A.DateOff IS NULL OR A.DateOff BETWEEN @beginDate AND @endDate)
GROUP BY C.CaseId, O.OfficeId, CRT.CourtId, ( SELECT OfficeId, SUM(CaseCount)AS Counts FROM ( SELECT COUNT(C.CaseId) AS CaseCount,O.OfficeId FROM [Case] C INNER JOIN [Appointment] A ON C.CaseId = A.CaseId INNER JOIN [Office] O ON A.OfficeId = O.OfficeId WHERE C.DateCreated <= @BeginDate AND C.CaseId NOT IN (SELECT CaseId FROM CaseStatusChange CSC WHERE CSC.DateClosed < @BeginDate) --GROUP BY O.OfficeId
UNION
-- Also need the cases that reopened and are currently open SELECT COUNT(ReOpened.CaseId) As CaseCount, ReOpened.OfficeID FROM (
SELECT C.CaseId, MAX(CSC.DateReopened) AS DateReOpened, O.OfficeId FROM [Case] C INNER JOIN [CaseStatusChange] CSC ON C.CaseId = CSC.CaseId INNER JOIN [Appointment] A ON C.CaseId = A.CaseId INNER JOIN [Office] O ON A.OfficeId = O.OfficeId WHERE CSC.DateReopened <= @BeginDate --GROUP BY C.CaseId, O.OfficeID ) AS ReOpened WHERE ReOpened.CaseId NOT IN ( SELECT CaseId FROM CaseStatusChange WHERE CaseId = ReOpened.CaseId AND CaseStatusChange.DateClosed BETWEEN ReOpened.DateReopened AND @BeginDate ) GROUP BY ReOpened.OfficeId ) AS OpenCasesCount GROUP BY OfficeId ) ) CaseOfficeAppointment INNER JOIN [Case] C ON CaseOfficeAppointment.CaseId = C.CaseId INNER JOIN [Office] O ON CaseOfficeAppointment.OfficeId = O.OfficeId INNER JOIN [CaseType] CT ON C.CaseTypeId = CT.CaseTypeId INNER JOIN [Court] CR ON C.CourtId = CR.CourtId | If I understood you right, you need something like: CREATE PROCEDURE new_proc AS BEGIN DECLARE @tmp_proc1 TABLE (// list all fields your first procedure returns ); DECLARE @tmp_proc2 TABLE (// list fields that your second SP returns); INSERT INTO @tmp_proc1 EXECUTE Your_First_Procedure; INSERT INTO @tmp_proc2 EXECUTE Your_Second_Procedure;
// Finally, join data in @tmp_proc1 and @tmp_proc2 //(you probably need FULL JOIN) and return 1 resultset
END; | merging two stored procedures So this is what i thought of doing but now the error i am getting is: Cannot use an aggregate or a subquery in an expression used for the group by list of a GROUP BY clause and not sure which part it means - the overall code i am trying to get open cases based on two different levels one is to return cases based on date range passed in and the other is to return cases based on just the begin date and before it. Help will be great!:) CODE: SELECT C.CaseNumber, O.OfficeName, CT.Description AS CaseType, DATEADD(dd, 0, DATEDIFF(dd, 0, C.DateOpened)) AS DateOpened, CR.Description AS Court, CaseOfficeAppointment.OpenCases, CaseOfficeAppointment.CloseCases FROM ( SELECT C.CaseId, O.OfficeId, CRT.CourtId, ( SELECT COUNT(DISTINCT CD.CaseId) FROM [Case] CD INNER JOIN CaseOffice COD ON CD.CaseId = COD.CaseId --INNER JOIN Court CR ON CD.CourtId = CR.CourtId INNER JOIN Office OD ON COD.OfficeId = OD.OfficeId LEFT OUTER JOIN CaseStatusChange CSC ON CD.CaseId = CSC.CaseId --WHERE CR.CourtId = CRT.CourtId WHERE OD.OfficeId = O.OfficeId AND ( CD.DateOpened BETWEEN @BeginDate AND @EndDate OR CSC.DateReopened BETWEEN @BeginDate AND @EndDate ) )AS OpenCases, ( SELECT COUNT(DISTINCT CD.CaseId) FROM [Case] CD INNER JOIN CaseOffice COD ON CD.CaseId = COD.CaseId --INNER JOIN Court CR ON CD.CourtId = CR.CourtId INNER JOIN Office OD ON COD.OfficeId = OD.OfficeId LEFT OUTER JOIN CaseStatusChange CSC ON CD.CaseId = CSC.CaseId --WHERE CR.CourtId = CRT.CourtId WHERE OD.OfficeId = O.OfficeId AND ( CSC.DateClosed BETWEEN @BeginDate AND @EndDate ) )AS CloseCases FROM [Case] C INNER JOIN [Appointment] A ON C.CaseId = A.CaseId INNER JOIN [Office] O ON A.OfficeId = O.OfficeId INNER JOIN [Court] CRT ON C.CourtId = CRT.CourtId
WHERE -- Case was open (or reopened) during the date range C.DateOpened BETWEEN @beginDate AND @endDate OR C.CaseId IN (SELECT CaseId FROM CaseStatusChange WHERE DateReopened BETWEEN @beginDate AND @endDate) AND -- Office had an appointment sometime during the date range A.DateOn < @endDate AND (A.DateOff IS NULL OR A.DateOff BETWEEN @beginDate AND @endDate)
GROUP BY C.CaseId, O.OfficeId, CRT.CourtId, ( SELECT OfficeId, SUM(CaseCount)AS Counts FROM ( SELECT COUNT(C.CaseId) AS CaseCount,O.OfficeId FROM [Case] C INNER JOIN [Appointment] A ON C.CaseId = A.CaseId INNER JOIN [Office] O ON A.OfficeId = O.OfficeId WHERE C.DateCreated <= @BeginDate AND C.CaseId NOT IN (SELECT CaseId FROM CaseStatusChange CSC WHERE CSC.DateClosed < @BeginDate) --GROUP BY O.OfficeId
UNION
-- Also need the cases that reopened and are currently open SELECT COUNT(ReOpened.CaseId) As CaseCount, ReOpened.OfficeID FROM (
SELECT C.CaseId, MAX(CSC.DateReopened) AS DateReOpened, O.OfficeId FROM [Case] C INNER JOIN [CaseStatusChange] CSC ON C.CaseId = CSC.CaseId INNER JOIN [Appointment] A ON C.CaseId = A.CaseId INNER JOIN [Office] O ON A.OfficeId = O.OfficeId WHERE CSC.DateReopened <= @BeginDate --GROUP BY C.CaseId, O.OfficeID ) AS ReOpened WHERE ReOpened.CaseId NOT IN ( SELECT CaseId FROM CaseStatusChange WHERE CaseId = ReOpened.CaseId AND CaseStatusChange.DateClosed BETWEEN ReOpened.DateReopened AND @BeginDate ) GROUP BY ReOpened.OfficeId ) AS OpenCasesCount GROUP BY OfficeId ) ) CaseOfficeAppointment INNER JOIN [Case] C ON CaseOfficeAppointment.CaseId = C.CaseId INNER JOIN [Office] O ON CaseOfficeAppointment.OfficeId = O.OfficeId INNER JOIN [CaseType] CT ON C.CaseTypeId = CT.CaseTypeId INNER JOIN [Court] CR ON C.CourtId = CR.CourtId | TITLE:
merging two stored procedures
QUESTION:
So this is what i thought of doing but now the error i am getting is: Cannot use an aggregate or a subquery in an expression used for the group by list of a GROUP BY clause and not sure which part it means - the overall code i am trying to get open cases based on two different levels one is to return cases based on date range passed in and the other is to return cases based on just the begin date and before it. Help will be great!:) CODE: SELECT C.CaseNumber, O.OfficeName, CT.Description AS CaseType, DATEADD(dd, 0, DATEDIFF(dd, 0, C.DateOpened)) AS DateOpened, CR.Description AS Court, CaseOfficeAppointment.OpenCases, CaseOfficeAppointment.CloseCases FROM ( SELECT C.CaseId, O.OfficeId, CRT.CourtId, ( SELECT COUNT(DISTINCT CD.CaseId) FROM [Case] CD INNER JOIN CaseOffice COD ON CD.CaseId = COD.CaseId --INNER JOIN Court CR ON CD.CourtId = CR.CourtId INNER JOIN Office OD ON COD.OfficeId = OD.OfficeId LEFT OUTER JOIN CaseStatusChange CSC ON CD.CaseId = CSC.CaseId --WHERE CR.CourtId = CRT.CourtId WHERE OD.OfficeId = O.OfficeId AND ( CD.DateOpened BETWEEN @BeginDate AND @EndDate OR CSC.DateReopened BETWEEN @BeginDate AND @EndDate ) )AS OpenCases, ( SELECT COUNT(DISTINCT CD.CaseId) FROM [Case] CD INNER JOIN CaseOffice COD ON CD.CaseId = COD.CaseId --INNER JOIN Court CR ON CD.CourtId = CR.CourtId INNER JOIN Office OD ON COD.OfficeId = OD.OfficeId LEFT OUTER JOIN CaseStatusChange CSC ON CD.CaseId = CSC.CaseId --WHERE CR.CourtId = CRT.CourtId WHERE OD.OfficeId = O.OfficeId AND ( CSC.DateClosed BETWEEN @BeginDate AND @EndDate ) )AS CloseCases FROM [Case] C INNER JOIN [Appointment] A ON C.CaseId = A.CaseId INNER JOIN [Office] O ON A.OfficeId = O.OfficeId INNER JOIN [Court] CRT ON C.CourtId = CRT.CourtId
WHERE -- Case was open (or reopened) during the date range C.DateOpened BETWEEN @beginDate AND @endDate OR C.CaseId IN (SELECT CaseId FROM CaseStatusChange WHERE DateReopened BETWEEN @beginDate AND @endDate) AND -- Office had an appointment sometime during the date range A.DateOn < @endDate AND (A.DateOff IS NULL OR A.DateOff BETWEEN @beginDate AND @endDate)
GROUP BY C.CaseId, O.OfficeId, CRT.CourtId, ( SELECT OfficeId, SUM(CaseCount)AS Counts FROM ( SELECT COUNT(C.CaseId) AS CaseCount,O.OfficeId FROM [Case] C INNER JOIN [Appointment] A ON C.CaseId = A.CaseId INNER JOIN [Office] O ON A.OfficeId = O.OfficeId WHERE C.DateCreated <= @BeginDate AND C.CaseId NOT IN (SELECT CaseId FROM CaseStatusChange CSC WHERE CSC.DateClosed < @BeginDate) --GROUP BY O.OfficeId
UNION
-- Also need the cases that reopened and are currently open SELECT COUNT(ReOpened.CaseId) As CaseCount, ReOpened.OfficeID FROM (
SELECT C.CaseId, MAX(CSC.DateReopened) AS DateReOpened, O.OfficeId FROM [Case] C INNER JOIN [CaseStatusChange] CSC ON C.CaseId = CSC.CaseId INNER JOIN [Appointment] A ON C.CaseId = A.CaseId INNER JOIN [Office] O ON A.OfficeId = O.OfficeId WHERE CSC.DateReopened <= @BeginDate --GROUP BY C.CaseId, O.OfficeID ) AS ReOpened WHERE ReOpened.CaseId NOT IN ( SELECT CaseId FROM CaseStatusChange WHERE CaseId = ReOpened.CaseId AND CaseStatusChange.DateClosed BETWEEN ReOpened.DateReopened AND @BeginDate ) GROUP BY ReOpened.OfficeId ) AS OpenCasesCount GROUP BY OfficeId ) ) CaseOfficeAppointment INNER JOIN [Case] C ON CaseOfficeAppointment.CaseId = C.CaseId INNER JOIN [Office] O ON CaseOfficeAppointment.OfficeId = O.OfficeId INNER JOIN [CaseType] CT ON C.CaseTypeId = CT.CaseTypeId INNER JOIN [Court] CR ON C.CourtId = CR.CourtId
ANSWER:
If I understood you right, you need something like: CREATE PROCEDURE new_proc AS BEGIN DECLARE @tmp_proc1 TABLE (// list all fields your first procedure returns ); DECLARE @tmp_proc2 TABLE (// list fields that your second SP returns); INSERT INTO @tmp_proc1 EXECUTE Your_First_Procedure; INSERT INTO @tmp_proc2 EXECUTE Your_Second_Procedure;
// Finally, join data in @tmp_proc1 and @tmp_proc2 //(you probably need FULL JOIN) and return 1 resultset
END; | [
"sql-server",
"stored-procedures"
] | 1 | 0 | 3,521 | 2 | 0 | 2011-06-10T15:47:53.117000 | 2011-06-10T16:16:47.227000 |
6,308,839 | 6,310,140 | How can I tell when my instrumented application is in front? | My instrumentation is launching an activity to instrument it, but I can't seem to find an elegant way to tell when it's safe to start sending it my MotionEvent 's. At the moment, I'm continually sending it MotionEvent 's, and catching the SecurityException 's that get thrown when the wrong application receives them. The problem with this approach is that when the first event gets through, the application responds to it, so this method is not without side effects... I was thinking of trying to do something with UID's, but I don't know where to look for that. | You might be able to leverage the standard Android lifecycle methods that get called on your Activity. You could set an 'infront' flag in onResume(), and clear it in onPause(). Then your instrumentation test just checks that flag to know when it's safe to send MotionEvents. If you don't want to pollute your app by putting in code specifically for test purposes, create a subclass, override onResume/onPause, set the flags, and call super. | How can I tell when my instrumented application is in front? My instrumentation is launching an activity to instrument it, but I can't seem to find an elegant way to tell when it's safe to start sending it my MotionEvent 's. At the moment, I'm continually sending it MotionEvent 's, and catching the SecurityException 's that get thrown when the wrong application receives them. The problem with this approach is that when the first event gets through, the application responds to it, so this method is not without side effects... I was thinking of trying to do something with UID's, but I don't know where to look for that. | TITLE:
How can I tell when my instrumented application is in front?
QUESTION:
My instrumentation is launching an activity to instrument it, but I can't seem to find an elegant way to tell when it's safe to start sending it my MotionEvent 's. At the moment, I'm continually sending it MotionEvent 's, and catching the SecurityException 's that get thrown when the wrong application receives them. The problem with this approach is that when the first event gets through, the application responds to it, so this method is not without side effects... I was thinking of trying to do something with UID's, but I don't know where to look for that.
ANSWER:
You might be able to leverage the standard Android lifecycle methods that get called on your Activity. You could set an 'infront' flag in onResume(), and clear it in onPause(). Then your instrumentation test just checks that flag to know when it's safe to send MotionEvents. If you don't want to pollute your app by putting in code specifically for test purposes, create a subclass, override onResume/onPause, set the flags, and call super. | [
"android",
"instrumentation"
] | 0 | 1 | 187 | 1 | 0 | 2011-06-10T15:48:26.820000 | 2011-06-10T17:44:12.117000 |
6,308,845 | 6,308,919 | Youtube videos in jQuery dialogs always on top of other content | I am having some troubles embedding videos in a jQuery dialog. It displays and plays all well but it is always in front of other dialogs. When I pass another dialog over the one with the video the video stays on top of everything... Can anyone help? | Your issue has nothing to do with jQuery or JavaScript. It has to do with the z-index of a Flash object. I've used this solution before with success... http://manisheriar.com/blog/flash_objects_and_z_index Put your Flash content into a wrapper div called flash Add to your object tag Add wmode="transparent" into the embed tag Use CSS to set the position and z-index for your div (don't set negative z-index values as it will hide your Flash) CSS #flash { position: relative; /*or absolute*/ z-index: 0; } HTML | Youtube videos in jQuery dialogs always on top of other content I am having some troubles embedding videos in a jQuery dialog. It displays and plays all well but it is always in front of other dialogs. When I pass another dialog over the one with the video the video stays on top of everything... Can anyone help? | TITLE:
Youtube videos in jQuery dialogs always on top of other content
QUESTION:
I am having some troubles embedding videos in a jQuery dialog. It displays and plays all well but it is always in front of other dialogs. When I pass another dialog over the one with the video the video stays on top of everything... Can anyone help?
ANSWER:
Your issue has nothing to do with jQuery or JavaScript. It has to do with the z-index of a Flash object. I've used this solution before with success... http://manisheriar.com/blog/flash_objects_and_z_index Put your Flash content into a wrapper div called flash Add to your object tag Add wmode="transparent" into the embed tag Use CSS to set the position and z-index for your div (don't set negative z-index values as it will hide your Flash) CSS #flash { position: relative; /*or absolute*/ z-index: 0; } HTML | [
"css",
"flash",
"youtube",
"z-index",
"video-embedding"
] | 2 | 1 | 1,880 | 1 | 0 | 2011-06-10T15:48:50.870000 | 2011-06-10T15:54:34.583000 |
6,308,846 | 6,308,884 | C# how to add focus to button issue | I have a windows form application which has a text box and 3 buttons. Now i need to add focus to a button for 1 second, and then add focus to the other button for a second.. like wise to adding focus to all these 3 buttons for 1 second each. How do i do this. I have tried everything but nothing worked. Can someone help me here or link me to a website that does this. i am using Visual Studio 2008, | Not sure why you would want to do that but maybe you can use a Timer and set it's interval to 1000ms and on it's Tick rotate focus as you want. Mind you, it's very user-unfriendly. | C# how to add focus to button issue I have a windows form application which has a text box and 3 buttons. Now i need to add focus to a button for 1 second, and then add focus to the other button for a second.. like wise to adding focus to all these 3 buttons for 1 second each. How do i do this. I have tried everything but nothing worked. Can someone help me here or link me to a website that does this. i am using Visual Studio 2008, | TITLE:
C# how to add focus to button issue
QUESTION:
I have a windows form application which has a text box and 3 buttons. Now i need to add focus to a button for 1 second, and then add focus to the other button for a second.. like wise to adding focus to all these 3 buttons for 1 second each. How do i do this. I have tried everything but nothing worked. Can someone help me here or link me to a website that does this. i am using Visual Studio 2008,
ANSWER:
Not sure why you would want to do that but maybe you can use a Timer and set it's interval to 1000ms and on it's Tick rotate focus as you want. Mind you, it's very user-unfriendly. | [
"c#",
"button",
"focus"
] | 0 | 0 | 3,285 | 2 | 0 | 2011-06-10T15:48:51.807000 | 2011-06-10T15:51:39.390000 |
6,308,849 | 6,308,874 | PHP GET url iframe | I have: and: If I go to my page, nothing displays unless I end the URL with?goto=. Example: http://example.com/windows8/apps/Flake/index.php?goto=http://google.com How can I make it so that if the user didn't type in?goto=http://google.com, the page displays like a backup website? | If you want to provide a default value for $goto, do it like this: However, you should be aware that by doing this, you allow everyone to construct URLs that point to your server but output to the browser HTML (and more importantly, scripts) that is not under your control (it comes from whatever URL goto points to). This would make it trivially easy for someone to attack your users. | PHP GET url iframe I have: and: If I go to my page, nothing displays unless I end the URL with?goto=. Example: http://example.com/windows8/apps/Flake/index.php?goto=http://google.com How can I make it so that if the user didn't type in?goto=http://google.com, the page displays like a backup website? | TITLE:
PHP GET url iframe
QUESTION:
I have: and: If I go to my page, nothing displays unless I end the URL with?goto=. Example: http://example.com/windows8/apps/Flake/index.php?goto=http://google.com How can I make it so that if the user didn't type in?goto=http://google.com, the page displays like a backup website?
ANSWER:
If you want to provide a default value for $goto, do it like this: However, you should be aware that by doing this, you allow everyone to construct URLs that point to your server but output to the browser HTML (and more importantly, scripts) that is not under your control (it comes from whatever URL goto points to). This would make it trivially easy for someone to attack your users. | [
"php",
"url",
"iframe",
"get"
] | 0 | 5 | 1,105 | 2 | 0 | 2011-06-10T15:49:06.883000 | 2011-06-10T15:50:58.820000 |
6,308,851 | 6,309,066 | LINQ Group by with multiple properties in VB.Net | I spent a lot of time on this problem. I am able to do simple Group By LINQ queries (on one property) but for multiple fields I'm a little stuck... Here is a LINQPad sample of what I want to do: dim lFinal={new with {.Year=2010,.Month=6,.Value1=0,.Value2=0}, new with {.Year=2010,.Month=6,.Value1=2,.Value2=1}, new with {.Year=2010,.Month=7,.Value1=3,.Value2=4}, new with {.Year=2010,.Month=8,.Value1=0,.Value2=1}, new with {.Year=2011,.Month=1,.Value1=2,.Value2=2}, new with {.Year=2011,.Month=1,.Value1=0,.Value2=0}}
Dim lFinal2 = From el In lFinal Group el By Key = new with {el.Year,el.Month} Into Group Select New With {.Year = Key.Year,.Month=Key.Month,.Value1 = Group.Sum(Function(x) x.Value1),.Value2 = Group.Sum(Function(x) x.Value2)}
lFinal.Dump() lFinal2.Dump() The lFinal list has 6 items, I want the lFinal2 to have 4 items: 2010-6 and 2011-1 should group. Thanks in advance. | Not 100% sure but group by probably uses the Equals() and/or GetHashCode implementation, so when you do the implicit creation: = Group el By Key = new with {el.Year,el.Month} the implicit object doesn't know to check both year and month (just because it has the properties doesn't mean it checks them when comparing to other objects). So you'll probably need to do something more like this: = Group el By Key = new CustomKey() { Year = el.Year, Month = el.Month };
public class CustomKey{ int Year { get; set; } int Month { get; set; }
public override bool Equals(obj A) { var key (CustomKey)A; return key.Year == this.Year && key.Month == this.Month; } } | LINQ Group by with multiple properties in VB.Net I spent a lot of time on this problem. I am able to do simple Group By LINQ queries (on one property) but for multiple fields I'm a little stuck... Here is a LINQPad sample of what I want to do: dim lFinal={new with {.Year=2010,.Month=6,.Value1=0,.Value2=0}, new with {.Year=2010,.Month=6,.Value1=2,.Value2=1}, new with {.Year=2010,.Month=7,.Value1=3,.Value2=4}, new with {.Year=2010,.Month=8,.Value1=0,.Value2=1}, new with {.Year=2011,.Month=1,.Value1=2,.Value2=2}, new with {.Year=2011,.Month=1,.Value1=0,.Value2=0}}
Dim lFinal2 = From el In lFinal Group el By Key = new with {el.Year,el.Month} Into Group Select New With {.Year = Key.Year,.Month=Key.Month,.Value1 = Group.Sum(Function(x) x.Value1),.Value2 = Group.Sum(Function(x) x.Value2)}
lFinal.Dump() lFinal2.Dump() The lFinal list has 6 items, I want the lFinal2 to have 4 items: 2010-6 and 2011-1 should group. Thanks in advance. | TITLE:
LINQ Group by with multiple properties in VB.Net
QUESTION:
I spent a lot of time on this problem. I am able to do simple Group By LINQ queries (on one property) but for multiple fields I'm a little stuck... Here is a LINQPad sample of what I want to do: dim lFinal={new with {.Year=2010,.Month=6,.Value1=0,.Value2=0}, new with {.Year=2010,.Month=6,.Value1=2,.Value2=1}, new with {.Year=2010,.Month=7,.Value1=3,.Value2=4}, new with {.Year=2010,.Month=8,.Value1=0,.Value2=1}, new with {.Year=2011,.Month=1,.Value1=2,.Value2=2}, new with {.Year=2011,.Month=1,.Value1=0,.Value2=0}}
Dim lFinal2 = From el In lFinal Group el By Key = new with {el.Year,el.Month} Into Group Select New With {.Year = Key.Year,.Month=Key.Month,.Value1 = Group.Sum(Function(x) x.Value1),.Value2 = Group.Sum(Function(x) x.Value2)}
lFinal.Dump() lFinal2.Dump() The lFinal list has 6 items, I want the lFinal2 to have 4 items: 2010-6 and 2011-1 should group. Thanks in advance.
ANSWER:
Not 100% sure but group by probably uses the Equals() and/or GetHashCode implementation, so when you do the implicit creation: = Group el By Key = new with {el.Year,el.Month} the implicit object doesn't know to check both year and month (just because it has the properties doesn't mean it checks them when comparing to other objects). So you'll probably need to do something more like this: = Group el By Key = new CustomKey() { Year = el.Year, Month = el.Month };
public class CustomKey{ int Year { get; set; } int Month { get; set; }
public override bool Equals(obj A) { var key (CustomKey)A; return key.Year == this.Year && key.Month == this.Month; } } | [
"vb.net",
"linq",
"list",
"group-by"
] | 9 | 3 | 22,132 | 3 | 0 | 2011-06-10T15:49:15.427000 | 2011-06-10T16:06:49.417000 |
6,308,853 | 6,308,875 | Is it possible to make custom Culture / Region combinations? | I would like to support something like a NL-Us culture. Is this possible? | Yes, it is. You need to start with CultureAndRegionInfoBuilder - the link above is a full howto on MSDN. | Is it possible to make custom Culture / Region combinations? I would like to support something like a NL-Us culture. Is this possible? | TITLE:
Is it possible to make custom Culture / Region combinations?
QUESTION:
I would like to support something like a NL-Us culture. Is this possible?
ANSWER:
Yes, it is. You need to start with CultureAndRegionInfoBuilder - the link above is a full howto on MSDN. | [
"c#",
".net",
"localization"
] | 0 | 3 | 497 | 2 | 0 | 2011-06-10T15:49:21.483000 | 2011-06-10T15:51:08.207000 |
6,308,857 | 6,308,958 | Detect when the Shader is done mixing the audio | so this the code with it i am able to mix several tracks with a Shader done in pixel bender. the problem here i don't know when the mixing is finish or all the sound reache their end to be able to save the bytearray into a file any Event or something like that help plz? package { import flash.display.*; import flash.media.*; import flash.events.*; import flash.net.*; import flash.utils.*; import fl.controls.Slider; import org.bytearray.micrecorder.encoder.WaveEncoder;
[SWF(width='500', height='380', frameRate='24')]
public class AudioMixer extends Sprite{
[Embed(source = "sound2.mp3")] private var Track1:Class; [Embed(source = "sound1.mp3")] private var Track2:Class;
[Embed(source = "mix.pbj",mimeType = "application/octet-stream")] private var EmbedShader:Class;
private var shader:Shader = new Shader(new EmbedShader());
private var sound:Vector. = new Vector. (); private var bytes:Vector. = new Vector. (); private var sliders:Vector. = new Vector. (); private var graph:Vector. = new Vector. (); private var recBA:ByteArray = new ByteArray(); private var BUFFER_SIZE:int = 0x800; public var playback:Sound = new Sound(); public var container:Sprite = new Sprite(); public var isEvent:Boolean = false; public function AudioMixer():void{ container.y = stage.stageHeight *.5; addChild(container);
sound.push(new Track1(), new Track2(),new Track2(),new Track2(),new Track2(),new Track2(),new Track2(),new Track2(),new Track2(),new Track2(),new Track2(),new Track2());
for(var i:int = 0; i < sound.length; i++){ var slider:Slider = new Slider(); slider.maximum = 1; slider.minimum = 0; slider.snapInterval = 0.025; slider.value = 0.8; slider.rotation += -90; slider.x = i * 40 + 25; container.addChild(slider); sliders.push(slider);
var line:Shape = new Shape(); line.graphics.lineStyle(1, 0x888888); line.graphics.drawRect(i * 40 + 14, 0, 5, -80); line.graphics.endFill(); container.addChild(line);
var shape:Shape = new Shape(); shape.graphics.beginFill(0x00cc00); shape.graphics.drawRect(i * 40 + 15, 0, 3, -80); shape.graphics.endFill(); container.addChild(shape); graph.push(shape); }
playback.addEventListener(SampleDataEvent.SAMPLE_DATA, onSoundData); playback.play();
}
private function onSoundData(event:SampleDataEvent):void {
for(var i:int = 0; i < sound.length; i++){ bytes[i] = new ByteArray(); bytes[i].length = BUFFER_SIZE * 4 * 2; sound[i].extract(bytes[i], BUFFER_SIZE);
var volume:Number = 0; bytes[i].position = 0;
for(var j:int = 0; j < BUFFER_SIZE; j++){ volume += Math.abs(bytes[i].readFloat()); volume += Math.abs(bytes[i].readFloat()); }
volume = (volume / (BUFFER_SIZE *.5)) * sliders[i].value;
shader.data['track' + (i + 1)].width = BUFFER_SIZE / 1024; shader.data['track' + (i + 1)].height = 512; shader.data['track' + (i + 1)].input = bytes[i]; shader.data['vol' + (i + 1)].value = [sliders[i].value];
graph[i].scaleY = volume; }
var shaderJob:ShaderJob = new ShaderJob(shader,event.data,BUFFER_SIZE / 1024,512);
shaderJob.start(true); var shaderJob2:ShaderJob = new ShaderJob(shader,recBA,BUFFER_SIZE / 1024,512); shaderJob2.start(true);
}
} } | You can tell when a shader has completed it's job using the ShaderEvent.COMPLETE listener. Like so: shaderJob.addEventListener(ShaderEvent.COMPLETE, onShaderComplete);
private function onShaderComplete(e:Event):void { //Do Something here } See this link for more details. One thing about your code though. You're doing this shader job inside of a sampleDataEvent and I can see this being problematic (possibly) in the sense that your mixing may be out of sync with your playback (that is, if you plan on mixing live and writing the mixed data back into the sound stream). Anyway that's perhaps an issue for a new question. This should solve your problem with needing to know when the mixing is complete. Note you also need to add "false" to the shaderJob.start(false) function. From the documentation about the ShaderEvent.COMPLETE: "Dispatched when a ShaderJob that executes asynchronously finishes processing the data using the shader. A ShaderJob instance executes asynchronously when the start() method is called with a false value for the waitForCompletion parameter." Update In response to your inquiry about how to only process inside the sampleDataEvent if the sound isnt being processed: private var isProcessing:Boolean = false;
private function onSoundData(event:SampleDataEvent):void {
if(isProcessing!= true){
for(var i:int = 0; i < sound.length; i++){ bytes[i] = new ByteArray(); bytes[i].length = BUFFER_SIZE * 4 * 2; sound[i].extract(bytes[i], BUFFER_SIZE);
var volume:Number = 0; bytes[i].position = 0;
for(var j:int = 0; j < BUFFER_SIZE; j++){ volume += Math.abs(bytes[i].readFloat()); volume += Math.abs(bytes[i].readFloat()); }
volume = (volume / (BUFFER_SIZE *.5)) * sliders[i].value;
shader.data['track' + (i + 1)].width = BUFFER_SIZE / 1024; shader.data['track' + (i + 1)].height = 512; shader.data['track' + (i + 1)].input = bytes[i]; shader.data['vol' + (i + 1)].value = [sliders[i].value];
graph[i].scaleY = volume; }
var shaderJob:ShaderJob = new ShaderJob(shader,event.data,BUFFER_SIZE / 1024,512);
shaderJob.start(false); shaderJob.addEventListener(ShaderEvent.COMPLETE, onShaderComplete); var shaderJob2:ShaderJob = new ShaderJob(shader,recBA,BUFFER_SIZE / 1024,512); shaderJob2.start(false);
}
}
private function onShaderComplete(e:ShaderEvent):void { //Do something here isProcessing = false; } | Detect when the Shader is done mixing the audio so this the code with it i am able to mix several tracks with a Shader done in pixel bender. the problem here i don't know when the mixing is finish or all the sound reache their end to be able to save the bytearray into a file any Event or something like that help plz? package { import flash.display.*; import flash.media.*; import flash.events.*; import flash.net.*; import flash.utils.*; import fl.controls.Slider; import org.bytearray.micrecorder.encoder.WaveEncoder;
[SWF(width='500', height='380', frameRate='24')]
public class AudioMixer extends Sprite{
[Embed(source = "sound2.mp3")] private var Track1:Class; [Embed(source = "sound1.mp3")] private var Track2:Class;
[Embed(source = "mix.pbj",mimeType = "application/octet-stream")] private var EmbedShader:Class;
private var shader:Shader = new Shader(new EmbedShader());
private var sound:Vector. = new Vector. (); private var bytes:Vector. = new Vector. (); private var sliders:Vector. = new Vector. (); private var graph:Vector. = new Vector. (); private var recBA:ByteArray = new ByteArray(); private var BUFFER_SIZE:int = 0x800; public var playback:Sound = new Sound(); public var container:Sprite = new Sprite(); public var isEvent:Boolean = false; public function AudioMixer():void{ container.y = stage.stageHeight *.5; addChild(container);
sound.push(new Track1(), new Track2(),new Track2(),new Track2(),new Track2(),new Track2(),new Track2(),new Track2(),new Track2(),new Track2(),new Track2(),new Track2());
for(var i:int = 0; i < sound.length; i++){ var slider:Slider = new Slider(); slider.maximum = 1; slider.minimum = 0; slider.snapInterval = 0.025; slider.value = 0.8; slider.rotation += -90; slider.x = i * 40 + 25; container.addChild(slider); sliders.push(slider);
var line:Shape = new Shape(); line.graphics.lineStyle(1, 0x888888); line.graphics.drawRect(i * 40 + 14, 0, 5, -80); line.graphics.endFill(); container.addChild(line);
var shape:Shape = new Shape(); shape.graphics.beginFill(0x00cc00); shape.graphics.drawRect(i * 40 + 15, 0, 3, -80); shape.graphics.endFill(); container.addChild(shape); graph.push(shape); }
playback.addEventListener(SampleDataEvent.SAMPLE_DATA, onSoundData); playback.play();
}
private function onSoundData(event:SampleDataEvent):void {
for(var i:int = 0; i < sound.length; i++){ bytes[i] = new ByteArray(); bytes[i].length = BUFFER_SIZE * 4 * 2; sound[i].extract(bytes[i], BUFFER_SIZE);
var volume:Number = 0; bytes[i].position = 0;
for(var j:int = 0; j < BUFFER_SIZE; j++){ volume += Math.abs(bytes[i].readFloat()); volume += Math.abs(bytes[i].readFloat()); }
volume = (volume / (BUFFER_SIZE *.5)) * sliders[i].value;
shader.data['track' + (i + 1)].width = BUFFER_SIZE / 1024; shader.data['track' + (i + 1)].height = 512; shader.data['track' + (i + 1)].input = bytes[i]; shader.data['vol' + (i + 1)].value = [sliders[i].value];
graph[i].scaleY = volume; }
var shaderJob:ShaderJob = new ShaderJob(shader,event.data,BUFFER_SIZE / 1024,512);
shaderJob.start(true); var shaderJob2:ShaderJob = new ShaderJob(shader,recBA,BUFFER_SIZE / 1024,512); shaderJob2.start(true);
}
} } | TITLE:
Detect when the Shader is done mixing the audio
QUESTION:
so this the code with it i am able to mix several tracks with a Shader done in pixel bender. the problem here i don't know when the mixing is finish or all the sound reache their end to be able to save the bytearray into a file any Event or something like that help plz? package { import flash.display.*; import flash.media.*; import flash.events.*; import flash.net.*; import flash.utils.*; import fl.controls.Slider; import org.bytearray.micrecorder.encoder.WaveEncoder;
[SWF(width='500', height='380', frameRate='24')]
public class AudioMixer extends Sprite{
[Embed(source = "sound2.mp3")] private var Track1:Class; [Embed(source = "sound1.mp3")] private var Track2:Class;
[Embed(source = "mix.pbj",mimeType = "application/octet-stream")] private var EmbedShader:Class;
private var shader:Shader = new Shader(new EmbedShader());
private var sound:Vector. = new Vector. (); private var bytes:Vector. = new Vector. (); private var sliders:Vector. = new Vector. (); private var graph:Vector. = new Vector. (); private var recBA:ByteArray = new ByteArray(); private var BUFFER_SIZE:int = 0x800; public var playback:Sound = new Sound(); public var container:Sprite = new Sprite(); public var isEvent:Boolean = false; public function AudioMixer():void{ container.y = stage.stageHeight *.5; addChild(container);
sound.push(new Track1(), new Track2(),new Track2(),new Track2(),new Track2(),new Track2(),new Track2(),new Track2(),new Track2(),new Track2(),new Track2(),new Track2());
for(var i:int = 0; i < sound.length; i++){ var slider:Slider = new Slider(); slider.maximum = 1; slider.minimum = 0; slider.snapInterval = 0.025; slider.value = 0.8; slider.rotation += -90; slider.x = i * 40 + 25; container.addChild(slider); sliders.push(slider);
var line:Shape = new Shape(); line.graphics.lineStyle(1, 0x888888); line.graphics.drawRect(i * 40 + 14, 0, 5, -80); line.graphics.endFill(); container.addChild(line);
var shape:Shape = new Shape(); shape.graphics.beginFill(0x00cc00); shape.graphics.drawRect(i * 40 + 15, 0, 3, -80); shape.graphics.endFill(); container.addChild(shape); graph.push(shape); }
playback.addEventListener(SampleDataEvent.SAMPLE_DATA, onSoundData); playback.play();
}
private function onSoundData(event:SampleDataEvent):void {
for(var i:int = 0; i < sound.length; i++){ bytes[i] = new ByteArray(); bytes[i].length = BUFFER_SIZE * 4 * 2; sound[i].extract(bytes[i], BUFFER_SIZE);
var volume:Number = 0; bytes[i].position = 0;
for(var j:int = 0; j < BUFFER_SIZE; j++){ volume += Math.abs(bytes[i].readFloat()); volume += Math.abs(bytes[i].readFloat()); }
volume = (volume / (BUFFER_SIZE *.5)) * sliders[i].value;
shader.data['track' + (i + 1)].width = BUFFER_SIZE / 1024; shader.data['track' + (i + 1)].height = 512; shader.data['track' + (i + 1)].input = bytes[i]; shader.data['vol' + (i + 1)].value = [sliders[i].value];
graph[i].scaleY = volume; }
var shaderJob:ShaderJob = new ShaderJob(shader,event.data,BUFFER_SIZE / 1024,512);
shaderJob.start(true); var shaderJob2:ShaderJob = new ShaderJob(shader,recBA,BUFFER_SIZE / 1024,512); shaderJob2.start(true);
}
} }
ANSWER:
You can tell when a shader has completed it's job using the ShaderEvent.COMPLETE listener. Like so: shaderJob.addEventListener(ShaderEvent.COMPLETE, onShaderComplete);
private function onShaderComplete(e:Event):void { //Do Something here } See this link for more details. One thing about your code though. You're doing this shader job inside of a sampleDataEvent and I can see this being problematic (possibly) in the sense that your mixing may be out of sync with your playback (that is, if you plan on mixing live and writing the mixed data back into the sound stream). Anyway that's perhaps an issue for a new question. This should solve your problem with needing to know when the mixing is complete. Note you also need to add "false" to the shaderJob.start(false) function. From the documentation about the ShaderEvent.COMPLETE: "Dispatched when a ShaderJob that executes asynchronously finishes processing the data using the shader. A ShaderJob instance executes asynchronously when the start() method is called with a false value for the waitForCompletion parameter." Update In response to your inquiry about how to only process inside the sampleDataEvent if the sound isnt being processed: private var isProcessing:Boolean = false;
private function onSoundData(event:SampleDataEvent):void {
if(isProcessing!= true){
for(var i:int = 0; i < sound.length; i++){ bytes[i] = new ByteArray(); bytes[i].length = BUFFER_SIZE * 4 * 2; sound[i].extract(bytes[i], BUFFER_SIZE);
var volume:Number = 0; bytes[i].position = 0;
for(var j:int = 0; j < BUFFER_SIZE; j++){ volume += Math.abs(bytes[i].readFloat()); volume += Math.abs(bytes[i].readFloat()); }
volume = (volume / (BUFFER_SIZE *.5)) * sliders[i].value;
shader.data['track' + (i + 1)].width = BUFFER_SIZE / 1024; shader.data['track' + (i + 1)].height = 512; shader.data['track' + (i + 1)].input = bytes[i]; shader.data['vol' + (i + 1)].value = [sliders[i].value];
graph[i].scaleY = volume; }
var shaderJob:ShaderJob = new ShaderJob(shader,event.data,BUFFER_SIZE / 1024,512);
shaderJob.start(false); shaderJob.addEventListener(ShaderEvent.COMPLETE, onShaderComplete); var shaderJob2:ShaderJob = new ShaderJob(shader,recBA,BUFFER_SIZE / 1024,512); shaderJob2.start(false);
}
}
private function onShaderComplete(e:ShaderEvent):void { //Do something here isProcessing = false; } | [
"actionscript-3",
"pixel-bender"
] | 1 | 0 | 255 | 1 | 0 | 2011-06-10T15:49:36.580000 | 2011-06-10T15:57:19.890000 |
6,308,867 | 6,308,927 | Database Queries in Open Source PHP Projects? | Downloaded a few open source php scripts such as Wordpress and Moodle to study the way they structure there code etc. However when looking through both of these scripts I am always unable to find there database queries (select, insert, update)? Why are they so hidden and how do I find them? | They may actually be generated through an ORM layer. Which is an object that generates a query through the object methods. | Database Queries in Open Source PHP Projects? Downloaded a few open source php scripts such as Wordpress and Moodle to study the way they structure there code etc. However when looking through both of these scripts I am always unable to find there database queries (select, insert, update)? Why are they so hidden and how do I find them? | TITLE:
Database Queries in Open Source PHP Projects?
QUESTION:
Downloaded a few open source php scripts such as Wordpress and Moodle to study the way they structure there code etc. However when looking through both of these scripts I am always unable to find there database queries (select, insert, update)? Why are they so hidden and how do I find them?
ANSWER:
They may actually be generated through an ORM layer. Which is an object that generates a query through the object methods. | [
"php",
"database",
"project"
] | 1 | 4 | 204 | 4 | 0 | 2011-06-10T15:50:44.073000 | 2011-06-10T15:55:15.963000 |
6,308,882 | 6,308,977 | Variable undefined in JS | I have some code I copied from an example and I am not certain I understand it, and it is giving me an error that didn't happen when I first used is. On this page: http://www.comehike.com/hikes/uncancel_hike.php?hike_id=30 I get the error: x is not defined on line 84 I am not too certain what x is supposed to be there. Any help appreciated, especially in helping me understand what is happening here:) Here is the code: function getCall(fn, param) { return function(e) { e = e || window.event; e.preventDefault(); // this might let you use real URLs instead of void(0) fn(e, param); }; }
window.onload = function() { var a = document.getElementById("mylink"); a.onclick = getCall(deleteHike, x ); }; | In your code here x is a parameter that will be passed into the function deleteHike and should be defined, or left null if you do not want a parameter, not knowing what deleteHike does here. Your code will wire up an event when the page is loaded to the element myLink. When that element is clicked even info from the browser along with an extra parameter ( x ) will be passed into the function named deleteHike. Does that explain it? | Variable undefined in JS I have some code I copied from an example and I am not certain I understand it, and it is giving me an error that didn't happen when I first used is. On this page: http://www.comehike.com/hikes/uncancel_hike.php?hike_id=30 I get the error: x is not defined on line 84 I am not too certain what x is supposed to be there. Any help appreciated, especially in helping me understand what is happening here:) Here is the code: function getCall(fn, param) { return function(e) { e = e || window.event; e.preventDefault(); // this might let you use real URLs instead of void(0) fn(e, param); }; }
window.onload = function() { var a = document.getElementById("mylink"); a.onclick = getCall(deleteHike, x ); }; | TITLE:
Variable undefined in JS
QUESTION:
I have some code I copied from an example and I am not certain I understand it, and it is giving me an error that didn't happen when I first used is. On this page: http://www.comehike.com/hikes/uncancel_hike.php?hike_id=30 I get the error: x is not defined on line 84 I am not too certain what x is supposed to be there. Any help appreciated, especially in helping me understand what is happening here:) Here is the code: function getCall(fn, param) { return function(e) { e = e || window.event; e.preventDefault(); // this might let you use real URLs instead of void(0) fn(e, param); }; }
window.onload = function() { var a = document.getElementById("mylink"); a.onclick = getCall(deleteHike, x ); };
ANSWER:
In your code here x is a parameter that will be passed into the function deleteHike and should be defined, or left null if you do not want a parameter, not knowing what deleteHike does here. Your code will wire up an event when the page is loaded to the element myLink. When that element is clicked even info from the browser along with an extra parameter ( x ) will be passed into the function named deleteHike. Does that explain it? | [
"javascript"
] | 0 | 2 | 93 | 2 | 0 | 2011-06-10T15:51:37.453000 | 2011-06-10T15:58:53.343000 |
6,308,913 | 6,308,935 | Test method or try-catch? | I was hoping that someone could tell me the best practice for the scenario I am running into with testing my code via junit4. My pseudocode is as follows: public class TestClass {
private String readFromFile(String filePath) { use BufferedReader, get content file input append BufferedReader to StringBuffer return string }
@Test public void testMethodOne() { String s = readFromFile(C:\fileOne); doStuff(s); } } The issue that I am having is that BufferedReader can throw an IOException. If the readFromFile() method is not a method in the test I am classing (I only need it for these test scenarios), do I annotate it with @Test (expected = IOException.class) anyway, or should I use a try-catch block? Thank you very much! | If it throws an exception and you're not expecting it to, then it's an exceptional situation. If the file cannot be read and the test cannot be performed, it's an error, it's not something related to the tests themselves. Add throws to the readFromFile method and to the test methods using it. | Test method or try-catch? I was hoping that someone could tell me the best practice for the scenario I am running into with testing my code via junit4. My pseudocode is as follows: public class TestClass {
private String readFromFile(String filePath) { use BufferedReader, get content file input append BufferedReader to StringBuffer return string }
@Test public void testMethodOne() { String s = readFromFile(C:\fileOne); doStuff(s); } } The issue that I am having is that BufferedReader can throw an IOException. If the readFromFile() method is not a method in the test I am classing (I only need it for these test scenarios), do I annotate it with @Test (expected = IOException.class) anyway, or should I use a try-catch block? Thank you very much! | TITLE:
Test method or try-catch?
QUESTION:
I was hoping that someone could tell me the best practice for the scenario I am running into with testing my code via junit4. My pseudocode is as follows: public class TestClass {
private String readFromFile(String filePath) { use BufferedReader, get content file input append BufferedReader to StringBuffer return string }
@Test public void testMethodOne() { String s = readFromFile(C:\fileOne); doStuff(s); } } The issue that I am having is that BufferedReader can throw an IOException. If the readFromFile() method is not a method in the test I am classing (I only need it for these test scenarios), do I annotate it with @Test (expected = IOException.class) anyway, or should I use a try-catch block? Thank you very much!
ANSWER:
If it throws an exception and you're not expecting it to, then it's an exceptional situation. If the file cannot be read and the test cannot be performed, it's an error, it's not something related to the tests themselves. Add throws to the readFromFile method and to the test methods using it. | [
"java",
"junit4"
] | 0 | 2 | 122 | 1 | 0 | 2011-06-10T15:53:51.287000 | 2011-06-10T15:55:56.177000 |
6,308,915 | 6,308,938 | Member fields, order of construction | In C++, when doing something like what you see below, is the order of construction guaranteed? Logger::Logger(): kFilePath_("../logs/runtime.log"), logFile_(kFilePath_) { //... } | Yes, the order of construction is always guaranteed. It is not, however, guaranteed to be the same as the order in which the objects appear in the initializer list. Member variables are constructed in the order in which they are declared in the body of the class. For example: struct A { }; struct B { };
struct S { A a; B b;
S(): b(), a() { } }; a is constructed first, then b. The order in which member variables appear in the initializer list is irrelevant. | Member fields, order of construction In C++, when doing something like what you see below, is the order of construction guaranteed? Logger::Logger(): kFilePath_("../logs/runtime.log"), logFile_(kFilePath_) { //... } | TITLE:
Member fields, order of construction
QUESTION:
In C++, when doing something like what you see below, is the order of construction guaranteed? Logger::Logger(): kFilePath_("../logs/runtime.log"), logFile_(kFilePath_) { //... }
ANSWER:
Yes, the order of construction is always guaranteed. It is not, however, guaranteed to be the same as the order in which the objects appear in the initializer list. Member variables are constructed in the order in which they are declared in the body of the class. For example: struct A { }; struct B { };
struct S { A a; B b;
S(): b(), a() { } }; a is constructed first, then b. The order in which member variables appear in the initializer list is irrelevant. | [
"c++",
"initialization"
] | 8 | 29 | 4,521 | 2 | 0 | 2011-06-10T15:54:04.320000 | 2011-06-10T15:56:06.313000 |
6,308,917 | 6,309,011 | Execute python command in django admin panel | Is it possible to execute python command in admin panel or in django view?I. e. if I would like to sync database in my app using a button. | Write a custom admin view featuring a form, and when the form is submitted in the view call django.core.management.call_command Remark regarding using a form: As your request will change things at the server-side, a post must be preferred over a get. | Execute python command in django admin panel Is it possible to execute python command in admin panel or in django view?I. e. if I would like to sync database in my app using a button. | TITLE:
Execute python command in django admin panel
QUESTION:
Is it possible to execute python command in admin panel or in django view?I. e. if I would like to sync database in my app using a button.
ANSWER:
Write a custom admin view featuring a form, and when the form is submitted in the view call django.core.management.call_command Remark regarding using a form: As your request will change things at the server-side, a post must be preferred over a get. | [
"python",
"django"
] | 3 | 3 | 2,963 | 1 | 0 | 2011-06-10T15:54:22.153000 | 2011-06-10T16:01:41.447000 |
6,308,931 | 6,309,019 | Java singleton with inheritance | I have a set of singleton classes and I want to avoid boilerplate code. Here is what I have now: public class Mammal { protected Mammal() {} }
public class Cat extends Mammal { static protected Cat instance = null; static public Cat getInstance() { if (null == instance) { instance = new Cat(); } return instance; }
private Cat() { // something cat-specific } } This works and there's nothing wrong with it, except that I have many subclasses of Mammal that must replicate the getInstance() method. I would prefer something like this, if possible: public class Mammal { protected Mammal() {}
static protected Mammal instance = null;
static public Mammal getInstance() { if (null == instance) { instance = new Mammal(); } return instance; } }
public class Cat extends Mammal { private Cat() { // something cat-specific } } How do I do that? | You can't since constructors are neither inherited nor overridable. The new Mammal() in your desired example creates only a Mammal, not one of its subclasses. I suggest you look at the Factory pattern, or go to something like Spring, which is intended for just this situation. | Java singleton with inheritance I have a set of singleton classes and I want to avoid boilerplate code. Here is what I have now: public class Mammal { protected Mammal() {} }
public class Cat extends Mammal { static protected Cat instance = null; static public Cat getInstance() { if (null == instance) { instance = new Cat(); } return instance; }
private Cat() { // something cat-specific } } This works and there's nothing wrong with it, except that I have many subclasses of Mammal that must replicate the getInstance() method. I would prefer something like this, if possible: public class Mammal { protected Mammal() {}
static protected Mammal instance = null;
static public Mammal getInstance() { if (null == instance) { instance = new Mammal(); } return instance; } }
public class Cat extends Mammal { private Cat() { // something cat-specific } } How do I do that? | TITLE:
Java singleton with inheritance
QUESTION:
I have a set of singleton classes and I want to avoid boilerplate code. Here is what I have now: public class Mammal { protected Mammal() {} }
public class Cat extends Mammal { static protected Cat instance = null; static public Cat getInstance() { if (null == instance) { instance = new Cat(); } return instance; }
private Cat() { // something cat-specific } } This works and there's nothing wrong with it, except that I have many subclasses of Mammal that must replicate the getInstance() method. I would prefer something like this, if possible: public class Mammal { protected Mammal() {}
static protected Mammal instance = null;
static public Mammal getInstance() { if (null == instance) { instance = new Mammal(); } return instance; } }
public class Cat extends Mammal { private Cat() { // something cat-specific } } How do I do that?
ANSWER:
You can't since constructors are neither inherited nor overridable. The new Mammal() in your desired example creates only a Mammal, not one of its subclasses. I suggest you look at the Factory pattern, or go to something like Spring, which is intended for just this situation. | [
"java",
"inheritance",
"singleton",
"code-formatting"
] | 8 | 3 | 3,811 | 3 | 0 | 2011-06-10T15:55:24.967000 | 2011-06-10T16:02:26.173000 |
6,308,933 | 6,308,972 | Concatenate row-wise across specific columns of dataframe | I have a data frame with columns that, when concatenated (row-wise) as a string, would allow me to partition the data frame into a desired form. > str(data) 'data.frame': 680420 obs. of 10 variables: $ A: chr "2011-01-26" "2011-01-26" "2011-02-09" "2011-02-09"... $ B: chr "2011-01-26" "2011-01-27" "2011-02-09" "2011-02-10"... $ C: chr "2011-01-26" "2011-01-26" "2011-02-09" "2011-02-09"... $ D: chr "AAA" "AAA" "BCB" "CCC"... $ E: chr "A00001" "A00002" "B00002" "B00001"... $ F: int 9 9 37 37 37 37 191 191 191 191... $ G: int NA NA NA NA NA NA NA NA NA NA... $ H: int 4 4 4 4 4 4 4 4 4 4... For each row, I would like to concatenate the data in columns F, E, D, and C into a string (with the underscore character as separator). Below is my unsuccessful attempt at this: data$id <- sapply(as.data.frame(cbind(data$F,data$E,data$D,data$C)), paste, sep="_") And below is the undesired result: > str(data) 'data.frame': 680420 obs. of 10 variables: $ A: chr "2011-01-26" "2011-01-26" "2011-02-09" "2011-02-09"... $ B: chr "2011-01-26" "2011-01-27" "2011-02-09" "2011-02-10"... $ C: chr "2011-01-26" "2011-01-26" "2011-02-09" "2011-02-09"... $ D: chr "AAA" "AAA" "BCB" "CCC"... $ E: chr "A00001" "A00002" "B00002" "B00001"... $ F: int 9 9 37 37 37 37 191 191 191 191... $ G: int NA NA NA NA NA NA NA NA NA NA... $ H: int 4 4 4 4 4 4 4 4 4 4... $ id: chr [1:680420, 1:4] "9" "9" "37" "37".....- attr(*, "dimnames")=List of 2....$: NULL....$: chr "V1" "V2" "V3" "V4" Any help would be greatly appreciated. | Try data$id <- paste(data$F, data$E, data$D, data$C, sep="_") instead. The beauty of vectorized code is that you do not need row-by-row loops, or loop-equivalent *apply functions. Edit Even better is data <- within(data, id <- paste(F, E, D, C, sep="")) | Concatenate row-wise across specific columns of dataframe I have a data frame with columns that, when concatenated (row-wise) as a string, would allow me to partition the data frame into a desired form. > str(data) 'data.frame': 680420 obs. of 10 variables: $ A: chr "2011-01-26" "2011-01-26" "2011-02-09" "2011-02-09"... $ B: chr "2011-01-26" "2011-01-27" "2011-02-09" "2011-02-10"... $ C: chr "2011-01-26" "2011-01-26" "2011-02-09" "2011-02-09"... $ D: chr "AAA" "AAA" "BCB" "CCC"... $ E: chr "A00001" "A00002" "B00002" "B00001"... $ F: int 9 9 37 37 37 37 191 191 191 191... $ G: int NA NA NA NA NA NA NA NA NA NA... $ H: int 4 4 4 4 4 4 4 4 4 4... For each row, I would like to concatenate the data in columns F, E, D, and C into a string (with the underscore character as separator). Below is my unsuccessful attempt at this: data$id <- sapply(as.data.frame(cbind(data$F,data$E,data$D,data$C)), paste, sep="_") And below is the undesired result: > str(data) 'data.frame': 680420 obs. of 10 variables: $ A: chr "2011-01-26" "2011-01-26" "2011-02-09" "2011-02-09"... $ B: chr "2011-01-26" "2011-01-27" "2011-02-09" "2011-02-10"... $ C: chr "2011-01-26" "2011-01-26" "2011-02-09" "2011-02-09"... $ D: chr "AAA" "AAA" "BCB" "CCC"... $ E: chr "A00001" "A00002" "B00002" "B00001"... $ F: int 9 9 37 37 37 37 191 191 191 191... $ G: int NA NA NA NA NA NA NA NA NA NA... $ H: int 4 4 4 4 4 4 4 4 4 4... $ id: chr [1:680420, 1:4] "9" "9" "37" "37".....- attr(*, "dimnames")=List of 2....$: NULL....$: chr "V1" "V2" "V3" "V4" Any help would be greatly appreciated. | TITLE:
Concatenate row-wise across specific columns of dataframe
QUESTION:
I have a data frame with columns that, when concatenated (row-wise) as a string, would allow me to partition the data frame into a desired form. > str(data) 'data.frame': 680420 obs. of 10 variables: $ A: chr "2011-01-26" "2011-01-26" "2011-02-09" "2011-02-09"... $ B: chr "2011-01-26" "2011-01-27" "2011-02-09" "2011-02-10"... $ C: chr "2011-01-26" "2011-01-26" "2011-02-09" "2011-02-09"... $ D: chr "AAA" "AAA" "BCB" "CCC"... $ E: chr "A00001" "A00002" "B00002" "B00001"... $ F: int 9 9 37 37 37 37 191 191 191 191... $ G: int NA NA NA NA NA NA NA NA NA NA... $ H: int 4 4 4 4 4 4 4 4 4 4... For each row, I would like to concatenate the data in columns F, E, D, and C into a string (with the underscore character as separator). Below is my unsuccessful attempt at this: data$id <- sapply(as.data.frame(cbind(data$F,data$E,data$D,data$C)), paste, sep="_") And below is the undesired result: > str(data) 'data.frame': 680420 obs. of 10 variables: $ A: chr "2011-01-26" "2011-01-26" "2011-02-09" "2011-02-09"... $ B: chr "2011-01-26" "2011-01-27" "2011-02-09" "2011-02-10"... $ C: chr "2011-01-26" "2011-01-26" "2011-02-09" "2011-02-09"... $ D: chr "AAA" "AAA" "BCB" "CCC"... $ E: chr "A00001" "A00002" "B00002" "B00001"... $ F: int 9 9 37 37 37 37 191 191 191 191... $ G: int NA NA NA NA NA NA NA NA NA NA... $ H: int 4 4 4 4 4 4 4 4 4 4... $ id: chr [1:680420, 1:4] "9" "9" "37" "37".....- attr(*, "dimnames")=List of 2....$: NULL....$: chr "V1" "V2" "V3" "V4" Any help would be greatly appreciated.
ANSWER:
Try data$id <- paste(data$F, data$E, data$D, data$C, sep="_") instead. The beauty of vectorized code is that you do not need row-by-row loops, or loop-equivalent *apply functions. Edit Even better is data <- within(data, id <- paste(F, E, D, C, sep="")) | [
"r",
"apply",
"paste",
"string-concatenation",
"sapply"
] | 39 | 69 | 73,984 | 3 | 0 | 2011-06-10T15:55:36.847000 | 2011-06-10T15:58:20.910000 |
6,308,950 | 6,309,323 | Capture Yahoo finance stock data symbols for daily break out, leaders, etc? | I am trying to figure out if there is a way to capture using free Yahoo Finance stock data: 1. Daily 'leaders' with stock symbols, ETFs, options, etc. 2. Any breakout symbols using any classic tecnical analysis indicatoras? 3. Can this be done in real time? Does any one know of a way to do this using programmatic or automated way? I have used the classic 'wget' or C# request methods. Any URLs would be helpful. I just want to output the actual symbols into a text, XML, or CSV format. Many Thanks | Last time I used Yahoo's data was about a year ago and they didn't have an API, so I had to request all the data by modifying the URL. You can find all of the information on my blog. Daily 'leaders' with stock symbols, ETFs, options, etc. As far as I know, there is no query which would result in "daily leaders", but if it's part of the quote (which it may be), then you should be able to get it. Any breakout symbols using any classic tecnical analysis [indicators]? Again, I don't know of any way to query for technical indicators in a manner that would show you the breakout symbols. However, if it's part of a quote, then you should be able to get it. Can this be done in real time? Does any one know of a way to do this using programmatic or automated way? Yes and no... you can query the data frequently, but Yahoo only updates the data every 15 minutes. They do update some of the symbols in "real time", so you can get updates as frequently as you hit up Yahoo and as frequently as Yahoo refreshes the information. I have used the classic 'wget' or C# request methods. Any URLs would be helpful. I just want to output the actual symbols into a text, XML, or CSV format. Many Thanks Gummy stuff is VERY informative when it comes to querying Yahoo data. You can query most of the data shown on yahoo finance. Note that there are a lot more things that are considered as part of the "quote" than just the Open, High, Low and Close, so you might be able to get all the information that you need. You can get quotes in CSV format: http://finance.yahoo.com/d/quotes.csv?s= + STOCK_SYMBOL(S) + &f= + TAG(S) You can also get historical data in CSV format: http://www.google.com/finance/historical?q= STOCK_SYMBOL(S) + & + output=csv | Capture Yahoo finance stock data symbols for daily break out, leaders, etc? I am trying to figure out if there is a way to capture using free Yahoo Finance stock data: 1. Daily 'leaders' with stock symbols, ETFs, options, etc. 2. Any breakout symbols using any classic tecnical analysis indicatoras? 3. Can this be done in real time? Does any one know of a way to do this using programmatic or automated way? I have used the classic 'wget' or C# request methods. Any URLs would be helpful. I just want to output the actual symbols into a text, XML, or CSV format. Many Thanks | TITLE:
Capture Yahoo finance stock data symbols for daily break out, leaders, etc?
QUESTION:
I am trying to figure out if there is a way to capture using free Yahoo Finance stock data: 1. Daily 'leaders' with stock symbols, ETFs, options, etc. 2. Any breakout symbols using any classic tecnical analysis indicatoras? 3. Can this be done in real time? Does any one know of a way to do this using programmatic or automated way? I have used the classic 'wget' or C# request methods. Any URLs would be helpful. I just want to output the actual symbols into a text, XML, or CSV format. Many Thanks
ANSWER:
Last time I used Yahoo's data was about a year ago and they didn't have an API, so I had to request all the data by modifying the URL. You can find all of the information on my blog. Daily 'leaders' with stock symbols, ETFs, options, etc. As far as I know, there is no query which would result in "daily leaders", but if it's part of the quote (which it may be), then you should be able to get it. Any breakout symbols using any classic tecnical analysis [indicators]? Again, I don't know of any way to query for technical indicators in a manner that would show you the breakout symbols. However, if it's part of a quote, then you should be able to get it. Can this be done in real time? Does any one know of a way to do this using programmatic or automated way? Yes and no... you can query the data frequently, but Yahoo only updates the data every 15 minutes. They do update some of the symbols in "real time", so you can get updates as frequently as you hit up Yahoo and as frequently as Yahoo refreshes the information. I have used the classic 'wget' or C# request methods. Any URLs would be helpful. I just want to output the actual symbols into a text, XML, or CSV format. Many Thanks Gummy stuff is VERY informative when it comes to querying Yahoo data. You can query most of the data shown on yahoo finance. Note that there are a lot more things that are considered as part of the "quote" than just the Open, High, Low and Close, so you might be able to get all the information that you need. You can get quotes in CSV format: http://finance.yahoo.com/d/quotes.csv?s= + STOCK_SYMBOL(S) + &f= + TAG(S) You can also get historical data in CSV format: http://www.google.com/finance/historical?q= STOCK_SYMBOL(S) + & + output=csv | [
"c#",
"stocks",
"stockquotes",
"yahoo-finance"
] | 1 | 3 | 6,455 | 2 | 0 | 2011-06-10T15:56:40.420000 | 2011-06-10T16:25:54.447000 |
6,308,962 | 6,310,366 | Using Javascript to hide/show all text | I have an ASP page that retrieves text from a database but the formatting looks awkward because there's a lot of text and it stretches the page until the end. I'm looking for a solution in javascript that will condense this text into a few lines and have an option to show all once a button is clicked. I'm completely new to embedding javascript in pages but I think this is the simplest way to do it. | Note that your asp will, more or less, not be in contact with your Javascript. They are very separate things. That being said, you can have a flag in the C# code and then grab that value in Javascript <%= num; %>, check if it's true, and commit your code. (or better yet check on post back) What you are trying to do sounds like you want to change the style of where the text is being put. In your javascript, grab the paragraph area. Do this by giving the paragraph an id: and then call it in javascript and set it as a variable: var text = document.getelementbyid('jollies'); then you can change some aspects about the text, for instance hiding it, size and other things... all under the text.style.[param] If you want to have it shown/hidden in javascript, have a button that is not runat server to have onclick="myjavascriptfunction()" that hides the said text visiblity:hidden; and so on. | Using Javascript to hide/show all text I have an ASP page that retrieves text from a database but the formatting looks awkward because there's a lot of text and it stretches the page until the end. I'm looking for a solution in javascript that will condense this text into a few lines and have an option to show all once a button is clicked. I'm completely new to embedding javascript in pages but I think this is the simplest way to do it. | TITLE:
Using Javascript to hide/show all text
QUESTION:
I have an ASP page that retrieves text from a database but the formatting looks awkward because there's a lot of text and it stretches the page until the end. I'm looking for a solution in javascript that will condense this text into a few lines and have an option to show all once a button is clicked. I'm completely new to embedding javascript in pages but I think this is the simplest way to do it.
ANSWER:
Note that your asp will, more or less, not be in contact with your Javascript. They are very separate things. That being said, you can have a flag in the C# code and then grab that value in Javascript <%= num; %>, check if it's true, and commit your code. (or better yet check on post back) What you are trying to do sounds like you want to change the style of where the text is being put. In your javascript, grab the paragraph area. Do this by giving the paragraph an id: and then call it in javascript and set it as a variable: var text = document.getelementbyid('jollies'); then you can change some aspects about the text, for instance hiding it, size and other things... all under the text.style.[param] If you want to have it shown/hidden in javascript, have a button that is not runat server to have onclick="myjavascriptfunction()" that hides the said text visiblity:hidden; and so on. | [
"javascript",
"asp.net"
] | 0 | 0 | 190 | 2 | 0 | 2011-06-10T15:57:41.330000 | 2011-06-10T18:06:42.703000 |
6,308,963 | 6,309,008 | Downloading speed limitation in MVC.NET | I have MVC.NET 2.0 project. It allows clients to download files which are stored on server. I use FileContentResult class for these purposes. How do I can add limitation of maximum downloading speed for unregistered users? | There is not automagic way to accomplish this. You will have to take control of the response stream and throttle it. As a quick example, you can look at this URI (notice it is not necessarily THE answer to your problem, but an example): http://www.codeproject.com/KB/IP/Bandwidth_throttling.aspx Translated, this means is you are not going to solve this through MVC alone. | Downloading speed limitation in MVC.NET I have MVC.NET 2.0 project. It allows clients to download files which are stored on server. I use FileContentResult class for these purposes. How do I can add limitation of maximum downloading speed for unregistered users? | TITLE:
Downloading speed limitation in MVC.NET
QUESTION:
I have MVC.NET 2.0 project. It allows clients to download files which are stored on server. I use FileContentResult class for these purposes. How do I can add limitation of maximum downloading speed for unregistered users?
ANSWER:
There is not automagic way to accomplish this. You will have to take control of the response stream and throttle it. As a quick example, you can look at this URI (notice it is not necessarily THE answer to your problem, but an example): http://www.codeproject.com/KB/IP/Bandwidth_throttling.aspx Translated, this means is you are not going to solve this through MVC alone. | [
"asp.net-mvc"
] | 0 | 2 | 214 | 2 | 0 | 2011-06-10T15:57:45.810000 | 2011-06-10T16:01:35.630000 |
6,308,967 | 6,309,240 | Javascript - Problem comparing dates | The code below is giving me trouble. When I select July 1st 11:00pm for fromDate, result 3 is being set to Thu Jun 02 2011 11:52:26. I check the values of fromDate and toDate in chrome and they seem fine but result 3 is getting set to a wacky date. Any solutions? function(value, element, params) { fromDate = new Date(startDate.val()); toDate = new Date(endDate.val()); result1 = this.optional(element); result2 = fromDate <= toDate; result3 = new Date(); result3.setDate(fromDate.getDate()+1); result5 = (toDate.getDate()+0); result4 = (fromDate.getDate()+1)>(toDate.getDate()+0); return result1 || (result2 && result4); } | result3.setDate(fromDate.getDate()+1) only sets the day of the month of your Date object. Since result3 creates a new Date object, this means that result3 is not having its time set correctly. If you want to set result3 to fromDate plus one day, you'll have to do something like this: var DAY_IN_MILLISECONDS = 1000 * 60 * 60 * 24; result3 = new Date(fromDate + DAY_IN_MILLISECONDS); However, since I'm not sure what your variables represent, it's hard to diagnose. | Javascript - Problem comparing dates The code below is giving me trouble. When I select July 1st 11:00pm for fromDate, result 3 is being set to Thu Jun 02 2011 11:52:26. I check the values of fromDate and toDate in chrome and they seem fine but result 3 is getting set to a wacky date. Any solutions? function(value, element, params) { fromDate = new Date(startDate.val()); toDate = new Date(endDate.val()); result1 = this.optional(element); result2 = fromDate <= toDate; result3 = new Date(); result3.setDate(fromDate.getDate()+1); result5 = (toDate.getDate()+0); result4 = (fromDate.getDate()+1)>(toDate.getDate()+0); return result1 || (result2 && result4); } | TITLE:
Javascript - Problem comparing dates
QUESTION:
The code below is giving me trouble. When I select July 1st 11:00pm for fromDate, result 3 is being set to Thu Jun 02 2011 11:52:26. I check the values of fromDate and toDate in chrome and they seem fine but result 3 is getting set to a wacky date. Any solutions? function(value, element, params) { fromDate = new Date(startDate.val()); toDate = new Date(endDate.val()); result1 = this.optional(element); result2 = fromDate <= toDate; result3 = new Date(); result3.setDate(fromDate.getDate()+1); result5 = (toDate.getDate()+0); result4 = (fromDate.getDate()+1)>(toDate.getDate()+0); return result1 || (result2 && result4); }
ANSWER:
result3.setDate(fromDate.getDate()+1) only sets the day of the month of your Date object. Since result3 creates a new Date object, this means that result3 is not having its time set correctly. If you want to set result3 to fromDate plus one day, you'll have to do something like this: var DAY_IN_MILLISECONDS = 1000 * 60 * 60 * 24; result3 = new Date(fromDate + DAY_IN_MILLISECONDS); However, since I'm not sure what your variables represent, it's hard to diagnose. | [
"javascript"
] | 0 | 1 | 104 | 1 | 0 | 2011-06-10T15:57:55.003000 | 2011-06-10T16:20:24.917000 |
6,308,970 | 6,309,406 | How can I replicate a div a certain number of times based on a select-box value? | I am trying to make a script that, when I choose in the dropdown 4, the div is repeated 4 times. repeat Now the problem is repeat the number of times that the user choose in dropdown. demo | Listening to the "onchange" event on the select element will give you the feedback you need to modify the document structure. Fiddle example HTML JavaScript var select_element = document.createElement("select"); var option_element;
for (var i = 0; i < 10; i++) { option_element = document.createElement("option"); option_element.value = i; option_element.text = i; select_element.appendChild(option_element); }
select_element.addEventListener("change", function (event) { var repeat_container = document.getElementById("repeat"); var div_element;
// Remove previously added divs while (repeat_container.firstChild) { repeat_container.removeChild(repeat_container.firstChild); }
// Add new divs for (var i = 0; i < event.currentTarget.value; i++) { div_element = document.createElement("div"); div_element.style.backgroundColor = "rgb(0,255," + (i * 20) + ")"; div_element.style.height = "10px"; repeat_container.appendChild(div_element); } }, false);
document.body.appendChild(select_element); | How can I replicate a div a certain number of times based on a select-box value? I am trying to make a script that, when I choose in the dropdown 4, the div is repeated 4 times. repeat Now the problem is repeat the number of times that the user choose in dropdown. demo | TITLE:
How can I replicate a div a certain number of times based on a select-box value?
QUESTION:
I am trying to make a script that, when I choose in the dropdown 4, the div is repeated 4 times. repeat Now the problem is repeat the number of times that the user choose in dropdown. demo
ANSWER:
Listening to the "onchange" event on the select element will give you the feedback you need to modify the document structure. Fiddle example HTML JavaScript var select_element = document.createElement("select"); var option_element;
for (var i = 0; i < 10; i++) { option_element = document.createElement("option"); option_element.value = i; option_element.text = i; select_element.appendChild(option_element); }
select_element.addEventListener("change", function (event) { var repeat_container = document.getElementById("repeat"); var div_element;
// Remove previously added divs while (repeat_container.firstChild) { repeat_container.removeChild(repeat_container.firstChild); }
// Add new divs for (var i = 0; i < event.currentTarget.value; i++) { div_element = document.createElement("div"); div_element.style.backgroundColor = "rgb(0,255," + (i * 20) + ")"; div_element.style.height = "10px"; repeat_container.appendChild(div_element); } }, false);
document.body.appendChild(select_element); | [
"javascript",
"jquery",
"loops"
] | 1 | 3 | 6,532 | 4 | 0 | 2011-06-10T15:58:15.560000 | 2011-06-10T16:33:27.897000 |
6,308,983 | 6,309,038 | Weird SQL behavior with INSERT and WHERE NOT EXISTS | I have this query, which should insert an amount if an amount equals or higher for the same ID doesn't already exists in the table. I tried this under MySQL 5.1 and MSSQL 2k5: MySQL INSERT IGNORE INTO test (id, amount) SELECT 6, 50 FROM test WHERE NOT EXISTS (SELECT 1 FROM test WHERE amount >= 50 AND id = 6) LIMIT 1 MSSQL INSERT INTO test (id, amount) SELECT 6, 50 FROM test WHERE NOT EXISTS (SELECT TOP 1 1 FROM test WHERE amount >= 50 AND id = 6) This query works fine IF there is already at least one entry in the table. If the table is empty, it will never work. It's the same behavior under MySQL (5.1) and MSSQL (2005). I don't understand why. Anybody has an explanation and a way to fix this query to work even if the table is completely empty? EDIT: I need this for MySQL mostly... UPDATE: I started a new question specifically for MySQL: MySQL Problem with inserting a row with certain conditions | It fails because the select statement selects values of 6 and 50 based on the number of rows returned. Since your table is empty - no rows are returned to have these values. Modify it to INSERT INTO test (id, amount) SELECT 6, 50 WHERE NOT EXISTS (SELECT TOP 1 1 FROM test WHERE amount >= 50 AND id = 6) | Weird SQL behavior with INSERT and WHERE NOT EXISTS I have this query, which should insert an amount if an amount equals or higher for the same ID doesn't already exists in the table. I tried this under MySQL 5.1 and MSSQL 2k5: MySQL INSERT IGNORE INTO test (id, amount) SELECT 6, 50 FROM test WHERE NOT EXISTS (SELECT 1 FROM test WHERE amount >= 50 AND id = 6) LIMIT 1 MSSQL INSERT INTO test (id, amount) SELECT 6, 50 FROM test WHERE NOT EXISTS (SELECT TOP 1 1 FROM test WHERE amount >= 50 AND id = 6) This query works fine IF there is already at least one entry in the table. If the table is empty, it will never work. It's the same behavior under MySQL (5.1) and MSSQL (2005). I don't understand why. Anybody has an explanation and a way to fix this query to work even if the table is completely empty? EDIT: I need this for MySQL mostly... UPDATE: I started a new question specifically for MySQL: MySQL Problem with inserting a row with certain conditions | TITLE:
Weird SQL behavior with INSERT and WHERE NOT EXISTS
QUESTION:
I have this query, which should insert an amount if an amount equals or higher for the same ID doesn't already exists in the table. I tried this under MySQL 5.1 and MSSQL 2k5: MySQL INSERT IGNORE INTO test (id, amount) SELECT 6, 50 FROM test WHERE NOT EXISTS (SELECT 1 FROM test WHERE amount >= 50 AND id = 6) LIMIT 1 MSSQL INSERT INTO test (id, amount) SELECT 6, 50 FROM test WHERE NOT EXISTS (SELECT TOP 1 1 FROM test WHERE amount >= 50 AND id = 6) This query works fine IF there is already at least one entry in the table. If the table is empty, it will never work. It's the same behavior under MySQL (5.1) and MSSQL (2005). I don't understand why. Anybody has an explanation and a way to fix this query to work even if the table is completely empty? EDIT: I need this for MySQL mostly... UPDATE: I started a new question specifically for MySQL: MySQL Problem with inserting a row with certain conditions
ANSWER:
It fails because the select statement selects values of 6 and 50 based on the number of rows returned. Since your table is empty - no rows are returned to have these values. Modify it to INSERT INTO test (id, amount) SELECT 6, 50 WHERE NOT EXISTS (SELECT TOP 1 1 FROM test WHERE amount >= 50 AND id = 6) | [
"sql",
"insert"
] | 0 | 2 | 684 | 4 | 0 | 2011-06-10T15:59:26.683000 | 2011-06-10T16:04:21.510000 |
6,308,985 | 6,309,027 | Running jQuery function after all media is loaded | I have a simple jQuery script which pushes the footer to the bottom of the page, even if the content is not long enough: $(document).ready(function(){ positionFooter(); function positionFooter(){ //get the div's padding var padding_top = $("#footer").css("padding-top").replace("px", ""); //get the current page height - the padding of the footer var page_height = $(document.body).height() - padding_top; var window_height = $(window).height(); //calculate the difference between page and window height var difference = window_height - page_height; if (difference < 0) difference = 0; //write the changes to the div $("#footer").css({ padding: difference + "px 0 0 0" }) } //re-run the function if browser window is resized $(window).resize(positionFooter) }); Unfortunately the (document).ready trigger is to early and dose not consider image & font loading, so the value that is calculated is incorrect. Is there a trigger that is suited for this kind of tasks? Also the site I'm building is using Disqus fot comments, which also changes the page length again, though I think I need a call-back from the Disqus script to take that change into consideration. | try $(window).load() You may also want to check the jQuery documentation on the different document loading events: http://api.jquery.com/category/events/document-loading/ Hope it helps | Running jQuery function after all media is loaded I have a simple jQuery script which pushes the footer to the bottom of the page, even if the content is not long enough: $(document).ready(function(){ positionFooter(); function positionFooter(){ //get the div's padding var padding_top = $("#footer").css("padding-top").replace("px", ""); //get the current page height - the padding of the footer var page_height = $(document.body).height() - padding_top; var window_height = $(window).height(); //calculate the difference between page and window height var difference = window_height - page_height; if (difference < 0) difference = 0; //write the changes to the div $("#footer").css({ padding: difference + "px 0 0 0" }) } //re-run the function if browser window is resized $(window).resize(positionFooter) }); Unfortunately the (document).ready trigger is to early and dose not consider image & font loading, so the value that is calculated is incorrect. Is there a trigger that is suited for this kind of tasks? Also the site I'm building is using Disqus fot comments, which also changes the page length again, though I think I need a call-back from the Disqus script to take that change into consideration. | TITLE:
Running jQuery function after all media is loaded
QUESTION:
I have a simple jQuery script which pushes the footer to the bottom of the page, even if the content is not long enough: $(document).ready(function(){ positionFooter(); function positionFooter(){ //get the div's padding var padding_top = $("#footer").css("padding-top").replace("px", ""); //get the current page height - the padding of the footer var page_height = $(document.body).height() - padding_top; var window_height = $(window).height(); //calculate the difference between page and window height var difference = window_height - page_height; if (difference < 0) difference = 0; //write the changes to the div $("#footer").css({ padding: difference + "px 0 0 0" }) } //re-run the function if browser window is resized $(window).resize(positionFooter) }); Unfortunately the (document).ready trigger is to early and dose not consider image & font loading, so the value that is calculated is incorrect. Is there a trigger that is suited for this kind of tasks? Also the site I'm building is using Disqus fot comments, which also changes the page length again, though I think I need a call-back from the Disqus script to take that change into consideration.
ANSWER:
try $(window).load() You may also want to check the jQuery documentation on the different document loading events: http://api.jquery.com/category/events/document-loading/ Hope it helps | [
"javascript",
"jquery",
"events",
"resize"
] | 2 | 8 | 8,653 | 5 | 0 | 2011-06-10T15:59:42.913000 | 2011-06-10T16:02:53.270000 |
6,308,991 | 6,309,050 | ASP.NET MVC Use Hyphens in parameter when the raw value has hyphens | I'm writing an MVC app where I want the URL's to be SEO friendly and parameter lookup to be by name rather than id. So for example, instead of having something like this: /Products/Category/23 I'll have something like this: /Products/Category/Books And, it seems that the best practice recommendations are to replace spaces with hyphens instead of underscores or %20, so multi-word categories in the example above would be something like this: /Products/Category/Wall-Decorations /Products/Category/some-other-name However, what do we do whenever the parameter's raw value actually contains hyphens? For example, something like /Products/Category/E-Books In this case, the hyphen is actually part of "E-books", not a word separator. So, if I were to: Products.Where(x => x.Name == parameter.Replace("-","")); then, "E-books" in the data store would not match "Ebooks" (hyphen replaced from parameter). The only solution I can come up with is doing something like: Products.Where(x=> x.Name.Replace("-","") == parameter.Replace("-","")); that way, "Ebooks" (hyphen replaced in data store) would match "Ebooks" (hyphen replaced from parameter), but that would effectively make it to where in your data store a value with hyphens is the same as a value with no hyphens. And while in this contrived example, "E-books" and "Ebooks" should never exist together, there are other scenarios where the presence of hyphens are important. For example: company names, url's, saved searches that include dashes for date ranges, etc. (not to mention that if you are allowing users to create these names, then we have to plan for everything). So, I've kind of found a potential workaround for certain specific instances where I can make simplifying assumptions, but does anyone out there have any other suggestions on how to safely handle this for all scenarios? | I am not sure what you mean by "safely handle this for all scenarios". The methodology is sound as long as you always removed spaces in your key (which is a string rather than a numeric - guessing you have a numeric key for your actual derived key (primary key) and a friendly key for the URI?). I would have to know what scenario you see that fits outside of this box. If some keys must have spaces, then you can replace hyphens with spaces in your code. Is that a scenario you are talking about? | ASP.NET MVC Use Hyphens in parameter when the raw value has hyphens I'm writing an MVC app where I want the URL's to be SEO friendly and parameter lookup to be by name rather than id. So for example, instead of having something like this: /Products/Category/23 I'll have something like this: /Products/Category/Books And, it seems that the best practice recommendations are to replace spaces with hyphens instead of underscores or %20, so multi-word categories in the example above would be something like this: /Products/Category/Wall-Decorations /Products/Category/some-other-name However, what do we do whenever the parameter's raw value actually contains hyphens? For example, something like /Products/Category/E-Books In this case, the hyphen is actually part of "E-books", not a word separator. So, if I were to: Products.Where(x => x.Name == parameter.Replace("-","")); then, "E-books" in the data store would not match "Ebooks" (hyphen replaced from parameter). The only solution I can come up with is doing something like: Products.Where(x=> x.Name.Replace("-","") == parameter.Replace("-","")); that way, "Ebooks" (hyphen replaced in data store) would match "Ebooks" (hyphen replaced from parameter), but that would effectively make it to where in your data store a value with hyphens is the same as a value with no hyphens. And while in this contrived example, "E-books" and "Ebooks" should never exist together, there are other scenarios where the presence of hyphens are important. For example: company names, url's, saved searches that include dashes for date ranges, etc. (not to mention that if you are allowing users to create these names, then we have to plan for everything). So, I've kind of found a potential workaround for certain specific instances where I can make simplifying assumptions, but does anyone out there have any other suggestions on how to safely handle this for all scenarios? | TITLE:
ASP.NET MVC Use Hyphens in parameter when the raw value has hyphens
QUESTION:
I'm writing an MVC app where I want the URL's to be SEO friendly and parameter lookup to be by name rather than id. So for example, instead of having something like this: /Products/Category/23 I'll have something like this: /Products/Category/Books And, it seems that the best practice recommendations are to replace spaces with hyphens instead of underscores or %20, so multi-word categories in the example above would be something like this: /Products/Category/Wall-Decorations /Products/Category/some-other-name However, what do we do whenever the parameter's raw value actually contains hyphens? For example, something like /Products/Category/E-Books In this case, the hyphen is actually part of "E-books", not a word separator. So, if I were to: Products.Where(x => x.Name == parameter.Replace("-","")); then, "E-books" in the data store would not match "Ebooks" (hyphen replaced from parameter). The only solution I can come up with is doing something like: Products.Where(x=> x.Name.Replace("-","") == parameter.Replace("-","")); that way, "Ebooks" (hyphen replaced in data store) would match "Ebooks" (hyphen replaced from parameter), but that would effectively make it to where in your data store a value with hyphens is the same as a value with no hyphens. And while in this contrived example, "E-books" and "Ebooks" should never exist together, there are other scenarios where the presence of hyphens are important. For example: company names, url's, saved searches that include dashes for date ranges, etc. (not to mention that if you are allowing users to create these names, then we have to plan for everything). So, I've kind of found a potential workaround for certain specific instances where I can make simplifying assumptions, but does anyone out there have any other suggestions on how to safely handle this for all scenarios?
ANSWER:
I am not sure what you mean by "safely handle this for all scenarios". The methodology is sound as long as you always removed spaces in your key (which is a string rather than a numeric - guessing you have a numeric key for your actual derived key (primary key) and a friendly key for the URI?). I would have to know what scenario you see that fits outside of this box. If some keys must have spaces, then you can replace hyphens with spaces in your code. Is that a scenario you are talking about? | [
"asp.net-mvc-3",
"routes"
] | 0 | 0 | 530 | 1 | 0 | 2011-06-10T16:00:17.900000 | 2011-06-10T16:05:22.877000 |
6,308,993 | 6,309,043 | Static/dynamic libraries vs .so libaries? | I come from a windows w/ visual-studio background for native development and I am now going to compile native code for use on android. I am not sure how the unix-like libraries (.so?) work. Are they static (like a.lib on windows) or dynamically loaded like a DLL? For example, in visual studio, I add the.lib file to my project for compiling, and then load the.dll during runtime. What is the equivalent in unix-stuff, say by using GCC? Thanks! | On Linux, the.so files are the equivalent(*) of the.dll files on Windows, in the sense that they are loaded dynamically to the executable when it is executed. Note however that you don't need a.lib file when linking your application. The linker will find the information directly in the.so file. *: There are differences. | Static/dynamic libraries vs .so libaries? I come from a windows w/ visual-studio background for native development and I am now going to compile native code for use on android. I am not sure how the unix-like libraries (.so?) work. Are they static (like a.lib on windows) or dynamically loaded like a DLL? For example, in visual studio, I add the.lib file to my project for compiling, and then load the.dll during runtime. What is the equivalent in unix-stuff, say by using GCC? Thanks! | TITLE:
Static/dynamic libraries vs .so libaries?
QUESTION:
I come from a windows w/ visual-studio background for native development and I am now going to compile native code for use on android. I am not sure how the unix-like libraries (.so?) work. Are they static (like a.lib on windows) or dynamically loaded like a DLL? For example, in visual studio, I add the.lib file to my project for compiling, and then load the.dll during runtime. What is the equivalent in unix-stuff, say by using GCC? Thanks!
ANSWER:
On Linux, the.so files are the equivalent(*) of the.dll files on Windows, in the sense that they are loaded dynamically to the executable when it is executed. Note however that you don't need a.lib file when linking your application. The linker will find the information directly in the.so file. *: There are differences. | [
"c",
"visual-studio",
"gcc",
"dll"
] | 3 | 5 | 2,113 | 3 | 0 | 2011-06-10T16:00:33.453000 | 2011-06-10T16:04:39.753000 |
6,308,994 | 6,309,222 | How to change images of other objects? | I am using a program called Greenfoot to do my java projects. there is two "actors" in Greenfoot that move around randomly. I would like to make it so that when one actor touches the other, it has a percent of changing the other actor to the same image. How do I accomplish this? | Are you looking for an Object Collision. If yes then please read this: http://www.greenfoot.org/doc/manual.html#collisions | How to change images of other objects? I am using a program called Greenfoot to do my java projects. there is two "actors" in Greenfoot that move around randomly. I would like to make it so that when one actor touches the other, it has a percent of changing the other actor to the same image. How do I accomplish this? | TITLE:
How to change images of other objects?
QUESTION:
I am using a program called Greenfoot to do my java projects. there is two "actors" in Greenfoot that move around randomly. I would like to make it so that when one actor touches the other, it has a percent of changing the other actor to the same image. How do I accomplish this?
ANSWER:
Are you looking for an Object Collision. If yes then please read this: http://www.greenfoot.org/doc/manual.html#collisions | [
"java",
"greenfoot"
] | 0 | 1 | 1,444 | 2 | 0 | 2011-06-10T16:00:33.843000 | 2011-06-10T16:19:06.827000 |
6,308,996 | 6,309,106 | problem with match namespace in xslt | It's a problem with match elements which have specific node. The xml: description of profile PhoneKeyPad SampleModel 3 1x1 128x240 and the XSLT is: The result is: description of profile PhoneKeyPad SampleModel 3 1x1 128x240 Why the "description of profile" is also output? It has "base" namespace. Thanks in advance. | The simple answer is: Because you never tell the XSLT processor to ignore it. You provide a template that processes prf:*, but you do not forbid the processing of base:. Given nothing else, the XSLT processor applies default behavior ( built-in rules, also here ) to any nodes it encounters that are not handled by any custom template. The default behavior for element nodes is: copy their text-node children to the output, process their child elements Knowing that, your and elements produce exactly what you see. To prevent it, either catch them with an empty template: or direct the program flow manually by defining a template for the root node: | problem with match namespace in xslt It's a problem with match elements which have specific node. The xml: description of profile PhoneKeyPad SampleModel 3 1x1 128x240 and the XSLT is: The result is: description of profile PhoneKeyPad SampleModel 3 1x1 128x240 Why the "description of profile" is also output? It has "base" namespace. Thanks in advance. | TITLE:
problem with match namespace in xslt
QUESTION:
It's a problem with match elements which have specific node. The xml: description of profile PhoneKeyPad SampleModel 3 1x1 128x240 and the XSLT is: The result is: description of profile PhoneKeyPad SampleModel 3 1x1 128x240 Why the "description of profile" is also output? It has "base" namespace. Thanks in advance.
ANSWER:
The simple answer is: Because you never tell the XSLT processor to ignore it. You provide a template that processes prf:*, but you do not forbid the processing of base:. Given nothing else, the XSLT processor applies default behavior ( built-in rules, also here ) to any nodes it encounters that are not handled by any custom template. The default behavior for element nodes is: copy their text-node children to the output, process their child elements Knowing that, your and elements produce exactly what you see. To prevent it, either catch them with an empty template: or direct the program flow manually by defining a template for the root node: | [
"xslt",
"namespaces"
] | 0 | 4 | 2,047 | 1 | 0 | 2011-06-10T16:00:38.123000 | 2011-06-10T16:09:34.800000 |
6,309,005 | 6,309,137 | How to apply CSS to elements that have multiple classes? | Is there a way to apply a style to elements that contain multiple classes? Example foo foo bar bar I only want to modify the styling of the element that contains class "foo bar". The XPath information would be something like //div[contains(@class,"foo") and contains(@class,"bar")]. Any ideas for pure CSS, w/o having to create a unique class? | Solutions.foo.bar {... } [class="foo bar"] {... } // explicit class name [class~="foo"][class~="bar"] {... } // inclusive class name | How to apply CSS to elements that have multiple classes? Is there a way to apply a style to elements that contain multiple classes? Example foo foo bar bar I only want to modify the styling of the element that contains class "foo bar". The XPath information would be something like //div[contains(@class,"foo") and contains(@class,"bar")]. Any ideas for pure CSS, w/o having to create a unique class? | TITLE:
How to apply CSS to elements that have multiple classes?
QUESTION:
Is there a way to apply a style to elements that contain multiple classes? Example foo foo bar bar I only want to modify the styling of the element that contains class "foo bar". The XPath information would be something like //div[contains(@class,"foo") and contains(@class,"bar")]. Any ideas for pure CSS, w/o having to create a unique class?
ANSWER:
Solutions.foo.bar {... } [class="foo bar"] {... } // explicit class name [class~="foo"][class~="bar"] {... } // inclusive class name | [
"css",
"css-selectors"
] | 0 | 1 | 1,226 | 2 | 0 | 2011-06-10T16:01:15.753000 | 2011-06-10T16:11:56.137000 |
6,309,023 | 6,309,120 | mysql select for checking if a entry exist | i had a large databse and had to chec if a email is in a special group I had to tables. first tabel called user CREATE TABLE user ( uid int(10) NOT NULL AUTO_INCREMENT, kid int(3) NOT NULL, Email varchar(255) DEFAULT NULL, PRIMARY KEY (uid), KEY kid (kid) ) ENGINE=MyISAM and a table named group CREATE TABLE `group` ( `vuid` int(10) NOT NULL AUTO_INCREMENT, `uid` int(3) NOT NULL, `vid` int(3) NOT NULL, PRIMARY KEY (`vuid`) ) ENGINE=MyISAM and for every insert i had a defined vid and a email Now i had to check, if a user with the uid is in the group vid. select a.email,b.vuid from user a, group b where a.email=\''.$email.'\' and a.kid='. $kid.' and b.vid='. $vid. ' and a.uid = b.uid limit 1') and check if the mysql_fetch_assoc is true or false. BUT this is verry verry slow. is there a simple way to speed up? | Rather than using a comma separated list of tables, try using a JOIN (in this case, INNER JOIN is your best bet since you want to check if records exist in both tables) with an ON clause. I have formatted your query and my changes are in capitals to make them stand out. select a.email, b.vuid from user a INNER JOIN group b ON a.uid = b.uid where a.email=\''.$email.'\' and a.kid='. $kid.' and b.vid='. $vid. ' limit 1 Next, check your indexes - make sure you have indexes on b.uid and a.kid. As a general rule, check your where clauses for values you can index; anything with unique values is a candidate. | mysql select for checking if a entry exist i had a large databse and had to chec if a email is in a special group I had to tables. first tabel called user CREATE TABLE user ( uid int(10) NOT NULL AUTO_INCREMENT, kid int(3) NOT NULL, Email varchar(255) DEFAULT NULL, PRIMARY KEY (uid), KEY kid (kid) ) ENGINE=MyISAM and a table named group CREATE TABLE `group` ( `vuid` int(10) NOT NULL AUTO_INCREMENT, `uid` int(3) NOT NULL, `vid` int(3) NOT NULL, PRIMARY KEY (`vuid`) ) ENGINE=MyISAM and for every insert i had a defined vid and a email Now i had to check, if a user with the uid is in the group vid. select a.email,b.vuid from user a, group b where a.email=\''.$email.'\' and a.kid='. $kid.' and b.vid='. $vid. ' and a.uid = b.uid limit 1') and check if the mysql_fetch_assoc is true or false. BUT this is verry verry slow. is there a simple way to speed up? | TITLE:
mysql select for checking if a entry exist
QUESTION:
i had a large databse and had to chec if a email is in a special group I had to tables. first tabel called user CREATE TABLE user ( uid int(10) NOT NULL AUTO_INCREMENT, kid int(3) NOT NULL, Email varchar(255) DEFAULT NULL, PRIMARY KEY (uid), KEY kid (kid) ) ENGINE=MyISAM and a table named group CREATE TABLE `group` ( `vuid` int(10) NOT NULL AUTO_INCREMENT, `uid` int(3) NOT NULL, `vid` int(3) NOT NULL, PRIMARY KEY (`vuid`) ) ENGINE=MyISAM and for every insert i had a defined vid and a email Now i had to check, if a user with the uid is in the group vid. select a.email,b.vuid from user a, group b where a.email=\''.$email.'\' and a.kid='. $kid.' and b.vid='. $vid. ' and a.uid = b.uid limit 1') and check if the mysql_fetch_assoc is true or false. BUT this is verry verry slow. is there a simple way to speed up?
ANSWER:
Rather than using a comma separated list of tables, try using a JOIN (in this case, INNER JOIN is your best bet since you want to check if records exist in both tables) with an ON clause. I have formatted your query and my changes are in capitals to make them stand out. select a.email, b.vuid from user a INNER JOIN group b ON a.uid = b.uid where a.email=\''.$email.'\' and a.kid='. $kid.' and b.vid='. $vid. ' limit 1 Next, check your indexes - make sure you have indexes on b.uid and a.kid. As a general rule, check your where clauses for values you can index; anything with unique values is a candidate. | [
"php",
"mysql"
] | 1 | 2 | 198 | 3 | 0 | 2011-06-10T16:02:44.780000 | 2011-06-10T16:10:43.533000 |
6,309,029 | 6,309,168 | Nested file input doesn't work in Firefox | I have the following HTML: Styled like such: #inner { cursor: pointer; position:absolute; opacity: 0; } #outer { position: relative; overflow: hidden; direction: ltr; } It looks like just a standard file input element, as the #inner input element is hidden and wrapped by the #outer one. My desired behavior is to see "Yes!" when I select a file, which I get with Webkit browsers (both inputs activate) but not Firefox. Do you have any ideas about how I can get this in Firefox as well? | The reason for the difference in behaviour is most likely that the code is invalid. See HTML 4: 17.4 The INPUT element: "Start tag: required, End tag: forbidden " So, you can't nest an input tag inside another. Different browsers handle invalid markup differently, so they can for example ignore that one is inside the other and place them beside each other, or ignore the inner tag completely. If you are curious, you can use FireBug to examine the DOM to find out what elements are created from the markup, but it's really moot as invalid markup won't work reliably anyway. | Nested file input doesn't work in Firefox I have the following HTML: Styled like such: #inner { cursor: pointer; position:absolute; opacity: 0; } #outer { position: relative; overflow: hidden; direction: ltr; } It looks like just a standard file input element, as the #inner input element is hidden and wrapped by the #outer one. My desired behavior is to see "Yes!" when I select a file, which I get with Webkit browsers (both inputs activate) but not Firefox. Do you have any ideas about how I can get this in Firefox as well? | TITLE:
Nested file input doesn't work in Firefox
QUESTION:
I have the following HTML: Styled like such: #inner { cursor: pointer; position:absolute; opacity: 0; } #outer { position: relative; overflow: hidden; direction: ltr; } It looks like just a standard file input element, as the #inner input element is hidden and wrapped by the #outer one. My desired behavior is to see "Yes!" when I select a file, which I get with Webkit browsers (both inputs activate) but not Firefox. Do you have any ideas about how I can get this in Firefox as well?
ANSWER:
The reason for the difference in behaviour is most likely that the code is invalid. See HTML 4: 17.4 The INPUT element: "Start tag: required, End tag: forbidden " So, you can't nest an input tag inside another. Different browsers handle invalid markup differently, so they can for example ignore that one is inside the other and place them beside each other, or ignore the inner tag completely. If you are curious, you can use FireBug to examine the DOM to find out what elements are created from the markup, but it's really moot as invalid markup won't work reliably anyway. | [
"html",
"css",
"cross-browser",
"nested",
"file-io"
] | 0 | 1 | 568 | 1 | 0 | 2011-06-10T16:03:19.590000 | 2011-06-10T16:14:35.560000 |
6,309,032 | 6,309,100 | Wanting to sort a hash in ruby by value first, and key second | Possible Duplicate: Sorting a hash in Ruby by its value first then its key. I need to order a hash so that the value is the first priority, and then when the values are the same it orders by the key. I am currently sorting using this code, but I don't see how to do sort_by with a second element. Hash[@card_value_counts.sort_by{|k, v| k * -1}] Examples of what I'm looking for would be: pre_sorted = {10=>1, 9=>2, 3=>2, 2=>1, 1=>1} sorted = {9=>2, 3=>2, 10=>1, 2=>1, 1=>1}
pre_sorted = {12=>2, 10=>3, 9=>4, 5=>3} sorted = {9=>4, 10=>3, 5=>3, 12=>2} | Array has a cool feature: comparing two arrays with the <=> method will compare them element-by-element. You can exploit this for multi-value sorting: sorted_hash = Hash[original_hash.sort_by { |k,v| [-1 * v, -1 * k] }] UPDATE: Maybe you know this already, but I assumed you're using Ruby 1.9. In earlier versions, Hashes are not guaranteed to maintain their order. | Wanting to sort a hash in ruby by value first, and key second Possible Duplicate: Sorting a hash in Ruby by its value first then its key. I need to order a hash so that the value is the first priority, and then when the values are the same it orders by the key. I am currently sorting using this code, but I don't see how to do sort_by with a second element. Hash[@card_value_counts.sort_by{|k, v| k * -1}] Examples of what I'm looking for would be: pre_sorted = {10=>1, 9=>2, 3=>2, 2=>1, 1=>1} sorted = {9=>2, 3=>2, 10=>1, 2=>1, 1=>1}
pre_sorted = {12=>2, 10=>3, 9=>4, 5=>3} sorted = {9=>4, 10=>3, 5=>3, 12=>2} | TITLE:
Wanting to sort a hash in ruby by value first, and key second
QUESTION:
Possible Duplicate: Sorting a hash in Ruby by its value first then its key. I need to order a hash so that the value is the first priority, and then when the values are the same it orders by the key. I am currently sorting using this code, but I don't see how to do sort_by with a second element. Hash[@card_value_counts.sort_by{|k, v| k * -1}] Examples of what I'm looking for would be: pre_sorted = {10=>1, 9=>2, 3=>2, 2=>1, 1=>1} sorted = {9=>2, 3=>2, 10=>1, 2=>1, 1=>1}
pre_sorted = {12=>2, 10=>3, 9=>4, 5=>3} sorted = {9=>4, 10=>3, 5=>3, 12=>2}
ANSWER:
Array has a cool feature: comparing two arrays with the <=> method will compare them element-by-element. You can exploit this for multi-value sorting: sorted_hash = Hash[original_hash.sort_by { |k,v| [-1 * v, -1 * k] }] UPDATE: Maybe you know this already, but I assumed you're using Ruby 1.9. In earlier versions, Hashes are not guaranteed to maintain their order. | [
"ruby-on-rails",
"ruby"
] | 0 | 6 | 2,247 | 1 | 0 | 2011-06-10T16:03:41.220000 | 2011-06-10T16:09:02.347000 |
6,309,045 | 6,309,124 | Windows Command Line : START Command Switch /I meaning? | From ss64.com: /I: Ignore any changes to the current environment. What does that mean? If you could give examples of usage and what it effects or doesn't effect, that would be great (none provided on website and have google searched with no luck). | If you modified the current environment by defining a variable; set foo=bar start app.exe App.exe would see %foo% as being "bar" set foo=bar start /i app.exe App.exe would see %foo% as being undefined. | Windows Command Line : START Command Switch /I meaning? From ss64.com: /I: Ignore any changes to the current environment. What does that mean? If you could give examples of usage and what it effects or doesn't effect, that would be great (none provided on website and have google searched with no luck). | TITLE:
Windows Command Line : START Command Switch /I meaning?
QUESTION:
From ss64.com: /I: Ignore any changes to the current environment. What does that mean? If you could give examples of usage and what it effects or doesn't effect, that would be great (none provided on website and have google searched with no luck).
ANSWER:
If you modified the current environment by defining a variable; set foo=bar start app.exe App.exe would see %foo% as being "bar" set foo=bar start /i app.exe App.exe would see %foo% as being undefined. | [
"windows",
"command-line",
"switch-statement"
] | 2 | 4 | 3,752 | 3 | 0 | 2011-06-10T16:04:49.163000 | 2011-06-10T16:10:59.613000 |
6,309,046 | 6,309,190 | SVN to Git to Gitolite and Lots of Files | Ok, so I've read just about every resource possible on converting from SVN to Git. I am attempting to abandon our SVN server completely and move forward with Gitolite, which is already setup and ready to go. I used svn2git (the ruby script), but ran into some issues that have been documented here on SO. I'm moving about 9gb everytime I run the script, so it's creating some difficulty when troubleshooting. I was finally able to import everything in using git svn from the SVN to my local machine, and that's where I'm stuck. I need to set one of the branches as the master, and then push that to a new gitolite repo - but I'm completely lost on the process. I'd also like to ignore a bunch of the media files that don't need to be tracked in the repo, and I'm lost on that too because (if I understand correctly) I can't use.gitignore on files that have already been tracked. Any tips, resources, or different methods would be totally appreciated. Edit: It should be noted that the SVN was being used by a single developer, so blowing out the SVN completely and starting from scratch (with the commit data saved, of course) is not out of the question. | A lot of times it's not worth it to import the history. Just manually import the important branches and tags. Refer to the old svn when needed. Been through this twice and would not recommend it to anyone. | SVN to Git to Gitolite and Lots of Files Ok, so I've read just about every resource possible on converting from SVN to Git. I am attempting to abandon our SVN server completely and move forward with Gitolite, which is already setup and ready to go. I used svn2git (the ruby script), but ran into some issues that have been documented here on SO. I'm moving about 9gb everytime I run the script, so it's creating some difficulty when troubleshooting. I was finally able to import everything in using git svn from the SVN to my local machine, and that's where I'm stuck. I need to set one of the branches as the master, and then push that to a new gitolite repo - but I'm completely lost on the process. I'd also like to ignore a bunch of the media files that don't need to be tracked in the repo, and I'm lost on that too because (if I understand correctly) I can't use.gitignore on files that have already been tracked. Any tips, resources, or different methods would be totally appreciated. Edit: It should be noted that the SVN was being used by a single developer, so blowing out the SVN completely and starting from scratch (with the commit data saved, of course) is not out of the question. | TITLE:
SVN to Git to Gitolite and Lots of Files
QUESTION:
Ok, so I've read just about every resource possible on converting from SVN to Git. I am attempting to abandon our SVN server completely and move forward with Gitolite, which is already setup and ready to go. I used svn2git (the ruby script), but ran into some issues that have been documented here on SO. I'm moving about 9gb everytime I run the script, so it's creating some difficulty when troubleshooting. I was finally able to import everything in using git svn from the SVN to my local machine, and that's where I'm stuck. I need to set one of the branches as the master, and then push that to a new gitolite repo - but I'm completely lost on the process. I'd also like to ignore a bunch of the media files that don't need to be tracked in the repo, and I'm lost on that too because (if I understand correctly) I can't use.gitignore on files that have already been tracked. Any tips, resources, or different methods would be totally appreciated. Edit: It should be noted that the SVN was being used by a single developer, so blowing out the SVN completely and starting from scratch (with the commit data saved, of course) is not out of the question.
ANSWER:
A lot of times it's not worth it to import the history. Just manually import the important branches and tags. Refer to the old svn when needed. Been through this twice and would not recommend it to anyone. | [
"svn",
"git",
"gitolite"
] | 1 | 1 | 1,008 | 2 | 0 | 2011-06-10T16:05:05.097000 | 2011-06-10T16:16:16.647000 |
6,309,070 | 6,309,173 | Can I use a SELECT subquery inside an INSERT query? | I've tried following the syntax suggested here, but it doesn't work for my query. Here's what I currently have: INSERT INTO dot (entrant_id, year, entry_code, title, retail_category, campaign_type, client_company, client_city, client_state, field_date_active, height, width, depth, weight, oversize_fee, volt_110, attach_to_gridwall, hang_from_ceiling, table_or_countertop, misc_setup, created_date, modified_date, co_entrant) VALUES (288, 2011, 1234, 'RG Total Defense BW mixed Floorstand', '32', 'C', 'Henkel', 'Scottsdale', 'AZ', '2011-01-15', 60, 26, 15, 29, 0, '0', '0', '0', '0', '', NOW(), NOW(), '') However, I need the value of entry_code to be selected from the same table - I can do it as an individual query: MAX(entry_code) FROM dot WHERE year = 2011 but can't seem to integrate that with the insert statement. Is this possible? Or will a subquery like that only work if it's selecting from a different table? | INSERT INTO dot (entrant_id, year, entry_code,...) SELECT 288, 2011, MAX(entry_code),... FROM dot WHERE year=2011 | Can I use a SELECT subquery inside an INSERT query? I've tried following the syntax suggested here, but it doesn't work for my query. Here's what I currently have: INSERT INTO dot (entrant_id, year, entry_code, title, retail_category, campaign_type, client_company, client_city, client_state, field_date_active, height, width, depth, weight, oversize_fee, volt_110, attach_to_gridwall, hang_from_ceiling, table_or_countertop, misc_setup, created_date, modified_date, co_entrant) VALUES (288, 2011, 1234, 'RG Total Defense BW mixed Floorstand', '32', 'C', 'Henkel', 'Scottsdale', 'AZ', '2011-01-15', 60, 26, 15, 29, 0, '0', '0', '0', '0', '', NOW(), NOW(), '') However, I need the value of entry_code to be selected from the same table - I can do it as an individual query: MAX(entry_code) FROM dot WHERE year = 2011 but can't seem to integrate that with the insert statement. Is this possible? Or will a subquery like that only work if it's selecting from a different table? | TITLE:
Can I use a SELECT subquery inside an INSERT query?
QUESTION:
I've tried following the syntax suggested here, but it doesn't work for my query. Here's what I currently have: INSERT INTO dot (entrant_id, year, entry_code, title, retail_category, campaign_type, client_company, client_city, client_state, field_date_active, height, width, depth, weight, oversize_fee, volt_110, attach_to_gridwall, hang_from_ceiling, table_or_countertop, misc_setup, created_date, modified_date, co_entrant) VALUES (288, 2011, 1234, 'RG Total Defense BW mixed Floorstand', '32', 'C', 'Henkel', 'Scottsdale', 'AZ', '2011-01-15', 60, 26, 15, 29, 0, '0', '0', '0', '0', '', NOW(), NOW(), '') However, I need the value of entry_code to be selected from the same table - I can do it as an individual query: MAX(entry_code) FROM dot WHERE year = 2011 but can't seem to integrate that with the insert statement. Is this possible? Or will a subquery like that only work if it's selecting from a different table?
ANSWER:
INSERT INTO dot (entrant_id, year, entry_code,...) SELECT 288, 2011, MAX(entry_code),... FROM dot WHERE year=2011 | [
"mysql",
"subquery"
] | 1 | 2 | 487 | 3 | 0 | 2011-06-10T16:06:59.730000 | 2011-06-10T16:14:54.577000 |
6,309,072 | 6,309,193 | Dealing with IMAP mailbox name case sensitivty | I have a python script using imaplib that connects to a gmail account and sorts emails based on '+' tags found in the email address. For example: emails sent to myaccount+root.foo.bar@gmail.com get moved to root\foo\bar. My logic goes as follows: extract tags -> attempt to create folders -> copy message to folder. Ocassionally an email will come in with the same tags, but different casing. myaccount+root.FOO.BAR@gmail.com, for example, and leads to this output: #Attempting to creating folder 'root/FOO/BAR' ('NO', ['[ALREADYEXISTS] Folder name conflicts with existing folder name. (Failure)']) #Copying message to folder 'root/FOO/BAR' ('NO', ['[TRYCREATE] No folder root/FOO/BAR (Failure)']) So it fails to create the folder, because a folder with the same name already exists (just with different case), but the copy fails because the explicit folder doesn't exist. Is there some clever way that I can figure out the correct case of the existing folder so I can move the message without issue? Note: This isn't as easy as just forcing all tags to lowercase. A User connects to the account with an email client and ocassioanlly manually makes folders with whatever casing makes sense to them at the time. | So Google complains that the folder already exists, but then gives an error when you try to move something into it? Terrific. IMAP has a "LIST" command to list available mailboxes (folders): https://www.rfc-editor.org/rfc/rfc3501#section-6.3.8 How to access that depends on your IMAP client library. Here are a couple of examples. | Dealing with IMAP mailbox name case sensitivty I have a python script using imaplib that connects to a gmail account and sorts emails based on '+' tags found in the email address. For example: emails sent to myaccount+root.foo.bar@gmail.com get moved to root\foo\bar. My logic goes as follows: extract tags -> attempt to create folders -> copy message to folder. Ocassionally an email will come in with the same tags, but different casing. myaccount+root.FOO.BAR@gmail.com, for example, and leads to this output: #Attempting to creating folder 'root/FOO/BAR' ('NO', ['[ALREADYEXISTS] Folder name conflicts with existing folder name. (Failure)']) #Copying message to folder 'root/FOO/BAR' ('NO', ['[TRYCREATE] No folder root/FOO/BAR (Failure)']) So it fails to create the folder, because a folder with the same name already exists (just with different case), but the copy fails because the explicit folder doesn't exist. Is there some clever way that I can figure out the correct case of the existing folder so I can move the message without issue? Note: This isn't as easy as just forcing all tags to lowercase. A User connects to the account with an email client and ocassioanlly manually makes folders with whatever casing makes sense to them at the time. | TITLE:
Dealing with IMAP mailbox name case sensitivty
QUESTION:
I have a python script using imaplib that connects to a gmail account and sorts emails based on '+' tags found in the email address. For example: emails sent to myaccount+root.foo.bar@gmail.com get moved to root\foo\bar. My logic goes as follows: extract tags -> attempt to create folders -> copy message to folder. Ocassionally an email will come in with the same tags, but different casing. myaccount+root.FOO.BAR@gmail.com, for example, and leads to this output: #Attempting to creating folder 'root/FOO/BAR' ('NO', ['[ALREADYEXISTS] Folder name conflicts with existing folder name. (Failure)']) #Copying message to folder 'root/FOO/BAR' ('NO', ['[TRYCREATE] No folder root/FOO/BAR (Failure)']) So it fails to create the folder, because a folder with the same name already exists (just with different case), but the copy fails because the explicit folder doesn't exist. Is there some clever way that I can figure out the correct case of the existing folder so I can move the message without issue? Note: This isn't as easy as just forcing all tags to lowercase. A User connects to the account with an email client and ocassioanlly manually makes folders with whatever casing makes sense to them at the time.
ANSWER:
So Google complains that the folder already exists, but then gives an error when you try to move something into it? Terrific. IMAP has a "LIST" command to list available mailboxes (folders): https://www.rfc-editor.org/rfc/rfc3501#section-6.3.8 How to access that depends on your IMAP client library. Here are a couple of examples. | [
"python",
"imap",
"imaplib",
"gmail-imap"
] | 2 | 2 | 752 | 1 | 0 | 2011-06-10T16:07:11.600000 | 2011-06-10T16:16:27.590000 |
6,309,074 | 6,309,156 | PHP Sessions not working in Internet Explorer, cookies are working great though | Im having trouble with sessions in IE. I have tested in IE 7-8, but it does not work in any of them. I can see that i am logged in, and then redirected, but the session is dropped somehow. It works great in Firefox, Chrome and Safari. If i use the "remember me" function i made, then it also works in IE?! So it cant be a problem with cookies? I researched the problem a lot and found some forums where people suggested the following changes to config: $config['sess_cookie_name'] = 'cisession'; $config['sess_expiration'] = 72000; This does not work either. In the same forum, a guy says he found the solution in the local time: I’ve found the solution to my problem. Apparently, IE7 drops sessions that are set when your machine’s date and time is not correctly configured. Follow this link, No Cookies in IE??. I hope it made your day as it made mine. The problem is that the link he refers to does not work. Does anybody here have a clue on whats the problem? Thanks! | Are you using a php header redirect immediatly after setting the session? That has been an issue for me sometimes. Can be solved by doing a redirect with javascript on page load. | PHP Sessions not working in Internet Explorer, cookies are working great though Im having trouble with sessions in IE. I have tested in IE 7-8, but it does not work in any of them. I can see that i am logged in, and then redirected, but the session is dropped somehow. It works great in Firefox, Chrome and Safari. If i use the "remember me" function i made, then it also works in IE?! So it cant be a problem with cookies? I researched the problem a lot and found some forums where people suggested the following changes to config: $config['sess_cookie_name'] = 'cisession'; $config['sess_expiration'] = 72000; This does not work either. In the same forum, a guy says he found the solution in the local time: I’ve found the solution to my problem. Apparently, IE7 drops sessions that are set when your machine’s date and time is not correctly configured. Follow this link, No Cookies in IE??. I hope it made your day as it made mine. The problem is that the link he refers to does not work. Does anybody here have a clue on whats the problem? Thanks! | TITLE:
PHP Sessions not working in Internet Explorer, cookies are working great though
QUESTION:
Im having trouble with sessions in IE. I have tested in IE 7-8, but it does not work in any of them. I can see that i am logged in, and then redirected, but the session is dropped somehow. It works great in Firefox, Chrome and Safari. If i use the "remember me" function i made, then it also works in IE?! So it cant be a problem with cookies? I researched the problem a lot and found some forums where people suggested the following changes to config: $config['sess_cookie_name'] = 'cisession'; $config['sess_expiration'] = 72000; This does not work either. In the same forum, a guy says he found the solution in the local time: I’ve found the solution to my problem. Apparently, IE7 drops sessions that are set when your machine’s date and time is not correctly configured. Follow this link, No Cookies in IE??. I hope it made your day as it made mine. The problem is that the link he refers to does not work. Does anybody here have a clue on whats the problem? Thanks!
ANSWER:
Are you using a php header redirect immediatly after setting the session? That has been an issue for me sometimes. Can be solved by doing a redirect with javascript on page load. | [
"php",
"internet-explorer",
"session",
"session-cookies"
] | 0 | 0 | 1,339 | 1 | 0 | 2011-06-10T16:07:16.110000 | 2011-06-10T16:13:49.807000 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.