qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
269,466
<p>I am having trouble with a very simple Perl process. I am basically querying an Oracle database and I want to load it into Excel. I have been able to use DBIx::Dump and it works. However, I need to be able to use a variety of Excel formatting tools. And I think <a href="http://search.cpan.org/dist/Spreadsheet::WriteExcel" rel="nofollow noreferrer">Spreadsheet::WriteExcel</a> is the best module that outputs to Excel that allows me do more formatting. </p> <p>Below is the code and the error I am getting. I basically query Oracle, fetch the data, load into an array and try to write to Excel. For some reason it is doing some kind of comparison and it does not like the data types. For example, the date is '25-OCT-08'. The SVP is 'S01'. It seems to be saying that they are not numeric. </p> <p>Error:</p> <pre><code>Argument "01-NOV-08" isn't numeric in numeric ge &lt;&gt;=&gt; at C:/Perl/site/lib/Spreadsheet/WriteExcel/Worksheet.pm line 3414. Argument "01-NOV-08" isn't numeric in pack ge &lt;&gt;=&gt; ge &lt;&gt;=&gt; at C:/Perl/site/lib/Spreadsheet/WriteExcel/Worksheet.pm line 2157. </code></pre> <p>Code:</p> <pre><code>#!/usr/bin/perl -w #Set the Perl Modules use strict; use DBI; use Spreadsheet::WriteExcel; # Connect to the oracle database my $dbh = DBI-&gt;connect( 'dbi:Oracle:xxxx', 'xxxx', 'xxxx', ) || die "Database connection not made: $DBI::errstr"; #Set up Query my $stmt = "select week_end_date, SVP, RD, DM, store, wtd_smrr_gain,QTD_SMRR_GAIN, wtd_bor_gain,QTD_BOR_GAIN, wtd_cust_gain,QTD_CUST_GAIN, wtd_CARD_CLOSED_OCT25,QTD_AVG_CARD_CL from bonus_4Q_store order by store"; #Prepare Query my $sth = $dbh-&gt;prepare($stmt); #Execute Query $sth-&gt;execute() or die $dbh-&gt;errstr; my( $week_end_date,$SVP,$RD,$DM,$store, $wtd_smrr_gain,$QTD_SMRR_GAIN, $wtd_bor_gain,$QTD_BOR_GAIN, $wtd_cust_gain,$QTD_CUST_GAIN, $wtd_CARD_CLOSED_OCT25,$QTD_AVG_CARD_CL); #binds each column to a scalar reference $sth-&gt;bind_columns(undef,\$week_end_date,\$SVP,\$RD,\$DM,\$store, \$wtd_smrr_gain,\$QTD_SMRR_GAIN, \$wtd_bor_gain,\$QTD_BOR_GAIN, \$wtd_cust_gain,\$QTD_CUST_GAIN, \$wtd_CARD_CLOSED_OCT25,\$QTD_AVG_CARD_CL,); #create a new instance my $Excelfile = "/Test_Report.xls"; my $excel = Spreadsheet::WriteExcel-&gt;new("$Excelfile"); my $worksheet = $excel-&gt;addworksheet("WOW_SHEET"); #Create array shell my @data; #Call data and Write to Excel while ( @data = $sth-&gt;fetchrow_array()){ my $week_end_date = $data[0]; my $SVP = $data[1]; my $RD = $data[2]; my $DM = $data[3]; my $store = $data[1]; my $wtd_smrr_gain = $data[2]; my $QTD_SMRR_GAIN = $data[3]; my $wtd_bor_gain = $data[4]; my $QTD_BOR_GAIN = $data[5]; my $wtd_cust_gain = $data[6]; my $QTD_CUST_GAIN = $data[7]; my $wtd_CARD_CLOSED_OCT25 = $data[8]; my $QTD_AVG_CARD_CL = $data[9]; my $row = 0; my $col = 0; foreach my $stmt (@data) { $worksheet-&gt;write($row++, @data); last; } } print "DONE \n"; $sth-&gt;finish(); $dbh-&gt;disconnect(); </code></pre>
[ { "answer_id": 269497, "author": "EvilTeach", "author_id": 7734, "author_profile": "https://Stackoverflow.com/users/7734", "pm_score": 2, "selected": false, "text": "to_char(date, 'YYYY/MM/DD HH24:MI:SS')\n to_date(date, 'YYYY/MM/DD HH24:MI:SS') \n" }, { "answer_id": 270591, "author": "jmcnamara", "author_id": 10238, "author_profile": "https://Stackoverflow.com/users/10238", "pm_score": 2, "selected": false, "text": "foreach my $stmt (@data) \n{ \n $worksheet->write($row++, @data); # !!\n last; \n} \n write() write($row, $column, $token, $format)\n $column $stmt $worksheet->write($row++, 0, $stmt); \n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
269,486
<p>I'm trying to change default firstDayOfWeek for java.util.Calendar from SUNDAY to MONDAY. Is it possible to achieve this through JVM configuration instead of adding this piece of code?</p> <pre><code>cal.setFirstDayOfWeek(Calendar.MONDAY); </code></pre>
[ { "answer_id": 269538, "author": "Kariem", "author_id": 12039, "author_profile": "https://Stackoverflow.com/users/12039", "pm_score": 5, "selected": true, "text": "public static void main(String[] args) {\n Calendar c = new GregorianCalendar();\n System.out.println(Locale.getDefault() + \": \" + c.getFirstDayOfWeek());\n}\n -Duser.language=en -Duser.country=US en_US: 1 -Duser.language=en -Duser.country=GB en_GB: 2" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269486", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35172/" ]
269,494
<p>I am launching a child process with ProcessBuilder, and need the child process to exit if the parent process does. Under normal circumstances, my code is stopping the child properly. However, if I cause the OS to kill the parent, the child will continue running.</p> <p>Is there any way to "tie" the child process to the parent, such that it'll exit when the parent is killed?</p> <hr> <p>Similar questions:</p> <ul> <li><a href="https://stackoverflow.com/questions/284325/how-to-make-child-process-die-after-parent-exits">How to make child process die after parent exits?</a></li> <li><a href="https://stackoverflow.com/questions/395877/are-child-processes-created-with-fork-automatically-killed-when-the-parent-is-k">Are child processes created with fork() automatically killed when the parent is killed?</a></li> </ul>
[ { "answer_id": 272728, "author": "Greg Case", "author_id": 462, "author_profile": "https://Stackoverflow.com/users/462", "pm_score": 5, "selected": false, "text": "String[] command;\nfinal Process childProcess = new ProcessBuilder(command).start();\n\nThread closeChildThread = new Thread() {\n public void run() {\n childProcess.destroy();\n }\n};\n\nRuntime.getRuntime().addShutdownHook(closeChildThread); \n" }, { "answer_id": 31450651, "author": "Juan Pablo Fernandez", "author_id": 5122932, "author_profile": "https://Stackoverflow.com/users/5122932", "pm_score": 1, "selected": false, "text": "static int getPpid(int pid) throws IOException {\n Process p = Runtime.getRuntime().exec(\"C:\\\\Windows\\\\System32\\\\wbem\\\\WMIC.exe process where (processid=\"+pid+\") get parentprocessid\");\n BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));\n br.readLine();\n br.readLine();\n String ppid= br.readLine().replaceAll(\" \",\"\");\n return Integer.parseInt(ppid);\n}\nstatic boolean shouldExit() {\n try {\n String pid = ManagementFactory.getRuntimeMXBean().getName().split(\"@\")[0];\n int ppid = getPpid(Integer.parseInt(pid));\n /* pppid */ getPpid(ppid);\n } catch (Exception e) {\n return true;\n } \n return false;\n}\n" }, { "answer_id": 33676140, "author": "xmpy", "author_id": 3339622, "author_profile": "https://Stackoverflow.com/users/3339622", "pm_score": 3, "selected": false, "text": "package process.parent_child;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.lang.ProcessBuilder.Redirect;\n\npublic class ParentProc {\n\n public static void main(String[] args) {\n System.out.println(\"I'm parent.\");\n\n String javaHome = System.getProperty(\"java.home\");\n String javaBin = javaHome + File.separator + \"bin\" + File.separator + \"java\";\n ProcessBuilder builder = new ProcessBuilder(javaBin, \"process.parent_child.ChildProc\");\n\n // Redirect subprocess's input stream to this parent process's input stream.\n builder.redirectInput(Redirect.INHERIT);\n // This is just for see the output of child process much more easily.\n builder.redirectOutput(Redirect.INHERIT);\n try {\n Process process = builder.start();\n Thread.sleep(5000);\n } catch (IOException e) {\n e.printStackTrace();\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n System.out.println(\"Parent exits.\");\n }\n}\n package process.parent_child;\n\nimport java.io.IOException;\nimport java.util.Scanner;\n\npublic class ChildProc {\n\n\n private static class StdinListenerThread extends Thread {\n\n public void run() {\n int c;\n try {\n c = System.in.read();\n while ( c != -1 ) {\n System.out.print(c);\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n System.out.println(\"\\nChild exits.\");\n System.exit(0);\n }\n }\n\n public static void main(String[] args) throws InterruptedException {\n System.out.println(\"I'm child process.\");\n StdinListenerThread thread = new StdinListenerThread();\n thread.start();\n Thread.sleep(10000);\n }\n}\n java process.parent_child.ParentProc\n I'm parent.\n I'm child process.\n Parent exits.\n xmpy-mbp:bin zhaoxm$\n Child exits\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269494", "https://Stackoverflow.com", "https://Stackoverflow.com/users/420/" ]
269,496
<p>There are two schools of thought on how to best extend, enhance, and reuse code in an object-oriented system:</p> <ol> <li><p>Inheritance: extend the functionality of a class by creating a subclass. Override superclass members in the subclasses to provide new functionality. Make methods abstract/virtual to force subclasses to "fill-in-the-blanks" when the superclass wants a particular interface but is agnostic about its implementation.</p></li> <li><p>Aggregation: create new functionality by taking other classes and combining them into a new class. Attach an common interface to this new class for interoperability with other code.</p></li> </ol> <p>What are the benefits, costs, and consequences of each? Are there other alternatives?</p> <p>I see this debate come up on a regular basis, but I don't think it's been asked on Stack Overflow yet (though there is some related discussion). There's also a surprising lack of good Google results for it. </p>
[ { "answer_id": 269535, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 9, "selected": true, "text": "class Dog\n Eat;\n Walk;\n Bark;\n Play;\nend;\n class Cat is Dog\n Purr; \nend;\n class Cat is Dog\n Purr; \n Bark = null;\nend;\n class Cat\n has Dog;\n Eat = Dog.Eat;\n Walk = Dog.Walk;\n Play = Dog.Play;\n Purr;\nend;\n class Pet\n Eat;\n Walk;\n Play;\nend;\n\nclass Dog is Pet\n Bark;\nend;\n\nclass Cat is Pet\n Purr;\nend;\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3488/" ]
269,513
<p>Why is the generic.list slower than array?</p>
[ { "answer_id": 270486, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "List<T> T[] T[] List<T>" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
269,523
<p>I've got a Page class in my .edmx ADO.NET Entity Data Model file with with Parent and Children properties. It's for a hierarchy of Pages.</p> <p><em>removed dead ImageShack link - ADO.NET Entity Framework Hierarchical Page Class</em></p> <p>This is handled in my SQL database with a ParentId foreign key in the Page table bound to the Id primary key of that same Page table.</p> <p>How do I display this hierarchy in a WPF TreeView?</p>
[ { "answer_id": 273535, "author": "Zack Peterson", "author_id": 83, "author_profile": "https://Stackoverflow.com/users/83", "pm_score": 5, "selected": true, "text": "<Window x:Class=\"Window1\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:local=\"clr-namespace:PageManager\"\n Title=\"Window1\" Height=\"300\" Width=\"300\" Name=\"Window1\">\n <Grid>\n <TreeView Margin=\"12\" Name=\"TreeViewPages\" ItemsSource=\"{Binding}\" TreeViewItem.Expanded=\"TreeViewPages_Expanded\">\n <TreeView.Resources>\n <HierarchicalDataTemplate DataType=\"{x:Type local:Page}\" ItemsSource=\"{Binding Children}\">\n <TextBlock Text=\"{Binding Path=ShortTitle}\" />\n </HierarchicalDataTemplate>\n </TreeView.Resources>\n </TreeView>\n </Grid>\n</Window>\n Class Window1\n\n Private Sub Window1_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded\n Dim db As New PageEntities\n Dim RootPage = From p In db.Page.Include(\"Children\") _\n Where (p.Parent Is Nothing) _\n Select p\n TreeViewPages.ItemsSource = RootPage\n End Sub\n\n Private Sub TreeViewPages_Expanded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)\n Dim ExpandedTreeViewItem As TreeViewItem = DirectCast(e.OriginalSource, TreeViewItem)\n Dim PageId As Guid = DirectCast(ExpandedTreeViewItem.DataContext, Page).Id\n Dim db As New PageEntities\n Dim ChildPages = From p In db.Page.Include(\"Children\") _\n Where p.Parent.Id = PageId _\n Select p\n ExpandedTreeViewItem.ItemsSource = ChildPages\n End Sub\nEnd Class\n" }, { "answer_id": 652762, "author": "Mike Christiansen", "author_id": 29249, "author_profile": "https://Stackoverflow.com/users/29249", "pm_score": 3, "selected": false, "text": "PageEntities db = new PageEntities();\nTreeViewPages.ItemsSource = db.Page.Where(u=>u.Parent==null);\n public partial class Page {\n public ObjectQuery<Page> LoadedChildren {\n get {\n var ret = Children;\n if(ret.IsLoaded==false) ret.Load();\n return ret;\n }\n }\n}\n <TreeView Name=\"TreeViewPages\">\n <TreeView.ItemTemplate>\n <HierarchicalDataTemplate ItemSource=\"{Binding LoadedChildren}\">\n <TextBlock Text=\"{Binding ShortTitle}\" />\n </HierarchicalDataTemplate>\n </TreeView.ItemTemplate>\n</TreeView>\n" }, { "answer_id": 4839274, "author": "Nathan R", "author_id": 584878, "author_profile": "https://Stackoverflow.com/users/584878", "pm_score": 1, "selected": false, "text": "<TreeView Height=\"Auto\" HorizontalAlignment=\"Stretch\" Name=\"trvVaults\" VerticalAlignment=\"Stretch\" Width=\"Auto\" Grid.Column=\"0\" Margin=\"5\">\n <!-- Treeview ItemsSource is loaded programmatically -->\n <TreeView.ItemTemplate>\n <HierarchicalDataTemplate ItemsSource=\"{Binding Vaults}\">\n <TextBlock Text=\"{Binding Name}\" />\n </HierarchicalDataTemplate>\n </TreeView.ItemTemplate>\n</TreeView>\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83/" ]
269,541
<p>I'm trying to build a HQL that can left join values from a collection, in order to give me the chance of checking "is null" on it.</p> <p>Taken from the example from hibernate manual:</p> <pre> from Cat as cat left join cat.kittens as kitten with kitten.bodyWeight > 10.0 </pre> <p>doesn't seem to work in NHibernate, since it doesn't recognize the "with" keyword. How else are you supposed to left join and check for no-matching entries if you cannot specify join-clauses directly in your join as opposed to in your WHERE-statement?</p> <p>I'm running NHibernate 2.0.0.</p>
[ { "answer_id": 494894, "author": "Frederik Gheysels", "author_id": 55774, "author_profile": "https://Stackoverflow.com/users/55774", "pm_score": 1, "selected": false, "text": "from Cat c\nleft join c.Kittens as kitten\nwhere kitten.bodyweight > 10 or kitten.bodyweight is null\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33663/" ]
269,545
<p>With the jQuery datepicker, how does one change the year range that is displayed? On the jQuery UI site it says the default is "10 years before and after the current year are shown". I want to use this for a birthday selection and 10 years before today is no good. Can this be done with the jQuery datepicker or will I have to use a different solution?</p> <p>link to datepicker demo: <a href="http://jqueryui.com/demos/datepicker/#dropdown-month-year" rel="noreferrer">http://jqueryui.com/demos/datepicker/#dropdown-month-year</a></p>
[ { "answer_id": 269561, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 8, "selected": true, "text": "Year dropdown shows last 20 years $(\"#restricting\").datepicker({ \n yearRange: \"-20:+0\", // this is the option you're looking for\n showOn: \"both\", \n buttonImage: \"templates/images/calendar.gif\", \n buttonImageOnly: true \n});\n -20 -100" }, { "answer_id": 269573, "author": "JamesSugrue", "author_id": 1075, "author_profile": "https://Stackoverflow.com/users/1075", "pm_score": 3, "selected": false, "text": "\"$(\".selector\").datepicker({ beforeShowDay: nationalDays}) \nnatDays = [[1, 26, 'au'], [2, 6, 'nz'], [3, 17, 'ie'], [4, 27, 'za'], \n[5, 25, 'ar'], [6, 6, 'se'], [7, 4, 'us'], [8, 17, 'id'], [9, 7, \n'br'], [10, 1, 'cn'], [11, 22, 'lb'], [12, 12, 'ke']]; \nfunction nationalDays(date) { \n for (i = 0; i < natDays.length; i++) { \n if (date.getMonth() == natDays[i][0] - 1 && date.getDate() == \nnatDays[i][1]) { \n return [false, natDays[i][2] + '_day']; \n } \n } \n return [true, '']; \n} \n" }, { "answer_id": 419283, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": ".au_day {\n text-indent: -9999px;\n background: #eee url(au.gif) no-repeat center;\n}\n" }, { "answer_id": 4068478, "author": "Plippie", "author_id": 344117, "author_profile": "https://Stackoverflow.com/users/344117", "pm_score": 5, "selected": false, "text": "$( \".datefield\" ).datepicker({\n changeMonth: true,\n changeYear: true,\n yearRange:'-90:+0'\n});\n" }, { "answer_id": 11734244, "author": "Warren Sergent", "author_id": 800505, "author_profile": "https://Stackoverflow.com/users/800505", "pm_score": 3, "selected": false, "text": "yearRange: \"1901:2012\"\n" }, { "answer_id": 15961162, "author": "Maverick", "author_id": 1500491, "author_profile": "https://Stackoverflow.com/users/1500491", "pm_score": 3, "selected": false, "text": "$(\".datePickerDOB\").datepicker({ \n yearRange: \"-122:-18\", //18 years or older up to 122yo (oldest person ever, can be sensibly set to something much smaller in most cases)\n maxDate: \"-18Y\", //Will only allow the selection of dates more than 18 years ago, useful if you need to restrict this\n minDate: \"-122Y\"\n});\n" }, { "answer_id": 21726498, "author": "Manish", "author_id": 1917951, "author_profile": "https://Stackoverflow.com/users/1917951", "pm_score": 2, "selected": false, "text": " $(\"#DateOfBirth\").datepicker({\n yearRange: \"-100:+0\",\n changeMonth: true,\n changeYear: true,\n });\n" }, { "answer_id": 23677495, "author": "Himansz", "author_id": 3328204, "author_profile": "https://Stackoverflow.com/users/3328204", "pm_score": 1, "selected": false, "text": "$(function () {\n $(\".DatepickerInputdob\").datepicker({\n dateFormat: \"d M yy\",\n changeMonth: true,\n changeYear: true,\n yearRange: '1900:+0',\n defaultDate: '01 JAN 1900'\n });\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2847/" ]
269,560
<p>In Python map() works on any data that follows the sequence protocol. It does The Right Thing^TM whether I feed it a string or a list or even a tuple.</p> <p>Can't I have my cake in OCaml too? Do I really have no other choice but to look at the collection type I'm using and find a corresponding List.map or an Array.map or a Buffer.map or a String.map? Some of these don't even exist! Is what I'm asking for unusual? I must be missing something.</p>
[ { "answer_id": 269851, "author": "Chris Conway", "author_id": 1412, "author_profile": "https://Stackoverflow.com/users/1412", "pm_score": 5, "selected": true, "text": "Enum Enum Enum.t Enum.t Enum.t Foldable Functor Foldable Functor" }, { "answer_id": 829115, "author": "J D", "author_id": 13924, "author_profile": "https://Stackoverflow.com/users/13924", "pm_score": 4, "selected": false, "text": "map collection#map" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18446/" ]
269,566
<p>I have two html pages, when you click on something on the first html, it will go to the second one. What I want to do is to show text according to what you clicked on the first html. different texts are wrapped with different ids. Here's how I wrote:</p> <pre><code>&lt;a href="secondpage.html#one"&gt;&lt;/a&gt; &lt;a href="secondpage.html#two"&gt;&lt;/a&gt; &lt;a href="secondpage.html#three"&gt;&lt;/a&gt; </code></pre> <p>I'm expecting to see two.html load the text with id "one", but it doesn't work, does anyone know what I did wrong? </p> <p>Here's the code on second page:</p> <pre><code>&lt;ul id="menu" class="aaa"&gt; &lt;li&gt;&lt;a id="one" href="#"&gt;one&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a id="two" href="#"&gt;two&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a id="three" href="#"&gt;three&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>And I have a JS file to modify each id:</p> <pre><code>$("one").observe('click', function() { $('Pic').writeAttribute('src',"picone.jpg"); $('Bio').update("texthere!"); }); </code></pre> <p>Same for two and three.</p> <p>Right now if I click on a button on the first page, it will always show the text and pic for "one", no matter which button I click.</p> <p>But I want to see the pic and text for "two" if i click on it.</p>
[ { "answer_id": 269592, "author": "Keltex", "author_id": 28260, "author_profile": "https://Stackoverflow.com/users/28260", "pm_score": 0, "selected": false, "text": "<a name='one'></a>\n" }, { "answer_id": 269595, "author": "Pim Jager", "author_id": 35197, "author_profile": "https://Stackoverflow.com/users/35197", "pm_score": 1, "selected": false, "text": "self.document.location.hash\n self.document.location.hash.substring(1)\n" }, { "answer_id": 269938, "author": "Pim Jager", "author_id": 35197, "author_profile": "https://Stackoverflow.com/users/35197", "pm_score": 1, "selected": false, "text": "<ul id=\"menu\" class=\"aaa\">\n<li><a id=\"one\" name=\"one\" href=\"#\">one</a></li>\n<li><a id=\"two\" name=\"two\" href=\"#\">two</a></li>\n<li><a id=\"three\" name=\"three\" href=\"#\">three</a></li></ul>\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34797/" ]
269,577
<p>I am working on a small parser that should accept input in a number of languages. I am going to have maybe 50 strings that will serve as keywords/anchors in parsing the input. In PHP, what would be the best way to organize these translated keywords? </p> <p>One possible solution that comes to my mind is to use an associative array. Like this:</p> <pre><code>$lang = array('us' =&gt; array('totalDebt' =&gt; 'Total Debt', 'color' =&gt; 'Color'), 'gb' =&gt; array('totalDebt' =&gt; 'Total Debt', 'color' =&gt; 'Colour')) </code></pre> <p>which I could then access using the following:</p> <pre><code>$langCode = 'en'; $debtPos = strpos($lang[$langCode]['totalDebt']); </code></pre> <p>Are there any better, proven methods for dealing with a bunch of short strings translated into a bunch of languages?</p>
[ { "answer_id": 270850, "author": "too much php", "author_id": 28835, "author_profile": "https://Stackoverflow.com/users/28835", "pm_score": 0, "selected": false, "text": "$lang <?php // lang.us.php\n$LANG['us'] = array(\n 'totalDebt' => 'Total Debt',\n 'color' => 'Color',\n );\n" }, { "answer_id": 270888, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 0, "selected": false, "text": "$lang['us'] <?php // lang.en-gb.php\n$lang = array(\n 'color' => \"Colour\",\n 'totalDebt' => \"Total Debt\",\n ...\n);\n?>\n\n<?php // lang.en-us.php\ninclude('lang.en-gb.php');\n\n$lang['color'] = \"Color\";\n// don't need to redefine \"totalDebt\"\n?>\n" }, { "answer_id": 270954, "author": "jcampbell1", "author_id": 20512, "author_profile": "https://Stackoverflow.com/users/20512", "pm_score": 0, "selected": false, "text": "echo \"Color\";\n echo t(\"Color\");\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
269,578
<p>I want to get the method <code>System.Linq.Queryable.OrderyBy&lt;T, TKey&gt;(the IQueryable&lt;T&gt; source, Expression&lt;Func&lt;T,TKey&gt;&gt; keySelector)</code> method, but I keep coming up with nulls.</p> <pre><code>var type = typeof(T); var propertyInfo = type.GetProperty(group.PropertyName); var propertyType = propertyInfo.PropertyType; var sorterType = typeof(Func&lt;,&gt;).MakeGenericType(type, propertyType); var expressionType = typeof(Expression&lt;&gt;).MakeGenericType(sorterType); var queryType = typeof(IQueryable&lt;T&gt;); var orderBy = typeof(System.Linq.Queryable).GetMethod("OrderBy", new[] { queryType, expressionType }); /// is always null. </code></pre> <p>Does anyone have any insight? I would prefer to not loop through the <code>GetMethods</code> result.</p>
[ { "answer_id": 269908, "author": "David", "author_id": 21909, "author_profile": "https://Stackoverflow.com/users/21909", "pm_score": 2, "selected": false, "text": "var orderBy =\n (from methodInfo in typeof(System.Linq.Queryable).GetMethods()\n where methodInfo.Name == \"OrderBy\"\n let parameterInfo = methodInfo.GetParameters()\n where parameterInfo.Length == 2\n && parameterInfo[0].ParameterType.GetGenericTypeDefinition() == typeof(IQueryable<>)\n && parameterInfo[1].ParameterType.GetGenericTypeDefinition() == typeof(Expression<>)\n select\n methodInfo\n ).Single();\n" }, { "answer_id": 269992, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": false, "text": "public static class TypeExtensions\n{\n private static readonly Func<MethodInfo, IEnumerable<Type>> ParameterTypeProjection = \n method => method.GetParameters()\n .Select(p => p.ParameterType.GetGenericTypeDefinition());\n\n public static MethodInfo GetGenericMethod(this Type type, string name, params Type[] parameterTypes)\n {\n return (from method in type.GetMethods()\n where method.Name == name\n where parameterTypes.SequenceEqual(ParameterTypeProjection(method))\n select method).SingleOrDefault();\n }\n}\n" }, { "answer_id": 373396, "author": "Neil", "author_id": 24315, "author_profile": "https://Stackoverflow.com/users/24315", "pm_score": 5, "selected": true, "text": "public static MethodInfo GetOrderByMethod<TElement, TSortKey>()\n{\n Func<TElement, TSortKey> fakeKeySelector = element => default(TSortKey);\n\n Expression<Func<IEnumerable<TElement>, IOrderedEnumerable<TElement>>> lamda\n = list => list.OrderBy(fakeKeySelector);\n\n return (lamda.Body as MethodCallExpression).Method;\n}\n\nstatic void Main(string[] args)\n{\n List<int> ints = new List<int>() { 9, 10, 3 };\n MethodInfo mi = GetOrderByMethod<int, string>(); \n Func<int,string> keySelector = i => i.ToString();\n IEnumerable<int> sortedList = mi.Invoke(null, new object[] { ints, \n keySelector }\n ) as IEnumerable<int>;\n\n foreach (int i in sortedList)\n {\n Console.WriteLine(i);\n }\n}\n public static MethodInfo GetOrderByMethod(Type elementType, Type sortKeyType)\n{\n MethodInfo mi = typeof(Program).GetMethod(\"GetOrderByMethod\", Type.EmptyTypes);\n\n var getOrderByMethod = mi.MakeGenericMethod(new Type[] { elementType,\n sortKeyType });\n return getOrderByMethod.Invoke(null, new object[] { }) as MethodInfo;\n}\n" }, { "answer_id": 3453666, "author": "Kyle", "author_id": 259594, "author_profile": "https://Stackoverflow.com/users/259594", "pm_score": 1, "selected": false, "text": " var method = type.GetGenericMethod\n (c => c.Validate((IValidator<object>)this, o, action));\n" }, { "answer_id": 3628713, "author": "qube", "author_id": 438137, "author_profile": "https://Stackoverflow.com/users/438137", "pm_score": 3, "selected": false, "text": "public static MethodInfo GetGenericMethod(\n this Type type, string name, Type[] generic_type_args, Type[] param_types, bool complain = true)\n{\n foreach (MethodInfo m in type.GetMethods())\n if (m.Name == name)\n {\n ParameterInfo[] pa = m.GetParameters();\n if (pa.Length == param_types.Length)\n {\n MethodInfo c = m.MakeGenericMethod(generic_type_args);\n if (c.GetParameters().Select(p => p.ParameterType).SequenceEqual(param_types))\n return c;\n }\n }\n if (complain)\n throw new Exception(\"Could not find a method matching the signature \" + type + \".\" + name +\n \"<\" + String.Join(\", \", generic_type_args.AsEnumerable()) + \">\" +\n \"(\" + String.Join(\", \", param_types.AsEnumerable()) + \").\");\n return null;\n}\n var type = typeof(T); \nvar propertyInfo = type.GetProperty(group.PropertyName); \nvar propertyType = propertyInfo.PropertyType; \n\nvar sorterType = typeof(Func<,>).MakeGenericType(type, propertyType); \nvar expressionType = typeof(Expression<>).MakeGenericType(sorterType); \n\nvar queryType = typeof(IQueryable<T>); \n\nvar orderBy = typeof(Queryable).GetGenericMethod(\"OrderBy\",\n new Type[] { type, propertyType },\n new[] { queryType, expressionType });\n" }, { "answer_id": 12117133, "author": "Konstantin Isaev", "author_id": 1026676, "author_profile": "https://Stackoverflow.com/users/1026676", "pm_score": 0, "selected": false, "text": "public static class SortingUtilities<T, TProperty>\n{\n public static IOrderedQueryable<T> ApplyOrderBy(IQueryable<T> query, Expression<Func<T, TProperty>> selector)\n {\n return query.OrderBy(selector);\n }\n\n\n public static IOrderedQueryable<T> ApplyOrderByDescending(IQueryable<T> query, Expression<Func<T, TProperty>> selector)\n {\n return query.OrderByDescending(selector);\n }\n\n public static IQueryable<T> Preload(IQueryable<T> query, Expression<Func<T, TProperty>> selector)\n {\n return query.Include(selector);\n }\n}\n public class SortingOption<T> where T: class\n{\n private MethodInfo ascendingMethod;\n private MethodInfo descendingMethod;\n private LambdaExpression lambda;\n public string Name { get; private set; }\n\n public SortDirection DefaultDirection { get; private set; }\n\n public bool ApplyByDefault { get; private set; }\n\n public SortingOption(PropertyInfo targetProperty, SortableAttribute options)\n {\n Name = targetProperty.Name;\n DefaultDirection = options.Direction;\n ApplyByDefault = options.IsDefault;\n var utilitiesClass = typeof(SortingUtilities<,>).MakeGenericType(typeof(T), targetProperty.PropertyType);\n ascendingMethod = utilitiesClass.GetMethod(\"ApplyOrderBy\", BindingFlags.Static | BindingFlags.Public | BindingFlags.IgnoreCase);\n descendingMethod = utilitiesClass.GetMethod(\"ApplyOrderByDescending\", BindingFlags.Static | BindingFlags.Public | BindingFlags.IgnoreCase);\n var param = Expression.Parameter(typeof(T));\n var getter = Expression.MakeMemberAccess(param, targetProperty);\n lambda = Expression.Lambda(typeof(Func<,>).MakeGenericType(typeof(T), targetProperty.PropertyType), getter, param);\n }\n\n public IQueryable<T> Apply(IQueryable<T> query, SortDirection? direction = null)\n {\n var dir = direction.HasValue ? direction.Value : DefaultDirection;\n var method = dir == SortDirection.Ascending ? ascendingMethod : descendingMethod;\n return (IQueryable<T>)method.Invoke(null, new object[] { query, lambda });\n }\n}\n public class SortableAttribute : Attribute \n{\n public SortDirection Direction { get; set; }\n public bool IsDefault { get; set; }\n}\n public enum SortDirection\n{\n Ascending,\n Descending\n}\n" }, { "answer_id": 15695892, "author": "PaulWh", "author_id": 2221700, "author_profile": "https://Stackoverflow.com/users/2221700", "pm_score": 2, "selected": false, "text": "public static MethodInfo GetOrderByMethod<TElement, TSortKey>() {\n IEnumerable<TElement> col = null;\n return new Func<Func<TElement, TSortKey>, IOrderedEnumerable<TElement>>(col.OrderBy).Method;\n}\n" }, { "answer_id": 19499360, "author": "MBoros", "author_id": 280562, "author_profile": "https://Stackoverflow.com/users/280562", "pm_score": 0, "selected": false, "text": " #region Count\n /// <summary>\n /// gets the \n /// public static int Count&lt;TSource>(this IEnumerable&lt;TSource> source);\n /// methodinfo\n /// </summary>\n /// <typeparam name=\"TSource\">type of the elements</typeparam>\n /// <returns></returns>\n public static MethodInfo GetCountMethod<TSource>()\n {\n Expression<Func<IEnumerable<TSource>, int>> lamda = list => list.Count();\n return (lamda.Body as MethodCallExpression).Method;\n }\n\n /// <summary>\n /// gets the \n /// public static int Count&lt;TSource>(this IEnumerable&lt;TSource> source);\n /// methodinfo\n /// </summary>\n /// <param name=\"elementType\">type of the elements</param>\n /// <returns></returns>\n public static MethodInfo GetCountMethodByType(Type elementType)\n {\n // to get the method name, we use lambdas too\n Expression<Action> methodNamer = () => GetCountMethod<object>();\n var gmi = ((MethodCallExpression)methodNamer.Body).Method.GetGenericMethodDefinition();\n var mi = gmi.MakeGenericMethod(new Type[] { elementType });\n return mi.Invoke(null, new object[] { }) as MethodInfo;\n }\n #endregion Disctinct\n" }, { "answer_id": 68642630, "author": "t.ouvre", "author_id": 5658778, "author_profile": "https://Stackoverflow.com/users/5658778", "pm_score": 2, "selected": false, "text": "Type.MakeGenericMethodParameter Queryable.OrderBy var TSource = Type.MakeGenericMethodParameter(0);\nvar TKey = Type.MakeGenericMethodParameter(1);\nvar orderBy = typeof(Queryable).GetMethod(nameof(Queryable.OrderBy), 2, BindingFlags.Static | BindingFlags.Public, null, CallingConventions.Standard\n , new[] { typeof(IQueryable<>).MakeGenericType(TSource), typeof(Expression<>).MakeGenericType(typeof(Func<,>).MakeGenericType(TSource, TKey)) }\n , null);\nAssert.NotNull(orderBy);\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21909/" ]
269,581
<p>I am attempting to return a collection of departments from a .NET assembly to be consumed by ASP via COM Interop. Using .NET I would just return a generic collection, e.g. <code>List&lt;Department&gt;</code>, but it seems that generics don't work well with COM Interop. So, what are my options?</p> <p>I would like to both iterate over the list and be able to access an item by index. Should I inherit from <code>List&lt;Department&gt;</code>, implement an <code>IList</code>, <code>IList&lt;Department&gt;</code> or another interface, or is there a better way? Ideally I would prefer not to have to implement a custom collection for every type of list I need. Also, will <code>List[index]</code> even work with COM Interop?</p> <p>Thanks, Mike</p> <h2>Example .NET components (C#):</h2> <pre><code>public class Department { public string Code { get; private set; } public string Name { get; private set; } // ... } public class MyLibrary { public List&lt;Department&gt; GetDepartments() { // return a list of Departments from the database } } </code></pre> <h2>Example ASP code:</h2> <pre><code>&lt;% Function PrintDepartments(departments) Dim department For Each department In departments Response.Write(department.Code &amp; ": " &amp; department.Name &amp; "&lt;br /&gt;") Next End Function Dim myLibrary, departments Set myLibrary = Server.CreateObject("MyAssembly.MyLibrary") Set departments = myLibrary.GetDepartments() %&gt; &lt;h1&gt;Departments&lt;/h1&gt; &lt;% Call PrintDepartments(departments) %&gt; &lt;h1&gt;The third department&lt;/h1&gt; &lt;%= departments(2).Name %&gt; </code></pre> <h2>Related questions:</h2> <ul> <li><a href="https://stackoverflow.com/questions/161704/using-generic-lists-on-serviced-component">Using Generic lists on serviced component</a></li> <li><a href="https://stackoverflow.com/questions/56375/are-non-generic-collections-in-net-obsolete">Are non-generic collections in .NET obsolete?</a></li> </ul>
[ { "answer_id": 270025, "author": "Mike Henry", "author_id": 14934, "author_profile": "https://Stackoverflow.com/users/14934", "pm_score": 5, "selected": true, "text": "System.Collections.ArrayList ComArrayList ArrayList GetByIndex SetByIndex public class ComArrayList : System.Collections.ArrayList {\n public virtual object GetByIndex(int index) {\n return base[index];\n }\n\n public virtual void SetByIndex(int index, object value) {\n base[index] = value;\n }\n}\n public ComArrayList GetDepartments() {\n // return a list of Departments from the database\n}\n <h1>The third department</h1>\n<%= departments.GetByIndex(2).Name %>\n" }, { "answer_id": 1860558, "author": "Christian Hayter", "author_id": 115413, "author_profile": "https://Stackoverflow.com/users/115413", "pm_score": 3, "selected": false, "text": "Department[] public Department[] GetDepartments() {\n var departments = new List<Department>();\n // populate list from database\n return departments.ToArray();\n}\n" }, { "answer_id": 4631789, "author": "Jeremy Prine", "author_id": 567669, "author_profile": "https://Stackoverflow.com/users/567669", "pm_score": 1, "selected": false, "text": "<h1>The third department</h1>\n<%= departments.Item(2).Name %>\n" }, { "answer_id": 9362837, "author": "akc42", "author_id": 438737, "author_profile": "https://Stackoverflow.com/users/438737", "pm_score": 1, "selected": false, "text": "Public Class MyClass\n...\n Private _MyList As List(of MyObject)\n Public ReadOnly Property MyList As IList Implements IMyClass.MyList\n Get\n Return _MyList\n End Get\n End Property\n ReadOnly Property MyList As IList\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14934/" ]
269,582
<p>What combination of CSS or attributes are needed?</p>
[ { "answer_id": 270195, "author": "Ionuț Staicu", "author_id": 23810, "author_profile": "https://Stackoverflow.com/users/23810", "pm_score": 5, "selected": false, "text": "<input type=\"file\" size=\"50\" .... />\n" }, { "answer_id": 270675, "author": "Bryan M.", "author_id": 4636, "author_profile": "https://Stackoverflow.com/users/4636", "pm_score": 3, "selected": false, "text": "visibility: hidden cursor: pointer cursor: hand" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337/" ]
269,590
<p>I just spent half an one our to find out what caused the Error-Message "Ci is not defined" in my JavaScript code. I finally found the reason:</p> <p>It should be (jQuery):</p> <pre><code>$("asd").bla(); </code></pre> <p>It was:</p> <pre><code>("asd").bla(); </code></pre> <p>(Dollar sign gone missing)</p> <p>Now after having fixed the problem I'd like to understand the message itself: What does Firefox mean when it tells me that "Ci" is not defined. What's "Ci"?</p> <hr> <p>Update: I'm using the current version of Firefox (3.0.3).</p> <p>To reproduce, just use this HTML code:</p> <pre><code>&lt;html&gt;&lt;head&gt;&lt;title&gt;test&lt;/title&gt; &lt;script&gt; ("asd").bla(); &lt;/script&gt; &lt;/head&gt;&lt;body&gt;&lt;/body&gt;&lt;/html&gt; </code></pre> <p>To make it clear: I know what caused the error message. I'd just like to know what Firefox tries to tell me with "Ci"...</p>
[ { "answer_id": 269636, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 3, "selected": true, "text": "bla() $ (\"asd\") bla() String.prototype.bla = function() {};\n\n// now this next line will execute without any problems:\n(\"asd\").bla();\n Ci" }, { "answer_id": 269831, "author": "BlaM", "author_id": 999, "author_profile": "https://Stackoverflow.com/users/999", "pm_score": 2, "selected": false, "text": "const Ci = Components.interfaces; \n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/999/" ]
269,601
<p>I have a file I need to rename to that of an existing file. This is a copy, modify, replace original operation on an existing JAR file. I've got the first two steps done, I just need help with the replace original bit. What's the best way to rename the new version of the JAR to that of the old. The old JAR doesn't need preserving and I don't want to have a copy of the new with its initial name sticking around. </p> <p>I have commons lang and io already, so if there's a method I've missed, that would be great.</p>
[ { "answer_id": 269647, "author": "Powerlord", "author_id": 15880, "author_profile": "https://Stackoverflow.com/users/15880", "pm_score": 3, "selected": true, "text": "java.io.File oldFile newFile oldFile.delete()\nnewFile.renameTo(oldFile);\n" }, { "answer_id": 269649, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 2, "selected": false, "text": "Java.io.File.renameTo(java.io.File) File.delete()" }, { "answer_id": 269666, "author": "James Van Huis", "author_id": 31828, "author_profile": "https://Stackoverflow.com/users/31828", "pm_score": 2, "selected": false, "text": "public boolean replaceOldJar(String originalJarPath, java.io.File newJar) {\n java.io.File originalJar = new java.io.File(originalJarPath);\n if (!originalJar.isFile()) {\n return false;\n }\n boolean deleteOldJarSucceeded = originalJar.delete();\n if (!deleteOldJarSucceeded) {\n return false;\n }\n newJar.renameTo(originalJar);\n return originalJar.exists();\n}\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4893/" ]
269,603
<p>I'm looking to convert a small .NET console application into a Windows Service. I'd like to build two versions, one using .NET 2.0 and another with .NET 3.5 .</p> <p>Are there radically different approaches that need to be taken, or will the 2.0 version be roughly equivalent to the 3.5 version? Where's a good source of information (i.e. a web-based guide) that can walk me through the steps of setting up the service?</p> <p>Thanks! P.A.</p>
[ { "answer_id": 15064862, "author": "Praveen", "author_id": 1671639, "author_profile": "https://Stackoverflow.com/users/1671639", "pm_score": 0, "selected": false, "text": "windows service" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35171/" ]
269,605
<p>I've got an MS access database and I would need to create an SQL query that allows me to select all the not distinct entries in one column while still keeping all the values.</p> <p>In this case more than ever an example is worth thousands of words:</p> <p>Table:</p> <pre><code>A B C 1 x q 2 y w 3 y e 4 z r 5 z t 6 z y </code></pre> <p><em>SQL magic</em></p> <p>Result:</p> <pre><code>B C y w y e z r z t z y </code></pre> <p>Basically it removes all unique values of column B but keeps the multiple rows of the data kept. I can "group by b" and then "count>1" to get the not distinct but the result will only list one row of B not the 2 or more that I need.</p> <p>Any help?</p> <p>Thanks.</p>
[ { "answer_id": 269620, "author": "a2800276", "author_id": 27408, "author_profile": "https://Stackoverflow.com/users/27408", "pm_score": 2, "selected": false, "text": "select \n * \nfrom \n my_table t1, \n my_table t2\nwhere \n t1.B = t2.B\nand\n t1.C != t2.C\n\n-- apparently you need to use <> instead of != in Access\n-- Thanks, Dave!\n" }, { "answer_id": 269671, "author": "Dave DuPlantis", "author_id": 8174, "author_profile": "https://Stackoverflow.com/users/8174", "pm_score": 3, "selected": false, "text": "select *\nfrom\n my_table\nwhere \n B in \n (select B from my_table group by B having count(*) > 1)\n" }, { "answer_id": 269708, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": 6, "selected": true, "text": "Select B, C\nFrom Table\nWhere B In\n (Select B From Table\n Group By B\n Having Count(*) > 1)\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269605", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
269,611
<p>"Both DataSource and DataSourceID are defined on 'grdCommunication'. Remove one definition."</p> <p>I just got this error today, the code has been working until this afternoon I published the latest version to our server and it broke with that error both locally and on the server. I don't use "DataSourceID", the application reads database queries into a datatable and sets the datatable as the DataSource on the GridViews. I did a search in Visual Studio, searching the entire solution and the string "DataSourceID" does not appear in even 1 line of code in the entire solution. This is the first thing that freaked me out. </p> <p>I figure it had been working yesterday, so I reverted the code to yesterday's build. The error was still there. I kept going back a build, and still the issue is there. I went back a month, I am still getting the same error. This application was working fine this morning? There has really been no code changes, and no where in the application is the DataSourceID EVER set on any of the gridviews. Has anyone ever seen anything like this at all??</p> <p>How can I get that error if DataSourceID is never set... and the word "DataSourceID" is not in my solution? I just did a wingrep on the entire tree doing a case insensitive search on datasourceid.... pulled up absolutely nothing. That word is absolutely no where in the entire application. </p> <pre><code> &lt;asp:GridView ID="grdCommunication" runat="server" Height="130px" Width="100%" AllowPaging="true" &gt; ... standard grid view column setup here... &lt;/asp:GridView&gt; // Code behind.. to set the datasource DataSet dsActivity = objCompany.GetActivityDetails(); grdCommunication.DataSource = dsActivity; grdCommunication.DataBind(); </code></pre> <p>// Updated: removed some confusing notes. </p>
[ { "answer_id": 269701, "author": "tsilb", "author_id": 11112, "author_profile": "https://Stackoverflow.com/users/11112", "pm_score": 4, "selected": true, "text": "DataSet dsActivity = objCompany.GetActivityDetails();\ngrdCommunication.DataSource = dsActivity.Tables[0];\ngrdCommunication.DataBind();\n" }, { "answer_id": 480840, "author": "weffey", "author_id": 13208, "author_profile": "https://Stackoverflow.com/users/13208", "pm_score": 0, "selected": false, "text": "if (Cache[\"countries\"] != null)\n{\n lbCountries.Items.Clear();\n lbCountries.DataValueField = \"Code\";\n lbCountries.DataTextField = \"Name\";\n lbCountries.DataSource = (Cache[\"countries\"]);\n lbCountries.DataBind();}\nelse\n{\n var lstCountries = from Countries in db_read.Countries orderby Countries.Name select Countries;\n lbCountries.Items.Clear();\n lbCountries.DataValueField = \"Code\";\n lbCountries.DataTextField = \"Name\";\n lbCountries.DataSource = lstCountries.ToList();\n lbCountries.DataBind();\n\n Cache.Add(\"countries\", lstCountries, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 240, 0), System.Web.Caching.CacheItemPriority.High, null);\n}\n" }, { "answer_id": 3522713, "author": "kjpowers2", "author_id": 233361, "author_profile": "https://Stackoverflow.com/users/233361", "pm_score": 0, "selected": false, "text": "Dim datatable As DataTable = dataset.Tables(0)\nDim dataSourceID As String = gvImageFiles.DataSourceID\ngvImageFiles.DataSourceID = Nothing\ngvImageFiles.DataSource = datatable.DefaultView\ngvImageFiles.DataBind()\ngvImageFiles.DataSource = Nothing\ngvImageFiles.DataSourceID = dataSourceID\n" }, { "answer_id": 12929357, "author": "Eren", "author_id": 1752377, "author_profile": "https://Stackoverflow.com/users/1752377", "pm_score": 2, "selected": false, "text": "grdCommunication.DataBind();\ngrdCommunication.DataSourceID=\"\";\n" }, { "answer_id": 46094277, "author": "amby", "author_id": 6359807, "author_profile": "https://Stackoverflow.com/users/6359807", "pm_score": 0, "selected": false, "text": "try catch raiserror" }, { "answer_id": 48396372, "author": "aries", "author_id": 9255449, "author_profile": "https://Stackoverflow.com/users/9255449", "pm_score": 0, "selected": false, "text": "Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load\n Page.DataBind()\nEnd Sub\nFunction GetData()\n Dim dt As New DataTable\n Try\n\n dt.Columns.Add(\"ROOM_ID\", GetType(String))\n dt.Columns.Add(\"SCHED_ID\", GetType(String))\n dt.Columns.Add(\"TIME_START\", GetType(Date))\n dt.Columns.Add(\"TIME_END\", GetType(Date))\n\n\n Dim dr As DataRow = dt.NewRow\n\n dr(\"ROOM_ID\") = \"Indocin\"\n dr(\"SCHED_ID\") = \"David\"\n dr(\"TIME_START\") = \"2018-01-03 09:00:00.000\"\n dr(\"TIME_END\") = \"2018-01-03 12:00:00.000\"\n dt.Rows.Add(dr)\n\n\n Catch ex As Exception\n MsgBox(ex.ToString)\n End Try\n Return dt\nEnd Function\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269611", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18893/" ]
269,623
<p>I am rather new to complex CSS, and have a question- I have a page which positions a floating element along the bottom of the page. It does so by setting the Bottom: 0, and Position: Absolute. </p> <p>When the user resizes their browser to a very-small size, this element covers up other content on the page.</p> <p>Ideally, The element would continue to float at the bottom of the browser at normal and large sizes, but if the browser window were to be shrunk too small, the browser would force a scrollbar, instead of moving the floating element any further.</p> <p>Essentially, I want to tell the browser- No matter how small the window is, never render the page smaller than 800x600. </p>
[ { "answer_id": 269680, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 1, "selected": false, "text": "html, body { min-width: 800px; min-height: 600px; }" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
269,632
<p>Upon a click on an IMG, I would like to get to the next subsequent DIV so that the DIVs content can either be displayed or hidden depending on its current display state.</p> <p>This is an HTML snippet:</p> <pre><code>&lt;div&gt; &lt;span class="expand"&gt;&lt;img src="images/plus.gif"&gt;&lt;/span&gt; &lt;span&gt;Subject Heading&lt;/span&gt; &lt;/div&gt; &lt;div class="record hidden"&gt;Display or Hide this text&lt;/div&gt; </code></pre> <p>I have some code (<a href="https://stackoverflow.com/questions/123401/using-jquery-to-find-the-next-table-row#123518">provided in another answer on this site</a>) for doing this in a table. Would I set an event listener for the img or the containing span? not sure how to use parent(), next(), sibling() functions to get around....</p> <p>Also, how do you test if your navigation is getting to the right element? can you use an alert to display the id or value?</p> <p>Any help is appreciated Thanks</p>
[ { "answer_id": 269691, "author": "Steve Perks", "author_id": 16124, "author_profile": "https://Stackoverflow.com/users/16124", "pm_score": 0, "selected": false, "text": "$('.expand').click(function () {\n $(\".record\").toggle();\n});\n $('.expand').click(function () {\n $(\".record\").slideToggle(\"slow\");\n});\n" }, { "answer_id": 269711, "author": "Adam Tuttle", "author_id": 751, "author_profile": "https://Stackoverflow.com/users/751", "pm_score": 3, "selected": true, "text": "<script type=\"text/javascript\" src=\"../jquery-1.2.6.min.js\"></script>\n\n<div>\n <span class=\"expand\"><img src=\"x.jpg\"></span>\n <span>Subject Heading</span>\n</div>\n<div class=\"record hidden\">Display or Hide this text</div>\n\n<script type=\"text/javascript\">\n $(document).ready(function(){\n $('.expand img').toggle(\n function(){\n $(this).parent().parent().next().hide();\n },\n function(){\n $(this).parent().parent().next().show();\n });\n });\n</script>\n" }, { "answer_id": 269719, "author": "Pistos", "author_id": 28558, "author_profile": "https://Stackoverflow.com/users/28558", "pm_score": 1, "selected": false, "text": "<html>\n\n<head>\n\n <script type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js\"></script>\n <script type=\"text/javascript\">\n $( document ).ready( function() {\n $( '.expand img' ).click(\n function() {\n $(this).parents( 'div' ).eq( 0 ).siblings( '.record' ).eq( 0 ).toggleClass( 'hidden' );\n }\n );\n } );\n </script>\n\n <style type=\"text/css\">\n .hidden {\n display: none;\n }\n </style>\n\n</head>\n\n<body>\n\n <div>\n <span class=\"expand\"><img src=\"http://stackoverflow.com/Content/Img/stackoverflow-logo-250.png\"></span>\n <span>Subject Heading</span>\n </div>\n <div class=\"other\">Don't care about this</div>\n <div class=\"record hidden\">Display or Hide this text</div>\n\n</body>\n\n</html>\n" }, { "answer_id": 269815, "author": "Jay Corbett", "author_id": 2755, "author_profile": "https://Stackoverflow.com/users/2755", "pm_score": 1, "selected": false, "text": "$(function(){\n$('.expand img').toggle(\n function(){\n $(this).parent().parent().next().show();\n $(this).attr('src', 'images/minus.gif') ;\n },\n function(){\n $(this).parent().parent().next().hide();\n $(this).attr('src', 'images/plus.gif') ;\n });\n});\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2755/" ]
269,653
<p>Does anybody know if there is a way to make autocompletion work in MySQL Command Line Client under Windows? It's working nicely under Linux for me, but simply moves the cursor under Windows instead.</p>
[ { "answer_id": 269750, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 5, "selected": true, "text": "C:\\> mysql --auto-rehash\n [mysql]\nauto-rehash\n mysqlc.exe mysqlc.exe" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9777/" ]
269,657
<p>I want to alert the user in a Swing application of certain events with an old fashioned PC Speaker beep (NOT the soundcard), since not on every PC there is a soundcard with an attached speaker, or volume might be turned to zero, or a headphone might be connected... How can I do this?</p> <p>UPDATE: java.awt.Toolkit.getDefaultToolkit().beep() seems usually to generate a sound on the soundcard. It only uses the speaker if there is no active soundcard. To print an ASCII value 7 works only if the application is launched in a terminal, which at least a Swing app usually isn't. So the question is still open.</p>
[ { "answer_id": 269663, "author": "Michael Myers", "author_id": 13531, "author_profile": "https://Stackoverflow.com/users/13531", "pm_score": 5, "selected": false, "text": "Toolkit.getDefaultToolkit().beep();" }, { "answer_id": 269690, "author": "Paulo Guedes", "author_id": 33857, "author_profile": "https://Stackoverflow.com/users/33857", "pm_score": 3, "selected": false, "text": "java.awt.Toolkit.getDefaultToolkit().beep(); \n" }, { "answer_id": 35260938, "author": "Beginner coder", "author_id": 5896543, "author_profile": "https://Stackoverflow.com/users/5896543", "pm_score": 0, "selected": false, "text": " {\n If (whatever you named the file) = true\n Then\n Process.Start (\"C:\\Windows\\Media\\{whatever you named the file})\n }\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21499/" ]
269,659
<p>I am trying to use a malloc hook to create a custom function my_malloc(). In my main program when I call malloc() I want it to call my_malloc() can someone please give me an example on how to do this in C</p>
[ { "answer_id": 269672, "author": "Alex Gartrell", "author_id": 10307, "author_profile": "https://Stackoverflow.com/users/10307", "pm_score": -1, "selected": false, "text": "#undef malloc\n#define malloc my_malloc\n" }, { "answer_id": 269695, "author": "Randy Stegbauer", "author_id": 34301, "author_profile": "https://Stackoverflow.com/users/34301", "pm_score": 3, "selected": false, "text": "/* Prototypes for __malloc_hook, __free_hook */\n #include <malloc.h>\n\n /* Prototypes for our hooks. */\n static void my_init_hook (void);\n static void *my_malloc_hook (size_t, const void *);\n static void my_free_hook (void*, const void *);\n\n /* Override initializing hook from the C library. */\n void (*__malloc_initialize_hook) (void) = my_init_hook;\n\n static void\n my_init_hook (void)\n {\n old_malloc_hook = __malloc_hook;\n old_free_hook = __free_hook;\n __malloc_hook = my_malloc_hook;\n __free_hook = my_free_hook;\n }\n\n static void *\n my_malloc_hook (size_t size, const void *caller)\n {\n void *result;\n /* Restore all old hooks */\n __malloc_hook = old_malloc_hook;\n __free_hook = old_free_hook;\n /* Call recursively */\n result = malloc (size);\n /* Save underlying hooks */\n old_malloc_hook = __malloc_hook;\n old_free_hook = __free_hook;\n /* printf might call malloc, so protect it too. */\n printf (\"malloc (%u) returns %p\\n\", (unsigned int) size, result);\n /* Restore our own hooks */\n __malloc_hook = my_malloc_hook;\n __free_hook = my_free_hook;\n return result;\n }\n\n static void\n my_free_hook (void *ptr, const void *caller)\n {\n /* Restore all old hooks */\n __malloc_hook = old_malloc_hook;\n __free_hook = old_free_hook;\n /* Call recursively */\n free (ptr);\n /* Save underlying hooks */\n old_malloc_hook = __malloc_hook;\n old_free_hook = __free_hook;\n /* printf might call free, so protect it too. */\n printf (\"freed pointer %p\\n\", ptr);\n /* Restore our own hooks */\n __malloc_hook = my_malloc_hook;\n __free_hook = my_free_hook;\n }\n\n main ()\n {\n ...\n }\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
269,660
<p>Does anyone know how to iterate over a generic list if the type of that list isn't known until runtime?</p> <p>For example, assume <code>obj1</code> is passed into a function as an <code>Object</code>:</p> <pre><code>Dim t As Type = obj1.GetType If t.IsGenericType Then Dim typeParameters() As Type = t.GetGenericArguments() Dim typeParam As Type = typeParameters(0) End If </code></pre> <p>If <code>obj</code> is passed as a <code>List(Of String)</code> then using the above I can determine that a generic list (<code>t</code>) was passed and that it's of type <code>String</code> (<code>typeParam</code>). I know I am making a big assumption that there is only one generic parameter, but that's fine for this simple example.</p> <p>What I'd like to know is, based on the above, how do I do something like this:</p> <pre><code>For Each item As typeParam In obj1 'do something with it here Next </code></pre> <p>Or even something as simple as getting <code>obj1.Count()</code>.</p>
[ { "answer_id": 269807, "author": "Todd", "author_id": 2572, "author_profile": "https://Stackoverflow.com/users/2572", "pm_score": 2, "selected": false, "text": "Public Sub Foo(Of T)(list As List(Of T))\n For Each obj As T In list\n ..do something with obj..\n Next\nEnd Sub\n Dim list As New List(Of String)\nFoo(Of String)(list)\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12842/" ]
269,669
<p>Either for comparisons or initialization of a new variable, does it make a difference which one of these you use?</p> <p>I know that BigDecimal.ZERO is a 1.5 feature, so that's a concern, but assuming I'm using 1.5 does it matter?</p> <p>Thanks.</p>
[ { "answer_id": 269684, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 6, "selected": true, "text": "BigDecimal.ZERO BigDecimal(\"0\") BigDecimal.ZERO BigDecimal(\"0\") BigDecimal.ZERO" }, { "answer_id": 642907, "author": "ordnungswidrig", "author_id": 9069, "author_profile": "https://Stackoverflow.com/users/9069", "pm_score": 2, "selected": false, "text": "Bigdecimal.ZERO new BigDecimal(\"9\")" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3098/" ]
269,676
<p>I want to make my Python library working with MySQLdb be able to detect deadlocks and try again. I believe I've coded a good solution, and now I want to test it.</p> <p>Any ideas for the simplest queries I could run using MySQLdb to create a deadlock condition would be?</p> <p>system info:</p> <ul> <li>MySQL 5.0.19 </li> <li>Client 5.1.11 </li> <li>Windows XP</li> <li>Python 2.4 / MySQLdb 1.2.1 p2</li> </ul>
[ { "answer_id": 270492, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": 1, "selected": false, "text": " Begin Transaction \n Insert TableA() Values()... \n Begin Transaction\n Insert TableB() Values()... \n Insert TableA() Values() ...\n Insert TableB() Values () ...\n" }, { "answer_id": 271789, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 1, "selected": false, "text": "import subprocess\nc1= subprocess.Popen( [\"python\", \"child.py\", \"1\"], stdin=subprocess.PIPE, stdout=subprocess.PIPE )\nc2= subprocess.Popen( [\"python\", \"child.py\", \"2\"], stdin=subprocess.PIPE, stdout=subprocess.PIPE )\nout1, err1= c1.communicate( \"to 1: hit it!\" )\nprint \" 1:\", repr(out1)\nprint \"*1:\", repr(err1)\nout2, err2= c2.communicate( \"to 2: ready, set, go!\" )\nprint \" 2:\", repr(out2)\nprint \"*2:\", repr(err2)\nout1, err1= c1.communicate()\nprint \" 1:\", repr(out1)\nprint \"*1:\", repr(err1)\nout2, err2= c2.communicate()\nprint \" 2:\", repr(out2)\nprint \"*2:\", repr(err2)\nc1.wait()\nc2.wait()\n import yourDBconnection as dbapi2\n\ndef child1():\n print \"Child 1 start\"\n conn= dbapi2.connect( ... )\n c1= conn.cursor()\n conn.begin() # turn off autocommit, start a transaction\n ra= c1.execute( \"UPDATE A SET AC1='Achgd' WHERE AC1='AC1-1'\" )\n print ra\n print \"Child1\", raw_input()\n rb= c1.execute( \"UPDATE B SET BC1='Bchgd' WHERE BC1='BC1-1'\" )\n print rb\n c1.close()\n print \"Child 1 finished\"\n\ndef child2():\n print \"Child 2 start\"\n conn= dbapi2.connect( ... )\n c1= conn.cursor()\n conn.begin() # turn off autocommit, start a transaction\n rb= c1.execute( \"UPDATE B SET BC1='Bchgd' WHERE BC1='BC1-1'\" )\n print rb\n print \"Child2\", raw_input()\n ra= c1.execute( \"UPDATE A SET AC1='Achgd' WHERE AC1='AC1-1'\" )\n print ta\n c1.close()\n print \"Child 2 finish\"\n\ntry:\n if sys.argv[1] == \"1\":\n child1()\n else:\n child2()\nexcept Exception, e:\n print repr(e)\n time.sleep( 0.001 )" }, { "answer_id": 8100573, "author": "leiavoia", "author_id": 1042374, "author_profile": "https://Stackoverflow.com/users/1042374", "pm_score": 2, "selected": false, "text": "START TRANSACTION;\nINSERT INTO table <anything you want>;\nSLEEP(5);\nUPDATE table SET field = 'foo';\nCOMMIT;\n START TRANSACTION;\nUPDATE table SET field = 'foo';\nSLEEP(5);\nINSERT INTO table <anything you want>;\nCOMMIT;\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269676", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13009/" ]
269,692
<p>I have a clock feature in a VB.NET program that displays the time including the seconds. I currently have a timer constantly polling using NOW. I have to poll the system clock quite often because I need to have the second update in sync with the system clock.</p> <p>Is there a more direct to access the time only when the seconds change?</p> <p>Is there a more efficient way to write this code?</p> <p>If you need more info let me know.</p>
[ { "answer_id": 269738, "author": "Jason Z", "author_id": 2470, "author_profile": "https://Stackoverflow.com/users/2470", "pm_score": 4, "selected": true, "text": "Public Class Form1\n Private WithEvents clockTimer As New Timer\n Private currentTime As DateTime = DateTime.MinValue\n\n Private Sub ClockTick(ByVal sender As Object, _\n ByVal e As System.EventArgs) Handles clockTimer.Tick\n\n UpdateTimer()\n DisplayTimer()\n End Sub\n\n Private Sub UpdateTimer()\n currentTime = DateTime.Now\n\n clockTimer.Stop()\n clockTimer.Interval = 1000 - currentTime.Millisecond\n clockTimer.Start()\n End Sub\n\n Private Sub DisplayTimer()\n lblTime.Text = currentTime.ToString(\"T\")\n End Sub\n\n Private Sub Form1_Load(ByVal sender As System.Object, _\n ByVal e As System.EventArgs) Handles MyBase.Load\n\n UpdateTimer()\n DisplayTimer()\n End Sub\nEnd Class\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4856/" ]
269,703
<p>I have an app with the following basic architecture:</p> <p>A windows service (Service) that registers a .NET type (RemoteObject) for remote access (.NET Remoting). RemoteObject creates non-ThreadPool threads that use the ThreadPool to do IO processing. The size of the ThreadPool must be restricted to a limit for a particular reason. A GUI app uses .NET Remoting to access RemoteObject. </p> <p>I've noticed that if the size of the ThreadPool is too low, the GUI app will hang when making a call to RemoteObject.</p> <p>My question is, how can I figure out why this is hanging, and why would the RemoteObject thread be affected by the ThreadPool?</p> <p>This is driving me crazy; thank you for your help!</p>
[ { "answer_id": 269808, "author": "vfilby", "author_id": 24279, "author_profile": "https://Stackoverflow.com/users/24279", "pm_score": 2, "selected": false, "text": "SERVICE_DEBUG #if !' #if SERVICE_DEBUG\n ServiceHost s = new ServiceHost();\n s.DebugService();\n Thread.Sleep( 300000000 );\n\n#else\n ServiceBase.Run( ServicesToRun );\n#endif\n" }, { "answer_id": 269886, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "#if DEBUG\n if (!System.Diagnostics.Debugger.IsAttached)\n Debugger.Launch();\n#endif\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7529/" ]
269,713
<p>We have a current application where user login credentials are stored in a SQL Server DB. These are, basically, stored as a plain text username, a password hash, and an associated salt for this hash.</p> <p>These were all created by built in functions in ASP.NET's membership/role system. Here's a row for a user named 'joe' and a password of 'password':</p> <blockquote> <p>joe,kDP0Py2QwEdJYtUX9cJABg==,OJF6H4KdxFLgLu+oTDNFodCEfMA=</p> </blockquote> <p>I've dumped this stuff into a CSV file and I'm attempting to get it into a usable format for Django which stores its passwords in this format:</p> <p>[algo]$[salt]$[hash]</p> <p>Where the salt is a plain string and the hash is the hex digest of an SHA1 hash.</p> <p>So far I've been able to ascertain that ASP is storing these hashes and salts in a base64 format. Those values above decode into binary strings.</p> <p>We've used reflector to glean how ASP authenticates against these values:</p> <pre><code>internal string EncodePassword(string pass, int passwordFormat, string salt) { if (passwordFormat == 0) { return pass; } byte[] bytes = Encoding.Unicode.GetBytes(pass); byte[] src = Convert.FromBase64String(salt); byte[] dst = new byte[src.Length + bytes.Length]; byte[] inArray = null; Buffer.BlockCopy(src, 0, dst, 0, src.Length); Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length); if (passwordFormat == 1) { HashAlgorithm algorithm = HashAlgorithm.Create(Membership.HashAlgorithmType); if ((algorithm == null) &amp;&amp; Membership.IsHashAlgorithmFromMembershipConfig) { RuntimeConfig.GetAppConfig().Membership.ThrowHashAlgorithmException(); } inArray = algorithm.ComputeHash(dst); } else { inArray = this.EncryptPassword(dst); } return Convert.ToBase64String(inArray); } </code></pre> <p>Eseentially, pulls in the salt from the DB and b64 decodes it into a binary representation. It does a "GetBytes" on the raw password and then it concatinates them, salt first.</p> <p>It then runs the SHA1 algorithm on this new string, base64 encodes it, and compares it against the value stored in the database.</p> <p>I've attempted to write some code to try and reproduce these hashes in Python and I'm failing. I won't be able to use them in Django until I can figure out how this translates over. Here's how I'm testing:</p> <pre><code>import hashlib from base64 import b64decode, b64encode b64salt = "kDP0Py2QwEdJYtUX9cJABg==" b64hash = "OJF6H4KdxFLgLu+oTDNFodCEfMA=" binsalt = b64decode(b64salt) password_string = 'password' m1 = hashlib.sha1() # Pass in salt m1.update(binsalt) # Pass in password m1.update(password_string) # B64 encode the binary digest if b64encode(m1.digest()) == b64hash: print "Logged in!" else: print "Didn't match" print b64hash print b64encode(m1.digest()) </code></pre> <p>I'm wondering if anyone can see any flaws in my approach or can suggest an alternate method. Perhaps you can take the algorithms above and the known password and salt above and produce the hash on your system?</p>
[ { "answer_id": 269888, "author": "grieve", "author_id": 34329, "author_profile": "https://Stackoverflow.com/users/34329", "pm_score": 0, "selected": false, "text": "0x00 0x70 0x00 0x61 0x00 0x73 0x00 0x73 0x00 0x77 0x00 0x6F 0x00 0x72 0x00 0x64\n 0x70 0x61 0x73 0x73 0x77 0x6F 0x72 0x64\n" }, { "answer_id": 270670, "author": "MrKurt", "author_id": 35296, "author_profile": "https://Stackoverflow.com/users/35296", "pm_score": 4, "selected": true, "text": "import hashlib\nfrom base64 import b64decode, b64encode\n\ndef utf16tobin(s):\n return s.encode('hex')[4:].decode('hex')\n\nb64salt = \"kDP0Py2QwEdJYtUX9cJABg==\"\nb64hash = \"OJF6H4KdxFLgLu+oTDNFodCEfMA=\"\nbinsalt = b64decode(b64salt)\npassword_string = 'password'.encode(\"utf16\")\npassword_string = utf16tobin(password_string)\n\nm1 = hashlib.sha1()\n# Pass in salt\nm1.update(binsalt + password_string)\n# Pass in password\n# B64 encode the binary digest\nif b64encode(m1.digest()) == b64hash:\n print \"Logged in!\"\nelse:\n print \"Didn't match\"\n print b64hash\n print b64encode(m1.digest())\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13668/" ]
269,720
<p>I'm looking for a good way to run a Apache Derby server in network mode. I'm using the NetworkServerControl to start the server and it's working great.</p> <p>I start the server like this:</p> <pre><code>/** * starts the network server * @return true if sucessfull */ public boolean start() { try { // just to be sure that we don't start two servers this.stop(); server = new NetworkServerControl(); server.start( null ); return true; } catch ( Exception ex ) { this.logLogger.debug( ex ); return false; } } </code></pre> <p>And stop it like this:</p> <pre><code>/** * stops the server * * @return true if there were no problems stopping the server */ public boolean stop() { try { if ( server == null ) { server = new NetworkServerControl(); } server.shutdown(); return true; } catch ( Exception ex ) { this.logLogger.debug( ex ); return false; } } </code></pre> <p>On the main() I have this so the process doesn't die while the server is running</p> <pre><code>(...) clsDB.start(); while( clsDB.testForConnection() ) { Thread.sleep( 60000 ); } </code></pre> <p>testForConnection() looks like this:</p> <pre><code>/** * Try to test for a connection * * @return true if the server is alive */ public boolean testForConnection() { try { server.ping(); return true; } catch ( Exception ex ) { this.logLogger.debug( ex ); return false; } } </code></pre> <p>My problem is that when a new instace of my JAR is called the old one will still be running (unless I'm really really lucky and the test is made before the new server is started).</p> <p>I know I could just test if the server is already running and then I wouldn't start again, but I would like for start to work like a restart if the server is already there.</p>
[ { "answer_id": 269765, "author": "SCdF", "author_id": 1666, "author_profile": "https://Stackoverflow.com/users/1666", "pm_score": 2, "selected": false, "text": "DriverManager.getConnection(\n \"jdbc:derby:sample;shutdown=true\");\n" }, { "answer_id": 269801, "author": "SCdF", "author_id": 1666, "author_profile": "https://Stackoverflow.com/users/1666", "pm_score": 1, "selected": false, "text": "stop() success start()" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2216428/" ]
269,721
<p>According to <a href="http://en.wikipedia.org/wiki/Rounding" rel="noreferrer">Wikipedia</a> when rounding a negative number, you round the absolute number. So by that reasoning, -3.5 would be rounded to -4. But when I use java.lang.Math.round(-3.5) returns -3. Can someone please explain this?</p>
[ { "answer_id": 269735, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 5, "selected": true, "text": "(long)Math.floor(a + 0.5d)" }, { "answer_id": 269746, "author": "Paulo Guedes", "author_id": 33857, "author_profile": "https://Stackoverflow.com/users/33857", "pm_score": 2, "selected": false, "text": "long long" }, { "answer_id": 269971, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "java.math.BigDecimal" }, { "answer_id": 73205914, "author": "Ankit Panday", "author_id": 19554834, "author_profile": "https://Stackoverflow.com/users/19554834", "pm_score": 0, "selected": false, "text": "//for Example dividing an Int A with 200 ; \npublic class Solution {\n public int solve(int A) {\n double B = (double) A /200;\n \n \n if (B<0){\n B= (int) Math.round(Math.abs(B));\n return (int) B * -1 ;\n }\n else{\n B= (int) Math.round(B);\n return (int) B ;\n }\n \n \n \n }\n }\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23249/" ]
269,722
<p>We are using feature branches in Subversion for our development which is a very convenient way of keeping code within version control that is not yet ready for the mainline. However, whenever I go to merge the feature branch revision into the mainline it is a pain. Right now I go through the following steps:</p> <ol> <li>Check out the original feature branch revision to a new directory</li> <li>Perform a difference between my current development and the original feature branch directories with a tool like Beyond Compare</li> <li>Check out the current mainline revision to a new directory</li> <li>Merge the new/changed files into the current mainline directory.</li> <li>Perform a difference using my IDE to ensure all of the files are properly checked out/added to subversion</li> <li>Compile and test</li> <li>Commit</li> </ol> <p>It seems to me that there is a lot of room for errors in this process and it makes me nervous every time I walk through the steps. Granted, everything is checked into Subversion on my feature branch, so a mistake at any step is recoverable. </p> <p>I believe that Subversion 1.5 has a way to merge a branch into the mainline, but we are still using Subversion 1.4. What are other people using to simplify the steps of merging a feature branch in Subversion into their mainline development? Are you using different tools? Are you utilizing the merging feature in Subversion 1.5?</p>
[ { "answer_id": 269760, "author": "Carl Seleborg", "author_id": 2095, "author_profile": "https://Stackoverflow.com/users/2095", "pm_score": 2, "selected": false, "text": "svn merge \"LASTSYNC\":HEAD svn://path/to/FeatureBranch ." } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4599/" ]
269,759
<p>I am writing a simple xml string to an MSMQ from a VB6 app, but when I attempt to read the message off the queue in C# using the XmlMessageFormatter I get the following error:</p> <p>"Name cannot begin with the '.' character"</p> <p>How do I successfully read these messages using .Net code?</p>
[ { "answer_id": 31191260, "author": "earthling42", "author_id": 1328604, "author_profile": "https://Stackoverflow.com/users/1328604", "pm_score": 0, "selected": false, "text": " private static string MsmqMsgBodyWtf(Message recalcitrantMsmqMessage, bool showHex = false, bool showChars = false)\n {\n recalcitrantMsmqMessage.Formatter = new ActiveXMessageFormatter();\n byte[] bytes = (byte[])recalcitrantMsmqMessage.Formatter.Read(recalcitrantMsmqMessage);\n StringBuilder dottedHex = new StringBuilder();\n StringBuilder dottedAscii = new StringBuilder();\n StringBuilder plainAscii = new StringBuilder();\n\n for (int i = 0; i < bytes.Length; i++)\n {\n byte b = bytes[i];\n\n string hexString;\n hexString = String.Format(\"{0:x2}\", b);\n dottedHex.Append(hexString + \".\");\n\n string charString = byte2char(b);\n string escapedCharString = (b > 31 && b < 128) ? charString : \"?\";\n dottedAscii.Append(escapedCharString + \" .\");\n plainAscii.Append(escapedCharString);\n }\n\n StringBuilder composedOutput = new StringBuilder(plainAscii.ToString());\n if (showHex || showChars) composedOutput.Append(System.Environment.NewLine);\n if (showHex) composedOutput.AppendLine(dottedHex.ToString());\n if (showChars) composedOutput.AppendLine(dottedAscii.ToString());\n\n return composedOutput.ToString(); ;\n }\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
269,761
<p>Please consider the following:</p> <pre><code>&lt;td style="width: 500px;"&gt; &lt;div style="width: 400px;"&gt;SomeContent&lt;/div&gt; &lt;/td&gt; </code></pre> <p>For some reason, the column that contains a div will not expand to 500px as the style suggests.</p> <p>Do you know how to get the td to honor the width that I am specifying in the style?</p>
[ { "answer_id": 269793, "author": "Steve Perks", "author_id": 16124, "author_profile": "https://Stackoverflow.com/users/16124", "pm_score": 0, "selected": false, "text": "<td style=\"width: 500px\">\n <div style=\"padding: 0 50px\">SomeContent</div>\n</td>\n" }, { "answer_id": 269975, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 0, "selected": false, "text": "<td style=\"width:500px;\">\n <div style=\"width:100%;\">SomeContent</div>\n</td>\n <td style=\"max-width:500px;\">\n <div style=\"width:100%;\">SomeContent</div>\n</td>\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10589/" ]
269,773
<p>I am using a custom item renderer in a combobox to display a custom drawing instead of the default text label.</p> <p>This works fine for the dropdown list but the displayed item ( when the list is closed) is still the textual representation of my object.</p> <p>Is there a way to have the displayed item rendered the same way as the one in the dropdown?</p>
[ { "answer_id": 280859, "author": "Matt MacLean", "author_id": 22, "author_profile": "https://Stackoverflow.com/users/22", "pm_score": 4, "selected": true, "text": "package\n{\n import mx.controls.ComboBox;\n import mx.core.UIComponent;\n\n public class ComboBox2 extends ComboBox\n {\n public function ComboBox2()\n {\n super();\n }\n\n protected var textInputReplacement:UIComponent;\n\n override protected function createChildren():void {\n super.createChildren();\n\n if ( !textInputReplacement ) {\n if ( itemRenderer != null ) {\n //remove the default textInput\n removeChild(textInput);\n\n //create a new itemRenderer to use in place of the text input\n textInputReplacement = itemRenderer.newInstance();\n addChild(textInputReplacement);\n }\n }\n }\n\n override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void {\n super.updateDisplayList(unscaledWidth, unscaledHeight);\n\n if ( textInputReplacement ) {\n textInputReplacement.width = unscaledWidth;\n textInputReplacement.height = unscaledHeight;\n }\n }\n }\n}\n" }, { "answer_id": 1782090, "author": "Maurits de Boer", "author_id": 94870, "author_profile": "https://Stackoverflow.com/users/94870", "pm_score": 3, "selected": false, "text": " if ( !textInputReplacement ) {\n if ( itemRenderer != null ) {\n //remove the default textInput\n removeChild(textInput);\n\n //create a new itemRenderer to use in place of the text input\n textInputReplacement = itemRenderer.newInstance();\n\n // ADD THIS BINDING:\n // Bind the data of the textInputReplacement to the selected item\n BindingUtils.bindProperty(textInputReplacement, \"data\", this, \"selectedItem\", true);\n\n addChild(textInputReplacement);\n }\n }\n" }, { "answer_id": 2446068, "author": "Dane", "author_id": 238751, "author_profile": "https://Stackoverflow.com/users/238751", "pm_score": 0, "selected": false, "text": "package\n{\n import mx.binding.utils.BindingUtils;\n import mx.controls.ComboBox;\n import mx.core.IFactory;\n import mx.core.UIComponent;\n\n public class ComboBox2 extends ComboBox\n {\n public function ComboBox2()\n {\n super();\n }\n\n protected var textInputReplacement:UIComponent;\n private var _increaseW:Number = 0;\n private var _increaseH:Number = 0;\n\n public function set increaseW(val:Number):void\n {\n _increaseW = val;\n }\n\n public function set increaseH(val:Number):void\n {\n _increaseH = val;\n }\n\n override public function set itemRenderer(value:IFactory):void\n {\n super.itemRenderer = value;\n replaceTextInput();\n }\n\n override protected function createChildren():void \n {\n super.createChildren();\n replaceTextInput();\n\n }\n\n override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void {\n\n unscaledWidth += _increaseW;\n unscaledHeight += _increaseH;\n\n super.updateDisplayList(unscaledWidth, unscaledHeight);\n\n if ( textInputReplacement ) {\n textInputReplacement.width = unscaledWidth - 25;\n textInputReplacement.height = unscaledHeight;\n }\n }\n\n protected function replaceTextInput():void\n {\n if ( !textInputReplacement ) {\n if ( this.itemRenderer != null ) {\n //remove the default textInput\n removeChild(textInput);\n\n //create a new itemRenderer to use in place of the text input\n textInputReplacement = this.itemRenderer.newInstance();\n addChild(textInputReplacement);\n\n // ADD THIS BINDING:\n // Bind the data of the textInputReplacement to the selected item\n BindingUtils.bindProperty(textInputReplacement, \"data\", this, \"selectedItem\", true);\n\n addChild(textInputReplacement);\n\n }\n }\n }\n }\n}\n" }, { "answer_id": 7744558, "author": "sixtyfootersdude", "author_id": 251589, "author_profile": "https://Stackoverflow.com/users/251589", "pm_score": 0, "selected": false, "text": "<s:SparkSkin>\n\n <... Lots of other stuff/>\n\n <s:BorderContainer height=\"25\">\n <WHATEVER YOU NEED HERE!/>\n </s:BorderContainer>\n\n <!-- Disable the textInput and hide it -->\n <s:TextInput id=\"textInput\"\n left=\"0\" right=\"18\" top=\"0\" bottom=\"0\" \n skinClass=\"spark.skins.spark.ComboBoxTextInputSkin\"\n\n visible=\"false\" enabled=\"false\"/> \n\n\n</s:SparkSkin>\n" }, { "answer_id": 32511399, "author": "Paulo Enmanuel", "author_id": 1541093, "author_profile": "https://Stackoverflow.com/users/1541093", "pm_score": 0, "selected": false, "text": "TextInput ComboBase.createChildren textInput textInputClass // Mechanism to use MXFTETextInput. \nvar textInputClass:Class = getStyle(\"textInputClass\"); \nif (!textInputClass || FlexVersion.compatibilityVersion < FlexVersion.VERSION_4_0)\n{\n textInput = new TextInput();\n}\nelse\n{\n textInput = new textInputClass();\n}\n selectedItem public function ComboAvailableProfessor()\n{\n super();\n\n itemRenderer = new ClassFactory( ProfessorAvailableListItemRenderer );\n setStyle( 'textInputClass', ProfessorAvailableSelectedListItemRenderer );\n}\n data selectedItem override protected function createChildren():void\n{\n super.createChildren();\n\n BindingUtils.bindProperty( textInput, 'data', this, 'selectedItem', true );\n}\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2011/" ]
269,774
<p>I've got a solution which I setup / cleanup using batch files ... - there are a pair of MSMQ ports, send and receive, with another application on the end of the queues</p> <p>I'm finding I can't properly stop the orchestration in the batch file ... the error is the send port is unenlisted - I'm using the StopOrch.vbs script from the SDK samples</p> <p>But I can go into BizTalk Admin Console and manually stop the orchestration with Full Terminate Ok</p> <p>The setup / cleanup works Ok if I don't actually push any messages down the MSMQ queues</p>
[ { "answer_id": 280859, "author": "Matt MacLean", "author_id": 22, "author_profile": "https://Stackoverflow.com/users/22", "pm_score": 4, "selected": true, "text": "package\n{\n import mx.controls.ComboBox;\n import mx.core.UIComponent;\n\n public class ComboBox2 extends ComboBox\n {\n public function ComboBox2()\n {\n super();\n }\n\n protected var textInputReplacement:UIComponent;\n\n override protected function createChildren():void {\n super.createChildren();\n\n if ( !textInputReplacement ) {\n if ( itemRenderer != null ) {\n //remove the default textInput\n removeChild(textInput);\n\n //create a new itemRenderer to use in place of the text input\n textInputReplacement = itemRenderer.newInstance();\n addChild(textInputReplacement);\n }\n }\n }\n\n override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void {\n super.updateDisplayList(unscaledWidth, unscaledHeight);\n\n if ( textInputReplacement ) {\n textInputReplacement.width = unscaledWidth;\n textInputReplacement.height = unscaledHeight;\n }\n }\n }\n}\n" }, { "answer_id": 1782090, "author": "Maurits de Boer", "author_id": 94870, "author_profile": "https://Stackoverflow.com/users/94870", "pm_score": 3, "selected": false, "text": " if ( !textInputReplacement ) {\n if ( itemRenderer != null ) {\n //remove the default textInput\n removeChild(textInput);\n\n //create a new itemRenderer to use in place of the text input\n textInputReplacement = itemRenderer.newInstance();\n\n // ADD THIS BINDING:\n // Bind the data of the textInputReplacement to the selected item\n BindingUtils.bindProperty(textInputReplacement, \"data\", this, \"selectedItem\", true);\n\n addChild(textInputReplacement);\n }\n }\n" }, { "answer_id": 2446068, "author": "Dane", "author_id": 238751, "author_profile": "https://Stackoverflow.com/users/238751", "pm_score": 0, "selected": false, "text": "package\n{\n import mx.binding.utils.BindingUtils;\n import mx.controls.ComboBox;\n import mx.core.IFactory;\n import mx.core.UIComponent;\n\n public class ComboBox2 extends ComboBox\n {\n public function ComboBox2()\n {\n super();\n }\n\n protected var textInputReplacement:UIComponent;\n private var _increaseW:Number = 0;\n private var _increaseH:Number = 0;\n\n public function set increaseW(val:Number):void\n {\n _increaseW = val;\n }\n\n public function set increaseH(val:Number):void\n {\n _increaseH = val;\n }\n\n override public function set itemRenderer(value:IFactory):void\n {\n super.itemRenderer = value;\n replaceTextInput();\n }\n\n override protected function createChildren():void \n {\n super.createChildren();\n replaceTextInput();\n\n }\n\n override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void {\n\n unscaledWidth += _increaseW;\n unscaledHeight += _increaseH;\n\n super.updateDisplayList(unscaledWidth, unscaledHeight);\n\n if ( textInputReplacement ) {\n textInputReplacement.width = unscaledWidth - 25;\n textInputReplacement.height = unscaledHeight;\n }\n }\n\n protected function replaceTextInput():void\n {\n if ( !textInputReplacement ) {\n if ( this.itemRenderer != null ) {\n //remove the default textInput\n removeChild(textInput);\n\n //create a new itemRenderer to use in place of the text input\n textInputReplacement = this.itemRenderer.newInstance();\n addChild(textInputReplacement);\n\n // ADD THIS BINDING:\n // Bind the data of the textInputReplacement to the selected item\n BindingUtils.bindProperty(textInputReplacement, \"data\", this, \"selectedItem\", true);\n\n addChild(textInputReplacement);\n\n }\n }\n }\n }\n}\n" }, { "answer_id": 7744558, "author": "sixtyfootersdude", "author_id": 251589, "author_profile": "https://Stackoverflow.com/users/251589", "pm_score": 0, "selected": false, "text": "<s:SparkSkin>\n\n <... Lots of other stuff/>\n\n <s:BorderContainer height=\"25\">\n <WHATEVER YOU NEED HERE!/>\n </s:BorderContainer>\n\n <!-- Disable the textInput and hide it -->\n <s:TextInput id=\"textInput\"\n left=\"0\" right=\"18\" top=\"0\" bottom=\"0\" \n skinClass=\"spark.skins.spark.ComboBoxTextInputSkin\"\n\n visible=\"false\" enabled=\"false\"/> \n\n\n</s:SparkSkin>\n" }, { "answer_id": 32511399, "author": "Paulo Enmanuel", "author_id": 1541093, "author_profile": "https://Stackoverflow.com/users/1541093", "pm_score": 0, "selected": false, "text": "TextInput ComboBase.createChildren textInput textInputClass // Mechanism to use MXFTETextInput. \nvar textInputClass:Class = getStyle(\"textInputClass\"); \nif (!textInputClass || FlexVersion.compatibilityVersion < FlexVersion.VERSION_4_0)\n{\n textInput = new TextInput();\n}\nelse\n{\n textInput = new textInputClass();\n}\n selectedItem public function ComboAvailableProfessor()\n{\n super();\n\n itemRenderer = new ClassFactory( ProfessorAvailableListItemRenderer );\n setStyle( 'textInputClass', ProfessorAvailableSelectedListItemRenderer );\n}\n data selectedItem override protected function createChildren():void\n{\n super.createChildren();\n\n BindingUtils.bindProperty( textInput, 'data', this, 'selectedItem', true );\n}\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27756/" ]
269,781
<p>Is there an easy way to convert a string that contains this:</p> <pre><code>Date: Wed, 5 Nov 2008 13:12:12 -0500 (EST) </code></pre> <p>into a string that contains this:</p> <pre><code>20081105_131212 </code></pre> <p><strong>UPDATE:</strong><br> I ended up using date.tryparse which is similar to tryParseExact except you don't have to specify the format string. I did have to eliminate the () and the EST for this to work. The date string will always be EST because the date string comes from 1 web server.</p> <p>Original string: <br></p> <pre><code>Date: Wed, 5 Nov 2008 13:12:12 -0500 (EST) </code></pre> <p>Using this code: <br></p> <pre><code>buff1.Remove(0, 6).Replace("(", "").Replace(")", "").Replace("EST", "").Trim() </code></pre> <p>Becomes this string: <br></p> <pre><code>Wed, 5 Nov 2008 13:12:12 -0500 </code></pre> <p>Then I can format appropriately to generate my filename date using this:</p> <pre><code> If Date.TryParse(buff1, dateValue) Then MsgBox(Format(dateValue, "yyyyMMdd_HHmmss")) Else MsgBox("nope") End If </code></pre>
[ { "answer_id": 269841, "author": "Salman Kasbati", "author_id": 33931, "author_profile": "https://Stackoverflow.com/users/33931", "pm_score": 0, "selected": false, "text": "Format(date, \"yyyyMMdd_HHmmss\")" }, { "answer_id": 269883, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 1, "selected": false, "text": "Date.Parse ToString() Date.Parse(YourDateString).ToString(\"yyyyMMdd_HHmmss\")\n" }, { "answer_id": 269915, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 4, "selected": true, "text": "Date.Parse Date.TryParseExact() .ToString(\"yyyyMMdd_HHmmss\")" }, { "answer_id": 269942, "author": "Kevin Fairchild", "author_id": 3743, "author_profile": "https://Stackoverflow.com/users/3743", "pm_score": 0, "selected": false, "text": "Dim strDateVal As String = \"Date: Wed, 5 Nov 2008 13:12:12 -0500 (EST)\"\nstrDateVal = strDateVal.Substring(strDateVal.IndexOf(\", \") + 2, strDateVal.Length - strDateVal.IndexOf(\", \") - 2)\nstrDateVal = strDateVal.Substring(0, strDateVal.LastIndexOf(\" \")).TrimEnd\nDim DateVal As Date = Date.Parse(strDateVal)\nDim NewStringVal As String = Format(DateVal, \"yyyyMMdd_HHmmss\")\n" }, { "answer_id": 269956, "author": "RS Conley", "author_id": 7890, "author_profile": "https://Stackoverflow.com/users/7890", "pm_score": 1, "selected": false, "text": "Function ConvertDateString(ByVal Original As String) As String\n Dim Elements As String() = Split(Original, \" \")\n Dim DateString As String = Elements(3) & \" \" & Elements(2) & \" \" & Elements(4) & \" \" & Elements(5)\n Return Date.Parse(DateString).ToString(\"yyyyMMdd_HHmmsss\")\nEnd Function\n" }, { "answer_id": 1480998, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "Dim strDateVal As String = \"Date: Wed, 5 Nov 2008 13:12:12 -0500 (EST)\"\n\nstrDateVal = strDateVal.Substring(strDateVal.IndexOf(\", \") + 2, \nstrDateVal.Length - strDateVal.IndexOf(\", \") - 2)\n\nstrDateVal = strDateVal.Substring(0, strDateVal.LastIndexOf(\" \")).TrimEnd\n\nDim DateVal As Date = Date.Parse(strDateVal)\nDim NewStringVal As String = Format(DateVal, \"ddMMyyyy_HHmmss\")\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24721/" ]
269,782
<p>I have a really simple WPF UserControl:</p> <pre><code>&lt;UserControl x:Class="dr.SitecoreCompare.WPF.ConnectionEntry" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Name="connEntry" BorderBrush="Navy" BorderThickness="1" Margin="5,0,0,5" &gt; &lt;StackPanel Margin="0,10,0,0" &gt; &lt;Label FontWeight="ExtraBold" Content="{Binding ElementName=connEntry, Path=Title}"&gt;&lt;/Label&gt; &lt;Label Margin="0,5,0,0"&gt;Server:&lt;/Label&gt; &lt;TextBox x:Name="txtServer" TabIndex="1" Text="{Binding Path=ServerName}" &gt;&lt;/TextBox&gt; &lt;Label&gt;Database:&lt;/Label&gt; &lt;TextBox x:Name="txtDatabase" TabIndex="2" Text="{Binding Path=DatabaseName}"&gt;&lt;/TextBox&gt; &lt;/StackPanel&gt; </code></pre> <p></p> <p>This is used twice in the same window. Now, I can select the first TextBox on both th instances of my UserControl, but the second ("txtDatabase") textbox cannot be selected, neither by tabbing or clicking. Why is this ? Am I missing something with regards to creating WPF usercontrols ? </p> <p>EDIT: DatabaseName is not readonly, it is a simple property. The XAML for the window the usercontrol is placed on looks like this:</p> <pre><code>&lt;Window x:Class="dr.SitecoreCompare.WPF.ProjectDialog" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:c="clr-namespace:dr.SitecoreCompare.WPF" Title="Choose project" Height="280" Width="500" WindowStartupLocation="CenterOwner" WindowStyle="SingleBorderWindow" HorizontalAlignment="Center" ShowInTaskbar="False" ShowActivated="True" ResizeMode="NoResize" VerticalContentAlignment="Top" VerticalAlignment="Center"&gt; &lt;StackPanel&gt; &lt;Label&gt;Choose databases&lt;/Label&gt; &lt;Grid&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition /&gt; &lt;ColumnDefinition /&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;c:ConnectionEntry Grid.Column="0" x:Name="connMaster" Title="Master:" Padding="5" /&gt; &lt;c:ConnectionEntry Grid.Column="1" x:Name="connSlave" Title="Slave:" Padding="5" /&gt; &lt;/Grid&gt; &lt;StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Margin="0,0" &gt; &lt;Button x:Name="btnCancel" Click="btnCancel_Click"&gt;Cancel&lt;/Button&gt; &lt;Button x:Name="btnOK" Click="btnOK_Click"&gt;OK&lt;/Button&gt; &lt;/StackPanel&gt; &lt;/StackPanel&gt; &lt;/Window&gt; </code></pre>
[ { "answer_id": 280095, "author": "Geoff Cox", "author_id": 30505, "author_profile": "https://Stackoverflow.com/users/30505", "pm_score": 3, "selected": true, "text": "<TextBox x:Name=\"txtDatabase\" TabIndex=\"2\" Text=\"{Binding Path=DatabaseName, Mode=TwoWay}\"></TextBox>\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269782", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13627/" ]
269,794
<p>I have this code:</p> <pre><code>CCalcArchive::CCalcArchive() : m_calcMap() { } </code></pre> <p><code>m_calcMap</code> is defined as this:</p> <pre><code>typedef CTypedPtrMap&lt;CMapStringToPtr, CString, CCalculation*&gt; CCalcMap; CCalcMap&amp; m_calcMap; </code></pre> <p>When I compile in Visual Studio 2008, I get this error:</p> <pre><code>error C2440: 'initializing' : cannot convert from 'int' to 'CCalcArchive::CCalcMap &amp;' </code></pre> <p>I don't even understand where it gets the "int" error from, and also why this doesn't work? It feels like I'm actually having some sort of syntax error, but isn't this how member initialization lists are supposed to be used? Also, AFAIK, the MFC class <code>CTypedPtrMap</code> has no constructor taking arguments.</p>
[ { "answer_id": 269811, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 2, "selected": false, "text": "int m_calcMap CCalcMap" }, { "answer_id": 270160, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 3, "selected": true, "text": "int CTypedPtrMap int m_calcMap CTypedPtrMap const m_calcMap const mfctest.cpp(72) : warning C4413: '' : reference member is initialized to a temporary \n that doesn't persist after the constructor exits\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9744/" ]
269,795
<p>How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux?</p> <p>I'm trying to look for the source of the <code>datetime</code> module in particular, but I'm interested in a more general answer as well.</p>
[ { "answer_id": 269803, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 6, "selected": false, "text": "sys.path python -v\n>>> import sys\n>>> sys.path\n['', '/usr/local/lib/python25.zip', '/usr/local/lib/python2.5', ... ]\n" }, { "answer_id": 269806, "author": "jblocksom", "author_id": 20626, "author_profile": "https://Stackoverflow.com/users/20626", "pm_score": 8, "selected": false, "text": "python -v C:\\>python -v\n# installing zipimport hook\nimport zipimport # builtin\n# installed zipimport hook\n# C:\\Python24\\lib\\site.pyc has bad mtime\nimport site # from C:\\Python24\\lib\\site.py\n# wrote C:\\Python24\\lib\\site.pyc\n# C:\\Python24\\lib\\os.pyc has bad mtime\nimport os # from C:\\Python24\\lib\\os.py\n# wrote C:\\Python24\\lib\\os.pyc\nimport nt # builtin\n# C:\\Python24\\lib\\ntpath.pyc has bad mtime\n...\n" }, { "answer_id": 269810, "author": "Bjarke Ebert", "author_id": 31890, "author_profile": "https://Stackoverflow.com/users/31890", "pm_score": 5, "selected": false, "text": "datetime .py .pyc mymodule.__file__ > import random\n> random.__file__\n'C:\\\\Python25\\\\lib\\\\random.pyc'\n" }, { "answer_id": 269825, "author": "Moe", "author_id": 3051, "author_profile": "https://Stackoverflow.com/users/3051", "pm_score": 10, "selected": true, "text": "themodule.__file__ datetime.__file__ datetime.__file__ Python-2.6/Modules/datetimemodule.c\n" }, { "answer_id": 2723437, "author": "Daryl Spitzer", "author_id": 4766, "author_profile": "https://Stackoverflow.com/users/4766", "pm_score": 3, "selected": false, "text": "cdp () {\n cd \"$(python -c \"import os.path as _, ${1}; \\\n print _.dirname(_.realpath(${1}.__file__[:-1]))\"\n )\"\n}\n" }, { "answer_id": 5089930, "author": "evdama", "author_id": 440041, "author_profile": "https://Stackoverflow.com/users/440041", "pm_score": 4, "selected": false, "text": "code_info()" }, { "answer_id": 5740458, "author": "Vijay", "author_id": 684799, "author_profile": "https://Stackoverflow.com/users/684799", "pm_score": 4, "selected": false, "text": "import os\n\nhelp(os)\n\n\nHelp on module os:\n\nNAME\n\nos - OS routines for Mac, NT, or Posix depending on what system we're on.\n\nFILE\n\n/usr/lib/python2.6/os.py\n\nMODULE DOCS\n\nhttp://docs.python.org/library/os\n\nDESCRIPTION\n\nThis exports:\n\n- all functions from posix, nt, os2, or ce, e.g. unlink, stat, etc.\n\n- os.path is one of the modules posixpath, or ntpath\n\n- os.name is 'posix', 'nt', 'os2', 'ce' or 'riscos'\n" }, { "answer_id": 13888157, "author": "abarnert", "author_id": 908494, "author_profile": "https://Stackoverflow.com/users/908494", "pm_score": 7, "selected": false, "text": "__file__ sys.path inspect getfile getsourcefile .pyc .py .so .pyd __file__ http://hg.python.org/cpython/file/X.Y/ inspect.getfile(datetime) .so .pyd /usr/local/lib/python2.7/lib-dynload/datetime.so foo.c foomodule.c" }, { "answer_id": 15211581, "author": "Ernest", "author_id": 408885, "author_profile": "https://Stackoverflow.com/users/408885", "pm_score": 4, "selected": false, "text": "echo 'import sys; t=__import__(sys.argv[1],fromlist=[\\\".\\\"]); print(t.__file__)' | python - \n alias getpmpath=\"echo 'import sys; t=__import__(sys.argv[1],fromlist=[\\\".\\\"]); print(t.__file__)' | python - \"\n $ getpmpath twisted\n/usr/lib64/python2.6/site-packages/twisted/__init__.pyc\n$ getpmpath twisted.web\n/usr/lib64/python2.6/site-packages/twisted/web/__init__.pyc\n" }, { "answer_id": 16370057, "author": "Codespaced", "author_id": 765049, "author_profile": "https://Stackoverflow.com/users/765049", "pm_score": 6, "selected": false, "text": ">>> import imp\n>>> imp.find_module('fontTools')\n(None, 'C:\\\\Python27\\\\lib\\\\site-packages\\\\FontTools\\\\fontTools', ('', '', 5))\n>>> imp.find_module('datetime')\n(None, 'datetime', ('', '', 6))\n" }, { "answer_id": 32784452, "author": "James Mark Mackenzie", "author_id": 4045979, "author_profile": "https://Stackoverflow.com/users/4045979", "pm_score": 7, "selected": false, "text": "pip show $module" }, { "answer_id": 37970790, "author": "nexayq", "author_id": 2450748, "author_profile": "https://Stackoverflow.com/users/2450748", "pm_score": 3, "selected": false, "text": "/usr/lib/python2.7/dist-packages/numpy\n" }, { "answer_id": 59930926, "author": "Supradeep", "author_id": 6281259, "author_profile": "https://Stackoverflow.com/users/6281259", "pm_score": 1, "selected": false, "text": "import site\nprint (site.getsitepackages())\n ['C:\\\\Users\\\\<your username>\\\\AppData\\\\Local\\\\Programs\\\\Python\\\\Python37', 'C:\\\\Users\\\\<your username>\\\\AppData\\\\Local\\\\Programs\\\\Python\\\\Python37\\\\lib\\\\site-packages']\n C:\\Users\\<your username>\\AppData\\Local\\Programs\\Python\\Python37\\lib\\site-packages\n" }, { "answer_id": 61095592, "author": "vub", "author_id": 9932834, "author_profile": "https://Stackoverflow.com/users/9932834", "pm_score": 3, "selected": false, "text": "$ python3 -m pip show pyperclip $ python -m pip show pyperclip" }, { "answer_id": 67790109, "author": "Ritik Attri", "author_id": 14652528, "author_profile": "https://Stackoverflow.com/users/14652528", "pm_score": 3, "selected": false, "text": "pip show pip show numpy\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269795", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4766/" ]
269,805
<p>I have been trying to parse Java exceptions that appear in a log for some code I'm working with. My question is, do you parse the exception trace from the top down, or the bottom up? It looks something like this:</p> <pre><code>ERROR [main]&lt;/b&gt; Nov/04 11:03:19,440 [localhost].[/BookmarksPortlet].[] - Exception sending context... org.springframework.beans.factory.BeanCreationException: Error creating bean...: Cannot Resolve reference...: Error creating bean... nested exception... nested exception is org.hibernate.HibernateException: Dialect class not found: org.hibernate.dialect.Oracle10gDialect Caused by: ... [similar exceptions and nested exceptions] ... at [start of stack trace] </code></pre> <p>Something like that. Obviously, I'm not looking for the answer to this specific exception, but how do you go about parsing an exception trace like this? Do you start at the top level error, or do you start at the inner most error (under the "caused by" clauses)?</p> <p>The problem is more difficult for me because I'm not working with code I wrote. I'm editing the XML configurations, so I'm not really even looking the Java code. In my own code, I would recognize locations in the trace and would know what sort of things to look for. So how do you approach an exception like this in general?</p>
[ { "answer_id": 269816, "author": "SCdF", "author_id": 1666, "author_profile": "https://Stackoverflow.com/users/1666", "pm_score": 2, "selected": false, "text": "com.mycompany.myproject" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269805", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8092/" ]
269,812
<p>There are all sorts of advantages to using Emacs, but for someone comfortable with the usual Win32 applications it comes with a wall-like learning curve. With most other editors it’s possible to just start using them and then learn about their other features and enhancements as you go along. </p> <p>How to just get on with using Emacs straight away, with the aim of reaching that point where you actually prefer to use Emacs over other editors or applications?</p> <p>Edit - To try and clarify the question: I’ve done the tutorial, read some docs, etc. then soon after when I’ve wanted to quickly edit some text it’s been easier to just use another editor, that I already know. What do I need to do so that not only I don’t just go for another easier editor, but that I actually prefer to use Emacs, and how to get here as quickly as possible? What if any are the training wheels for Emacs?</p>
[ { "answer_id": 270481, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "(icomplete-mode t)\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25093/" ]
269,837
<p>I have a class derived from <code>CTreeCtrl</code>. In <code>OnCreate()</code> I replace the default <code>CToolTipCtrl</code> object with a custom one:</p> <pre><code>int CMyTreeCtrl::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CTreeCtrl::OnCreate(lpCreateStruct) == -1) return -1; // Replace tool tip with our own which will // ask us for the text to display with a TTN_NEEDTEXT message CTooltipManager::CreateToolTip(m_pToolTip, this, AFX_TOOLTIP_TYPE_DEFAULT); m_pToolTip-&gt;AddTool(this, LPSTR_TEXTCALLBACK); SetToolTips(m_pToolTip); // Update: Added these two lines, which don't help either m_pToolTip-&gt;Activate(TRUE); EnableToolTips(TRUE); return 0; } </code></pre> <p>My message handler looks like this:</p> <pre><code>ON_NOTIFY_EX(TTN_NEEDTEXT, 0, &amp;CMyTreeCtrl::OnTtnNeedText) </code></pre> <p>However I never receive a <code>TTN_NEEDTEXT</code> message. I had a look with Spy++ and it also looks like this message never gets sent.</p> <p>What could be the problem here?</p> <h2>Update</h2> <p>I'm not sure whether this is relevant: The <code>CTreeCtrl</code>'s parent window is of type <code>CDockablePane</code>. Could there be some extra work needed for this to work?</p>
[ { "answer_id": 269873, "author": "ravenspoint", "author_id": 16582, "author_profile": "https://Stackoverflow.com/users/16582", "pm_score": 2, "selected": false, "text": "EnableToolTips(TRUE);\n" }, { "answer_id": 274406, "author": "skst", "author_id": 4858, "author_profile": "https://Stackoverflow.com/users/4858", "pm_score": 0, "selected": false, "text": "ON_NOTIFY_EX_RANGE(TTN_NEEDTEXT, 0, 0xFFFF, &CMyTreeCtrl::OnNeedTipText)\n" }, { "answer_id": 275395, "author": "Javier De Pedro", "author_id": 14053, "author_profile": "https://Stackoverflow.com/users/14053", "pm_score": 1, "selected": false, "text": "virtual BOOL PreTranslateMessage(MSG* pMsg);\n BOOL CMyTreeCtrl::PreTranslateMessage(MSG* pMsg) \n{\n m_pToolTip.Activate(TRUE);\n m_pToolTip.RelayEvent(pMsg);\n\n return CTreeCtrl::PreTranslateMessage(pMsg);\n}\n" }, { "answer_id": 799366, "author": "JeffH", "author_id": 73826, "author_profile": "https://Stackoverflow.com/users/73826", "pm_score": 1, "selected": false, "text": " int nHit = MAKELONG(pt.x, pt.y);\n pTI->hwnd = m _ hWnd;\n pTI->uId = nHit;\n pTI->rect = CRect(CPoint(pt.x-1,pt.y-1),CSize(2,2));\n pTI->uFlags |= TTF _ NOTBUTTON;\n pTI->lpszText = LPSTR _ TEXTCALLBACK;\n" }, { "answer_id": 867675, "author": "foraidt", "author_id": 27596, "author_profile": "https://Stackoverflow.com/users/27596", "pm_score": 4, "selected": true, "text": "OnCreate() int CMyPane::OnCreate(LPCREATESTRUCT lpCreateStruct)\n{\n if (CDockablePane::OnCreate(lpCreateStruct) == -1)\n return -1;\n\nconst DWORD dwStyle = WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN |\n TVS_CHECKBOXES | TVS_DISABLEDRAGDROP | TVS_HASBUTTONS | TVS_HASLINES | TVS_LINESATROOT |\n TVS_INFOTIP | TVS_NOHSCROLL | TVS_SHOWSELALWAYS;\n\n// TREECTRL_ID is a custom member constant, set to 1\nif(!m_tree.Create(dwStyle, m_treeRect, this, TREECTRL_ID ) )\n{\n TRACE0(\"Failed to create trace tree list control.\\n\");\n return -1;\n}\n\n// m_pToolTip is a protected member of CDockablePane\nm_pToolTip->AddTool(&m_tree, LPSTR_TEXTCALLBACK, &m_treeRect, TREECTRL_ID);\nm_tree.SetToolTips(m_pToolTip);\n\n\nreturn 0;\n AddTool() ASSERT uFlag CRect (0, 0, 10000, 10000) // Message map entry\nON_NOTIFY(TVN_GETINFOTIP, TREECTRL_ID, &CMobileCatalogPane::OnTvnGetInfoTip)\n\n\n// Handler\nvoid CMyPane::OnTvnGetInfoTip(NMHDR *pNMHDR, LRESULT *pResult)\n{\n LPNMTVGETINFOTIP pGetInfoTip = reinterpret_cast<LPNMTVGETINFOTIP>(pNMHDR);\n\n // This is a CString member\n m_toolTipText.ReleaseBuffer();\n m_toolTipText.Empty();\n\n // Set your text here...\n\n pGetInfoTip->pszText = m_toolTipText.GetBuffer();\n\n *pResult = 0;\n}\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27596/" ]
269,839
<p>So odd situation that I ran into today with OrderBy:</p> <pre><code>Func&lt;SomeClass, int&gt; orderByNumber = currentClass =&gt; currentClass.SomeNumber; </code></pre> <p>Then:</p> <pre><code>someCollection.OrderBy(orderByNumber); </code></pre> <p>This is fine, but I was going to create a method instead because it might be usable somewhere else other than an orderBy.</p> <pre><code>private int ReturnNumber(SomeClass currentClass) { return currentClass.SomeNumber; } </code></pre> <p>Now when I try to plug that into the OrderBy:</p> <pre><code>someCollection.OrderBy(ReturnNumber); </code></pre> <p>It can't infer the type like it can if I use a Func. Seems like to me they should be the same since the method itself is "strongly typed" like the Func.</p> <p>Side Note: I realize I can do this:</p> <pre><code>Func&lt;SomeClass, int&gt; orderByNumber = ReturnNumber; </code></pre>
[ { "answer_id": 269873, "author": "ravenspoint", "author_id": 16582, "author_profile": "https://Stackoverflow.com/users/16582", "pm_score": 2, "selected": false, "text": "EnableToolTips(TRUE);\n" }, { "answer_id": 274406, "author": "skst", "author_id": 4858, "author_profile": "https://Stackoverflow.com/users/4858", "pm_score": 0, "selected": false, "text": "ON_NOTIFY_EX_RANGE(TTN_NEEDTEXT, 0, 0xFFFF, &CMyTreeCtrl::OnNeedTipText)\n" }, { "answer_id": 275395, "author": "Javier De Pedro", "author_id": 14053, "author_profile": "https://Stackoverflow.com/users/14053", "pm_score": 1, "selected": false, "text": "virtual BOOL PreTranslateMessage(MSG* pMsg);\n BOOL CMyTreeCtrl::PreTranslateMessage(MSG* pMsg) \n{\n m_pToolTip.Activate(TRUE);\n m_pToolTip.RelayEvent(pMsg);\n\n return CTreeCtrl::PreTranslateMessage(pMsg);\n}\n" }, { "answer_id": 799366, "author": "JeffH", "author_id": 73826, "author_profile": "https://Stackoverflow.com/users/73826", "pm_score": 1, "selected": false, "text": " int nHit = MAKELONG(pt.x, pt.y);\n pTI->hwnd = m _ hWnd;\n pTI->uId = nHit;\n pTI->rect = CRect(CPoint(pt.x-1,pt.y-1),CSize(2,2));\n pTI->uFlags |= TTF _ NOTBUTTON;\n pTI->lpszText = LPSTR _ TEXTCALLBACK;\n" }, { "answer_id": 867675, "author": "foraidt", "author_id": 27596, "author_profile": "https://Stackoverflow.com/users/27596", "pm_score": 4, "selected": true, "text": "OnCreate() int CMyPane::OnCreate(LPCREATESTRUCT lpCreateStruct)\n{\n if (CDockablePane::OnCreate(lpCreateStruct) == -1)\n return -1;\n\nconst DWORD dwStyle = WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN |\n TVS_CHECKBOXES | TVS_DISABLEDRAGDROP | TVS_HASBUTTONS | TVS_HASLINES | TVS_LINESATROOT |\n TVS_INFOTIP | TVS_NOHSCROLL | TVS_SHOWSELALWAYS;\n\n// TREECTRL_ID is a custom member constant, set to 1\nif(!m_tree.Create(dwStyle, m_treeRect, this, TREECTRL_ID ) )\n{\n TRACE0(\"Failed to create trace tree list control.\\n\");\n return -1;\n}\n\n// m_pToolTip is a protected member of CDockablePane\nm_pToolTip->AddTool(&m_tree, LPSTR_TEXTCALLBACK, &m_treeRect, TREECTRL_ID);\nm_tree.SetToolTips(m_pToolTip);\n\n\nreturn 0;\n AddTool() ASSERT uFlag CRect (0, 0, 10000, 10000) // Message map entry\nON_NOTIFY(TVN_GETINFOTIP, TREECTRL_ID, &CMobileCatalogPane::OnTvnGetInfoTip)\n\n\n// Handler\nvoid CMyPane::OnTvnGetInfoTip(NMHDR *pNMHDR, LRESULT *pResult)\n{\n LPNMTVGETINFOTIP pGetInfoTip = reinterpret_cast<LPNMTVGETINFOTIP>(pNMHDR);\n\n // This is a CString member\n m_toolTipText.ReleaseBuffer();\n m_toolTipText.Empty();\n\n // Set your text here...\n\n pGetInfoTip->pszText = m_toolTipText.GetBuffer();\n\n *pResult = 0;\n}\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21691/" ]
269,840
<p>I've uploaded a bunch of images to Amazon S3, and now want to add a Cache-Control header to them. </p> <p>Can the header be updated without downloading the entire image? If so, how?</p>
[ { "answer_id": 270066, "author": "stevemegson", "author_id": 25028, "author_profile": "https://Stackoverflow.com/users/25028", "pm_score": 6, "selected": true, "text": "PUT /myObject HTTP/1.1\nHost: mybucket.s3.amazonaws.com \nx-amz-copy-source: /mybucket/myObject \nx-amz-metadata-directive: REPLACE \nx-amz-meta-myKey: newValue\n" }, { "answer_id": 8917419, "author": "bkaid", "author_id": 265570, "author_profile": "https://Stackoverflow.com/users/265570", "pm_score": 3, "selected": false, "text": "var s3Client = new AmazonS3Client(\"publicKey\", \"privateKey\");\nvar copyRequest = new CopyObjectRequest()\n .WithDirective(S3MetadataDirective.REPLACE)\n .WithSourceBucket(\"bucketName\")\n .WithSourceKey(\"fileName\")\n .WithDestinationBucket(\"bucketName\")\n .WithDestinationKey(\"fileName)\n .WithMetaData(new NameValueCollection { { \"x-amz-meta-yourKey\", \"your-value }, { \"x-amz-your-otherKey\", \"your-value\" } });\nvar copyResponse = s3Client.CopyObject(copyRequest);\n" }, { "answer_id": 9758282, "author": "rjha94", "author_id": 262376, "author_profile": "https://Stackoverflow.com/users/262376", "pm_score": 2, "selected": false, "text": "<?php\n error_reporting(-1);\n require_once 'sdk.class.php';\n\n // UPLOAD FILES TO S3\n // Instantiate the AmazonS3 class\n $options = array(\"key\" => \"aws-key\" , \"secret\" => \"aws-secret\") ;\n\n\n $s3 = new AmazonS3($options);\n $bucket = \"bucket.3mik.com\" ;\n\n\n $exists = $s3->if_bucket_exists($bucket);\n if(!$exists) {\n trigger_error(\"S3 bucket does not exists \\n\" , E_USER_ERROR);\n }\n\n $name = \"cows-and-aliens.jpg\" ;\n echo \" change headers for $name \\n\" ;\n $source = array(\"bucket\" => $bucket, \"filename\" => $name);\n $dest = array(\"bucket\" => $bucket, \"filename\" => $name);\n\n //caching headers\n $offset = 3600*24*365;\n $expiresOn = gmdate('D, d M Y H:i:s \\G\\M\\T', time() + $offset);\n $headers = array('Expires' => $expiresOn, 'Cache-Control' => 'public, max-age=31536000');\n\n $meta = array('acl' => AmazonS3::ACL_PUBLIC, 'headers' => $headers);\n\n $response = $s3->copy_object($source,$dest,$meta);\n if($response->isOk()){\n printf(\"copy object done \\n\" );\n\n }else {\n printf(\"Error in copy object \\n\" );\n }\n\n?>\n" }, { "answer_id": 14463356, "author": "luissquall", "author_id": 102353, "author_profile": "https://Stackoverflow.com/users/102353", "pm_score": 3, "selected": false, "text": "<?php\nrequire 'vendor/autoload.php';\n\nuse Aws\\Common\\Aws;\nuse Aws\\S3\\Enum\\CannedAcl;\nuse Aws\\S3\\Exception\\S3Exception;\n\nconst MONTH = 2592000;\n\n// Instantiate an S3 client\n$s3 = Aws::factory('config.php')->get('s3');\n// Settings\n$bucketName = 'example.com';\n$objectKey = 'image.jpg';\n$maxAge = MONTH;\n$contentType = 'image/jpeg';\n\ntry {\n $o = $s3->copyObject(array(\n 'Bucket' => $bucketName,\n 'Key' => $objectKey,\n 'CopySource' => $bucketName . '/'. $objectKey,\n 'MetadataDirective' => 'REPLACE',\n 'ACL' => CannedAcl::PUBLIC_READ,\n 'command.headers' => array(\n 'Cache-Control' => 'public,max-age=' . $maxAge,\n 'Content-Type' => $contentType\n )\n ));\n\n // print_r($o->ETag);\n} catch (Exception $e) {\n echo $objectKey . ': ' . $e->getMessage() . PHP_EOL;\n}\n?>\n" }, { "answer_id": 29798456, "author": "Jefin Stephan", "author_id": 2198345, "author_profile": "https://Stackoverflow.com/users/2198345", "pm_score": 1, "selected": false, "text": "S3Object s3Object = amazonS3Client.getObject(bucketName, fileKey);\nObjectMetadata metadata = s3Object.getObjectMetadata();\nMap customMetaData = new HashMap();\ncustomMetaData.put(\"yourKey\", \"updateValue\");\ncustomMetaData.put(\"otherKey\", \"newValue\");\nmetadata.setUserMetadata(customMetaData);\n\namazonS3Client.putObject(new PutObjectRequest(bucketName, fileId, s3Object.getObjectContent(), metadata));\n ObjectMetadata metadata = amazonS3Client.getObjectMetadata(bucketName, fileKey);\nObjectMetadata metadataCopy = new ObjectMetadata();\nmetadataCopy.addUserMetadata(\"yourKey\", \"updateValue\");\nmetadataCopy.addUserMetadata(\"otherKey\", \"newValue\");\nmetadataCopy.addUserMetadata(\"existingKey\", metadata.getUserMetaDataOf(\"existingValue\"));\n\nCopyObjectRequest request = new CopyObjectRequest(bucketName, fileKey, bucketName, fileKey)\n .withSourceBucketName(bucketName)\n .withSourceKey(fileKey)\n .withNewObjectMetadata(metadataCopy);\n\namazonS3Client.copyObject(request);\n" }, { "answer_id": 34396020, "author": "Vivek", "author_id": 3726185, "author_profile": "https://Stackoverflow.com/users/3726185", "pm_score": 0, "selected": false, "text": "import boto\n\none_year = 3600*24*365\ncckey = 'cache-control'\ns3_connection = S3Connection()\nbucket_name = 'my_bucket'\nbucket = s3_connection.get_bucket(bucket_name validate=False)\n\n\nfor key in bucket:\n key_name = key.key\n if key.size == 0: # continue on directories\n continue\n # Get key object\n key = bucket.get_key(key_name)\n\n if key.cache_control is not None:\n print(\"Exists\")\n continue\n\n cache_time = one_year\n #set metdata\n key.set_metadata(name=cckey, value = ('max-age=%d, public' % (cache_time)))\n key.set_metadata(name='content-type', value = key.content_type)\n # Copy the same key\n key2 = key.copy(key.bucket.name, key.name, key.metadata, preserve_acl=True)\n continue\n\n " } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7399/" ]
269,845
<p>According to the help file that comes with the Spring.NET framework, you can inject a dependancy defined in the local file by using an 'idref' tag along with a 'local' attribute. </p> <p>I have been trying to do this with no success and was hoping someone had the experience to help me out. </p> <p>Below I have a snippet from the config where I am passing it as a constructor argument, but I have tried setting it as a property as well. Both methods seem to yield the same error.</p> <pre><code>&lt;object id="theTargetObject" type="TestClassLibrary.TargetObject, TestClassLibrary"/&gt; &lt;object id="theClientObject" type="TestClassLibrary.ClientObject, TestClassLibrary"&gt; &lt;constructor-arg name="myClass"&gt; &lt;idref local="theTargetObject"/&gt; &lt;/constructor-arg&gt; &lt;/object&gt; </code></pre> <p>Error creating context 'spring.root': Error creating object with name 'theClientObject' defined in 'file [C:\Test\TestApp\bin\Debug\my.config.xml]' : Unsatisfied dependency expressed through constructor argument with index 0 of type [TestClassLibrary.TargetObject] : Could not convert constructor argument value [theTargetObject] to required type [TestClassLibrary.TargetObject] : Cannot convert property value of type [System.String] to required type [TestClassLibrary.TargetObject] for property ''.</p>
[ { "answer_id": 411132, "author": "Erich Eichinger", "author_id": 51264, "author_profile": "https://Stackoverflow.com/users/51264", "pm_score": 2, "selected": false, "text": "<object id=\"theTargetObject\" type=\"TestClassLibrary.TargetObject, TestClassLibrary\"/>\n<object id=\"theClientObject\" type=\"TestClassLibrary.ClientObject, TestClassLibrary\">\n <property name=\"myClass\">\n <ref local=\"theTargetObject\"/>\n </property>\n <object id=\"theClientObject\" type=\"TestClassLibrary.ClientObject, TestClassLibrary\">\n <property name=\"myClass ref=\"theTargetObject\"/>\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
269,864
<p>So I'm looking for a pattern like this:</p> <blockquote> <p>size='0x0'</p> </blockquote> <p>In a log file, but I'm only interested in large sizes (4 digits or more). The following regex works great in EditPadPro (nice tool BTW)</p> <pre><code>size='0x[0-9a-fA-F]{4,} </code></pre> <p>But the same RegEx does not work in awk - seems like the repetition <code>{4,}</code> is messing it up. Same with WinGrep - any idea from the RegEx gurus? Thanks!</p>
[ { "answer_id": 269874, "author": "Adam Alexander", "author_id": 33164, "author_profile": "https://Stackoverflow.com/users/33164", "pm_score": 2, "selected": false, "text": "size='0x[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]+\n" }, { "answer_id": 270023, "author": "Keng", "author_id": 730, "author_profile": "https://Stackoverflow.com/users/730", "pm_score": 0, "selected": false, "text": "'\n" }, { "answer_id": 270101, "author": "Dan Fego", "author_id": 34426, "author_profile": "https://Stackoverflow.com/users/34426", "pm_score": 4, "selected": true, "text": "awk --re-interval \"/size='0x[0-9a-fA-F]{4,}'/\" thefile\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15797/" ]
269,876
<p>I've always done web apps and now I need to do a console app. I need to use both an odbc connection and a regular connection. </p> <p>In the past I would have used:</p> <pre><code>&lt;add name="LinkConnectionString" connectionString="Data Source=SERENITY\SQLEXPRESS;Initial Catalog=Link;Integrated Security=True" providerName="System.Data.SqlClient"/&gt; </code></pre> <p>In the web.config, however I am not sure how to do the same thing with inline code. So like string connectionString = @".....";</p> <p>I have tried multiple combinations, looked online (including connectionstrings.com), but none of them worked. </p> <p>Can anyone help me out? I want both the odbc and the regular... as they seem different should be different according to the sample ones online (that don't work). </p>
[ { "answer_id": 269940, "author": "Nathan Koop", "author_id": 18821, "author_profile": "https://Stackoverflow.com/users/18821", "pm_score": 0, "selected": false, "text": " SqlConnection conn = new SqlConnection(@\"Data Source=SERENITY\\SQLEXPRESS;Initial Catalog=Link;Integrated Security=True\");\n SqlCommand cmd = new SqlCommand(\"SELECT * FROM tableName\", conn);\n conn.Open();\n //<snip> Run Command\n conn.Close();\n OdbcConnection conn = new OdbcConnection(@\"ODBC connection string\");\nOdbcCommand cmd = new OdbcCommand(\"SELECT * FROM tableName\", conn);\nconn.Open();\n//Run Command\nconn.Close();\n" }, { "answer_id": 269959, "author": "x0n", "author_id": 6920, "author_profile": "https://Stackoverflow.com/users/6920", "pm_score": 5, "selected": false, "text": "function get-oledbconnection ([switch]$Open) {\n $null | set-content ($udl = \"$([io.path]::GetTempPath())\\temp.udl\");\n $psi = new-object Diagnostics.ProcessStartInfo\n $psi.CreateNoWindow = $true\n $psi.UseShellExecute = $true\n $psi.FileName = $udl\n $pi = [System.Diagnostics.Process]::Start($psi)\n $pi.WaitForExit()\n write-host (gc $udl) # verbose \n if (gc $udl) {\n $conn = new-object data.oledb.oledbconnection (gc $udl)[2]\n if ($Open) { $conn.Open() }\n }\n $conn\n}\n" }, { "answer_id": 711208, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<add name=\"myName\" connectionString=\"dsn=myDSN;UID=myUID;\"\nproviderName=\"System.Data.Odbc\" />" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23695/" ]
269,882
<p>If I do this:</p> <pre><code>// In header class Foo { void foo(bar*); }; // In cpp void Foo::foo(bar* const pBar) { //Stuff } </code></pre> <p>The compiler does not complain that the signatures for Foo::foo do not match. However if I had:</p> <pre><code>void foo(const bar*); //In header void Foo::foo(bar*) {} //In cpp </code></pre> <p>The code will fail to compile.</p> <p>What is going on? I'm using gcc 4.1.x</p>
[ { "answer_id": 269889, "author": "Douglas Mayle", "author_id": 8458, "author_profile": "https://Stackoverflow.com/users/8458", "pm_score": 4, "selected": false, "text": "bar* const variable\n const bar* variable\n const bar* const variable\n class Foo {\n void func1 (int x);\n void func2 (int *x);\n}\n Foo::func1(const int x) {}\nFoo::func2(const int *x) {}\n Foo::func1(const int x) {}\nFoo::func2(const int* const x) {}\n" }, { "answer_id": 269890, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 0, "selected": false, "text": "const bar* bar bar*" }, { "answer_id": 269912, "author": "anio", "author_id": 35227, "author_profile": "https://Stackoverflow.com/users/35227", "pm_score": 0, "selected": false, "text": "void Foo::foo(const bar* const);\n" }, { "answer_id": 269941, "author": "Dusty Campbell", "author_id": 2174, "author_profile": "https://Stackoverflow.com/users/2174", "pm_score": 3, "selected": true, "text": "// In header \nclass Foo {\nvoid foo( int b );\n};\n\n// In cpp\nvoid Foo::foo( const int b ) {\n//Stuff\n}\n // In header \nclass Foo {\nvoid foo( const int b );\n};\n\n// In cpp\nvoid Foo::foo( int b ) {\n//Stuff\n}\n" }, { "answer_id": 269968, "author": "Martin Cote", "author_id": 9936, "author_profile": "https://Stackoverflow.com/users/9936", "pm_score": 0, "selected": false, "text": "void foo( int i );\n void foo( const int i ) { ... }\n" }, { "answer_id": 269980, "author": "T.E.D.", "author_id": 29639, "author_profile": "https://Stackoverflow.com/users/29639", "pm_score": 0, "selected": false, "text": "void Foo::foo(bar* const pBar) (const bar* pBar)" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35227/" ]
269,893
<p>I need to store log files and configuration files for my application. Where is the best place to store them?</p> <p>Right now, I'm just using the current directory, which ends up putting them in the Program Files directory where my program lives.</p> <p>The log files will probably be accessed by the user somewhat regularly, so <code>%APPDATA%</code> seems a little hard to get to.</p> <p>Is a directory under <code>%USERPROFILE%\My Documents</code> the best? It needs to work for all versions of Windows, from 2000 forward.</p>
[ { "answer_id": 269964, "author": "Sunny Milenov", "author_id": 8220, "author_profile": "https://Stackoverflow.com/users/8220", "pm_score": 3, "selected": false, "text": "System.Environment.SpecialFolder.ApplicationData System.Environment.SpecialFolder.LocalApplicationData" }, { "answer_id": 270013, "author": "Klathzazt", "author_id": 35223, "author_profile": "https://Stackoverflow.com/users/35223", "pm_score": 2, "selected": false, "text": "int MAX_PATH = 255;\n\nCString m_strMyPath;\n\nSHGetSpecialFolderPath(NULL, m_strMyPath.GetBuffer(MAX_PATH), CSIDL_COMMON_APPDATA, TRUE);\n C:\\Documents and Settings\\All Users\\Application Data C:\\ProgramData" }, { "answer_id": 270060, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 6, "selected": true, "text": "ConfigurationManager ConfigurationManager System.Environment.SpecialFolder.LocalApplicationData System.Environment.SpecialFolder.LocalApplicationData ConfigurationManager Settings app.config" }, { "answer_id": 2862148, "author": "WWC", "author_id": 311749, "author_profile": "https://Stackoverflow.com/users/311749", "pm_score": 4, "selected": false, "text": "string strPath=System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData);\n" }, { "answer_id": 12956746, "author": "Dylan Hayes", "author_id": 892460, "author_profile": "https://Stackoverflow.com/users/892460", "pm_score": 3, "selected": false, "text": "System.Environment.SpecialFolder.LocalApplicationData C:\\Users\\[User]\\AppData\\Roaming System.Environment.SpecialFolder.CommonApplicationData C:\\ProgramData CommonApplicationData" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35229/" ]
269,906
<p>Hopefully this won't be taken as asking the same question twice...</p> <p>So I'm working on a Flash website (in AS2) which has an outer index swf which loads sub swf files using <code>loadMovie("subfoo1.swf", placeToShowSwf)</code>. These in turn load an xml file which tells it what content to load. Everything works peachy, but we'd like to add a button to the index swf that opens a sub swf file with one or two different values for one or two variables.</p> <p>Unfortunately, just adding a button that says</p> <pre><code>loadMovie("foo1.swf", placeToShowSwf); placeToShowSwf.openProject(x); </code></pre> <p>doesn't work, I assume because <code>openProject(x)</code> is called on a file that isn't fully loaded. I know that there's not a problem with the code, because I made a button elsewhere that only calls <code>placeToShowSwf.openProject(x)</code> and there aren't any problems. </p> <p>I see two solutions, both of which I'm unsure how to do.</p> <ol> <li>Change the desired value when the swf file is made, like a constructor for a class. But is there some sort of constructor function for swf files? It'd be really nice just to say <code>loadMovie(new foo1.swf(x), placeToShowSwf)</code> or something equivalent.</li> <li>Wait until after swf (and probably xml) is loaded, and then call <code>placeToShowSwf.openProject(x)</code>. </li> </ol> <p>Anyone got any guidance towards either of these solutions, or perhaps some other way that my pea-like brain has been unable to fathom?</p>
[ { "answer_id": 269964, "author": "Sunny Milenov", "author_id": 8220, "author_profile": "https://Stackoverflow.com/users/8220", "pm_score": 3, "selected": false, "text": "System.Environment.SpecialFolder.ApplicationData System.Environment.SpecialFolder.LocalApplicationData" }, { "answer_id": 270013, "author": "Klathzazt", "author_id": 35223, "author_profile": "https://Stackoverflow.com/users/35223", "pm_score": 2, "selected": false, "text": "int MAX_PATH = 255;\n\nCString m_strMyPath;\n\nSHGetSpecialFolderPath(NULL, m_strMyPath.GetBuffer(MAX_PATH), CSIDL_COMMON_APPDATA, TRUE);\n C:\\Documents and Settings\\All Users\\Application Data C:\\ProgramData" }, { "answer_id": 270060, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 6, "selected": true, "text": "ConfigurationManager ConfigurationManager System.Environment.SpecialFolder.LocalApplicationData System.Environment.SpecialFolder.LocalApplicationData ConfigurationManager Settings app.config" }, { "answer_id": 2862148, "author": "WWC", "author_id": 311749, "author_profile": "https://Stackoverflow.com/users/311749", "pm_score": 4, "selected": false, "text": "string strPath=System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData);\n" }, { "answer_id": 12956746, "author": "Dylan Hayes", "author_id": 892460, "author_profile": "https://Stackoverflow.com/users/892460", "pm_score": 3, "selected": false, "text": "System.Environment.SpecialFolder.LocalApplicationData C:\\Users\\[User]\\AppData\\Roaming System.Environment.SpecialFolder.CommonApplicationData C:\\ProgramData CommonApplicationData" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32139/" ]
269,913
<p>As already discussed in "<a href="https://stackoverflow.com/questions/250151/lua-as-a-general-purpose-scripting-language">Lua as a general-purpose scripting language?</a>" Lua currently probably isn't the best scripting language for the desktop environment.</p> <p>But what do you think about the future? Will Lua get so popular that there will soon be enough libraries to be able to use it like Python, Ruby or something similar?</p> <p>Or will it simply stay in it's WoW niche and that's it?</p>
[ { "answer_id": 44992091, "author": "Pushpendre", "author_id": 538192, "author_profile": "https://Stackoverflow.com/users/538192", "pm_score": 2, "selected": false, "text": "Torch" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32756/" ]
269,918
<p>I'm trying to diff two strings to determine whether or not they solely vary in one numerical subset of the string structure; for example,</p> <pre><code>varies_in_single_number_field('foo7bar', 'foo123bar') # Returns True, because 7 != 123, and there's only one varying # number region between the two strings. </code></pre> <p>In Python I can use the <code>difflib</code> to accomplish this:</p> <pre><code>import difflib, doctest def varies_in_single_number_field(str1, str2): """ A typical use case is as follows: &gt;&gt;&gt; varies_in_single_number_field('foo7bar00', 'foo123bar00') True Numerical variation in two dimensions is no good: &gt;&gt;&gt; varies_in_single_number_field('foo7bar00', 'foo123bar01') False Varying in a nonexistent field is okay: &gt;&gt;&gt; varies_in_single_number_field('foobar00', 'foo123bar00') True Identical strings don't *vary* in any number field: &gt;&gt;&gt; varies_in_single_number_field('foobar00', 'foobar00') False """ in_differing_substring = False passed_differing_substring = False # There should be only one. differ = difflib.Differ() for letter_diff in differ.compare(str1, str2): letter = letter_diff[2:] if letter_diff.startswith(('-', '+')): if passed_differing_substring: # Already saw a varying field. return False in_differing_substring = True if not letter.isdigit(): return False # Non-digit diff character. elif in_differing_substring: # Diff character not found - end of diff. in_differing_substring = False passed_differing_substring = True return passed_differing_substring # No variation if no diff was passed. if __name__ == '__main__': doctest.testmod() </code></pre> <p>But I have no idea how to find something like <code>difflib</code> for C++. Alternative approaches welcome. :)</p>
[ { "answer_id": 270143, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 3, "selected": true, "text": "#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <cctype>\n\nbool starts_with(const std::string &s1, const std::string &s2) {\n return (s1.length() <= s2.length()) && (s2.substr(0, s1.length()) == s1);\n}\n\nbool ends_with(const std::string &s1, const std::string &s2) {\n return (s1.length() <= s2.length()) && (s2.substr(s2.length() - s1.length()) == s1);\n}\n\nbool is_numeric(const std::string &s) {\n for(std::string::const_iterator it = s.begin(); it != s.end(); ++it) {\n if(!std::isdigit(*it)) {\n return false;\n }\n }\n return true;\n}\n\nbool varies_in_single_number_field(std::string s1, std::string s2) {\n\n size_t index1 = 0;\n size_t index2 = s1.length() - 1;\n\n if(s1 == s2) {\n return false;\n }\n\n if((s1.empty() && is_numeric(s2)) || (s2.empty() && is_numeric(s1))) {\n return true;\n }\n\n if(s1.length() < s2.length()) {\n s1.swap(s2);\n }\n\n while(index1 < s1.length() && starts_with(s1.substr(0, index1), s2)) { index1++; }\n while(ends_with(s1.substr(index2), s2)) { index2--; }\n\n return is_numeric(s1.substr(index1 - 1, (index2 + 1) - (index1 - 1)));\n\n}\n\nint main() {\n std::cout << std::boolalpha << varies_in_single_number_field(\"foo7bar00\", \"foo123bar00\") << std::endl;\n std::cout << std::boolalpha << varies_in_single_number_field(\"foo7bar00\", \"foo123bar01\") << std::endl;\n std::cout << std::boolalpha << varies_in_single_number_field(\"foobar00\", \"foo123bar00\") << std::endl;\n std::cout << std::boolalpha << varies_in_single_number_field(\"foobar00\", \"foobar00\") << std::endl;\n std::cout << std::boolalpha << varies_in_single_number_field(\"7aaa\", \"aaa\") << std::endl;\n std::cout << std::boolalpha << varies_in_single_number_field(\"aaa7\", \"aaa\") << std::endl;\n std::cout << std::boolalpha << varies_in_single_number_field(\"aaa\", \"7aaa\") << std::endl;\n std::cout << std::boolalpha << varies_in_single_number_field(\"aaa\", \"aaa7\") << std::endl;\n}\n" }, { "answer_id": 270241, "author": "cdleary", "author_id": 3594, "author_profile": "https://Stackoverflow.com/users/3594", "pm_score": 0, "selected": false, "text": "#include <cassert>\n#include <cctype>\n#include <string>\n#include <sstream>\n#include <iostream>\n\nusing namespace std;\n\nostringstream debug;\nconst bool DEBUG = true;\n\nbool varies_in_single_number_field(const string &str1, const string &str2) {\n bool in_difference = false;\n bool passed_difference = false;\n string str1_digits, str2_digits;\n size_t str1_iter = 0, str2_iter = 0;\n while (str1_iter < str1.size() && str2_iter < str2.size()) {\n const char &str1_char = str1.at(str1_iter);\n const char &str2_char = str2.at(str2_iter);\n debug << \"str1: \" << str1_char << \"; str2: \" << str2_char << endl;\n if (str1_char == str2_char) {\n if (in_difference) {\n in_difference = false;\n passed_difference = true;\n }\n ++str1_iter, ++str2_iter;\n continue;\n }\n in_difference = true;\n if (passed_difference) { /* Already passed a difference. */\n debug << \"Already passed a difference.\" << endl;\n return false;\n }\n bool str1_char_is_digit = isdigit(str1_char);\n bool str2_char_is_digit = isdigit(str2_char);\n if (str1_char_is_digit && !str2_char_is_digit) {\n ++str1_iter;\n str1_digits.push_back(str1_char);\n } else if (!str1_char_is_digit && str2_char_is_digit) {\n ++str2_iter;\n str2_digits.push_back(str2_char);\n } else if (str1_char_is_digit && str2_char_is_digit) {\n ++str1_iter, ++str2_iter;\n str1_digits.push_back(str1_char);\n str2_digits.push_back(str2_char);\n } else { /* Both are non-digits and they're different. */\n return false;\n }\n }\n if (in_difference) {\n in_difference = false;\n passed_difference = true;\n }\n string str1_remainder = str1.substr(str1_iter);\n string str2_remainder = str2.substr(str2_iter);\n debug << \"Got to exit point; passed difference: \" << passed_difference\n << \"; str1 digits: \" << str1_digits\n << \"; str2 digits: \" << str2_digits\n << \"; str1 remainder: \" << str1_remainder\n << \"; str2 remainder: \" << str2_remainder\n << endl;\n return passed_difference\n && (str1_digits != str2_digits)\n && (str1_remainder == str2_remainder);\n}\n\nint main() {\n assert(varies_in_single_number_field(\"foo7bar00\", \"foo123bar00\") == true);\n assert(varies_in_single_number_field(\"foo7bar00\", \"foo123bar01\") == false);\n assert(varies_in_single_number_field(\"foobar00\", \"foo123bar00\") == true);\n assert(varies_in_single_number_field(\"foobar00\", \"foobar00\") == false);\n assert(varies_in_single_number_field(\"foobar00\", \"foobaz00\") == false);\n assert(varies_in_single_number_field(\"foo00bar\", \"foo01barz\") == false);\n assert(varies_in_single_number_field(\"foo01barz\", \"foo00bar\") == false);\n if (DEBUG) {\n cout << debug.str();\n }\n return 0;\n}\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3594/" ]
269,931
<p>I have a script that generates data in csv format which is sent to the user along with a set of headers that tell the browser it is a .csv file. Everything works great when users (left)click on the link to the script, they are presented with a download dialog with the filename ending in .csv and it suggests using excel, or calc, to open it. However, when users right-click and choose Save As it is being saved with the php script name.</p> <p>Here is the header code:</p> <pre><code>header("Pragma: public"); header("Expires: 0"); // set expiration time header("Content-Type: application/force-download"); header("Content-Type: application/octet-stream"); header("Content-Type: application/download"); $val = date("m_d_Y_g_i"); Header('Content-Disposition: attachment; filename="personal_information_'.$val.'.csv"'); </code></pre> <p>So again, when users left-click it saves the file as personal_information_date.csv; when they right click it saves as download.php. I'm using FF3. Oddly enough, IE7 does not have this problem.</p> <p>Any ideas?</p>
[ { "answer_id": 269955, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 2, "selected": false, "text": "personal_information_date.csv mod_rewrite personal_information_date.csv download.php RewriteRule ^personal_information_date.csv$ download.php" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
269,932
<p>I wrote a managed C++ class that has the following function:</p> <pre><code>void EndPointsMappingWrapper::GetLastError(char* strErrorMessage) { strErrorMessage = (char*) Marshal::StringToHGlobalAnsi(_managedObject-&gt;GetLastError()).ToPointer(); } </code></pre> <p>As you can see, this is a simple method to copy the managed string of the last error to the unmanaged world (<code>char*</code>).</p> <p>From my unmanaged class I call the method like this:</p> <pre><code>char err[1000]; ofer-&gt;GetLastError(err); </code></pre> <p>Putting a breakpoint at the managed C++ method shows that the string is successfully translated into the <code>char*</code>. However, once I return to the unmanaged class, the content of <code>err[1000]</code> is lost and it's empty again.</p>
[ { "answer_id": 269953, "author": "Rob Prouse", "author_id": 30827, "author_profile": "https://Stackoverflow.com/users/30827", "pm_score": 0, "selected": false, "text": "public ref class ManagedStringConverter\n{\npublic:\n ManagedStringConverter( System::String^ pString );\n ~ManagedStringConverter();\n\n property char* PrimitiveString\n {\n char* get() { return m_pString; }\n }\n\n /// <summary>\n /// Converts a System::String to a char * string. You must release this with FreeString.\n /// </summary>\n static const char* StringToChar( System::String^ str );\n\n /// <summary>\n /// Converts a System::String to a __wchar_t * string. You must release this with FreeString.\n /// </summary>\n static const __wchar_t * StringToWChar( System::String^ str );\n\n /// <summary>\n /// Frees memory allocated in StringToChar()\n /// </summary>\n static void FreeString( const char * pszStr );\n\nprivate:\n char* m_pString;\n};\n ManagedStringConverter::ManagedStringConverter( System::String^ pString )\n{\n m_pString = const_cast<char*>( ManagedStringConverter::StringToChar( pString ) );\n}\n\nManagedStringConverter::~ManagedStringConverter()\n{\n ManagedStringConverter::FreeString( m_pString );\n}\n\n// static\nconst char * ManagedStringConverter::StringToChar( System::String^ str )\n{\n IntPtr^ ip = Marshal::StringToHGlobalAnsi( str );\n if ( ip != IntPtr::Zero )\n {\n return reinterpret_cast<const char *>( ip->ToPointer() );\n }\n else\n {\n return nullptr;\n }\n}\n\n// static\nconst __wchar_t * ManagedStringConverter::StringToWChar( System::String^ str )\n{\n IntPtr^ ip = Marshal::StringToHGlobalUni( str );\n if ( ip != IntPtr::Zero )\n {\n return reinterpret_cast<const __wchar_t *>( ip->ToPointer() );\n }\n else\n {\n return nullptr;\n }\n}\n\n// static\nvoid ManagedStringConverter::FreeString( const char * pszStr )\n{\n IntPtr ip = IntPtr( (void *)pszStr );\n Marshal::FreeHGlobal( ip );\n}\n" }, { "answer_id": 269961, "author": "Alex Shnayder", "author_id": 26042, "author_profile": "https://Stackoverflow.com/users/26042", "pm_score": 0, "selected": false, "text": "void EndPointsMappingWrapper::GetLastError(char** strErrorMessage) \n{ \n *strErrorMessage = (char*) Marshal::StringToHGlobalAnsi(_managedObject->GetLastError()).ToPointer(); \n}\n char* err;\nGetLastError(&err);\n\n//and here you need to free the error string memory\n" }, { "answer_id": 269973, "author": "Nicola Bonelli", "author_id": 19630, "author_profile": "https://Stackoverflow.com/users/19630", "pm_score": 3, "selected": true, "text": "void EndPointsMappingWrapper::GetLastError(char* strErrorMessage, int len) \n{ char *str = (char*) Marshal::StringToHGlobalAnsi(_managedObject->GetLastError()).ToPointer(); \n strncpy(strErrorMessage,str,len);\n strErrorMessage[len-1] = '\\0';\n Marshal::FreeHGlobal(IntPtr(str));\n}\n strncpy()" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33030/" ]
269,944
<p>Is there a way to run a one-liner in sas, or do I have to create a file? I'm looking for something like the -e flag in perl.</p>
[ { "answer_id": 270262, "author": "davr", "author_id": 14569, "author_profile": "https://Stackoverflow.com/users/14569", "pm_score": 0, "selected": false, "text": "echo <insert sas code here> | sas --execute-file -\n" }, { "answer_id": 270302, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "echo \"your SAS code\" > temp;sas -sysin temp\n" }, { "answer_id": 536142, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "sas -initstmt '%put hello world ; endsas ;' \n\nsas -initstmt 'proc print data=sashelp.class; run ;' \n sas -initstmt '%inc large_program.sas; endsas;'\n" }, { "answer_id": 539368, "author": "Rog", "author_id": 65338, "author_profile": "https://Stackoverflow.com/users/65338", "pm_score": 4, "selected": true, "text": "sas -stdio\n echo \"proc options; run;\" | sas -stdio\n" }, { "answer_id": 37667019, "author": "Chris Blake", "author_id": 6432265, "author_profile": "https://Stackoverflow.com/users/6432265", "pm_score": 0, "selected": false, "text": "-nodms" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14167/" ]
269,946
<p>I'm constructing a simple form in ERB but the HTML produced by the text_field tag makes the <em>for</em> attribute in the label tag invalid.</p> <pre><code>&lt;div&gt; &lt;p&gt;&lt;%= label_tag "email[name]", "Name" %&gt;&lt;/p&gt; &lt;%= text_field :email, :name, :class =&gt; "text_field" %&gt; &lt;/div&gt; </code></pre> <p>Produces the HTML</p> <pre><code>&lt;div&gt; &lt;p&gt;&lt;label for="email[name]"&gt;Name&lt;/label&gt;&lt;/p&gt; &lt;input class="text_field" id="email_name" name="email[name]" size="30" type="text" /&gt; &lt;/div&gt; </code></pre> <p>Which results in the error </p> <blockquote> <p>character "[" is not allowed in the value of attribute "for".</p> </blockquote> <p>How do I generate the text with without the nested parameter name email[name] to change the label tag <em>for</em> attribute? Is there an alternative approach that produces valid HTML?</p>
[ { "answer_id": 270262, "author": "davr", "author_id": 14569, "author_profile": "https://Stackoverflow.com/users/14569", "pm_score": 0, "selected": false, "text": "echo <insert sas code here> | sas --execute-file -\n" }, { "answer_id": 270302, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "echo \"your SAS code\" > temp;sas -sysin temp\n" }, { "answer_id": 536142, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "sas -initstmt '%put hello world ; endsas ;' \n\nsas -initstmt 'proc print data=sashelp.class; run ;' \n sas -initstmt '%inc large_program.sas; endsas;'\n" }, { "answer_id": 539368, "author": "Rog", "author_id": 65338, "author_profile": "https://Stackoverflow.com/users/65338", "pm_score": 4, "selected": true, "text": "sas -stdio\n echo \"proc options; run;\" | sas -stdio\n" }, { "answer_id": 37667019, "author": "Chris Blake", "author_id": 6432265, "author_profile": "https://Stackoverflow.com/users/6432265", "pm_score": 0, "selected": false, "text": "-nodms" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269946", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9424/" ]
269,974
<p>Does anyone know how to stop jQuery fromparsing html you insert through before() and after()? Say I have an element:</p> <pre><code>&lt;div id='contentdiv'&gt;bla content bla&lt;/div&gt; </code></pre> <p>and I want to wrap it in the following way: </p> <pre><code>&lt;div id='wrapperDiv'&gt; &lt;div id='beforeDiv'&gt;&lt;/div&gt; &lt;div id='contentDiv'&gt;bla content bla&lt;/div&gt; &lt;div id='afterDiv'&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>I use the following jQuery/Javascript </p> <pre><code>$('#contentDiv').each( function() { var beforeHTML = "&lt;div id='wrapperDiv'&gt;&lt;div id='beforeDiv'&gt;&lt;/div&gt;"; var afterHTML = "&lt;div id='afterDiv'&gt;&lt;/div&gt;&lt;/div&gt;"; $(this).before(beforeHTML); $(this).after(afterHTML); } </code></pre> <p>This however will not result in the correct wrapping, it will create:</p> <pre><code>&lt;div id='wrapperDiv'&gt; &lt;div id='beforeDiv'&gt;&lt;/div&gt; &lt;/div&gt; &lt;div id='contentDiv'&gt;bla content bla&lt;/div&gt; &lt;div id='afterDiv'&gt;&lt;/div&gt; </code></pre> <p>Using wrap() won't work either since that gets jQuery even more mixed up when using:</p> <pre><code>$(this).wrap("&lt;div id='wrapperDiv'&gt;&lt;div id='beforeDiv'&gt;&lt;/div&gt;&lt;div id='afterDiv'&gt;&lt;/div&gt;&lt;/div&gt;"); </code></pre> <p>How should I solve this?<br> Thanks in advance!</p>
[ { "answer_id": 270022, "author": "Douglas Mayle", "author_id": 8458, "author_profile": "https://Stackoverflow.com/users/8458", "pm_score": 0, "selected": false, "text": "$('#contentDiv').each( function() {\n var beforeHTML = \"<div id='wrapperDiv'><div id='beforeDiv'></div>\";\n var afterHTML = \"<div id='afterDiv'></div></div>\";\n\n // This line below will do it...\n $(this).html(beforeHTML + $(this).html() + afterHTML);\n}\n" }, { "answer_id": 270059, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 4, "selected": true, "text": "$('#contentDiv').each(function() {\n $(this).wrap('<div id=\"wrapperDiv\">');\n $(this).before('<div id=\"beforeDiv\">');\n $(this).after('<div id=\"afterDiv\">');\n});\n <div id='wrapperDiv'>\n <div id='beforeDiv'></div>\n <div id='contentDiv'>bla content bla</div>\n <div id='afterDiv'></div>\n</div>\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35197/" ]
269,979
<p>I'm developing a web app using Java servlet to access Mysql db, how can I get the number of connections to my DB that is currently open ?</p> <p>Edit :</p> <p>I tried "show processlist", it showed me : 2695159, but that's not right, I'm just developing this new project, I'm the only user, couldn't have that many processes running, what I want is the number of users accessing <strong>my project's DB</strong>, not the number of all db users, but just the ones logged in to my database which has only one table.</p>
[ { "answer_id": 270014, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 3, "selected": false, "text": "show processlist" }, { "answer_id": 7592487, "author": "Gerryjun", "author_id": 970360, "author_profile": "https://Stackoverflow.com/users/970360", "pm_score": 4, "selected": false, "text": "SELECT COUNT(*) FROM information_schema.PROCESSLIST; where USE information_schema;\nSELECT COUNT(*) FROM PROCESSLIST WHERE db =\"mycase\" AND HOST LIKE \"192.168.11.174%\"\n" }, { "answer_id": 11605155, "author": "DmitrySemenov", "author_id": 1233751, "author_profile": "https://Stackoverflow.com/users/1233751", "pm_score": 2, "selected": false, "text": "Information_Schema.Processlist SELECT variable_value\nFROM INFORMATION_SCHEMA.GLOBAL_STATUS\nWHERE variable_name='threads_connected'\n" }, { "answer_id": 46375280, "author": "Idham Perdameian", "author_id": 973530, "author_profile": "https://Stackoverflow.com/users/973530", "pm_score": 1, "selected": false, "text": "Threads_connected SHOW STATUS WHERE variable_name = 'Threads_connected';\n information_schema.PROCESSLIST SELECT COUNT(*) FROM information_schema.PROCESSLIST;\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269979", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32834/" ]
269,988
<p>I have a .NET class library containing a class with a method that performs some lengthy operation. When a client calls this method it should perform the lengthy operation on a new thread in order to avoid blocking the caller. But once the method finishes it should execute some code on the main thread. In a WinForms application I could have used the System.Windows.Forms.Control.Invoke method but this is not my case. So how can I achieve this in C#?</p>
[ { "answer_id": 270030, "author": "Darin Dimitrov", "author_id": 29407, "author_profile": "https://Stackoverflow.com/users/29407", "pm_score": 2, "selected": false, "text": "new ActiveXObject" }, { "answer_id": 270770, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": 2, "selected": false, "text": "public delegate bool CheckPrimeDelegate(long n);\n class MyClassApp\n{\n static void Main() \n {\n CheckPrimeDelegate ckPrimDel = new CheckPrimeDelegate(Prime.Check);\n\n // Initiate the operation\n ckPrimDel.BeginInvoke(4501232117, new AsyncCallback(OnChkPrimeDone), null);\n\n // go do something else . . . . \n }\n\n static void OnChkPrimeDone( IAsyncResult iAr)\n {\n AsyncResult ar = iAr as AsynchResult;\n CheckPrimeDelegate ckPrimDel = ar.AsyncDelegate as CheckPrimeDelegate;\n bool isPrime = ckPrimDel.EndInvoke(ar);\n Console.WriteLine(\" Number is \" + (isPrime? \"prime \": \"not prime\");\n }\n}\n If (MyActiveXObject.InvokeRequired())\n MyActiveXObject.BeginInvoke(...);\n" }, { "answer_id": 272252, "author": "Darin Dimitrov", "author_id": 29407, "author_profile": "https://Stackoverflow.com/users/29407", "pm_score": 5, "selected": true, "text": "public class Runner\n{\n public void Run(string executable, object processExitHandler)\n {\n ThreadPool.QueueUserWorkItem(state =>\n {\n var p = new Process()\n {\n StartInfo = new ProcessStartInfo()\n {\n FileName = executable\n }\n };\n p.Start();\n while (!p.HasExited)\n {\n Thread.Sleep(100);\n }\n\n state\n .GetType()\n .InvokeMember(\n \"call\", \n BindingFlags.InvokeMethod, \n null, \n state, \n new object[] { null, p.ExitCode }\n );\n }, processExitHandler);\n }\n}\n <!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\n<html>\n<head><title>ActiveXRunner</title> \n <script type=\"text/javascript\">\n function runNotepad() {\n var ax = new ActiveXObject('ActiveXRunner.Runner');\n ax.Run('c:\\\\windows\\\\notepad.exe', h);\n }\n\n function h(exitCode) {\n alert('exitCode = ' + exitCode);\n }\n </script>\n</head>\n<body>\n <a href=\"#\" onclick=\"runNotepad();\">Run notepad and show exit code when finished</a>\n</body>\n</html>\n" }, { "answer_id": 3363089, "author": "cdiggins", "author_id": 184528, "author_profile": "https://Stackoverflow.com/users/184528", "pm_score": 5, "selected": false, "text": "System.Windows.Threading.Dispatcher public class ClassCreatedBySomeThread\n{\n Dispatcher dispatcher = Dispatcher.CurrentDispatcher; \n\n public void SafelyCallMeFromAnyThread(Action a)\n {\n dispatcher.Invoke(a);\n }\n} \n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29407/" ]
269,989
<p><strong>EDIT:</strong> I also have access to <a href="http://www.exslt.org/" rel="nofollow noreferrer">ESXLT</a> functions.</p> <p>I have two node sets of string tokens. One set contains values like these:</p> <pre><code>/Geography/North America/California/San Francisco /Geography/Asia/Japan/Tokyo/Shinjuku </code></pre> <p>The other set contains values like these:</p> <pre><code>/Geography/North America/ /Geography/Asia/Japan/ </code></pre> <p>My goal is to find a "match" between the two. A match is made when any string in set 1 begins with a string in set 2. For example, a match would be made between <strong>/Geography/North America/California/San Francisco</strong> and <strong>/Geography/North America/</strong> because a string from set 1 begins with a string from set 2.</p> <p>I can compare strings using wildcards by using a third-party extension. I can also use a regular expression all within an Xpath.</p> <p>My problem is how do I structure the Xpath to select using a function between all nodes of both sets? XSL is also a viable option.</p> <p>This XPATH:</p> <pre><code>count($set1[.=$set2]) </code></pre> <p>Would yield the count of intersection between set1 and set2, but it's a 1-to-1 comparison. Is it possible to use some other means of comparing the nodes?</p> <p>EDIT: I did get this working, but I am cheating by using some of the other third-party extensions to get the same result. I am still interested in other methods to get this done.</p>
[ { "answer_id": 273285, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 3, "selected": true, "text": "<xsl:variable name=\"matches\" select=\"$set1[starts-with(., $set2)]\"/>\n $matches $set1 starts-with $set2 $set1 $set2 <xsl:variable name=\"hits\" select=\"$set1[. = $set2]\"/>\n $set1 $set2 <xsl:variable name=\"matches\" select=\"$set1[$set2[starts-with(?, .)]]\"/>\n ? <xsl:variable name=\"matches\">\n <xsl:for-each select=\"$set1\">\n <xsl:if test=\"$set2[starts-with(current(), .)]\">\n <xsl:copy-of select=\".\"/>\n </xsl:if>\n </xsl:for-each>\n</xsl:variable>\n msxsl:node-set" }, { "answer_id": 273951, "author": "ChuckB", "author_id": 28605, "author_profile": "https://Stackoverflow.com/users/28605", "pm_score": -1, "selected": false, "text": "<?xml version=\"1.0\"?>\n<sets>\n <set>\n <text>/Geography/North America/California/San Francisco</text>\n <text>/Geography/Asia/Japan/Tokyo/Shinjuku</text>\n </set>\n <set>\n <text>/Geography/North America/</text>\n <text>/Geography/Asia/Japan/</text>\n </set>\n</sets>\n <?xml version=\"1.0\"?>\n<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n\n <xsl:output method=\"text\"/>\n\n <xsl:template match=\"/\">\n <xsl:variable name=\"set1\" select=\"sets/set[1]/text/text()\"/>\n <xsl:variable name=\"set2\" select=\"sets/set[2]/text/text()\"/>\n <xsl:value-of select=\"count($set1[starts-with(., $set2)])\"/>\n <xsl:text>\n</xsl:text>\n </xsl:template>\n\n</xsl:stylesheet>\n" }, { "answer_id": 275298, "author": "ChuckB", "author_id": 28605, "author_profile": "https://Stackoverflow.com/users/28605", "pm_score": 0, "selected": false, "text": "xsl:variable <?xml version=\"1.0\"?>\n<xsl:stylesheet version=\"1.0\"\n xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n\n <xsl:output indent=\"yes\" method=\"text\"/>\n\n <xsl:template match=\"/\">\n <xsl:call-template name=\"count-matches\">\n <xsl:with-param name=\"set1-node\" select=\"sets/set[1]/text[1]\"/>\n <xsl:with-param name=\"set2-node\" select=\"sets/set[2]/text[1]\"/>\n <xsl:with-param name=\"total-count\" select=\"0\"/>\n </xsl:call-template>\n <xsl:text>\n</xsl:text>\n </xsl:template>\n\n <xsl:template name=\"count-matches\">\n <xsl:param name=\"set1-node\"/>\n <xsl:param name=\"set2-node\"/>\n <xsl:param name=\"total-count\" select=\"0\"/>\n <xsl:variable name=\"this-count\">\n <xsl:choose>\n <xsl:when test=\"contains($set1-node, $set2-node)\">\n <xsl:value-of select=\"1\"/>\n </xsl:when>\n <xsl:otherwise>\n <xsl:value-of select=\"0\"/>\n </xsl:otherwise>\n </xsl:choose>\n </xsl:variable>\n <xsl:choose>\n <xsl:when test=\"$set2-node/following-sibling::text\">\n <xsl:call-template name=\"count-matches\">\n <xsl:with-param name=\"set1-node\"\n select=\"$set1-node\"/>\n <xsl:with-param name=\"set2-node\"\n select=\"$set2-node/following-sibling::text[1]\"/>\n <xsl:with-param name=\"total-count\"\n select=\"$total-count + $this-count\"/>\n </xsl:call-template>\n </xsl:when>\n <xsl:when test=\"$set1-node/following-sibling::text\">\n <xsl:call-template name=\"count-matches\">\n <xsl:with-param name=\"set1-node\"\n select=\"$set1-node/following-sibling::text[1]\"/>\n <xsl:with-param name=\"set2-node\"\n select=\"$set2-node/preceding-sibling::text[last()]\"/>\n <xsl:with-param name=\"total-count\"\n select=\"$total-count + $this-count\"/>\n </xsl:call-template>\n </xsl:when>\n <xsl:otherwise>\n <xsl:value-of select=\"$total-count + $this-count\"/>\n </xsl:otherwise>\n </xsl:choose>\n </xsl:template>\n\n</xsl:stylesheet>\n xsl:for-each" }, { "answer_id": 345481, "author": "Dimitre Novatchev", "author_id": 36305, "author_profile": "https://Stackoverflow.com/users/36305", "pm_score": 1, "selected": false, "text": "<xsl:stylesheet version=\"1.0\"\n xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n <xsl:output method=\"text\"/>\n\n <xsl:template match=\"/\">\n <xsl:variable name=\"vStars\">\n <xsl:for-each select=\"*/regions/*\">\n <xsl:for-each select=\"/*/cities/*[starts-with(.,current())]\">\n <xsl:value-of select=\"'*'\"/>\n </xsl:for-each>\n </xsl:for-each>\n </xsl:variable>\n\n <xsl:value-of select=\"string-length($vStars)\"/>\n </xsl:template>\n</xsl:stylesheet>\n <t>\n <cities>\n <city>/Geography/North America/California/San Francisco</city>\n <city>/Geography/Asia/Japan/Tokyo/Shinjuku</city>\n </cities>\n <regions>\n <region>/Geography/North America/</region>\n <region>/Geography/Asia/Japan/</region>\n </regions>\n</t>\n $vStars string-length()" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269989", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18265/" ]
269,991
<p>In IIS Manager under Web Service Extensions, ASP.NET v2.0.50727 is set to "Prohibited" by default. I would like to set this to Allow during the install.</p> <p>I am currently using WiX Version 2.</p> <p>I have tried using:</p> <pre><code>&lt;Component Id="Allow_WebServiceExtension_ASP.NET_2.0" DiskId="1" Guid="02247363-E423-41E1-AC15-BEF589B65A4D"&gt; &lt;WebServiceExtension Id="WebServiceExtension_ASP.NET_2.0" Allow="yes" File="%SystemRoot%\Microsoft.NET\Framework\[DOTNETFRAMEWORKVER]\aspnet_isapi.dll" Description="ASP.NET v2.0.50727" UIDeletable="no" /&gt; &lt;/Component&gt; </code></pre> <p>This adds a second ASP.NET 2.0.50727 entry and does not enable the first.</p>
[ { "answer_id": 516893, "author": "Friend Of George", "author_id": 424, "author_profile": "https://Stackoverflow.com/users/424", "pm_score": 1, "selected": true, "text": "Dim WebSvcObj As Object\nDim LocatorObj As Object = CreateObject(\"WbemScripting.SWbemLocator\")\nDim ProviderObj As Object = LocatorObj.ConnectServer(\".\", \"root/MicrosoftIISv2\", \"\", \"\")\nWebSvcObj = ProviderObj.get(\"IIsWebService='w3svc'\")\nWebSvcObj.EnableWebServiceExtension(\"ASP.NET v2.0.50727\")\n" }, { "answer_id": 2674215, "author": "Bon", "author_id": 321180, "author_profile": "https://Stackoverflow.com/users/321180", "pm_score": 0, "selected": false, "text": " Dim LocatorObj\n Dim WebSvcObj\n Dim ProviderObj\n\n Set LocatorObj = CreateObject(\"WbemScripting.SWbemLocator\")\n Set ProviderObj = LocatorObj.ConnectServer(\".\", \"root/MicrosoftIISv2\", \"\", \"\")\n Set WebSvcObj = ProviderObj.get(\"IIsWebService='w3svc'\")\n WebSvcObj.EnableWebServiceExtension(\"ASP.NET v4.0.30319\")\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/424/" ]
269,999
<p>I want the log to roll over as long as the application is running, but I want the log to start fresh when the application is restarted.</p> <p><em>Updated:</em> Based on <a href="https://stackoverflow.com/questions/269999/how-do-i-make-log4j-clear-a-log-at-startup#270026">erickson's</a> feedback, my appender looks like this:</p> <pre><code> &lt;appender name="myRFA" class="org.apache.log4j.RollingFileAppender"&gt; &lt;param name="File" value="my-server.log"/&gt; &lt;param name="Append" value="false" /&gt; &lt;param name="MaxFileSize" value="10MB"/&gt; &lt;param name="MaxBackupIndex" value="10"/&gt; &lt;layout class="org.apache.log4j.PatternLayout"&gt; &lt;param name="ConversionPattern" value="%d{ISO8601} %p - %t - %c - %m%n"/&gt; &lt;/layout&gt; &lt;/appender&gt; </code></pre> <p>I simply added the following line:</p> <pre><code>&lt;param name="Append" value="false" /&gt; </code></pre> <p>It now truncates the base log file at startup, but it leaves the rolled files alone.</p>
[ { "answer_id": 270026, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 7, "selected": true, "text": "append false" }, { "answer_id": 496741, "author": "Eddie", "author_id": 57752, "author_profile": "https://Stackoverflow.com/users/57752", "pm_score": 3, "selected": false, "text": "RollingFileAppender public void rollLogFile(Logger logger) {\n while (logger != null && !logger.getAllAppenders().hasMoreElements()) {\n logger = (Logger)logger.getParent();\n }\n\n if (logger == null) {\n return;\n }\n\n for (Enumeration e2 = logger.getAllAppenders(); e2.hasMoreElements();) {\n final Appender appender = (Appender)e2.nextElement();\n if (appender instanceof RollingFileAppender) {\n final RollingFileAppender rfa = (RollingFileAppender)appender;\n final File logFile = new File(rfa.getFile());\n if (logFile.length() > 0) {\n rfa.rollOver();\n }\n }\n }\n}\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/269999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28991/" ]
270,029
<p>I am implementing a class to compare directory trees (in C#). At first I implemented the actual comparison in the class's constructor. Like this:</p> <pre><code>DirectoryComparer c = new DirectoryComparer("C:\\Dir1", "C:\\Dir2"); </code></pre> <p>But it doesn't feel "right" to do a possible lengthy operation in the constructor. An alternative way is to make the constructor private and add a static method like this:</p> <pre><code>DirectoryComparer c = DirectoryComparer.Compare("C:\\Dir1", "C:\\Dir2"); </code></pre> <p>What do you think? Do you expect a constructor to be "quick"? Is the second example better or is it just complicating the usage of the class?</p> <p><strong>BTW:</strong> </p> <p>I wont mark any answer as accepted because I don't think there is a correct answer, just preference and taste.</p> <p><strong>Edit:</strong></p> <p>Just to clarify my example a little. I'm not only insterested if the directories differs, I'm also interested in how they differ (which files). So a simple int return value wont be enough. The answer by cdragon76.myopenid.com actually is pretty close to what I want (+1 to you).</p>
[ { "answer_id": 270040, "author": "Dana the Sane", "author_id": 2567, "author_profile": "https://Stackoverflow.com/users/2567", "pm_score": 3, "selected": false, "text": "D1 = new Directory(\"C:\\\");\n..\nD1.compare(D2);\n" }, { "answer_id": 270050, "author": "Peter Lillevold", "author_id": 35245, "author_profile": "https://Stackoverflow.com/users/35245", "pm_score": 4, "selected": false, "text": "DirectoryComparer c = new DirectoryComparer();\n\nint equality = c.Compare(\"C:\\\\Dir1\", \"C:\\\\Dir2\");\n" }, { "answer_id": 270063, "author": "Klathzazt", "author_id": 35223, "author_profile": "https://Stackoverflow.com/users/35223", "pm_score": 1, "selected": false, "text": "\nDirectoryComparer = new DirectoryComparer(&Dir1,&Dir2); \n\nDirectoryComparer->Compare();\n\n \nDirectoryComparer = new DirectoryComparer(); \n\nDirectoryComparer->Compare(&Dir1,&Dir2);\n\n " }, { "answer_id": 270123, "author": "Alex Shnayder", "author_id": 26042, "author_profile": "https://Stackoverflow.com/users/26042", "pm_score": 0, "selected": false, "text": "Directory dir1 = new Directory(\"C:\\.....\");\nDirectory dir2 = new Directory(\"D:\\.....\");\n\nDirectoryCompare c = dir1.CompareTo(dir2);\n" }, { "answer_id": 270244, "author": "C. Dragon 76", "author_id": 5682, "author_profile": "https://Stackoverflow.com/users/5682", "pm_score": 2, "selected": false, "text": "DirectoryComparer.Compare DirectoryComparer DirectoryDifferences DirectoryComparisonResult DirectoryComparer DirectoryComparer DirectoryComparer DirectoryComparer DirectoryComparer comparer = new DirectoryComparer(\n DirectoryComparerOptions.IgnoreDirectoryAttributes\n);\nDirectoryComparerResult result = comparer.Compare(\"C:\\\\Dir1\", \"C:\\\\Dir2\");\n" }, { "answer_id": 272230, "author": "Andre", "author_id": 17650, "author_profile": "https://Stackoverflow.com/users/17650", "pm_score": 1, "selected": false, "text": "bool IsValid() DirectoryComparer DirectoryComparer" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/270029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4422/" ]
270,042
<p>I'm optimizing some frequently run Perl code (once per day per file). </p> <p>Do comments slow Perl scripts down? My experiments lean towards no:</p> <pre><code>use Benchmark; timethese(20000000, { 'comments' =&gt; '$b=1; # comment ... (100 times) ', 'nocomments' =&gt; '$b=1;'}); </code></pre> <p>Gives pretty much identical values (apart from noise).</p> <pre><code>Benchmark: timing 10000000 iterations of comments, nocomments... comments: 1 wallclock secs ( 0.53 usr + 0.00 sys = 0.53 CPU) @ 18832391.71/s (n=10000000) nocomments: 0 wallclock secs ( 0.44 usr + 0.00 sys = 0.44 CPU) @ 22935779.82/s (n=10000000) Benchmark: timing 20000000 iterations of comments, nocomments... comments: 0 wallclock secs ( 0.86 usr + -0.01 sys = 0.84 CPU) @ 23696682.46/s (n=20000000) nocomments: 1 wallclock secs ( 0.90 usr + 0.00 sys = 0.90 CPU) @ 22099447.51/s (n=20000000) </code></pre> <p>I get similar results if I run the comments and no-comments versions as separate Perl scripts.</p> <p>It seems counter-intuitive though, if nothing else the interpreter needs to read the comments into memory every time.</p>
[ { "answer_id": 270225, "author": "Michael Carman", "author_id": 8233, "author_profile": "https://Stackoverflow.com/users/8233", "pm_score": 3, "selected": false, "text": "Benchmark INIT END" }, { "answer_id": 270554, "author": "Schwern", "author_id": 14660, "author_profile": "https://Stackoverflow.com/users/14660", "pm_score": 5, "selected": true, "text": "-c" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/270042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9056/" ]
270,048
<p>I'm writing a small GUI app that contains some "editor" functionality, and something that I'd like to let users open a few sample text files to test things out quickly. The easiest way of doing this would be to package a separate zip with the appropriate sample files, and have them open them manually; I'd like to make things a little more user-friendly and allow them to pick the files from inside the application and then run them.</p> <p>So... what do I use? I initially considered .properties but that doesn't seem terribly well suited for the job...</p>
[ { "answer_id": 270071, "author": "Steve B.", "author_id": 19479, "author_profile": "https://Stackoverflow.com/users/19479", "pm_score": 0, "selected": false, "text": "myDialog.setFilenameFilter( new FilenameFilter() {\n\n public void accept (File dir, String name) {\n return name.startsWith(\"FooBar\");\n }\n}\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/270048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23845/" ]
270,074
<p>An application that has been working well for months has stopped picking up the JPA <code>@Entity</code> annotations that have been a part of it for months. As my integration tests run I see dozens of "<code>org.hibernate.MappingException: Unknown entity: com.whatever.OrderSystem</code>" type errors.</p> <p>It isn't clear to me what's gone wrong here.</p> <p>I have no <code>hibernate.cfg.xml</code> file because I'm using the Hibernate Entity Manager. Since I'm exclusively using annotations, there are no .hbm.xml files for my entities. My <code>persistence.xml</code> file is minimal, and lives in <code>META-INF</code> as it is supposed to.</p> <p>I'm obviously missing something but can't put my finger on it.</p> <p>I'm using hibernate-annotations 3.2.1, hibernate-entitymanager 3.2.1, persistence-api 1.0 and hibernate 3.2.1. hibernate-commons-annotations is also a part of the project's POM but I don't know if that's relevant.</p> <p>Is there a web.xml entry that has vanished, or a Spring configuration entry that has accidentally been deleted?</p>
[ { "answer_id": 270137, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 3, "selected": true, "text": "<persistence ...>\n <persistence-unit ...>\n <provider>org.hibernate.ejb.HibernatePersistence</provider> <---- explicit setting\n ....\n </persistence-unit>\n</persistence>\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/270074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7178/" ]
270,080
<p>What are the main differences between a Linked List and a BinarySearchTree? Is BST just a way of maintaining a LinkedList? My instructor talked about LinkedList and then BST but did't compare them or didn't say when to prefer one over another. This is probably a dumb question but I'm really confused. I would appreciate if someone can clarify this in a simple manner.</p>
[ { "answer_id": 270094, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 7, "selected": true, "text": "Item(1) -> Item(2) -> Item(3) -> Item(4) -> Item(5) -> Item(6) -> Item(7)\n Node(1)\n /\n Node(2)\n / \\\n / Node(3)\n RootNode(4)\n \\ Node(5)\n \\ /\n Node(6)\n \\\n Node(7)\n ------ ------ ------\nkey List Tree\n------ ------ ------\n1 1 3\n2 2 2\n3 3 3\n4 4 1\n5 5 3\n6 6 2\n7 7 3\n------ ------ ------\navg 4 2.43\n------ ------ ------\n ------ ------ ------\nitems List Tree\n------ ------ ------\n 1 1 1\n 3 2 1.67\n 7 4 2.43\n 15 8 3.29\n 31 16 4.16\n 63 32 5.09\n------ ------ ------\n" }, { "answer_id": 270098, "author": "Mike G.", "author_id": 18901, "author_profile": "https://Stackoverflow.com/users/18901", "pm_score": 2, "selected": false, "text": "1 -> 2 -> 5 -> 3 -> 9 -> 12 -> |i. 5\n / \\\n 3 9\n / \\ \\\n1 2 12\n" }, { "answer_id": 270107, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 3, "selected": false, "text": "public class LinkedListNode\n{\n Object Data;\n LinkedListNode NextNode;\n}\n public class BSTNode\n{\n Object Data\n BSTNode LeftNode;\n BSTNode RightNode;\n} \n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/270080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33203/" ]
270,091
<p>I cannot understand how this is possible. Please help!!</p> <p>I have an app with a trayicon. I want a form to be show when the user double clicks the trayicon. I have a problem where it is possible to get 2 or more forms showing by quickly triple or quadruple clicking the trayicon. The reason I don't want a singleton is that I want the form to be released each time it is closed to save memory, maybe this is not a good idea?</p> <p>I have a field called m_form1. I have a method called ShowForm1; I call the method ShowForm1 on the double-click of the TrayIcon.</p> <pre><code> private Form1 m_form1; private void ShowForm1() { if (m_form1 == null) { Trace.WriteLine("*CREATE*" + Thread.CurrentThread.ManagedThreadId.ToString()); m_form1 = new Form1(); m_form1.FormClosed += new FormClosedEventHandler(m_form1_FormClosed); m_form1.Show(); } m_form1.BringToFront(); m_form1.Activate(); } </code></pre> <p>So when Form1 takes a while to construct, then it is possible to create 2 because m_form1 is still null when the second call arrives. Locking does not seem to work as it is the same thread both calls (I'm guessing the UI thread) ie the trace writes out *CREATE*1 twice (below).</p> <pre><code>[3560] *CREATE*1 [3560] *CREATE*1 </code></pre> <p>Changing the code to include a lock statement does not help me.</p> <pre><code> private Form1 m_form1; private object m_Locker = new object(); private void ShowForm1() { lock (m_Locker) { if (m_form1 == null) { Trace.WriteLine("****CREATE****" + Thread.CurrentThread.ManagedThreadId.ToString()); m_form1 = new Form1(); m_form1.FormClosed += new FormClosedEventHandler(m_form1_FormClosed); m_form1.Show(); } } m_form1.BringToFront(); m_form1.Activate(); } </code></pre> <p>How should I handle this situation? </p> <p>Thanks guys</p> <p>Tim.</p>
[ { "answer_id": 270106, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": true, "text": "private Form1 m_form1;\nprivate bool m_underConstruction = false;\n\nprivate void ShowForm1()\n{\n if (m_underConstruction)\n {\n // We're about to show it anyway\n return;\n }\n m_underConstruction = true;\n try\n {\n if (m_form1 == null)\n {\n m_form1 = new Form1();\n m_form1.FormClosed += new FormClosedEventHandler(m_form1_FormClosed);\n m_form1.Show();\n }\n }\n finally\n {\n m_underConstruction = false;\n }\n m_form1.BringToFront();\n m_form1.Activate();\n}\n" }, { "answer_id": 270136, "author": "Sunny Milenov", "author_id": 8220, "author_profile": "https://Stackoverflow.com/users/8220", "pm_score": 0, "selected": false, "text": "private int openedForms = 0;\nprivate Form1 m_form1;\nprivate void ShowForm1()\n{\n\n if (Interlocked.Increment(ref openedForms) = 1)\n {\n m_form1 = new Form1();\n m_form1.FormClosed += new FormClosedEventHandler(m_form1_FormClosed);\n m_form1.Show();\n }\n else\n {\n Interlocked.Decrement(ref openedForms);\n }\n if (m_form1 != null)\n {\n m_form1.BringToFront();\n m_form1.Activate();\n }\n}\n\nprivate void m_form1_FormClosed(object Sender, EventArgs args)\n{\n Interlocked.Decrement(ref openedForms);\n}\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/270091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1077232/" ]
270,093
<p>I came across this code and wanted others to provide their point of view... is it good or bad ? ;)</p> <pre><code>Class ReportClass { public string ReportName {get; set;} } </code></pre> <p>Then it was used as follows in code:</p> <pre><code>displayReport(ReportClass.ReportName = cmbReportName.SelectedValue.ToString()) </code></pre> <p>That is about the simplest form example I can give you. Quetion is... why can't I find examples ? What would this be called? Is this just asking for trouble?</p> <p><strong>EDIT:</strong> I'm referring to the inplace assignment. Which I wasn't aware of until today</p>
[ { "answer_id": 270118, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 2, "selected": false, "text": "var a = 0;\nvar b = 0;\n\n// This makes a *and* b equals to 1\na = b = 1; \n\n// This line prints 3 and a is now equals to 3\nConsole.WriteLine(a = 3);\n\n// This line prints 7 and a and b is now equals to 7\nConsole.WriteLine(a = b = 7);\n displayReport(\n ReportClass.ReportName = cmbReportName.SelectedValue.ToString());\n var reportName = cmbReportName.SelectedValue.ToString();\n\ndisplayReport(ReportClass.ReportName = reportName);\n" }, { "answer_id": 270129, "author": "EvilSyn", "author_id": 6350, "author_profile": "https://Stackoverflow.com/users/6350", "pm_score": 2, "selected": false, "text": "ReportClass.ReportName = cmbReportName.SelectedValue.ToString();\ndisplayReport(ReportClass.ReportName);\n" }, { "answer_id": 270151, "author": "Tamas Czinege", "author_id": 8954, "author_profile": "https://Stackoverflow.com/users/8954", "pm_score": 2, "selected": false, "text": "{get; set;}" }, { "answer_id": 270206, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "string line;\nwhile ((line = reader.ReadLine()) != null)\n{\n // Do something with line \n}\n Foo(new Bar { X=1, Y=2 });\n" }, { "answer_id": 270213, "author": "Peter Wone", "author_id": 1715673, "author_profile": "https://Stackoverflow.com/users/1715673", "pm_score": 2, "selected": false, "text": "for int a, b, c;\na = b = c = 0;\n while ((packetPos = Packet.FindStart(buffer, nextUnconsideredPos)) > -1)\n packetPosition = Packet.FindStart(buffer, nextUnconsideredPosition);\nwhile (packetPosition > -1)\n{\n ...\n packetPosition = Packet.FindStart(buffer, nextUnconsideredPosition);\n}\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/270093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
270,112
<p>I have an application where the user selects the dates of a first statement and a last statement. Example, first statement = 1/1/08, last statement = 12/1/08, should equal 12 statements.</p> <p>However, when using the following code, the result is 11:</p> <pre><code>numPayments = DateDiff(DateInterval.Month, CDate(.FeeStartDate), CDate(.FeeEndDate)) </code></pre> <p>Is there another way to calculate this, or do I have to be stuck with adding 1 to the result?</p>
[ { "answer_id": 270128, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "numPayments = (Date.Parse(.FeeEndDate) - Date.Parse(.FeeStartDate)).TotalMonths + 1\n" }, { "answer_id": 13736603, "author": "Joa.know", "author_id": 1721727, "author_profile": "https://Stackoverflow.com/users/1721727", "pm_score": 0, "selected": false, "text": "Dim myDate As Date\nDim dateNow As Date\nDim nextMonth As Date\n\nmyDate = Now\ndateNow = Format(myDate, \"MM/dd/yyyy\")\nnextMonth = DateAdd(DateInterval.Month, 5, dateNow) 'compute the next 5 months from date now. Let say, #12/6/2012# the result will be #5/6/2013#\n\n\nMessageBox.Show(DateDiff(DateInterval.Month, dateNow, nextMonth) & \"months==> \" & nextMonth)\n'This will count the number of months interval. The result will be 5 months=>> #5/6/2013 because we count december to may.\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/270112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4770/" ]
270,113
<p>I have two Slackware Linux systems on which the POSIX semaphore <code>sem_open()</code> call fails with errno set to 38. Sample code to reproduce below (the code works fine on CentOS / RedHat).</p> <p>Are there any kernel or system configuration options that could cause this? Other suggestions?</p> <p>Systems with issue are Slackware 10.1.0 kernel 2.6.11 /lib/librt-2.3.4.so /lib/libpthread-0.10.so, but the same code works on the much older RedHat 9 kernel 2.4.20 /lib/librt-2.3.2.so /lib/tls/libpthread-0.29.so. (and also works on CentOS 5 kernel 2.6.18 /lib/librt-2.5.so /lib/i686/nosegneg/libpthread-2.5.so).</p> <p><code>man sem_open</code> suggests this errno means <code>sem_open()</code> is not supported by system.</p> <pre><code>#define ENOSYS 38 /* Function not implemented */ </code></pre> <p>The <code>sem_open()</code> userspace is in <code>librt</code> which we link against dynamically and <code>librt</code> is present on the affected systems.</p> <p>The affected system claims to support POSIX semaphores: <code>_POSIX_SEMAPHORES</code> is true and <code>sysconf(_SC_SEMAPHORES)</code> confirms this.</p> <p>Thanks, Kieran</p> <p>Edit 1: I've added more detail on the software versions in use and removed some irrelevant comments.</p> <p>Edit 2: /dev/shm is mounted on the good systems and not mounted on the bad systems. Mounting it did not change the behaviour on the affected systems. I think /dev/shm is necessary too but sem_open() is failing before that, and strace supports this.</p> <pre><code># /* Quick'n'dirty test program to illustrate sem_open failure #Run this file to auto-build test and run as a.out # Build gcc $0 -lrt if [ $? -ne 0 ] ; then exit ; fi # Run $( dirname $0)/a.out exit */ #include &lt;stdio.h&gt; #include &lt;fcntl.h&gt; #include &lt;errno.h&gt; #include &lt;unistd.h&gt; #include &lt;semaphore.h&gt; int main(int argc, char *argv[]) { const char *SEM_NAME = "SHRMEM_SCXL"; /* name of mutex */ sem_t *mutex = SEM_FAILED; /* ptr to mutex */ #ifdef _POSIX_SEMAPHORES printf("_POSIX_SEMAPHORES %ld\n", _POSIX_SEMAPHORES); #else puts("Undefined"); #endif printf("sysconf %s\n", sysconf(_SC_SEMAPHORES) ? "Yes" : "No" ); mutex = sem_open(SEM_NAME, O_CREAT, 0666, 1); if (mutex == SEM_FAILED) printf("Failed %d\n", errno); else { puts("Success - pause while you check /dev/shm "); sleep(5); sem_close(mutex); sem_unlink(SEM_NAME); } } </code></pre>
[ { "answer_id": 270377, "author": "Steve Baker", "author_id": 13566, "author_profile": "https://Stackoverflow.com/users/13566", "pm_score": 4, "selected": true, "text": "tmpfs /dev/shm tmpfs defaults 0 0\n LD_ASSUME_KERNEL" }, { "answer_id": 271901, "author": "Kieran Tully", "author_id": 18023, "author_profile": "https://Stackoverflow.com/users/18023", "pm_score": 2, "selected": false, "text": "man sem_init /etc/fstab /dev/shm mount /dev/shm" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/270113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18023/" ]
270,138
<p>I've read a bunch of tutorials involving XNA (and it's various versions) and I still am a little confused on drawing primitives. Everything seems to be really convoluted.</p> <p>Can someone show me, using code, the simplest XNA implementation of drawing one or two lines on to the screen? Perhaps with a brief explanation (including the boilerplate)?</p> <p>I'm not a games programmer and I have little XNA experience. My ultimate goal is to draw some lines onto the screen which I will eventually transform with rotations, etc (by hand). However, for this first step.. I need to simply draw the lines! I remember back in my ancient OpenGL days it was fairly straightforward when drawing a line with a few method calls. Should I simply revert to using unmanaged directx calls?</p>
[ { "answer_id": 3746172, "author": "No hay Problema", "author_id": 87602, "author_profile": "https://Stackoverflow.com/users/87602", "pm_score": 3, "selected": false, "text": "Texture2D SimpleTexture = new Texture2D(GraphicsDevice, 1, 1, false, SurfaceFormat.Color); this.spriteBatch.Draw(SimpleTexture, new Rectangle(100, 100, 100, 1), Color.Blue);" }, { "answer_id": 4697364, "author": "Elideb", "author_id": 481534, "author_profile": "https://Stackoverflow.com/users/481534", "pm_score": 4, "selected": false, "text": "Texture2D SimpleTexture = new Texture2D(GraphicsDevice, 1, 1, false,\n SurfaceFormat.Color);\n\nInt32[] pixel = {0xFFFFFF}; // White. 0xFF is Red, 0xFF0000 is Blue\nSimpleTexture.SetData<Int32> (pixel, 0, SimpleTexture.Width * SimpleTexture.Height);\n\n// Paint a 100x1 line starting at 20, 50\nthis.spriteBatch.Draw(SimpleTexture, new Rectangle(20, 50, 100, 1), Color.Blue);\n this.spriteBatch.Draw (SimpleTexture, new Rectangle(0, 0, 100, 1), null,\n Color.Blue, -(float)Math.PI/4, new Vector2 (0f, 0f), SpriteEffects.None, 1f);\n" }, { "answer_id": 13337365, "author": "ColacX", "author_id": 700735, "author_profile": "https://Stackoverflow.com/users/700735", "pm_score": 3, "selected": false, "text": "basicEffect = new BasicEffect(GraphicsDevice);\nbasicEffect.VertexColorEnabled = true;\nbasicEffect.Projection = Matrix.CreateOrthographicOffCenter\n(0, GraphicsDevice.Viewport.Width,     // left, right\nGraphicsDevice.Viewport.Height, 0,    // bottom, top\n0, 1);   \n basicEffect.CurrentTechnique.Passes[0].Apply();\nvar vertices = new VertexPositionColor[4];\nvertices[0].Position = new Vector3(100, 100, 0);\nvertices[0].Color = Color.Black;\nvertices[1].Position = new Vector3(200, 100, 0);\nvertices[1].Color = Color.Red;\nvertices[2].Position = new Vector3(200, 200, 0);\nvertices[2].Color = Color.Black;\nvertices[3].Position = new Vector3(100, 200, 0);\nvertices[3].Color = Color.Red;\n\nGraphicsDevice.DrawUserPrimitives<VertexPositionColor>(PrimitiveType.LineList, vertices, 0, 2);\n" }, { "answer_id": 19957844, "author": "Viviano Cantu", "author_id": 2559240, "author_profile": "https://Stackoverflow.com/users/2559240", "pm_score": 2, "selected": false, "text": "class Line\n{\n Texture pixel = ((set this to a texture of a white pixel with no border));\n Vector2 p1, p2; //this will be the position in the center of the line\n int length, thickness; //length and thickness of the line, or width and height of rectangle\n Rectangle rect; //where the line will be drawn\n float rotation; // rotation of the line, with axis at the center of the line\n Color color;\n\n\n //p1 and p2 are the two end points of the line\n public Line(Vector2 p1, Vector2 p2, int thickness, Color color)\n {\n this.p1 = p1;\n this.p2 = p2;\n this.thickness = thickness;\n this.color = color;\n }\n\n public void Update(GameTime gameTime)\n {\n length = (int)Vector2.Distance(p1, p2); //gets distance between the points\n rotation = getRotation(p1.X, p1.Y, p2.X, p2.Y); //gets angle between points(method on bottom)\n rect = new Rectangle((int)p1.X, (int)p1.Y, length, thickness)\n\n //To change the line just change the positions of p1 and p2\n }\n\n public void Draw(SpriteBatch spriteBatch, GameTime gameTime)\n {\n spriteBatch.Draw(pixel, rect, null, color, rotation, new Vector2.Zero, SpriteEffects.None, 0.0f);\n }\n\n //this returns the angle between two points in radians \n private float getRotation(float x, float y, float x2, float y2)\n {\n float adj = x - x2;\n float opp = y - y2;\n float tan = opp / adj;\n float res = MathHelper.ToDegrees((float)Math.Atan2(opp, adj));\n res = (res - 180) % 360;\n if (res < 0) { res += 360; }\n res = MathHelper.ToRadians(res);\n return res;\n }\n" }, { "answer_id": 20368575, "author": "Finn Bear", "author_id": 3064544, "author_profile": "https://Stackoverflow.com/users/3064544", "pm_score": 0, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing Microsoft.Xna.Framework;\nusing Microsoft.Xna.Framework.Audio;\nusing Microsoft.Xna.Framework.Content;\nusing Microsoft.Xna.Framework.GamerServices;\nusing Microsoft.Xna.Framework.Graphics;\nusing Microsoft.Xna.Framework.Input;\nusing Microsoft.Xna.Framework.Media;\n\nnamespace Xna.LineHelper\n{\n public class LineManager\n {\n int loopCounter;\n int lineLegnth;\n Vector2 lineDirection;\n Vector2 _position;\n Color dotColor;\n Rectangle _rectangle;\n List<Texture2D> _dots = new List<Texture2D>();\n FunctionsLibrary functions = new FunctionsLibrary();\n\n public void CreateLineFiles(Vector2 startPosition, Vector2 endPosition, int width, Color color, ContentManager content)\n {\n dotColor = color;\n _position.X = startPosition.X;\n _position.Y = startPosition.Y;\n lineLegnth = functions.Distance((int)startPosition.X, (int)endPosition.X, (int)startPosition.Y, (int)endPosition.Y);\n lineDirection = new Vector2((endPosition.X - startPosition.X) / lineLegnth, (endPosition.Y - startPosition.Y) / lineLegnth);\n _dots.Clear();\n loopCounter = 0;\n _rectangle = new Rectangle((int)startPosition.X, (int)startPosition.Y, width, width);\n while (loopCounter < lineLegnth)\n {\n Texture2D dot = content.Load<Texture2D>(\"dot\");\n _dots.Add(dot);\n\n loopCounter += 1;\n }\n\n }\n\n public void DrawLoadedLine(SpriteBatch sb)\n {\n foreach (Texture2D dot in _dots)\n {\n _position.X += lineDirection.X;\n _position.Y += lineDirection.Y;\n _rectangle.X = (int)_position.X;\n _rectangle.Y = (int)_position.Y;\n sb.Draw(dot, _rectangle, dotColor);\n }\n }\n }\n\n public class FunctionsLibrary\n {\n //Random for all methods\n Random Rand = new Random();\n\n #region math\n public int TriangleArea1(int bottom, int height)\n {\n int answer = (bottom * height / 2);\n return answer;\n }\n\n public double TriangleArea2(int A, int B, int C)\n {\n int s = ((A + B + C) / 2);\n double answer = (Math.Sqrt(s * (s - A) * (s - B) * (s - C)));\n return answer;\n }\n public int RectangleArea(int side1, int side2)\n {\n int answer = (side1 * side2);\n return answer;\n }\n public int SquareArea(int side)\n {\n int answer = (side * side);\n return answer;\n }\n public double CircleArea(int diameter)\n {\n double answer = (((diameter / 2) * (diameter / 2)) * Math.PI);\n return answer;\n }\n public int Diference(int A, int B)\n {\n int distance = Math.Abs(A - B);\n return distance;\n }\n #endregion\n\n #region standardFunctions\n\n public int Distance(int x1, int x2, int y1, int y2)\n {\n return (int)(Math.Sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)));\n }\n\n #endregion\n\n\n\n }\n}\n" }, { "answer_id": 25937738, "author": "trinalbadger587", "author_id": 3208848, "author_profile": "https://Stackoverflow.com/users/3208848", "pm_score": 1, "selected": false, "text": "public class LineBatch\n{\n bool cares_about_begin_without_end;\n bool began;\n GraphicsDevice GraphicsDevice;\n List<VertexPositionColor> verticies = new List<VertexPositionColor>();\n BasicEffect effect;\n public LineBatch(GraphicsDevice graphics)\n {\n GraphicsDevice = graphics;\n effect = new BasicEffect(GraphicsDevice);\n Matrix world = Matrix.Identity;\n Matrix view = Matrix.CreateTranslation(-GraphicsDevice.Viewport.Width / 2, -GraphicsDevice.Viewport.Height / 2, 0);\n Matrix projection = Matrix.CreateOrthographic(GraphicsDevice.Viewport.Width, -GraphicsDevice.Viewport.Height, -10, 10);\n effect.World = world;\n effect.View = view;\n effect.VertexColorEnabled = true;\n effect.Projection = projection;\n effect.DiffuseColor = Color.White.ToVector3();\n cares_about_begin_without_end = true;\n }\n public LineBatch(GraphicsDevice graphics, bool cares_about_begin_without_end)\n {\n this.cares_about_begin_without_end = cares_about_begin_without_end;\n GraphicsDevice = graphics;\n effect = new BasicEffect(GraphicsDevice);\n Matrix world = Matrix.Identity;\n Matrix view = Matrix.CreateTranslation(-GraphicsDevice.Viewport.Width / 2, -GraphicsDevice.Viewport.Height / 2, 0);\n Matrix projection = Matrix.CreateOrthographic(GraphicsDevice.Viewport.Width, -GraphicsDevice.Viewport.Height, -10, 10);\n effect.World = world;\n effect.View = view;\n effect.VertexColorEnabled = true;\n effect.Projection = projection;\n effect.DiffuseColor = Color.White.ToVector3();\n }\n public void DrawAngledLineWithRadians(Vector2 start, float length, float radians, Color color)\n {\n Vector2 offset = new Vector2(\n (float)Math.Sin(radians) * length, //x\n -(float)Math.Cos(radians) * length //y\n );\n Draw(start, start + offset, color);\n }\n public void DrawOutLineOfRectangle(Rectangle rectangle, Color color)\n {\n Draw(new Vector2(rectangle.X, rectangle.Y), new Vector2(rectangle.X + rectangle.Width, rectangle.Y), color);\n Draw(new Vector2(rectangle.X, rectangle.Y), new Vector2(rectangle.X, rectangle.Y + rectangle.Height), color);\n Draw(new Vector2(rectangle.X + rectangle.Width, rectangle.Y), new Vector2(rectangle.X + rectangle.Width, rectangle.Y + rectangle.Height), color);\n Draw(new Vector2(rectangle.X, rectangle.Y + rectangle.Height), new Vector2(rectangle.X + rectangle.Width, rectangle.Y + rectangle.Height), color);\n }\n public void DrawOutLineOfTriangle(Vector2 point_1, Vector2 point_2, Vector2 point_3, Color color)\n {\n Draw(point_1, point_2, color);\n Draw(point_1, point_3, color);\n Draw(point_2, point_3, color);\n }\n float GetRadians(float angleDegrees)\n {\n return angleDegrees * ((float)Math.PI) / 180.0f;\n }\n public void DrawAngledLine(Vector2 start, float length, float angleDegrees, Color color)\n {\n DrawAngledLineWithRadians(start, length, GetRadians(angleDegrees), color);\n }\n public void Draw(Vector2 start, Vector2 end, Color color)\n {\n verticies.Add(new VertexPositionColor(new Vector3(start, 0f), color));\n verticies.Add(new VertexPositionColor(new Vector3(end, 0f), color));\n }\n public void Draw(Vector3 start, Vector3 end, Color color)\n {\n verticies.Add(new VertexPositionColor(start, color));\n verticies.Add(new VertexPositionColor(end, color));\n }\n public void End()\n {\n if (!began)\n if (cares_about_begin_without_end)\n throw new ArgumentException(\"Please add begin before end!\");\n else\n Begin();\n if (verticies.Count > 0)\n {\n VertexBuffer vb = new VertexBuffer(GraphicsDevice, typeof(VertexPositionColor), verticies.Count, BufferUsage.WriteOnly);\n vb.SetData<VertexPositionColor>(verticies.ToArray());\n GraphicsDevice.SetVertexBuffer(vb);\n\n foreach (EffectPass pass in effect.CurrentTechnique.Passes)\n {\n pass.Apply();\n GraphicsDevice.DrawPrimitives(PrimitiveType.LineList, 0, verticies.Count / 2);\n }\n }\n began = false;\n }\n public void Begin()\n {\n if (began)\n if (cares_about_begin_without_end)\n throw new ArgumentException(\"You forgot end.\");\n else\n End();\n verticies.Clear();\n began = true;\n }\n}\n" }, { "answer_id": 37696675, "author": "Max", "author_id": 5863588, "author_profile": "https://Stackoverflow.com/users/5863588", "pm_score": 2, "selected": false, "text": " point = game.Content.Load<Texture2D>(\"ui/point\");\n\n public void DrawLine(Vector2 start, Vector2 end, Color color)\n {\n Vector2 edge = end - start;\n float angle = (float)Math.Atan2(edge.Y, edge.X);\n\n spriteBatch.Begin();\n spriteBatch.Draw(point,\n new Rectangle((int)start.X, (int)start.Y, (int)edge.Length(), 1),\n null, \n color, \n angle,\n new Vector2(0, 0),\n SpriteEffects.None,\n 0);\n spriteBatch.End();\n }\n" }, { "answer_id": 42421719, "author": "NuBc4k3", "author_id": 7612283, "author_profile": "https://Stackoverflow.com/users/7612283", "pm_score": 2, "selected": false, "text": "public class myRay\n{\n public Vector3 position, direction;\n public float length;\n} \n List<myRay> DebugRays= new List<myRay>();\n private void DrawRays()\n{\n spriteBatch.Begin();\n\n foreach (myRay ray in DebugRays)\n {\n //An array of 2 vertices - a start and end position\n VertexPositionColor[] Vertices = new VertexPositionColor[2];\n int[] Indices = new int[2];\n\n //Starting position of the ray\n Vertices[0] = new VertexPositionColor()\n {\n Color = Color.Orange,\n Position = ray.position\n };\n\n //End point of the ray\n Vertices[1] = new VertexPositionColor()\n {\n Color = Color.Orange,\n Position = ray.position + (ray.direction * ray.length)\n };\n\n Indices[0] = 0;\n Indices[1] = 1;\n\n foreach (EffectPass pass in BasicEffect.CurrentTechnique.Passes)\n {\n pass.Apply();\n GraphicsDevice.DrawUserIndexedPrimitives(PrimitiveType.LineStrip, Vertices, 0, 2, Indices, 0, 1, VertexPositionColorTexture.VertexDeclaration);\n }\n }\n\n spriteBatch.End();\n}\n OnExplosionHappened()\n{\n DebugRays.Clear()\n\n myRay ray = new myRay()\n {\n position = explosion.Position,\n direction = GetDirection(explosion, solid),\n //Used GetValueOrDefault here to prevent null value errors\n length = explosionRay.Intersects(solid.BoundingBox).GetValueOrDefault()\n };\n\n DebugRays.Add(ray);\n}\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/270138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2635/" ]
270,148
<p>I have these 3 tables + data:</p> <p><strong>items</strong>: itemId, itemName <br />data: 1, my item one</p> <p><strong>categories</strong>: catId, catName <br />data: 1, my cat one. 2, my cat two</p> <p><strong>map</strong>: mapId, itemId, catId</p> <p>When you include item "my item one" in category "my cat one", you insert [1, 1, 1] into the map. When you add "my item one" to "my cat two", you insert [2, 1, 2] into the map. Now let's say we change our mind and only want the item in "my cat two". This means we need to know what categories the item is no longer in and delete the associations from the map. What's the most efficient sequence of steps to take to do so? (I'm looking for a solution that will scale beyond this trivial example.)</p>
[ { "answer_id": 270173, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": true, "text": "DELETE FROM MAP WHERE ItemID = @MyItem1Id\n AND CatID <> @MyCat2Id\n" }, { "answer_id": 270180, "author": "Tom H", "author_id": 5696608, "author_profile": "https://Stackoverflow.com/users/5696608", "pm_score": 0, "selected": false, "text": "DELETE\n M\nFROM\n Map M\nWHERE\n M.itemid = @item_id AND\n M.catid <> @new_cat_id\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/270148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/356/" ]
270,177
<p>I have a bunch of images that need to rotate in and out one at a time every 2 seconds with fancy JQuery fadeIn and fadeOut. I have all the images in the HTML to pre-load them and a setInterval timer that fades the current image out, then fades the next image in. Problem is that sometimes when you are clicking or scrolling during the fade in/out process, the JS gets interrupted and the current image never disappears and the next one fades in giving you two images.</p> <p>I get the feeling it has something to do with setInterval not running properly every 2 seconds, but are there any better ways to accomplish what I need?</p> <p>Here's a snippet of code:</p> <p>HTML</p> <pre><code>&lt;a href="javascript:;"&gt; &lt;img id="img1" src="image1.gif" /&gt; &lt;img id="img2" src="image2.gif" style="display:none;" /&gt; &lt;img id="img3" src="image3.gif" style="display:none;" /&gt; &lt;/a&gt; </code></pre> <p>JS</p> <pre><code>var numImages = 3; var currentImage = 1; imageInterval = window.setInterval("changeImage();", 2000); function changeImage() { $("#img" + currentImage).fadeOut("slow", function() { if (currentImage &gt;= numImages) { currentImage = 0; } $("#img" + (currentImage + 1) ).fadeIn("slow", function() { currentImage++; }); }); } </code></pre>
[ { "answer_id": 270259, "author": "Jim Nelson", "author_id": 32168, "author_profile": "https://Stackoverflow.com/users/32168", "pm_score": 2, "selected": false, "text": "function changeImage()\n{\n $(\"#img\" + currentImage).fadeOut(\"slow\");\n currentImage = (currentImage >= numImages) ? 1 : currentImage + 1;\n $(\"#img\" + currentImage).fadeIn(\"slow\");\n}\n" }, { "answer_id": 270289, "author": "Steve Perks", "author_id": 16124, "author_profile": "https://Stackoverflow.com/users/16124", "pm_score": 1, "selected": false, "text": "numImages = $(\"a > img\").size();\n" }, { "answer_id": 2990974, "author": "tom", "author_id": 360577, "author_profile": "https://Stackoverflow.com/users/360577", "pm_score": 1, "selected": false, "text": "setInterval (function () {\n $(\"img:eq(0)\").fadeOut (\"slow\").next (\"img\").fadeIn (\"slow\");\n}, 2000);\n" }, { "answer_id": 6354699, "author": "Chris", "author_id": 632174, "author_profile": "https://Stackoverflow.com/users/632174", "pm_score": 0, "selected": false, "text": "display:block" }, { "answer_id": 59708994, "author": "Yamil Duba", "author_id": 8658119, "author_profile": "https://Stackoverflow.com/users/8658119", "pm_score": 0, "selected": false, "text": "$(document).ready(() => {\n\nlet numImages = 4;\nlet currentImage = 1;\n\nfunction changeImage() {\n $('#img-' + currentImage).fadeOut(1000, function() {\n if (currentImage === numImages) {\n currentImage = 0;\n }\n currentImage++;\n $('#img-' + currentImage).fadeIn(1000, function() {\n changeImage();\n });\n })\n}\n\nchangeImage();\n\n})\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/270177", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1396/" ]
270,187
<p>Is it possible to create an attribute that can be initialized with a variable number of arguments?</p> <p>For example:</p> <pre><code>[MyCustomAttribute(new int[3,4,5])] // this doesn't work public MyClass ... </code></pre>
[ { "answer_id": 270223, "author": "Rob Prouse", "author_id": 30827, "author_profile": "https://Stackoverflow.com/users/30827", "pm_score": 3, "selected": false, "text": "[Row( new[] { \"-l\", \"/port:13102\", \"-lfsw\" } )]\npublic void MyTest( string[] args ) { //... }\n" }, { "answer_id": 270224, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": false, "text": "using System;\n\n[AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)]\npublic class SampleAttribute : Attribute\n{\n public SampleAttribute(int[] foo)\n {\n }\n}\n\n[Sample(new int[]{1, 3, 5})]\nclass Test\n{\n}\n" }, { "answer_id": 270227, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 5, "selected": false, "text": "public class MyCustomAttribute : Attribute\n{\n public MyCustomAttribute(params int[] t)\n {\n }\n}\n [MyCustomAttribute(3, 4, 5)]" }, { "answer_id": 270228, "author": "Alan", "author_id": 31223, "author_profile": "https://Stackoverflow.com/users/31223", "pm_score": 2, "selected": false, "text": "class MyAttribute: Attribute\n{\n public MyAttribute(params object[] args)\n {\n }\n}\n\n[MyAttribute(\"hello\", 2, 3.14f)]\nclass Program\n{\n static void Main(string[] args)\n {\n }\n}\n" }, { "answer_id": 270231, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 9, "selected": true, "text": "params class MyCustomAttribute : Attribute {\n public int[] Values { get; set; }\n\n public MyCustomAttribute(params int[] values) {\n this.Values = values;\n }\n}\n\n[MyCustomAttribute(3, 4, 5)]\nclass MyClass { }\n class MyCustomAttribute : Attribute {\n public int[] Values { get; set; }\n\n public MyCustomAttribute(int[] values) {\n this.Values = values;\n }\n}\n\n[MyCustomAttribute(new int[] { 3, 4, 5 })]\nclass MyClass { }\n" }, { "answer_id": 270447, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 5, "selected": false, "text": "[assembly: CLSCompliant(true)]\n\nclass Foo : Attribute\n{\n public Foo(string[] vals) { }\n}\n[Foo(new string[] {\"abc\",\"def\"})]\nstatic void Bar() {}\n Warning 1 Arrays as attribute arguments is not CLS-compliant\n [Foo(\"abc\"), Foo(\"def\")]\n TypeDescriptor PropertyDescriptor" }, { "answer_id": 72259423, "author": "Michal Pokluda", "author_id": 1102229, "author_profile": "https://Stackoverflow.com/users/1102229", "pm_score": 0, "selected": false, "text": "public class CLParam : Attribute\n{\n /// <summary>\n /// Command line parameter\n /// </summary>\n public string Names { get; set; }\n}\n var names = loadAtt.Names.Split(',');\n class CLContext\n{\n [CLParam(Names = \"selectscene,ss\")]\n public List<string> SelectScene { get; set; }\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/270187", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
270,190
<p>I have 4 databases with similar schema's, and I'm trying to create a query to return just the table, column pairs that exist ONLY in database 1 and do not exist in database 2, 3, or 4.</p> <p>Currently I can return the symmetric difference between database 1 and 2 via the following query...</p> <pre><code>select table_name, column_name from ( select table_name, column_name from [Database1].information_schema.columns union all select table_name, column_name from [Database2].information_schema.columns) as tmp group by table_name, column_name having count(*) = 1 </code></pre> <p>However, in trying to isolate just those columns in database 1, and doing the same across all 4 databases, things are getting complicated. What is the cleanest solution for this query?</p>
[ { "answer_id": 270223, "author": "Rob Prouse", "author_id": 30827, "author_profile": "https://Stackoverflow.com/users/30827", "pm_score": 3, "selected": false, "text": "[Row( new[] { \"-l\", \"/port:13102\", \"-lfsw\" } )]\npublic void MyTest( string[] args ) { //... }\n" }, { "answer_id": 270224, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": false, "text": "using System;\n\n[AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)]\npublic class SampleAttribute : Attribute\n{\n public SampleAttribute(int[] foo)\n {\n }\n}\n\n[Sample(new int[]{1, 3, 5})]\nclass Test\n{\n}\n" }, { "answer_id": 270227, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 5, "selected": false, "text": "public class MyCustomAttribute : Attribute\n{\n public MyCustomAttribute(params int[] t)\n {\n }\n}\n [MyCustomAttribute(3, 4, 5)]" }, { "answer_id": 270228, "author": "Alan", "author_id": 31223, "author_profile": "https://Stackoverflow.com/users/31223", "pm_score": 2, "selected": false, "text": "class MyAttribute: Attribute\n{\n public MyAttribute(params object[] args)\n {\n }\n}\n\n[MyAttribute(\"hello\", 2, 3.14f)]\nclass Program\n{\n static void Main(string[] args)\n {\n }\n}\n" }, { "answer_id": 270231, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 9, "selected": true, "text": "params class MyCustomAttribute : Attribute {\n public int[] Values { get; set; }\n\n public MyCustomAttribute(params int[] values) {\n this.Values = values;\n }\n}\n\n[MyCustomAttribute(3, 4, 5)]\nclass MyClass { }\n class MyCustomAttribute : Attribute {\n public int[] Values { get; set; }\n\n public MyCustomAttribute(int[] values) {\n this.Values = values;\n }\n}\n\n[MyCustomAttribute(new int[] { 3, 4, 5 })]\nclass MyClass { }\n" }, { "answer_id": 270447, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 5, "selected": false, "text": "[assembly: CLSCompliant(true)]\n\nclass Foo : Attribute\n{\n public Foo(string[] vals) { }\n}\n[Foo(new string[] {\"abc\",\"def\"})]\nstatic void Bar() {}\n Warning 1 Arrays as attribute arguments is not CLS-compliant\n [Foo(\"abc\"), Foo(\"def\")]\n TypeDescriptor PropertyDescriptor" }, { "answer_id": 72259423, "author": "Michal Pokluda", "author_id": 1102229, "author_profile": "https://Stackoverflow.com/users/1102229", "pm_score": 0, "selected": false, "text": "public class CLParam : Attribute\n{\n /// <summary>\n /// Command line parameter\n /// </summary>\n public string Names { get; set; }\n}\n var names = loadAtt.Names.Split(',');\n class CLContext\n{\n [CLParam(Names = \"selectscene,ss\")]\n public List<string> SelectScene { get; set; }\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/270190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7287/" ]
270,197
<p>I know the file needs to be where the getClass().getResource(filename) can find it, but I don't know where that is.</p> <p>I'm interested both in where to put the files on the filesystem itself, and how to go about using Eclipse's functionality to set up the resources.</p>
[ { "answer_id": 270210, "author": "jodonnell", "author_id": 4223, "author_profile": "https://Stackoverflow.com/users/4223", "pm_score": 3, "selected": false, "text": "getResource(\"/com/x/y/foo.png\")" }, { "answer_id": 270398, "author": "BCunningham", "author_id": 7689, "author_profile": "https://Stackoverflow.com/users/7689", "pm_score": 7, "selected": true, "text": "/src /src/resources getResource(\"/resources/image.png\") com.mycompany com.mycompany.Foo getResource(\"image.png\")" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/270197", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16593/" ]
270,230
<p>What is the difference between having</p> <pre class="lang-java prettyprint-override"><code>&lt;%# Eval("State") %&gt; </code></pre> <p>in your <code>aspx</code> page, versus having</p> <pre class="lang-java prettyprint-override"><code>&lt;%# DataBinder.Eval(Container.DataItem, "State") %&gt; </code></pre> <p>in your <code>aspx</code> page?</p>
[ { "answer_id": 270252, "author": "Jeromy Irvine", "author_id": 8223, "author_profile": "https://Stackoverflow.com/users/8223", "pm_score": 6, "selected": true, "text": "Eval(\"State\") DataBinder.Eval(Container.DataItem, \"State\")" }, { "answer_id": 13805517, "author": "GLP", "author_id": 968273, "author_profile": "https://Stackoverflow.com/users/968273", "pm_score": -1, "selected": false, "text": "<%# (DataBinder.Eval(Container.DataItem, \"ApplicationId\").ToString() == \"-1\" ? \"N/A\" : Eval(\"ApplicationId\").ToString()) %>\n" }, { "answer_id": 14624021, "author": "Raman Sharma", "author_id": 2028752, "author_profile": "https://Stackoverflow.com/users/2028752", "pm_score": 3, "selected": false, "text": "<%# Eval %> <%# DataBinder.Eval %> Eval TemplateControl.Eval DataBinder.Eval Eval Control.DataBind() Page null Page DataItem Page.GetDataItem() Eval() XPath() Bind() DataBinder.Eval" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/270230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33690/" ]
270,260
<p>Let's imagine I got this:</p> <p>index.php generates form with unpredictable number of inputs with certain IDs/Names and different values that can be edited by user and saved by script.php</p> <pre><code>&lt;form action="script.php" method="post"&gt; &lt;input id="1" name="1" type="text" value="1"/&gt; &lt;input id="24" name="24" type="text" value="2233"/&gt; &lt;input id="55" name="55" type="text" value="231321"/&gt; &lt;/form&gt; </code></pre> <p>Script.php:</p> <p>Here I need to get something like array of all inputs that were generated by index.php and save every value that corresponds to its id/name.</p> <p>Is there a way to do this?</p>
[ { "answer_id": 270279, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 3, "selected": true, "text": "$_POST print_r($_POST);\n\n// contains:\n\narray\n(\n [1] => 1\n [24] => 2233\n [55] => 231321\n)\n\n// example access:\n\nforeach($_POST as $name => $value) {\n print \"Name: {$name} Value: {$value} <br />\";\n}\n" }, { "answer_id": 270285, "author": "Rob Prouse", "author_id": 30827, "author_profile": "https://Stackoverflow.com/users/30827", "pm_score": 1, "selected": false, "text": "$keys = array_keys( $_POST );\nforeach( $keys as $key ) {\n echo \"Name=\" . $key . \" Value=\" . $_POST[$key];\n}\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/270260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21209/" ]
270,268
<p>I have a class which has a method that is receiving an object as a parameter. This method is invoked via RMI.</p> <pre><code>public RMIClass extends Serializable { public RMIMethod(MyFile file){ // do stuff } } </code></pre> <p>MyFile has a property called "body", which is a byte array. </p> <pre><code>public final class MyFile implements Serializable { private byte[] body = new byte[0]; //.... public byte[] getBody() { return body; } //.... } </code></pre> <p>This property holds the gzipped data of a file that was parsed by another application.</p> <p>I need to decompress this byte array before performing further actions with it. </p> <p>All the examples I see of decompressing gzipped data assume that I want to write it to the disk and create a physical file, which I do not.</p> <p>How do I do this?</p> <p>Thanks in advance.</p>
[ { "answer_id": 56170655, "author": "Judd", "author_id": 843116, "author_profile": "https://Stackoverflow.com/users/843116", "pm_score": 0, "selected": false, "text": "private static void uncompress(final byte[] input, final ByteBuffer output) throws IOException\n {\n final GZIPInputStream inputGzipStream = new GZIPInputStream(new ByteArrayInputStream(input));\n Channels.newChannel(inputGzipStream).read(output);\n }\n" }, { "answer_id": 70748230, "author": "Tony BenBrahim", "author_id": 80075, "author_profile": "https://Stackoverflow.com/users/80075", "pm_score": 1, "selected": false, "text": " private byte[] gzipUncompress(byte[] compressedBytes) throws IOException {\n try (InputStream inputStream = new GZIPInputStream(new ByteArrayInputStream(compressedBytes))) {\n try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {\n inputStream.transferTo(outputStream);\n return outputStream.toByteArray();\n }\n }\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/270268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34380/" ]
270,282
<p>I'm looking to update our project's jaxb version from 1 to 2. Has anyone tried doing this on their projects and are there any tips that anyone wanting to do this? I understand that each project is unique, I'm just looking for general tips.</p>
[ { "answer_id": 2210180, "author": "Blaisorblade", "author_id": 53974, "author_profile": "https://Stackoverflow.com/users/53974", "pm_score": 1, "selected": false, "text": "<xs:element name=\"logging\">\n <xs:complexType>\n <xs:attribute name=\"debug\" type=\"xs:boolean\" use=\"required\"/>\n <xs:attribute name=\"file\" type=\"xs:string\" use=\"required\"/>\n </xs:complexType>\n</xs:element>\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/270282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1459442/" ]
270,284
<p>We've got a webserver running IIS. We'd like to run maybe a shared blog or something to keep track of information. Because of security issues, we'd like for that part to be only viewable from localhost so people have to remote in to use it.</p> <p>So, to repeat my question, can part of a website be made viewable from localhost only?</p>
[ { "answer_id": 270321, "author": "TravisO", "author_id": 35116, "author_profile": "https://Stackoverflow.com/users/35116", "pm_score": -1, "selected": false, "text": "string MyWebServerName = currentContext.Request.ServerVariables[\"SERVER_NAME\"];\n\nif ( MyWebServerName == \"127.0.0.1\" || MyWebServerName == \"localhost\" )\n{\n // the user is local \n}\nelse\n{\n // the user is NOT local\n}\n" }, { "answer_id": 22575734, "author": "Serj Sagan", "author_id": 550975, "author_profile": "https://Stackoverflow.com/users/550975", "pm_score": 5, "selected": false, "text": "IIS 8 Windows 2012 Server Manager Manage, Add Roles and Features Server Roles Web Server (IIS) Web Server Security IIS Manager Features View Actions Edit Feature Settings 'Access for unspecified clients:' 'Deny' 'Add Allow Entry' Action" }, { "answer_id": 30886897, "author": "Chris", "author_id": 1308967, "author_profile": "https://Stackoverflow.com/users/1308967", "pm_score": 2, "selected": false, "text": "%windir%\\system32\\inetsrv\\appcmd.exe set config \"Default Web Site\" -section:system.webServer/security/ipSecurity /+\"[ipAddress='0',allowed='False']\" /commit:apphost\n%windir%\\system32\\inetsrv\\appcmd.exe set config \"Default Web Site\" -section:system.webServer/security/ipSecurity /+\"[ipAddress='127.0.0.1',allowed='True']\" /commit:apphost\n <security>\n <ipSecurity allowUnlisted=\"false\"> <!-- this line blocks everybody, except those listed below --> \n <clear/> <!-- removes all upstream restrictions -->\n <add ipAddress=\"127.0.0.1\" allowed=\"true\"/> <!-- allow requests from the local machine -->\n </ipSecurity>\n</security>\n" }, { "answer_id": 58587409, "author": "Florian Winter", "author_id": 2279059, "author_profile": "https://Stackoverflow.com/users/2279059", "pm_score": 1, "selected": false, "text": "127.0.0.1 [::1] * localhost appcmd add site /name:MyLoalSite /bindings:http/127.0.0.1:7103:*,http/[::1]:7103:* /physicalPath:\"C:\\path\\to\\site\\\"\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/270284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25680/" ]
270,287
<p>What is a good way to edit a Web.config file programmatically?</p> <p>I looked into System.Xml but couldn't find any obvious answers.</p>
[ { "answer_id": 270335, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 5, "selected": true, "text": "protected void EditConfigButton(object sender, EventArgs e)\n{\n Configuration objConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(\"~\");\n AppSettingsSection objAppsettings = (AppSettingsSection)objConfig.GetSection(\"appSettings\");\n //Edit\n if (objAppsettings != null)\n {\n objAppsettings.Settings[\"test\"].Value = \"newvalueFromCode\";\n objConfig.Save();\n }\n}\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/270287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4886/" ]
270,288
<p>I'm currently optimizing the performance on my company's site; when it was taking 6-10 seconds to download 2MB+ of our homepage and assets (the site is mostly Flash with a lot of media, so it's not 2MB of HTML and viewstate). There are a lot of things that will need to be done to get this download size down; but one thing I definitely want to do is enable HTTP compression to compress our static content, specifically XML, CSS, and JS; I don't imagine compression will do much for the SWFs and JPGs.</p> <p>I want to enable this on just our staging site so I can do some server testing and benchmarking. This means I'm going to have to do some Metabase editing, since IIS 6 doesn't allow you to set compression on an individual site via IIS manager. The problem with that is the Metabase is locked by IIS so I can't save; and even if I save the edits, I'm required to restart IIS for the changes to take affect; which will take down other live sites hosted on the same server. Is there anyway to enable compression for one site without restarting IIS? I don't mind restarting our staging site; I just don't want this work to take down other sites on the server.</p> <p>Any assistance is greatly appreciated.</p>
[ { "answer_id": 270335, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 5, "selected": true, "text": "protected void EditConfigButton(object sender, EventArgs e)\n{\n Configuration objConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(\"~\");\n AppSettingsSection objAppsettings = (AppSettingsSection)objConfig.GetSection(\"appSettings\");\n //Edit\n if (objAppsettings != null)\n {\n objAppsettings.Settings[\"test\"].Value = \"newvalueFromCode\";\n objConfig.Save();\n }\n}\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/270288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10922/" ]
270,292
<p>For a windows script I am writing, I need to detect if the machine has Apache 2.2 installed, and to find the application path. </p> <p>One solution I came up with is to wget <a href="http://localhost:8080/server-info" rel="nofollow noreferrer">http://localhost:8080/server-info</a> and parse the root and the config file from it. This would fail if the server does not use port 8080</p> <p>Another option would be to call “sc qc Apache2.2” and to parse the returning string. This would fail if the server is not installed as a service, or is using a different name. </p> <p>Is there any better way to do that?</p>
[ { "answer_id": 270336, "author": "James Schek", "author_id": 17871, "author_profile": "https://Stackoverflow.com/users/17871", "pm_score": 3, "selected": true, "text": "HKEY_LOCAL_MACHINE\\SOFTWARE\\Apache Software Foundation\\Apache\\2.2.2\\ServerRoot \nHKEY_CURRENT_USER\\SOFTWARE\\Apache Software Foundation\\Apache\\2.2.2\\ServerRoot\n WMIC PROCESS get Caption,Commandline,Processid\n" }, { "answer_id": 65550658, "author": "Hilal Alghallabi", "author_id": 14931934, "author_profile": "https://Stackoverflow.com/users/14931934", "pm_score": 0, "selected": false, "text": "[enter code here][1]" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/270292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5661/" ]
270,309
<p>I want to do something like this:</p> <pre> <code> create table app_users ( app_user_id smallint(6) not null auto_increment primary key, api_key char(36) not null default uuid() ); </code> </pre> <p>However this results in a error, is there a way to call a function for a default value in mysql?</p> <p>thanks.</p>
[ { "answer_id": 29752768, "author": "Pamput", "author_id": 1659888, "author_profile": "https://Stackoverflow.com/users/1659888", "pm_score": 5, "selected": false, "text": "CREATE TRIGGER before_insert_app_users\nBEFORE INSERT ON app_users\nFOR EACH ROW\n IF new.uuid IS NULL\n THEN\n SET new.uuid = uuid();\n END IF;\n UPDATE app_users SET uuid = (SELECT uuid());\n" }, { "answer_id": 51445194, "author": "ravindu1024", "author_id": 2286245, "author_profile": "https://Stackoverflow.com/users/2286245", "pm_score": 0, "selected": false, "text": ".... column_name binary(16) not null default unhex(replace(uuid(),'-','')) \n" }, { "answer_id": 51623586, "author": "StephenS", "author_id": 1139715, "author_profile": "https://Stackoverflow.com/users/1139715", "pm_score": 2, "selected": false, "text": "UUID() CHAR(36) BINARY(16) UUID_TO_BIN() BIN_TO_UUID() CREATE TABLE app_users\n(\n app_user_id SMALLINT(6) NOT NULL AUTO_INCREMENT PRIMARY KEY,\n api_key BINARY(16)\n);\n\nCREATE TRIGGER before_insert_app_users\nBEFORE INSERT ON app_users\nFOR EACH ROW\n IF new.api_key IS NULL\n THEN\n SET new.api_key = UUID_TO_BIN(UUID());\n END IF;\n" }, { "answer_id": 52382915, "author": "ibotty", "author_id": 3714434, "author_profile": "https://Stackoverflow.com/users/3714434", "pm_score": 2, "selected": false, "text": "CREATE TABLE test ( uuid BINARY(16) PRIMARY KEY DEFAULT unhex(replace(uuid(),'-','')) );\nINSERT INTO test () VALUES ();\nSELECT * FROM test;\n" }, { "answer_id": 52769071, "author": "Shadow", "author_id": 5389997, "author_profile": "https://Stackoverflow.com/users/5389997", "pm_score": 6, "selected": false, "text": "CREATE TABLE t1 (\n uuid_field VARCHAR(32) DEFAULT (uuid()),\n binary_uuid BINARY(16) DEFAULT (UUID_TO_BIN(UUID()))\n);\n" }, { "answer_id": 69688616, "author": "Federico Razzoli", "author_id": 9445059, "author_profile": "https://Stackoverflow.com/users/9445059", "pm_score": 0, "selected": false, "text": "DEFAULT NOW() USER() binlog_format=statement" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/270309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1638/" ]
270,325
<p>We frequently have users that create multiple accounts and then end up storing the same lesson activity data more than once. Once they realize the error, then they contact us to merge the accounts into a single one that they can use. </p> <p>I've been beating myself to death trying to figure out how to write a query in MySQL that will merge their activity logs into a single profile so that I can then delete the other profiles, but I still can't find the query that will work.</p> <p>The tables look like this:</p> <pre><code>CREATE TABLE user_rtab ( user_id int PRIMARY KEY, username varchar, last_name varchar, first_name varchar ); CREATE TABLE lessonstatus_rtab ( lesson_id int, user_id int, accessdate timestamp, score double, ); </code></pre> <p>What happens is that a user ends up taking the same lessons and also different lessons under two or more accounts and then they want to take all of their lesson statuses and have them assigned under one user account.</p> <p>Can anyone provide a query that would accomplish this based on the lastname and firstname fields from the user table to determine all user accounts and then use only the user or username field to migrate all necessary statuses to the one single account?</p>
[ { "answer_id": 270357, "author": "WW.", "author_id": 14663, "author_profile": "https://Stackoverflow.com/users/14663", "pm_score": 1, "selected": false, "text": "UPDATE lessonstatus_rtab\nSET user_id = 1\nWHERE user_id = 2\nAND NOT EXISTS\n(SELECT *\n FROM lessonstatus_rtab e\n WHERE e.lesson_id = lessonstatus_rtab.lesson_id\n AND user_id = 1)\n DELETE FROM lessonstatus_rtab\nWHERE user_id = 2\n" }, { "answer_id": 270359, "author": "TravisO", "author_id": 35116, "author_profile": "https://Stackoverflow.com/users/35116", "pm_score": 2, "selected": false, "text": "UPDATE lessonstatus_rtab SET user_id=12 WHERE user_id=7;\nDELETE FROM user_rtab WHERE user_id=7;\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/270325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20178/" ]
270,329
<p>I was just wondering how many experienced programers out there actually map out their process or algorithms in a program like MS Visio or Gnome Dia? </p> <p>I am trying to code some complex PHP for my website and just seem to be missing something. Is a diagram program going to help or should I be looking in another area?</p>
[ { "answer_id": 270498, "author": "siukurnin", "author_id": 35273, "author_profile": "https://Stackoverflow.com/users/35273", "pm_score": 0, "selected": false, "text": "Input -> Frobnicator -> Output\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/270329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33194/" ]
270,334
<p>I have a class that contains two methods like these:</p> <pre><code>public String getFoo(Int32 a) { return getBar(a, "b", null); } public String getBar(Int32 a, String b, Int32 c) { //do something return ""; } </code></pre> <p>However when I compile my class I get two errors:</p> <ol> <li>The best overloaded method match for getBar(int,string,int) has some invalid arguments</li> <li>Argument '3': cannot convert from '<code>&lt;null&gt;</code>' to 'int'</li> </ol> <p>I think I understand why I'm getting this error: the compiler doesn't know at the time of compilation what the real type of the object is. Can someone confirm if I'm correct about the cause of the error or point out the real reason?</p> <p>More importantly, can I design my code this way? If so, what do I need to do to fix the errors? My reason for designing my class this way is because I don't want to duplicate the code in getBar, in getFoo. The two methods do essentially the same thing except one takes a third parameter.</p> <p>Thanks.</p>
[ { "answer_id": 270345, "author": "Jacob Krall", "author_id": 3140, "author_profile": "https://Stackoverflow.com/users/3140", "pm_score": 1, "selected": false, "text": "Int32 null Int32 int?" }, { "answer_id": 270346, "author": "jerhinesmith", "author_id": 1108, "author_profile": "https://Stackoverflow.com/users/1108", "pm_score": 2, "selected": false, "text": "getBar public String getBar(Int32 a, String b, Int32? c)\n" }, { "answer_id": 270354, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 4, "selected": true, "text": "int? nullableInt = null;\nfloat? nullableFloat = null;\n public String getBar(Int32 a, String b, Nullable<Int32> c)\n public String getBar(Int32 a, String b)\n{\n this.getBar(a,b,null);\n}\n\npublic String getBar(Int32 a, String b, Nullable<Int32> c)\n{\n}\n" }, { "answer_id": 270355, "author": "George Mauer", "author_id": 5056, "author_profile": "https://Stackoverflow.com/users/5056", "pm_score": 1, "selected": false, "text": "int? nullable = ...;\nint non_nullable = nullable??0; \n" }, { "answer_id": 270368, "author": "Tim Scott", "author_id": 29493, "author_profile": "https://Stackoverflow.com/users/29493", "pm_score": 0, "selected": false, "text": "public String getBar(Int32 a, String b, Int32? c)\n{\n if (c.HasValue)\n {\n ...do something with c.Value...\n }\n return \"\";\n}\n" }, { "answer_id": 270372, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 0, "selected": false, "text": "int? null public String getFoo(Int32 a)\n{\n return getBar(a, \"b\", null);\n}\n\npublic String getBar(Int32 a, String b)\n{\n //do something else, without the int\n}\n default null return getBar(a, \"b\", default(int));\n 0" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/270334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9809/" ]
270,337
<p>I have a page with a GridView on it that launches a popup, using Javascript. The user then selects an item, that updates the data connected to the GridView and closes the popup.</p> <p>How do I refresh the first (ie the Calling page) so that I can refresh the data shown in my Gridview?</p>
[ { "answer_id": 270351, "author": "TonyB", "author_id": 3543, "author_profile": "https://Stackoverflow.com/users/3543", "pm_score": 1, "selected": false, "text": "<script>\nwindow.opener.location.reload()\n</script>\n" }, { "answer_id": 270465, "author": "stevemegson", "author_id": 25028, "author_profile": "https://Stackoverflow.com/users/25028", "pm_score": 0, "selected": false, "text": "<script>\nwindow.parent.document.forms[0].submit();\n</script>\n window.parent.document.__doPostBack()" }, { "answer_id": 281792, "author": "David Smit", "author_id": 29441, "author_profile": "https://Stackoverflow.com/users/29441", "pm_score": 0, "selected": false, "text": "Dim CloseScript As String = \"<script language='javascript'>function closeWindow(){ window.opener.document.forms[0].submit();window.close();}closeWindow();</script>\"\n 'register with ClientScript \n 'The RegisterStartupScript method is also slightly different \n 'from ASP.NET 1.x \n Dim s As Type = Me.[GetType]()\n If Not ClientScript.IsClientScriptBlockRegistered(s, \"CloseScript\") Then\n ClientScript.RegisterClientScriptBlock(s, \"CloseScript\", CloseScript)\n End If\n" }, { "answer_id": 2869528, "author": "Justin", "author_id": 191347, "author_profile": "https://Stackoverflow.com/users/191347", "pm_score": 0, "selected": false, "text": "window.opener.location = window.opener.location;\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/270337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29441/" ]
270,347
<p><code>std::auto_ptr</code> is broken in VC++ 8 (which is what we use at work). My main gripe with it is that it allows <code>auto_ptr&lt;T&gt; x = new T();</code>, which of course leads to horrible crashes, while being simple to do by mistake.</p> <p>From an <a href="https://stackoverflow.com/questions/106508/what-is-a-smart-pointer-and-when-should-i-use-one#110706">answer</a> to another question here on stackoverflow:</p> <blockquote> <p>Note that the implementation of std::auto_ptr in Visual Studio 2005 is horribly broken. <a href="http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=98871" rel="nofollow noreferrer">http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=98871</a> <a href="http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=101842" rel="nofollow noreferrer">http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=101842</a></p> </blockquote> <p>I want to use </p> <ul> <li><code>boost::scoped_ptr</code>, for pointers that shouldn't pass ownership.</li> <li><code>boost::shared_ptr</code>, for pointers in containers and elsewhere where they are required. </li> <li><code>std::auto_ptr</code>, for pointers that should/can pass ownership.</li> </ul> <p>But since <code>std::auto_ptr</code> is broken for me, I wonder what would be the best approach:</p> <ul> <li>Replace <code>std::auto_ptr</code> with something from the net. Like this <a href="http://groups.google.com/group/comp.std.c++/msg/97a2539a1bbbe491" rel="nofollow noreferrer">this</a> one from Rani Sharoni (haven't tried it yet).</li> <li>Use <code>boost::shared_ptr</code> instead. Will of course work, although there will be some minor overhead that I don't care about. But I want to use <code>auto_ptr</code> to signal the intent of the pointer. (See <a href="https://stackoverflow.com/questions/197048/idiomatic-use-of-stdautoptr-or-only-use-sharedptr#197083">this</a> answer for a vote on this approach.)</li> <li>I will never need to pass ownership in practice, so I shouldn't worry about this.</li> </ul> <hr> <p>Update: Here is what I did: I copied the aforementioned auto_ptr implementation by Rani Sharoni. <a href="http://groups.google.com/group/comp.std.c++/msg/97a2539a1bbbe491" rel="nofollow noreferrer">From here</a>.</p> <p>Did some minor tests:</p> <pre><code>class T { public: T() { OutputDebugStringA("T\n"); }; ~T() { OutputDebugStringA("~T\n"); }; }; { fix::auto_ptr&lt;T&gt; x(new T); // This just works. } { fix::auto_ptr&lt;T&gt; x = (new T); // Doesn't compile. Great! } { fix::auto_ptr&lt;T&gt; x = fix::auto_ptr&lt;T&gt;(new T); // Transfer of ownership works also. } </code></pre> <p>Of course these tests are by no means exhaustive and you shouldn't trust them. Implementing an exception safe templated class is hairy business. At least this works better than the built in one.</p> <p><strike>Note: I don't know if I'm allowed to use this implementation yet, with respect to copyright. I have emailed Rani and I'm waiting for a reply. I'll update this post when I know more.</strike> Permission is granted for everyone to use Rani Sharoni's auto_ptr implementation as you wish.</p> <p>Thank you for all your replies.</p>
[ { "answer_id": 270365, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 1, "selected": false, "text": "std::auto_ptr<T> x(new T); // Use the explicit constructor.\n" }, { "answer_id": 1237411, "author": "Maciek", "author_id": 142168, "author_profile": "https://Stackoverflow.com/users/142168", "pm_score": 0, "selected": false, "text": "auto_ptr<T> x = auto_ptr<T>(new T()); ??\n" }, { "answer_id": 1237459, "author": "Pavel Minaev", "author_id": 111335, "author_profile": "https://Stackoverflow.com/users/111335", "pm_score": 0, "selected": false, "text": "auto_ptr auto_ptr auto_ptr reinterpret_cast static_cast struct Base1 { int x; };\nstruct Base2 { int y; };\nstruct Derived : Base1, Base2 {};\n\nstd::auto_ptr<Derived> createDerived()\n{\n return std::auto_ptr<Derived>(new Derived);\n}\n\nstd::auto_ptr<Base2> base2(createDerived());\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/270347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35256/" ]
270,350
<p>I have been experimenting with Lambda expressions in Oxygene. Very simple recursive lambda expression to calculate a fibonacci number :</p> <pre><code>var fib : Func&lt;int32, int32&gt;; fib := n -&gt; iif(n &gt; 1, fib(n - 1) + fib(n - 2), n); fib(3); </code></pre> <p>When I run this code I get a nullreferenceexception. Any ideas as to what I'm doing wrong?</p>
[ { "answer_id": 270559, "author": "Barry Kelly", "author_id": 3712, "author_profile": "https://Stackoverflow.com/users/3712", "pm_score": 4, "selected": true, "text": "<html>\n<head>\n<script language='javascript'>\nfunction main()\n{\n var x = 1;\n var f = function() { return x; };\n alert(f());\n x = 2;\n alert(f());\n}\n</script>\n</head>\n<body>\n<input type=button onclick=\"javascript:main()\"></input>\n</body>\n</html>\n" }, { "answer_id": 271859, "author": "Robert Giesecke", "author_id": 35443, "author_profile": "https://Stackoverflow.com/users/35443", "pm_score": 0, "selected": false, "text": "\n var fib := new class(Call : Func<Integer, Integer> := nil); \n fib.Call := n -> iif(n > 1, fib.Call(n - 1) + fib.Call(n - 2), n); \n var x := fib.Call(3); \n \n var fib : Func; \n with fibWrapper := new class(Call : Func<Integer, Integer> := nil) do \n begin \n fibWrapper.Call := n -> iif(n > 1, fibWrapper.Call(n - 1) + fibWrapper.Call(n - 2), n); \n fib := fibWrapper.Call; \n end;\n" }, { "answer_id": 271877, "author": "Steve", "author_id": 22712, "author_profile": "https://Stackoverflow.com/users/22712", "pm_score": 0, "selected": false, "text": " var f : Tfib;\n f := method(n : Int32): Int32\n begin\n if n > 1 then \n Result := f(n-1) + f(n-2)\n else\n Result := n;\n end;\n var f := new class(call : TFib := nil);\n f.call := method(n : Int32): Int32\n begin\n if n > 1 then \n Result := f.call(n-1) + f.call(n-2)\n else\n Result := n;\n end;\n" }, { "answer_id": 272039, "author": "Carlo Kok", "author_id": 22180, "author_profile": "https://Stackoverflow.com/users/22180", "pm_score": 1, "selected": false, "text": "var f := new class(f: Tfib := nil);\nf.f := method(n : Int32): Int32\nbegin\n if n > 1 then \n Result := f.f(n-1) + f.f(n-2)\n else\n Result := n;\nend;\nf.f(3);\n" }, { "answer_id": 1491314, "author": "Cary Jensen", "author_id": 84904, "author_profile": "https://Stackoverflow.com/users/84904", "pm_score": 2, "selected": false, "text": " var fib : Func<int32, int32>;\n fib := n -> iif(n > 1, fib(n - 1) + fib(n - 2), n);\n var i := fib(9); //1,1,2,3,5,8,13,21,34\n MessageBox.Show(i.ToString);\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/270350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22712/" ]
270,369
<p>A colleague recently asked me how to deep-clone a Map and I realized that I probably have never used the clone() method- which worries me.</p> <p>What are the most common scenarios you have found where you need to clone an object?</p>
[ { "answer_id": 270467, "author": "Julien Chastang", "author_id": 32174, "author_profile": "https://Stackoverflow.com/users/32174", "pm_score": 5, "selected": true, "text": "Object.clone() Object.clone() Object.clone()" }, { "answer_id": 271752, "author": "tetsuo", "author_id": 176897, "author_profile": "https://Stackoverflow.com/users/176897", "pm_score": 2, "selected": false, "text": "//simple clone\nclass A implements Cloneable {\n private int value;\n public A clone() {\n try {\n A copy = (A) super.clone();\n copy.value = this.value;\n return copy;\n } catch (CloneNotSupportedException ex) {}\n }\n}\n\n//clone with deep and shallow copying\nclass B extends A {\n Calendar date;\n Date date;\n public B clone() {\n B copy = (B) super.clone();\n copy.date = (Calendar) this.date.clone(); // clones the object\n copy.date = this.date; // copies the reference\n return copy;\n }\n}\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/270369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26787/" ]
270,380
<p>This probably sounds really stupid but I have noo idea how to implement jquery's rounded corners (<a href="http://www.methvin.com/jquery/jq-corner-demo.html" rel="nofollow noreferrer">http://www.methvin.com/jquery/jq-corner-demo.html</a>). My javascript-fu is complete fail and I can't seem to get it to work on my page. Can anyone show me a simple example of the HTML and JavaScript you would use to get them to show? Apologies for my idiocy.</p>
[ { "answer_id": 270436, "author": "Josh", "author_id": 2204759, "author_profile": "https://Stackoverflow.com/users/2204759", "pm_score": 0, "selected": false, "text": "$(document).ready(function() {\n $(\"#idofdiv\").corners();\n});\n" }, { "answer_id": 270443, "author": "Tamas Czinege", "author_id": 8954, "author_profile": "https://Stackoverflow.com/users/8954", "pm_score": 4, "selected": true, "text": "<script type=\"text/javascript\" src=\"jquery.js\"></script> <script type=\"text/javascript\" src=\"jquery.corner.js\"></script> <div> <div id=\"divToHaveCorners\" style=\"width: 200px; height: 100px; background-color: #701080;\">Hello World!</div> <script type=\"text/javascript\">$(function() { $('#divToHaveCorners').corner(); } );</script>" }, { "answer_id": 1684388, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "http://www.methvin.com/jquery/jq-corner-demo.html http://blue-anvil.com/jquerycurvycorners/test.html\n http://code.google.com/p/jquerycurvycorners/downloads/list\n <head>\n<script src=\"http://path.to.your.downloaded.jquery.library/jquery-1.2.6.min.js\" type=\"text/javascript\"></script> \n<script src=\"http://path.to.your.downloaded.jquery.library/jquery.curvycorners.min.js\" type=\"text/javascript\"></script>\n\n<script type=\"text/javascript\">\n$(function(){\n\n$('.myClassName').corner({\n tl: { radius: 6 },\n tr: { radius: 6 },\n bl: { radius: 6 },\n br: { radius: 6 }\n});\n\n}\n</script>\n</head>\n http://img44.imageshack.us/img44/3638/corners.jpg\n <html>\n <head>\n <script src=\"http://blue-anvil.com/jquerycurvycorners/jquery-1.2.6.min.js\" type=\"text/javascript\"></script> \n <script src=\"http://blue-anvil.com/jquerycurvycorners/jquery.curvycorners.min.js\" type=\"text/javascript\"></script>\n <script type=\"text/javascript\">\n $(function(){\n\n $('.myClassName').corner({\n tl: { radius: 12 },\n tr: { radius: 12 },\n bl: { radius: 12 },\n br: { radius: 12 }\n });\n\n });\n </script>\n <style>\n .myClassName\n {\n width:320px;\n height:64px;\n background-color:red;\n text-align:center;\n margin:auto;\n margin-top:30px;\n }\n </style>\n</head>\n\n<body>\n\n<div class=\"myClassName\">content</div>\n\n</body>\n\n</html>\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/270380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
270,391
<p>I'm using MessageFormat to format some addresses with a template like this:</p> <pre><code>"{0}\n{1}\n{2}\n{3}, {4} {5}" </code></pre> <p>where</p> <ul> <li>0 = street 1</li> <li>1 = street 2</li> <li>2 = street 3</li> <li>3 = city</li> <li>4 = state</li> <li>5 = zip</li> </ul> <p>Most of these fields are optional when captured. How do I avoid having an empty line when for instance, there is not street 3? I could use a template like this "{0}{1}{2}{3}{4}{5}" and then substitute either "street 3\n" or "" accordingly, but then the template doesn't provide much benefit toward formatting.</p> <p>Is there a way to include conditionals in the format string? Or is there another, preferably lightweight, templating tool available that supports conditional formatting?</p>
[ { "answer_id": 270466, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 1, "selected": false, "text": "'\\n' '\\n' result = result.replaceAll(\"\\n+\", \"\\n\");\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/270391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21176/" ]
270,408
<p>Is it better in C++ to pass by value or pass by reference-to-const?</p> <p>I am wondering which is better practice. I realize that pass by reference-to-const should provide for better performance in the program because you are not making a copy of the variable.</p>
[ { "answer_id": 270435, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 9, "selected": true, "text": "char int double std::*_function" }, { "answer_id": 271344, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 7, "selected": false, "text": "foo * f;\n\nvoid bar(foo g) {\n g.i = 10;\n f->i = 2;\n g.i += 5;\n}\n g.i = 15;\nf->i = 2;\n my::string uppercase(my::string s) { /* change s and return it */ }\n bool all_uppercase(my::string const& s) { \n /* check to see whether any character is uppercase */\n}\n bool try_parse(T text, my::string &out) {\n /* try to parse, write result into out */\n}\n" }, { "answer_id": 19660014, "author": "Germán Diago", "author_id": 429879, "author_profile": "https://Stackoverflow.com/users/429879", "pm_score": 2, "selected": false, "text": "class Person {\n public:\n Person(std::string name) : name_(std::move(name)) {}\n private:\n std::string name_;\n};\n Person p(std::string(\"Albert\"));\n name_ Person name_" }, { "answer_id": 27773263, "author": "Dhirendra Sengar", "author_id": 4418761, "author_profile": "https://Stackoverflow.com/users/4418761", "pm_score": -1, "selected": false, "text": "void amount(int account , int deposit , int total ) void amount(int total , int deposit )" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/270408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20229/" ]
270,434
<p>In Reporting Services I would like to add a parameter that contains data from a custom code block. Ideally, I would be able to run the following code (this is a simple testing example):</p> <pre><code>Function GetPeriods() As String() Dim values As System.Collections.ArrayList = New System.Collections.ArrayList() For i as integer = 1 to 24 values.Add(i) Next Return values.ToArray() End Function </code></pre> <p>and put the following in the "Text Field" of the parameter:</p> <pre><code>=Code.GetPeriods() </code></pre> <p>However, when I run the report, the parameter I apply this to is disabled and empty. Is there a different technique that should be used? Or am I doing something wrong?</p>
[ { "answer_id": 337378, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "String() Array Function GetPeriods() As Array" }, { "answer_id": 598512, "author": "Maksym Gontar", "author_id": 67407, "author_profile": "https://Stackoverflow.com/users/67407", "pm_score": 1, "selected": false, "text": "Public Function GetPeriods() As String\n...\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/270434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/105/" ]
270,437
<p>Is there a way to download older versions of Visual C++ Express? I'm particularly interested in Visual C++ 2005 Express (PRIOR SP1) and Visual C++ Toolkit 2003. I tried googling for them, but all the sites linked to microsoft.com, from where microsoft (for some reason) has taken them down.</p>
[ { "answer_id": 271379, "author": "bk1e", "author_id": 8090, "author_profile": "https://Stackoverflow.com/users/8090", "pm_score": 2, "selected": false, "text": "_USE_RTM_VERSION" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/270437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35268/" ]