text
stringlengths
8
267k
meta
dict
Q: Shouldn't this hashtable be read only? I have a class that has a getter function for a hashtable called _Parameters. private Hashtable _Parameters = new Hashtable(); public Hashtable Parameters { get { return _Parameters; } } _Parameters is not referenced anywhere else in code. Now, since there is no setter function I would think that nothing outside of this class could modify what _Parameters has stored, only read it. However that is not the case. Another class calls this code (where template is an instance of the class mentioned above) template.Parameters[key] = parameters[key]; This ends up modifying _Parameters. How is this possible? Do setter functions only apply if we are assigning vales with an '='? A: No. You're returning a reference, which can be modified. But you can't override the reference itself. Consider using a ReadOnlyDictionary<TKey, TValue> instead. Consider reading up on Immutable Objects as well. It should explain the subject to you. A: There is a difference between changing the HashTable object or changing the content of the HashTable. The lack of setter makes sure nobody can: * *set the HashTable to NULL *change the reference of the HashTable to another HashTable. The contents of the HashTable however can be changed. A: You can access the methods of the Hashtable, you just can't set it to a new value (such as NULL or a new Hashtable instance). For example, if I have a List of strings and a Property with a getter but no setter, I can add to the list, remove from the list, call the Clear() method to empty out the list... but I can't do a myList = null (or myList = new List()) because there's no setter. I'm getting the reference to the object, which allows me to manipulate it, but without a setter I cannot set the reference to a new object. A: When you return _Parameters, you're not returning a brand new Hashtable. You're returning another reference to the same one. This one, being a reference to the same object, has the full interface of Hashtable usable on it, including things which modify it. What the lack of a setter does is prevent you from replacing the previous _Parameters with a brand new Hashtable A: Having a read only property to a class object (as opposed to a struct) only prevents modifying the value of the property, in this case the object reference. However, when you access the property you get a reference to your internal HashTable object, and you are free to call any public method on the HashTable object returned, including adding and removing entries in the HashTable. What that read only property does is prevent a caller from replacing your HashTable object with a completley different HashTable object.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600918", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PhoneGap CRUD examples Im new to iPhone development and I find PhoneGap suitable for me for i am a web developer. I'm into practicing database using SQL. because of HTML5 support built into safari browser they support database natively into the browser. I wonder if theres a good example that is easy to follow of using CRUD into SQL database in iPhone. A: After reading your question, I think some points need to be explain: phonegap Official documentation & description can be found on : OfficialWebSite Phonegap is an open source framework / tool to develop cross mobile application. It allows to create mobile applications using only web technologies like html, css, javascript (ajax philosophy mostly used) and get access to APIs & app store. It provides a wrapper for javascript to access to core mobile technologies like sensor or gps... You write your web application with phonegap functionnality, and after compilation for each plateform you obtain an native application (webview inside the application runs the application...) To write the application, you can take advantage of HTML 5, javasvript The obtained app can be deployed on the application store. actual supported plateform iPhone, Android, Blackberry, webOS, Symbian and Bada html5 & storage One of the functionnality introduced by html 5 is the local storage which permits to manage local storage in your browser with a key-value approach. it could be considered as a super cookie (too much resteictive) and permits to speed up treatment or have an off line access to the application. Refence good introduction for example: * *you can write a rss reader which download the news locally and store them tx to local storage. next lanch you just have to do the rotation with old news and if phone is out of network it works always but no update... CRUD the html 5 storage could be manipulated with javascript manipulation sample
{ "language": "en", "url": "https://stackoverflow.com/questions/7600920", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android when to close database dilemma I have a main activity which user a viewpager and a database adapter to serve up the views. Initially all the rows from the Db are pulled into the cursor (Async) Once this cursor is returned the user can add various search criteria from different activities which then runs all the data through an Async scoring algorithm. I was getting some Database errors about having not closed the database so I have closed the cursor and the database in onPause and re-instantiated them in onResume. This would work fine but the activities which build up the search criteria for scoring are started for result. When they return to the main thread onActivityResult is called before on resume so I can't run the scoring algorithm from here as the cursor doesn't exist yet (it has to be recreated in onResume). now, If I want to be able to switch activities while the asyncTask is running I can't close the cursor and Db in onPause. Does anyone have any ideas? Is my "design" just fundamentally flawed? thanks, m A: You should be passing the cursor to the activity to manage, so that when the activity is removed the cursor is automatically closed. Hmm, although when I looked up the reference it suggested a new cusorLoader and using the compatibility libraries. This link should get you started though Developer Docs - Activity.startManagingCursor() A: A Cursor result assigned to say myCursor in onPostExecute() from Async requires managing.  You can override onDestroy() if you want a simple management solution. @Override protected void onPostExecute(Cursor result) { myCursor = result; } ... @Override protected void onDestroy() { if (myCursor != null) myCursor.close(); myCursor = null; /* GC */ super.onDestroy(); } Works for me :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7600926", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to get selected value from mono Gtk.ComboBox? How do I get the selected value (either the string, or an int reference) from a Gtk.ComboBox in mono? All I can find is stuff about using iterators. Why isn't there a function to simply fetch the value (or is there)? A: For (int) index you can use: comboBox.Active; and for text: comboBox.ActiveText; A: to get the selected value in a GTK+ combo box I used: TreeIter tree; comboBox.GetActiveIter(out tree); TreeModel = comboBox.Model (); String selectedText = (String) comboBox.Model.GetValue (tree, 0); "comboBox" is the GTK combo box. I hope this will help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600933", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Handling program args with Groovy Eclipse plugin v2 I am wondering how to handle program arguments when you are running Groovy within Eclipse. It isn't as straight forward as it is from the command line and I am having trouble figure it out. Im using Eclipse 3.5. My run configuration has these arguments all on one line: --classpath "${workspace_loc:/GroovyProject};${workspace_loc:/GroovyProject}" --main groovy.ui.GroovyMain "C:\Temp\Workspace\GroovyProject\GroovyTest.groovy " argtest1 argtest2 argtest3 The script I am using to try to make this work looks like this: // GroovyTest.groovy class GroovyTest { static main(args) { println "hello, world" for (arg in this.args ) { println "Argument:" + arg; } } } The error I get is: hello, world Caught: groovy.lang.MissingPropertyException: No such property: args for class: GroovyTest at GroovyTest.main(GroovyTest.groovy:5) A: You have az unnecessary this in the for (arg in this.args) line. this.args means that you have an instance of the GroovyTest object and you refer to its args field. In this case args is a method parameter so you have to refer to it simply as args.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600943", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to iterate XML data using XSL without hardcoding element names? We're transforming this xml data into pipe-delimited format using XSL... <?xml version="1.0" encoding="ISO-8859-1" ?> <LIBRARY> <BOOK> <TITLE>Professional JINI</TITLE> <AUTHOR>Sing Li</AUTHOR> <PUBLISHER>Wrox Publications</PUBLISHER> </BOOK> </LIBRARY> . <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text" indent="no"/> <!-- New line character variable --> <xsl:variable name="newline"> <xsl:text>&#10;</xsl:text> </xsl:variable> <xsl:template match="/"> <xsl:for-each select="LIBRARY/BOOK"> <xsl:value-of select="TITLE"/>|<xsl:value-of select="AUTHOR"/>|<xsl:value-of select="PUBLISHER"/> <xsl:value-of select="$newline"/> </xsl:for-each> </xsl:template> </xsl:stylesheet> This is the output... Professional JINI|Sing Li|Wrox Publications Is there a way to get the values of TITLE, AUTHOR, etc..from without hard coding the element names in xsl:value-of? We want this XSL to be generic so that if we add more book attributes later the style sheet will automatically capture those new fields. A: Here is an XSLT 1.0 complete solution that is probably among the simplest (no xsl:for-each, push style) shortest possible: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text"/> <xsl:strip-space elements="*"/> <xsl:template match="BOOK"> <xsl:if test="not(position()=1)"> <xsl:text>&#xA;</xsl:text> </xsl:if> <xsl:apply-templates select="*"/> </xsl:template> <xsl:template match="BOOK/*"> <xsl:if test="not(position()=1)">|</xsl:if> <xsl:value-of select="."/> </xsl:template> </xsl:stylesheet> when this transformation is applied on the following XML document: <LIBRARY> <BOOK> <TITLE>Professional JINI</TITLE> <AUTHOR>Sing Li</AUTHOR> <PUBLISHER>Wrox Publications</PUBLISHER> </BOOK> <BOOK> <TITLE>XSLT 2.0 Programmer's Reference</TITLE> <AUTHOR>Michael Kay</AUTHOR> <PUBLISHER>Wrox Publications</PUBLISHER> </BOOK> </LIBRARY> the wanted, correct result is produced: Professional JINI|Sing Li|Wrox Publications XSLT 2.0 Programmer's Reference|Michael Kay|Wrox Publications II. XSLT 2.0 solution: <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text"/> <xsl:strip-space elements="*"/> <xsl:template match="BOOK"> <xsl:if test="not(position()=1)"> <xsl:text>&#xA;</xsl:text> </xsl:if> <xsl:value-of select="*" separator="|"/> </xsl:template> </xsl:stylesheet> A: You mean a concatenation of all subelements with | separating them? <xsl:for-each select="node()>|<xsl:value-of select="."/></xsl:for-each>
{ "language": "en", "url": "https://stackoverflow.com/questions/7600947", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cycling values in a hidden field on image click I hope someone can help me. I am new to jquery. I want to show pictures of my students on a page so I can take the presence easily. I made that using a MySQL DB with php. That's the easy part. Next, i managed to make a jquery script so when I click each image the border of that image cycle through green, red and yellow (in - out - late css class). Here is the html code (id from hidden field is the student number) <div class="presences-container"> <ul> <li class="presences-image in"><img src="7465.jpg"> <input type="hidden" id="7465" name="presence2" value="in"/></li> <li class="presences-image out"><img src="9484.jpg"> <input type="hidden" id="9484" name="presence3" value="in"/></li> <li class="presences-image late"><img src="2627.jpg"> <input type="hidden" id="2627" name="presence4" value="in"/></li> </ul> </div> And the jQuery $(document).ready(function() { $('li').toggle( function() { $(this).toggleClass('in out'); $(this).removeClass('in'); ;}, function() { $(this).toggleClass('out late'); $(this).removeClass('out'); }, function() { $(this).toggleClass('late in'); $(this).removeClass('late'); } ); }); Now, I want to set each hidden field value according to the state of the image (in ou or late) with jquery and submit all hidden field to put it in my DB. Hope I'm clear enough! Thanks in advance for your help!! François A: is this what you want? just change the type to hidden. Live demo html: <div class="presences-container"> <ul id="ulPics"> <li class="presences-image in"><img src="7465.jpg"> <input type="text" id="7465" name="presence2"/></li> <li class="presences-image out"><img src="9484.jpg"> <input type="text" id="9484" name="presence3"/></li> <li class="presences-image late"><img src="2627.jpg"> <input type="text" id="2627" name="presence4"/></li> </ul> js: $("#ulPics li input").each(function(){ $(this).val($(this).parents('li').attr("class").split(" ")[1]); }); A: You could use some code like this to update the corresponding hidden fields when the the <li>s have been clicked - var hiddenid = $(this).find('img').attr('src').replace(".jpg",""); $("#" + hiddenid).val($(this).attr('class').split(' ').splice(-1)); You could then serialize your hidden input values like this - vat hiddenvals = $("input[type=hidden]").serialize(); And then post back to you your server using the 'post' or 'ajax' methods. A: From what I understand, something like this should do the trick: var states = $(['late','out','in']); $('li').click(function() { var $this = $(this), $hiddenField = $this.find('input:hidden'), idx = $.inArray($hiddenField.val(), states); // update hidden field $hiddenField.val(states.get(--idx)); // update li $this.removeClass('in out late').addClass($hiddenField.val()); }); jsFiddle
{ "language": "en", "url": "https://stackoverflow.com/questions/7600953", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to check for the immediate following sibling of parents in xpath I am now using xpath to test a node's parent node's immediate following sibling(uncle or ant) node. My xml looks like <MyParent> <A> <B> <C> </MyParent> <Uncle> .. </Uncle> Now I am in the template match for child node B, and I want to test if the immeididate following-sibling of my parent is called "Uncle", I tried the following two xpaths: <xsl:if test="parent::MyParent/following-sibling::*[1][self::Uncle]"> <xsl:text>we have it</xsl:text> </xsl:if> and <xsl:if test="parent::MyParent[following-sibling::*[1][self::Uncle]]"> <xsl:text>we have it</xsl:text> </xsl:if> neither of them will work, could experts help debug where I made mistakes? Thanks :). A: Try this. ../following-sibling::*[position()=1][name()='Uncle']
{ "language": "en", "url": "https://stackoverflow.com/questions/7600960", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: page is not processed if content is in a while loop <?php include("global-settings.php"); session_start(); mysql_connect($dbhost, $dbuser, $dbpass)or die("Could Not Connect: " . mysql_error()); mysql_select_db($dbname) or die(mysql_error()); $email = mysql_real_escape_string(strip_tags($_POST['email'])); $password = mysql_real_escape_string(strip_tags(sha1($_POST['password']))); $result = mysql_query("SELECT * FROM users WHERE username='$email' AND password='$password'") or die(mysql_error()); while($row = mysql_fetch_array($result)) { if(mysql_num_rows($result) > 0) { $_SESSION['user_pid'] = $row['user_pid']; $_SESSION['firstname'] = $row['first_name']; $_SESSION['lastname'] = $row['last_name']; header("Location: ../protected/home.php"); } else { $userid_generator = uniqid(rand(), false); $date = date("Y/m/d"); mysql_query("INSERT INTO users (user_pid, username, password, datetime_registered) VALUES('$userid_generator', '$email', '$password', '$date')")or die(mysql_error()); $_SESSION['userid'] = $userid_generator; $_SESSION['firstname'] = $row['first_name']; $_SESSION['lastname'] = $row['last_name']; $leaders_query = "SELECT * FROM leaders"; $leaders = mysql_query($leaders_query); $id = $row['id']; mysql_query("INSERT IGNORE INTO friends (node1id, node2id, is_leader, friends_since, friend_type) VALUES('$id', '$userid_generator', 'Yes', '$date', 'full)")or die(mysql_error()); } } ?> for some reason the while loop doesn't seem to work. It leaves a blank screen when I insert the content inside the while loop. Any help? A: Your logic is a bit wonky. There's no need for a while loop in this case (using one for what should only ever produce at most a single row of data is evidence of cargo cult programming). The logic flow should be: $sql = "..."; $result = mysql_query($sql) or die(mysql_error()); if (mysql_num_rows($result) > 0) { $row = mysql_fetch_array($result); $_SESSION stuff } else { ... create user record ... } As well, what is the point of the SELECT * FROM Leaders query? You don't actually fetch anything from that query so basically it's a useless operation. A: The logic of your code is wrong: your if(mysql_num_rows(...)) should be before the while(mysql_fetch_array(...)) loop. Try something like this: <?php include("global-settings.php"); session_start(); mysql_connect($dbhost, $dbuser, $dbpass)or die("Could Not Connect: " . mysql_error()); mysql_select_db($dbname) or die(mysql_error()); $email = mysql_real_escape_string(strip_tags($_POST['email'])); $password = mysql_real_escape_string(strip_tags(sha1($_POST['password']))); $result = mysql_query("SELECT * FROM users WHERE username='$email' AND password='$password'") or die(mysql_error()); if(mysql_num_rows($result) > 0) { $row = mysql_fetch_array($result); $_SESSION['user_pid'] = $row['user_pid']; $_SESSION['firstname'] = $row['first_name']; $_SESSION['lastname'] = $row['last_name']; header("Location: ../protected/home.php"); } else { $userid_generator = uniqid(rand(), false); $date = date("Y/m/d"); $res_insert = mysql_query("INSERT INTO users (user_pid, username, password, datetime_registered) VALUES('$userid_generator', '$email', '$password', '$date'); SELECT MAX(user_pid) FROM users;") or die(mysql_error()); $_SESSION['userid'] = $userid_generator; $_SESSION['firstname'] = $row['first_name']; $_SESSION['lastname'] = $row['last_name']; $leaders_query = "SELECT * FROM leaders"; $leaders = mysql_query($leaders_query); $id = mysql_insert_id($res_insert); mysql_query("INSERT IGNORE INTO friends (node1id, node2id, is_leader, friends_since, friend_type) VALUES('$id', '$userid_generator', 'Yes', '$date', 'full)") or die(mysql_error()); } ?> A: probably the resultset is empty, you can change de while for a do while, so it will be executed at least once. the way it is, you are trying to count if there are rows inside the while, if there is none, it will never pass through there. A: <?php session_start(); include("global-settings.php"); mysql_connect($dbhost, $dbuser, $dbpass)or die("Could Not Connect: " . mysql_error()); mysql_select_db($dbname) or die(mysql_error()); $email = mysql_real_escape_string(strip_tags($_POST["email"])); $password = sha1($_POST["password"]); $sql = "SELECT * FROM users WHERE email = '{$email}' AND password = '{$password}'"; $result = mysql_query($sql) or exit("ERROR: " . mysql_error() . "<br>IN QUERY: " . $sql); if (mysql_num_rows($result) > 0) { $row = mysql_fetch_array($result); $_SESSION["userid"] = $row['user_pid']; echo "logged in"; } else { $userid_generator = uniqid(rand(), false); mysql_query("INSERT INTO users (user_pid, email, password, datetime_registered, is_leader) VALUES ('$userid_generator', '{$email}', '{$password}', NOW(), 'no')"); $id = mysql_insert_id(); $leaders = mysql_query("SELECT * FROM users WHERE is_leader LIKE '%yes%'"); while($rows = mysql_fetch_array($leaders)) { if ($rows['is_leader'] == 'yes') { $leader_id = $rows['user_pid']; mysql_query("INSERT IGNORE INTO friends (node1id, node2id, friends_since, friend_type) VALUES('$leader_id', '$userid_generator', NOW(), 'full')"); $_SESSION["userid"] = $userid_generator; echo "new user created and logged in"; } if(is_dir($userid_generator)) { echo "Something wen't wrong. A bug report has been sent and we are doing what we can to fix it."; $message = 'Registration problem on account number $userid_generator. The user succesfully registered, but there is already a directory with the account id of $userid_generator.'; mail($bug_report_email, "Registration Bug!", $message); } else { mkdir('../media/User-PID{' . $userid_generator . '}', 0777); mkdir('../media/User-PID{' . $userid_generator . '}/photos', 0777); mkdir('../media/User-PID{' . $userid_generator . '}/backups', 0777); mkdir('../media/User-PID{' . $userid_generator . '}/videos', 0777); mkdir('../media/User-PID{' . $userid_generator . '}/documents', 0777); mkdir('../media/User-PID{' . $userid_generator . '}/developer', 0777); mkdir('../media/User-PID{' . $userid_generator . '}/developer/apps', 0777); mkdir('../media/User-PID{' . $userid_generator . '}/developer/themes', 0777); mkdir('../media/User-PID{' . $userid_generator . '}/xml', 0777); } } } ?> I actually fixed it. Thanks for your all's help though!
{ "language": "en", "url": "https://stackoverflow.com/questions/7600961", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I make a function only possible to be called by certain subclasses in c++? I have a class base with a private array (I cannot make it protected). I have getters and setters set for objects in the array. base has a subclass sub1 and sub1 has a subclass sub2. Is there a way to make sub1 only able to access some of base's getter's and setter's and make sub2 able to access other getters and setters? Something with virtual methods perhaps? A: No. Not in any good fashion If you want this, you should break your base class into better granularity by creating several polymorphic interfaces and instead pass those interfaces around via pointer or reference so that each class only sees the functions it needs to see.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600962", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Drop down menu hover does not cover whole text Screenshot1: Screenshot 2: If you look at the screenshot1, you can see when you hover over web design it doesn't completely change the background color. However it does in case you hover over text 'Search Engine' in Screenshot 2. Here is the markup: Html: <div id="nav"> <ul> <li><a href="#" >My Health</a></li> <li><a href="#" >Fitness</a></li> <li><a href="#" >Diet &amp; Nutrition</a> <ul> <li><a href="#">Webdesign</a></li> <li><a href="#">Development</a></li> <li><a href="#">Illustration</a></li> <li><a href="#">Search engine</a></li> <li><a href="#">WordPress</a></li> </ul> </li> <li><a href="#">Stress Management</a></li> </ul> </div> CSS: #nav { width: 100%; height: 36px; background: url('../images/nav-bg.png') repeat; margin-bottom: 10px; } #nav ul li a{ display: block; float: left; font: bold 15px Arial, Helvetica, sans-serif; color: #FFFFFF; padding: 9px 14px; } #nav ul li a:hover{ color: #355da5; background: #fff; border: medium black; } #nav ul li ul{ display: none; position: absolute; top: 130px; margin: 8px 0px 0px 180px; background: url('../images/nav-bg.png') repeat; } #nav ul li ul li a{ text-align: center; font-size: 12px; } #nav ul li:hover ul, li.over ul{ display: block; } Does anyone know how can i fix this? Thank you. A: Try setting width: 100% on #nav ul li a. A: your nested <a> tags are matched by the css selector #nav ul li a, and are therefore floated left. try adding float:none; inside #nav ul li ul li a
{ "language": "en", "url": "https://stackoverflow.com/questions/7600965", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Check existence of rows for last n days I want to perform a check "is there an entry for each of the last 100 days in a table" where the table has something like a reference date column and was thinking about joining with a subquery that returns sysdate - 0, sysdate - 1, ... sysdate - 100. Updates (for clarification): * *I need to know which dates are missing in the last n days *I want to avoid additional tables (also temp tables) Is this a good approach? A: Assuming your Oracle table looks like this... CREATE TABLE DATE_TABLE ( D DATE, -- And other fields, PK etc... ) ...and assuming D contains "round" dates (i.e. no time-of-day), the following query will give you all the missing dates between :min_date and :min_date + :day_count: SELECT * FROM ( SELECT (TO_DATE(:min_date) + LEVEL - 1) GENERATED_DATE FROM DUAL CONNECT BY LEVEL <= :day_count ) WHERE GENERATED_DATE NOT IN (SELECT D FROM DATE_TABLE) In plain English: * *Generate all dates in given interval (the sub-query). *Check if any of them is missing from the table (the super-query). A: This is what you are looking for: Select seqnum.date, count(issues.id) from ( SELECT Curdate() - interval (TENS.SeqValue + ONES.SeqValue) day Date FROM ( SELECT 0 SeqValue UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9 ) ONES CROSS JOIN ( SELECT 0 SeqValue UNION SELECT 10 UNION SELECT 20 UNION SELECT 30 UNION SELECT 40 UNION SELECT 50 UNION SELECT 60 UNION SELECT 70 UNION SELECT 80 UNION SELECT 90 ) TENS ) seqnum left join issues on (cast(issues.created_on as date) = seqnum.date) group by seqnum.date I ran it against a Redmine instance to see how many issues were created in the last 100 days, day by day, including days where no issue was created. Adjust to your data structures accordingly. Enjoy :) A: This might help you out: create table your_table (a_date date not null); insert into your_table values (date(now()-interval 0 day)); insert into your_table values (date(now()-interval 1 day)); insert into your_table values (date(now()-interval 2 day)); insert into your_table values (date(now()-interval 3 day)); insert into your_table values (date(now()-interval 5 day)); insert into your_table values (date(now()-interval 6 day)); insert into your_table values (date(now()-interval 9 day)); insert into your_table values (date(now()-interval 10 day)); insert into your_table values (date(now()-interval 50 day)); insert into your_table values (date(now()-interval 60 day)); insert into your_table values (date(now()-interval 70 day)); insert into your_table values (date(now()-interval 80 day)); insert into your_table values (date(now()-interval 90 day)); select a_date,ifnull(datediff(next_date ,a_date)-1,0) as number_of_days_missing_after_date from ( select dt.a_date, (select min(a_date) from your_table dtp where dtp.a_date > dt.a_date and dtp.a_date >= date(now()-interval 100 day)) as next_date from (select a_date from your_table union select date(now()-interval 100 day)) dt where dt.a_date >= date(now()-interval 100 day) ) a; Should give you an indication as to which dates are missing. I have created table your_table in place of the table that you are planning to check for missing dates (so that I could illustrate my example more clearly to you). Perhaps the only problem with this solution is that it will not give you a list of the missing dates - though they can be easily derived by looking at the (in the example) a_date column and the number of days missing after a_date. Hope it helps & good luck! A: If there aren’t any gaps (e.g., weekends), a trick you can use is SELECT COUNT(DISTINCT somedate)=100 FROM sometable -- evaluates to boolean WHERE somedate>=sysdate-100; Depending on your RDBMS, a GROUP BY may work faster than COUNT DISTINCT. [Post clarification comment] As you have explained it now, I think you want a LEFT JOIN between a dense date list and your table, then COUNT and GROUP BY. If you are using MySQL, the way to generate the date list in a subquery is covered by this earlier stackoverflow (I don't know MySQL nearly well enough to have thought of the accepted answer). It is easier in most other DB systems. The solution mentioned at that link of a permanent calendar table is not so bad, either. A: In MySQL: SELECT * FROM `table_name` WHERE `date_column` > DATE_SUB(CURDATE(), INTERVAL 99 DAY) See MySQL Date Arithmetic
{ "language": "en", "url": "https://stackoverflow.com/questions/7600967", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Vaadin + Eclipse Visual Editor NOT reloading/updating Composite components I created a Vaadin Project, then wanted to create a Custom composite and display that as my main window (so i could take advantage of the Visual UI editor). Working with Tomcat Apache Server and the Visual Editor has been a pain! Nothing updates even when i start, stop or restart the server. My mainWindow application will display some Vaadin components and not others. Here is an example i have of my main window code import com.vaadin.Application; import com.vaadin.ui.*; public class DApplication extends Application { @Override public void init() { Window mainWindow = new Window("DApplication"); //Header header = new Header(); //header.setSizeFull(); DHome dHome = new DHome(); // **HERE IS THE COMPOSITE INSTANCE I CREATED IN ECLIPSE** dHome.setSizeFull(); mainWindow.getContent().setSizeFull(); mainWindow.addComponent(dHome); setMainWindow(mainWindow); } } Is this a bug or a problem with others using these same tool for making vaadin applications. My application even if i shut off my machine wont update with newly components added to the composite? A: When you open the URL for the application, it creates a new user session. The session is preserved even if you reload the page. However, if you use Eclipse, it likes to do hot deployment to Tomcat and you may experience a problem that the application does not return to its initial state after you modify code. As Tomcat likes to persist sessions on server shutdown, the application state can remain even if you restart the server. Adding the ?restartApplication parameter in the URL tells the Vaadin servlet to create a new Application instance on loading the page. If you also include a URI fragment, the parameter should be given before the fragment.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600970", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to extract the digit part from the string I have a column that has a string in it as follow Data black83736 white87 white893 pink82928 pink1 black27 ... ... I want to just get the digits out of that column. Edit I would prefer mysql solution A: Try this mysql Solution : (updated) SELECT replace(reverse(FORMAT(reverse(COLUMN_NAME), 0)), ',', '') as number from TABLE_NAME; this is for your particular case, where you want the numbers in the end. so first we Reverse, so numbers come to beginning format, so alphabets are removed, format is used for formatting a number with specified decimal places, here we specify it to 0. reverse again -> to obtain the original number replace ',' to '' -> to remove the effect of formatting of second step. ** (UPDATE) ** the above solution doesnt work for numbers ending in 0's (thanks to karolis for telling) so for that SELECT replace(replace(reverse(FORMAT(reverse(concat(numbers, '9099')), 0)), ',', ''), '9099', '') as number from test1; Here we are appending '9099' to the end of the number, and then removing 9099 in the end. 9099 ? just a number which would be highly in-probable to occur in your columns A: $result = preg_replace('~[^0-9]*~', '', $string); A: Yes, it's very inelegant, but currently the only reliable MySQL only solution that I know: select replace(column_name, replace(replace(replace(replace(replace( replace(replace(replace(replace(replace( column_name, 0, ''), 1, ''), 2, ''), 3, ''), 4, ''), 5, ''), 6, ''), 7, ''), 8, ''), 9, ''), '') A: filter_var('stri99ng', FILTER_SANITIZE_NUMBER_INT); I would prefer mysql solution Well, you shouldn't unless you have powerful processor or this query does not return many results. MySQL isn't generally good for any string manipulation operations.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600974", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Is the SVN Book Inconsistent about "Switching a Working Copy"? The SVN Book chapter on "Switching a Working Copy" seems to say both that performing a switch 1) makes your working copy identical to the branch switched to (as if one had done a fresh checkout) and 2) preserves edits to your working copy (so that you could commit them to the branch switched to.) This sounds inconsistent to me, because if the switch makes it like a fresh checkout, then your edits can't be preserved. Can anyone please explain? Here are the relevant quotes: After “switching” to the branch, your working copy is no different than what you would get from doing a fresh checkout of the directory. ... For example, suppose you have a working copy of /calc/trunk and make a number of changes to it. Then you suddenly realize that you meant to make the changes to a branch instead. No problem! When you svn switch your working copy to the branch, the local changes will remain. You can then test and commit them to the branch. TIA A: Check out the box on that page called "Switches and Updates": Have you noticed that the output of svn switch and svn update look the same? The switch command is actually a superset of the update command. When you run svn update, you're asking the repository to compare two trees. The repository does so, and then sends a description of the differences back to the client. The only difference between svn switch and svn update is that the update command always compares two identical paths. That is, if your working copy is a mirror of /calc/trunk, then svn update will automatically compare your working copy of /calc/trunk to /calc/trunk in the HEAD revision. If you're switching your working copy to a branch, then svn switch will compare your working copy of /calc/trunk to some other branch-directory in the HEAD revision. In other words, an update moves your working copy through time. A switch moves your working copy through time and space. Basically, think of the "switch" command as telling SVN, "hey, back my working copy by this new repository URL, then update my working copy to the latest version of that new URL". So, the comment that "switch" makes your working copy look like a fresh checkout of the new URL is correct if you have no local modifications to your working copy. It is not accurate if you have local modifications. In that case, your working copy would look like a fresh checkout of the new URL, with your modifications merged in.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600978", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Writing HTML in email Newbie Is there any sample application/tutorial that demonstrates how to write HTML code using [mailComposer setMessageBody:nil isHTML:_________]; I simply want to write some HTML code here, how do i code it ? A: Just write your HTML code as NSString and set it to the composer body. Then set isHTML to YES: MFMailComposeViewController *composer = [[MFMailComposeViewController alloc] init]; composer.mailComposeDelegate = self; NSString *emailBody = @"<p><b>Hello World</b></p>"; [picker setMessageBody:emailBody isHTML:YES]; RTFM ;)
{ "language": "en", "url": "https://stackoverflow.com/questions/7600980", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to add a new html tag with Jsoup? I'm having some trouble adding a new tag to my Document. For example I have: Document doc = Jsoup.parse(htmlString); Element table = doc.select("table").first(); Now If I want to add a <LINK>tag with attributes (href,type,rel) to my table element, and then return the total as a string, How would I do this? A: Use something like this: Jsoup.parse(new URL(""), 0).getElementById("test").appendElement("h1").attr("id", "header").text("Welcome"); And all ".append*" methods. A: It's been quite some time but I also searched through for it a while so I will share my answer. This is for Jsoup 1.13.1 Document doc = Jsoup.parse(htmlString); Element table = doc.select("table").first(); table.appendElement("link").attr("href","example.com/file.css").attr("rel","stylesheet").attr("type","text/css");
{ "language": "en", "url": "https://stackoverflow.com/questions/7600984", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Implement Interface Wizard - how to find the "type library" of an interface? I want to implement (e.g) the IPersistFile interface via the "Implement Interface" Wizard in Visual Studio (2010), but I have to choose from the "Available type libraries" the one that has that interface. The MS documentation only says it is in "ole32.dll" (when I choose that file I get an error "No type library found in file ..."). How do I find which "type library" holds the (e.g) IPersistFile interface ? A: For some interfaces you can look up containing type via registry HKEY_CLASSES_ROOT\Interface\<IID>\TypeLib, but note that an interface does not necessarily have to have a type library reference.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600985", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Stop Recording and Context My problem is follow: when the call ends I get an error. I think there somthing with Context. My problem as in this case Sound Recorder Widget doesnt stop recording Please help me! public class Call extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); if(null == bundle) return; String state = bundle.getString(TelephonyManager.EXTRA_STATE); if(state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_RINGING)) { mFileName = "/sdcard/Record.3gp"; MediaRecorder mRecorder = new MediaRecorder(); mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); mRecorder.setOutputFile(mFileName); mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); try {mRecorder.prepare();} catch (IOException e){} mRecorder.start(); } if(state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_IDLE)) { mRecorder.stop(); mRecorder.release(); mRecorder = null; } } } This is from LogCat: 10-01 07:13:28.054: ERROR/AndroidRuntime(553): Uncaught handler: thread main exiting due to uncaught exception 10-01 07:13:29.134: ERROR/AndroidRuntime(553): java.lang.RuntimeException: Unable to start receiver xxx.xxx.xxx.Call: java.lang.NullPointerException 10-01 07:13:29.134: ERROR/AndroidRuntime(553): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2646) 10-01 07:13:29.134: ERROR/AndroidRuntime(553): at android.app.ActivityThread.access$3100(ActivityThread.java:119) 10-01 07:13:29.134: ERROR/AndroidRuntime(553): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1913) 10-01 07:13:29.134: ERROR/AndroidRuntime(553): at android.os.Handler.dispatchMessage(Handler.java:99) 10-01 07:13:29.134: ERROR/AndroidRuntime(553): at android.os.Looper.loop(Looper.java:123) 10-01 07:13:29.134: ERROR/AndroidRuntime(553): at android.app.ActivityThread.main(ActivityThread.java:4363) 10-01 07:13:29.134: ERROR/AndroidRuntime(553): at java.lang.reflect.Method.invokeNative(Native Method) 10-01 07:13:29.134: ERROR/AndroidRuntime(553): at java.lang.reflect.Method.invoke(Method.java:521) 10-01 07:13:29.134: ERROR/AndroidRuntime(553): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860) 10-01 07:13:29.134: ERROR/AndroidRuntime(553): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618) 10-01 07:13:29.134: ERROR/AndroidRuntime(553): at dalvik.system.NativeStart.main(Native Method) 10-01 07:13:29.134: ERROR/AndroidRuntime(553): Caused by: java.lang.NullPointerException 10-01 07:13:29.134: ERROR/AndroidRuntime(553): at xxx.xxx.xxx.Call.onReceive(Call.java:49) 10-01 07:13:29.134: ERROR/AndroidRuntime(553): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2637) 10-01 07:13:29.134: ERROR/AndroidRuntime(553): ... 10 more 10-01 07:13:33.184: ERROR/audio_input(31): unsupported parameter: x-pvmf/media-input-node/cap-config-interface;valtype=key_specific_value 10-01 07:13:33.184: ERROR/audio_input(31): VerifyAndSetParameter failed A: The mRecorder is null when the call ends because, is never initialized. You should make the mRecorder variable a class variable and initialize it when the call starts. Now, your are just declaring a new MediaRecorder in the scope of that if statement when the call starts. So it should be like this: public class Call extends BroadcastReceiver{ private MediaRecorder mRecorder; public void onReceive(Context context, Intent intent){ //... if(state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_RINGING)){ mRecorder = new MediaRecorder(); mRecorder.start(); //.... } if(state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_IDLE)){ if(mRecorder!=null){ mRecorder.stop(); mRecorder.release(); mRecorder = null; } } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7601005", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Python equivalent to Bash $() I search the Python equivalent for the following Bash code: VAR=$(echo $VAR) Pseudo Python code could be: var = print var Can you help? :-) Regards Edit: I search a way to do this: for dhIP in open('dh-ips.txt', 'r'): gi = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE) print gi.country_code_by_addr(print dhIP) # <-- this line is my problem In Bash i would do it like this: print gi.country_code_by_addr($(dhIP)) # only pseudo code... Hope it's more clear now. Edit2: Thank you all! Here's my solution which works. Thanks to Liquid_Fire for the remark with the newline char and thanks to hop for his code! import GeoIP fp = open('dh-ips.txt', 'r') gi = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE) try: for dhIP in fp: print gi.country_code_by_addr(dhIP.rstrip("\n")) finally: fp.close() A: You don't need a print in there, just use the name of the variable: for dhIP in open('dh-ips.txt', 'r'): gi = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE) print gi.country_code_by_addr(dhIP) Also note that iterating through a file object gives you lines with the newline characters at the end. You may want to use something like dhIP.rstrip("\n") to remove them before passing it on to country_code_by_addr. A: Just use dhIP as it is. There is no need to do anything special with it: for dhIP in open('dh-ips.txt', 'r'): gi = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE) print gi.country_code_by_addr(dhIP) NB: There are some other issues with your code. Without being familiar with the library you use, it seems to me that you unnecessarily instantiate GeoIP in every iteration of the loop. Also, you should not throw away the file handle, so you can close the file afterwards. fp = open('dh-ips.txt', 'r') gi = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE) try: for dhIP in fp: print gi.country_code_by_addr(dhIP) finally: fp.close() Or, even better, in 2.5 and above you can use a context manager: with open('dh-ips.txt', 'r') as fp: gi = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE) for dhIP in fp: print gi.country_code_by_addr(dhIP) A: You might want to try these functions: str(var) repr(var) A: If you're just trying to reassign a value to the same name it would be: var = var Now if you're trying to assign the string representation (which is usually what print returns) of whatever object is referred to by var: var = str(var) Is that what you're after?
{ "language": "en", "url": "https://stackoverflow.com/questions/7601010", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Saving the DeviceToken for Later Use in Apple Push Notification Services In my iPhone app I am getting the device token from Apple which I am assigning a public property inside the Delegate file as shown below: - (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken { self.dToken = [[NSString alloc] initWithData:deviceToken encoding:NSUTF8StringEncoding]; } The dToken property is declared as shown below: NSString *dToken; @property (nonatomic,retain) NSString *dToken; But when I try to retrieve the device token from another file I get the null value. +(NSString *) getDeviceToken { NSString *deviceToken = [(MyAppDelegate *)[[UIApplication sharedApplication] delegate] dToken]; NSLog(@" getDeviceToken = %@",deviceToken); // This prints NULL return deviceToken; } What am I doing wrong? A: From the discussion at Best way to serialize an NSData into a hexadeximal string, here is a better way to do it. Is longer, but your code will be future-proof if Apple changes the way NSData emit debugger descriptions. Extend NSData as follows: @implementation NSData (Hex) - (NSString*)hexString { unichar* hexChars = (unichar*)malloc(sizeof(unichar) * (self.length*2)); unsigned char* bytes = (unsigned char*)self.bytes; for (NSUInteger i = 0; i < self.length; i++) { unichar c = bytes[i] / 16; if (c < 10) c += '0'; else c += 'A' - 10; hexChars[i*2] = c; c = bytes[i] % 16; if (c < 10) c += '0'; else c += 'A' - 10; hexChars[i*2+1] = c; } NSString* retVal = [[NSString alloc] initWithCharactersNoCopy:hexChars length:self.length*2 freeWhenDone:YES]; return [retVal autorelease]; } @end A: I suggest you to convert token to string in this way: self.dToken = [[[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]] stringByReplacingOccurrencesOfString:@" " withString:@""]; UPDATED: As many people mentioned it is better to use next approach to convert NSData * to NSString *: @implementation NSData (Conversion) - (NSString *)hexadecimalString { const unsigned char *dataBuffer = (const unsigned char *)[self bytes]; if (!dataBuffer) { return [NSString string]; } NSUInteger dataLength = [self length]; NSMutableString *hexString = [NSMutableString stringWithCapacity:(dataLength * 2)]; for (int i = 0; i < dataLength; ++i) { [hexString appendFormat:@"%02lx", (unsigned long)dataBuffer[i]]; } return hexString; } @end A: I know that this is an old question and that this may be new information that has come up since then, but I'd just like to point something out to all of the people who are claiming that using the description method is a really bad idea. In most cases, you'd be exactly right. The description property is generally just used for debugging, but for the NSData class, it's specifically defined as returning a hexadecimal representation of the receivers contents which is exactly what is needed here. Since Apple has put it in their documentation, I think you're pretty safe as far as them changing it. This can be found in the NSData Class Reference here: https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/Reference/Reference.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7601011", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: How to return tree within same level efficiently I have a tree with nodes that implement this interface Interface Node { public boolean hasChildren() {}; } How can I return a List of List with same treeLevel ? for example if I have a tree like                  1       2                   3 4       5            6      7 I'll return a list of list like this {{1}{2,3}{4,5,6,7}} Thanks. A: This is basically a breadth-first traversal, except at each level you keep a list of that level. something like this example C# code: IEnumerable<Node[]> Traverse(Node root) { Node[] currentLevel = new [] { root }; Node[] nextLevel = null; while(true) { nextLevel = currentLevel.SelectMany(n => n.Children).ToArray(); if (nextLevel.Length > 0) { yield return nextLevel; currentLevel = nextLevel; } else { break; } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7601012", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How would you pass HTTP Headers using a standard anchor tag? According to the HTML4 reference there's no attribute to pass on HTTP headers using the anchor tag. I would like to offer a link requesting for a specific file type using the Accept header. The only way I can see is simply let it be, and pass a GET parameter. You may as why I would want to do this... I intend to expose a bunch of methods as a public API, serving the results as JSON. And when doing requests using JavaScript, or another programming language, using the Accept header to request a specific response format is "The Right Way" to do it. But that would mean that I need to accommodate both the Accept header and the GET parameter in my code, which smells like a duplication of logic. This topic is largely debatable, as such links may not be possible to bookmark in the browser... still... I'd like to know if it was possible without too much magic... A: I don't see another way than using the GET parameter or an extension like http://myurl/page?format=json or better http://myurl/page.json Which overrides the accept header (since the browser will only send it's default accept header). Then you just need to initialize a format to accept header mapping like this (which I don't find duplicate logic at all): { "json" : "application/json", "html" : "text/html" } A: You can't. I intend to expose a bunch of methods as a public API, serving the results as JSON. And when doing requests using JavaScript, or another programming language, using the Accept header to request a specific response format is "The Right Way" to do it. But that would mean that I need to accommodate both the Accept header and the GET parameter in my code, which smells like a duplication of logic. If I understand you correctly, you don't have to do this anyway. Browsers already supply an Accept header. A: Hmm, seems like if your results are JSON, you will be sending / receiving from script anyway, which can provide any header you want. Just have your link call a script function and you're done.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601015", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: how to increase speed of my application? My applications requirement is to contact the webservice, get the xml, parse it and display it using a listfield. I am calling all this classes xmlhandler, objectmodel, displaying it using a lisfield from a class that extends mainscreen which is making my application slow. Can anyone suggest me how to make it fast? Is it a apt to popup a loading screen and start a thread for contacting the webservice, get the xml, parsing it and kill the thread, then populate the listscreen and display it? suggestions of any kind is welcome! A: Test the speed of every part of your program. What I usually use is System.nanoTime() and find the difference in time after every part of the program. A: Find out which part is slow before you do anything else. Otherwise, you'll waste a lot of your time on the wrong parts. For doing this kind of timing work, I often will do internal logging into a StringBuilder, or maybe just into an ArrayList holding raw, unformatted data. After the test is over, I format and output the data. This minimizes the effect of the logging on the timings. A: I can only gues so forgive me if I'm wrong - to me it seems more efficient to create the item of list field only when they're really viewed. So I'd try to keep in memory only the parsed strings and create only the UI items currently to be displayed, discard invisible. To make it more smooth you can you can extend it one or more pages before and after current page. This way the number of displayed items is always constant. You may also add paging to the service layer to limit number of records trabsmitted at once.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601016", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can I map a table and a view of the same table in Hibernate without breaking my automated tests? Say I have a table like so: CREATE TABLE big_table (UUID varchar(32) not null, ... ); I have a query on the table that I can't express as an HQL or Criteria query. I am trying to set up the query as view in Oracle, like so: CREATE VIEW big_table_view AS SELECT bt.* FROM big_table bt LEFT OUTER JOIN ... -- (multicolumn subselect over big_table for some historical stuff) WHERE ... I am trying to map the same Java class to both the table and the view. That would be really cool because then I can run the same Criteria queries against both, etc. My problem is that I can't come up with an HBM mapping file that doesn't wreak havoc with my HSQLDB test code. My test setup is a typical Maven/Spring test setup with hibernate.hbm2ddl.auto set to create-drop so that Hibernate creates the HSQLDB schema on the fly for testing. My mapping file currently looks like this: <hibernate-mapping> <class name="com.example.BigPojo" entity-name="bigPojo" table="big_table"> &commonPropertiesEntity; </class> <class name="com.example.BigPojo" entity-name="bigPojoView" table="big_table_view"> &commonPropertiesEntity; </class> </hibernate-mapping> ...when I run my tests, they blow up all over the place because HSLQDB is trying to create a table called big_table_view with all the same foreign key constraints, indices, etc. I'm trying to fix the schema after it gets created via a database-object element like this: <database-object> <create> DROP TABLE big_table_view CASCADE; CREATE VIEW big_table_view... </create> <drop> DROP VIEW big_table_view IF EXISTS; </drop> <dialect-scope name="org.hibernate.dialect.HSQLDialect" /> </database-object> ...but there's still something breaking and I'm still wading through trying to figure it out. Is there a way to tell Hibernate to exclude the bigPojoView entity from hbm2ddl? Is there a better way to do this mapping generally? I'm open to any advice... A: There's no easy way to exclude a table from hbm2ddl. You can, however, map your view via Hibernate's subselect: see footnote #20 under 5.1.1. Something like: <class name="com.example.BigPojo" entity-name="bigPojoView" <subselect> ... your view definition here ... </subselect> <synchronize table="big_table"/> <id name="UUID"/> ... </class>
{ "language": "en", "url": "https://stackoverflow.com/questions/7601025", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using Multiple Databases Within CodeIgniter DISCLAIMER: I'm new to web development SCENARIO: I'm building a web application that uses ion_auth to manage all of the user/administrator information (uses MySQL database), and each user has their own database (MySQL as well) for core application purposes. I've autoloaded the database that I'm using for ion_auth in the applicaton/config/database.php file within CodeIgniter. I am using standard MVC format (individual models pertaining to each database). ISSUE: I'm needing to know how to use multiple databases at once within CodeIgniter easily and efficiently. Do I need to link the two database schemas together, or will CodeIgniter do that for me? Are there any resources out there that address this issue (I've had trouble trying to find one)? Thank you so much for all of your help! A: in your database config file add as many configuration groups as the numbers of your databases: $db['a']['hostname'] = 'localhost'; $db['a']['username'] = 'user'; $db['a']['password'] = 'pw'; $db['a']['database'] = 'db1'; ... $db['b']['hostname'] = 'localhost'; $db['b']['username'] = 'user'; $db['b']['password'] = 'pw'; $db['b']['database'] = 'db2'; ... //set the default db $active_group = 'a'; then on your model initialize a class variable: private $db_b; and, into the contructor, set it as follow __construct() { ... $this->db_b = $this->load->database('b', TRUE); } now you are able to use the database b as usual: $this->db_b->query('YOUR QUERY'); and obviously the default one as follow: $this->db->query('YOUR QUERY');
{ "language": "en", "url": "https://stackoverflow.com/questions/7601028", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Sql query result if no records found what will be the output of the below given query, if no matching records are found select avg(salary) from employee where dept='sales' Will it return 0 or null ? A: Have a look at this. It returns NULL A: Easy test in SQL Server: DECLARE @T TABLE (id int) INSERT INTO @T SELECT NULL SELECT AVG(id) FROM @T Returns NULL A: It returns null: http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_avg A: By default in MySQL and i'm pretty sure it is too in MSSQL, all aggregation functions return NULL if no data or if ANY OF THE DATA IS NULL, you cannot compute an aggregation on missing data.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601030", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Main differences between JSF 1.2 and 2.0 I am in need of getting up to speed with JSF 2.0. I have found a nice and practical tutorial at JSF tutorial. This tutorial covers creating JSF applications using JSPs (JSF 1.2). At our place we are using JSF 2.0 and building with Facelets. When studying a tutorial using JSPs what are the pitfalls and differences I need to be aware of when having to do things with Facelets ? A: The great thing about Facelets vs. JSP as a view technology for JSF is that facelets respect the entire jsf lifecycle whereas with JSP you have the two lifecycles competing (JSF vs. JSP). With JSP, you may be tempted to use other tag libraries (like JSTL) which may not behave as you are expecting due to the differences in the lifecycle. Some of the JSTL tags have been converted to facelet tags, but even then there are generally suitable pure JSF replacements for them (like ui:repeat in place of c:foreach) If you are doing JSF 2.0, use facelets and you'll never look back. A: Facelets are generally nice to work with. The major difference in JSF 2.0 compared to earlier versions is that you can directly invoke Java methods easily from EL, making it much easier to do logic operations and information passing in the JSF snippets themselves.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601033", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Ruby: How to pass options to test::unit in 1.9.3 I want to run a test file: # xxx.rb require 'test/unit'; class XTest < Test::Unit::TestCase; def test_xxx; end; end Until ruby 1.9.2 ruby -Itest -e "require './xxx.rb'" - -v did the job, with 1.9.3 I suddenly get: /usr/local/rvm/rubies/ruby-1.9.3-rc1/lib/ruby/1.9.1/test/unit.rb:167:in `block in non_options': file not found: - (ArgumentError) (it tries to load the file '-' which does not exist) Any ideas how to get the verbose mode back / to pass options to test::unit ? Correct output would look like: Loaded suite -e Started test_xxx(XTest): . A: Try it with a double-dash: ruby -Itest -e "require './xxx.rb'" -- -v Or like this (no dashes, no require): ruby -Itest xxx.rb -v To explain, I think that in your example you are using a single dash which commonly means 'use stdin as a file'. You could do this, for example: cat xxx.rb | ruby -Itest - -v Double-dashes are used to stop argument parsing and hence pass the -v to test unit. As to why your example with a single dash worked up to 1.9.3... I'm guessing that prior to 1.9.3 ruby wasn't as strict when you specify stdin but don't have anything coming in on stdin (as you don't).
{ "language": "en", "url": "https://stackoverflow.com/questions/7601039", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Understanding different methods of cloning a stream, and which situation to use which in When copying a file stream, I've come across two examples: This one, Using requestStream as IO.Stream = state.Request.EndGetRequestStream(ar) ' Copy the file contents to the request stream. Const bufferLength As Integer = 2048 Dim buffer(bufferLength - 1) As Byte Dim count As Integer = 0 Dim readBytes As Integer = 0 Using stream As IO.FileStream = IO.File.OpenRead(state.FileName) While readBytes <> 0 readBytes = stream.Read(buffer, 0, bufferLength) requestStream.Write(buffer, 0, readBytes) count += readBytes End While End Using End Using and this one: 'Copy the contents of the file to the request stream. Dim fileContents As Byte() Using fileStream As New IO.StreamReader(state.FileName) fileContents = Encoding.UTF8.GetBytes(fileStream.ReadToEnd()) End Using Using requestStream As IO.Stream = state.Request.EndGetRequestStream(ar) requestStream.Write(fileContents, 0, fileContents.Length) End Using My understanding is that the first one copies one stream directly to another, the second copies via a byte array. Both work and achieve the same thing. I believe the first one would be quicker, but the second one looks a lot simpler and easier to maintain etc. I can't see where you set the encoding in the first one though. Why would you need to do it in one, but not the other? Also, objective comments on the pro's and con's of each snippet would be useful. Thx A: The second one will not work with arbitrary binary data - it treats the data as UTF-8-encoded text data, then re-encodes it - this is a very bad idea unless you actually know it's UTF-8-encoded text. The second form uses a byte array as well, just one buffer at a time. However, you've got a bug in the first version: you're going to keep going while bytesRead is non-zero, but it starts as 0. You might want: Using stream As IO.FileStream = IO.File.OpenRead(state.FileName) readBytes = stream.Read(buffer, 0, bufferLength) While readBytes <> 0 requestStream.Write(buffer, 0, readBytes) count += readBytes readBytes = stream.Read(buffer, 0, bufferLength) End While End Using In C# I'd use: int bytesRead; while ((bytesRead = stream.Read(buffer, 0, bufferLength)) > 0) { requestStream.Write(buffer, 0, readBytes); count += readBytes; } but I don't know whether you can do a compound assignment like that in VB. Some other options: * *You can use File.ReadAllBytes to read a whole file as a byte array, although obviously that will waste memory if it's a large file. This is a sort of safe version of your second code. *You can use Stream.CopyTo(Stream) if you're using .NET 4. If not, you could potentially write the same code yourself as an extension method to be reused from other projects.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601041", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: php_intl.dll 4+ in xamp 1.7.4 + php 5.3.5 V6 for symfony 2 I'm trying to setup symfony under my local development machine using xampp 1.7.4 (with PHP 5.3.5 V6) but I'm getting this warning: Upgrade your intl extension with a newer ICU version (4+). I've tried downloading the source from windows.php.net but the version there is only for PHP VC9 (for PHP 5.3) I've also downloaded the latest version of ICU in http://site.icu-project.org/download but I'm missing the curresponding dll. Can anyone help me out? A: You might try the PHP PECL intl extension Wamp is another windows AMP stack, the last version comes with php 5.3.8... Good luck
{ "language": "en", "url": "https://stackoverflow.com/questions/7601045", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Detect when a new event is logged in Windows How would i detect in my application, when a new event is logged in the windows event log. Currently i'm running a timer ever 5 minutes to check for new events but it would be much better if i can detect new events in realtime using WMI or .net Thanks A: You need to set up a WMI Temporary Event Consumer in your app. Note that to monitor the Event Log you will need to request the SeSecurityPrivilege in your WMI connection (as it's possible you could receive events from the Security log, which require this permission) These are some example WQL queries: // See all events: select * from __InstanceCreationEvent where TargetInstance ISA 'Win32_NTLogEvent' // Catch only specific events: 4202 is a network transport failure select * from __InstanceCreationEvent where TargetInstance ISA 'Win32_NTLogEvent' and TargetInstance.EventCode=4202 // Catch only events from a specific source: in this case WMI itself. select * from __InstanceCreationEvent where TargetInstance ISA 'Win32_NTLogEvent' and TargetInstance.SourceName='WinMgmt'
{ "language": "en", "url": "https://stackoverflow.com/questions/7601047", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Div is laying ontop of absolute-positioned element. How to put element above the div? I have a couple of controls on the page. One of which is a button, another is div with width: 100%. The button has position: absolute. My buttons CSS -- just playing around with it for now: .toggleButton { z-index: 99999999px; position: absolute; margin-top: 2px; right: 130px; } The div is automatically generated, but here's its computed style: background-color: transparent; clear: both; color: dimGray; display: block; font-family: 'Lucida Grande', 'Lucida Sans', Arial, sans-serif; font-size: 11px; height: 26px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px; min-height: 0px; overflow-x: hidden; overflow-y: hidden; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; position: relative; width: 1026px; I'm wondering how to place the button over the div. In its current state the button isn't able to be clicked in all spots. I'm not looking to restrict the width of the div, just place the button over it. A: z-index is not in a px unit. So set your z-index of the div to 1 and set the z-index of the button to 20. .toggleButton { z-index: 20; position: absolute; margin-top: 2px; right: 130px; } I need a reference for this but I'm pretty certain z-index is capped at 100 so funky huge numbers like 9999999 just gets considered 100.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601049", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Process Synchronisation using semaphores Here is the problem. I want two processes to occur alternatively, the complete problem is here. Q. In a system ther are two processes named A and B.When the system starts,the process A executes twice then process B executes once.The Process B cannot execute until process A has executed twice. Once Process A haas executed it can not execute again until process B has executed. The restriction mentioned above allows the process A and B to execute in the following manner. AABAABAAB... Write the pseudocode for Process A and B using counting semaphore to achieve the desired synchronisation. Here is my attemp for this. Solution: Process A var a=1,b=0,i; begin repeat wait(a); for(i=0;i<2;i++) printf("A"); // conidering this is what process a does. signal(b); forever end Process B begin repeat wait(b); printf("B"); //considering this is what process B does. signal(a); forever end Is this correct? A: An alternative solution would be: Semaphore as = 1; Semaphore bs = 0; A() { int counter = 0; while(TRUE) { if(counter % 2 == 0) P(as); print("A"); // and whatever A does counter++; if(counter % 2 == 0) V(bs); } } B() { P(bs); print("B"); // and whatever B does V(as); } The idea is that A waits for B on every 2nd turn (execept the 0th). A: I think that the general idea is correct, but the terminology is rather strange. Wait-signal pair is usually used for condition variables (although e.g. POSIX semaphorese use post/wait). I suggest you substitue the wait with semaphore_down and signal with semaphore_up.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601050", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Validation on TextBox: red border does not always appear on invalid results I have a textbox that is bound to a property that requires a value, ie: [Required(ErrorMessage = "required value")] public string SomeText { //get set... } And in my XAML, I have the following setup for my textbox: UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=true, ValidatesOnExceptions=true As expected, the red border appears when there is no value in the textbox, however when I select a different tab and then go back to the page with the invalid results, the red border no longer appears. It only reappears if I enter a valid result and then erase it. How can I debug this? How can I find out what event causes the red border to appear? A: In WPF when items on the tab get unloaded from the visual tree the fact that they were marked invalid is lost. Basically, when a validation error happens the UI responds to an event in the validation stack and marks the item invalid. This marking doesn't get re-evaluated when the item comes back into the visual tree unless the binding is also re-evaluated (which it usually isn't if the user clicks on a tab item). Define a function like this somewhere (I put it in a static ValidationHelper class along with some other things): public static void ReMarkInvalid( DependencyObject obj ) { if( Validation.GetHasError( obj ) ) { List<ValidationError> errors = new List<ValidationError>( Validation.GetErrors( obj ) ); foreach( ValidationError error in errors ) { Validation.ClearInvalid((BindingExpressionBase)error.BindingInError); Validation.MarkInvalid((BindingExpressionBase)error.BindingInError, error); } } for( int i = 0; i < VisualTreeHelper.GetChildrenCount( obj ); i++ ) { ReMarkInvalid( VisualTreeHelper.GetChild( obj, i ) ); } } I think you can call this function in the TabControl's Selected event and it should have the desired effect. E.g.: private void TabControl_Selected(...) { ReMarkInvalid( tabControl ); } If that doesn't work you may need to do this at a lower Dispatcher priority to make sure the visual tree has finished loading first. Which would look like replacing ReMarkInvalid... with: Dispatcher.BeginInvoke( new Action( delegate() { ReMarkInvalid( tabControl ); } ), DispatcherPriority.Render ); A: You can simply put the contents of your tab inside AdornerDecorator tags: <TabControl> <TabItem> <AdornerDecorator> <ContentControl Content="{Binding TabItemViewModel}" /> <Grid> <!-- Other Stuff --> </Grid> </AdornerDecorator> </TabItem> </TabControl> Update: AdornerDecorator doesn't render borders on controls that are invisible (in unselected tabs). It just preserves borders across tabs once the borders have already been rendered. However, the code put above by Dana Cartwright works fine. You just have to put a ClearInvalid before MarkInvalid as pointed out by lost_bits1110: Validation.ClearInvalid((BindingExpressionBase)error.BindingInError); Validation.MarkInvalid((BindingExpressionBase)error.BindingInError, error);
{ "language": "en", "url": "https://stackoverflow.com/questions/7601055", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How do you add HTML into an email in Blackberry? How do you add HTML into an email in Blackberry? I've tried multipart emails, but that does not seem to work. I am asking how to send an HTML formatted email from an application running on a Blackberry, if I am wording too vaguely, please let me know how to rephrase my question A: All HTML emails work the same way - the HTML is in the email body and any images must have a fully-qualified url (http://...). CSS support is limited and must be defined inline statements (style="") on each element (no stylesheets). Background images are not supported. Tables must be used for layouts (awful but true). A: You are talking about the HTML mailers, which are tricky and depend on the client Machine, where they will be eventually seen. Your HTML should be fully table layout based, Styles need to be inline. Below is an HTML mailer that is like almost perfect to display correctly on any device, whether it is MAC or PC or iPad or Blackberry. http://www.dreamincode.net/iem/display.php?M=2016&C=f945ef50b90408df6b2eb3054df75e79&S=63&L=1&N=25 If you view the source of this page, you would come to know how the mailers need to be build out. To send the mailers as a mass mailing list you need an Email Marketing Software's.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601057", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android turning clicks into touches I have an on click listener: whiteKeyPressedArray[i].setOnClickListener(new View.OnClickListener() { public void onClick(View v) { }} I see that this allows touches: public boolean onTouch(View v, MotionEvent event) { //Switch case for type of touch } But how can I detect touch rather than click on my whiteKeyPressedArray[i]? Thanks! A: OnTouch will fire many many times :), actually onTouch will be trigered over and over again as long as you keep your finger to that element (as long as you touch that element). Where onClick will be fire just ones but ONLY if you return false from your onTouch handler. A: I don't know what the whiteKeyPressedArray[i] is, but have you tried: whiteKeyPressedArray[i].setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { return true; // or false if you want the event to pass on } }); Maybe this is what you are looking for?
{ "language": "en", "url": "https://stackoverflow.com/questions/7601061", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: AJAX calls fail in Opera and IE8 For some reason, AJAX requests seem to be failing in both Opera 11.51 and IE8 but work in Firefox and Chrome. I am not doing anything fancy other than the standard post request call: $.post('/dashboard/valid_email/', { email:email }, function(data) { I've added an alert before and after the AJAX call and I only get one alert which means the callback function isn't called. I am using jquery.1.6.2 hosted on Google. Any ideas? A: Add an error handler to see what error is being thrown. If you are returning something other than text/html, you need to set the dataType parameter to the proper dataType. Parse error means that there is something wrong with the data you are returning; if you are returning html, then the html is not valid, and if you are returning json, the json is not well-formed. $.post(url,data,callback,datatype).fail(function(x,y,z){ alert(x + "\n" + y + "\n" + z); }) A: I finally found out what the problem was. I was making use of mouseflow and it was causing problems for some reason on those two browsers! I just removed it and won't be using mouseflow again. I've let the developers know - maybe they can apply a fix. A: One error I see: You need to change email to 'email': $.post('/dashboard/valid_email/', { 'email' : email }, function(data) { It's not likely your whole problem, but it needs correction.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601068", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Accessing custom model data from another widget when an item in view is clicked I have a QListView that sets a custom QAbstractListModel as the model. The model loads data from a database and puts it all in a QList<QHash<QString, QString> > dataList data structure. Each QHash<QString, QString> data contains stuff like data["id"] and data["name"]. The data["name"] value is passed to the QListView via the model's data() method. Now what I want to do is access the QHash<QString, QString> belonging to the clicked item from another widget when an item is clicked in the QListView. So something like this... connect(view, SIGNAL(clicked(...)), someOtherWidget, SLOT(foo(...)) And in foo() we could do for example... void someOtherWidget::foo(const QHash<QString, QString>& customData) { QMessageBox::information(this, "User ID", customData["id"]; } And it would display the item's id in the message box. A: You can use special role in your data() function. data() will then return the QHash QVariant yourModel::data( QModelIndex index, int role ) { .... if( role == myCustomRole ) { return QVariant::fromValue( myData[ index.row ] ) } .... } Then in your foo function QHashMap<QString, QString> & model = view->model()->data( view->selectedIndex(), myCustomRole ) .value< QHashMap<QString, QString> >(); A: A QListView class has a handy clicked() signal, that passes QDataIndex for an item that was clicked. Just define a clicked slot and a custom signal for your model: signals: void elementSelected (QStringHash _element); // Also, there's a string hash // class, so save the <> public slots: void onClicked (const QModelIndex &_index); and create a respective slot for your widget: public slots: void onElementSelected (QStringHash _element); In onClicked, emit the elementSelected() signal void YourModel::onClicked (const QModelIndex &_index) { elementSelected (dataList (_index.row()) } Finally, just connect all your signals: clicked() from list view to your model and elementSelected() from your model to your custom widget. If you really need the view to emit elementSelected() signal, and not the model, you'll have to define a class derived from QListView with a similar signal and connect elementSelected() signal from the model to elementSelected() signal from this new class. It's perfectly okay to connect signals to each other.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601069", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: opening a jquery popup form in rails to display comments and create a comment I'm have the standard comments controller attached to my project through a has_many association. I have a set of rows that show the latest comments. When the user clicks on the comment that is displayed (let's say they click on title), then i want 1)a popup to open that shows a) a comment submit form b) underneath the comment form, a list of all comments associated with the project. i'm having a hard time with getting the popup to work and then populating the popup with 1 and 2 from above. when i submit hte form, i want it to refresh the popup with the same setup (new comment form and list of existing comments below. i think i can do this with jquery and rails, but not sure how. i'm using jquery-rails. thanks for the help! A: It sounds like you're going to want to use a little AJAX in your Rails. Rails' unobtrusive JavaScript and AJAX capability allows you to load remote views into pop-ups without reloading the page, and I think what you probably want to do here is load a remote view containing your comment edit/display combination layout into your pop-up. Then have AJAX update the main page once the dialog is closed. I would start with this short tutorial on using unobtrusive JavaScript with AJAX with Rails 3, then check out Facebox, which I learned about from this post that asks a question related to yours. Best of luck! A: As a start you could take at look at the JQuery dialog demo - put a form inside the dialog and submit it with ajax (remote => true) and close the dialog if successful. Evan's answer will give you a prettier and ultimately better solution (as will many other lightbox-like gems) but using a jquery dialog is probably the simplest way to start A: I went with Facebox and both answers were good so thank you. However i have the following problem: Any ideas? with Facebox, i'm getting raw text when i use it for the ('#facebox .content') selector. It works fine for ('#facebox') or ('#facebox .popup'). Have you guys run into this? By raw output, i mean the following: $('#facebox .content').html(" \n Hello from box div\n<\/div> "); that's what shows up in the box. and only for the .content selector! in application.js i have: $('a[rel*=facebox]').facebox(function($) { $.getScript(this.href); }); in my controller: respond_to do |format| format.html # show.html.erb format.xml { render :xml => @project } format.js {render :layout => false} end in my show.js.erb: $('#facebox .content').html("<%= escape_javascript(render("spaces"))%>");
{ "language": "en", "url": "https://stackoverflow.com/questions/7601070", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there a way to group methods/properties in the outline view of Aptana IDE I've looked everywhere for a feature like this. I use the Aptana IDE (which is based on Eclipse) for my php development, and I use the outline feature a lot. I enjoy xcode's 'pragma mark' feature, which lets you group sections of your source code together in the outline view for quick reference. (Described here: http://cocoasamurai.blogspot.com/2006/09/tip-pragma-mark-organizing-your-source.html) Is there anything like this for Aptana/Eclipse? A: [EDIT: I wrote this blog post which explains further: https://peacocksoftware.com/blog/create-pragma-separator-eclipse-xcode ] The closest I have found is to do one of these two things: Create a dummy constant, or create a dummy function. Both will create entries in the outline. See screenshot. Personally, I think I like the constant better, because its icon in the outline makes it clear it isn't really a function.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601072", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: java return from private method to public I have a public method and a private method. they are both supposed to return int values. The private method is the one that does all the work and the public is the one that is called from the main program. How can I return the results returned from the private method by the public method? its like this public int longer() { longer(a.length); } private int longer(int n) { int index //find largest index recursively //make recursive call longer(n-1) return index; } I want to pass it up to the public method and then return it from there. Would I just return it from the public method by saying return longer.index; or something along those lines? i guess i should clarify. n isnt index. idnex is being calculated based on whats being passed into the method. the public and the private is because its going to be a recursive method. i'll edit what i posted above to make itm ore accurate of what im trying to do. passing in an array and recursively working on it. A: public int longer() { return longerInternal(a.length); } private int longerInternal(int n) { int index //find largest index recursively //make recursive call longer(n-1) return index; } From your public method, you can call down into the private method. I renamed the private method so that there was not a naming collision for your methods. A simple implementation should look something like this: public class MyClass { private int[] a; public MyClass(int[] _a) { a = _a; } public int longer() { return longerInternal(a.length); } private int longerInternal(int n) { int index; //do recursive call return index; } } And it can be called like this: MyClass myClass = new MyClass(new int[]{1,2,3,4,5,10}); int result = myClass.longer(); A: First, you probably need better function names. You'd call your public function getLonger(int n) and then pass it to your private longer(int n) function. When this function is done, it will return to getLonger(int n) and then back to the caller. A: You mentioned in an answer to a comment that the "caller does not need to have access to all internal workings of a class." To me that suggests that you want to use an interface. Create an interface that describes the class that will contain that secret algorithm: package com.stevej; public interface Longer { public int longer(); } Implement that interface using your secret algorithm: package com.stevej; public class LongerImpl implements Longer { private int longer(int n){ return 0; // whatever } @Override public int longer() { return longer(5); // whatever } } Now the caller only creates objects using the interface definition, guaranteeing that there are no exposed methods that he can access by accident. That implementation is hooked to that interface-defined object: package com.stevej; public class LongerProcessor { Longer longerImpl = new LongerImpl(); public LongerProcessor() { super(); } public int longer() { return longerImpl.longer(); } } Now you can rewrite the implementation of Longer as often as you like. As long as the interface definition never changes, the caller (LongerProcessor) will never have a problem. Heck, you could have two or more different implementations (LongerImplRecursive, LongerImplBruteForce, and so on), each implementing Longer, and all in use in different places in the same program: package com.stevej; public class LongerProcessor { Longer longerImpl; public LongerProcessor(boolean useRecursive) { super(); if (useRecursive){ longerImpl = new LongerImplRecursive(); }else{ longerImpl = new LongerImplBruteForce(); } } public int longer() { return longerImpl.longer(); } } How cool is that? Since you tagged this question as "homework", I'm wondering if the problem is supposed to engage you to think about separating the contract (interface) from the implementation (implementing class).
{ "language": "en", "url": "https://stackoverflow.com/questions/7601076", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Ordering of eigenvectors when calculating eigenvectors using LAPACK's ssteqr I am using LAPACK's ssteqr function to calculate eigenvalues/eigenvectors. The documentation for ssteqr says that the eigenvalues are sorted "in ascending order". Is it reasonable to assume that the list of eigenvectors is also sorted in ascending order? A: Yes, it is reasonable to assume that the eigenvectors are ordered so that the i-th eigenvector corresponds to the i-th eigenvalue. Nevertheless, if I were you, I would check for each eigenvalue the result of the multiplication of the eigenvector by the matrix. This way you are sure that you interpret the output right, and you see explicitly the accuracy of the calculations. A: An old question, this, but I struggled with this recently, so am adding this for current and future readers. The basic answer is that, yes, the eigenvectors are sorted such that the ith eigenvector corresponds to the ith eigenvalue. However, note that the eigenvectors thus obtained may not be the actual eigenvectors you want. This is so because of the following. Since the ?steqr functions work only on tridiagonal matrices, one typically uses LAPACK's ?sytrd functions to first transform one's original symmetric matrix, call it M, to a tridiagonal form, call it T, such that M = QTQT where Q is an orthogonal matrix (and QT denotes its transpose). One then applies the ?steqr function on this tridiagonal matrix T to find its eigenvalues and eigenvectors. Now the eigenvalues thus obtained (of T) are exactly the same as the eigenvalues of M, so if one only wants the eigenvalues one can stop here. But if one is interested in the eigenvectors, like the OP, then one needs to bear in mind that the eigenvectors of T and M are different. To find the eigenvectors of the original matrix M, one needs to left-multiply the obtained eigenvectors of T by Q. This is very easily done by using the LAPACK functions orgtr or ormtr. See here for a clear explanation: https://software.intel.com/en-us/mkl-developer-reference-fortran-sytrd.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601077", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: set new Image on ImageView I created an XML layout for my project with an ImageView in it. I add a default image for imageView. Now programatically I am getting that imageview and trying to change the image source using imgView.setImageBitmap(newbitmap);. The problem is that both images are showing - the default image displays behind programatically added one. I tried: * *imgView.setImageResource(0); *imgView.setImageDrawable(null); *imgView.setAlpha(0); *imgView.setImageBitmap(null); ...but the default image is still visible. A: If you are setting the background of the ImageView in the xml file, then it will remain until you clear the background. ImageView is odd in that it can display two images, background and source. Use the attribute android:src to set the source image and 'android:background' to set the background. All the methods you described will replace the source image but keep the background unchanged.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601078", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Loading indicator with dojo XHR requests I only recently started using dojo and I am doing numerous ajax calls using dojo xhrGet, xhrPost,..etc. Now I have an animated gif image which i want to use to indicate "loading" to the user. I am not too sure how this can be done. Can someone please advise me on this? here is my code, dojo.xhrGet({ url: registcarturl, handleAs: "json", preventCache: true, load: function(data, ioArgs) { //DO STUFF WITH data HERE }, error: function(error) { alert("sorry ! an error occurred while adding to the cart with ajax"); } }); How do i get my loading gif file into the interaction? Thank you. A: Have a look at dojox.widget.Standby: http://dojotoolkit.org/reference-guide/dojox/widget/Standby.html To give you an example, define the widget.Standby <div jsId="basicStandby1" dojoType="dojox.widget.Standby" target="yourDomTarget"> After calling dojo.xhrGet, show it: basicStandby1.show(); And when you receive your answer, hide it: basicStandby1.hide();
{ "language": "en", "url": "https://stackoverflow.com/questions/7601079", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there any way to skip the crop screen in the Sincerely Ship library? My application handles photo editing already, which includes cropping. Is there anyway to skip this screen in the Sincerely Ship library? A: Sure thing! Just pass the sincerely library an image which is already resized to the correct print size when calling the initWithImages: product: applicationKey: delegate:. Print images should be either 1800x1200 or 1200x1800 pixels.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601081", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to pass model from json to view? i have a button on my view when fire it execute GetReport() and it execute :public ActionResult GetReport(int licenseId) by json. now public ActionResult GetReport(int licenseId) fill my model and return it by json. everythings are correct but i do not know how link returned model (by json) to my view? function GetReport() { var id = $("select#LicensesDropdown").val(); if (id == null || id == '') return; var inputParams = "{licenseId : '" + id + "'}"; var abc; $.ajax({ url: "/Members/ClientMonitoring/GetReport", type: 'POST', dataType: 'json', data: inputParams, contentType: 'application/json; charset=utf-8', success: function (msg) { var d = Date.parseJSON(msg.StartDate);<-----------------returned filled model------------- here i don't know how to fill my grid now } }); } My Model--------------------------------------------------------------------------------------------------------------------- public class ReportBaseModel { public List<person> MonitoringLicenseModelsList { get; set; } } my action result---------------------------------------------------------------------------------------------------------- [HttpPost] public ActionResult GetReport(int licenseId) { // fill reportmodel it contains list of data and return it by jason return Json(reportmodel); } in my view -------------------------------------------------------------------------------------------------------------- @model Karanoos.Areas.Members.Models.CompositModels.ReportBaseModel <input id="ButtonGetReport" type="button" value="Report" class="btnnormal" onclick="GetReport();" /> @{ var grid = new WebGrid(source: Model.LicensesClientsPacketModelsList, defaultSort: "LicenseUI", rowsPerPage: 3); } <div id="grid"> @grid.GetHtml( tableStyle: "grid", headerStyle: "head", alternatingRowStyle: "alt", columns: grid.Columns( grid.Column("LicenseUI"), grid.Column("AccountName"), grid.Column("AppName") ) ) A: When you execute the Ajax call, and get JSON you are on the client side, so you can forgot any grids and server-side controls. Only thing you can do is to take the JSON array and fill it into the plain empty HTML table in the page that is generated in the browser. There are lot of JQuery plugins that can help you to load json into the HTML elements one of them is loadJSON plugin (see details on the http://code.google.com/p/jquery-load-json/) that enables you to load json array into the blank HTML table. As an example see on the http://jquery-load-json.googlecode.com/svn/trunk/list.html how JSON array is taken from the server-side and loaded into the UL/LI HTML structure. you can do similar thing using the blank table. Jovan
{ "language": "en", "url": "https://stackoverflow.com/questions/7601090", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Possible to link .dll with .lib? Here's my dilemma: I'm attempting to create a .dll version of my project. This project uses the V8 and CURL libraries which are currently built as debug .libs. I'd like to package all of them up in a single DLL that can be shared (I understand I need to alter my code with __declspec(dllexport) but that's a separate issue) to others. Do I need to compile the V8 and CURL libraries as DLLs then somehow wrap them up in my own DLL? A: If you have a .lib with no .dll for the CURL libraries, then they are most certainly static libraries. When you link them to your DLL, the code from these libraries is linked into your DLL. A: I've generally had to include the source for the dependencies (in your case both V8 and CURL) in my project and build that way to get them completely incorporated without extra headaches. If you have libs and you link to those you SHOULD get them merged though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601093", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to move a specific trunk revision and its subsequent edits to a branch? We realized that we would like some work in the trunk to have actually have been in a branch. We would like several commits to go into a branch, and preferably, we would preserve the history of the commits. So: r0 --- r1 --- r2 --- r3 would become branch --- r2 --- r3 / r0 --- r1 ----- * Where "*" is where we will start making new commits to the trunk. I'm nervous that I'll destroy our repository if I do something incorrectly. Please advise, thank you! A: Basically the current status of trunk is good for the branch, so you should just do a server-side svn copy from trunk to the desired branches subdirectory: svn copy svn://path/to/trunk svn://path/to/branches/foo -m "Creating branch Foo" Then you would need to revert trunk to r1, which is easily achieved by either applying a reverse patch from r1 to r3 or by actually using svn merge: svn merge r3:r1 svn://path/to/trunk EDIT: Actually, there's a better solution here: How do I properly branch post-commit and revert the trunk in svn?
{ "language": "en", "url": "https://stackoverflow.com/questions/7601097", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: dependency resolution pip virtualenv I have 2 local libraries which are dependent on different version of suds. Example - * *Module-A-1.0's setup.py has a requirement of suds ==0.3.9. *Module-B-1.0's setup.py has a requirement of suds ==0.4.0. Both these modules are required by Module-C, which has the following its setup.py * *django *Module-A-1.0 *Module-B-1.0 Module-C will be installed in a virtualenv using pip. My question is which version of suds will be installed and can I have both versions installed in the same virtual env? What I noticed was, whichever module I specified first in the setup.py for Module-C, that version of suds gets installed. So in this case suds 0.3.9. If I switched the modules to * *django *Module-B-1.0 *Module-A-1.0 The version of suds that gets installed in suds-0.4.0. A: Using pip + virtualenv you can't have two versions of a library installed at the same time. And, unfortunately, I don't know of any good ways of handling this situation. Sorry.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601098", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there an type of array in c that allows strings to be used as indices? I am looking for something like: a["hello"] points to a list, a["h"] to another. Basically, I'm looking for an associative array implementation. A: No, not in C. You may want to look into hash table libraries to get what you want. A: A bit of trivia: although strings cannot typically be used as indices, in certain narrow cases, they are valid. Consider this line of code: printf("%c", 1["hello"]); The output is "e". This exploits the property that a[b] == *(a+b) == *(b+a) == b[a]. As a result, 1["hello"] == "hello"[1], which clearly results in the second letter, "e" A: You cannot do this exactly as written ( like you can do in python or perl ) But, If you want to use a string as an index. It sounds very much like you want a perl hash or dictionary. I have a quite lightweight dictionary/ahash implementation for C that lets you use anything as a key (index) including strings. xrhash - guthub Here's a brief example of using a string as an indexer: XRHash * dict = xr_init_hash( xr_hash__strhash, xr_hash__strcmp ); /* add things to the hash */ if ( xr_hash_contains( dict, "mary" ) != XRHASH_EXISTS_TRUE ) printf("does not contain mary\n"); xr_hash_add( dict, "fred", strdup("my name is fred") ); xr_hash_add( dict, "mary", strdup("my name is mary") ); xr_hash_add( dict, "sally", strdup("my name is sally") ); xr_hash_add( dict, "bob", strdup("my name is bob") ); /* test if things exist */ if ( xr_hash_contains( dict, "mary" ) == XRHASH_EXISTS_TRUE ) printf("does contain mary\n"); /* iterate the hash */ xrhash_fast_iterator * iter = xr_init_fasthashiterator( dict ); char * hashkey = NULL; do { hashkey = (char*) xr_hash_fastiteratekey( iter ); if ( hashkey != NULL ){ /* get values */ char * data; xr_hash_get( dict, (void*)hashkey, (void**)&data ); printf("key = %s, value = %s\n", hashkey, data ); } else { break; } } while ( 1 ); The full source for the above is here EDIT: There also turns out to be Hash Tables that do the same and more from GLib. My lib is quite fast though :) A: Not directly, but there are a number of hash table implementations in C. Here's one example. I haven't tried it, but it was near the top of a Google search. (Presumably it doesn't let you use the a["hello"] syntax.) (And if using C++ rather than C is an option, something like a map might be a good solution.) A: All the answers so far have focused purely on syntax, not on solving your problem. If you really need an "associative array", you need to find or write some library routines to provide such a data structure. C does not have any high-level data structures as builtin types or part of the standard library. glib surely provides something like what you're looking for. Note however: (!!) If you find yourself needing associative arrays outside of specialized applications where the key comes from the outside world (as opposed to within your program), I think you should really evaluate either (1) whether there's a better way to do what you're trying to achieve in C, or (2) whether you really want to be programming in C. Associative arrays are not a C idiom, and by using them when another data type would do, you're throwing out many of the advantages of C and just keeping all of the pain of C. A: It's called an std::map and you can use std::string as a key. Note that this is only an option in C++, not C. However, I'm thinking it's probably what you were looking for, as many times novices will tag C questions as C++ and the other way around. A: No, array are just pointers and the index operator ( [] ) is just a shorthand for : a[i] == *(a + i * sizeof(*a))
{ "language": "en", "url": "https://stackoverflow.com/questions/7601101", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Add selected values to a div w/ jQuery I have a table with values. <table id="myTable"> <tr> <th title="Text to copy to list">header 1</th> <th title="Text to copy to list">header 2</th> <th title="Text to copy to list">header 3</th> </tr> <tr> <td>Value 1</td> <td>Value 2</td> <td>Value 3</td> </tr> </table> <div id="selectedVlues"></div> I need to be able to click on a with value and add that value to the #selectedVlues div, while adding a class="added" to that column. I need to be able to select any number of th and list them one below another. <div id="selectedVlues"> header 2<br> header 3<br> </div> If I click on a selected item either in the table header or the list, needs to remove that item from the list and remove class="added" from the column. So far I have only this: $(".myTable th").click(function() { var headerVal = $(this).text(); $("#selectedVlues").text(catVal+"<br>"); }); Not really sure how to add the rest... A: http://jsfiddle.net/N6h8G/6/ $("#myTable th").click(function() { var column_header = $(this); var column_rows = $('#myTable tr td:nth-child(' + (column_header.index() + 1) + ')'); if (column_header.hasClass('added')) { $('#selectedValues #' + column_header.index()).remove(); column_header.removeClass('added'); } else { $('#selectedValues').append('<span id="' + column_header.index() + '">' + column_header.text() + '</span>'); column_header.addClass('added'); } column_rows.each(function(i, row) { if ($(row).hasClass('added')) { $(row).removeClass('added'); } else { $(row).addClass('added'); } }); }); EDIT: Sorry, updated response. EDIT 2: Updated based on comments and fixed a syntax error. A: Something like this example jsfiddle var $myTable = $('#myTable'), $headers = $('#myTable th'), $cells = $('#myTable td'), $selectedValues = $('#selectedValues'); $headers.click(function() { // clicked header var $this = $(this); if ($this.hasClass('added')) { // remove added class from column $this.removeClass('added'); $cells.each(function() { var $cell = $(this); if ($cell.index() === $this.index()) { $cell.removeClass('added') } }); // remove from selected values $selectedValues.find(':contains("' + $this.text() + '")').remove(); } else { // add class $this.addClass('added'); $cells.each(function() { var $cell = $(this); if ($cell.index() === $this.index()) { $cell.addClass('added') } }); $selectedValues.append('<li title="remove">' + $this.text() + '</li>'); } }); $selectedValues.delegate('li', 'click', function() { // clicked list item var $this = $(this); $header = $headers.filter(':contains("' + $this.text() + '")'); // remove 'added' class $header.removeClass('added'); $cells.each(function() { var $cell = $(this); if ($cell.index() === $header.index()) { $cell.removeClass('added') } }); $this.remove(); }); A: Try with this Jquery $("#myTable th").click(function() { var table_value = $(this).text(); $("#selectedVlues").append(table_value+'<br />').addClass('added'); }); A: $(function(){ $("#myTable th").click(function() { debugger; var headerVal = $(this).text(); $("#selectedVlues").html(headerVal+"<br>"); indexVal = $(this).index(); $("#myTable").find("td").eq(indexVal).addClass("added"); }); }); check this out
{ "language": "en", "url": "https://stackoverflow.com/questions/7601102", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Drupal autocreate custom content type on registration I have created a new content type for storing additional user data (outside of the standard profile) page. This content type is only viewable by the user and the admin. What I would like is that when a user registers this custom content type is automatically created for them so they can then populate it. How can this be achieved? A: Rules module - module allows site administrators to define conditionally executed actions based on occurring events. So there's condition = user register, action - create content.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601105", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python adding config files to path I have directory structure like following: analytics / / \ \ conf script src other / \ / \ / \ <setup> <source> < setup >: setup.yaml sql.yaml < source >: src/ folder A/ s1.py s2.py ... folder B/ m1.py m2.py ... How can I inclue the setup files in of this structure to the source files in structure without hardcoding the paths I tried sys.path.append('< path >') but when I try to open the file I see error >>> import sys >>> sys.path.append('/Users/user/Documents/work/dw/analytics/conf') >>> f = open('setup.yaml', 'r') Traceback (most recent call last): File "<stdin>", line 1, in <module> IOError: [Errno 2] No such file or directory: 'setup.yaml' >>> f = open('setup.yaml', 'r') A: open() (and all the other file access functions) don't care about sys.path. It's only used when importing modules. Create your own variable that contains the path that contains your files, and use it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601108", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Combining Apps Into Universal Easy? iPhone/iPad I am about to begin developing an app and have never worked with universal binary. Is it possible to create them both individually and then merge them is needed later? Or is that out of the question? It is pretty important to decide from step one whether I need to go universal or not? Also whats your expericne been with universal apps? Has it been an easy experience, or troubling? Thanks. A: It's very easy and works out of the box. The template has two app delegates and two MainWindow xibs, one per platform (iPhone/iPad). You can also factor common code into a shared app delegate. When you start adding code, usually the Model part is the same code, the controllers are part the same and part different depending on how the GUI behaviour differs, and the View part is the only one which is really different - You would usually need two XIBs per view controller, one per platform.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601109", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Oracle to_char bug I don't know if it's a bug or what, but when I try to format the Day of the week in a certain way with the to_char function in Oracle, SQL Plus give me this error : ORA-01821: date format not recognized Here's the line that cause a problem SELECT TO_CHAR(sysdate,'dsp') from dual; So d is of 'Day of the week' and sp is for spell. This line should print five because we are thursday. It's weird because this next line worked SELECT TO_CHAR(sysdate,'ddsp') from dual; dd is for 'Day of the month' so sql plus printed twenty-nine without any problem!! Can someone tell me why this line is not working? Thanks.. A: If you must make this work, here's an ugly workaround: SELECT to_char(to_date(to_char(SYSDATE,'d'),'j'),'jsp') FROM dual; Looks like a bug to me...
{ "language": "en", "url": "https://stackoverflow.com/questions/7601114", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Getting absolute file/dir path in python From the code below both returns me the same output. When should I use one over the other? import os from os.path import abspath, dirname print abspath(dirname(__file__)) print os.getcwd() PS: I wanted to use this for dynamically changing the path for logs, static files and templates in my django project to run it in different environments. A: Use the first when you want to know the location of the file being executed. Use the second when you want to know the process's current working directory. A: os.getcwd can be used at places where you want to move from your current directory to perform some actions on other directory, for this you save your current working directory or to know the location of the file being executed. abspath is used to get absolute path of file, gives you location information of file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601116", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ExtJS 4 class loading fails I have code similar to this: Ext.define('GG.view.Workbench', { extend: 'Ext.container.Viewport', layout: 'fit', items: [ { xtype: 'container', layout: 'border', items: [ { region: 'center', items: [ Ext.create('GG.view.Foo') ] }, { region: 'south', items: [ Ext.create('GG.view.Bar') ] } ] } ], initComponent: function() { this.callParent(arguments); } }); What happens is that the code does not work when the two Ext.create calls are placed there. This is what I get on Chrome: Uncaught TypeError: object is not a function (anonymous function) Ext.ClassManager.instantiateext-debug.js:6428 (anonymous function)ext-debug.js:2414 (anonymous function) How am I supposed to use this Ext.create? A: You are overnesting and you have to do that within a method that will be executed each time the class is created Ext.define('GG.view.Workbench', { extend: 'Ext.container.Viewport', layout: 'border', initComponent: function() { var me = this; Ext.apply(me, { items : me.buildItems() }); me.callParent(arguments); }, buildItems: function() { return [ { region: 'center', items: [ Ext.create('GG.view.Foo') ] }, { region: 'south', items: [ Ext.create('GG.view.Bar') ] } ]; } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7601123", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error calling getResources().openRawResource() I have to read a file called hello.txt using the following code on java/eclipse/android: import java.io.InputStream; public class Tokenirzer { public String ReadPath () { InputStream inputStream = getResources().openRawResource(R.raw.hello); } } However I get the following error: The method getResources() is undefined for the type Tokenirzer What am I doing wrong? A: getResources() is part of Context. You can use it like that in an Activity because it inherits from Context. You need to pass in your activity's Context to use getResources. A: Your class Tokenirzr does not contain the method getResources(). A: I see this question is old, but I faced similar situation and as per my experience there are 2 solutions. Either the class has to extend Activity() or a reference should be passed from MainActivity()
{ "language": "en", "url": "https://stackoverflow.com/questions/7601129", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Facebook error on tab application with fbgraph I am trying to ask for extended permissions on a Facebook tab application with fbgraph gem on ROR3. The error message given is: { "error": { "message": "Invalid redirect_uri: Given URL is not allowed by the Application configuration.", "type": "OAuthException" } } I was trying with localhost. I thought that the problem was with localhost, so I uploaded my site to a server and then I configured the Facebook app. However, this threw this error message. I configured on my application: Basic info, Page tab info and in advanced tab I wrote "deauthorize callback url". The generated URL is: https://graph.facebook.com/oauth/authorize?client_id=XXXXXXXXXXXXXXXXX&redirect_uri=http%3A%2F%2Ffbpromo.testenvironment.com.ar%2Fauthorize&response_type=code&scope=email+read_stream+offline_access+manage_pages+user_about_me What could be the error? A: Sorry, the problem was my configuration. However, Facebook redirects out of tab application. How could I configure my application if I want to request permissions without exiting out of my tab application? My page is allocated for example in http://example.com/facebook_callback. How could it be redirected to http://www.facebook_com/app_id/callback_url (i.e., redirect 'inside' tab application)?
{ "language": "en", "url": "https://stackoverflow.com/questions/7601132", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: spooling a clob value with multiple lines using sqlplus to a single cell of a CSV I tried to spool a CLOB to a CSV file using code that looks like below: set pagesize 0 set heading off set long 30000 set longchunksize 30000 SPOOL test.csv select text from user_views; But the above code returns the CLOB as multiple rows because of newline/carriage returns in the CLOB in the resulting CSV when viewed from a spreadsheet program(OOcalc). Is there anyway to keep the whole CLOB intact in a single cell? A: You'll probably want to look at the DBMS_LOB package for ideas on how to get the data out of there cleanly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601133", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C#, Winform - creating PDF I'm still kinda new on the programming thing, but i would like to create a program wich could create PDF's with some information in them. Could anybody recommend a neat way of doing so, i kinda need to create a regular A4 page with a table on it.. and some other informations. is it possible to create it from within Visual studio 2010 - or do i need some kind of add-in like that? A: As @Jon Skeet said, you can use iTextSharp (which is a C# port of the Java iText). First, download iTextSharp (currently 5.1.2), extract itextsharp.dll to some location and add a reference to it in Visual Studio. Then use the following code which is a full-working WinForms app that creates a very basic table in an A4 document. See the comments in the code for more of an explanation. using System; using System.Text; using System.Windows.Forms; using System.IO; using iTextSharp.text; using iTextSharp.text.pdf; namespace Full_Profile1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { //This is the absolute path to the PDF that we will create string outputFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Sample.pdf"); //Create a standard .Net FileStream for the file, setting various flags using (FileStream fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.None)) { //Create a new PDF document setting the size to A4 using (Document doc = new Document(PageSize.A4)) { //Bind the PDF document to the FileStream using an iTextSharp PdfWriter using (PdfWriter w = PdfWriter.GetInstance(doc, fs)) { //Open the document for writing doc.Open(); //Create a table with two columns PdfPTable t = new PdfPTable(2); //Borders are drawn by the individual cells, not the table itself. //Tell the default cell that we do not want a border drawn t.DefaultCell.Border = 0; //Add four cells. Cells are added starting at the top left of the table working left to right first, then down t.AddCell("R1C1"); t.AddCell("R1C2"); t.AddCell("R2C1"); t.AddCell("R2C2"); //Add the table to our document doc.Add(t); //Close our document doc.Close(); } } } this.Close(); } } } A: You probably want to use a library such as iText, which will let you build up a PDF document programmatically. It's not clear what you mean by "creating it from within Visual Studio 2010" - if you're expecting a visual designer, I think you'll be disappointed; I don't know of anything which would allow you to do that easily. However, it doesn't sound like you have particularly tricky requirements, so just writing the code to do it shouldn't be too hard. A: There are several libraries available for that purpose. Here are a few: * *iTextSharp *PDFSharp *SharpPDF A: I have used iTextSharp once to merge and split pdf, but has lost those files. But iTextSharp is good. And regarding your need to create tables and all, I think you will have to write regular code and then you will have to convert them into bytes and then create a pdf file out of it. As I remember, iTextSharp work that way. Hope it helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601145", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: what happens to pointers to dynamically allocated memory after a UNIX fork? Someone please clarify what happens with pointers after a fork(). As I understand it, pointers to anything on the stack or statically allocated are relative to the stack/data segment registers, so copying them exactly during a fork is OK. However, what happens if I malloc() something before forking? for example: void* p = malloc(64); // put something in *p; fork(); // what happens to p and the memory i allocated here? possibilities I am thinking of: * **p is copied to some other part of the heap, p is updated to reflect the newly copied location. *p still points to the original. if any child runs free(p); the parent may be unable to access it. *p still points to the original data, but the child process does not have rights to access/manage the memory. which of these, if any, is correct? A: The value is also copied, as fork copies code, globals, heap and stack. Source : http://web.eecs.utk.edu/~huangj/cs360/360/notes/Fork/lecture.html A: When forking, child process becomes a copy of its parent. That includes any dynamically allocated memory. So the memory will be copied. Pointer address will stay the same (copy doesn't change data, remember?), which is achieved by virtual addressing. Don't forget to call free in both parent and child processes. A: Malloced memory comes from the heap, which is just a fancy word for a set of memory pages. Since fork() copies all of a process's memory pages regardless of any fancy naming they've been given in textbooks, pointers returned by fork() work just fine in the child :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/7601146", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Drupal 7 - New template for other pages I've tried using the page-node-2.tpl.php but it hasn't worked... Is there something I'm missing? I'm new to Drupal, but I think it might have something to do with not having a template.php in my themes directory? A: See http://drupal.org/node/1089656 for template file name conventions. Note that there are two dashes (--) in between page and node and 2. Also remember to clear your cache so that Drupal recognizes the new files and/or paths.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601152", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ruby - "extend" statement in a class If (for whatever reason) I extend Stuff in class Dog how can I access CONST1 through the Dog class? I know I can get CONST1 by saying Stuff::CONST1, but how through dog can I get it. I also know that this code would work if I include Stuff in class Dog. module Stuff CONST1 = "Roll Over" end class Dog extend Stuff end Dog::CONST1 #NameError: uninitialized constant Dog::CONST1 A: You're probably thinking of include, not extend. extend adds the instance methods: Adds to obj the instance methods from each module given as a parameter. but include: Invokes Module.append_features on each parameter in reverse order. and append_features: Ruby‘s default implementation is to add the constants, methods, and module variables of this module to mod if this module has not already been added to mod or one of its ancestors. So if you do this: module M PANCAKES = 11 end class C include M end Then you can get PANCAKES from C: puts C::PANCAKES # gives you 11 A: From the documentation of extend: Adds to obj the instance methods from each module given as a parameter. It seems there is no reason to expect extend to add the constants. A: Use: module Stuff CONST1 = "Roll Over" end class Dog include Stuff end Dog::CONST1 # works See What is the difference between include and extend in Ruby?
{ "language": "en", "url": "https://stackoverflow.com/questions/7601153", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Rails on iOS - action "show" could not be found on :method => :delete I have a Rails application that has a mobile view for iOS users. All links seem to be working, except those that have posts tied to the rails :delete method. An example link_to: <%= link_to list_task_path(t.list, t), :method => :delete do %> <%= image_tag "white_minus.png", :id => "complete_task", :class => "#{important_class?(t)} icon", :title => "Complete Task", :alt => "Complete Task" %> <% end %> When this link is pressed on mobile safari, the following error is returned: The action 'show' could not be found... I tried turning the link into an ajax link to see if that correct the problem, no cigar: $(function() { $("#complete_task a").click(function() { $.post(this.href, { _method: 'delete' }, null, "script"); return false; }); }); I think the issue is related to javascript that I'm using, though admittedly don't understand to the fullest, to stop links from opening up in mobile safari if the website has been added to the users homescreen. It's copy pasta on my part from another question on here: // open links in app and not safari var iWebkit;if(!iWebkit){iWebkit=window.onload=function(){function fullscreen(){var a=document.getElementsByTagName("a");for(var i=0;i<a.length;i++){if(a[i].className.match("noeffect")){}else{a[i].onclick=function(){window.location=this.getAttribute("href");return false}}}}function hideURLbar(){window.scrollTo(0,0.9)}iWebkit.init=function(){fullscreen();hideURLbar()};iWebkit.init()}} Removing this javascript allows me to execute deletes, but all other links are opened externally like they're a _blank target. I was wondering if anyone else had been in a similar situation and were able to correct destroy links on Rails 3 running in mobile safari. A: If I read this script correctly than you should add the class noeffectto the link. This prevents the default behaviour of the script, which is to set window.location to the anchor's href
{ "language": "en", "url": "https://stackoverflow.com/questions/7601154", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android browser php cookies I am unable to manipulate cookies via php on the vanilla android browser. (ver 2.3.4) The browser options are set to accept cookies, and some websites do allow me to log in normally (though not all). I have made a really simple test script to try and see if cookies are set at all: setcookie("TestCookie", "cookievalue", time()+3600); and on the next page echo $_COOKIE["TestCookie"]; On my desktop browser or on firefox mobile this displays the word "cookievalue" but on the android browser it's blank. This issue also won't let me store anything in a session cookie since that won't persist. Am I missing something? A: After examining things closely and trying all options I've discovered that this is indeed a problem with how the stock browser is handling cookies when android is configured to use a port and proxy in the APN settings. I suspect that it has problems associating cookies with their domains under certain conditions when these settings are on. (cookies were being set, but lost as soon as a page redirect or link was clicked). My provider had these in there by default. Removing them so that the fields are blank has solved this problem. Anyone else having this issue, I suggest going into your wireless networks options, finding the access point names setting, selecting the active APN and clearing the port and proxy fields if they are filled in. (write them down first in case this doesn't work for you) After you do this you'll have to re-register on your network by searching for available networks and selecting it again. A: That code will not work. Cookie data set with setcookie does not become available until the next page request.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601160", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to grab last 12 12 months from cygwin "date" INCLUDING FEBRUARY I want to make directories for the last 12 months, starting whenever I run my script. I've got this code, which is %90 good: for i in {1..12}; do mkdir "$(date -d "$i months ago" +%Y-%m)-01" The problem is that instead of making a 2011-02-01 directory it tries to make 2 2011-03-01 directories. My guess is that because today is the 29th, it's going back a month at a time and interprets February 29th as March 1st. Any way to make sure I get a Feb directory too? A: Try this: echo "$(date -d "$(date +%Y-%m-15) -$i months" +%Y-%m)-01" This means that it tries going back from the 15th of each month instead of the current day.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601162", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to pass querystring values to swf? This is driving me nuts... Based on my research I should be able to pass QueryString parameters directly to a swf object like so: http://localhost:3000/SomeFlash/bin-debug/myFlash.swf?userId=827419 In the mxml oncreationcomplete method I have tried the following: // oncreationcomplete method var userIdTest1:String = FlexGlobals.topLevelApplication.parameters[0]; var userIdTest2:String = Application.application.parameters.userId; var userIdTest3:String = this.parameters.userId; // External Interface ExternalInterface.addCallback("OnGameLoad", ClientParams); // callback method protected function ClientParams(userId:String):void { this.userId = userId; } source http://help.adobe.com/en_US/flex/using/WS2db454920e96a9e51e63e3d11c0bf626ae-7feb.html I am using Flashbuilder 4.5 with Flex 4.5.1 compiler. I am using a mxml with an html wrapper, but I am trying to pass the parameters via url to the swf directly. A: ExternalInterface is not available if you're launching the swf directly. Likewise, I suspect that's the reason that the queryString is not available. Try hitting the hosting HTML page instead. (ie., http://localhost:3000/SomeFlash/bin-debug/myFlash.html?userId=827419) A: After lots of testing and some dumb luck I found that the following will work for getting querystring parameters. // In the oncreationcomplete method this.userId = this.parameters.userId;
{ "language": "en", "url": "https://stackoverflow.com/questions/7601164", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Trigger prettyPhoto after PHP Post Instead of going to another page after a successful INSERT, I'd like to trigger an instance of prettyPhoto to let the user know their email was successfully sent and to keep them from leaving the page, and for eye candy. Right now I'm just using: header("Location: http://website.com/thank_you.php"); I've tried to use: <script type="text/javascript" charset="utf-8"> $(document).ready(function(){ $.prettyPhoto.open('http://www.website.com/popup.htm?iframe=true&width=850&height=420'); }); </script> In thank_you.php after instantiating prettyPhoto, but it goes to the page first, of course. A: I'm not sure exactly how you want this to go but here are my 2 cents. First of all, you are mixing up php and javascript. PHP is executed between two pages, and generates page html. So you can't act on the browser after a post was done unless you work with AJAX. At that moment, AJAX will act as a communication between the server and the webpage and you won't change page per se. You will still query the browser and post something to it though. So your first steo is to post your stuff with lets say JQuery and expect some JSON to come back to you. That JSON will tell you what to do, error output or success output. And that part will $.prettyPhoto.open() the page you want. So you'll stay on the same page error or success, and will display something on success. Is that any help?
{ "language": "en", "url": "https://stackoverflow.com/questions/7601169", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jquery plugin not working - TypeError 'Undefined is not a function' in safari I am using a jquery treeview plugin to make a list in to hierarchy view. This works fine in firefox, but results in a error like 'TypeError: undefined is not a function' in safari and 'Uncaught TypeEror : Object [object object] has no method 'treeview' in chrome error console. Here is the code snippet <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link type="text/css" href="./methodeditor4.css" rel="stylesheet" /> <link type="text/css" href="../../css/cupertino/jquery-ui-1.8.16.custom.css" rel="Stylesheet" /> <script type="text/javascript" src="../../js/jquery-1.6.2.min.js"></script> <script type="text/javascript" src="../../js/jquery-ui-1.8.16.custom.min.js"></script> <script type="text/javascript" src="./treeview/jquery.treeview.js"></script> <link rel="stylesheet" href="./treeview/jquery.treeview.css" type="text/css" media="screen" /> <title>Method editor</title> <script> $(function() { getmethodgroups(); }); function getmethodgroups(){ $.ajax({ url: "listmethods.php", cache:false, success: function(data){ var methgroups = JSON.parse(data); for ( var i=0; i < methgroups.length; i++ ) { $(".list").append("<li class=\"mgclick filetree\" id=" + methgroups[i] + "><span class=folder>" + methgroups[i] + "</span><ul></ul>" ); $(".list").append("</li>"); }; $("#list").treeview({ collapsed: true }); } }); } </script> </head> <body > ( has all the elements ) </body> </html> The treeview plugin's script is loaded in the page and the path is correct. The same happens with some of other plugins like tabs. Firefox is working fine, the problem is with safari and chrome. Any clues? Thanks, Srini. A: onReady Change $(function() { //add this $("#list").treeview(); getmethodgroups(); }); Script Change# var branches = ""; for ( var i=0; i < methgroups.length; i++ ) { branches = branches + "<li class=\"mgclick filetree\" id=" + methgroups[i] + "><span class=folder>" + methgroups[i] + "</span><ul></ul></li>" }; $(branches).appendTo("#list"); $("#list").treeview({ add: branches }); html <body> <ul id="#list" class="filetree"> </ul> </body>
{ "language": "en", "url": "https://stackoverflow.com/questions/7601170", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to repeat a set of characters I'd like to repeat a set of characters multiple times. I know how to do it with a single character: string line = new string('x', 10); But what I'd like would be something more like this: string line = new string("-.", 10); which would result in: -.-.-.-.-.-.-.-.-.-. I know the string constructor can't do it, but is there some other way within the BCL? Other suggestions? Thanks! A: string line = new String('x', 10).Replace("x", "-."); A: A slight variation on the answer by Bala R var s = String.Concat(Enumerable.Repeat("-.", 10)); A: var result = String.Join("", Enumerable.Repeat("-.", 10));
{ "language": "en", "url": "https://stackoverflow.com/questions/7601171", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: GAE/Python: collection_name not working with Polymodel? I'm having trouble using db.ReferenceProperty with PolyModel in GAE. If I have two models derived from a base PolyModel, and each one has a reference to another "container" model, the collections on the container contain both PolyModels, not just the one as you would expect. Here is a test case that shows the problem: from google.appengine.ext import db from google.appengine.ext.db import polymodel class MyContainer(db.Model): name = db.StringProperty(default='mycontainer', multiline=False) class MyBaseModel(polymodel.PolyModel): name = db.StringProperty(default='mybasemodel', multiline=False) class MyModelOne(MyBaseModel): container = db.ReferenceProperty(MyContainer, collection_name='model_ones') class MyModelTwo(MyBaseModel): container = db.ReferenceProperty(MyContainer, collection_name='model_twos') print "Beginning test.\n" c = MyContainer(name="Container") c.put() one = MyModelOne(name="One", container=c) two = MyModelTwo(name="Two", container=c) one.put() two.put() print "Ones:" for o in c.model_ones: print o.name print "\nTwos:" for o in c.model_twos: print o.name And the output: Beginning test. Ones: One Two Twos: One Two Am I missing something in setting up my ReferenceProperties, or is this expected behavior? A: So looking at the SDK source, it appears that _ReverseReferenceProperty (which translates collections into Query objects) doesn't make any attempt to handle PolyModels. There are a few related complaints on the issue tracker, here and here. IMO, if this is a known limitation it ought to be mentioned somewhere in the PolyModel docs. Edit: The collection-less workaround would be something like this: for o in MyModelOne.all().filter('container =', c):
{ "language": "en", "url": "https://stackoverflow.com/questions/7601175", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Xcode 4: How to open the currently-viewed file in the Assistant pane? I often want to edit in two different locations in the same source file. I miss the ability to drag a vertical split in an Xcode window; this feature was apparently lost when going from Xcode 3 to 4. Is there a super-quick way to open the currently-viewed file in the Assistant pane? A: Right click (or control click) in the Primary editor window. A context menu should appear. In the menu there is a "Open in Assistant Editor" option. Select this and you'll have the same file in both windows. Also in here is a "Reveal in Project Navigator" option which is useful for finding a file in a large project as you were describing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601177", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Display Logcat in Terminal? Edit/Solution: execute ./adb logcat in the platform-tools directory. Original Question: I know that there's a way to display the LogCat for an Android device/emulator in Terminal on my Mac, but I'm not sure what the command is. This is mostly due to my incompetence with UNIX commands. Here are my previous failures: adb logcat adb.exe logcat FULL_PATH_TO_PLATFORM_TOOLS/adb logcat FULL_PATH_TO_PLATFORM_TOOLS/adb.exe logcat A: If you have NPM, you could install module: $ npm install -g logcat that will provide you to start monitoring colored logcat in console and //127.0.0.1/. $ logcat Here is description A: Ah, just adb logcat should work. You may need to do an explicit path if the Android SDK tools directories aren't in your PATH, but that should do it. A: In Terminal Emulator: logcat > /sdcard/logfile.txt This will put the logcat content in /sdcard/logfile.txt (your sd card main directory) obviously. Source (with more ways to acquire logcat):
{ "language": "en", "url": "https://stackoverflow.com/questions/7601178", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "46" }
Q: "Could not map the MEP URI" Error from Axis2/c and Rampart I had my web services working. I introduced rampart and now I am getting an error in response. The Webserver is Apache httpd. Running Axis2/c with Rampart 1.3.0. The services.xml looks correct as far as I can tell but I can post that too if needed. The MEP in the services.xml is the correct one which is http://www.w3.org/ns/wsdl/in-out This is my Request from SoapUI. It's very basic. <soapenv:Envelope xmlns:itr="http://../WS/" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> <soapenv:Header> <wsse:Security soapenv:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"> <wsse:UsernameToken wsu:Id="UsernameToken-7" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"> <wsse:Username>a</wsse:Username> <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">6AkYWCxaCOoiBT7QqLC/R0bIM68=</wsse:Password> <wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">qKcdLrqAOYsZojFzapXDdg==</wsse:Nonce> <wsu:Created>2011-09-29T16:05:59.146Z</wsu:Created> </wsse:UsernameToken> </wsse:Security> </soapenv:Header> <soapenv:Body> <itr:GetEquipmentRoot/> </soapenv:Body> </soapenv:Envelope> This is the response I get in SoapUI: <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> <soapenv:Header/> <soapenv:Body> <soapenv:Fault> <faultcode>soapenv:Client</faultcode> <faultstring>Could not map the MEP URI to an Axis2/C MEP constant value</faultstring> </soapenv:Fault> </soapenv:Body> </soapenv:Envelope> This is the Axis Log: [Thu Sep 29 10:00:16 2011] [debug] ..\..\src\util\rampart_util.c(32) [rampart]Trying to load module AuthenticatorCallBack.dll [Thu Sep 29 10:00:16 2011] [debug] ..\..\util\src\class_loader.c(140) AuthenticatorCallBack.dll shared lib loaded successfully [Thu Sep 29 10:00:16 2011] [debug] ..\..\src\util\rampart_util.c(48) [rampart]Successfully loaded module AuthenticatorCallBack.dll [Thu Sep 29 10:00:16 2011] [debug] ..\..\src\util\rampart_sec_header_processor.c(1815) [rampart]Processing security header in Strict layout [Thu Sep 29 10:00:16 2011] [debug] ..\..\src\util\rampart_sec_header_processor.c(1824) [rampart]Processing security header element UsernameToken [Thu Sep 29 10:00:16 2011] [info] [rampart]Validating UsernameToken [Thu Sep 29 10:00:16 2011] [debug] ..\..\src\util\rampart_sec_processed_result.c(48) [rampart]Set SPR_UT_nonce in Security Processed Results of message context [Thu Sep 29 10:00:16 2011] [debug] ..\..\src\util\rampart_sec_processed_result.c(48) [rampart]Set SPR_UT_created in Security Processed Results of message context [Thu Sep 29 10:00:16 2011] [debug] ..\..\src\util\rampart_sec_processed_result.c(48) [rampart]Set SPR_UT_username in Security Processed Results of message context [Thu Sep 29 10:00:16 2011] [debug] ..\..\src\util\rampart_sec_processed_result.c(48) [rampart]Set SPR_UT_passwordType in Security Processed Results of message context [Thu Sep 29 10:00:16 2011] [info] [rampart]Password comparison SUCCESS [Thu Sep 29 10:00:16 2011] [debug] ..\..\src\util\rampart_sec_processed_result.c(48) [rampart]Set SPR_UT_Checked in Security Processed Results of message context [Thu Sep 29 10:00:16 2011] [info] [rampart]Validating UsernameToken SUCCESS [Thu Sep 29 10:00:16 2011] [debug] ..\..\src\util\rampart_sec_header_processor.c(1824) [rampart]Processing security header element (null) [Thu Sep 29 10:00:16 2011] [error] ..\..\src\util\rampart_sec_header_processor.c(1908) [rampart]Unknown security header (null) [Thu Sep 29 10:00:16 2011] [error] ..\..\src\util\rampart_sec_header_processor.c(1915) [rampart](null) processing failed [Thu Sep 29 10:00:16 2011] [error] ..\..\src\handlers\rampart_in_handler.c(143) [rampart][rampart_in_handler] Security Header processing failed. [Thu Sep 29 10:00:16 2011] [error] ..\..\src\core\engine\phase.c(233) Handler RampartInHandler invoke failed within phase Security [Thu Sep 29 10:00:16 2011] [error] ..\..\src\core\engine\engine.c(696) Invoking phase Security failed [Thu Sep 29 10:00:16 2011] [error] ..\..\src\core\engine\engine.c(279) Invoking operation specific phases failed for operation GetEquipmentRoot [Thu Sep 29 10:00:16 2011] [debug] ..\..\src\core\engine\phase.c(210) Invoke the handler RampartOutHandler within the phase MessageOut [Thu Sep 29 10:00:16 2011] [error] ..\..\src\util\rampart_engine.c(159) [rampart][rampart_engine] Cannot get saved rampart_context [Thu Sep 29 10:00:16 2011] [error] ..\..\src\handlers\rampart_out_handler.c(136) [rampart][rampart_out_handler] ramaprt_context creation failed. [Thu Sep 29 10:00:16 2011] [error] ..\..\src\core\engine\phase.c(233) Handler RampartOutHandler invoke failed within phase MessageOut [Thu Sep 29 10:00:16 2011] [error] ..\..\src\core\engine\engine.c(696) Invoking phase MessageOut failed I cannot figure out this one issue. A: can u publish your WSDL file too? Basically in your WSDL file, did you specify MEP information to operations?
{ "language": "en", "url": "https://stackoverflow.com/questions/7601188", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to suppress "There are still active COM objects in this application" error when closing application? I've written a few ATL COM objects that are used for drag-and-drop within my C++ Builder application. Due to reasons beyond my control, my application still has active COM objects when the user attempts to close it. This is because other COM clients that use my objects seem to cache my COM objects and don't release them - as a result, my COM objects still have a reference count greater than zero when the user clicks the "X" to close my program. This results in the user getting an unfriendly message like this: I would like my application to silently terminate and not ask the user this annoying question. How do I suppress this message? A: The popup message is displayed by the the TATLModule::AutomationTerminateProc() callback function in atlmod.h. It is registered by the TATLModule::InitATLServer() callback, which calls the VCL's AddTerminateProc() function. When the TForm::Close() method is called, it calls CallTerminationProcs() to see if the app can safely close, which then calls TATLModule::AutomationTerminateProc(). The TATLModule constructor calls InitATLServer() if you do not provide your own initialization callback. So to avoid the popup, simply pass in a custom callback in your project's main .cpp file that does everything TATLModule::InitATLServer() normally does other than call AddTerminateProc(), eg: void __fastcall MyInitATLServer(); TComModule _ProjectModule(&MyInitATLServer); // <-- here TComModule &_Module = _ProjectModule; BEGIN_OBJECT_MAP(ObjectMap) ... END_OBJECT_MAP() void __fastcall MyInitATLServer() { if (TComModule::SaveInitProc) TComModule::SaveInitProc(); _Module.Init(ObjectMap, Sysinit::HInstance); _Module.m_ThreadID = ::GetCurrentThreadId(); _Module.m_bAutomationServer = true; _Module.DoFileAndObjectRegistration(); // AddTerminationProc(AutomationTerminationProc); // <-- no more popup! } A: I found a workaround for this. I'll leave this question open in case anyone posts a better method, since this one is dependent on undocumented internal implementation details of C++ Builder's ATL/VCL libraries. In the main form, place: extern TComModule &_Module; void __fastcall TMainAppForm::FormCloseQuery(TObject *Sender, bool &CanClose) { _Module.m_nLockCnt = 0; VCL appears to check the lock count and display this annoying message after the close query event is raised. It only displays the message if the lock count is 0. Therefore, I set the lock count to 0 which causes the message to not be shown. I think it's harmless to do, because I searched the ATL/VCL source code for places where the lock count is used, and I didn't find anything other than the code that checks whether to display this message. A: Try TerminateProcess(GetCurrentProcess(), 0); Of course, if there is no better way.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601204", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Add less specific class without !important I have the following CSS rules: .bookItem:hover { background: rgba(0,150,255,0.1); } .selected { background: rgba(0,150,255,0.2) !important; } When a bookItem is clicked, I use jQuery to add the selected class to it. The trouble is, without the !important the selected class does not show until the mouse is no longer hovering. I know this is because the :hover pseudoclass makes this selector "more specific". Is it possible to change the .selected class to cause it to take higher precedence than :bookItem:hover without the !important? A: Well, in my opinion, you should reconsider using this css keyword at all. !important is a tool too powerful and it mainly destroys all the hierarchy css has, making it very difficult to debug your code. Its usage should be restricted to a small number of extreme examples when there is no way out. Again, in my opinion, you should try to use as many html tags as possible, then use classes and ids, and lastly the specific atributes on css. I would go with the composed class like my fellows suggested: .bookitem.selected { back... ; } Finally, for additional information, you can read this post at smashing magazine A: I would suggest to change the specificity of .selected to .bookItem.selected Demo: http://jsfiddle.net/WK34y/ A: to make .selected class more general so it can be anywhere and not only on .bookItem elements, it worked for me forcing the .selected style on hover .selected,.selected:hover { background: rgba(0,150,255,0.2)} a working example A: This is a problem of specificity. In you stylesheet define .selected like this div item#books .selected {bacground: rgba(0,150,255,0.2);} http://css-tricks.com/855-specifics-on-css-specificity/
{ "language": "en", "url": "https://stackoverflow.com/questions/7601208", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Make workbox show workflows outside of sitecore/system/workflows Sitecore's workbox seems to only be able to show items that are in workflows in sitecore/system/workflows. Is there a way to make it show workflows in other parts of the tree? I have been able to solve several issues with moving a workflow out of that location but this one is the current sticking point. Our site is divided into several sections for different clients (in the "customers" sense of the word). The clients each need their own workflows and we would like them to be able to navigate to the workflows without having to get out of the content portion of the tree and into the system portion. Ideally we would also like to move as much of each client's custom stuff, e.g. layouts, renderings, etc, as we can into the content area so that we or they can publish that one node and subitems and have everything related to that client go live, like what I am guessing most people do with the "publish site" function. A: I'd be curious what you've done so far to alleviate this. Using reflector, I searched for the Workflow root item's GUID, {05592656-56D7-4D85-AACF-30919EE494F9}. It is stored in Sitecore.ItemIDs.WorkflowRoot, which is used in turn by Sitecore.Workflows.Simple.WorkflowProvider.GetWorkflows(). This method is called by, among other places, Sitecore.Shell.Applications.Workbox.WorkboxForm. However, it is accessed through Context.ContentDatabase.WorkflowProvider, which is a configuration element located at /sitecore/databases/database/workflowProvider. Long story short, if you haven't already, you should try implementing your own IWorkflowProvider that extends Sitecore.Workflows.Simple.WorkflowProvider and configure it in your Web.config. Override GetWorkflows() to find workflows from the location you're looking for. Use a tool like reflector or ILSpy to see what this method does currently, and make the necessary changes. Please report back (blog it if you can!). This is not an area of Sitecore that I think many people usually extend/enhance.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601211", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is there a Netbeans ruler Heres a quick questions for all you folks out there: Is it possible in the Netbeans IDE to show a ruler on top of the coding window - like in Microsoft Word or the Context code editor? If so, how? I have tried googling it, but to no avail... A: I am fairly certain that the answer is no, as the editor stands right now. The only thing remotely related is the right-margin line, which can be set in Options, under Editor, then Formatting. It, by no means, serves as a ruler, but at least gives you a hint that you've reached a particular column. In order to get this functionality, either a module would have to be written that adds the functionality to the editor, or the development team would have to add it to the core editor code. A feature request can be made on Netbeans.org's issues page. Be sure to search first, as someone may have already made the request. A: If by ruler you mean you want to show which character/column you're on, you can get that information from the looking in the bottom right hand portion of the editor window (shown as "row | column"), but if by ruler you mean grid, it isn't doable with Netbeans out of the box. You only get the character limit line, which is still defaulted to 80 characters for those required to print their code for review or delivery artifacts (...shiver...) That limit line can be set in NB 7.2 (et al) from menu Tools -> Options -> Editor -> Formatting then look for Right Margin. The color can be set on the Tools -> Options -> Fonts and Colors then look for Text Line Limit. I don't add this next possibility without a bit of eye rolling, but given Netbeans' great horizontal splitting, you could always mimic a top ruler by creating a ruler.txt file with this as the text: ***|***1***|***2***|***3***|***4***|***5***|***6***|***7***|***8***|***9***|***0 and then grab that file's tab and move it to the top split. I'll say this now so as to save all those who are at this very moment reaching for their mouse to click on the comment link to blast me, but this is totally hokey and really unnecessary for practical purposes : )
{ "language": "en", "url": "https://stackoverflow.com/questions/7601218", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to keep spaces in the formatted expression in jqMath I am using jqMath for Math equation formatter. I don't want to remove spaces and newline character from the expression. How can I do that? I have tried a lot but I coudn't find any solution. A: from the author ... In general, it's best to let html handle the text, and jqMath handle the math. For example, write " using $y = (x+1)/(x+2)$", or "<td>$x+y = 2$<td>(1)" inside an html table. You have to be able to separate user input into mathematics and non-mathematics. If a user inputs "using y=x" you don't want "using" parsed as the product of 5 variables u, s, i, n, and g. Similarly, if he inputs extra spaces that you want to keep outside the mathematics, you have to capture them using regular expressions or something, and don't pass them to jqMath. If you want the spaces to be part of the mathematics, you could make the user input \table or \sp or \text or something, though most users won't know to do that. You could tell users that they need to put $ $ around their mathematics if they want it to format, and then you could search for that. Basically, jqMath isn't smart enough to tell what's math and what isn't, without $ $ to help. Probably 0.2.0 will be out in a couple months, or at least I'll have a version I could send you by then. Update : New version is out which support /text and /html A: Using \text and "" is used to give space inside the formula HTML source : [\text"average speed" = \text"distance traveled" / \text"elapsed time"] Result : this example is available in http://mathscribe.com/author/jqmath.html A: Update: If you stumble on this, jqmath has added \, \: and \; operaters that specify thin, mid, and thicker white spacing. A: It doesn't look like it can be done. To quote the page you provided: spaces, tabs and newlines are ignored - jqMath formats the mathematics
{ "language": "en", "url": "https://stackoverflow.com/questions/7601222", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Need a PHP script to return an exact match of a python script Please I need help getting the exact md5 value of this python script in PHP The Python script def md5code(params): params = {'identifier': ' ', 'amount': '0.0', 'code': 'UNIA'} req = dict([[key, params.get(key, '')] for key in ['code', 'identifier', 'amount']]) secret = '2fd0bba6b1774ed391c1ff8467f52a5d' text = ":".join([req[x] for x in ['code', 'identifier', 'amount']] + secret) return md5(text).hexdigest().upper() The return value is: 5D316CD2311678A1B12F6152988F3097 The PHP script $secret = '2fd0bba6b1774ed391c1ff8467f52a5d'; $code = 'UNIA'; $valid_institution = array('amount' => '0.0', 'code' => $code, 'identifier' => ' '); foreach($valid_institution as $k => $v) { $text = implode(":", $v[$k] + $secret); } print strtoupper(hash("md5", $text)); The return value is: D41D8CD98F00B204E9800998ECF8427E I'm expecting the PHP script to return an exact md5 value, but it is not. Any suggestions will be appreciated. Thanks A: ok, seems you're using foreach in a wrong way. Try this: $secret = '2fd0bba6b1774ed391c1ff8467f52a5d'; $code = 'UNIA'; $valid_institution = array('amount' => '0.0', 'code' => $code, 'identifier' => ' '); $text = $valid_institution['code'] . ":" . $valid_institution['identifier'] . ":" . $valid_institution['amount'] . ":" . $secret; print strtoupper(hash("md5", $text)); A: Valid Python code could look like this: from hashlib import md5 params = {'identifier': ' ', 'amount': '0.0', 'code': 'UNIA'} req = dict([[key, params.get(key, '')] for key in ['code', 'identifier', 'amount']]) secret = '2fd0bba6b1774ed391c1ff8467f52a5d' text = ":".join(req[x] for x in ['code', 'identifier', 'amount']) + secret print md5(text).hexdigest().upper() and this is the equivalent PHP <?php $secret = '2fd0bba6b1774ed391c1ff8467f52a5d'; $code = 'UNIA'; $valid_institution = array( 'code' => $code, 'identifier' => ' ', 'amount' => '0.0'); $text = implode(':', $valid_institution) . $secret; print strtoupper(hash("md5", $text)); ?> A: $secret = '2fd0bba6b1774ed391c1ff8467f52a5d'; $code = 'UNIA'; $valid_institution = array('amount' => '0.0', 'code' => $code, 'identifier' => ' '); $text = implode(":", $valid_institution). $secret; print strtoupper(hash("md5", $text));
{ "language": "en", "url": "https://stackoverflow.com/questions/7601223", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get Dynamic Index of Rows I've created an SQL Query that orders all the rows of a table by a specific way. Q: How can I get the row number (index?) of a certain row in such a dynamically created list? Thanks in advance. A: SELECT Row_NUMBER() OVER (ORDER BY <your criteria>) as RowIndex, other fields FROM MyTable Update: To add this as a field, you can do: UPDATE T SET T.Indexfield = X.RowIndex FROM MyTable T INNER JOIN (SELECT Row_NUMBER() OVER (ORDER BY <your criteria>) as RowIndex, other fields FROM MyTable) as X ON X.<field> = T.<Field>
{ "language": "en", "url": "https://stackoverflow.com/questions/7601225", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How do I stub a class in a module in Python for testing? I have a module I am using which uses RealClass, so it is an internal dependency I don't have access to. I want to be able to create a FakeClass which replaces the functionality of the RealClass for testing. I don't want to replace individual methods but the entire class. I looked at stubble which seems to be what I want but I was wondering if mox or any of the other mocking frameworks have this functionality? Or what would you suggest to use? Maybe fudge, monkey-patching? Just looking for best practices with this stuff. Also any useful examples would be awesome. Pseudo code: from module import RealClass class FakeClass methodsFromRealClassOverridden class Test(unittest.TestCase): setup() teardown() test1() stub(RealClass, FakeClass) // something like this, but really just want the functionality classThatUsesRealClass // now will use FakeClass UPDATE: Here's one way I found to do it. It isn't perfect but it works. Example: fake = FakeClass() stub = stubout.StubOutForTesting() stub.Set(RealClass, 'method_1', fake.method_1) stub.Set(RealClass, 'method_2', fake.method_2) A: I think you want opinions/experiences so I'm just giving my 2 cents. As you noticed there are a few Python testing tools/classes/frameworks, but most of the time given the simplicity/dynamism/openness of Python you will limit yourself to using ad-hoc relevant test cases which involve stubbing at the interface level, and a bit of unittest... until you start using the frameworks. There is nothing pejorative about monkey-patching, especially when it comes to performing testing/stubbing: #!/usr/bin/env python # minimal example of library code class Class: """ a class """ def method(self, arg): """ a method that does real work """ print("pouet %s" % arg) #!/usr/bin/env python # minimal example for stub and tests, overriding/wrapping one method from Class import Class Class._real_method = Class.method def mymethod(self, arg): # do what you want print("called stub") # in case you want to call the real function... self._real_method(arg) Class.method = mymethod # ... e = Class() e.method("pouet") Namespaces will allow you to patch stuff inside of imported modules inside of imported modules... Note that the above method does not work with classes in C modules. For them you can use a wrapper class that filters on class member names using getattr/setattr, and returns the redefined members from the wrapper class. #!/usr/bin/env python # Stupid minimal example replacing the sys module # (not very useful / optimal, it's just an example of patching) import sys class SysWrap(): real = sys def __getattr__(self, attr): if attr == 'stderr': class StdErr(): def write(self, txt): print("[err: %s]" % txt) return StdErr() print("Getattr %s" % attr) return getattr(SysWrap.real, attr) sys = SysWrap() # use the real stdout sys.stdout.write("pouet") # use fake stderr sys.stderr.write("pouet") Once you are becoming tired of performing ad-hoc testing, you'll find higher level stuff such as the ones you mentioned (stubble, fudge) useful, but to enjoy them and use them efficiently you have to first see the problems they solve and accept all the automatic stuff they do under the hood. It is probable that a part of ad-hoc monkey patching will remain, it's just easier to understand, and all the tools have some limitations. Tools empower you but you have to deeply understand them to use them efficiently. An important aspect when deciding whether to use a tool or not is that when you transmit a chunk of code, you transmit the whole environment (including testing tools). The next guy might not be as smart as you and skip the testing because your testing tool is too complex for him. Generally you want to avoid using a lot of dependencies in your software. In the end, I think that nobody will bother you if you just use unittest and ad-hoc tests/monkey-patching, provided your stuff works. Your code might not be that complex anyway.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601228", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: XSL Foreach - Getting The Value Here is a bit of XML that's in each record: <MT N="usage" V="something"/> <MT N="usage" V="something else"/> I'm trying to display all of these V values for each record with XSLT, but am having issues targeting the correct value. <xsl:for-each select="MT[@N = 'usage']/@V"> <xsl:value-of select="V"/> 11 </xsl:for-each> This outputs "1111", but the value of V isn't displayed. How do I target that? Cheers A: select="V" probably is not a node. What about <xsl:for-each select="MT[@N = 'practice']"> <xsl:value-of select="@V"/> 11 </xsl:for-each> A: <xsl:for-each select="MT[@N = 'usage']/@V"> <xsl:value-of select="V"/> 11 </xsl:for-each> The <xsl:value-of> above is trying to display the value of an element V that is a child of the current node. However the current node is an attribute, and attributes by definition have no children. This is the problem that you have. Solution: <xsl:for-each select="MT[@N = 'usage']/@V"> <xsl:value-of select="."/> 11 </xsl:for-each> Now the <xsl:value-of> outputs the string value of the current node -- which was probably intended.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601233", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Can multiple VS 2010 code snippets be stored in the same file? I have about 10 code snippets I want to use in a demo in Visual Studio 2010. Does each code snippet need to be stored in a separate snippetName.snippet file? Or, can I have all snippets in one file? VS complains when I add a 2nd snippet to a file. Maybe I'm missing something though. A: According to this the <CodeSnippets> element may contain multiple <CodeSnippet> elements. I'm not sure how you are adding your second code snippet to the file, but my guess would be to add another <CodeSnippet> section for each additional code snippet you wish to include.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601235", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to calculate a date difference in calendar months? $time_start = mktime(12,0,0,1,1,2011); $time_end = mktime(12,0,0,7,1,2011); $format = '%m months'; $start_date = new DateTime(date(DATE_ATOM,$time_start)); $end_date = new DateTime(date(DATE_ATOM,$time_end)); $diff = $start_date->diff($end_date, true); echo $diff->format($format); Outputs "5 months", I guess because it's off by an hour due to DST. However, I need to calculate the difference in calendar months; is there another class/function that will do this? Added some fixes: if($time_start > $time_end) list($time_start, $time_end) = array($time_end, $time_start); $time_end += (date('I',$time_end)-date('I',$time_start))*3600; // correct for DST $start_date = new DateTime(date(DATE_ATOM,$time_start)); $end_date = new DateTime(date(DATE_ATOM,$time_end)); $start_date->modify('12pm'); // ignore time difference $end_date->modify('12pm'); $diff = $start_date->diff($end_date); echo $diff->format($format); This seems to give the results I want, but I haven't fully tested it yet. More fixes, based on Herbert's suggestions: if($time_start > $time_end) list($time_start, $time_end) = array($time_end, $time_start); $start_date = new DateTime(); $end_date = new DateTime(); $start_date->setTimestamp($time_start); $end_date->setTimestamp($time_end); $diff = $start_date->diff($end_date); $hours = $diff->format('%h'); $mins = $diff->format('%i'); $secs = $diff->format('%s'); $start_date->setTime(12,0,0);//ignore time difference for date calculations $end_date->setTime(12,0,0); $diff = $start_date->diff($end_date); $years = $diff->format('%y'); $months = $diff->format('%m'); $weeks = $diff->format('%w'); $days = $diff->format('%d'); Note that the $start_date->modify('12pm') wasn't actually doing anything at all. Not sure why it didn't error. A: Update After messing around with a lot of different ideas it occurred to me that timestamps are in GMT (UTC). date(DATE_ATOM,$time_start) is applying the default timezone. However, if you set the timestamp explicitly, DateTime will assume UTC — thus, no DST problem. The following code seems to work regardless of timezone or DST. <?php $time_start = mktime(12,0,0,1,1,2011); $time_end = mktime(12,0,0,7,1,2011) $start_date = new DateTime(); $end_date = new DateTime(); $start_date->setTimestamp($time_start); $end_date->setTimestamp($time_end); $diff = $start_date->diff($end_date); $format = '%m months'; echo $diff->format($format); ?> I tested some edge cases — both date and time, and a variety of timezones — but I haven’t tested every possibility so if you come across an issue, I’d be interested in hearing about it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601239", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Box2D and GameCenter multiplayer i have a hockey game with mallets running on iphone/ipad. The server controlls all the physics and send to the other device the server mallet position and the client sends to the server his mallet position. This part is working properly, the problem is about the puck. Becuase is way too fast and the server is the onde whos sending the message. The problem is that the puck is a b2_dynamic body and the server sends to the client where puck is at. I have updated to send the position to the client every frame on gameLoop, but the problem is thats not flowing properly. The mallets movements are ok, but with the puck its wierd a bit, i think it has to due with the linear velocity of the puck. What im doing is this: [gamedelegate movePuckToX:messageData->x andY:messageData->y andAngle:0.0]; - (void) sendMovePuck { MessageMovePuckTo message; message.message.messageType = kMessageTypeMovePuck; float_t pX = puck->GetPosition().x; float_t pY = puck->GetPosition().y; message.x = pX; message.y = pY; NSData *data = [NSData dataWithBytes:&message length:sizeof(MessageMovePuckTo)]; [self sendData:data]; } -(void )movePuckToX:(float_t)x andY:(float_t)y andAngle:(float_t)ang { lastPuckReceivedPosition = b2Vec2(x, [self getScreenSize].height/32 - y); puck->SetAwake(false); puck->SetTransform(b2Vec2(x, [self getScreenSize].height/32 - y), 0); puck->SetLinearVelocity(b2Vec2(0,0)); } Whats the best of sending the puck position to the client? Any ideas or insights? I cant managed to solve this :( A: You should try using dead reckoning and calculate it on each side. Use the host just to distribute last play. In navigation, dead reckoning is the process of calculating one's current position by using a previously determined position, or fix, and advancing that position based upon known or estimated speeds over elapsed time, and course. http://en.wikipedia.org/wiki/Dead_reckoning
{ "language": "en", "url": "https://stackoverflow.com/questions/7601241", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WAV plays from file, does not play directly from URL I have a URL that returns a 8-bit PCM, mono, 8 kHz WAV sound. When I try to play that URL via Android's MediaPlayer class, I get an error and the following in LogCat: 09-29 17:36:40.710: ERROR/PlayerDriver(562): Command PLAYER_INIT completed with an error or info PVMFFailure 09-29 17:36:40.730: ERROR/MediaPlayer(25215): error (1, -1) The content type that the URL returns is audio/x-wav. I The error occurs after calling prepareAsync(): String uri = "http://whatever"; s_Player.setDataSource(uri); s_Player.setAudioStreamType(AudioManager.STREAM_MUSIC); s_Player.prepareAsync(); When I replace uri with a file path to the same sound stored in the filesystem, it plays fine. Playing the URL in the Android browser works. So it must be me somehow misusing MediaPlayer. Any ideas, please? EDIT: it's on the emulator (for now), so permissions are not an issue. A: Maybe you didn't request Internet permission in the manifest???
{ "language": "en", "url": "https://stackoverflow.com/questions/7601247", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to style a subset of some text in HTML/CSS? Currently, I'm doing something like this: <h2><div class='q'>Q:</div> Does alfredo sauce contain soy?</h2> and then styling it in my CSS file, like so: .q { padding-bottom: 15px; display: inline; font-size: 35px; font-weight: 700; color: #65A6D1; } While this displays fine in my browser, when running the page through http://validator.w3.org, it complains: "Element div not allowed as child of element h2 in this context. (Suppressing further errors from this subtree.)" How would I style this piece of text in valid HTML/CSS? A: You can use a span <h2><span class='q'>Q:</span> Does alfredo sauce contain soy?</h2> also remove display: inline from the class .q { padding-bottom: 15px; /*display: inline;*/ font-size: 35px; font-weight: 700; color: #65A6D1; } A: Use a span instead of a div inside the h2. A: Use the <span> tag instead of <div>. <span> is an inline element, while <div> is a block element. A: A div creates a new block element. These are forbidden in h2 and many other elements. You can create an inline element with span. <h2><span class='q'>Q:</span> Does alfredo sauce contain soy?</h2> Of course, you need to change the stylesheet accordingly. A: div and h2 are both block elements. Use span instead of div. For example: <h2><span class="q">Q:</span> Blammy blammo soy?</h2> additional note: [Non-normative description] Some elements don't like to contain block elements. The header (h1, h2, ...) elements don't like to contain block elements. "Don't like": the spec says "should not" I believe. A: You can do this: <h2 id="q"><span>Q</span>Does alfredo sauce contain soy?</h2> h2#q span { padding-bottom: 15px; display: inline; font-size: 35px; font-weight: 700; color: #65A6D1; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7601249", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to convert ANM files to Maya Acii? I had these bunch of maya files on my hard drive. Unfortunately, my hard drive crashed, and I had to give it for data recovery. Now, those maya files got recovered as .anm files. Is there a way to convert them back to maya ascii or maya binary files? ANM files are described as being "3d Image File"! Those files are very important to me for a project that I'm working on..... I've really drawn a blank from the intertubes so far. Thanks in advance, S PS : the files belonged to maya 2008 - maya 2010. Here's a sample: https://docs.google.com/open?id=0B2AL684G-ov-M3lSU0pueVZyOGc A: As a Maya artist, I've not encountered anm files yet, but according to this site: http://www.blender.org/forum/viewtopic.php?t=23480&sid=d2f60eb43548e316a4c563ececccaf28 "A bit of google finds that .anm is a proprietary format which supposedly can be opened in Maya, though even that looks questionable." Have you tried loading the Maya importers under plugins? Have you tried just opening them in Maya or importing it? If not, this may sound silly, but it works for some files, try changning the extension file.anm to file.mb or file.ma and then try opening it. A: To import or export them you need to enable the AnimImportExport.mll plugin in you maya plugin manager. The file format is documented here. It looks pretty simple.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601250", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: SROLLBARINFO.rcScrollbar is referred to dimesion of scroll bar itself or scroll thumb SCROLLBARINFO Struct cbSize DWORD rcScrollBar RECT dxyLineButton DWORD xyThumbTop DWORD xyThumbBottom DWORD reserved DWORD rgstate DWORD 6 DUP SCROLLBARINFO ends When GetScrollBarInfo() return this structure, rcScrollBar is the dimension of scroll bar or scroll thumb? Update: Another structure from GetScrollInfo: typedef struct tagSCROLLINFO { UINT cbSize; UINT fMask; int nMin; int nMax; UINT nPage; int nPos; int nTrackPos; } SCROLLINFO, **LPCSCROLLINFO; To detect whether the scroll thumb at the bottom, why this formula works: IsAtBottom = (si.nMax - si.nPos) < (sbi.rcScrollBar.bottom - sbi.rcScrollBar.top) What is the relationship between nMax, nPos and scrollbar rect? Thanks in advance. A: It's the dimensions of the scroll bar rather than the thumb. A: It's the coordinates (as a RECT, so top, left, right, bottom) of the scrollbar itself (see msdn). In order to get the dimensions you would need to perform the subtraction (code snippet is in C++ but you could translate to C#): RECT coords = info.rcScollBar; LONG width = coords.right - coords.left; LONG height = coords.bottom - coords.top; You will also want to be sure you are working in the correct coordinate system (screen or client). I was trying to find what coordinate system you get back from GetScrollBarInfo but haven't found it yet. My guess would be it is in client coordinates, but I cannot confirm this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601251", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can subclass inline a pure virtual method that is not inline in the base? As I understand it, the compiler can inline a virtual function call when it knows at compile time what the type of the object will be at runtime (C++ faq). What happens, however, when one is implementing a pure virtual method from a base class? Do the same rules apply? Will the following function call be inlined? class base { public: virtual void print() = 0; virtual void callPrint() { print(); // will this be inline? } }; class child : public base { public: void print() { cout << "hello\n"; } }; int main() { child c; c.callPrint(); return 0; } EDIT: I think my original example code was actually a poor representation of what I wanted to ask. I've updated the code, but the question remains the same. A: The answer is of course "it depends", but in principle there's no obstruction to optimization. In fact, you're not even doing anything polymorphic here, so this is really straight-forward. The question would be more interesting if you had code like this: child c; base & b = c; b.print(); The point is that the compiler knows at this point what the ultimate target of the dynamic dispatch will be (namly child::print()), so this is eligible for optimization. (There are two separate opportunities for optimization, of course: one by avoiding the dynamic dispatch, and one coming from having the function body of the target visible in the TU.) A: The compiler is never required to inline a function call. In this case, it is permitted to inline the function call, because it knows the concrete type of c (since it is not indirected through a pointer or reference, the compiler can see where it was allocated as a child). As such, the compiler knows which implementation of print() is used, and can choose not to perform vtable indirection, and further choose to inline the implementation of the function. However, the compiler is also free to not inline it; it might insert a direct call to child::print(), or indirect through the vtable, if it decides to do so. These optimizations in general boil down to the 'as-if' rule - the compiler must behave as-if it was doing a full vtable indirect - this means that the result must be the same, but the compiler can choose a different method of achieving the result if the result is the same. This includes inlining, etc. A: There are only a couple of rules you should be aware of: 1) The compiler is never forced to inline - even using the directive or defining a method in the header. 2) Polymorphism MUST ALWAYS WORK. This means that the compiler will prefer calling the function via the vftable rather than inlining it when the possibility of dynamic calls exists.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601256", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to delete an object store on Persisten Object on Blackberry? I have a class with name DataContext that use Hashtable to save data to Persistent Object. Example I save two object: DataContext data = new DataContext(); data.set("object1", EditField1.getText(); data.set("object2", EditField2.getText(); data.commit(); I only want to delete data of "object1" ( not delete data of "object2" ), so i can not use data.clear(); I make like this code: if(data.get("object1")!=null){ data.set("object1",null); data.commit(); } But I received error " App Error 104 NullPointerExceptions ". How I can to delete data of "object1" ? Please help me. Binh - VietNam A: If you want to remove an element from a Hashtable then use the remove() method of your hashtable object.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601257", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I edit a properties file without trashing the rest of it Example.properties user=somePerson env=linux file=mpg properties.java class propertiestTest.java { Properties props = new Properties(); props.setProperty("user", "GodIsUser"); final File propsFile = new File(someDir/Example.properties"); props.store(new FileOutputStream(propsFile), ""); } reseult of Example.properties user=GodIsUser and all other entries are deleted A: You need to populate it from the file first using props.load: final File propsFile = new File("someDir/Example.properties"); Properties props = new Properties(); props.load(new FileInputStream(propsFile)); // make changes props.save(new FileOutputStream(propsFile), ""); A: You should use props.load(inStream) to load the existing props first. first use Properties.load(), and only after it: modify the properties by using Properties.setProperty() A: * *Read the properties file into a Properties object. *Add the new properties. *Store the newly updated Properties object. Step 1 above is the key. A: You can use put: //Load the props final File propsFile = new File(someDir/Example.properties"); Properties props = load(new FileOutputStream(propsFile)); props.put("user", "GodIsUser"); props.store(new FileOutputStream(propsFile), ""); A: try { FileInputStream fileName=new FileInputStream(fname); Properties props = new Properties(); props.load(fileName); props.setProperty(Id, value); fileName.close(); FileOutputStream outFileName=new FileOutputStream(fname); props.store(outFileName, ""); outFileName.close(); } catch (IOException io) { io.printStackTrace(); } If there is a need close the file , do it as mentioned above.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601259", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is the preferred way of upgrading to new major version of Plone? I am currently running a plone 4.0.x instance I would like to keep up to date. Buildout upgrades of minor versions like 4.0.0 -> 4.0.1 are easily done by just changing the "extends" statement in the buildout.cfg. But how about major version changes like 4.0 -> 4.1 or possibly 4.0 -> 4.2? What is the preferred way of performing such an upgrade? Is it feasible to just point buildout.cfg to the new version (e. g. 4.2) and run buildout? Or should I rerun the quickinstaller, copy the data.fs etc...? The latter seems to be a large undertaking, is there an easier way? A: It is the same procedure. With a major version upgrade there is always the chance that some things have changed a bit that require a different approach. This is not the case for 4.1. But for version specific information please see http://plone.org/documentation/migration Of course always create a backup of your data (Data.fs and var/blobstorage usually). And it is recommended to try the migration first on a copy of the site. General upgrade advice is in that same link.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601265", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What is the correct import statement to use for a Select object in webdriver 2.4 under python? I am writing tests with selenium webdriver 2.4 on python 2.7. The documentation (http://seleniumhq.org/docs/03_webdriver.html) demonstrates the ability to manipulate select form elements as follows: Select select = new Select(driver.findElement(By.xpath("//select"))); select.deselectAll(); select.selectByVisibleText("Edam"); I need to manipulate select form elements like this but in python. However I cannot figure out what to import to successfully instantiate the Select object. What should my import statement be? Thanks. A: However I cannot figure out what to import to successfully instantiate the Select object. It is available as: from selenium.webdriver.support.ui import Select See also: http://selenium.googlecode.com/svn/trunk/docs/api/py/webdriver_support/selenium.webdriver.support.select.html#module-selenium.webdriver.support.select A: Since I posted this question I've spent a good amount of time searching for the python equivalent to the java Select() object and found nothing. I've come up with a work around based on this: https://gist.github.com/1205069 Perhaps the following code will help someone save some time. from selenium import webdriver from selenium.common.exceptions import NoSuchElementException def select_by_text(web_element, select_text): """given a web element representing a select object, click the option matching select_text """ option_is_found = False options = web_element.find_elements_by_tag_name('option') for option in options: if option.text.strip() == select_text: option.click() option_is_found = True break if option_is_found == False: raise NoSuchElementException('could not find the requested element') # ...omitted setting up the driver and getting the page web_element = webdriver.find_element_by_name('country_select') select_by_text(web_element, 'Canada') This code should click on the select element given its text or raise a NoSuchElementException exception if the given element is not a select form element or the text does not exist.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601270", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Populate dropdown select with array-with multiple options So I'm trying to populate a dropdown with the states, the value for the option should be the two characters value, and the text for the option should be the full state's name, using the code below is returning a value of 0,1,2,3... and returning all the options in the var as the text. var states = ["Select State","","Alabama","AL","Alaska","AK","Arizona","AZ","Arkansas","AR",...]; $.each(states, function(val, text) { $('#selector').append( $('<option> </option>').val(val).html(text) ) }); A: Try this, using an object for states instead of an array. Same results, but it's more clear what's what and you're less likely to have problems if you accidentally skip a name or abbreviation: var states = { "Select State":"", "Alabama":"AL", "Alaska":"AK", "Arizona":"AZ", "Arkansas":"AR" }; var val, text; for (text in states) { val = states[text]; $('<option/>').val(val).text(text).appendTo($('#selector')); }; http://jsfiddle.net/g59U4/ A: The problem is that the callback function provided to .each results in val containing the index of the current iteration (e.g. 0, 1, 2 etc.) and text containing the value of that index of the array. To achieve what you are trying to, you would probably be better off with a normal for loop: for(var i = 0; i < states.length; i+=2) { $("#selector").append($('<option> </option>').val(states[i+1]).html(states[i])); } You would be even better off caching the jQuery object containing #selector outside of your loop, so it doesn't have to look it up every iteration. Here's a working example of the above. Another option would be to use an object instead of an array, using the state name or abbreviation as the keys, and the other as the values. Edit: just like @mblase75 has done A: Well you have the jQuery.each function arguments confused. The first is the index of the value in the array, and the second in the value itself. What you need to do is something like: $.each(states, function(index) { if(index%2 > 0) { //continue, basically skip every other one. Although there is probably a better way to do this return true; } $('#selector').append( $('<option> </option>').val(states[index+1]).html(states[index]) ) }); A: That would be really straightforward if your array had two dimensions. Considering you really need to use the one-dimensional array you presented, you could do this: var states = ["Select State","","Alabama","AL","Alaska","AK","Arizona","AZ","Arkansas","AR"]; for(var i=1; i<states.length; i+=2) { $('#selector').append( $('<option value="' + states[i] + '">' + states[i-1] + '</option>').val(val).html(text) ) } A: If you changed your array to be an array of objects, you could do something like this - var states = [{"text":"Select State","val":""},{"text":"Alabama","val":"AL"}]; //etc $.each(states, function(val, statedata) { $('#selector').append( $('<option> </option>').val(statedata.val).html(statedata.text) ) }); This change passes a JavaScript object in to the callback each time. The object has text and val properties and is passed in to the callback as the statedata parameter. The val parameter holds the current index position of the array so it is not required to populate the select box. Demo - http://jsfiddle.net/sR35r/ A: I have a similar situation populating a select list with a two-dimensional array as the result of an $.ajax callback .... JSON ... [["AL","Alabama"],["AK","Alaska"],["AS","American Samoa"],["AZ","Arizona"] ... var stateOptions = $('#state'); var html =''; for (var i =1; i<data.length; i++){ html+= '<option value="' +data[i][0]+ '">' +data[i][1]+ '</option>'; } stateOptions.append(html); <form name="form" id="form"> <select name="state" id="state"> <option value=''>State</option> </select> </form>
{ "language": "en", "url": "https://stackoverflow.com/questions/7601287", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: "Missing Parameter Values" error on moving to next page of report I am writing a web application using ASP.NET 2.0 [Visual Studio 2005 Professional Edition]. I have a Crystal Report that is connected to a stored procedure residing in SQL Server. This stored procedure accepts a parameter and therefore I have a formula in my report's hyperlink section to pass the parameter via Query String. Everything works fine except when I click the navigation buttons to move to the next page of the report, I either get an error or Crystal Reports shows an input box to enter the parameter values. The error shown is: "Missing Parameter Values". Only this error is shown and nothing else. If I try to export the report by selecting Export option on the Crystal toolbar, it opens a page and asks for the parameter values. I am not following why parameter values disappear when either I move from the first page to the other or try to export the report? A: Most likely you are setting the parameters in the report viewer instead of the report object. If the parameters are set in the report object they should persist on navigation. If you still have issues create an event handler for the report viewer's 'Navigate' event and reset them. A: Aditionally, if you call report.Refresh() or report.VerifyDatabase() after you set parameters it clears the values so be aware of that, MD A: When we click on report navigatin button, print button page is refeshed and we facing with 'missing parameter values error ' My probem is solved by using below line of code. If Not Page.IsPostBack Then CrystalReportViewer1.ParameterFieldInfo = paramFields CrystalReportViewer1.ReportSource = myReportDocument CrystalReportViewer1.DataBind() Else CrystalReportViewer1.ReportSource = myReportDocument CrystalReportViewer1.DataBind() End If where paramFields are runtime created ParmeterFields Best Regards, Vinay Shukla
{ "language": "en", "url": "https://stackoverflow.com/questions/7601289", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: A way to convert bitrate/format of audio files (between upload & storage to S3) Currently using PHP 5.3.x & Fedora Ok. I'll try to keep this simple. I'm working on a tool that allows the upload & storing of audio files on S3 for playback. Essentially, the user uploads a file (currently only allowing mp3 & m4a) to the server, and the file is then pushed to S3 for storage via the PHP SDK for amazon aws. The missing link is that I would like to perform a simple bitrate & format conversion of the file prior to uploading the file. (ensuring that all files are 160kbs and .mp3). I've looked into ffmpeg, although it seems that the PHP library only allows for reading bitrates and other meta, not for actual conversion. Does anyone have any thoughts on the best way to approach this? Would running a shell_exec() command that performs the conversion be sufficient to do this, or is there a more efficient/better way of doing this? Thanks in advance! Any help or advice is much appreciated. A: You need to perform the conversion and upload to S3 'outside' of the PHP application as it'll take to long for the user to hang around on the page. This could be a simple app that uses ffmpeg from the command line. I'm not familar with linux, so perhaps someone else can provide a more specific answer, but here is the basic premise: * *User uploads file to server. *You set some kind of flag (eg in a database) for the user to see that the file is being processed. *You 'tell' your external encoder that a file needs to be processed and uploaded - you could use an entry in a database or some kind of message queue for this. *The encoder (possibly a command line app that invokes ffmpeg) picks up the next file in the queue and encodes it. *When complete, it uploads it to S3. *The flag is then updated to show that processing is complete and that the file is available.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601292", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }